Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/scripts/customer-portal-uat/project-invitation-contact.test.ts
T

285 lines
12 KiB
TypeScript

// @vitest-environment node
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { publishAuditEventViaOutbox } from "@hivegrid/db/audit-events.server";
import type { DbClient } from "@hivegrid/db/client.server";
import { describe, expect, it, vi } from "vitest";
import { CUSTOMER_PORTAL_UAT_PROJECT_ID, CUSTOMER_PORTAL_UAT_TENANT_SLUG } from "./contracts";
import {
applyProjectInvitationContact,
assessProjectInvitationContact,
parseProjectInvitationContactInput,
projectInvitationContactIds,
type ProjectInvitationContactCommand,
type ProjectInvitationContactSnapshot,
} from "./project-invitation-contact";
vi.mock("@hivegrid/db/audit-events.server", () => ({ publishAuditEventViaOutbox: vi.fn(async () => undefined) }));
const tenantId = "tenant-demo-pro";
const correlationKey = "p26a-project-20260720t120000z-42";
const mailboxEmail = "fixture@example.test";
const email = `fixture+${correlationKey}@example.test`;
function command(mode: ProjectInvitationContactCommand["mode"] = "apply"): ProjectInvitationContactCommand {
return {
target: "fixture",
mode,
databaseUrl: "postgresql://hivegrid_app:redacted@127.0.0.1:6432/hivegrid_staging",
expectedDatabaseHost: "127.0.0.1",
expectedDatabasePort: "6432",
expectedDatabaseName: "hivegrid_staging",
operatorUserId: "operator-user-id",
auditChainSecret: "redacted-audit-chain-secret-at-least-32-bytes",
expectedTenantId: tenantId,
password: "redacted-strong-fixture-password",
correlationKey,
email,
};
}
function healthySnapshot(): ProjectInvitationContactSnapshot {
const ids = projectInvitationContactIds(tenantId, correlationKey);
const suffix = ids.kontaktId.slice(-12).toUpperCase();
return {
tenant: { id: tenantId, slug: CUSTOMER_PORTAL_UAT_TENANT_SLUG, active: true },
project: {
id: CUSTOMER_PORTAL_UAT_PROJECT_ID,
tenantId,
projekttyp: "sales",
archivedAt: null,
pipeline: { id: "pipeline-sales", tenantId, archivedAt: null },
stage: { id: "stage-open", tenantId, pipelineId: "pipeline-sales", archivedAt: null },
},
portal: { id: "portal-demo-pro", tenantId, isPublished: true },
configuration: { portalId: "portal-demo-pro", tenantId, enabledProjectTypes: ["sales"] },
stageVisibility: { portalId: "portal-demo-pro", tenantId, stageId: "stage-open", visible: true },
ownerMembership: {
tenantId,
userId: "customer-portal-uat-tenant-admin",
joined: 1,
status: 2,
user: {
id: "customer-portal-uat-tenant-admin",
active: true,
pendingDeletion: false,
pseudonymized: false,
},
},
contacts: [
{
id: ids.kontaktId,
tenantId,
createdByUserId: "customer-portal-uat-tenant-admin",
kontaktTyp: "privatperson",
kontaktStatus: "kontakt",
vorname: "Portal",
nachname: `Project-${suffix}`,
primaerEmail: email,
zustaendigerUserId: "customer-portal-uat-tenant-admin",
isDemoData: true,
archivedAt: null,
},
],
emails: [{ id: ids.kontaktEmailId, tenantId, kontaktId: ids.kontaktId, email, primaer: true }],
projectContacts: [
{
id: ids.projektKontaktId,
tenantId,
projektId: CUSTOMER_PORTAL_UAT_PROJECT_ID,
kontaktId: ids.kontaktId,
rolle: "ansprechpartner",
primaer: false,
},
],
};
}
describe("VA-P26a project invitation contact fixture", () => {
it("binds the existing invitation inputs to the dedicated project namespace", () => {
expect(
parseProjectInvitationContactInput({
E2E_PORTAL_INVITATION_ENTRYPOINT: "project",
E2E_PORTAL_SETUP_MAIL_FIXTURE_KEY: correlationKey,
E2E_PORTAL_INVITATION_EMAIL: email,
MAILBOX_EMAIL: mailboxEmail,
})
).toEqual({ correlationKey, email });
expect(() =>
parseProjectInvitationContactInput({
E2E_PORTAL_INVITATION_ENTRYPOINT: "contact",
E2E_PORTAL_SETUP_MAIL_FIXTURE_KEY: correlationKey,
E2E_PORTAL_INVITATION_EMAIL: email,
MAILBOX_EMAIL: mailboxEmail,
})
).toThrow("requires the project entrypoint");
expect(() =>
parseProjectInvitationContactInput({
E2E_PORTAL_INVITATION_ENTRYPOINT: "project",
E2E_PORTAL_SETUP_MAIL_FIXTURE_KEY: "p26a-project-UPPERCASE",
E2E_PORTAL_INVITATION_EMAIL: "fixture+p26a-project-uppercase@example.test",
MAILBOX_EMAIL: mailboxEmail,
})
).toThrow("outside the dedicated P26a project namespace");
for (const invalidCorrelationKey of [
"p26a-project-with.dot",
"p26a-project-with_underscore",
"p26a-project-with:colon",
`p26a-project-${"a".repeat(84)}`,
]) {
expect(() =>
parseProjectInvitationContactInput({
E2E_PORTAL_INVITATION_ENTRYPOINT: "project",
E2E_PORTAL_SETUP_MAIL_FIXTURE_KEY: invalidCorrelationKey,
E2E_PORTAL_INVITATION_EMAIL: `fixture+${invalidCorrelationKey}@example.test`,
MAILBOX_EMAIL: mailboxEmail,
})
).toThrow("outside the dedicated P26a project namespace");
}
expect(() =>
parseProjectInvitationContactInput({
E2E_PORTAL_INVITATION_ENTRYPOINT: "project",
E2E_PORTAL_SETUP_MAIL_FIXTURE_KEY: correlationKey,
E2E_PORTAL_INVITATION_EMAIL: "fixture+different@example.test",
MAILBOX_EMAIL: mailboxEmail,
})
).toThrow("does not match its fixture key");
});
it("rejects invalid authenticated mailbox bases without exposing them", () => {
for (const invalidMailboxEmail of ["fixture+existing@example.test", "fixture@localhost", ".fixture@example.test", "fixture@-example.test"]) {
expect(() =>
parseProjectInvitationContactInput({
E2E_PORTAL_INVITATION_ENTRYPOINT: "project",
E2E_PORTAL_SETUP_MAIL_FIXTURE_KEY: correlationKey,
E2E_PORTAL_INVITATION_EMAIL: email,
MAILBOX_EMAIL: invalidMailboxEmail,
})
).toThrow("MAILBOX_EMAIL is invalid");
}
});
it("derives all row ids from the tenant, project, and correlation key", () => {
const digest = createHash("sha256").update(`${tenantId}:${CUSTOMER_PORTAL_UAT_PROJECT_ID}:${correlationKey}`).digest("hex");
expect(projectInvitationContactIds(tenantId, correlationKey)).toEqual({
kontaktId: `customer-portal-uat-project-kontakt-${digest}`,
kontaktEmailId: `customer-portal-uat-project-email-${digest}`,
projektKontaktId: `customer-portal-uat-project-link-${digest}`,
});
});
it("accepts only the complete UAT-owned rows and emits a redacted handoff", () => {
const assessment = assessProjectInvitationContact(healthySnapshot(), command("verify"));
expect(assessment).toMatchObject({ action: "noop", reconcileIssues: [], blockingIssues: [] });
expect(assessment.handoff).toEqual({
projectPath: `/${CUSTOMER_PORTAL_UAT_TENANT_SLUG}/projects/${CUSTOMER_PORTAL_UAT_PROJECT_ID}`,
projectContactRowId: projectInvitationContactIds(tenantId, correlationKey).projektKontaktId,
});
const handoffJson = JSON.stringify(assessment.handoff);
expect(handoffJson).not.toContain(email);
expect(handoffJson).not.toContain(correlationKey);
expect(handoffJson).not.toContain("Project-");
});
it("reconciles missing rows but blocks recipient and ownership collisions", () => {
const healthy = healthySnapshot();
expect(assessProjectInvitationContact({ ...healthy, contacts: [], emails: [], projectContacts: [] }, command()).action).toBe("reconcile");
const hiddenProject = assessProjectInvitationContact({ ...healthy, stageVisibility: { ...healthy.stageVisibility!, visible: false } }, command());
expect(hiddenProject.action).toBe("blocked");
expect(hiddenProject.blockingIssues).toContain("deterministic UAT project is not visible through the published target portal");
const foreignContact = {
...healthy.contacts[0]!,
id: "foreign-contact",
createdByUserId: "another-user",
isDemoData: false,
};
const collision = assessProjectInvitationContact({ ...healthy, contacts: [...healthy.contacts, foreignContact] }, command());
expect(collision.action).toBe("blocked");
expect(collision.blockingIssues).toContain("invitation recipient collides with another CRM contact");
expect(collision.handoff).toBeNull();
const foreignOwner = assessProjectInvitationContact({ ...healthy, contacts: [{ ...healthy.contacts[0]!, createdByUserId: "another-user" }] }, command());
expect(foreignOwner.action).toBe("blocked");
expect(foreignOwner.blockingIssues).toContain("deterministic CRM contact id is not owned by the VA-P26a fixture");
});
it("locks and revalidates before typed writes and appends a redacted audit outbox event", async () => {
const missingSnapshot = { ...healthySnapshot(), contacts: [], emails: [], projectContacts: [] };
const ids = projectInvitationContactIds(tenantId, correlationKey);
const queryRaw = vi.fn().mockResolvedValue([]);
queryRaw.mockResolvedValueOnce([{ id: tenantId }]);
const kontaktUpsert = vi.fn(async () => ({ id: ids.kontaktId }));
const emailUpsert = vi.fn(async () => ({ id: ids.kontaktEmailId }));
const projectContactUpsert = vi.fn(async () => ({ id: ids.projektKontaktId }));
const tx = {
$queryRaw: queryRaw,
tenant: { findFirst: vi.fn(async () => missingSnapshot.tenant) },
projekt: { findFirst: vi.fn(async () => missingSnapshot.project) },
portal: { findFirst: vi.fn(async () => missingSnapshot.portal) },
portalConfiguration: { findFirst: vi.fn(async () => missingSnapshot.configuration) },
portalStageVisibility: { findFirst: vi.fn(async () => missingSnapshot.stageVisibility) },
tenantUser: { findFirst: vi.fn(async () => missingSnapshot.ownerMembership) },
kontakt: { findMany: vi.fn(async () => []), upsert: kontaktUpsert },
kontaktEmail: { findMany: vi.fn(async () => []), upsert: emailUpsert },
projektKontakt: { findMany: vi.fn(async () => []), upsert: projectContactUpsert },
};
const db = {
$transaction: vi.fn(async (operation: (client: typeof tx) => Promise<void>) => operation(tx)),
} as unknown as DbClient;
await applyProjectInvitationContact(db, command(), missingSnapshot);
expect(queryRaw).toHaveBeenCalledTimes(12);
expect(kontaktUpsert).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: ids.kontaktId },
create: expect.objectContaining({
kontaktTyp: "privatperson",
primaerEmail: email,
zustaendigerUserId: "customer-portal-uat-tenant-admin",
isDemoData: true,
}),
})
);
expect(emailUpsert).toHaveBeenCalledWith(expect.objectContaining({ create: expect.objectContaining({ kontaktId: ids.kontaktId, email, primaer: true }) }));
expect(projectContactUpsert).toHaveBeenCalledWith(
expect.objectContaining({
create: expect.objectContaining({
projektId: CUSTOMER_PORTAL_UAT_PROJECT_ID,
kontaktId: ids.kontaktId,
rolle: "ansprechpartner",
primaer: false,
}),
})
);
expect(publishAuditEventViaOutbox).toHaveBeenCalledTimes(1);
const auditInput = vi.mocked(publishAuditEventViaOutbox).mock.calls[0]?.[1];
expect(auditInput).toMatchObject({
action: "customer_portal.uat_project_invitation_contact.provisioned",
targetType: "ProjektKontakt",
targetId: ids.projektKontaktId,
});
const auditJson = JSON.stringify(auditInput);
expect(auditJson).not.toContain(email);
expect(auditJson).not.toContain(correlationKey);
});
it("keeps plan/apply/verify output limited to mode, completion, and handoff", () => {
const coreSource = readFileSync(new URL("./project-invitation-contact.ts", import.meta.url), "utf8");
const cliSource = readFileSync(new URL("./provision-project-invitation-contact.ts", import.meta.url), "utf8");
expect(coreSource.match(/FOR UPDATE/gu)?.length).toBeGreaterThanOrEqual(10);
expect(coreSource.match(/lower\(btrim\(/gu)?.length).toBeGreaterThanOrEqual(4);
expect(coreSource).toContain("const lockedSnapshot = await readProjectInvitationContact(transactionDb, command)");
expect(coreSource).toContain("satisfies Prisma.KontaktUncheckedCreateInput");
expect(coreSource).toContain("publishAuditEventViaOutbox(tx");
expect(cliSource).toContain("readonly handoff: ProjectInvitationContactHandoff | null");
expect(cliSource).not.toContain("readonly assessment:");
expect(cliSource).not.toContain("command.email");
expect(cliSource).not.toContain("command.correlationKey");
});
});