import { createHash } from "node:crypto"; import { publishAuditEventViaOutbox } from "@hivegrid/db/audit-events.server"; import type { DbClient } from "@hivegrid/db/client.server"; import type { Prisma } from "@hivegrid/db/prisma-browser"; import { CUSTOMER_PORTAL_UAT_PROJECT_ID, CUSTOMER_PORTAL_UAT_TENANT_SLUG, CustomerPortalUatError, type CustomerPortalFixtureCommand, type CustomerPortalUatEnvironment, } from "./contracts"; const UAT_ADMIN_USER_ID = "customer-portal-uat-tenant-admin"; const UAT_PROJECT_KEY_PATTERN = /^p26a-project-[a-z0-9-]{1,83}$/u; const MAILBOX_LOCAL_PART_PATTERN = /^[A-Za-z0-9!#$%&'*\/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*\/=?^_`{|}~-]+)*$/u; const MAILBOX_DOMAIN_LABEL_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/u; const MAX_MAILBOX_ADDRESS_BYTES = 254; const MAX_MAILBOX_LOCAL_PART_BYTES = 64; const MAX_MAILBOX_DOMAIN_BYTES = 253; export type ProjectInvitationContactInput = { readonly correlationKey: string; readonly email: string; }; export type ProjectInvitationContactCommand = CustomerPortalFixtureCommand & ProjectInvitationContactInput; export type ProjectInvitationContactIds = { readonly kontaktId: string; readonly kontaktEmailId: string; readonly projektKontaktId: string; }; export type ProjectInvitationContactSnapshot = { readonly tenant: { readonly id: string; readonly slug: string; readonly active: boolean } | null; readonly project: { readonly id: string; readonly tenantId: string; readonly projekttyp: string | null; readonly archivedAt: Date | null; readonly pipeline: { readonly id: string; readonly tenantId: string; readonly archivedAt: Date | null }; readonly stage: { readonly id: string; readonly tenantId: string; readonly pipelineId: string; readonly archivedAt: Date | null; }; } | null; readonly portal: { readonly id: string; readonly tenantId: string; readonly isPublished: boolean } | null; readonly configuration: { readonly portalId: string; readonly tenantId: string; readonly enabledProjectTypes: readonly string[]; } | null; readonly stageVisibility: { readonly portalId: string; readonly tenantId: string; readonly stageId: string; readonly visible: boolean; } | null; readonly ownerMembership: { readonly tenantId: string; readonly userId: string; readonly joined: number; readonly status: number; readonly user: { readonly id: string; readonly active: boolean; readonly pendingDeletion: boolean; readonly pseudonymized: boolean; }; } | null; readonly contacts: readonly { readonly id: string; readonly tenantId: string; readonly createdByUserId: string; readonly kontaktTyp: string; readonly kontaktStatus: string; readonly vorname: string | null; readonly nachname: string | null; readonly primaerEmail: string | null; readonly zustaendigerUserId: string | null; readonly isDemoData: boolean; readonly archivedAt: Date | null; }[]; readonly emails: readonly { readonly id: string; readonly tenantId: string; readonly kontaktId: string; readonly email: string; readonly primaer: boolean; }[]; readonly projectContacts: readonly { readonly id: string; readonly tenantId: string; readonly projektId: string; readonly kontaktId: string; readonly rolle: string; readonly primaer: boolean; }[]; }; export type ProjectInvitationContactHandoff = { readonly projectPath: string; readonly projectContactRowId: string; }; export type ProjectInvitationContactAssessment = { readonly action: "noop" | "reconcile" | "blocked"; readonly reconcileIssues: readonly string[]; readonly blockingIssues: readonly string[]; readonly handoff: ProjectInvitationContactHandoff | null; }; type CanonicalProjectInvitationContact = { readonly ids: ProjectInvitationContactIds; readonly firstName: "Portal"; readonly lastName: string; }; function requiredEnvironmentValue(env: CustomerPortalUatEnvironment, name: string): string { const value = env[name]?.trim(); if (!value) throw new CustomerPortalUatError(`customer-portal UAT: ${name} is required for the project invitation fixture`); return value; } function parseMailboxBase(env: CustomerPortalUatEnvironment): { readonly localPart: string; readonly domain: string } { const raw = env.MAILBOX_EMAIL; if (!raw || raw !== raw.trim() || Buffer.byteLength(raw, "utf8") > MAX_MAILBOX_ADDRESS_BYTES || Buffer.byteLength(raw, "utf8") !== raw.length) { throw new CustomerPortalUatError("customer-portal UAT: MAILBOX_EMAIL is invalid for the project invitation fixture"); } const parts = raw.split("@"); if (parts.length !== 2) { throw new CustomerPortalUatError("customer-portal UAT: MAILBOX_EMAIL is invalid for the project invitation fixture"); } const [localPart = "", domain = ""] = parts; const labels = domain.split("."); if ( localPart.includes("+") || !MAILBOX_LOCAL_PART_PATTERN.test(localPart) || Buffer.byteLength(localPart, "ascii") > MAX_MAILBOX_LOCAL_PART_BYTES || Buffer.byteLength(domain, "ascii") > MAX_MAILBOX_DOMAIN_BYTES || labels.length < 2 || labels.some((label) => Buffer.byteLength(label, "ascii") > 63 || !MAILBOX_DOMAIN_LABEL_PATTERN.test(label)) ) { throw new CustomerPortalUatError("customer-portal UAT: MAILBOX_EMAIL is invalid for the project invitation fixture"); } return { localPart: localPart.toLocaleLowerCase("en-US"), domain: domain.toLocaleLowerCase("en-US") }; } export function parseProjectInvitationContactInput(env: CustomerPortalUatEnvironment): ProjectInvitationContactInput { if (requiredEnvironmentValue(env, "E2E_PORTAL_INVITATION_ENTRYPOINT") !== "project") { throw new CustomerPortalUatError("customer-portal UAT: project invitation fixture requires the project entrypoint"); } const correlationKey = requiredEnvironmentValue(env, "E2E_PORTAL_SETUP_MAIL_FIXTURE_KEY"); if (!UAT_PROJECT_KEY_PATTERN.test(correlationKey)) { throw new CustomerPortalUatError("customer-portal UAT: project invitation fixture key is outside the dedicated P26a project namespace"); } const mailbox = parseMailboxBase(env); const derivedLocalPart = `${mailbox.localPart}+${correlationKey}`; const expectedEmail = `${derivedLocalPart}@${mailbox.domain}`; if (Buffer.byteLength(derivedLocalPart, "ascii") > MAX_MAILBOX_LOCAL_PART_BYTES || Buffer.byteLength(expectedEmail, "ascii") > MAX_MAILBOX_ADDRESS_BYTES) { throw new CustomerPortalUatError("customer-portal UAT: project invitation recipient does not match its fixture key"); } const rawEmail = requiredEnvironmentValue(env, "E2E_PORTAL_INVITATION_EMAIL"); if (rawEmail !== env.E2E_PORTAL_INVITATION_EMAIL) { throw new CustomerPortalUatError("customer-portal UAT: project invitation recipient does not match its fixture key"); } const email = rawEmail.toLocaleLowerCase("en-US"); if (email !== expectedEmail) { throw new CustomerPortalUatError("customer-portal UAT: project invitation recipient does not match its fixture key"); } return { correlationKey, email }; } export function projectInvitationContactIds(tenantId: string, correlationKey: string): ProjectInvitationContactIds { const digest = createHash("sha256").update(`${tenantId}:${CUSTOMER_PORTAL_UAT_PROJECT_ID}:${correlationKey}`).digest("hex"); return { kontaktId: `customer-portal-uat-project-kontakt-${digest}`, kontaktEmailId: `customer-portal-uat-project-email-${digest}`, projektKontaktId: `customer-portal-uat-project-link-${digest}`, }; } function canonicalContact(command: ProjectInvitationContactCommand): CanonicalProjectInvitationContact { const ids = projectInvitationContactIds(command.expectedTenantId, command.correlationKey); const suffix = ids.kontaktId.slice(-12).toUpperCase(); return { ids, firstName: "Portal", lastName: `Project-${suffix}` }; } function sameEmail(left: string | null, right: string): boolean { return left?.trim().toLocaleLowerCase("en-US") === right; } export function assessProjectInvitationContact( snapshot: ProjectInvitationContactSnapshot, command: ProjectInvitationContactCommand ): ProjectInvitationContactAssessment { const canonical = canonicalContact(command); const reconcileIssues: string[] = []; const blockingIssues: string[] = []; if ( !snapshot.tenant || snapshot.tenant.id !== command.expectedTenantId || snapshot.tenant.slug !== CUSTOMER_PORTAL_UAT_TENANT_SLUG || !snapshot.tenant.active ) { blockingIssues.push("target tenant is missing, inactive, or outside the explicit demo-pro-crm binding"); } if ( !snapshot.project || snapshot.project.id !== CUSTOMER_PORTAL_UAT_PROJECT_ID || snapshot.project.tenantId !== command.expectedTenantId || snapshot.project.archivedAt !== null || !snapshot.project.projekttyp || snapshot.project.pipeline.tenantId !== command.expectedTenantId || snapshot.project.pipeline.archivedAt !== null || snapshot.project.stage.tenantId !== command.expectedTenantId || snapshot.project.stage.pipelineId !== snapshot.project.pipeline.id || snapshot.project.stage.archivedAt !== null ) { blockingIssues.push("deterministic UAT project, stage, or pipeline is missing, archived, incomplete, or outside the target tenant"); } if ( !snapshot.portal || snapshot.portal.tenantId !== command.expectedTenantId || !snapshot.portal.isPublished || !snapshot.configuration || snapshot.configuration.tenantId !== command.expectedTenantId || snapshot.configuration.portalId !== snapshot.portal.id || !snapshot.project?.projekttyp || !snapshot.configuration.enabledProjectTypes.includes(snapshot.project.projekttyp) || !snapshot.stageVisibility || snapshot.stageVisibility.tenantId !== command.expectedTenantId || snapshot.stageVisibility.portalId !== snapshot.portal.id || snapshot.stageVisibility.stageId !== snapshot.project.stage.id || !snapshot.stageVisibility.visible ) { blockingIssues.push("deterministic UAT project is not visible through the published target portal"); } if ( !snapshot.ownerMembership || snapshot.ownerMembership.tenantId !== command.expectedTenantId || snapshot.ownerMembership.userId !== UAT_ADMIN_USER_ID || snapshot.ownerMembership.joined !== 1 || snapshot.ownerMembership.status !== 2 || snapshot.ownerMembership.user.id !== UAT_ADMIN_USER_ID || !snapshot.ownerMembership.user.active || snapshot.ownerMembership.user.pendingDeletion || snapshot.ownerMembership.user.pseudonymized ) { blockingIssues.push("dedicated UAT tenant admin is not an active target-tenant member"); } const contact = snapshot.contacts.find((candidate) => candidate.id === canonical.ids.kontaktId); const contactCollisions = snapshot.contacts.filter((candidate) => candidate.id !== canonical.ids.kontaktId); if (contactCollisions.length > 0) blockingIssues.push("invitation recipient collides with another CRM contact"); if (contact && (!contact.isDemoData || contact.tenantId !== command.expectedTenantId || contact.createdByUserId !== UAT_ADMIN_USER_ID)) { blockingIssues.push("deterministic CRM contact id is not owned by the VA-P26a fixture"); } else if ( !contact || contact.kontaktTyp !== "privatperson" || contact.kontaktStatus !== "kontakt" || contact.vorname !== canonical.firstName || contact.nachname !== canonical.lastName || !sameEmail(contact.primaerEmail, command.email) || contact.zustaendigerUserId !== UAT_ADMIN_USER_ID || contact.archivedAt !== null ) { reconcileIssues.push("deterministic UAT CRM contact is missing or drifted"); } const email = snapshot.emails.find((candidate) => candidate.id === canonical.ids.kontaktEmailId); const emailCollisions = snapshot.emails.filter((candidate) => candidate.id !== canonical.ids.kontaktEmailId); if (emailCollisions.length > 0) blockingIssues.push("invitation recipient collides with another CRM email row"); if (email && (email.tenantId !== command.expectedTenantId || email.kontaktId !== canonical.ids.kontaktId)) { blockingIssues.push("deterministic CRM email id belongs to another contact"); } else if (!email || !sameEmail(email.email, command.email) || !email.primaer) { reconcileIssues.push("deterministic primary CRM email is missing or drifted"); } const projectContact = snapshot.projectContacts.find((candidate) => candidate.id === canonical.ids.projektKontaktId); const projectContactCollisions = snapshot.projectContacts.filter((candidate) => candidate.id !== canonical.ids.projektKontaktId); if (projectContactCollisions.length > 0) blockingIssues.push("project already has another matching contact assignment"); if ( projectContact && (projectContact.tenantId !== command.expectedTenantId || projectContact.projektId !== CUSTOMER_PORTAL_UAT_PROJECT_ID || projectContact.kontaktId !== canonical.ids.kontaktId) ) { blockingIssues.push("deterministic project-contact id belongs to another assignment"); } else if (!projectContact || projectContact.rolle !== "ansprechpartner" || projectContact.primaer) { reconcileIssues.push("deterministic private project-contact assignment is missing or drifted"); } const action = blockingIssues.length > 0 ? "blocked" : reconcileIssues.length > 0 ? "reconcile" : "noop"; return { action, reconcileIssues, blockingIssues, handoff: action === "noop" ? { projectPath: `/${CUSTOMER_PORTAL_UAT_TENANT_SLUG}/projects/${CUSTOMER_PORTAL_UAT_PROJECT_ID}`, projectContactRowId: canonical.ids.projektKontaktId, } : null, }; } export async function readProjectInvitationContact(db: DbClient, command: ProjectInvitationContactCommand): Promise { const canonical = canonicalContact(command); const tenant = await db.tenant.findFirst({ where: { id: command.expectedTenantId, slug: CUSTOMER_PORTAL_UAT_TENANT_SLUG }, select: { id: true, slug: true, active: true }, }); const project = await db.projekt.findFirst({ where: { id: CUSTOMER_PORTAL_UAT_PROJECT_ID, tenantId: command.expectedTenantId }, select: { id: true, tenantId: true, projekttyp: true, archivedAt: true, pipeline: { select: { id: true, tenantId: true, archivedAt: true } }, stage: { select: { id: true, tenantId: true, pipelineId: true, archivedAt: true } }, }, }); const portal = await db.portal.findFirst({ where: { tenantId: command.expectedTenantId }, select: { id: true, tenantId: true, isPublished: true }, }); const configuration = await db.portalConfiguration.findFirst({ where: { tenantId: command.expectedTenantId }, select: { portalId: true, tenantId: true, enabledProjectTypes: true }, }); const stageVisibility = project ? await db.portalStageVisibility.findFirst({ where: { tenantId: command.expectedTenantId, stageId: project.stage.id }, select: { portalId: true, tenantId: true, stageId: true, visible: true }, }) : null; const ownerMembership = await db.tenantUser.findFirst({ where: { tenantId: command.expectedTenantId, userId: UAT_ADMIN_USER_ID }, select: { tenantId: true, userId: true, joined: true, status: true, user: { select: { id: true, active: true, pendingDeletion: true, pseudonymized: true } }, }, }); const contactMatches = await db.$queryRaw>` SELECT contact."id" FROM "Kontakt" AS contact WHERE contact."tenantId" = ${command.expectedTenantId} AND ( contact."id" = ${canonical.ids.kontaktId} OR lower(btrim(contact."primaerEmail")) = ${command.email} ) `; const contacts = await db.kontakt.findMany({ where: { tenantId: command.expectedTenantId, id: { in: contactMatches.map(({ id }) => id) } }, select: { id: true, tenantId: true, createdByUserId: true, kontaktTyp: true, kontaktStatus: true, vorname: true, nachname: true, primaerEmail: true, zustaendigerUserId: true, isDemoData: true, archivedAt: true, }, }); const emailMatches = await db.$queryRaw>` SELECT email."id" FROM "KontaktEmail" AS email WHERE email."tenantId" = ${command.expectedTenantId} AND ( email."id" = ${canonical.ids.kontaktEmailId} OR email."kontaktId" = ${canonical.ids.kontaktId} OR lower(btrim(email."email")) = ${command.email} ) `; const emails = await db.kontaktEmail.findMany({ where: { tenantId: command.expectedTenantId, id: { in: emailMatches.map(({ id }) => id) } }, select: { id: true, tenantId: true, kontaktId: true, email: true, primaer: true }, }); const projectContacts = await db.projektKontakt.findMany({ where: { tenantId: command.expectedTenantId, OR: [{ id: canonical.ids.projektKontaktId }, { projektId: CUSTOMER_PORTAL_UAT_PROJECT_ID, kontaktId: canonical.ids.kontaktId }], }, select: { id: true, tenantId: true, projektId: true, kontaktId: true, rolle: true, primaer: true }, }); return { tenant, project, portal, configuration, stageVisibility, ownerMembership, contacts, emails, projectContacts }; } async function lockProjectInvitationContactRows(db: DbClient, command: ProjectInvitationContactCommand): Promise { const canonical = canonicalContact(command); const tenantLocks = await db.$queryRaw>` SELECT tenant."id" FROM "Tenant" AS tenant WHERE tenant."id" = ${command.expectedTenantId} AND tenant."slug" = ${CUSTOMER_PORTAL_UAT_TENANT_SLUG} FOR UPDATE `; if (tenantLocks.length !== 1) { throw new CustomerPortalUatError("customer-portal UAT: target tenant changed after guarded project-contact preflight"); } await db.$queryRaw` SELECT project."id" FROM "Projekt" AS project WHERE project."id" = ${CUSTOMER_PORTAL_UAT_PROJECT_ID} AND project."tenantId" = ${command.expectedTenantId} FOR UPDATE `; await db.$queryRaw` SELECT portal."id" FROM "Portal" AS portal WHERE portal."tenantId" = ${command.expectedTenantId} FOR UPDATE `; await db.$queryRaw` SELECT configuration."id" FROM "PortalConfiguration" AS configuration WHERE configuration."tenantId" = ${command.expectedTenantId} FOR UPDATE `; await db.$queryRaw` SELECT visibility."id" FROM "PortalStageVisibility" AS visibility JOIN "Projekt" AS project ON project."tenantId" = visibility."tenantId" AND project."stageId" = visibility."stageId" WHERE project."id" = ${CUSTOMER_PORTAL_UAT_PROJECT_ID} AND project."tenantId" = ${command.expectedTenantId} FOR UPDATE OF visibility `; await db.$queryRaw` SELECT uat_user."id" FROM "User" AS uat_user WHERE uat_user."id" = ${UAT_ADMIN_USER_ID} FOR UPDATE `; await db.$queryRaw` SELECT membership."id" FROM "TenantUser" AS membership WHERE membership."tenantId" = ${command.expectedTenantId} AND membership."userId" = ${UAT_ADMIN_USER_ID} FOR UPDATE `; await db.$queryRaw` SELECT contact."id" FROM "Kontakt" AS contact WHERE contact."tenantId" = ${command.expectedTenantId} AND ( contact."id" = ${canonical.ids.kontaktId} OR lower(btrim(contact."primaerEmail")) = ${command.email} ) FOR UPDATE `; await db.$queryRaw` SELECT email."id" FROM "KontaktEmail" AS email WHERE email."tenantId" = ${command.expectedTenantId} AND ( email."id" = ${canonical.ids.kontaktEmailId} OR email."kontaktId" = ${canonical.ids.kontaktId} OR lower(btrim(email."email")) = ${command.email} ) FOR UPDATE `; await db.$queryRaw` SELECT project_contact."id" FROM "ProjektKontakt" AS project_contact WHERE project_contact."tenantId" = ${command.expectedTenantId} AND ( project_contact."id" = ${canonical.ids.projektKontaktId} OR ( project_contact."projektId" = ${CUSTOMER_PORTAL_UAT_PROJECT_ID} AND project_contact."kontaktId" = ${canonical.ids.kontaktId} ) ) FOR UPDATE `; } export async function applyProjectInvitationContact( db: DbClient, command: ProjectInvitationContactCommand, snapshot: ProjectInvitationContactSnapshot ): Promise { const assessment = assessProjectInvitationContact(snapshot, command); if (assessment.action === "blocked") { throw new CustomerPortalUatError("customer-portal UAT: project invitation contact apply is blocked by unsafe or non-UAT state"); } if (assessment.action === "noop") return; await db.$transaction(async (tx) => { const transactionDb = tx as unknown as DbClient; await lockProjectInvitationContactRows(transactionDb, command); const lockedSnapshot = await readProjectInvitationContact(transactionDb, command); const lockedAssessment = assessProjectInvitationContact(lockedSnapshot, command); if (lockedAssessment.action === "blocked") { throw new CustomerPortalUatError("customer-portal UAT: project invitation contact ownership changed after guarded preflight"); } if (lockedAssessment.action === "noop") return; const canonical = canonicalContact(command); const contactCreate = { id: canonical.ids.kontaktId, tenantId: command.expectedTenantId, createdByUserId: UAT_ADMIN_USER_ID, kontaktTyp: "privatperson", kontaktStatus: "kontakt", vorname: canonical.firstName, nachname: canonical.lastName, primaerEmail: command.email, zustaendigerUserId: UAT_ADMIN_USER_ID, isDemoData: true, } satisfies Prisma.KontaktUncheckedCreateInput; const contactUpdate = { kontaktTyp: "privatperson", kontaktStatus: "kontakt", vorname: canonical.firstName, nachname: canonical.lastName, orgName: null, orgMerkmal: null, primaerEmail: command.email, zustaendigerUserId: UAT_ADMIN_USER_ID, isDemoData: true, archivedAt: null, } satisfies Prisma.KontaktUncheckedUpdateInput; await tx.kontakt.upsert({ where: { id: canonical.ids.kontaktId }, create: contactCreate, update: contactUpdate }); const emailCreate = { id: canonical.ids.kontaktEmailId, tenantId: command.expectedTenantId, kontaktId: canonical.ids.kontaktId, email: command.email, primaer: true, } satisfies Prisma.KontaktEmailUncheckedCreateInput; const emailUpdate = { email: command.email, primaer: true } satisfies Prisma.KontaktEmailUncheckedUpdateInput; await tx.kontaktEmail.upsert({ where: { id: canonical.ids.kontaktEmailId }, create: emailCreate, update: emailUpdate }); const projectContactCreate = { id: canonical.ids.projektKontaktId, tenantId: command.expectedTenantId, projektId: CUSTOMER_PORTAL_UAT_PROJECT_ID, kontaktId: canonical.ids.kontaktId, rolle: "ansprechpartner", primaer: false, } satisfies Prisma.ProjektKontaktUncheckedCreateInput; const projectContactUpdate = { rolle: "ansprechpartner", primaer: false, } satisfies Prisma.ProjektKontaktUncheckedUpdateInput; await tx.projektKontakt.upsert({ where: { id: canonical.ids.projektKontaktId }, create: projectContactCreate, update: projectContactUpdate, }); await publishAuditEventViaOutbox(tx, { tenantId: command.expectedTenantId, actorId: command.operatorUserId, actorType: "operator", action: "customer_portal.uat_project_invitation_contact.provisioned", targetType: "ProjektKontakt", targetId: canonical.ids.projektKontaktId, sourceModule: "customer-portal-uat", outcome: "success", dataSensitivity: "internal", regulatoryScope: ["none"], metadata: { tenantSlug: CUSTOMER_PORTAL_UAT_TENANT_SLUG, projectId: CUSTOMER_PORTAL_UAT_PROJECT_ID }, }); }); }