952 lines
37 KiB
TypeScript
952 lines
37 KiB
TypeScript
import { hashCurrentPassword, verifySupportedPassword } from "../../apps/api/src/auth/password";
|
|
import { isDeepStrictEqual } from "node:util";
|
|
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_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,
|
|
CustomerPortalUatError,
|
|
type CustomerPortalFixtureCommand,
|
|
} from "./contracts";
|
|
|
|
const UAT_FORM_SLUG = "customer-portal-uat-complaint";
|
|
const UAT_FORM_KEY = "customer-portal-uat-complaint-key";
|
|
const UAT_FORM_NAME = "Kundenportal UAT Reklamation";
|
|
const UAT_INBOX_SOURCE_KEY = "customer-portal-uat:initial-service-item";
|
|
const UAT_INBOX_SOURCE_ID = "customer-portal-uat";
|
|
const UAT_INBOX_TITLE_KEY = "customerPortal.inbox.items.complaint";
|
|
const UAT_LEGAL_ORIGIN = "https://saas-ctrl.com";
|
|
const UAT_PORTAL_TITLE = "Demo Pro CRM Kundenportal";
|
|
const UAT_VERIFIED_AT = new Date("2026-07-17T00:00:00.000Z");
|
|
|
|
export const customerPortalUatComplaintDefinition = Object.freeze({
|
|
title: "Reklamation",
|
|
submitLabel: "Reklamation senden",
|
|
successMessage: "Deine Reklamation wurde gespeichert und das Projektteam informiert.",
|
|
gdprConsentLabel: "Ich stimme der Verarbeitung meiner Angaben zur Bearbeitung der Reklamation zu.",
|
|
fields: Object.freeze([
|
|
Object.freeze({ key: "subject", type: "text", label: "Betreff", required: true, validationRules: { minLength: 3, maxLength: 200 } }),
|
|
Object.freeze({ key: "details", type: "textarea", label: "Beschreibung", required: true, validationRules: { minLength: 3, maxLength: 5_000 } }),
|
|
]),
|
|
});
|
|
|
|
type FixtureProject = {
|
|
readonly id: string;
|
|
readonly projektname: string;
|
|
readonly projekttyp: string | null;
|
|
readonly stageId: string;
|
|
readonly archivedAt: Date | null;
|
|
readonly stage: { readonly name: string; readonly archivedAt: Date | null };
|
|
};
|
|
|
|
type FixtureUser = {
|
|
readonly id: string;
|
|
readonly emailNormalized: string;
|
|
readonly passwordHash: string | null;
|
|
readonly passwordMatches: boolean;
|
|
readonly firstName: string;
|
|
readonly lastName: string;
|
|
readonly kind: string;
|
|
readonly status: string;
|
|
readonly archivedAt: Date | null;
|
|
readonly emailVerifiedAt: Date | null;
|
|
readonly isDemoData: boolean;
|
|
};
|
|
|
|
type FixtureAccess = {
|
|
readonly id: string;
|
|
readonly portalUserId: string;
|
|
readonly projectId: string;
|
|
readonly active: boolean;
|
|
readonly revokedAt: Date | null;
|
|
readonly isDemoData: boolean;
|
|
readonly subcontractorAccess: {
|
|
readonly active: boolean;
|
|
readonly revokedAt: Date | null;
|
|
readonly canUpload: boolean;
|
|
readonly isDemoData: boolean;
|
|
} | null;
|
|
};
|
|
|
|
export type CustomerPortalFixtureSnapshot = {
|
|
readonly tenant: {
|
|
readonly id: string;
|
|
readonly slug: string;
|
|
readonly active: boolean;
|
|
readonly subscription: { readonly planCode: string | null; readonly status: string; readonly frozenAt: Date | null } | null;
|
|
} | null;
|
|
readonly projects: readonly FixtureProject[];
|
|
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;
|
|
} | null;
|
|
readonly configuration: {
|
|
readonly lifecycleMode: 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;
|
|
readonly users: readonly FixtureUser[];
|
|
readonly accesses: readonly FixtureAccess[];
|
|
readonly stageVisibilities: readonly {
|
|
readonly stageId: string;
|
|
readonly visible: boolean;
|
|
readonly isDemoData: boolean;
|
|
}[];
|
|
readonly form: {
|
|
readonly key: string;
|
|
readonly name: string;
|
|
readonly subtype: string;
|
|
readonly status: string;
|
|
readonly publishedAt: Date | null;
|
|
readonly isPublic: boolean;
|
|
readonly isEnabled: boolean;
|
|
readonly isDemoData: boolean;
|
|
readonly definition: unknown;
|
|
readonly targetType: string | null;
|
|
readonly targetEntityId: string | null;
|
|
readonly allowedOrigins: readonly string[];
|
|
readonly notifyEmails: readonly string[];
|
|
readonly config: unknown;
|
|
} | null;
|
|
readonly inbox: {
|
|
readonly portalId: string;
|
|
readonly portalUserId: string | null;
|
|
readonly projectId: string | null;
|
|
readonly kind: string;
|
|
readonly status: string;
|
|
readonly priority: number;
|
|
readonly sourceId: string | null;
|
|
readonly titleKey: string;
|
|
readonly metadata: unknown;
|
|
readonly bundledCount: number;
|
|
readonly ownerUserId: string | null;
|
|
readonly resolvedAt: Date | null;
|
|
readonly expiresAt: Date;
|
|
readonly isDemoData: boolean;
|
|
} | null;
|
|
};
|
|
|
|
export type CustomerPortalFixtureAssessment = {
|
|
readonly action: "noop" | "reconcile" | "blocked";
|
|
readonly reconcileIssues: readonly string[];
|
|
readonly blockingIssues: readonly string[];
|
|
readonly e2e: {
|
|
readonly portalBaseUrl: typeof CUSTOMER_PORTAL_UAT_STANDARD_ORIGIN;
|
|
readonly tenantSlug: typeof CUSTOMER_PORTAL_UAT_TENANT_SLUG;
|
|
readonly customerEmail: typeof CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL;
|
|
readonly subcontractorEmail: typeof CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL;
|
|
readonly subcontractorExpectedProject: string | null;
|
|
readonly subcontractorForbiddenProject: string | null;
|
|
};
|
|
};
|
|
|
|
function findUser(snapshot: CustomerPortalFixtureSnapshot, email: string): FixtureUser | undefined {
|
|
return snapshot.users.find((user) => user.emailNormalized === email);
|
|
}
|
|
|
|
function projectById(snapshot: CustomerPortalFixtureSnapshot, id: string): FixtureProject | undefined {
|
|
return snapshot.projects.find((project) => project.id === id);
|
|
}
|
|
|
|
function isUatOwnedPortal(metadata: unknown): boolean {
|
|
return typeof metadata === "object" && metadata !== null && "uatFixture" in metadata && metadata.uatFixture === "VA-P26";
|
|
}
|
|
|
|
export function assessCustomerPortalFixture(
|
|
snapshot: CustomerPortalFixtureSnapshot,
|
|
expectedTenantId: string,
|
|
now: Date = new Date()
|
|
): CustomerPortalFixtureAssessment {
|
|
const reconcileIssues: string[] = [];
|
|
const blockingIssues: string[] = [];
|
|
const expectedProject = projectById(snapshot, CUSTOMER_PORTAL_UAT_PROJECT_ID);
|
|
const forbiddenProject = projectById(snapshot, CUSTOMER_PORTAL_UAT_FORBIDDEN_PROJECT_ID);
|
|
|
|
if (!snapshot.tenant) blockingIssues.push("target tenant is not visible under the operator RLS context");
|
|
else {
|
|
if (snapshot.tenant.id !== expectedTenantId || snapshot.tenant.slug !== CUSTOMER_PORTAL_UAT_TENANT_SLUG) {
|
|
blockingIssues.push("target tenant does not match the explicit demo-pro-crm binding");
|
|
}
|
|
if (!snapshot.tenant.active) blockingIssues.push("target tenant is inactive");
|
|
if (
|
|
snapshot.tenant.subscription?.planCode !== "business" ||
|
|
snapshot.tenant.subscription.status.toLowerCase() !== "active" ||
|
|
snapshot.tenant.subscription.frozenAt !== null
|
|
) {
|
|
blockingIssues.push("target tenant must have an active, non-frozen business subscription");
|
|
}
|
|
}
|
|
|
|
for (const [label, project] of [
|
|
["expected", expectedProject],
|
|
["forbidden", forbiddenProject],
|
|
] as const) {
|
|
if (!project || project.archivedAt || project.stage.archivedAt || !project.projekttyp) {
|
|
blockingIssues.push(`${label} deterministic UAT project is missing, archived, or incomplete`);
|
|
}
|
|
}
|
|
if (expectedProject && forbiddenProject && expectedProject.projektname === forbiddenProject.projektname) {
|
|
blockingIssues.push("expected and forbidden UAT projects must have distinct names");
|
|
}
|
|
|
|
if (!snapshot.portal) reconcileIssues.push("published portal missing");
|
|
else {
|
|
if (!isUatOwnedPortal(snapshot.portal.metadata)) blockingIssues.push("existing portal is not marked as the VA-P26 UAT fixture");
|
|
if (
|
|
snapshot.portal.subdomain !== CUSTOMER_PORTAL_UAT_TENANT_SLUG ||
|
|
snapshot.portal.title !== UAT_PORTAL_TITLE ||
|
|
!snapshot.portal.isPublished ||
|
|
snapshot.portal.authRequireEmailVerification ||
|
|
snapshot.portal.authRequireOrganization ||
|
|
!snapshot.portal.authRequireName
|
|
) {
|
|
reconcileIssues.push("portal publication, standard-host, title, or login contract differs");
|
|
}
|
|
}
|
|
|
|
const requiredProjectTypes = [...new Set([expectedProject?.projekttyp, forbiddenProject?.projekttyp].filter((value): value is string => Boolean(value)))];
|
|
if (!snapshot.configuration) reconcileIssues.push("portal configuration missing");
|
|
else {
|
|
if (!snapshot.configuration.isDemoData) blockingIssues.push("existing portal configuration is not UAT-owned demo data");
|
|
if (
|
|
snapshot.configuration.lifecycleMode !== "customer" ||
|
|
!isDeepStrictEqual([...snapshot.configuration.enabledProjectTypes].sort(), [...requiredProjectTypes].sort()) ||
|
|
!snapshot.configuration.statusEmailsEnabled ||
|
|
snapshot.configuration.welcomeMessage !== "Willkommen im HiveGrid Test-Kundenportal." ||
|
|
snapshot.configuration.supportEmail !== "support@saas-ctrl.com"
|
|
) {
|
|
reconcileIssues.push("portal configuration does not enable the deterministic project types");
|
|
}
|
|
if (snapshot.configuration.uploadMaxFiles < 2 || snapshot.configuration.uploadMaxFileSizeBytes < 1_024) {
|
|
reconcileIssues.push("portal upload configuration is insufficient for the P26b journey");
|
|
}
|
|
if (!snapshot.configuration.imprintUrl || !snapshot.configuration.privacyUrl) {
|
|
reconcileIssues.push("portal legal links are incomplete");
|
|
}
|
|
}
|
|
|
|
const expectedUsers = [
|
|
{ email: CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL, kind: "customer" },
|
|
{ email: CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL, kind: "subcontractor" },
|
|
] as const;
|
|
for (const expected of expectedUsers) {
|
|
const user = findUser(snapshot, expected.email);
|
|
if (!user) {
|
|
reconcileIssues.push(`${expected.kind} UAT identity missing`);
|
|
continue;
|
|
}
|
|
if (!user.isDemoData) blockingIssues.push(`${expected.kind} UAT identity is not UAT-owned demo data`);
|
|
const canonicalName = expected.kind === "customer" ? ["Karla", "Kundin"] : ["Sascha", "Subunternehmer"];
|
|
if (
|
|
user.firstName !== canonicalName[0] ||
|
|
user.lastName !== canonicalName[1] ||
|
|
user.kind !== expected.kind ||
|
|
user.status !== "active" ||
|
|
user.archivedAt !== null ||
|
|
user.emailVerifiedAt === null ||
|
|
!user.passwordMatches
|
|
) {
|
|
reconcileIssues.push(`${expected.kind} UAT identity differs from the login contract`);
|
|
}
|
|
}
|
|
|
|
if (snapshot.portal && expectedProject) {
|
|
const customer = findUser(snapshot, CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL);
|
|
const subcontractor = findUser(snapshot, CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL);
|
|
for (const [kind, user] of [
|
|
["customer", customer],
|
|
["subcontractor", subcontractor],
|
|
] as const) {
|
|
if (!user) continue;
|
|
const activeAccesses = snapshot.accesses.filter((access) => access.portalUserId === user.id && access.active && !access.revokedAt);
|
|
const expectedAccess = activeAccesses.find((access) => access.projectId === expectedProject.id);
|
|
if (!expectedAccess) reconcileIssues.push(`${kind} project access missing`);
|
|
else if (!expectedAccess.isDemoData) blockingIssues.push(`${kind} project access is not UAT-owned demo data`);
|
|
const extra = activeAccesses.filter((access) => access.projectId !== expectedProject.id);
|
|
if (extra.some((access) => !access.isDemoData)) blockingIssues.push(`${kind} has a non-demo extra project access`);
|
|
else if (extra.length > 0) reconcileIssues.push(`${kind} has extra active demo project access`);
|
|
if (kind === "subcontractor" && expectedAccess) {
|
|
const sub = expectedAccess.subcontractorAccess;
|
|
if (sub && !sub.isDemoData) blockingIssues.push("subcontractor scope record is not UAT-owned demo data");
|
|
else if (!sub || !sub.active || sub.revokedAt || !sub.canUpload) reconcileIssues.push("subcontractor scope record is missing or inactive");
|
|
}
|
|
}
|
|
}
|
|
|
|
const requiredStageIds = [expectedProject?.stageId, forbiddenProject?.stageId].filter((value): value is string => Boolean(value));
|
|
for (const stageId of requiredStageIds) {
|
|
const visibility = snapshot.stageVisibilities.find((candidate) => candidate.stageId === stageId);
|
|
if (visibility && !visibility.isDemoData) blockingIssues.push(`stage visibility ${stageId} is not UAT-owned demo data`);
|
|
else if (!visibility?.visible) reconcileIssues.push(`stage visibility ${stageId} is incomplete`);
|
|
}
|
|
|
|
if (!snapshot.form) reconcileIssues.push("project-specific portal complaint form missing");
|
|
else {
|
|
if (!snapshot.form.isDemoData) blockingIssues.push("existing UAT complaint form is not UAT-owned demo data");
|
|
if (
|
|
snapshot.form.subtype !== "portal_form" ||
|
|
snapshot.form.key !== UAT_FORM_KEY ||
|
|
snapshot.form.name !== UAT_FORM_NAME ||
|
|
snapshot.form.status !== "published" ||
|
|
snapshot.form.publishedAt === null ||
|
|
!snapshot.form.isPublic ||
|
|
!snapshot.form.isEnabled ||
|
|
!isDeepStrictEqual(snapshot.form.definition, customerPortalUatComplaintDefinition) ||
|
|
snapshot.form.targetType !== "project" ||
|
|
snapshot.form.targetEntityId !== CUSTOMER_PORTAL_UAT_PROJECT_ID ||
|
|
!isDeepStrictEqual(snapshot.form.allowedOrigins, [CUSTOMER_PORTAL_UAT_STANDARD_ORIGIN]) ||
|
|
!isDeepStrictEqual(snapshot.form.notifyEmails, []) ||
|
|
!isDeepStrictEqual(snapshot.form.config, { honeypotEnabled: false })
|
|
) {
|
|
reconcileIssues.push("portal complaint form differs from the P26b contract");
|
|
}
|
|
}
|
|
|
|
if (!snapshot.inbox) reconcileIssues.push("open service-inbox UAT item missing");
|
|
else {
|
|
if (!snapshot.inbox.isDemoData) blockingIssues.push("existing UAT inbox item is not UAT-owned demo data");
|
|
const customer = findUser(snapshot, CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL);
|
|
if (
|
|
snapshot.inbox.portalId !== snapshot.portal?.id ||
|
|
snapshot.inbox.portalUserId !== customer?.id ||
|
|
snapshot.inbox.projectId !== expectedProject?.id ||
|
|
snapshot.inbox.kind !== "complaint" ||
|
|
snapshot.inbox.status !== "open" ||
|
|
snapshot.inbox.priority !== 100 ||
|
|
snapshot.inbox.sourceId !== UAT_INBOX_SOURCE_ID ||
|
|
snapshot.inbox.titleKey !== UAT_INBOX_TITLE_KEY ||
|
|
!isDeepStrictEqual(snapshot.inbox.metadata, { fixture: "VA-P26" }) ||
|
|
snapshot.inbox.bundledCount !== 1 ||
|
|
snapshot.inbox.ownerUserId !== null ||
|
|
snapshot.inbox.resolvedAt !== null ||
|
|
snapshot.inbox.expiresAt.getTime() <= now.getTime()
|
|
) {
|
|
reconcileIssues.push("service-inbox UAT item differs from the canonical project, customer, source, title, or lifecycle contract");
|
|
}
|
|
}
|
|
|
|
return {
|
|
action: blockingIssues.length > 0 ? "blocked" : reconcileIssues.length > 0 ? "reconcile" : "noop",
|
|
reconcileIssues,
|
|
blockingIssues,
|
|
e2e: {
|
|
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: expectedProject?.projektname ?? null,
|
|
subcontractorForbiddenProject: forbiddenProject?.projektname ?? null,
|
|
},
|
|
};
|
|
}
|
|
|
|
export async function readCustomerPortalFixture(db: DbClient, command: CustomerPortalFixtureCommand): Promise<CustomerPortalFixtureSnapshot> {
|
|
const tenant = await db.tenant.findFirst({
|
|
where: { id: command.expectedTenantId, slug: CUSTOMER_PORTAL_UAT_TENANT_SLUG },
|
|
select: { id: true, slug: true, active: true, subscription: { select: { planCode: true, status: true, frozenAt: true } } },
|
|
});
|
|
const projects = await db.projekt.findMany({
|
|
where: { tenantId: command.expectedTenantId, id: { in: [CUSTOMER_PORTAL_UAT_PROJECT_ID, CUSTOMER_PORTAL_UAT_FORBIDDEN_PROJECT_ID] } },
|
|
select: { id: true, projektname: true, projekttyp: true, stageId: true, archivedAt: true, stage: { select: { name: true, archivedAt: true } } },
|
|
});
|
|
const portal = await db.portal.findUnique({
|
|
where: { tenantId: command.expectedTenantId },
|
|
select: {
|
|
id: true,
|
|
subdomain: true,
|
|
title: true,
|
|
isPublished: true,
|
|
authRequireEmailVerification: true,
|
|
authRequireOrganization: true,
|
|
authRequireName: true,
|
|
metadata: true,
|
|
},
|
|
});
|
|
if (!portal) {
|
|
const [form, inbox] = await Promise.all([
|
|
db.form.findUnique({ where: { tenantId_slug: { tenantId: command.expectedTenantId, slug: UAT_FORM_SLUG } }, select: fixtureFormSelect }),
|
|
db.portalServiceInboxItem.findUnique({
|
|
where: { tenantId_sourceKey: { tenantId: command.expectedTenantId, sourceKey: UAT_INBOX_SOURCE_KEY } },
|
|
select: fixtureInboxSelect,
|
|
}),
|
|
]);
|
|
return { tenant, projects, portal: null, configuration: null, users: [], accesses: [], stageVisibilities: [], form, inbox };
|
|
}
|
|
|
|
const [configuration, rawUsers, visibleStages, form, inbox] = await Promise.all([
|
|
db.portalConfiguration.findUnique({
|
|
where: { portalId_tenantId: { portalId: portal.id, tenantId: command.expectedTenantId } },
|
|
select: {
|
|
lifecycleMode: true,
|
|
enabledProjectTypes: true,
|
|
uploadMaxFiles: true,
|
|
uploadMaxFileSizeBytes: true,
|
|
statusEmailsEnabled: true,
|
|
welcomeMessage: true,
|
|
supportEmail: true,
|
|
imprintUrl: true,
|
|
privacyUrl: true,
|
|
isDemoData: true,
|
|
},
|
|
}),
|
|
db.portalUser.findMany({
|
|
where: {
|
|
tenantId: command.expectedTenantId,
|
|
portalId: portal.id,
|
|
emailNormalized: { in: [CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL, CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL] },
|
|
},
|
|
select: {
|
|
id: true,
|
|
emailNormalized: true,
|
|
passwordHash: true,
|
|
firstName: true,
|
|
lastName: true,
|
|
kind: true,
|
|
status: true,
|
|
archivedAt: true,
|
|
emailVerifiedAt: true,
|
|
isDemoData: true,
|
|
},
|
|
}),
|
|
db.portalStageVisibility.findMany({
|
|
where: {
|
|
tenantId: command.expectedTenantId,
|
|
portalId: portal.id,
|
|
stageId: { in: projects.map((project) => project.stageId) },
|
|
},
|
|
select: { stageId: true, visible: true, isDemoData: true },
|
|
}),
|
|
db.form.findUnique({ where: { tenantId_slug: { tenantId: command.expectedTenantId, slug: UAT_FORM_SLUG } }, select: fixtureFormSelect }),
|
|
db.portalServiceInboxItem.findUnique({
|
|
where: { tenantId_sourceKey: { tenantId: command.expectedTenantId, sourceKey: UAT_INBOX_SOURCE_KEY } },
|
|
select: fixtureInboxSelect,
|
|
}),
|
|
]);
|
|
const users: FixtureUser[] = await Promise.all(
|
|
rawUsers.map(async (user) => ({
|
|
...user,
|
|
kind: String(user.kind),
|
|
status: String(user.status),
|
|
passwordMatches: user.passwordHash ? await verifySupportedPassword(command.password, user.passwordHash) : false,
|
|
}))
|
|
);
|
|
const accesses =
|
|
users.length === 0
|
|
? []
|
|
: await db.portalProjectAccess.findMany({
|
|
where: { tenantId: command.expectedTenantId, portalId: portal.id, portalUserId: { in: users.map((user) => user.id) } },
|
|
select: {
|
|
id: true,
|
|
portalUserId: true,
|
|
projectId: true,
|
|
active: true,
|
|
revokedAt: true,
|
|
isDemoData: true,
|
|
subcontractorAccess: { select: { active: true, revokedAt: true, canUpload: true, isDemoData: true } },
|
|
},
|
|
});
|
|
return {
|
|
tenant,
|
|
projects,
|
|
portal,
|
|
configuration,
|
|
users,
|
|
accesses,
|
|
stageVisibilities: visibleStages,
|
|
form,
|
|
inbox,
|
|
};
|
|
}
|
|
|
|
const fixtureFormSelect = {
|
|
key: true,
|
|
name: true,
|
|
subtype: true,
|
|
status: true,
|
|
publishedAt: true,
|
|
isPublic: true,
|
|
isEnabled: true,
|
|
isDemoData: true,
|
|
definition: true,
|
|
targetType: true,
|
|
targetEntityId: true,
|
|
allowedOrigins: true,
|
|
notifyEmails: true,
|
|
config: true,
|
|
} as const;
|
|
|
|
const fixtureInboxSelect = {
|
|
portalId: true,
|
|
portalUserId: true,
|
|
projectId: true,
|
|
kind: true,
|
|
status: true,
|
|
priority: true,
|
|
sourceId: true,
|
|
titleKey: true,
|
|
metadata: true,
|
|
bundledCount: true,
|
|
ownerUserId: true,
|
|
resolvedAt: true,
|
|
expiresAt: true,
|
|
isDemoData: true,
|
|
} as const;
|
|
|
|
async function passwordHashForUser(snapshot: CustomerPortalFixtureSnapshot, email: string, password: string): Promise<string> {
|
|
const existing = findUser(snapshot, email);
|
|
return existing?.passwordMatches && existing.passwordHash ? existing.passwordHash : hashCurrentPassword(password);
|
|
}
|
|
|
|
async function lockCustomerPortalFixtureRows(db: DbClient, command: CustomerPortalFixtureCommand): Promise<void> {
|
|
const tenantLocks = await db.$queryRaw<Array<{ id: string }>>`
|
|
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 preflight");
|
|
}
|
|
await db.$queryRaw`
|
|
SELECT project."id"
|
|
FROM "Projekt" AS project
|
|
WHERE project."tenantId" = ${command.expectedTenantId}
|
|
AND (project."id" = ${CUSTOMER_PORTAL_UAT_PROJECT_ID} OR project."id" = ${CUSTOMER_PORTAL_UAT_FORBIDDEN_PROJECT_ID})
|
|
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 portal_user."id"
|
|
FROM "PortalUser" AS portal_user
|
|
WHERE portal_user."tenantId" = ${command.expectedTenantId}
|
|
AND (
|
|
portal_user."id" IN ('customer-portal-uat-customer', 'customer-portal-uat-subcontractor')
|
|
OR portal_user."emailNormalized" = ${CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL}
|
|
OR portal_user."emailNormalized" = ${CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL}
|
|
)
|
|
FOR UPDATE
|
|
`;
|
|
await db.$queryRaw`
|
|
SELECT project_access."id"
|
|
FROM "PortalProjectAccess" AS project_access
|
|
WHERE project_access."tenantId" = ${command.expectedTenantId}
|
|
AND project_access."portalUserId" IN (
|
|
SELECT portal_user."id"
|
|
FROM "PortalUser" AS portal_user
|
|
WHERE portal_user."tenantId" = ${command.expectedTenantId}
|
|
AND (
|
|
portal_user."id" IN ('customer-portal-uat-customer', 'customer-portal-uat-subcontractor')
|
|
OR portal_user."emailNormalized" = ${CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL}
|
|
OR portal_user."emailNormalized" = ${CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL}
|
|
)
|
|
)
|
|
FOR UPDATE
|
|
`;
|
|
await db.$queryRaw`
|
|
SELECT subcontractor_access."id"
|
|
FROM "PortalSubcontractorAccess" AS subcontractor_access
|
|
WHERE subcontractor_access."tenantId" = ${command.expectedTenantId}
|
|
AND subcontractor_access."portalUserId" IN (
|
|
SELECT portal_user."id"
|
|
FROM "PortalUser" AS portal_user
|
|
WHERE portal_user."tenantId" = ${command.expectedTenantId}
|
|
AND (
|
|
portal_user."id" IN ('customer-portal-uat-customer', 'customer-portal-uat-subcontractor')
|
|
OR portal_user."emailNormalized" = ${CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL}
|
|
OR portal_user."emailNormalized" = ${CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL}
|
|
)
|
|
)
|
|
FOR UPDATE
|
|
`;
|
|
await db.$queryRaw`
|
|
SELECT visibility."id"
|
|
FROM "PortalStageVisibility" AS visibility
|
|
WHERE visibility."tenantId" = ${command.expectedTenantId}
|
|
AND visibility."stageId" IN (
|
|
SELECT project."stageId"
|
|
FROM "Projekt" AS project
|
|
WHERE project."tenantId" = ${command.expectedTenantId}
|
|
AND (project."id" = ${CUSTOMER_PORTAL_UAT_PROJECT_ID} OR project."id" = ${CUSTOMER_PORTAL_UAT_FORBIDDEN_PROJECT_ID})
|
|
)
|
|
FOR UPDATE
|
|
`;
|
|
await db.$queryRaw`
|
|
SELECT form."id"
|
|
FROM "Form" AS form
|
|
WHERE form."tenantId" = ${command.expectedTenantId}
|
|
AND (form."id" = 'customer-portal-uat-complaint-form' OR form."slug" = ${UAT_FORM_SLUG} OR form."key" = ${UAT_FORM_KEY})
|
|
FOR UPDATE
|
|
`;
|
|
await db.$queryRaw`
|
|
SELECT inbox."id"
|
|
FROM "PortalServiceInboxItem" AS inbox
|
|
WHERE inbox."tenantId" = ${command.expectedTenantId}
|
|
AND (inbox."id" = 'customer-portal-uat-inbox-item' OR inbox."sourceKey" = ${UAT_INBOX_SOURCE_KEY})
|
|
FOR UPDATE
|
|
`;
|
|
}
|
|
|
|
export async function applyCustomerPortalFixture(db: DbClient, command: CustomerPortalFixtureCommand, snapshot: CustomerPortalFixtureSnapshot): Promise<void> {
|
|
const assessment = assessCustomerPortalFixture(snapshot, command.expectedTenantId);
|
|
if (assessment.action === "blocked") {
|
|
throw new CustomerPortalUatError("customer-portal UAT: fixture apply is blocked by non-UAT or mismatched staging state");
|
|
}
|
|
if (assessment.action === "noop") return;
|
|
|
|
const now = new Date();
|
|
const inboxExpiry = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1_000);
|
|
|
|
await db.$transaction(async (tx) => {
|
|
const transactionDb = tx as unknown as DbClient;
|
|
await lockCustomerPortalFixtureRows(transactionDb, command);
|
|
const lockedSnapshot = await readCustomerPortalFixture(transactionDb, command);
|
|
const lockedAssessment = assessCustomerPortalFixture(lockedSnapshot, command.expectedTenantId);
|
|
if (lockedAssessment.action === "blocked") {
|
|
throw new CustomerPortalUatError("customer-portal UAT: fixture ownership changed after guarded preflight");
|
|
}
|
|
if (lockedAssessment.action === "noop") return;
|
|
const expectedProject = projectById(lockedSnapshot, CUSTOMER_PORTAL_UAT_PROJECT_ID);
|
|
const forbiddenProject = projectById(lockedSnapshot, CUSTOMER_PORTAL_UAT_FORBIDDEN_PROJECT_ID);
|
|
if (!expectedProject?.projekttyp || !forbiddenProject?.projekttyp) {
|
|
throw new CustomerPortalUatError("customer-portal UAT: deterministic projects changed after guarded preflight");
|
|
}
|
|
const [customerPasswordHash, subcontractorPasswordHash] = await Promise.all([
|
|
passwordHashForUser(lockedSnapshot, CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL, command.password),
|
|
passwordHashForUser(lockedSnapshot, CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL, command.password),
|
|
]);
|
|
const projectTypes = [...new Set([expectedProject.projekttyp, forbiddenProject.projekttyp])];
|
|
const portal = await tx.portal.upsert({
|
|
where: { tenantId: command.expectedTenantId },
|
|
create: {
|
|
id: "customer-portal-uat-demo-pro-crm",
|
|
tenantId: command.expectedTenantId,
|
|
subdomain: CUSTOMER_PORTAL_UAT_TENANT_SLUG,
|
|
title: UAT_PORTAL_TITLE,
|
|
isPublished: true,
|
|
authRequireEmailVerification: false,
|
|
authRequireOrganization: false,
|
|
authRequireName: true,
|
|
metadata: { uatFixture: "VA-P26" },
|
|
},
|
|
update: {
|
|
subdomain: CUSTOMER_PORTAL_UAT_TENANT_SLUG,
|
|
title: UAT_PORTAL_TITLE,
|
|
isPublished: true,
|
|
authRequireEmailVerification: false,
|
|
authRequireOrganization: false,
|
|
authRequireName: true,
|
|
},
|
|
select: { id: true },
|
|
});
|
|
await tx.portalConfiguration.upsert({
|
|
where: { portalId_tenantId: { portalId: portal.id, tenantId: command.expectedTenantId } },
|
|
create: {
|
|
id: "customer-portal-uat-configuration",
|
|
tenantId: command.expectedTenantId,
|
|
portalId: portal.id,
|
|
lifecycleMode: "customer",
|
|
enabledProjectTypes: projectTypes,
|
|
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,
|
|
},
|
|
update: {
|
|
lifecycleMode: "customer",
|
|
enabledProjectTypes: projectTypes,
|
|
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 customer = await tx.portalUser.upsert({
|
|
where: { portalId_emailNormalized: { portalId: portal.id, emailNormalized: CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL } },
|
|
create: {
|
|
id: "customer-portal-uat-customer",
|
|
tenantId: command.expectedTenantId,
|
|
portalId: portal.id,
|
|
email: CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL,
|
|
emailNormalized: CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL,
|
|
passwordHash: customerPasswordHash,
|
|
firstName: "Karla",
|
|
lastName: "Kundin",
|
|
kind: "customer",
|
|
status: "active",
|
|
locale: "de",
|
|
emailVerifiedAt: UAT_VERIFIED_AT,
|
|
isDemoData: true,
|
|
},
|
|
update: {
|
|
email: CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL,
|
|
passwordHash: customerPasswordHash,
|
|
firstName: "Karla",
|
|
lastName: "Kundin",
|
|
kind: "customer",
|
|
status: "active",
|
|
locale: "de",
|
|
emailVerifiedAt: UAT_VERIFIED_AT,
|
|
archivedAt: null,
|
|
isDemoData: true,
|
|
},
|
|
select: { id: true },
|
|
});
|
|
const subcontractor = await tx.portalUser.upsert({
|
|
where: { portalId_emailNormalized: { portalId: portal.id, emailNormalized: CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL } },
|
|
create: {
|
|
id: "customer-portal-uat-subcontractor",
|
|
tenantId: command.expectedTenantId,
|
|
portalId: portal.id,
|
|
email: CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL,
|
|
emailNormalized: CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL,
|
|
passwordHash: subcontractorPasswordHash,
|
|
firstName: "Sascha",
|
|
lastName: "Subunternehmer",
|
|
kind: "subcontractor",
|
|
status: "active",
|
|
locale: "de",
|
|
emailVerifiedAt: UAT_VERIFIED_AT,
|
|
isDemoData: true,
|
|
},
|
|
update: {
|
|
email: CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL,
|
|
passwordHash: subcontractorPasswordHash,
|
|
firstName: "Sascha",
|
|
lastName: "Subunternehmer",
|
|
kind: "subcontractor",
|
|
status: "active",
|
|
locale: "de",
|
|
emailVerifiedAt: UAT_VERIFIED_AT,
|
|
archivedAt: null,
|
|
isDemoData: true,
|
|
},
|
|
select: { id: true },
|
|
});
|
|
|
|
await tx.portalProjectAccess.updateMany({
|
|
where: {
|
|
tenantId: command.expectedTenantId,
|
|
portalId: portal.id,
|
|
portalUserId: { in: [customer.id, subcontractor.id] },
|
|
projectId: { not: CUSTOMER_PORTAL_UAT_PROJECT_ID },
|
|
isDemoData: true,
|
|
active: true,
|
|
},
|
|
data: { active: false, revokedAt: now },
|
|
});
|
|
await tx.portalProjectAccess.upsert({
|
|
where: { portalId_portalUserId_projectId: { portalId: portal.id, portalUserId: customer.id, projectId: expectedProject.id } },
|
|
create: {
|
|
id: "customer-portal-uat-customer-access",
|
|
tenantId: command.expectedTenantId,
|
|
portalId: portal.id,
|
|
portalUserId: customer.id,
|
|
projectId: expectedProject.id,
|
|
active: true,
|
|
statusEmailsEnabled: true,
|
|
isDemoData: true,
|
|
},
|
|
update: { active: true, revokedAt: null, statusEmailsEnabled: true, isDemoData: true },
|
|
select: { id: true },
|
|
});
|
|
const subcontractorAccess = await tx.portalProjectAccess.upsert({
|
|
where: {
|
|
portalId_portalUserId_projectId: { portalId: portal.id, portalUserId: subcontractor.id, projectId: expectedProject.id },
|
|
},
|
|
create: {
|
|
id: "customer-portal-uat-subcontractor-access",
|
|
tenantId: command.expectedTenantId,
|
|
portalId: portal.id,
|
|
portalUserId: subcontractor.id,
|
|
projectId: expectedProject.id,
|
|
active: true,
|
|
statusEmailsEnabled: false,
|
|
isDemoData: true,
|
|
},
|
|
update: { active: true, revokedAt: null, statusEmailsEnabled: false, isDemoData: true },
|
|
select: { id: true },
|
|
});
|
|
await tx.portalSubcontractorAccess.upsert({
|
|
where: {
|
|
portalId_portalUserId_projectId: { portalId: portal.id, portalUserId: subcontractor.id, projectId: expectedProject.id },
|
|
},
|
|
create: {
|
|
id: "customer-portal-uat-subcontractor-scope",
|
|
tenantId: command.expectedTenantId,
|
|
portalId: portal.id,
|
|
portalUserId: subcontractor.id,
|
|
projectId: expectedProject.id,
|
|
projectAccessId: subcontractorAccess.id,
|
|
companyName: "HiveGrid UAT Subunternehmer",
|
|
roleLabel: "Montagepartner",
|
|
visibleStageIds: [expectedProject.stageId],
|
|
visibleDocumentTypes: [],
|
|
canSeeOtherSubcontractors: false,
|
|
canUpload: true,
|
|
active: true,
|
|
isDemoData: true,
|
|
},
|
|
update: {
|
|
projectAccessId: subcontractorAccess.id,
|
|
companyName: "HiveGrid UAT Subunternehmer",
|
|
roleLabel: "Montagepartner",
|
|
visibleStageIds: [expectedProject.stageId],
|
|
visibleDocumentTypes: [],
|
|
canSeeOtherSubcontractors: false,
|
|
canUpload: true,
|
|
active: true,
|
|
revokedAt: null,
|
|
isDemoData: true,
|
|
},
|
|
});
|
|
|
|
for (const project of [expectedProject, forbiddenProject]) {
|
|
await tx.portalStageVisibility.upsert({
|
|
where: { portalId_stageId: { portalId: portal.id, stageId: project.stageId } },
|
|
create: {
|
|
tenantId: command.expectedTenantId,
|
|
portalId: portal.id,
|
|
stageId: project.stageId,
|
|
visible: true,
|
|
customerLabel: project.stage.name,
|
|
isDemoData: true,
|
|
},
|
|
update: { visible: true, customerLabel: project.stage.name, isDemoData: true },
|
|
});
|
|
}
|
|
|
|
await tx.form.upsert({
|
|
where: { tenantId_slug: { tenantId: command.expectedTenantId, slug: UAT_FORM_SLUG } },
|
|
create: {
|
|
id: "customer-portal-uat-complaint-form",
|
|
key: UAT_FORM_KEY,
|
|
tenantId: command.expectedTenantId,
|
|
slug: UAT_FORM_SLUG,
|
|
name: UAT_FORM_NAME,
|
|
subtype: "portal_form",
|
|
status: "published",
|
|
publishedAt: now,
|
|
isPublic: true,
|
|
isDemoData: true,
|
|
definition: customerPortalUatComplaintDefinition as unknown as Prisma.InputJsonValue,
|
|
targetType: "project",
|
|
targetEntityId: expectedProject.id,
|
|
allowedOrigins: [CUSTOMER_PORTAL_UAT_STANDARD_ORIGIN],
|
|
notifyEmails: [],
|
|
config: { honeypotEnabled: false },
|
|
isEnabled: true,
|
|
},
|
|
update: {
|
|
key: UAT_FORM_KEY,
|
|
name: UAT_FORM_NAME,
|
|
subtype: "portal_form",
|
|
status: "published",
|
|
publishedAt: now,
|
|
isPublic: true,
|
|
isDemoData: true,
|
|
definition: customerPortalUatComplaintDefinition as unknown as Prisma.InputJsonValue,
|
|
targetType: "project",
|
|
targetEntityId: expectedProject.id,
|
|
allowedOrigins: [CUSTOMER_PORTAL_UAT_STANDARD_ORIGIN],
|
|
notifyEmails: [],
|
|
config: { honeypotEnabled: false },
|
|
isEnabled: true,
|
|
},
|
|
});
|
|
await tx.portalServiceInboxItem.upsert({
|
|
where: { tenantId_sourceKey: { tenantId: command.expectedTenantId, sourceKey: UAT_INBOX_SOURCE_KEY } },
|
|
create: {
|
|
id: "customer-portal-uat-inbox-item",
|
|
tenantId: command.expectedTenantId,
|
|
portalId: portal.id,
|
|
portalUserId: customer.id,
|
|
projectId: expectedProject.id,
|
|
kind: "complaint",
|
|
status: "open",
|
|
priority: 100,
|
|
sourceKey: UAT_INBOX_SOURCE_KEY,
|
|
sourceId: UAT_INBOX_SOURCE_ID,
|
|
titleKey: UAT_INBOX_TITLE_KEY,
|
|
metadata: { fixture: "VA-P26" },
|
|
occurredAt: now,
|
|
lastOccurredAt: now,
|
|
bundledCount: 1,
|
|
expiresAt: inboxExpiry,
|
|
isDemoData: true,
|
|
},
|
|
update: {
|
|
portalId: portal.id,
|
|
portalUserId: customer.id,
|
|
projectId: expectedProject.id,
|
|
kind: "complaint",
|
|
status: "open",
|
|
priority: 100,
|
|
sourceId: UAT_INBOX_SOURCE_ID,
|
|
titleKey: UAT_INBOX_TITLE_KEY,
|
|
metadata: { fixture: "VA-P26" },
|
|
occurredAt: now,
|
|
lastOccurredAt: now,
|
|
bundledCount: 1,
|
|
expiresAt: inboxExpiry,
|
|
ownerUserId: null,
|
|
resolvedAt: null,
|
|
isDemoData: true,
|
|
},
|
|
});
|
|
|
|
await publishAuditEventViaOutbox(tx, {
|
|
tenantId: command.expectedTenantId,
|
|
actorId: command.operatorUserId,
|
|
actorType: "operator",
|
|
action: "customer_portal.uat_fixture.provisioned",
|
|
targetType: "Portal",
|
|
targetId: portal.id,
|
|
sourceModule: "customer-portal-uat",
|
|
outcome: "success",
|
|
dataSensitivity: "internal",
|
|
regulatoryScope: ["none"],
|
|
metadata: { tenantSlug: CUSTOMER_PORTAL_UAT_TENANT_SLUG, projectCount: 2, portalUserCount: 2 },
|
|
});
|
|
});
|
|
}
|