Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -0,0 +1,40 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import { aggregateSyncOutcome } from "./appsEngineService.server";
import type { AdapterSyncOutcome } from "@hivegrid/foundation";
// R-P5 — pure sync-aggregation: maps adapter item results to AppSyncRun counters
// and a terminal status (no DB).
const outcome = (statuses: Array<"synced" | "failed" | "skipped">): AdapterSyncOutcome => ({
summaryKey: "integrations.sync.summary.ok",
items: statuses.map((status, i) => ({ entityType: "contact", externalId: `ext-${i}`, operation: "created" as const, status })),
});
describe("aggregateSyncOutcome", () => {
it("all synced → completed", () => {
const agg = aggregateSyncOutcome(outcome(["synced", "synced"]));
expect(agg).toMatchObject({ itemsTotal: 2, itemsSucceeded: 2, itemsFailed: 0, status: "completed" });
});
it("some failed → partial", () => {
const agg = aggregateSyncOutcome(outcome(["synced", "failed"]));
expect(agg).toMatchObject({ itemsTotal: 2, itemsSucceeded: 1, itemsFailed: 1, status: "partial" });
});
it("all failed → failed", () => {
const agg = aggregateSyncOutcome(outcome(["failed", "failed"]));
expect(agg).toMatchObject({ itemsSucceeded: 0, itemsFailed: 2, status: "failed" });
});
it("empty run → completed with zero counters", () => {
const agg = aggregateSyncOutcome(outcome([]));
expect(agg).toMatchObject({ itemsTotal: 0, status: "completed" });
expect(agg.summaryKey).toBe("integrations.sync.summary.ok");
});
it("skipped items count toward total but not success/fail", () => {
const agg = aggregateSyncOutcome(outcome(["synced", "skipped"]));
expect(agg).toMatchObject({ itemsTotal: 2, itemsSucceeded: 1, itemsFailed: 0, status: "completed" });
});
});
@@ -0,0 +1,426 @@
// R-P5 (P5) §P2c — Apps-Engine domain service: DataConnection lifecycle, sync
// runs, and health monitoring. NO React/UI imports; routes/worker call these and
// build View-Models from the rows.
//
// Tenant isolation: every query is `where: { tenantId }` AND runs inside
// withTenantRLS() (RLS-ready; functional no-op until apps-engine-isolation.sql is
// activated at the P5 cutover). Credentials are stored ENVELOPE-ENCRYPTED via the
// per-tenant DEK (R-P5 Phase 1) — never plaintext, never selected into list VMs.
// Connect/sync/health route through the type-safe adapter registry (DoD #1/#2/#4).
import { CatalogError, foundationErrors, withIdempotency, type AdapterResult, type AdapterSyncOutcome } from "@hivegrid/foundation";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { db } from "~/utils/db.server";
import { createNotificationDelivery } from "@hivegrid/db/notifications.server";
import { decryptTenantField, encryptTenantField } from "@hivegrid/db/crypto/tenant-envelope.server";
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import { resolveAdapter } from "@hivegrid/integrations";
const APPS_AUDIT_MODULE = "integrations";
/** Domain error carrying an i18n message key (M002 Klartext). */
export class AppsEngineServiceError extends Error {
readonly messageKey: string;
constructor(messageKey: string) {
super(messageKey);
this.name = "AppsEngineServiceError";
this.messageKey = messageKey;
}
}
export type ConnectionStatus = "pending" | "active" | "degraded" | "broken" | "revoked";
export type SyncKind = "manual" | "scheduled" | "webhook";
export type SyncStatus = "pending" | "running" | "completed" | "partial" | "failed" | "cancelled";
/** A connection as shown in a list/detail VM — NEVER includes credentials. */
export type DataConnectionRow = {
id: string;
tenantId: string;
appId: string;
label: string;
connectionStatus: ConnectionStatus;
lastHealthCheck: Date | null;
healthMessageKey: string | null;
tokenExpiresAt: Date | null;
createdByUserId: string | null;
isDemoData: boolean;
createdAt: Date;
archivedAt: Date | null;
};
const CONNECTION_SELECT = {
id: true,
tenantId: true,
appId: true,
label: true,
connectionStatus: true,
lastHealthCheck: true,
healthMessageKey: true,
tokenExpiresAt: true,
createdByUserId: true,
isDemoData: true,
createdAt: true,
archivedAt: true,
} as const;
// --- Pure helpers (unit-tested, no DB) ------------------------------------
/** Aggregate an adapter sync outcome into AppSyncRun counters + a terminal status. */
export function aggregateSyncOutcome(outcome: AdapterSyncOutcome): {
itemsTotal: number;
itemsSucceeded: number;
itemsFailed: number;
status: "completed" | "partial" | "failed";
summaryKey: string;
} {
const itemsTotal = outcome.items.length;
const itemsFailed = outcome.items.filter((item) => item.status === "failed").length;
const itemsSucceeded = outcome.items.filter((item) => item.status === "synced").length;
const status = itemsFailed === 0 ? "completed" : itemsSucceeded === 0 ? "failed" : "partial";
return { itemsTotal, itemsSucceeded, itemsFailed, status, summaryKey: outcome.summaryKey };
}
// --- Credential crypto (envelope, per-tenant DEK) -------------------------
async function encryptCredentials(tenantId: string, credentials: Record<string, unknown>): Promise<string> {
return encryptTenantField(tenantId, JSON.stringify(credentials));
}
async function decryptCredentials(tenantId: string, ciphertext: string): Promise<Record<string, unknown>> {
return JSON.parse(await decryptTenantField(tenantId, ciphertext)) as Record<string, unknown>;
}
// --- Connection lifecycle (DoD #1/#6/#7) ----------------------------------
/** List a tenant's connections (newest first). Credentials are never selected. */
export async function listConnections(tenantId: string, opts?: { appId?: string; includeArchived?: boolean }): Promise<DataConnectionRow[]> {
const rows = await withTenantRLS(tenantId, (tx) =>
tx.dataConnection.findMany({
where: {
tenantId,
...(opts?.appId ? { appId: opts.appId } : {}),
...(opts?.includeArchived ? {} : { archivedAt: null }),
},
select: CONNECTION_SELECT,
orderBy: { createdAt: "desc" },
}),
);
return rows as DataConnectionRow[];
}
export async function getConnectionOrThrow(tenantId: string, connectionId: string): Promise<DataConnectionRow> {
const row = await withTenantRLS(tenantId, (tx) => tx.dataConnection.findFirst({ where: { id: connectionId, tenantId }, select: CONNECTION_SELECT }));
if (!row) {
throw new CatalogError(foundationErrors.notFound, { connectionId });
}
return row as DataConnectionRow;
}
export type CreateConnectionInput = {
tenantId: string;
appId: string;
label: string;
credentials: Record<string, unknown>;
createdByUserId: string;
isDemoData?: boolean;
};
/**
* Connect a new DataConnection: validate the credentials via the app's adapter,
* then store them envelope-encrypted with status `active`. Multiple connections
* per (tenant, app) are allowed (DoD #7). Validation failure surfaces the
* adapter's Klartext message (M002) without persisting.
*/
export async function createConnection(input: CreateConnectionInput): Promise<{ id: string }> {
const label = input.label.trim();
if (!label) {
throw new AppsEngineServiceError("integrations.error.labelRequired");
}
const adapter = resolveAdapter(input.appId);
if (!adapter) {
throw new AppsEngineServiceError("integrations.error.unknownApp");
}
const result = await adapter.validateConnection(input.credentials);
if (!result.ok) {
throw new AppsEngineServiceError(result.messageKey);
}
const ciphertext = await encryptCredentials(input.tenantId, input.credentials);
const created = await withTenantRLS(input.tenantId, (tx) =>
tx.dataConnection.create({
data: {
tenantId: input.tenantId,
appId: input.appId,
label,
credentialsCiphertext: ciphertext,
connectionStatus: "active",
lastHealthCheck: new Date(),
healthMessageKey: result.messageKey,
createdByUserId: input.createdByUserId,
isDemoData: input.isDemoData ?? false,
},
select: { id: true },
}),
);
await audit(input.tenantId, input.createdByUserId, "INTEGRATION_CONNECT", created.id, { appId: input.appId });
return created;
}
/** Reconnect an existing connection (same id, no history loss): re-validate +
* re-encrypt new credentials, status back to `active`. */
export async function reconnectConnection(input: { tenantId: string; connectionId: string; credentials: Record<string, unknown>; actorUserId: string }): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.dataConnection.findFirst({ where: { id: input.connectionId, tenantId: input.tenantId }, select: { id: true, appId: true } });
if (!existing) {
throw new CatalogError(foundationErrors.notFound, { connectionId: input.connectionId });
}
const adapter = resolveAdapter(existing.appId);
if (!adapter) {
throw new AppsEngineServiceError("integrations.error.unknownApp");
}
const result = await adapter.validateConnection(input.credentials);
if (!result.ok) {
throw new AppsEngineServiceError(result.messageKey);
}
const ciphertext = await encryptCredentials(input.tenantId, input.credentials);
await tx.dataConnection.updateMany({
where: { id: input.connectionId, tenantId: input.tenantId },
data: { credentialsCiphertext: ciphertext, connectionStatus: "active", lastHealthCheck: new Date(), healthMessageKey: result.messageKey, archivedAt: null },
});
});
await audit(input.tenantId, input.actorUserId, "INTEGRATION_RECONNECT", input.connectionId, {});
}
/** Disconnect: set status `revoked` (NOT hard-delete → sync history preserved). */
export async function disconnectConnection(input: { tenantId: string; connectionId: string; actorUserId: string }): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.dataConnection.findFirst({ where: { id: input.connectionId, tenantId: input.tenantId }, select: { id: true } });
if (!existing) {
throw new CatalogError(foundationErrors.notFound, { connectionId: input.connectionId });
}
// Keep the Klartext consistent with the revoked badge (A.1): without this
// the card keeps showing the stale "connection active" health message.
await tx.dataConnection.updateMany({
where: { id: input.connectionId, tenantId: input.tenantId },
data: { connectionStatus: "revoked", credentialsCiphertext: null, healthMessageKey: "integrations.health.notConnected", lastHealthCheck: new Date() },
});
});
await audit(input.tenantId, input.actorUserId, "INTEGRATION_DISCONNECT", input.connectionId, {});
}
// --- Sync (DoD #3/#8) -----------------------------------------------------
export type AppSyncRunRow = {
id: string;
tenantId: string;
dataConnectionId: string;
kind: SyncKind;
status: SyncStatus;
itemsTotal: number;
itemsSucceeded: number;
itemsFailed: number;
summaryText: string | null;
startedAt: Date | null;
completedAt: Date | null;
createdAt: Date;
};
/**
* Run a sync for a connection NOW (manual re-sync, DoD #8) or from the worker
* (scheduled/webhook). Resolves the adapter, decrypts credentials on demand,
* runs the adapter sync, and persists the AppSyncRun + items + a summary log.
* A broken connection short-circuits with a failed run.
*/
export async function runSyncForConnection(input: { tenantId: string; connectionId: string; kind?: SyncKind; createdByUserId?: string | null }): Promise<{ runId: string; status: SyncStatus }> {
return withTenantRLS(input.tenantId, async (tx) => {
const connection = await tx.dataConnection.findFirst({ where: { id: input.connectionId, tenantId: input.tenantId }, select: { id: true, appId: true, connectionStatus: true, credentialsCiphertext: true } });
if (!connection) {
throw new CatalogError(foundationErrors.notFound, { connectionId: input.connectionId });
}
const run = await tx.appSyncRun.create({
data: { tenantId: input.tenantId, dataConnectionId: input.connectionId, kind: input.kind ?? "manual", status: "running", startedAt: new Date(), createdByUserId: input.createdByUserId ?? null },
select: { id: true },
});
const adapter = resolveAdapter(connection.appId);
if (!adapter || connection.connectionStatus === "revoked" || !connection.credentialsCiphertext) {
await tx.appSyncRun.updateMany({ where: { id: run.id, tenantId: input.tenantId }, data: { status: "failed", completedAt: new Date(), summaryText: "integrations.sync.summary.notConnected" } });
await tx.appSyncRunLog.create({ data: { tenantId: input.tenantId, syncRunId: run.id, severity: "error", messageText: "integrations.sync.log.notConnected" } });
return { runId: run.id, status: "failed" as SyncStatus };
}
let outcome: AdapterSyncOutcome;
try {
const credentials = await decryptCredentials(input.tenantId, connection.credentialsCiphertext);
outcome = await adapter.sync(credentials);
} catch {
await tx.appSyncRun.updateMany({ where: { id: run.id, tenantId: input.tenantId }, data: { status: "failed", completedAt: new Date(), summaryText: "integrations.sync.summary.adapterError" } });
await tx.appSyncRunLog.create({ data: { tenantId: input.tenantId, syncRunId: run.id, severity: "error", messageText: "integrations.sync.log.adapterError" } });
return { runId: run.id, status: "failed" as SyncStatus };
}
const agg = aggregateSyncOutcome(outcome);
if (outcome.items.length > 0) {
await tx.appSyncItem.createMany({
data: outcome.items.map((item) => ({
tenantId: input.tenantId,
syncRunId: run.id,
entityType: item.entityType,
entityId: item.entityId ?? null,
externalId: item.externalId,
operation: item.operation,
status: item.status,
errorText: item.errorText ?? null,
})),
});
}
await tx.appSyncRun.updateMany({
where: { id: run.id, tenantId: input.tenantId },
data: { status: agg.status, itemsTotal: agg.itemsTotal, itemsSucceeded: agg.itemsSucceeded, itemsFailed: agg.itemsFailed, summaryText: agg.summaryKey, completedAt: new Date() },
});
await tx.appSyncRunLog.create({ data: { tenantId: input.tenantId, syncRunId: run.id, severity: agg.status === "failed" ? "error" : "success", messageText: agg.summaryKey } });
return { runId: run.id, status: agg.status };
});
}
export async function listSyncRuns(tenantId: string, connectionId: string, limit = 50): Promise<AppSyncRunRow[]> {
const rows = await withTenantRLS(tenantId, (tx) =>
tx.appSyncRun.findMany({ where: { tenantId, dataConnectionId: connectionId }, orderBy: { createdAt: "desc" }, take: Math.min(Math.max(limit, 1), 100) }),
);
return rows as AppSyncRunRow[];
}
export type AppSyncItemRowData = {
id: string;
entityType: string;
entityId: string | null;
externalId: string;
operation: "created" | "updated" | "deleted" | "skipped";
status: "pending" | "synced" | "failed" | "skipped";
errorText: string | null;
createdAt: Date;
};
export type AppSyncRunLogRowData = {
id: string;
severity: "info" | "success" | "warning" | "error";
messageText: string;
createdAt: Date;
};
export async function getSyncRunWithItems(tenantId: string, runId: string): Promise<{ run: AppSyncRunRow; items: AppSyncItemRowData[]; logs: AppSyncRunLogRowData[] }> {
return withTenantRLS(tenantId, async (tx) => {
const run = await tx.appSyncRun.findFirst({ where: { id: runId, tenantId } });
if (!run) {
throw new CatalogError(foundationErrors.notFound, { runId });
}
const [items, logs] = await Promise.all([
tx.appSyncItem.findMany({
where: { tenantId, syncRunId: runId },
select: { id: true, entityType: true, entityId: true, externalId: true, operation: true, status: true, errorText: true, createdAt: true },
orderBy: { createdAt: "asc" },
}),
tx.appSyncRunLog.findMany({
where: { tenantId, syncRunId: runId },
select: { id: true, severity: true, messageText: true, createdAt: true },
orderBy: { createdAt: "asc" },
}),
]);
return { run: run as AppSyncRunRow, items: items as AppSyncItemRowData[], logs: logs as AppSyncRunLogRowData[] };
});
}
// --- Webhook-triggered sync with storm protection (DoD #8) ----------------
/** Dedup window for inbound webhooks: identical events within this window collapse
* to a single sync (no storm). */
const WEBHOOK_DEDUP_WINDOW_MS = 60_000;
/**
* Trigger a sync from an inbound webhook, GUARDED by withIdempotency (M007) so a
* webhook storm (the same event delivered many times) runs the sync ONCE. The
* concrete per-app webhook ingest routes (P14/P15/P16) call this with a stable
* `webhookEventKey` (provider event id / signature). `replayed = true` means the
* call was deduped (a storm hit), not a fresh sync.
*/
export async function triggerWebhookSync(input: { tenantId: string; connectionId: string; webhookEventKey: string }): Promise<{ runId: string | null; status: SyncStatus | "replayed"; replayed: boolean }> {
const result = await withIdempotency(
{
scope: `integrations-webhook:${input.tenantId}:${input.connectionId}`,
key: input.webhookEventKey,
fingerprint: { connectionId: input.connectionId },
expiresAt: new Date(Date.now() + WEBHOOK_DEDUP_WINDOW_MS),
},
// db has the IdempotencyKey model; the structural cast bridges Prisma's broader
// delegate signatures to the narrow IdempotencyClient seam (M007).
db as unknown as Parameters<typeof withIdempotency>[1],
async () => {
const sync = await runSyncForConnection({ tenantId: input.tenantId, connectionId: input.connectionId, kind: "webhook" });
return { status: 200, body: { runId: sync.runId, status: sync.status } };
},
);
const body = result.body as { runId?: string; status?: SyncStatus } | undefined;
return { runId: body?.runId ?? null, status: result.replayed ? "replayed" : (body?.status ?? "pending"), replayed: result.replayed };
}
// --- Health monitoring (DoD #4) -------------------------------------------
/**
* Probe a connection's health via its adapter and persist the new status. On a
* degraded/broken transition, notify the connection owner (who holds
* integrations.connect) so they can act.
*/
export async function checkConnectionHealth(input: { tenantId: string; connectionId: string }): Promise<{ status: ConnectionStatus; messageKey: string }> {
const outcome = await withTenantRLS(input.tenantId, async (tx) => {
const connection = await tx.dataConnection.findFirst({ where: { id: input.connectionId, tenantId: input.tenantId }, select: { id: true, appId: true, connectionStatus: true, credentialsCiphertext: true, createdByUserId: true } });
if (!connection) {
throw new CatalogError(foundationErrors.notFound, { connectionId: input.connectionId });
}
const adapter = resolveAdapter(connection.appId);
let result: AdapterResult;
if (!adapter || connection.connectionStatus === "revoked" || !connection.credentialsCiphertext) {
result = { ok: false, health: "broken", messageKey: "integrations.health.notConnected" };
} else {
try {
const credentials = await decryptCredentials(input.tenantId, connection.credentialsCiphertext);
result = await adapter.healthCheck(credentials);
} catch {
result = { ok: false, health: "broken", messageKey: "integrations.health.probeFailed" };
}
}
const status: ConnectionStatus = connection.connectionStatus === "revoked" ? "revoked" : result.health;
await tx.dataConnection.updateMany({ where: { id: input.connectionId, tenantId: input.tenantId }, data: { connectionStatus: status, lastHealthCheck: new Date(), healthMessageKey: result.messageKey } });
return { status, messageKey: result.messageKey, ownerUserId: connection.createdByUserId, degradedOrBroken: status === "degraded" || status === "broken" };
});
if (outcome.degradedOrBroken && outcome.ownerUserId) {
// notify() the owner (M011 path); failure to notify must not fail the probe.
await createNotificationDelivery({
tenantId: input.tenantId,
userId: outcome.ownerUserId,
channel: "in-app",
category: "system",
messageKey: "integrations.notify.connectionUnhealthy",
status: "PENDING",
payloadMetadata: { source: APPS_AUDIT_MODULE, connectionId: input.connectionId, health: outcome.status },
}).catch(() => undefined);
}
return { status: outcome.status, messageKey: outcome.messageKey };
}
// --- Audit helper ---------------------------------------------------------
async function audit(tenantId: string, actorId: string | null, action: string, targetId: string, metadata: Record<string, unknown>): Promise<void> {
await createAuditEvent({
tenantId,
actorId,
actorType: "user",
action,
targetType: "DataConnection",
targetId,
sourceModule: APPS_AUDIT_MODULE,
outcome: "success",
metadata: metadata as never,
}).catch(() => undefined);
}
export type { TenantRlsClient };
@@ -0,0 +1,93 @@
// R-P6 (P6 CRM core, Variante A) — shared loader/action guard for CRM routes.
//
// Resolves the authenticated tenant context and the user's permission set once,
// so routes can gate consistently (mirrors taskAccess). Module-not-active handling
// differs by intent (§ "404 vs locked"):
// - GET loaders pass `requireModule: false` and render a locked/empty VM when
// `hasModule` is false.
// - Write actions pass `requireModule: true` → 404 (CatalogError.notFound) when
// the module is off, and additionally require an explicit crm.* permission.
import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo } from "~/utils/session.server";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
import { CrmServiceError, type CrmVisibilityContext } from "./crmService.server";
// The connector/entitlement feature key. The phase is called "crm", but the
// seeded/registered feature key is "crm-basic" (packages/entitlements →
// featureKeys.crmBasic). A fresh "crm" key would be unseeded, so tenantHasModule
// would always return false; "crm-basic" is the key tenants actually carry.
export const CRM_MODULE_KEY = "crm-basic";
// Owner-scope helpers live in crmService (the leaf, used by listKontakteForBrowser)
// and are re-exported here so routes can reach them from the access module.
export { canReadAllKontakte, ownerScopeWhere } from "./crmService.server";
export type { CrmVisibilityContext } from "./crmService.server";
export type CrmRouteContext = CrmVisibilityContext & {
tenantId: string;
hasModule: boolean;
};
export async function loadCrmContext({
request,
params,
requireModule = false,
}: {
request: Request;
params: Record<string, string | undefined>;
requireModule?: boolean;
}): Promise<CrmRouteContext> {
await requireAuth({ request, params });
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
if (!tenantId || !userInfo.userId) {
throw new CatalogError(foundationErrors.notFound);
}
const [hasModule, permissions] = await Promise.all([
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: CRM_MODULE_KEY }),
getPermissionsByUser(userInfo.userId, tenantId),
]);
if (requireModule && !hasModule) {
// Mutations on a disabled module look "not found" (Bauprinzip A.5.3).
throw new CatalogError(foundationErrors.notFound, { module: CRM_MODULE_KEY });
}
return { tenantId, userId: userInfo.userId, permissions, hasModule };
}
/** Require a crm.* permission; throws 404 (CatalogError.notFound) if missing. */
export function requireCrmPermission(ctx: CrmRouteContext, permission: string): CrmRouteContext {
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, permission);
return ctx;
}
/**
* Bare 404 Response for throwing from CRM loaders/actions. The body text is never
* shown to users (the route ErrorBoundary renders ServerError); the helper keeps
* call sites from inlining a hardcoded user-facing literal.
*/
export function notFoundResponse(): Response {
return new Response("Not Found", { status: 404 });
}
/** Bare 400 Response for invalid action input (same rationale as notFoundResponse). */
export function badRequestResponse(): Response {
return new Response("Bad Request", { status: 400 });
}
/**
* Map a CRM action error to a JSON Response for resource routes. CatalogError keeps
* its status + i18nKey; CrmServiceError is a 400 with its Klartext message key.
* Unknown errors are rethrown (→ 500).
*/
export function crmActionErrorResponse(error: unknown): Response {
if (error instanceof CatalogError) {
return Response.json({ error: error.i18nKey, code: error.code }, { status: error.status });
}
if (error instanceof CrmServiceError) {
return Response.json({ error: error.messageKey }, { status: 400 });
}
throw error;
}
@@ -0,0 +1,107 @@
// R-P6 (P6 CRM core, Variante A) — audit + activity wiring for the CRM module.
//
// Audit (DoD 13): every write action records a tamper-evident AuditEvent (M001)
// via createAuditEvent with the shared db client.
//
// Activity (DoD 14): user-facing timeline entries are logged against the contact.
// A private person maps to the Activity subject "contact", an organisation to
// "company". Tag / assignment / note activities reuse the EXISTING activity types
// (tag_added, tag_removed, assignee_changed, note_added). All best-effort.
import type { JsonValue } from "@hivegrid/foundation";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { logActivity, type ActivityRelatedRef, type ActivitySubjectType, type ActivityType } from "@hivegrid/activity";
import type { CrmRouteContext } from "./crmAccess.server";
import type { KontaktTyp } from "./crmService.server";
export type CrmAuditTargetType = "kontakt" | "custom_field" | "custom_field_value" | "tag" | "tag_assignment";
export type CrmAuditAction =
| "kontakt.created"
| "kontakt.updated"
| "kontakt.archived"
| "kontakt.reactivated"
| "kontakt.deleted"
| "kontakt.reassigned"
| "kontakt.email_added"
| "kontakt.email_primary_set"
| "kontakt.email_removed"
| "kontakt.telefon_added"
| "kontakt.telefon_primary_set"
| "kontakt.telefon_removed"
| "kontakt.relation_added"
| "kontakt.relation_removed"
| "kontakt.bulk_archived"
| "kontakt.bulk_reassigned"
| "custom_field.created"
| "custom_field.updated"
| "custom_field.archived"
| "custom_field_value.set"
| "custom_field.demo_seeded"
| "custom_field.demo_cleared"
| "tag.created"
| "tag.updated"
| "tag.deleted"
| "tag_assignment.assigned"
| "tag_assignment.unassigned";
export async function auditCrmEvent(input: {
ctx: Pick<CrmRouteContext, "tenantId" | "userId">;
action: CrmAuditAction;
targetType: CrmAuditTargetType;
targetId: string;
metadata?: Record<string, JsonValue>;
}): Promise<void> {
try {
await createAuditEvent({
tenantId: input.ctx.tenantId,
actorId: input.ctx.userId,
actorType: "user",
action: input.action,
targetType: input.targetType,
targetId: input.targetId,
metadata: input.metadata ?? null,
});
} catch {
// Audit must never break the user action; the failure is logged upstream.
}
}
/** Map a Kontakt type to its Activity subject (DoD 14). */
function kontaktSubjectType(kontaktTyp: KontaktTyp): ActivitySubjectType {
return kontaktTyp === "organisation" ? "company" : "contact";
}
export type KontaktActivityType = Extract<
ActivityType,
"contact_created" | "contact_updated" | "contact_archived" | "assignee_changed" | "tag_added" | "tag_removed" | "note_added"
>;
/**
* Log a contact activity. The entry hangs off the contact's own timeline; its
* subject type is derived from `kontaktTyp` (private person → contact, organisation
* → company). Best-effort.
*/
export async function logKontaktActivity(input: {
ctx: Pick<CrmRouteContext, "tenantId" | "userId">;
kontaktId: string;
kontaktTyp: KontaktTyp;
activityType: KontaktActivityType;
summaryText: string;
relatedEntityRefs?: ActivityRelatedRef[];
}): Promise<void> {
try {
await logActivity({
tenantId: input.ctx.tenantId,
actorUserId: input.ctx.userId,
actorKind: "user",
activityType: input.activityType,
subjectType: kontaktSubjectType(input.kontaktTyp),
subjectId: input.kontaktId,
summaryText: input.summaryText,
relatedEntityRefs: input.relatedEntityRefs,
});
} catch {
// Activity logging is best-effort; never break the user action.
}
}
@@ -0,0 +1,369 @@
// R-P6 (P6 CRM core, Variante A) — shared loader/action for the contact detail
// (`/contacts/:id`) and the organisation detail (`/contacts/companies/:id`).
// Both render the SAME server-built KontaktDetailVM + ActivityStreamVM and share
// the inline-edit intents (DoD 3); the only per-route difference is the back
// link / breadcrumb root. Server-only (.server) — never imported by a component.
//
// Every write intent is audited (DoD 13, via crmAudit.auditCrmEvent) and, when
// contact-relevant, appends an Activity-Stream entry (DoD 14, logKontaktActivity).
import { redirect } from "react-router";
import type { JsonValue } from "@hivegrid/foundation";
import {
buildActivityStreamVM,
buildKontaktDetailVM,
datentypLabelKey,
type ActivityStreamVM,
type KontaktDetailVM,
} from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import {
badRequestResponse,
crmActionErrorResponse,
loadCrmContext,
notFoundResponse,
requireCrmPermission,
type CrmRouteContext,
} from "./crmAccess.server";
import {
addKontaktEmail,
addKontaktRelation,
addKontaktTelefon,
archiveKontakt,
getKontaktDetail,
getVisibleKontaktOrThrow,
hardDeleteKontakt,
listAssignableUsers,
reactivateKontakt,
reassignKontakt,
removeKontaktEmail,
removeKontaktRelation,
removeKontaktTelefon,
resolveUserLabels,
setPrimaryEmail,
setPrimaryTelefon,
updateKontakt,
type KontaktArt,
type KontaktRow,
type KontaktStatus,
type OrgMerkmal,
} from "./crmService.server";
import { getCustomFieldValues, listCustomFieldDefinitions, setCustomFieldValue } from "./customFieldService.server";
import { assignTag, listTags, listTagsForEntity, unassignTag } from "./tagService.server";
import { auditCrmEvent, logKontaktActivity } from "./crmAudit.server";
import { companiesPath, contactDetailPath, contactsPath, companyDetailPath } from "./crmRoutePaths";
import { maskEmailActivitiesForViewer } from "~/modules/emailInbox/services/emailActivityMasking.server";
const KONTAKT_CUSTOM_FIELD_ENTITY = "kontakt";
const KONTAKT_TAG_ENTITY_TYPE = "kontakt";
const ACTIVITY_LIMIT = 50;
export type KontaktDetailVariant = "contacts" | "companies";
export type CustomFieldDefOption = { id: string; key: string; label: string; datentyp: string; datentypLabelKey: string };
export type KontaktDetailLoaderData = {
title: string;
variant: KontaktDetailVariant;
backHref: string;
listLabelKey: string;
detailVM: KontaktDetailVM;
activityVM: ActivityStreamVM;
allTags: { id: string; name: string; farbe: string }[];
customFieldDefs: CustomFieldDefOption[];
ownerOptions: { id: string; label: string }[];
};
type ActivityDbRow = {
id: string;
createdAt: Date;
actorUserId: string | null;
actorKind: string;
activityType: string;
summaryText: string;
metadata?: unknown;
};
async function loadKontaktActivities(tenantId: string, subjectType: "contact" | "company", subjectId: string): Promise<ActivityDbRow[]> {
// No read helper is exported from @hivegrid/activity yet — load the per-entity
// timeline tenant-scoped (RLS GUC set by withTenantRLS), newest first.
// `metadata` is selected ONLY for the email-visibility masking (VA-P23) and
// never reaches the VM.
const rows = await withTenantRLS(tenantId, (tx) =>
tx.activity.findMany({
where: { tenantId, subjectType, subjectId },
orderBy: { createdAt: "desc" },
take: ACTIVITY_LIMIT + 1,
select: { id: true, createdAt: true, actorUserId: true, actorKind: true, activityType: true, summaryText: true, metadata: true },
}),
);
return rows as ActivityDbRow[];
}
export async function loadKontaktDetailData(args: {
request: Request;
params: Record<string, string | undefined>;
variant: KontaktDetailVariant;
}): Promise<KontaktDetailLoaderData> {
const { t } = await getTranslations(args.request);
const ctx = await loadCrmContext({ request: args.request, params: args.params });
const tenantSlug = args.params.tenant ?? "";
const kontaktId = args.params.id ?? "";
if (!ctx.hasModule) {
throw notFoundResponse();
}
try {
requireCrmPermission(ctx, "crm.read_own");
} catch {
throw notFoundResponse();
}
let detail;
try {
detail = await getKontaktDetail(ctx.tenantId, kontaktId, ctx);
} catch {
throw notFoundResponse();
}
const subjectType = detail.kontakt.kontaktTyp === "organisation" ? "company" : "contact";
const [customFields, tags, definitions, allTags, ownerOptions, activityRows] = await Promise.all([
getCustomFieldValues({ tenantId: ctx.tenantId, entityType: KONTAKT_CUSTOM_FIELD_ENTITY, entityId: kontaktId }),
listTagsForEntity({ tenantId: ctx.tenantId, entityType: KONTAKT_TAG_ENTITY_TYPE, entityId: kontaktId }),
listCustomFieldDefinitions({ tenantId: ctx.tenantId, entityType: KONTAKT_CUSTOM_FIELD_ENTITY }),
listTags(ctx.tenantId),
listAssignableUsers(ctx.tenantId),
loadKontaktActivities(ctx.tenantId, subjectType, kontaktId),
]);
const actorIds = activityRows.map((row) => row.actorUserId).filter((id): id is string => Boolean(id));
const userLabels = await resolveUserLabels([detail.kontakt.zustaendigerUserId, ...actorIds].filter((id): id is string => Boolean(id)));
const detailVM = buildKontaktDetailVM({
detail: {
kontakt: detail.kontakt,
emails: detail.emails.map((e) => ({ id: e.id, email: e.email, primaer: e.primaer })),
telefone: detail.telefone.map((p) => ({ id: p.id, telefon: p.telefon, primaer: p.primaer })),
relationen: detail.relationen.map((r) => ({ id: r.id, vonKontaktId: r.vonKontaktId, zuKontaktId: r.zuKontaktId, rolle: r.rolle, kontext: r.kontext })),
adresse: detail.adresse
? { strasse: detail.adresse.strasse, hausnummer: detail.adresse.hausnummer, plz: detail.adresse.plz, ort: detail.adresse.ort, land: detail.adresse.land }
: null,
},
customFields: customFields.map((cf) => ({
definition: { id: cf.definition.id, key: cf.definition.key, label: cf.definition.label, datentyp: cf.definition.datentyp, optionen: cf.definition.optionen },
wert: cf.wert,
})),
tags: tags.map((tag) => ({ id: tag.id, name: tag.name, farbe: tag.farbe })),
userLabels,
perms: { canWrite: ctx.permissions.includes("crm.write"), canDelete: ctx.permissions.includes("crm.delete") },
tenantSlug,
});
// VA-P23 (M09 Block H): email activities are permission-masked — without
// email.read_all only the viewer's OWN mailbox activities show details.
const maskedActivityRows = await maskEmailActivitiesForViewer({
tenantId: ctx.tenantId,
userId: ctx.userId,
permissions: ctx.permissions,
rows: activityRows,
maskedText: t("emailInbox.activity.masked"),
});
const activityVM = buildActivityStreamVM({
rows: maskedActivityRows.slice(0, ACTIVITY_LIMIT).map((row) => ({
id: row.id,
createdAt: row.createdAt,
actorUserId: row.actorUserId,
actorKind: row.actorKind as never,
activityType: row.activityType as never,
summaryText: row.summaryText,
})),
userLabels,
hasMore: activityRows.length > ACTIVITY_LIMIT,
});
const backHref = args.variant === "companies" ? companiesPath(tenantSlug) : contactsPath(tenantSlug);
return {
title: `${detailVM.data?.displayName ?? t("crm.detail.title")} | ${process.env.APP_NAME}`,
variant: args.variant,
backHref,
listLabelKey: args.variant === "companies" ? "crm.companies.title" : "crm.contacts.title",
detailVM,
activityVM,
allTags: allTags.map((tag) => ({ id: tag.id, name: tag.name, farbe: tag.farbe })),
customFieldDefs: definitions.map((def) => ({
id: def.id,
key: def.key,
label: def.label,
datentyp: def.datentyp,
datentypLabelKey: datentypLabelKey(def.datentyp),
})),
ownerOptions,
};
}
function field(form: FormData, name: string): string {
return form.get(name)?.toString().trim() ?? "";
}
function optionalField(form: FormData, name: string): string | null {
const value = form.get(name)?.toString().trim();
return value ? value : null;
}
export async function handleKontaktDetailAction(args: {
request: Request;
params: Record<string, string | undefined>;
variant: KontaktDetailVariant;
}): Promise<Response> {
const ctx: CrmRouteContext = await loadCrmContext({ request: args.request, params: args.params, requireModule: true });
const tenantSlug = args.params.tenant ?? "";
const kontaktId = args.params.id ?? "";
const form = await args.request.formData();
const intent = form.get("intent")?.toString();
const detailHref = args.variant === "companies" ? companyDetailPath(tenantSlug, kontaktId) : contactDetailPath(tenantSlug, kontaktId);
const listHref = args.variant === "companies" ? companiesPath(tenantSlug) : contactsPath(tenantSlug);
try {
// Visibility + type are needed by almost every branch (activity subject).
const kontakt: KontaktRow = await getVisibleKontaktOrThrow(ctx.tenantId, kontaktId, ctx);
const typ = kontakt.kontaktTyp;
if (intent === "delete") {
requireCrmPermission(ctx, "crm.delete");
await hardDeleteKontakt({ tenantId: ctx.tenantId, kontaktId });
await auditCrmEvent({ ctx, action: "kontakt.deleted", targetType: "kontakt", targetId: kontaktId });
return redirect(listHref);
}
requireCrmPermission(ctx, "crm.write");
switch (intent) {
case "updateBasics": {
await updateKontakt({
tenantId: ctx.tenantId,
kontaktId,
kontaktStatus: (optionalField(form, "kontaktStatus") as KontaktStatus | null) ?? undefined,
vorname: form.has("vorname") ? optionalField(form, "vorname") : undefined,
nachname: form.has("nachname") ? optionalField(form, "nachname") : undefined,
orgName: form.has("orgName") ? optionalField(form, "orgName") : undefined,
orgMerkmal: form.has("orgMerkmal") ? (optionalField(form, "orgMerkmal") as OrgMerkmal | null) : undefined,
});
await auditCrmEvent({ ctx, action: "kontakt.updated", targetType: "kontakt", targetId: kontaktId });
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "Stammdaten aktualisiert" });
break;
}
case "addEmail": {
await addKontaktEmail({ tenantId: ctx.tenantId, kontaktId, email: field(form, "email"), primaer: form.get("primaer") === "1" });
await auditCrmEvent({ ctx, action: "kontakt.email_added", targetType: "kontakt", targetId: kontaktId });
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "E-Mail hinzugefügt" });
break;
}
case "setPrimaryEmail": {
await setPrimaryEmail({ tenantId: ctx.tenantId, emailId: field(form, "emailId") });
await auditCrmEvent({ ctx, action: "kontakt.email_primary_set", targetType: "kontakt", targetId: kontaktId });
break;
}
case "removeEmail": {
await removeKontaktEmail({ tenantId: ctx.tenantId, emailId: field(form, "emailId") });
await auditCrmEvent({ ctx, action: "kontakt.email_removed", targetType: "kontakt", targetId: kontaktId });
break;
}
case "addTelefon": {
await addKontaktTelefon({ tenantId: ctx.tenantId, kontaktId, telefon: field(form, "telefon"), primaer: form.get("primaer") === "1" });
await auditCrmEvent({ ctx, action: "kontakt.telefon_added", targetType: "kontakt", targetId: kontaktId });
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "Telefonnummer hinzugefügt" });
break;
}
case "setPrimaryTelefon": {
await setPrimaryTelefon({ tenantId: ctx.tenantId, telefonId: field(form, "telefonId") });
await auditCrmEvent({ ctx, action: "kontakt.telefon_primary_set", targetType: "kontakt", targetId: kontaktId });
break;
}
case "removeTelefon": {
await removeKontaktTelefon({ tenantId: ctx.tenantId, telefonId: field(form, "telefonId") });
await auditCrmEvent({ ctx, action: "kontakt.telefon_removed", targetType: "kontakt", targetId: kontaktId });
break;
}
case "addRelation": {
await addKontaktRelation({
tenantId: ctx.tenantId,
vonKontaktId: kontaktId,
zuKontaktId: field(form, "zuKontaktId"),
rolle: (field(form, "rolle") || "hauptkontakt") as KontaktArt,
kontext: optionalField(form, "kontext"),
});
await auditCrmEvent({ ctx, action: "kontakt.relation_added", targetType: "kontakt", targetId: kontaktId });
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "Verknüpfung hinzugefügt" });
break;
}
case "removeRelation": {
await removeKontaktRelation({ tenantId: ctx.tenantId, relationId: field(form, "relationId") });
await auditCrmEvent({ ctx, action: "kontakt.relation_removed", targetType: "kontakt", targetId: kontaktId });
break;
}
case "reassign": {
const owner = field(form, "zustaendigerUserId");
if (!owner) {
throw badRequestResponse();
}
await reassignKontakt({ tenantId: ctx.tenantId, kontaktId, zustaendigerUserId: owner });
await auditCrmEvent({ ctx, action: "kontakt.reassigned", targetType: "kontakt", targetId: kontaktId, metadata: { zustaendigerUserId: owner } });
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "assignee_changed", summaryText: "Verantwortlicher geändert" });
break;
}
case "addTag": {
const tagId = field(form, "tagId");
await assignTag({ tenantId: ctx.tenantId, tagId, entityType: KONTAKT_TAG_ENTITY_TYPE, entityId: kontaktId });
await auditCrmEvent({ ctx, action: "tag_assignment.assigned", targetType: "tag_assignment", targetId: kontaktId, metadata: { tagId } });
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "tag_added", summaryText: "Tag zugewiesen" });
break;
}
case "removeTag": {
const tagId = field(form, "tagId");
await unassignTag({ tenantId: ctx.tenantId, tagId, entityType: KONTAKT_TAG_ENTITY_TYPE, entityId: kontaktId });
await auditCrmEvent({ ctx, action: "tag_assignment.unassigned", targetType: "tag_assignment", targetId: kontaktId, metadata: { tagId } });
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "tag_removed", summaryText: "Tag entfernt" });
break;
}
case "setCustomField": {
const wert: JsonValue = field(form, "wert");
await setCustomFieldValue({ tenantId: ctx.tenantId, definitionId: field(form, "definitionId"), entityType: KONTAKT_CUSTOM_FIELD_ENTITY, entityId: kontaktId, wert });
await auditCrmEvent({ ctx, action: "custom_field_value.set", targetType: "custom_field_value", targetId: kontaktId, metadata: { definitionId: field(form, "definitionId") } });
break;
}
case "addNote": {
const note = field(form, "note");
if (!note) {
throw badRequestResponse();
}
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "note_added", summaryText: note });
await auditCrmEvent({ ctx, action: "kontakt.updated", targetType: "kontakt", targetId: kontaktId, metadata: { note: true } });
break;
}
case "archive": {
await archiveKontakt({ tenantId: ctx.tenantId, kontaktId });
await auditCrmEvent({ ctx, action: "kontakt.archived", targetType: "kontakt", targetId: kontaktId });
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_archived", summaryText: "Kontakt archiviert" });
break;
}
case "reactivate": {
await reactivateKontakt({ tenantId: ctx.tenantId, kontaktId });
await auditCrmEvent({ ctx, action: "kontakt.reactivated", targetType: "kontakt", targetId: kontaktId });
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "Kontakt reaktiviert" });
break;
}
default:
throw badRequestResponse();
}
return redirect(detailHref);
} catch (error) {
if (error instanceof Response) {
throw error;
}
return crmActionErrorResponse(error);
}
}
@@ -0,0 +1,271 @@
// R-P6 (P6 CRM core, Variante A) — shared loader/action for the contact and the
// organisation browser. Both `/contacts` and `/contacts/companies` render the
// SAME server-built KontaktListVM (DoD 2: filter / sort / paginate / bulk / CSV);
// the only difference is the forced `organisation` type filter and the detail
// href. Keeping the wiring here keeps the two route files thin and identical in
// behaviour. Server-only (.server) — never imported by a component.
import { redirect } from "react-router";
import { buildKontaktListVM, type KontaktListVM } from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import {
badRequestResponse,
crmActionErrorResponse,
loadCrmContext,
notFoundResponse,
requireCrmPermission,
} from "./crmAccess.server";
import {
archiveKontakt,
bulkArchiveKontakte,
bulkReassignKontakte,
getVisibleKontaktOrThrow,
listAssignableUsers,
listKontakteForBrowser,
reactivateKontakt,
resolveUserLabels,
type KontaktRow,
} from "./crmService.server";
import { assignTag, listTags, listTagsForEntity } from "./tagService.server";
import { auditCrmEvent, logKontaktActivity } from "./crmAudit.server";
import { parseKontaktListQuery, kontaktListQueryToParams, type KontaktListQuery } from "./kontaktListQuery";
import { companiesPath, companyDetailPath, contactDetailPath, contactNewPath, contactsExportPath, contactsPath } from "./crmRoutePaths";
// The canonical TagAssignment.entityType for a Kontakt (mirrors crmService).
const KONTAKT_TAG_ENTITY_TYPE = "kontakt";
export type KontaktListVariant = "contacts" | "companies";
export type KontaktTagOption = { id: string; name: string; farbe: string };
export type OwnerOption = { id: string; label: string };
export type KontaktListLoaderData = {
title: string;
moduleActive: boolean;
variant: KontaktListVariant;
vm: KontaktListVM;
tagOptions: KontaktTagOption[];
ownerOptions: OwnerOption[];
query: KontaktListQuery;
baseHref: string;
newHref: string;
exportHref: string;
};
function variantQuery(variant: KontaktListVariant, query: KontaktListQuery): KontaktListQuery {
if (variant !== "companies") {
return query;
}
// The organisation browser always pins the type filter, regardless of the URL.
return { ...query, filter: { ...query.filter, kontaktTyp: "organisation" } };
}
export async function loadKontaktListData(args: {
request: Request;
params: Record<string, string | undefined>;
variant: KontaktListVariant;
}): Promise<KontaktListLoaderData> {
const { t } = await getTranslations(args.request);
const ctx = await loadCrmContext({ request: args.request, params: args.params });
const tenantSlug = args.params.tenant ?? "";
const titleKey = args.variant === "companies" ? "crm.companies.title" : "crm.contacts.title";
const baseHref = args.variant === "companies" ? companiesPath(tenantSlug) : contactsPath(tenantSlug);
const url = new URL(args.request.url);
const query = variantQuery(args.variant, parseKontaktListQuery(url.searchParams));
const base: Omit<KontaktListLoaderData, "vm" | "tagOptions" | "ownerOptions"> = {
title: `${t(titleKey)} | ${process.env.APP_NAME}`,
moduleActive: ctx.hasModule,
variant: args.variant,
query,
baseHref,
newHref: contactNewPath(tenantSlug),
exportHref: `${contactsExportPath(tenantSlug)}?${kontaktListQueryToParams(query).toString()}`,
};
if (!ctx.hasModule) {
return { ...base, vm: buildKontaktListVM({ ...emptyVmInput(tenantSlug) }), tagOptions: [], ownerOptions: [] };
}
try {
requireCrmPermission(ctx, "crm.read_own");
} catch {
throw notFoundResponse();
}
const { rows, total, page, pageCount } = await listKontakteForBrowser({
tenantId: ctx.tenantId,
ctx,
filter: query.filter,
sort: query.sort,
page: query.page,
});
const [userLabels, tagOptions, ownerOptions] = await Promise.all([
resolveUserLabels(rows.map((row) => row.zustaendigerUserId).filter((id): id is string => Boolean(id))),
listTags(ctx.tenantId),
listAssignableUsers(ctx.tenantId),
]);
const tagsByKontakt = new Map<string, KontaktTagOption[]>();
await Promise.all(
rows.map(async (row) => {
const tags = await listTagsForEntity({ tenantId: ctx.tenantId, entityType: KONTAKT_TAG_ENTITY_TYPE, entityId: row.id });
tagsByKontakt.set(
row.id,
tags.map((tag) => ({ id: tag.id, name: tag.name, farbe: tag.farbe })),
);
}),
);
const detailHrefFor = (row: { id: string }) =>
args.variant === "companies" ? companyDetailPath(tenantSlug, row.id) : contactDetailPath(tenantSlug, row.id);
const vm = buildKontaktListVM({
rows,
userLabels,
tagsByKontakt,
pagination: { page, pageCount, total },
sort: query.sort,
filter: query.filter,
perms: {
canWrite: ctx.permissions.includes("crm.write"),
canDelete: ctx.permissions.includes("crm.delete"),
canReadAll: ctx.permissions.includes("crm.read_all"),
},
tenantSlug,
detailHrefFor,
});
return {
...base,
vm,
tagOptions: tagOptions.map((tag) => ({ id: tag.id, name: tag.name, farbe: tag.farbe })),
ownerOptions,
};
}
function emptyVmInput(tenantSlug: string) {
return {
rows: [],
userLabels: new Map<string, string>(),
tagsByKontakt: new Map<string, never[]>(),
pagination: { page: 1, pageCount: 0, total: 0 },
sort: { field: "createdAt" as const, dir: "desc" as const },
filter: {
kontaktTyp: null,
kontaktStatus: null,
zustaendigerUserId: null,
search: null,
tagIds: null,
tagMatch: "or" as const,
includeArchived: false,
},
perms: { canWrite: false, canDelete: false, canReadAll: false },
tenantSlug,
};
}
function parseIds(form: FormData): string[] {
return [...new Set(form.getAll("kontaktId").map((v) => v.toString().trim()).filter(Boolean))];
}
/** Resolve the visible target contacts for a bulk action (owner-scope enforced
* per item). Returns the rows so the activity log can pick the right subject. */
async function visibleTargets(tenantId: string, ctx: Parameters<typeof getVisibleKontaktOrThrow>[2], ids: string[]): Promise<KontaktRow[]> {
const targets: KontaktRow[] = [];
for (const id of ids) {
try {
targets.push(await getVisibleKontaktOrThrow(tenantId, id, ctx));
} catch {
// Skip contacts the caller may not touch (read_own); never fail the batch.
}
}
return targets;
}
export async function handleKontaktListAction(args: {
request: Request;
params: Record<string, string | undefined>;
variant: KontaktListVariant;
}): Promise<Response> {
const ctx = await loadCrmContext({ request: args.request, params: args.params, requireModule: true });
const tenantSlug = args.params.tenant ?? "";
const form = await args.request.formData();
const intent = form.get("intent")?.toString();
const redirectBack = redirect(args.variant === "companies" ? companiesPath(tenantSlug) : contactsPath(tenantSlug));
try {
if (intent === "archive" || intent === "reactivate") {
requireCrmPermission(ctx, "crm.write");
const kontaktId = form.get("kontaktId")?.toString().trim();
if (!kontaktId) {
throw badRequestResponse();
}
const kontakt = await getVisibleKontaktOrThrow(ctx.tenantId, kontaktId, ctx);
if (intent === "archive") {
await archiveKontakt({ tenantId: ctx.tenantId, kontaktId });
await auditCrmEvent({ ctx, action: "kontakt.archived", targetType: "kontakt", targetId: kontaktId });
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: kontakt.kontaktTyp, activityType: "contact_archived", summaryText: "Kontakt archiviert" });
} else {
await reactivateKontakt({ tenantId: ctx.tenantId, kontaktId });
await auditCrmEvent({ ctx, action: "kontakt.reactivated", targetType: "kontakt", targetId: kontaktId });
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: kontakt.kontaktTyp, activityType: "contact_updated", summaryText: "Kontakt reaktiviert" });
}
return redirectBack;
}
if (intent === "bulkArchive") {
requireCrmPermission(ctx, "crm.write");
const targets = await visibleTargets(ctx.tenantId, ctx, parseIds(form));
const ids = targets.map((t) => t.id);
if (ids.length > 0) {
await bulkArchiveKontakte({ tenantId: ctx.tenantId, ctx, kontaktIds: ids });
await auditCrmEvent({ ctx, action: "kontakt.bulk_archived", targetType: "kontakt", targetId: ids[0], metadata: { kontaktIds: ids } });
for (const target of targets) {
await logKontaktActivity({ ctx, kontaktId: target.id, kontaktTyp: target.kontaktTyp, activityType: "contact_archived", summaryText: "Kontakt archiviert (Massenaktion)" });
}
}
return redirectBack;
}
if (intent === "bulkReassign") {
requireCrmPermission(ctx, "crm.write");
const owner = form.get("zustaendigerUserId")?.toString().trim();
if (!owner) {
throw badRequestResponse();
}
const targets = await visibleTargets(ctx.tenantId, ctx, parseIds(form));
const ids = targets.map((t) => t.id);
if (ids.length > 0) {
await bulkReassignKontakte({ tenantId: ctx.tenantId, ctx, kontaktIds: ids, zustaendigerUserId: owner });
await auditCrmEvent({ ctx, action: "kontakt.bulk_reassigned", targetType: "kontakt", targetId: ids[0], metadata: { kontaktIds: ids, zustaendigerUserId: owner } });
for (const target of targets) {
await logKontaktActivity({ ctx, kontaktId: target.id, kontaktTyp: target.kontaktTyp, activityType: "assignee_changed", summaryText: "Verantwortlicher geändert (Massenaktion)" });
}
}
return redirectBack;
}
if (intent === "bulkTag") {
requireCrmPermission(ctx, "crm.write");
const tagId = form.get("tagId")?.toString().trim();
if (!tagId) {
throw badRequestResponse();
}
const targets = await visibleTargets(ctx.tenantId, ctx, parseIds(form));
for (const target of targets) {
await assignTag({ tenantId: ctx.tenantId, tagId, entityType: KONTAKT_TAG_ENTITY_TYPE, entityId: target.id });
await auditCrmEvent({ ctx, action: "tag_assignment.assigned", targetType: "tag_assignment", targetId: target.id, metadata: { tagId } });
await logKontaktActivity({ ctx, kontaktId: target.id, kontaktTyp: target.kontaktTyp, activityType: "tag_added", summaryText: "Tag zugewiesen (Massenaktion)" });
}
return redirectBack;
}
throw badRequestResponse();
} catch (error) {
if (error instanceof Response) {
throw error;
}
return crmActionErrorResponse(error);
}
}
@@ -0,0 +1,44 @@
// R-P6 (P6 CRM core, Variante A) — pure route-path builders for the typed CRM
// URLs. Loaders build these and pass them into the View-Models / route data so
// the VMs and components stay routing-agnostic. Client-safe (no server imports)
// so a route `handle` export can reference CRM_MODULE_KEY without dragging the
// server-only access guard into the client bundle.
// Tenant connector module key (the seeded entitlement key — see crmAccess.server).
export const CRM_MODULE_KEY = "crm-basic";
export function contactsPath(tenantSlug: string): string {
return `/${tenantSlug}/contacts`;
}
export function contactNewPath(tenantSlug: string): string {
return `/${tenantSlug}/contacts/new`;
}
export function contactDetailPath(tenantSlug: string, kontaktId: string): string {
return `/${tenantSlug}/contacts/${kontaktId}`;
}
export function companiesPath(tenantSlug: string): string {
return `/${tenantSlug}/contacts/companies`;
}
export function companyDetailPath(tenantSlug: string, kontaktId: string): string {
return `/${tenantSlug}/contacts/companies/${kontaktId}`;
}
export function contactsExportPath(tenantSlug: string): string {
return `/${tenantSlug}/contacts/export`;
}
export function customFieldsAdminPath(tenantSlug: string): string {
return `/${tenantSlug}/contacts/admin/custom-fields`;
}
export function tagsAdminPath(tenantSlug: string): string {
return `/${tenantSlug}/contacts/admin/tags`;
}
export function duplicatesAdminPath(tenantSlug: string): string {
return `/${tenantSlug}/contacts/admin/duplicates`;
}
@@ -0,0 +1,807 @@
// R-P6 (P6 CRM core, Variante A) — domain service for the CRM module.
//
// Pure-ish server logic for the typed CRM entities (Kontakt + address/email/phone
// channels, relations, list/filter/dup-check/bulk). Always tenant-scoped, enforces
// owner visibility (crm.read_own → 404, not 403). NO React/UI imports. Routes call
// these from their loaders/actions and build the View-Model from the returned rows.
// Audit + Activity are NOT written here — the routes wire them via crmAudit.
//
// RLS-ready (mirrors taskService / fileService): every tenant-scoped access runs
// inside withTenantRLS() so the tenant GUC is set before the query. Internal
// composition goes through *WithTx(tx, ...) helpers that reuse the active
// transaction client — functions never nest withTenantRLS(). This is a functional
// no-op until the CRM RLS policies are activated (prisma/rls/crm-isolation.sql, P5
// cutover). The only access NOT wrapped is the global User lookup
// (resolveUserLabels): User is not tenant-scoped, so it stays on the db singleton.
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { crmContactsIndex } from "@hivegrid/search";
import { publishKontaktSearchUpsert, publishSearchProjectionDelete } from "~/services/search/searchIndexProjection.server";
import { db } from "~/utils/db.server";
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
/**
* Domain error carrying an i18n message key (M002 Klartext). Routes map
* `messageKey` to a catalog error / VM error branch — never a bare HTTP code.
*/
export class CrmServiceError extends Error {
readonly messageKey: string;
constructor(messageKey: string) {
super(messageKey);
this.name = "CrmServiceError";
this.messageKey = messageKey;
}
}
// --- Domain type aliases (mirror the crm.prisma enums 1:1) -----------------
export type KontaktTyp = "privatperson" | "organisation";
export type KontaktStatus = "kontakt" | "kunde" | "bestandskunde";
export type OrgMerkmal = "gmbh" | "kg" | "oeffentliche_einrichtung" | "sonstige";
export type KontaktArt = "hauptkontakt" | "sekundaerkontakt" | "mitarbeiter" | "sonstige";
const MAX_LIST_LIMIT = 200;
const DEFAULT_LIST_LIMIT = 50;
/** Owner-visibility context (the user's permissions for this tenant). */
export type CrmVisibilityContext = {
userId: string;
/** The user's permission names for this tenant (from getPermissionsByUser). */
permissions: readonly string[];
};
/** True when the user may see every contact in the tenant (crm.read_all). */
export function canReadAllKontakte(ctx: CrmVisibilityContext): boolean {
return ctx.permissions.includes("crm.read_all");
}
/**
* Owner-scope `where` fragment for the crm.read_own filter (DoD 8). read_all users
* get an empty fragment (no restriction); everyone else only ever sees contacts
* assigned to them (`zustaendigerUserId`).
*/
export function ownerScopeWhere(ctx: CrmVisibilityContext): { zustaendigerUserId?: string } {
return canReadAllKontakte(ctx) ? {} : { zustaendigerUserId: ctx.userId };
}
// --- Row types (returned to routes; relation fields excluded) --------------
export type KontaktRow = {
id: string;
tenantId: string;
createdByUserId: string;
kontaktTyp: KontaktTyp;
kontaktStatus: KontaktStatus;
vorname: string | null;
nachname: string | null;
orgName: string | null;
orgMerkmal: OrgMerkmal | null;
primaerEmail: string | null;
primaerTelefon: string | null;
adresseId: string | null;
zustaendigerUserId: string | null;
isDemoData: boolean;
createdAt: Date;
updatedAt: Date;
archivedAt: Date | null;
};
export type KontaktEmailRow = {
id: string;
tenantId: string;
kontaktId: string;
email: string;
primaer: boolean;
createdAt: Date;
};
export type KontaktTelefonRow = {
id: string;
tenantId: string;
kontaktId: string;
telefon: string;
primaer: boolean;
createdAt: Date;
};
export type KontaktRelationRow = {
id: string;
tenantId: string;
vonKontaktId: string;
zuKontaktId: string;
rolle: KontaktArt;
kontext: string | null;
createdAt: Date;
};
export type AdresseRow = {
id: string;
tenantId: string;
strasse: string | null;
hausnummer: string | null;
plz: string | null;
ort: string | null;
land: string;
createdAt: Date;
updatedAt: Date;
};
export type AdresseInput = {
strasse?: string | null;
hausnummer?: string | null;
plz?: string | null;
ort?: string | null;
land?: string | null;
};
// --- Primary-channel helper (pure) -----------------------------------------
/**
* Pick the primary channel from an input list (DoD: exactly one primary). The
* first item flagged `primaer` wins; if none is flagged the first item is the
* primary; an empty list has no primary. Returns the denormalised primary value
* plus the per-item primary flags to persist. Pure (no DB) — used at create time.
*/
function pickPrimary<T extends { value: string; primaer?: boolean }>(items: readonly T[]): {
primaryValue: string | null;
flags: boolean[];
} {
if (items.length === 0) {
return { primaryValue: null, flags: [] };
}
let primaryIndex = items.findIndex((item) => item.primaer === true);
if (primaryIndex < 0) {
primaryIndex = 0;
}
return {
primaryValue: items[primaryIndex].value,
flags: items.map((_, index) => index === primaryIndex),
};
}
/**
* Re-derive the single primary email for a contact and sync `Kontakt.primaerEmail`.
* Runs on the active RLS tx (no own transaction). `preferredEmailId` forces that
* row to become primary (e.g. just-added / explicit set); otherwise the existing
* primary is kept, falling back to the oldest row.
*/
async function syncPrimaryEmailWithTx(tx: TenantRlsClient, tenantId: string, kontaktId: string, preferredEmailId?: string): Promise<void> {
const emails = await tx.kontaktEmail.findMany({
where: { tenantId, kontaktId },
select: { id: true, email: true, primaer: true },
orderBy: { createdAt: "asc" },
});
if (emails.length === 0) {
await tx.kontakt.updateMany({ where: { id: kontaktId, tenantId }, data: { primaerEmail: null } });
return;
}
const preferred = preferredEmailId ? emails.find((row) => row.id === preferredEmailId) : undefined;
const primary = preferred ?? emails.find((row) => row.primaer) ?? emails[0];
for (const row of emails) {
const shouldBePrimary = row.id === primary.id;
if (row.primaer !== shouldBePrimary) {
await tx.kontaktEmail.updateMany({ where: { id: row.id, tenantId }, data: { primaer: shouldBePrimary } });
}
}
await tx.kontakt.updateMany({ where: { id: kontaktId, tenantId }, data: { primaerEmail: primary.email } });
}
/** Telephone counterpart of {@link syncPrimaryEmailWithTx}. */
async function syncPrimaryTelefonWithTx(tx: TenantRlsClient, tenantId: string, kontaktId: string, preferredTelefonId?: string): Promise<void> {
const telefone = await tx.kontaktTelefon.findMany({
where: { tenantId, kontaktId },
select: { id: true, telefon: true, primaer: true },
orderBy: { createdAt: "asc" },
});
if (telefone.length === 0) {
await tx.kontakt.updateMany({ where: { id: kontaktId, tenantId }, data: { primaerTelefon: null } });
return;
}
const preferred = preferredTelefonId ? telefone.find((row) => row.id === preferredTelefonId) : undefined;
const primary = preferred ?? telefone.find((row) => row.primaer) ?? telefone[0];
for (const row of telefone) {
const shouldBePrimary = row.id === primary.id;
if (row.primaer !== shouldBePrimary) {
await tx.kontaktTelefon.updateMany({ where: { id: row.id, tenantId }, data: { primaer: shouldBePrimary } });
}
}
await tx.kontakt.updateMany({ where: { id: kontaktId, tenantId }, data: { primaerTelefon: primary.telefon } });
}
// --- Create / update / lifecycle -------------------------------------------
export type CreateKontaktInput = {
tenantId: string;
userId: string;
kontaktTyp: KontaktTyp;
kontaktStatus?: KontaktStatus;
vorname?: string | null;
nachname?: string | null;
orgName?: string | null;
orgMerkmal?: OrgMerkmal | null;
emails?: { email: string; primaer?: boolean }[];
telefone?: { telefon: string; primaer?: boolean }[];
adresse?: AdresseInput | null;
zustaendigerUserId?: string | null;
isDemoData?: boolean;
};
function validateKontaktName(input: { kontaktTyp: KontaktTyp; vorname?: string | null; nachname?: string | null; orgName?: string | null }): void {
if (input.kontaktTyp === "privatperson") {
if (!input.vorname?.trim() && !input.nachname?.trim()) {
throw new CrmServiceError("crm.error.nameRequired");
}
} else if (!input.orgName?.trim()) {
throw new CrmServiceError("crm.error.orgNameRequired");
}
}
function hasAddressData(adresse?: AdresseInput | null): boolean {
if (!adresse) {
return false;
}
return Boolean(adresse.strasse?.trim() || adresse.hausnummer?.trim() || adresse.plz?.trim() || adresse.ort?.trim() || adresse.land?.trim());
}
export async function createKontakt(input: CreateKontaktInput): Promise<KontaktRow> {
validateKontaktName(input);
const emailItems = (input.emails ?? []).map((entry) => ({ value: entry.email.trim(), primaer: entry.primaer })).filter((entry) => entry.value);
const telefonItems = (input.telefone ?? []).map((entry) => ({ value: entry.telefon.trim(), primaer: entry.primaer })).filter((entry) => entry.value);
const primaryEmail = pickPrimary(emailItems);
const primaryTelefon = pickPrimary(telefonItems);
const kontakt = await withTenantRLS(input.tenantId, async (tx) => {
let adresseId: string | null = null;
if (hasAddressData(input.adresse)) {
const adresse = await tx.adresse.create({
data: {
tenantId: input.tenantId,
strasse: input.adresse?.strasse ?? null,
hausnummer: input.adresse?.hausnummer ?? null,
plz: input.adresse?.plz ?? null,
ort: input.adresse?.ort ?? null,
land: input.adresse?.land?.trim() || "DE",
},
select: { id: true },
});
adresseId = adresse.id;
}
const created = await tx.kontakt.create({
data: {
tenantId: input.tenantId,
createdByUserId: input.userId,
kontaktTyp: input.kontaktTyp,
kontaktStatus: input.kontaktStatus ?? "kontakt",
vorname: input.vorname ?? null,
nachname: input.nachname ?? null,
orgName: input.orgName ?? null,
orgMerkmal: input.orgMerkmal ?? null,
primaerEmail: primaryEmail.primaryValue,
primaerTelefon: primaryTelefon.primaryValue,
adresseId,
zustaendigerUserId: input.zustaendigerUserId ?? input.userId,
isDemoData: input.isDemoData ?? false,
},
});
for (let i = 0; i < emailItems.length; i += 1) {
await tx.kontaktEmail.create({ data: { tenantId: input.tenantId, kontaktId: created.id, email: emailItems[i].value, primaer: primaryEmail.flags[i] } });
}
for (let i = 0; i < telefonItems.length; i += 1) {
await tx.kontaktTelefon.create({ data: { tenantId: input.tenantId, kontaktId: created.id, telefon: telefonItems[i].value, primaer: primaryTelefon.flags[i] } });
}
await publishKontaktSearchUpsert(tx, created);
return created;
});
return kontakt as KontaktRow;
}
export type UpdateKontaktInput = {
tenantId: string;
kontaktId: string;
kontaktStatus?: KontaktStatus;
vorname?: string | null;
nachname?: string | null;
orgName?: string | null;
orgMerkmal?: OrgMerkmal | null;
};
export async function updateKontakt(input: UpdateKontaktInput): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId }, select: { id: true } });
if (!existing) {
throw new CatalogError(foundationErrors.notFound, { kontaktId: input.kontaktId });
}
const updated = await tx.kontakt.update({
where: { id: existing.id },
data: {
...(input.kontaktStatus !== undefined ? { kontaktStatus: input.kontaktStatus } : {}),
...(input.vorname !== undefined ? { vorname: input.vorname } : {}),
...(input.nachname !== undefined ? { nachname: input.nachname } : {}),
...(input.orgName !== undefined ? { orgName: input.orgName } : {}),
...(input.orgMerkmal !== undefined ? { orgMerkmal: input.orgMerkmal } : {}),
},
});
await publishKontaktSearchUpsert(tx, updated);
});
}
export async function archiveKontakt(input: { tenantId: string; kontaktId: string }): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const kontakt = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId }, select: { id: true, kontaktTyp: true } });
if (!kontakt) {
throw new CatalogError(foundationErrors.notFound, { kontaktId: input.kontaktId });
}
await tx.kontakt.update({ where: { id: kontakt.id }, data: { archivedAt: new Date() } });
await publishSearchProjectionDelete(tx, {
schema: crmContactsIndex,
tenantId: input.tenantId,
entityType: kontakt.kontaktTyp === "organisation" ? "company" : "contact",
entityId: kontakt.id,
});
});
}
export async function reactivateKontakt(input: { tenantId: string; kontaktId: string }): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId }, select: { id: true } });
if (!existing) {
throw new CatalogError(foundationErrors.notFound, { kontaktId: input.kontaktId });
}
const updated = await tx.kontakt.update({ where: { id: existing.id }, data: { archivedAt: null } });
await publishKontaktSearchUpsert(tx, updated);
});
}
export async function hardDeleteKontakt(input: { tenantId: string; kontaktId: string }): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const kontakt = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId }, select: { id: true, kontaktTyp: true } });
if (!kontakt) {
throw new CatalogError(foundationErrors.notFound, { kontaktId: input.kontaktId });
}
// KontaktEmail / KontaktTelefon / KontaktRelation cascade on Kontakt delete
// (schema onDelete: Cascade). The reusable Adresse stays (it may be shared).
await tx.kontakt.delete({ where: { id: kontakt.id } });
await publishSearchProjectionDelete(tx, {
schema: crmContactsIndex,
tenantId: input.tenantId,
entityType: kontakt.kontaktTyp === "organisation" ? "company" : "contact",
entityId: kontakt.id,
});
});
}
export async function reassignKontakt(input: { tenantId: string; kontaktId: string; zustaendigerUserId: string }): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId }, select: { id: true } });
if (!existing) {
throw new CatalogError(foundationErrors.notFound, { kontaktId: input.kontaktId });
}
const updated = await tx.kontakt.update({ where: { id: existing.id }, data: { zustaendigerUserId: input.zustaendigerUserId } });
await publishKontaktSearchUpsert(tx, updated);
});
}
// --- Email channels --------------------------------------------------------
export async function addKontaktEmail(input: { tenantId: string; kontaktId: string; email: string; primaer?: boolean }): Promise<KontaktEmailRow> {
const email = input.email.trim();
if (!email) {
throw new CrmServiceError("crm.error.emailRequired");
}
return withTenantRLS(input.tenantId, async (tx) => {
const kontakt = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId }, select: { id: true } });
if (!kontakt) {
throw new CatalogError(foundationErrors.notFound, { kontaktId: input.kontaktId });
}
const created = await tx.kontaktEmail.create({ data: { tenantId: input.tenantId, kontaktId: input.kontaktId, email, primaer: false } });
await syncPrimaryEmailWithTx(tx, input.tenantId, input.kontaktId, input.primaer ? created.id : undefined);
const updated = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId } });
if (updated) await publishKontaktSearchUpsert(tx, updated);
return created as KontaktEmailRow;
});
}
export async function setPrimaryEmail(input: { tenantId: string; emailId: string }): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const email = await tx.kontaktEmail.findFirst({ where: { id: input.emailId, tenantId: input.tenantId }, select: { id: true, kontaktId: true } });
if (!email) {
throw new CatalogError(foundationErrors.notFound, { emailId: input.emailId });
}
await syncPrimaryEmailWithTx(tx, input.tenantId, email.kontaktId, email.id);
const updated = await tx.kontakt.findFirst({ where: { id: email.kontaktId, tenantId: input.tenantId } });
if (updated) await publishKontaktSearchUpsert(tx, updated);
});
}
export async function removeKontaktEmail(input: { tenantId: string; emailId: string }): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const email = await tx.kontaktEmail.findFirst({ where: { id: input.emailId, tenantId: input.tenantId }, select: { id: true, kontaktId: true } });
if (!email) {
throw new CatalogError(foundationErrors.notFound, { emailId: input.emailId });
}
await tx.kontaktEmail.deleteMany({ where: { id: input.emailId, tenantId: input.tenantId } });
await syncPrimaryEmailWithTx(tx, input.tenantId, email.kontaktId);
const updated = await tx.kontakt.findFirst({ where: { id: email.kontaktId, tenantId: input.tenantId } });
if (updated) await publishKontaktSearchUpsert(tx, updated);
});
}
// --- Telephone channels ----------------------------------------------------
export async function addKontaktTelefon(input: { tenantId: string; kontaktId: string; telefon: string; primaer?: boolean }): Promise<KontaktTelefonRow> {
const telefon = input.telefon.trim();
if (!telefon) {
throw new CrmServiceError("crm.error.telefonRequired");
}
return withTenantRLS(input.tenantId, async (tx) => {
const kontakt = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId }, select: { id: true } });
if (!kontakt) {
throw new CatalogError(foundationErrors.notFound, { kontaktId: input.kontaktId });
}
const created = await tx.kontaktTelefon.create({ data: { tenantId: input.tenantId, kontaktId: input.kontaktId, telefon, primaer: false } });
await syncPrimaryTelefonWithTx(tx, input.tenantId, input.kontaktId, input.primaer ? created.id : undefined);
const updated = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId } });
if (updated) await publishKontaktSearchUpsert(tx, updated);
return created as KontaktTelefonRow;
});
}
export async function setPrimaryTelefon(input: { tenantId: string; telefonId: string }): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const telefon = await tx.kontaktTelefon.findFirst({ where: { id: input.telefonId, tenantId: input.tenantId }, select: { id: true, kontaktId: true } });
if (!telefon) {
throw new CatalogError(foundationErrors.notFound, { telefonId: input.telefonId });
}
await syncPrimaryTelefonWithTx(tx, input.tenantId, telefon.kontaktId, telefon.id);
const updated = await tx.kontakt.findFirst({ where: { id: telefon.kontaktId, tenantId: input.tenantId } });
if (updated) await publishKontaktSearchUpsert(tx, updated);
});
}
export async function removeKontaktTelefon(input: { tenantId: string; telefonId: string }): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const telefon = await tx.kontaktTelefon.findFirst({ where: { id: input.telefonId, tenantId: input.tenantId }, select: { id: true, kontaktId: true } });
if (!telefon) {
throw new CatalogError(foundationErrors.notFound, { telefonId: input.telefonId });
}
await tx.kontaktTelefon.deleteMany({ where: { id: input.telefonId, tenantId: input.tenantId } });
await syncPrimaryTelefonWithTx(tx, input.tenantId, telefon.kontaktId);
const updated = await tx.kontakt.findFirst({ where: { id: telefon.kontaktId, tenantId: input.tenantId } });
if (updated) await publishKontaktSearchUpsert(tx, updated);
});
}
// --- Relations -------------------------------------------------------------
export async function addKontaktRelation(input: { tenantId: string; vonKontaktId: string; zuKontaktId: string; rolle: KontaktArt; kontext?: string | null }): Promise<KontaktRelationRow> {
if (input.vonKontaktId === input.zuKontaktId) {
throw new CrmServiceError("crm.error.selfRelation");
}
return withTenantRLS(input.tenantId, async (tx) => {
const endpoints = await tx.kontakt.findMany({ where: { id: { in: [input.vonKontaktId, input.zuKontaktId] }, tenantId: input.tenantId }, select: { id: true } });
if (endpoints.length !== 2) {
throw new CatalogError(foundationErrors.notFound, { vonKontaktId: input.vonKontaktId, zuKontaktId: input.zuKontaktId });
}
try {
const created = await tx.kontaktRelation.create({
data: { tenantId: input.tenantId, vonKontaktId: input.vonKontaktId, zuKontaktId: input.zuKontaktId, rolle: input.rolle, kontext: input.kontext ?? null },
});
return created as KontaktRelationRow;
} catch (error) {
if (isUniqueConstraintError(error)) {
throw new CrmServiceError("crm.error.relationExists");
}
throw error;
}
});
}
export async function removeKontaktRelation(input: { tenantId: string; relationId: string }): Promise<void> {
await withTenantRLS(input.tenantId, (tx) => tx.kontaktRelation.deleteMany({ where: { id: input.relationId, tenantId: input.tenantId } }));
}
/** All relations touching a contact, in both directions (von/zu). */
export async function listRelationsForKontakt(tenantId: string, kontaktId: string): Promise<KontaktRelationRow[]> {
const rows = await withTenantRLS(tenantId, (tx) =>
tx.kontaktRelation.findMany({
where: { tenantId, OR: [{ vonKontaktId: kontaktId }, { zuKontaktId: kontaktId }] },
orderBy: { createdAt: "asc" },
}),
);
return rows as KontaktRelationRow[];
}
// --- Visibility / read -----------------------------------------------------
function isKontaktVisible(kontakt: Pick<KontaktRow, "createdByUserId" | "zustaendigerUserId">, ctx: CrmVisibilityContext): boolean {
return canReadAllKontakte(ctx) || kontakt.zustaendigerUserId === ctx.userId || kontakt.createdByUserId === ctx.userId;
}
async function getVisibleKontaktOrThrowWithTx(tx: TenantRlsClient, tenantId: string, kontaktId: string, ctx: CrmVisibilityContext): Promise<KontaktRow> {
const kontakt = await tx.kontakt.findFirst({ where: { id: kontaktId, tenantId } });
if (!kontakt || !isKontaktVisible(kontakt as KontaktRow, ctx)) {
throw new CatalogError(foundationErrors.notFound, { kontaktId });
}
return kontakt as KontaktRow;
}
/** Load a single contact (tenant-scoped) and enforce owner visibility, else 404. */
export async function getVisibleKontaktOrThrow(tenantId: string, kontaktId: string, ctx: CrmVisibilityContext): Promise<KontaktRow> {
return withTenantRLS(tenantId, (tx) => getVisibleKontaktOrThrowWithTx(tx, tenantId, kontaktId, ctx));
}
export type KontaktDetail = {
kontakt: KontaktRow;
emails: KontaktEmailRow[];
telefone: KontaktTelefonRow[];
relationen: KontaktRelationRow[];
adresse: AdresseRow | null;
};
/** Load a contact with its channels, relations and address (visibility-checked). */
export async function getKontaktDetail(tenantId: string, kontaktId: string, ctx: CrmVisibilityContext): Promise<KontaktDetail> {
return withTenantRLS(tenantId, async (tx) => {
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, tenantId, kontaktId, ctx);
const [emails, telefone, relationen, adresse] = await Promise.all([
tx.kontaktEmail.findMany({ where: { tenantId, kontaktId }, orderBy: { createdAt: "asc" } }),
tx.kontaktTelefon.findMany({ where: { tenantId, kontaktId }, orderBy: { createdAt: "asc" } }),
tx.kontaktRelation.findMany({ where: { tenantId, OR: [{ vonKontaktId: kontaktId }, { zuKontaktId: kontaktId }] }, orderBy: { createdAt: "asc" } }),
kontakt.adresseId ? tx.adresse.findFirst({ where: { id: kontakt.adresseId, tenantId } }) : Promise.resolve(null),
]);
return {
kontakt,
emails: emails as KontaktEmailRow[],
telefone: telefone as KontaktTelefonRow[],
relationen: relationen as KontaktRelationRow[],
adresse: (adresse as AdresseRow | null) ?? null,
};
});
}
// --- List / filter / sort / paginate (server-side, DoD 2) ------------------
export type KontaktSortField = "name" | "createdAt" | "kontaktStatus";
export type SortDir = "asc" | "desc";
export type ListKontakteFilter = {
kontaktTyp?: KontaktTyp | null;
kontaktStatus?: KontaktStatus | null;
zustaendigerUserId?: string | null;
search?: string | null;
tagIds?: string[] | null;
tagMatch?: "and" | "or";
includeArchived?: boolean;
includeDemoData?: boolean;
};
export type ListKontakteSort = { field: KontaktSortField; dir: SortDir };
// Tags on Kontakte are stored with TagAssignment.entityType === "kontakt"
// (the canonical string for this entity, mirroring CustomFieldEntityType).
const KONTAKT_TAG_ENTITY_TYPE = "kontakt";
function buildOrderBy(sort?: ListKontakteSort): Record<string, SortDir> | Array<Record<string, SortDir>> {
if (!sort) {
return { createdAt: "desc" };
}
if (sort.field === "name") {
return [{ nachname: sort.dir }, { vorname: sort.dir }, { orgName: sort.dir }];
}
if (sort.field === "kontaktStatus") {
return { kontaktStatus: sort.dir };
}
return { createdAt: sort.dir };
}
/**
* Build the tenant-scoped, owner-filtered, tag/search-filtered `where` for the
* contact browser. Returns `{ where, empty }`; `empty` short-circuits to a 0-row
* result when a tag filter matched no contacts (avoids an `id IN ()` query).
*/
async function resolveKontaktBrowserWhereWithTx(
tx: TenantRlsClient,
tenantId: string,
ctx: CrmVisibilityContext,
filter: ListKontakteFilter,
): Promise<{ where: Record<string, unknown>; empty: boolean }> {
const search = filter.search?.trim();
let tagScopedIds: string[] | undefined;
if (filter.tagIds && filter.tagIds.length > 0) {
const assignments = await tx.tagAssignment.findMany({
where: { tenantId, entityType: KONTAKT_TAG_ENTITY_TYPE, tagId: { in: filter.tagIds } },
select: { entityId: true, tagId: true },
});
if (filter.tagMatch === "and") {
const byEntity = new Map<string, Set<string>>();
for (const row of assignments) {
const set = byEntity.get(row.entityId) ?? new Set<string>();
set.add(row.tagId);
byEntity.set(row.entityId, set);
}
const required = new Set(filter.tagIds);
tagScopedIds = [...byEntity.entries()].filter(([, tags]) => [...required].every((tag) => tags.has(tag))).map(([entityId]) => entityId);
} else {
tagScopedIds = [...new Set(assignments.map((row) => row.entityId))];
}
if (tagScopedIds.length === 0) {
return { where: {}, empty: true };
}
}
const where = {
tenantId,
...ownerScopeWhere(ctx),
...(filter.includeArchived ? {} : { archivedAt: null }),
...(filter.includeDemoData ? {} : { isDemoData: false }),
...(filter.kontaktTyp ? { kontaktTyp: filter.kontaktTyp } : {}),
...(filter.kontaktStatus ? { kontaktStatus: filter.kontaktStatus } : {}),
...(filter.zustaendigerUserId ? { zustaendigerUserId: filter.zustaendigerUserId } : {}),
...(tagScopedIds ? { id: { in: tagScopedIds } } : {}),
...(search
? {
OR: [
{ vorname: { contains: search, mode: "insensitive" as const } },
{ nachname: { contains: search, mode: "insensitive" as const } },
{ orgName: { contains: search, mode: "insensitive" as const } },
{ primaerEmail: { contains: search, mode: "insensitive" as const } },
],
}
: {}),
};
return { where, empty: false };
}
export async function listKontakteForBrowser(input: {
tenantId: string;
ctx: CrmVisibilityContext;
filter?: ListKontakteFilter;
sort?: ListKontakteSort;
page?: number;
limit?: number;
}): Promise<{ rows: KontaktRow[]; total: number; page: number; pageCount: number }> {
const limit = Math.min(Math.max(input.limit ?? DEFAULT_LIST_LIMIT, 1), MAX_LIST_LIMIT);
const page = Math.max(input.page ?? 1, 1);
const filter = input.filter ?? {};
return withTenantRLS(input.tenantId, async (tx) => {
const { where, empty } = await resolveKontaktBrowserWhereWithTx(tx, input.tenantId, input.ctx, filter);
if (empty) {
return { rows: [], total: 0, page, pageCount: 0 };
}
const [rows, total] = await Promise.all([
tx.kontakt.findMany({ where, orderBy: buildOrderBy(input.sort), skip: (page - 1) * limit, take: limit }),
tx.kontakt.count({ where }),
]);
return { rows: rows as KontaktRow[], total, page, pageCount: Math.ceil(total / limit) };
});
}
/** All contacts matching the same browser filter, unpaginated, for CSV export
* (DoD 2). The CSV string itself is built in the route / a pure util. */
export async function listKontakteForCsv(input: { tenantId: string; ctx: CrmVisibilityContext; filter?: ListKontakteFilter; sort?: ListKontakteSort }): Promise<KontaktRow[]> {
const filter = input.filter ?? {};
return withTenantRLS(input.tenantId, async (tx) => {
const { where, empty } = await resolveKontaktBrowserWhereWithTx(tx, input.tenantId, input.ctx, filter);
if (empty) {
return [];
}
const rows = await tx.kontakt.findMany({ where, orderBy: buildOrderBy(input.sort) });
return rows as KontaktRow[];
});
}
// --- Duplicate detection (DoD 4) -------------------------------------------
export type DuplicateCheckInput = {
tenantId: string;
email?: string | null;
telefon?: string | null;
vorname?: string | null;
nachname?: string | null;
orgName?: string | null;
excludeKontaktId?: string | null;
};
/**
* Find potential duplicate contacts (tenant-scoped, non-archived). `hard` = exact
* channel match (primary or any email/phone row); `soft` = name match only
* (excluding hard hits). The contact identified by `excludeKontaktId` is omitted.
*/
export async function findDuplicateKontakte(input: DuplicateCheckInput): Promise<{ hard: KontaktRow[]; soft: KontaktRow[] }> {
const email = input.email?.trim();
const telefon = input.telefon?.trim();
const vorname = input.vorname?.trim();
const nachname = input.nachname?.trim();
const orgName = input.orgName?.trim();
const hardConds: Record<string, unknown>[] = [];
if (email) {
hardConds.push({ primaerEmail: { equals: email, mode: "insensitive" as const } }, { emails: { some: { email: { equals: email, mode: "insensitive" as const } } } });
}
if (telefon) {
hardConds.push({ primaerTelefon: telefon }, { telefone: { some: { telefon } } });
}
const softConds: Record<string, unknown>[] = [];
if (vorname && nachname) {
softConds.push({ AND: [{ vorname: { equals: vorname, mode: "insensitive" as const } }, { nachname: { equals: nachname, mode: "insensitive" as const } }] });
}
if (orgName) {
softConds.push({ orgName: { equals: orgName, mode: "insensitive" as const } });
}
if (hardConds.length === 0 && softConds.length === 0) {
return { hard: [], soft: [] };
}
const excludeId = input.excludeKontaktId ?? undefined;
return withTenantRLS(input.tenantId, async (tx) => {
const base = { tenantId: input.tenantId, archivedAt: null, ...(excludeId ? { id: { not: excludeId } } : {}) };
const hard = hardConds.length > 0 ? await tx.kontakt.findMany({ where: { ...base, OR: hardConds }, orderBy: { createdAt: "desc" } }) : [];
const hardIds = new Set(hard.map((row) => row.id));
const softRaw = softConds.length > 0 ? await tx.kontakt.findMany({ where: { ...base, OR: softConds }, orderBy: { createdAt: "desc" } }) : [];
const soft = softRaw.filter((row) => !hardIds.has(row.id));
return { hard: hard as KontaktRow[], soft: soft as KontaktRow[] };
});
}
// --- Bulk actions (DoD 2) --------------------------------------------------
/** Archive many contacts; only contacts inside the caller's owner-scope are
* affected (read_own may not touch others'). Returns the number affected. */
export async function bulkArchiveKontakte(input: { tenantId: string; ctx: CrmVisibilityContext; kontaktIds: string[] }): Promise<{ affected: number }> {
if (input.kontaktIds.length === 0) {
return { affected: 0 };
}
const result = await withTenantRLS(input.tenantId, (tx) =>
tx.kontakt.updateMany({ where: { id: { in: input.kontaktIds }, tenantId: input.tenantId, ...ownerScopeWhere(input.ctx) }, data: { archivedAt: new Date() } }),
);
return { affected: result.count };
}
/** Reassign many contacts; owner-scoped like {@link bulkArchiveKontakte}. */
export async function bulkReassignKontakte(input: { tenantId: string; ctx: CrmVisibilityContext; kontaktIds: string[]; zustaendigerUserId: string }): Promise<{ affected: number }> {
if (input.kontaktIds.length === 0) {
return { affected: 0 };
}
const result = await withTenantRLS(input.tenantId, (tx) =>
tx.kontakt.updateMany({ where: { id: { in: input.kontaktIds }, tenantId: input.tenantId, ...ownerScopeWhere(input.ctx) }, data: { zustaendigerUserId: input.zustaendigerUserId } }),
);
return { affected: result.count };
}
// --- Directory helpers (zustaendigerUser display + picker) -----------------
export type LabeledOption = { id: string; label: string };
function userLabel(user: { firstName: string; lastName: string; email: string }): string {
const name = `${user.firstName} ${user.lastName}`.trim();
return name || user.email;
}
/** Resolve display labels for a set of user ids (global user table). */
export async function resolveUserLabels(userIds: readonly string[]): Promise<Map<string, string>> {
const ids = [...new Set(userIds)].filter(Boolean);
if (ids.length === 0) {
return new Map();
}
const users = await db.user.findMany({ where: { id: { in: ids } }, select: { id: true, firstName: true, lastName: true, email: true } });
return new Map(users.map((user) => [user.id, userLabel(user)]));
}
/** Tenant members as zustaendigerUser picker options (id + display label). */
export async function listAssignableUsers(tenantId: string): Promise<LabeledOption[]> {
const members = await withTenantRLS(tenantId, (tx) =>
tx.tenantUser.findMany({ where: { tenantId }, select: { user: { select: { id: true, firstName: true, lastName: true, email: true } } } }),
);
return members.filter((member) => member.user).map((member) => ({ id: member.user.id, label: userLabel(member.user) }));
}
// --- internal --------------------------------------------------------------
function isUniqueConstraintError(error: unknown): boolean {
return Boolean(error && typeof error === "object" && "code" in error && (error as { code?: unknown }).code === "P2002");
}
@@ -0,0 +1,236 @@
// R-P6 (P6 CRM core, Variante A) — tenant custom-field service.
//
// Definitions (CustomFieldDefinition) describe a polymorphic field per entity
// type; values (CustomFieldValue) hold the concrete data for a single entity.
// `entityId` carries NO DB foreign key — this service validates the entityType
// match. Always tenant-scoped via withTenantRLS. NO React/UI imports. Audit +
// Activity are wired by the routes (crmAudit), not here.
import { Prisma } from "@hivegrid/db/prisma-browser";
import { CatalogError, foundationErrors, type JsonValue } from "@hivegrid/foundation";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { CrmServiceError } from "./crmService.server";
export type CustomFieldEntityType = "projekt" | "kontakt" | "lead" | "rechnung";
export type CustomFieldDatentyp =
| "text"
| "textarea"
| "zahl"
| "waehrung"
| "datum"
| "datum_range"
| "select"
| "multiselect"
| "boolean"
| "email"
| "telefon"
| "datei";
export type CustomFieldDefinitionRow = {
id: string;
tenantId: string;
entityType: CustomFieldEntityType;
key: string;
label: string;
datentyp: CustomFieldDatentyp;
optionen: JsonValue | null;
archiviert: boolean;
isDemoData: boolean;
createdAt: Date;
};
export type CustomFieldValueRow = {
id: string;
tenantId: string;
definitionId: string;
entityType: CustomFieldEntityType;
entityId: string;
wert: JsonValue | null;
createdAt: Date;
updatedAt: Date;
};
function toJsonInput(value: JsonValue | null | undefined): Prisma.InputJsonValue | typeof Prisma.JsonNull {
return value === null || value === undefined ? Prisma.JsonNull : (value as Prisma.InputJsonValue);
}
// --- Definitions -----------------------------------------------------------
export async function createCustomFieldDefinition(input: {
tenantId: string;
entityType: CustomFieldEntityType;
key: string;
label: string;
datentyp: CustomFieldDatentyp;
optionen?: JsonValue | null;
isDemoData?: boolean;
}): Promise<CustomFieldDefinitionRow> {
const key = input.key.trim();
const label = input.label.trim();
if (!key) {
throw new CrmServiceError("crm.error.fieldKeyRequired");
}
if (!label) {
throw new CrmServiceError("crm.error.fieldLabelRequired");
}
try {
const created = await withTenantRLS(input.tenantId, (tx) =>
tx.customFieldDefinition.create({
data: {
tenantId: input.tenantId,
entityType: input.entityType,
key,
label,
datentyp: input.datentyp,
optionen: toJsonInput(input.optionen),
isDemoData: input.isDemoData ?? false,
},
}),
);
return created as CustomFieldDefinitionRow;
} catch (error) {
if (isUniqueConstraintError(error)) {
throw new CrmServiceError("crm.error.fieldKeyExists");
}
throw error;
}
}
export async function updateCustomFieldDefinition(input: {
tenantId: string;
definitionId: string;
label?: string;
optionen?: JsonValue | null;
archiviert?: boolean;
}): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.customFieldDefinition.findFirst({ where: { id: input.definitionId, tenantId: input.tenantId }, select: { id: true } });
if (!existing) {
throw new CatalogError(foundationErrors.notFound, { definitionId: input.definitionId });
}
await tx.customFieldDefinition.updateMany({
where: { id: input.definitionId, tenantId: input.tenantId },
data: {
...(input.label !== undefined ? { label: input.label.trim() } : {}),
...(input.optionen !== undefined ? { optionen: toJsonInput(input.optionen) } : {}),
...(input.archiviert !== undefined ? { archiviert: input.archiviert } : {}),
},
});
});
}
export async function archiveCustomFieldDefinition(input: { tenantId: string; definitionId: string }): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.customFieldDefinition.findFirst({ where: { id: input.definitionId, tenantId: input.tenantId }, select: { id: true } });
if (!existing) {
throw new CatalogError(foundationErrors.notFound, { definitionId: input.definitionId });
}
await tx.customFieldDefinition.updateMany({ where: { id: input.definitionId, tenantId: input.tenantId }, data: { archiviert: true } });
});
}
export async function listCustomFieldDefinitions(input: { tenantId: string; entityType: CustomFieldEntityType; includeArchived?: boolean }): Promise<CustomFieldDefinitionRow[]> {
const rows = await withTenantRLS(input.tenantId, (tx) =>
tx.customFieldDefinition.findMany({
where: { tenantId: input.tenantId, entityType: input.entityType, ...(input.includeArchived ? {} : { archiviert: false }) },
orderBy: { createdAt: "asc" },
}),
);
return rows as CustomFieldDefinitionRow[];
}
// --- Values ----------------------------------------------------------------
export async function setCustomFieldValue(input: {
tenantId: string;
definitionId: string;
entityType: CustomFieldEntityType;
entityId: string;
wert: JsonValue | null;
}): Promise<CustomFieldValueRow> {
return withTenantRLS(input.tenantId, async (tx) => {
const definition = await tx.customFieldDefinition.findFirst({ where: { id: input.definitionId, tenantId: input.tenantId }, select: { entityType: true } });
if (!definition) {
throw new CatalogError(foundationErrors.notFound, { definitionId: input.definitionId });
}
if (definition.entityType !== input.entityType) {
throw new CrmServiceError("crm.error.entityTypeMismatch");
}
const value = await tx.customFieldValue.upsert({
where: { definitionId_entityId: { definitionId: input.definitionId, entityId: input.entityId } },
update: { wert: toJsonInput(input.wert) },
create: { tenantId: input.tenantId, definitionId: input.definitionId, entityType: input.entityType, entityId: input.entityId, wert: toJsonInput(input.wert) },
});
return value as CustomFieldValueRow;
});
}
export type CustomFieldValueWithDefinition = { definition: CustomFieldDefinitionRow; wert: JsonValue | null };
export async function getCustomFieldValues(input: { tenantId: string; entityType: CustomFieldEntityType; entityId: string }): Promise<CustomFieldValueWithDefinition[]> {
const rows = await withTenantRLS(input.tenantId, (tx) =>
tx.customFieldValue.findMany({ where: { tenantId: input.tenantId, entityType: input.entityType, entityId: input.entityId }, include: { definition: true }, orderBy: { createdAt: "asc" } }),
);
return rows.map((row) => ({ definition: row.definition as CustomFieldDefinitionRow, wert: (row.wert as JsonValue | null) ?? null }));
}
// --- SHK demo-seed mechanism (DoD 6) ---------------------------------------
export type ShkCustomFieldTemplateEntry = {
entityType: CustomFieldEntityType;
key: string;
label: string;
datentyp: CustomFieldDatentyp;
optionen?: JsonValue;
};
/**
* SHK (Sanitär-Heizung-Klima) custom-field template. Filled with Geerkens later
* (E3). The seeding mechanism below is complete; the template is intentionally
* empty so no SHK fields are invented before the domain workshop.
*/
export const SHK_CUSTOM_FIELD_TEMPLATE: ReadonlyArray<ShkCustomFieldTemplateEntry> = [];
/**
* Idempotently create the SHK template fields for a tenant as demo data
* (`isDemoData = true`). Existing fields with the same (tenant, entityType, key)
* are skipped. With the empty template this is a no-op that returns 0.
*/
export async function seedShkCustomFieldTemplate(input: { tenantId: string }): Promise<{ created: number }> {
let created = 0;
for (const entry of SHK_CUSTOM_FIELD_TEMPLATE) {
const exists = await withTenantRLS(input.tenantId, (tx) =>
tx.customFieldDefinition.findFirst({ where: { tenantId: input.tenantId, entityType: entry.entityType, key: entry.key }, select: { id: true } }),
);
if (exists) {
continue;
}
await withTenantRLS(input.tenantId, (tx) =>
tx.customFieldDefinition.create({
data: {
tenantId: input.tenantId,
entityType: entry.entityType,
key: entry.key,
label: entry.label,
datentyp: entry.datentyp,
optionen: toJsonInput(entry.optionen ?? null),
isDemoData: true,
},
}),
);
created += 1;
}
return { created };
}
/** Bulk-remove demo custom-field definitions on the production switch-over. */
export async function clearDemoCustomFields(input: { tenantId: string }): Promise<{ deleted: number }> {
const result = await withTenantRLS(input.tenantId, (tx) => tx.customFieldDefinition.deleteMany({ where: { tenantId: input.tenantId, isDemoData: true } }));
return { deleted: result.count };
}
// --- internal --------------------------------------------------------------
function isUniqueConstraintError(error: unknown): boolean {
return Boolean(error && typeof error === "object" && "code" in error && (error as { code?: unknown }).code === "P2002");
}
@@ -0,0 +1,67 @@
import { describe, expect, it } from "vitest";
import { kontaktListQueryToParams, parseKontaktListQuery } from "./kontaktListQuery";
describe("parseKontaktListQuery", () => {
it("falls back to safe defaults on an empty query", () => {
const query = parseKontaktListQuery(new URLSearchParams());
expect(query).toEqual({
filter: {
kontaktTyp: null,
kontaktStatus: null,
zustaendigerUserId: null,
search: null,
tagIds: null,
tagMatch: "or",
includeArchived: false,
includeDemoData: false,
},
sort: { field: "createdAt", dir: "desc" },
page: 1,
});
});
it("parses filter, sort, tag and pagination params", () => {
const params = new URLSearchParams("typ=organisation&status=kunde&owner=u1&q=meier&tags=t1,t2&tagMatch=and&archived=1&sort=name&dir=asc&page=3");
const query = parseKontaktListQuery(params);
expect(query.filter).toEqual({
kontaktTyp: "organisation",
kontaktStatus: "kunde",
zustaendigerUserId: "u1",
search: "meier",
tagIds: ["t1", "t2"],
tagMatch: "and",
includeArchived: true,
includeDemoData: false,
});
expect(query.sort).toEqual({ field: "name", dir: "asc" });
expect(query.page).toBe(3);
});
it("rejects unknown enum / malformed values", () => {
const query = parseKontaktListQuery(new URLSearchParams("typ=bogus&status=nope&sort=weird&dir=sideways&page=-4"));
expect(query.filter.kontaktTyp).toBeNull();
expect(query.filter.kontaktStatus).toBeNull();
expect(query.sort).toEqual({ field: "createdAt", dir: "desc" });
expect(query.page).toBe(1);
});
it("merges repeated tag params and the csv tags param", () => {
const query = parseKontaktListQuery(new URLSearchParams("tag=a&tag=b&tags=b,c"));
expect(query.filter.tagIds).toEqual(["a", "b", "c"]);
});
it("round-trips through kontaktListQueryToParams omitting defaults", () => {
const params = kontaktListQueryToParams(parseKontaktListQuery(new URLSearchParams()));
expect(params.toString()).toBe("");
const round = kontaktListQueryToParams(parseKontaktListQuery(new URLSearchParams("status=kunde&sort=name&dir=asc&page=2")));
expect(parseKontaktListQuery(round)).toEqual(parseKontaktListQuery(new URLSearchParams("status=kunde&sort=name&dir=asc&page=2")));
});
it("keeps demo data hidden by default and preserves the explicit show flag", () => {
expect(parseKontaktListQuery(new URLSearchParams()).filter.includeDemoData).toBe(false);
const query = parseKontaktListQuery(new URLSearchParams("demo=show"));
expect(query.filter.includeDemoData).toBe(true);
expect(kontaktListQueryToParams(query).toString()).toBe("demo=show");
});
});
@@ -0,0 +1,94 @@
// R-P6 (P6 CRM core, Variante A) — pure URL <-> contact-browser-query mapping.
//
// The contact list, the organisation list and the CSV export all read the SAME
// filter/sort/page state from the request URL (server-side, DoD 2). Keeping the
// parse/serialise here (pure, no server imports) lets the loaders and the
// pagination/export links share one source of truth and lets it be unit-tested
// without a DB. The literal unions mirror crmService's filter/sort types
// structurally so the parsed objects drop straight into listKontakteForBrowser.
export type KontaktTyp = "privatperson" | "organisation";
export type KontaktStatus = "kontakt" | "kunde" | "bestandskunde";
export type KontaktSortField = "name" | "createdAt" | "kontaktStatus";
export type SortDir = "asc" | "desc";
export interface KontaktListFilter {
kontaktTyp: KontaktTyp | null;
kontaktStatus: KontaktStatus | null;
zustaendigerUserId: string | null;
search: string | null;
tagIds: string[] | null;
tagMatch: "and" | "or";
includeArchived: boolean;
includeDemoData: boolean;
}
export interface KontaktListSort {
field: KontaktSortField;
dir: SortDir;
}
export interface KontaktListQuery {
filter: KontaktListFilter;
sort: KontaktListSort;
page: number;
}
const KONTAKT_TYP = new Set<KontaktTyp>(["privatperson", "organisation"]);
const KONTAKT_STATUS = new Set<KontaktStatus>(["kontakt", "kunde", "bestandskunde"]);
const SORT_FIELD = new Set<KontaktSortField>(["name", "createdAt", "kontaktStatus"]);
function oneOf<T>(value: string | null, allowed: Set<T>): T | null {
return value && (allowed as Set<string>).has(value) ? (value as T) : null;
}
function parseTagIds(params: URLSearchParams): string[] | null {
const repeated = params.getAll("tag").map((v) => v.trim()).filter(Boolean);
const csv = (params.get("tags") ?? "").split(",").map((v) => v.trim()).filter(Boolean);
const ids = [...new Set([...repeated, ...csv])];
return ids.length > 0 ? ids : null;
}
/** Parse the request URL search params into a contact-browser query. Unknown /
* malformed values fall back to safe defaults (no filter, createdAt desc, p1). */
export function parseKontaktListQuery(params: URLSearchParams): KontaktListQuery {
const search = params.get("q")?.trim() || null;
const sortField = oneOf<KontaktSortField>(params.get("sort"), SORT_FIELD) ?? "createdAt";
const dir: SortDir = params.get("dir") === "asc" ? "asc" : "desc";
const pageRaw = Number.parseInt(params.get("page") ?? "1", 10);
const page = Number.isFinite(pageRaw) && pageRaw > 0 ? pageRaw : 1;
return {
filter: {
kontaktTyp: oneOf<KontaktTyp>(params.get("typ"), KONTAKT_TYP),
kontaktStatus: oneOf<KontaktStatus>(params.get("status"), KONTAKT_STATUS),
zustaendigerUserId: params.get("owner")?.trim() || null,
search,
tagIds: parseTagIds(params),
tagMatch: params.get("tagMatch") === "and" ? "and" : "or",
includeArchived: params.get("archived") === "1",
includeDemoData: params.get("demo") === "show",
},
sort: { field: sortField, dir },
page,
};
}
/** Serialise a query back to a `URLSearchParams` (stable order) for pagination /
* export hrefs. Defaults are omitted to keep the URL clean. */
export function kontaktListQueryToParams(query: KontaktListQuery): URLSearchParams {
const params = new URLSearchParams();
const { filter, sort, page } = query;
if (filter.kontaktTyp) params.set("typ", filter.kontaktTyp);
if (filter.kontaktStatus) params.set("status", filter.kontaktStatus);
if (filter.zustaendigerUserId) params.set("owner", filter.zustaendigerUserId);
if (filter.search) params.set("q", filter.search);
if (filter.tagIds && filter.tagIds.length > 0) params.set("tags", filter.tagIds.join(","));
if (filter.tagMatch === "and") params.set("tagMatch", "and");
if (filter.includeArchived) params.set("archived", "1");
if (filter.includeDemoData) params.set("demo", "show");
if (sort.field !== "createdAt") params.set("sort", sort.field);
if (sort.dir !== "desc") params.set("dir", sort.dir);
if (page > 1) params.set("page", String(page));
return params;
}
@@ -0,0 +1,115 @@
// R-P6 (P6 CRM core, Variante A) — tag + polymorphic tag-assignment service.
//
// Tags are tenant-scoped (unique name per tenant). Assignments link a tag to any
// entity via a (entityType, entityId) string pair with NO DB foreign key — this
// service validates the tag's existence. Always tenant-scoped via withTenantRLS.
// NO React/UI imports. Audit + Activity are wired by the routes (crmAudit).
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { CrmServiceError } from "./crmService.server";
export type TagRow = {
id: string;
tenantId: string;
name: string;
farbe: string;
createdAt: Date;
};
// --- Tag CRUD --------------------------------------------------------------
export async function createTag(input: { tenantId: string; name: string; farbe: string }): Promise<TagRow> {
const name = input.name.trim();
if (!name) {
throw new CrmServiceError("crm.error.tagNameRequired");
}
try {
const created = await withTenantRLS(input.tenantId, (tx) => tx.tag.create({ data: { tenantId: input.tenantId, name, farbe: input.farbe } }));
return created as TagRow;
} catch (error) {
if (isUniqueConstraintError(error)) {
throw new CrmServiceError("crm.error.tagNameExists");
}
throw error;
}
}
export async function updateTag(input: { tenantId: string; tagId: string; name?: string; farbe?: string }): Promise<void> {
if (input.name !== undefined && !input.name.trim()) {
throw new CrmServiceError("crm.error.tagNameRequired");
}
try {
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.tag.findFirst({ where: { id: input.tagId, tenantId: input.tenantId }, select: { id: true } });
if (!existing) {
throw new CatalogError(foundationErrors.notFound, { tagId: input.tagId });
}
await tx.tag.updateMany({
where: { id: input.tagId, tenantId: input.tenantId },
data: { ...(input.name !== undefined ? { name: input.name.trim() } : {}), ...(input.farbe !== undefined ? { farbe: input.farbe } : {}) },
});
});
} catch (error) {
if (isUniqueConstraintError(error)) {
throw new CrmServiceError("crm.error.tagNameExists");
}
throw error;
}
}
export async function deleteTag(input: { tenantId: string; tagId: string }): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.tag.findFirst({ where: { id: input.tagId, tenantId: input.tenantId }, select: { id: true } });
if (!existing) {
throw new CatalogError(foundationErrors.notFound, { tagId: input.tagId });
}
// TagAssignment rows cascade on Tag delete (schema onDelete: Cascade).
await tx.tag.delete({ where: { id: existing.id } });
});
}
export async function listTags(tenantId: string): Promise<TagRow[]> {
const rows = await withTenantRLS(tenantId, (tx) => tx.tag.findMany({ where: { tenantId }, orderBy: { name: "asc" } }));
return rows as TagRow[];
}
// --- Polymorphic assignments -----------------------------------------------
export async function assignTag(input: { tenantId: string; tagId: string; entityType: string; entityId: string }): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const tag = await tx.tag.findFirst({ where: { id: input.tagId, tenantId: input.tenantId }, select: { id: true } });
if (!tag) {
throw new CatalogError(foundationErrors.notFound, { tagId: input.tagId });
}
// Idempotent: the (tagId, entityId, entityType) unique key makes re-assign a no-op.
await tx.tagAssignment.upsert({
where: { tagId_entityId_entityType: { tagId: input.tagId, entityId: input.entityId, entityType: input.entityType } },
update: {},
create: { tenantId: input.tenantId, tagId: input.tagId, entityType: input.entityType, entityId: input.entityId },
});
});
}
export async function unassignTag(input: { tenantId: string; tagId: string; entityType: string; entityId: string }): Promise<void> {
await withTenantRLS(input.tenantId, (tx) =>
tx.tagAssignment.deleteMany({ where: { tenantId: input.tenantId, tagId: input.tagId, entityType: input.entityType, entityId: input.entityId } }),
);
}
export async function listTagsForEntity(input: { tenantId: string; entityType: string; entityId: string }): Promise<TagRow[]> {
const assignments = await withTenantRLS(input.tenantId, (tx) =>
tx.tagAssignment.findMany({ where: { tenantId: input.tenantId, entityType: input.entityType, entityId: input.entityId }, include: { tag: true }, orderBy: { createdAt: "asc" } }),
);
return assignments.map((assignment) => assignment.tag as TagRow);
}
export async function countTagUsage(tenantId: string, tagId: string): Promise<number> {
return withTenantRLS(tenantId, (tx) => tx.tagAssignment.count({ where: { tenantId, tagId } }));
}
// --- internal --------------------------------------------------------------
function isUniqueConstraintError(error: unknown): boolean {
return Boolean(error && typeof error === "object" && "code" in error && (error as { code?: unknown }).code === "P2002");
}
@@ -0,0 +1,93 @@
import { describe, expect, it } from "vitest";
import { buildTokenMap, hasFooter, injectFooter, replaceTokens } from "./personalization";
import { assignVariants, planCampaignSend, sendAtForIndex, type PlanRecipient, type PlanVariant } from "./campaignSendPlan";
describe("personalization", () => {
it("builds standard + custom-field tokens", () => {
const map = buildTokenMap({ vorname: "Ada", nachname: "Lovelace", email: "ada@x.de", orgName: "ACME", customFields: { sprache: "DE" } });
expect(map).toMatchObject({ firstName: "Ada", lastName: "Lovelace", email: "ada@x.de", company_name: "ACME", "cf.sprache": "DE" });
});
it("replaces known tokens and collapses unknown ones", () => {
expect(replaceTokens("Hi {{firstName}} <{{email}}> {{missing}}", { firstName: "Ada", email: "ada@x.de" })).toBe("Hi Ada <ada@x.de> ");
});
it("injects the footer once (idempotent) and fills the unsubscribe url", () => {
const footer = '<a href="{{unsubscribeUrl}}">Abmelden</a> · Impressum';
const once = injectFooter("<p>Body</p>", footer, "https://t.de/unsubscribe/tok");
expect(hasFooter(once)).toBe(true);
expect(once).toContain("https://t.de/unsubscribe/tok");
const twice = injectFooter(once, footer, "https://t.de/unsubscribe/tok2");
// footer block not duplicated; url refreshed
expect(twice.match(/data-hg-footer/g)?.length).toBe(1);
});
});
describe("assignVariants", () => {
it("returns all null with no variants", () => {
expect(assignVariants(3, [])).toEqual([null, null, null]);
});
it("interleaves 50/50 as a,b,a,b", () => {
const variants: PlanVariant[] = [
{ label: "a", subject: "A", htmlBody: "<p>A</p>", weightPercent: 50 },
{ label: "b", subject: "B", htmlBody: "<p>B</p>", weightPercent: 50 },
];
expect(assignVariants(4, variants).map((v) => v?.label)).toEqual(["a", "b", "a", "b"]);
});
it("respects 60/40 weights over 5 (3:2, interleaved)", () => {
const variants: PlanVariant[] = [
{ label: "a", subject: "A", htmlBody: "<p>A</p>", weightPercent: 60 },
{ label: "b", subject: "B", htmlBody: "<p>B</p>", weightPercent: 40 },
];
const labels = assignVariants(5, variants).map((v) => v?.label);
expect(labels).toEqual(["a", "b", "a", "a", "b"]);
expect(labels.filter((l) => l === "a")).toHaveLength(3);
expect(labels.filter((l) => l === "b")).toHaveLength(2);
});
});
describe("sendAtForIndex", () => {
it("returns startAt with no throttle", () => {
expect(sendAtForIndex(500, 1000, 0)).toBe(1000);
expect(sendAtForIndex(500, 1000)).toBe(1000);
});
it("spreads by minute buckets at the configured rate", () => {
expect(sendAtForIndex(0, 1000, 100)).toBe(1000);
expect(sendAtForIndex(99, 1000, 100)).toBe(1000);
expect(sendAtForIndex(100, 1000, 100)).toBe(1000 + 60_000);
expect(sendAtForIndex(250, 1000, 100)).toBe(1000 + 2 * 60_000);
});
});
describe("planCampaignSend", () => {
const recipients: PlanRecipient[] = [
{ outboundEmailId: "o1", kontaktId: "k1", email: "a@x.de", unsubscribeToken: "t1", tokens: { vorname: "Ada", email: "a@x.de" } },
{ outboundEmailId: "o2", kontaktId: "k2", email: "b@x.de", unsubscribeToken: "t2", tokens: { vorname: "Bo", email: "b@x.de" } },
];
const base = { subject: "Hi {{firstName}}", htmlBody: "<p>Hello {{firstName}}</p>" };
const footer = '<a href="{{unsubscribeUrl}}">Abmelden</a>';
it("personalizes, injects footer, builds list-unsubscribe + sendAt", () => {
const plan = planCampaignSend({ recipients, base, footerHtml: footer, unsubscribeBaseUrl: "https://t.de/", startAt: 5000, ratePerMinute: 1 });
expect(plan).toHaveLength(2);
expect(plan[0].subject).toBe("Hi Ada");
expect(plan[0].html).toContain("Hello Ada");
expect(plan[0].html).toContain("https://t.de/unsubscribe/t1");
expect(plan[0].listUnsubscribe).toBe("<https://t.de/unsubscribe/t1>");
expect(plan[0].variantLabel).toBeNull();
expect(plan[0].sendAt).toBe(5000);
expect(plan[1].sendAt).toBe(5000 + 60_000); // rate 1/min
});
it("assigns A/B variants by weight", () => {
const variants: PlanVariant[] = [
{ label: "a", subject: "A {{firstName}}", htmlBody: "<p>A</p>", weightPercent: 50 },
{ label: "b", subject: "B {{firstName}}", htmlBody: "<p>B</p>", weightPercent: 50 },
];
const plan = planCampaignSend({ recipients, base, variants, footerHtml: footer, unsubscribeBaseUrl: "https://t.de", startAt: 0 });
expect(plan[0].variantLabel).toBe("a");
expect(plan[0].subject).toBe("A Ada");
expect(plan[1].variantLabel).toBe("b");
expect(plan[1].subject).toBe("B Bo");
});
});
@@ -0,0 +1,129 @@
// AK-P14b (P14 email marketing) — pure campaign send planning.
//
// Turns a resolved recipient list + campaign content + variants + schedule into
// a deterministic list of per-recipient send instructions: which A/B variant,
// the personalized subject/html/text, and the throttled `sendAt` timestamp.
// PURE: no DB, no queue, no clock — `now` and rate are injected so it is fully
// unit-testable. The send-engine service (S3) persists OutboundEmail rows and
// enqueues one `mail.transactional` job per plan entry.
import { buildTokenMap, injectFooter, replaceTokens, type RecipientTokenSource } from "./personalization";
export type CampaignVariantLabel = "a" | "b";
/** One A/B variant's content + audience weight. */
export interface PlanVariant {
label: CampaignVariantLabel;
subject: string;
htmlBody: string;
textBody?: string | null;
weightPercent: number;
}
/** One resolved recipient (already eligibility-filtered by the segment engine). */
export interface PlanRecipient {
outboundEmailId: string;
kontaktId: string;
email: string;
unsubscribeToken: string;
tokens: RecipientTokenSource;
}
export interface PlanCampaignInput {
recipients: readonly PlanRecipient[];
/** Default (non-A/B) content. Used when `variants` is empty. */
base: { subject: string; htmlBody: string; textBody?: string | null };
variants?: readonly PlanVariant[];
footerHtml: string;
unsubscribeBaseUrl: string;
/** Send start (epoch ms). Already resolved to the campaign timezone by caller. */
startAt: number;
/** Max sends per minute (throttle). 0/undefined ⇒ no throttle (all at startAt). */
ratePerMinute?: number;
}
export interface PlannedSend {
outboundEmailId: string;
kontaktId: string;
email: string;
variantLabel: CampaignVariantLabel | null;
subject: string;
html: string;
text: string;
unsubscribeUrl: string;
listUnsubscribe: string;
sendAt: number;
}
function buildUnsubscribeUrl(baseUrl: string, token: string): string {
return `${baseUrl.replace(/\/+$/, "")}/unsubscribe/${encodeURIComponent(token)}`;
}
/**
* Assign `count` recipients to A/B variants proportionally to their weights,
* INTERLEAVED (d'Hondt highest-averages) so both variants are spread evenly
* across the send/throttle window rather than front-loading one variant. With
* weights [50,50] the sequence is a,b,a,b…; with [60,40] over 5 it is a,b,a,a,b.
* Deterministic ⇒ re-planning is idempotent.
*/
export function assignVariants(count: number, variants: readonly PlanVariant[]): (PlanVariant | null)[] {
if (variants.length === 0) return new Array(count).fill(null);
const weights = variants.map((v) => Math.max(0, v.weightPercent));
const totalWeight = weights.reduce((sum, w) => sum + w, 0);
if (totalWeight <= 0) return Array.from({ length: count }, (_, i) => variants[i % variants.length]);
const counts = variants.map(() => 0);
const out: (PlanVariant | null)[] = [];
for (let i = 0; i < count; i += 1) {
let best = 0;
let bestQuotient = -Infinity;
for (let j = 0; j < variants.length; j += 1) {
const quotient = weights[j] / (counts[j] + 1);
if (quotient > bestQuotient) {
bestQuotient = quotient;
best = j;
}
}
counts[best] += 1;
out.push(variants[best]);
}
return out;
}
/** Throttled send time for the i-th recipient. */
export function sendAtForIndex(index: number, startAt: number, ratePerMinute?: number): number {
if (!ratePerMinute || ratePerMinute <= 0) return startAt;
const minuteOffset = Math.floor(index / ratePerMinute);
return startAt + minuteOffset * 60_000;
}
export function planCampaignSend(input: PlanCampaignInput): PlannedSend[] {
const variants = input.variants ?? [];
const assignments = assignVariants(input.recipients.length, variants);
return input.recipients.map((recipient, index) => {
const variant = assignments[index];
const content = variant ?? { subject: input.base.subject, htmlBody: input.base.htmlBody, textBody: input.base.textBody };
const tokens = buildTokenMap(recipient.tokens);
const unsubscribeUrl = buildUnsubscribeUrl(input.unsubscribeBaseUrl, recipient.unsubscribeToken);
const tokensWithUrl = { ...tokens, unsubscribeUrl };
const subject = replaceTokens(content.subject, tokensWithUrl);
const htmlWithFooter = injectFooter(content.htmlBody, input.footerHtml, unsubscribeUrl);
const html = replaceTokens(htmlWithFooter, tokensWithUrl);
const text = replaceTokens(content.textBody ?? "", tokensWithUrl);
return {
outboundEmailId: recipient.outboundEmailId,
kontaktId: recipient.kontaktId,
email: recipient.email,
variantLabel: variant?.label ?? null,
subject,
html,
text,
unsubscribeUrl,
// RFC 8058 one-click List-Unsubscribe header value.
listUnsubscribe: `<${unsubscribeUrl}>`,
sendAt: sendAtForIndex(index, input.startAt, input.ratePerMinute),
};
});
}
@@ -0,0 +1,68 @@
// AK-P14b (P14 email marketing) — pure personalization + footer injection.
//
// Replaces `{{token}}` placeholders in subject/body with per-recipient values
// (standard contact tokens + tenant custom fields as `{{cf.<key>}}`), and injects
// the DSGVO-mandatory footer (Impressum + unsubscribe link) when missing. PURE:
// no DB, no React — fully unit-testable. Used by the send-engine (S3) and the
// pre-send checklist (S5).
/** Standard token source for a recipient. */
export interface RecipientTokenSource {
vorname?: string | null;
nachname?: string | null;
email?: string | null;
orgName?: string | null;
/** Tenant custom-field values by field key (rendered as `{{cf.<key>}}`). */
customFields?: Record<string, string>;
}
/** Build the `{{token}} → value` map for a recipient. Missing values render
* as empty strings so a template never leaks a raw `{{token}}`. */
export function buildTokenMap(source: RecipientTokenSource): Record<string, string> {
const map: Record<string, string> = {
firstName: source.vorname ?? "",
lastName: source.nachname ?? "",
email: source.email ?? "",
company_name: source.orgName ?? "",
};
for (const [key, value] of Object.entries(source.customFields ?? {})) {
map[`cf.${key}`] = value;
}
return map;
}
const TOKEN_PATTERN = /\{\{\s*([\w.]+)\s*\}\}/g;
/** Replace every `{{token}}` with its mapped value. Unknown tokens collapse to
* an empty string (never left raw in a sent mail). */
export function replaceTokens(template: string, tokens: Record<string, string>): string {
return template.replace(TOKEN_PATTERN, (_match, key: string) => tokens[key] ?? "");
}
/** Marker the footer carries so re-injection is idempotent. */
export const FOOTER_MARKER = "data-hg-footer";
/** True when the html already contains an injected footer. */
export function hasFooter(html: string): boolean {
return html.includes(FOOTER_MARKER);
}
/**
* Append the mandatory footer to the html body if not already present. The
* footer carries the Impressum + the unsubscribe link; `{{unsubscribeUrl}}` in
* the footer template is replaced with the per-recipient URL.
*/
export function injectFooter(html: string, footerHtml: string, unsubscribeUrl: string): string {
if (hasFooter(html)) {
return replaceTokens(html, { unsubscribeUrl });
}
const footer = replaceTokens(footerHtml, { unsubscribeUrl });
const wrapped = `<div ${FOOTER_MARKER}="1">${footer}</div>`;
return `${html}${wrapped}`;
}
/** Build the public one-click unsubscribe URL for a signed token. */
export function buildUnsubscribeUrl(baseUrl: string, token: string): string {
const trimmed = baseUrl.replace(/\/+$/, "");
return `${trimmed}/unsubscribe/${encodeURIComponent(token)}`;
}
@@ -0,0 +1,109 @@
import { describe, expect, it } from "vitest";
import {
buildKontaktWhere,
collectLookupRefs,
lookupRefKey,
MAX_SEGMENT_DEPTH,
SEGMENT_FILTER_ERRORS,
validateSegmentTree,
type SegmentNode,
} from "./segmentFilter";
describe("validateSegmentTree", () => {
it("accepts a valid nested AND/OR tree", () => {
const tree = {
op: "and",
children: [
{ field: "kontaktStatus", in: ["kunde", "bestandskunde"] },
{ op: "or", children: [{ field: "tag", tagId: "t1" }, { field: "hasPrimaerEmail", value: true }] },
],
};
const result = validateSegmentTree(tree);
expect(result.ok).toBe(true);
});
it("rejects a non-object root", () => {
expect(validateSegmentTree(null)).toEqual({ ok: false, errorKey: SEGMENT_FILTER_ERRORS.invalidShape });
expect(validateSegmentTree("nope")).toEqual({ ok: false, errorKey: SEGMENT_FILTER_ERRORS.invalidShape });
});
it("rejects an unknown leaf field", () => {
expect(validateSegmentTree({ field: "ssn", eq: "x" })).toEqual({ ok: false, errorKey: SEGMENT_FILTER_ERRORS.invalidLeaf });
});
it("rejects a leaf with a bad value type", () => {
expect(validateSegmentTree({ field: "hasPrimaerEmail", value: "yes" })).toEqual({ ok: false, errorKey: SEGMENT_FILTER_ERRORS.invalidLeaf });
expect(validateSegmentTree({ field: "kontaktStatus", in: ["bogus"] })).toEqual({ ok: false, errorKey: SEGMENT_FILTER_ERRORS.invalidLeaf });
});
it("rejects a group missing children", () => {
expect(validateSegmentTree({ op: "and" })).toEqual({ ok: false, errorKey: SEGMENT_FILTER_ERRORS.invalidShape });
});
it("rejects trees nested beyond the depth cap", () => {
let node: unknown = { field: "hasPrimaerEmail", value: true };
for (let i = 0; i <= MAX_SEGMENT_DEPTH + 1; i += 1) {
node = { op: "and", children: [node] };
}
expect(validateSegmentTree(node)).toEqual({ ok: false, errorKey: SEGMENT_FILTER_ERRORS.tooDeep });
});
it("accepts an ISO date for createdAfter and rejects garbage", () => {
expect(validateSegmentTree({ field: "createdAfter", value: "2026-01-01" }).ok).toBe(true);
expect(validateSegmentTree({ field: "createdAfter", value: "not-a-date" })).toEqual({ ok: false, errorKey: SEGMENT_FILTER_ERRORS.invalidLeaf });
});
});
describe("collectLookupRefs", () => {
it("collects unique tag + custom-field refs and dedupes by key", () => {
const tree: SegmentNode = {
op: "or",
children: [
{ field: "tag", tagId: "t1" },
{ field: "tag", tagId: "t1" }, // dup
{ field: "tag", tagId: "t2" },
{ field: "customFieldExists", definitionId: "d1" },
{ field: "customFieldEquals", definitionId: "d2", value: "DE" },
],
};
const refs = collectLookupRefs(tree);
expect(refs.map(lookupRefKey).sort()).toEqual(["cfEquals:d2:string:DE", "cfExists:d1", "tag:t1", "tag:t2"]);
});
it("returns nothing for a tree of only native leaves", () => {
expect(collectLookupRefs({ field: "kontaktTyp", eq: "organisation" })).toEqual([]);
});
});
describe("buildKontaktWhere", () => {
const empty = new Map<string, readonly string[]>();
it("maps native leaves to Prisma where fragments", () => {
expect(buildKontaktWhere({ field: "kontaktTyp", eq: "privatperson" }, empty)).toEqual({ kontaktTyp: "privatperson" });
expect(buildKontaktWhere({ field: "kontaktStatus", in: ["kunde"] }, empty)).toEqual({ kontaktStatus: { in: ["kunde"] } });
expect(buildKontaktWhere({ field: "hasPrimaerEmail", value: true }, empty)).toEqual({ primaerEmail: { not: null } });
expect(buildKontaktWhere({ field: "hasPrimaerEmail", value: false }, empty)).toEqual({ primaerEmail: null });
});
it("resolves a tag leaf to an id-IN fragment", () => {
const resolved = new Map<string, readonly string[]>([["tag:t1", ["k1", "k2"]]]);
expect(buildKontaktWhere({ field: "tag", tagId: "t1" }, resolved)).toEqual({ id: { in: ["k1", "k2"] } });
});
it("falls back to an empty id-IN (match none) for an unresolved lookup", () => {
expect(buildKontaktWhere({ field: "tag", tagId: "missing" }, empty)).toEqual({ id: { in: [] } });
});
it("composes AND / OR groups", () => {
const tree: SegmentNode = {
op: "and",
children: [
{ field: "kontaktTyp", eq: "organisation" },
{ op: "or", children: [{ field: "hasPrimaerEmail", value: true }] },
],
};
expect(buildKontaktWhere(tree, empty)).toEqual({
AND: [{ kontaktTyp: "organisation" }, { OR: [{ primaerEmail: { not: null } }] }],
});
});
});
@@ -0,0 +1,211 @@
// AK-P14b (P14 email marketing) — pure segment filter logic.
//
// A RecipientSegment carries a nested AND/OR filter tree (`filterDefinition`
// JSONB). This module is PURE (no DB, no React): it validates an untrusted tree,
// collects the leaves that need DB resolution (tags / custom fields are
// polymorphic in crm.prisma and cannot be a plain Kontakt relation join), and
// builds a `Prisma.KontaktWhereInput`-shaped fragment from the tree + the
// resolved lookup id-sets. The DB resolution + auto-exclusion happen in
// SegmentService.server.ts. Kept pure so it is fully unit-testable with fixtures.
export type SegmentLogicalOp = "and" | "or";
export type KontaktTyp = "privatperson" | "organisation";
export type KontaktStatus = "kontakt" | "kunde" | "bestandskunde";
/** A leaf predicate. `tag` / `customField*` are LOOKUP leaves (need DB id-sets);
* the rest map directly onto native Kontakt columns. */
export type SegmentLeaf =
| { field: "kontaktTyp"; eq: KontaktTyp }
| { field: "kontaktStatus"; in: KontaktStatus[] }
| { field: "zustaendigerUserId"; eq: string }
| { field: "createdBefore"; value: string } // ISO date string
| { field: "createdAfter"; value: string } // ISO date string
| { field: "hasPrimaerEmail"; value: boolean }
| { field: "tag"; tagId: string }
| { field: "customFieldEquals"; definitionId: string; value: string | number | boolean }
| { field: "customFieldExists"; definitionId: string };
export interface SegmentGroup {
op: SegmentLogicalOp;
children: SegmentNode[];
}
export type SegmentNode = SegmentGroup | SegmentLeaf;
/** A leaf that must be resolved to a set of Kontakt ids via the DB. */
export type LookupRef =
| { kind: "tag"; tagId: string }
| { kind: "customFieldEquals"; definitionId: string; value: string | number | boolean }
| { kind: "customFieldExists"; definitionId: string };
// Guard rails against abusive trees (deep nesting / huge node counts).
export const MAX_SEGMENT_DEPTH = 6;
export const MAX_SEGMENT_NODES = 200;
/** i18n message keys (M002 Klartext) the service maps to a catalog/VM error. */
export const SEGMENT_FILTER_ERRORS = {
invalidShape: "emailMarketing.segment.error.invalidShape",
tooDeep: "emailMarketing.segment.error.tooDeep",
tooManyNodes: "emailMarketing.segment.error.tooManyNodes",
invalidLeaf: "emailMarketing.segment.error.invalidLeaf",
} as const;
export type SegmentValidationError = (typeof SEGMENT_FILTER_ERRORS)[keyof typeof SEGMENT_FILTER_ERRORS];
export type SegmentValidation = { ok: true; tree: SegmentNode } | { ok: false; errorKey: SegmentValidationError };
function isGroup(node: SegmentNode): node is SegmentGroup {
return (node as SegmentGroup).op === "and" || (node as SegmentGroup).op === "or";
}
function isPlainObject(v: unknown): v is Record<string, unknown> {
return typeof v === "object" && v !== null && !Array.isArray(v);
}
function validateLeaf(raw: Record<string, unknown>): SegmentLeaf | null {
const field = raw.field;
switch (field) {
case "kontaktTyp":
return raw.eq === "privatperson" || raw.eq === "organisation" ? { field, eq: raw.eq } : null;
case "kontaktStatus": {
if (!Array.isArray(raw.in) || raw.in.length === 0) return null;
const allowed: KontaktStatus[] = ["kontakt", "kunde", "bestandskunde"];
const values = raw.in.filter((v): v is KontaktStatus => allowed.includes(v as KontaktStatus));
return values.length === raw.in.length ? { field, in: values } : null;
}
case "zustaendigerUserId":
return typeof raw.eq === "string" && raw.eq.length > 0 ? { field, eq: raw.eq } : null;
case "createdBefore":
case "createdAfter":
return typeof raw.value === "string" && !Number.isNaN(Date.parse(raw.value)) ? { field, value: raw.value } : null;
case "hasPrimaerEmail":
return typeof raw.value === "boolean" ? { field, value: raw.value } : null;
case "tag":
return typeof raw.tagId === "string" && raw.tagId.length > 0 ? { field, tagId: raw.tagId } : null;
case "customFieldExists":
return typeof raw.definitionId === "string" && raw.definitionId.length > 0 ? { field, definitionId: raw.definitionId } : null;
case "customFieldEquals": {
if (typeof raw.definitionId !== "string" || raw.definitionId.length === 0) return null;
const value = raw.value;
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
return { field, definitionId: raw.definitionId, value };
}
return null;
}
default:
return null;
}
}
function validateNode(raw: unknown, depth: number, counter: { n: number }): SegmentNode | SegmentValidationError {
if (depth > MAX_SEGMENT_DEPTH) return SEGMENT_FILTER_ERRORS.tooDeep;
counter.n += 1;
if (counter.n > MAX_SEGMENT_NODES) return SEGMENT_FILTER_ERRORS.tooManyNodes;
if (!isPlainObject(raw)) return SEGMENT_FILTER_ERRORS.invalidShape;
if (raw.op === "and" || raw.op === "or") {
if (!Array.isArray(raw.children)) return SEGMENT_FILTER_ERRORS.invalidShape;
const children: SegmentNode[] = [];
for (const child of raw.children) {
const result = validateNode(child, depth + 1, counter);
if (typeof result === "string") return result;
children.push(result);
}
return { op: raw.op, children };
}
if (typeof raw.field === "string") {
const leaf = validateLeaf(raw);
return leaf ?? SEGMENT_FILTER_ERRORS.invalidLeaf;
}
return SEGMENT_FILTER_ERRORS.invalidShape;
}
/** Validate an untrusted `filterDefinition` into a typed tree (or an error key). */
export function validateSegmentTree(input: unknown): SegmentValidation {
const result = validateNode(input, 0, { n: 0 });
if (typeof result === "string") return { ok: false, errorKey: result };
return { ok: true, tree: result };
}
/** Stable key for a lookup ref, used to map resolution results back. */
export function lookupRefKey(ref: LookupRef): string {
switch (ref.kind) {
case "tag":
return `tag:${ref.tagId}`;
case "customFieldExists":
return `cfExists:${ref.definitionId}`;
case "customFieldEquals":
return `cfEquals:${ref.definitionId}:${typeof ref.value}:${String(ref.value)}`;
}
}
function leafLookupRef(leaf: SegmentLeaf): LookupRef | null {
switch (leaf.field) {
case "tag":
return { kind: "tag", tagId: leaf.tagId };
case "customFieldExists":
return { kind: "customFieldExists", definitionId: leaf.definitionId };
case "customFieldEquals":
return { kind: "customFieldEquals", definitionId: leaf.definitionId, value: leaf.value };
default:
return null;
}
}
/** Collect the unique lookup leaves (by key) that need DB resolution. */
export function collectLookupRefs(node: SegmentNode): LookupRef[] {
const byKey = new Map<string, LookupRef>();
const walk = (n: SegmentNode): void => {
if (isGroup(n)) {
n.children.forEach(walk);
return;
}
const ref = leafLookupRef(n);
if (ref) byKey.set(lookupRefKey(ref), ref);
};
walk(node);
return [...byKey.values()];
}
/** A Prisma.KontaktWhereInput-shaped fragment (kept loose to stay DB-free). */
export type KontaktWhereFragment = Record<string, unknown>;
function leafToWhere(leaf: SegmentLeaf, resolved: ReadonlyMap<string, readonly string[]>): KontaktWhereFragment {
switch (leaf.field) {
case "kontaktTyp":
return { kontaktTyp: leaf.eq };
case "kontaktStatus":
return { kontaktStatus: { in: leaf.in } };
case "zustaendigerUserId":
return { zustaendigerUserId: leaf.eq };
case "createdBefore":
return { createdAt: { lt: new Date(leaf.value) } };
case "createdAfter":
return { createdAt: { gt: new Date(leaf.value) } };
case "hasPrimaerEmail":
return leaf.value ? { primaerEmail: { not: null } } : { primaerEmail: null };
case "tag":
case "customFieldExists":
case "customFieldEquals": {
const ref = leafLookupRef(leaf);
const ids = (ref && resolved.get(lookupRefKey(ref))) ?? [];
return { id: { in: [...ids] } };
}
}
}
/**
* Build a `Prisma.KontaktWhereInput`-shaped fragment from the tree and the
* resolved lookup id-sets. Empty AND ⇒ match all; empty OR ⇒ match none
* (Prisma's native semantics for `{ AND: [] }` / `{ OR: [] }`).
*/
export function buildKontaktWhere(node: SegmentNode, resolved: ReadonlyMap<string, readonly string[]>): KontaktWhereFragment {
if (isGroup(node)) {
const children = node.children.map((c) => buildKontaktWhere(c, resolved));
return node.op === "and" ? { AND: children } : { OR: children };
}
return leafToWhere(node, resolved);
}
@@ -0,0 +1,172 @@
// AK-P14a · P14 Email — sending-domain settings service.
//
// Backs the Sende-Domain screen: read the tenant's sending domain (+ its
// BCC-logging inbound address), add a domain (registers it with Mailjet and
// stores the DKIM/SPF records the tenant must publish), and toggle BCC logging.
// The 5-minute worker probe (email-domain-probe-cron) drives the verification
// status; this service never blocks on DNS.
//
// Every tenant DB op runs inside withTenantRLS() so the policy binds at the P5
// cutover. The Mailjet provisioner is the EU SMTP abstraction (AD-6); it is
// optional at runtime — without credentials the domain row is still created
// (status pending) and the cron verifies DNS independently.
import { createMailjetDnsProvisioner, type MailjetDnsProvisioner } from "@hivegrid/mail";
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo } from "~/utils/session.server";
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
const BCC_LOCAL_PART = "crm";
const BCC_INBOUND_HOST = "bcc.hivegrid.de";
const DEFAULT_DMARC_RECORD = "v=DMARC1; p=none";
const DOMAIN_PATTERN = /^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/;
export type EmailDomainContext = {
tenantId: string;
userId: string;
permissions: readonly string[];
};
export async function loadEmailDomainContext({ request, params }: { request: Request; params: Record<string, string | undefined> }): Promise<EmailDomainContext> {
await requireAuth({ request, params });
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
if (!tenantId || !userInfo.userId) {
throw new CatalogError(foundationErrors.notFound);
}
const permissions = await getPermissionsByUser(userInfo.userId, tenantId);
return { tenantId, userId: userInfo.userId, permissions };
}
export function emailDomainCanView(ctx: EmailDomainContext): boolean {
return ctx.permissions.includes("email.domain.view") || ctx.permissions.includes("email.domain.manage");
}
export function emailDomainCanManage(ctx: EmailDomainContext): boolean {
return ctx.permissions.includes("email.domain.manage");
}
/** Permission-denied surfaces as 404, never 403 (Bauprinzip A.5.3). */
export function notFoundResponse(): Response {
return new Response("Not Found", { status: 404 });
}
export function badRequestResponse(): Response {
return new Response("Bad Request", { status: 400 });
}
/** Pure: normalize + validate a domain input. Returns null when invalid. */
export function normalizeDomainInput(raw: string): string | null {
const domain = raw.trim().toLowerCase().replace(/\.$/, "");
return DOMAIN_PATTERN.test(domain) ? domain : null;
}
/** Deterministic, display-only BCC address for a tenant. */
export function bccAddressFor(tenantSlug: string): string {
const safeSlug = tenantSlug.trim().toLowerCase().replace(/[^a-z0-9-]/g, "") || "tenant";
return `${BCC_LOCAL_PART}.${safeSlug}@${BCC_INBOUND_HOST}`;
}
function envProvisioner(): MailjetDnsProvisioner | null {
const apiKey = process.env.MAILJET_API_KEY;
const secretKey = process.env.MAILJET_SECRET_KEY;
if (!apiKey || !secretKey) {
return null;
}
return createMailjetDnsProvisioner({ apiKey, secretKey });
}
export type SendingDomainStateRow = {
id: string;
domain: string;
status: "pending" | "verifying" | "verified" | "failed";
dkimSelector: string | null;
dkimRecord: string | null;
spfRecord: string | null;
dmarcRecord: string | null;
lastError: string | null;
};
export async function getSendingDomainState(tenantId: string): Promise<{ domain: SendingDomainStateRow | null; bccEnabled: boolean }> {
return withTenantRLS(tenantId, async (tx) => {
const row = await tx.tenantSendingDomain.findFirst({ where: { tenantId, archivedAt: null }, orderBy: { createdAt: "desc" } });
const bcc = await tx.tenantInboundAddress.findFirst({ where: { tenantId, purpose: "bcc_logging", archivedAt: null } });
const domain: SendingDomainStateRow | null = row
? {
id: row.id,
domain: row.domain,
status: row.verificationStatus,
dkimSelector: row.dkimSelector,
dkimRecord: row.dkimRecord,
spfRecord: row.spfRecord,
dmarcRecord: row.dmarcRecord,
lastError: row.lastError,
}
: null;
return { domain, bccEnabled: bcc?.enabled ?? false };
});
}
/**
* Add (or replace) the tenant sending domain. Registers it with Mailjet and
* stores the published DKIM/SPF records; falls back to a record-less pending row
* when Mailjet credentials are absent. Soft-archives any prior domain.
*/
export async function createSendingDomain(
tenantId: string,
domain: string,
now: Date = new Date(),
deps: { provisioner?: MailjetDnsProvisioner | null } = {},
): Promise<{ id: string }> {
const provisioner = deps.provisioner === undefined ? envProvisioner() : deps.provisioner;
let dkimSelector: string | null = null;
let dkimRecord: string | null = null;
let spfRecord: string | null = null;
let mailjetDnsId: string | null = null;
if (provisioner) {
await provisioner.registerDomain(domain).catch(() => undefined);
const records = await provisioner.getRecords(domain).catch(() => null);
if (records) {
dkimSelector = records.dkimSelector;
dkimRecord = records.dkimRecord;
spfRecord = records.spfRecord;
mailjetDnsId = records.dnsId;
}
}
return withTenantRLS(tenantId, async (tx) => {
await tx.tenantSendingDomain.updateMany({ where: { tenantId, archivedAt: null }, data: { archivedAt: now } });
const created = await tx.tenantSendingDomain.create({
data: {
tenantId,
domain,
dkimSelector,
dkimRecord,
spfRecord,
dmarcRecord: DEFAULT_DMARC_RECORD,
mailjetDnsId,
verificationStatus: "pending",
firstProbeAt: now,
},
select: { id: true },
});
return created;
});
}
/** Enable/disable BCC logging by upserting the tenant bcc_logging inbound address. */
export async function setBccLogging(tenantId: string, tenantSlug: string, enabled: boolean): Promise<void> {
const address = bccAddressFor(tenantSlug);
await withTenantRLS(tenantId, async (tx) => {
const existing = await tx.tenantInboundAddress.findFirst({ where: { tenantId, purpose: "bcc_logging" } });
if (existing) {
await tx.tenantInboundAddress.update({ where: { id: existing.id }, data: { enabled, archivedAt: null } });
return;
}
await tx.tenantInboundAddress.create({
data: { tenantId, address, fullAddress: address, localPart: BCC_LOCAL_PART, purpose: "bcc_logging", enabled },
});
});
}
@@ -8,7 +8,7 @@
// - Write actions pass `requireModule: true` → 404 (CatalogError.notFound) when
// the module is off, and additionally require an explicit permission.
import { CatalogError, foundationErrors, requirePermission } from "@toolctrl/foundation";
import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo } from "~/utils/session.server";
@@ -9,8 +9,8 @@
// (contact/company/lead/deal/project/task) produce an activity; others are
// skipped (no shared @hivegrid/activity edit).
import type { JsonValue } from "@toolctrl/foundation";
import { createAuditEvent } from "@toolctrl/db/audit-events.server";
import type { JsonValue } from "@hivegrid/foundation";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { logActivity, type ActivitySubjectType, type ActivityType } from "@hivegrid/activity";
import type { FilesRouteContext } from "./fileAccess.server";
import type { FileEntityType } from "./fileService.server";
@@ -1,4 +1,4 @@
// Producer-side helper for the toolctrl.file-preview BullMQ queue. Web routes
// Producer-side helper for the hivegrid.file-preview BullMQ queue. Web routes
// call enqueueFilePreview(...) after a successful upload (and on the "regenerate
// preview" action) to trigger asynchronous preview generation in the worker.
// Mirrors fileScanQueue.server.ts so the queue lifecycle is the same shared
@@ -14,7 +14,7 @@ import {
resolveRedisConnectionOptionsFromProcessEnv,
type RedisConnectionEnv,
type TypedQueue,
} from "@toolctrl/queue";
} from "@hivegrid/queue";
export type EnqueueFilePreviewInput = {
fileId: string;
@@ -46,8 +46,8 @@ export async function enqueueFilePreview(input: EnqueueFilePreviewInput, depende
}
if (!queue && connection) {
const queueRuntimeModule = "@toolctrl/queue/runtime";
const { createQueue } = (await import(/* @vite-ignore */ queueRuntimeModule)) as typeof import("@toolctrl/queue/runtime");
const queueRuntimeModule = "@hivegrid/queue/runtime";
const { createQueue } = (await import(/* @vite-ignore */ queueRuntimeModule)) as typeof import("@hivegrid/queue/runtime");
queue = createQueue(queueNames.filePreview, { connection });
shouldCloseQueue = true;
}
@@ -1,4 +1,4 @@
// Producer-side helper for the toolctrl.file-scan BullMQ queue. Web routes
// Producer-side helper for the hivegrid.file-scan BullMQ queue. Web routes
// call enqueueFileScan(...) after a successful upload to trigger the
// asynchronous post-upload ClamAV scan in the worker. Mirrors the
// TransactionalEmailQueue.server.ts shape so the queue lifecycle is the
@@ -12,7 +12,7 @@ import {
resolveRedisConnectionOptionsFromProcessEnv,
type RedisConnectionEnv,
type TypedQueue,
} from "@toolctrl/queue";
} from "@hivegrid/queue";
export type EnqueueFileScanInput = {
bucket: string;
@@ -54,8 +54,8 @@ export async function enqueueFileScan(input: EnqueueFileScanInput, dependencies:
}
if (!queue && connection) {
const queueRuntimeModule = "@toolctrl/queue/runtime";
const { createQueue } = (await import(/* @vite-ignore */ queueRuntimeModule)) as typeof import("@toolctrl/queue/runtime");
const queueRuntimeModule = "@hivegrid/queue/runtime";
const { createQueue } = (await import(/* @vite-ignore */ queueRuntimeModule)) as typeof import("@hivegrid/queue/runtime");
queue = createQueue(queueNames.fileScan, { connection });
shouldCloseQueue = true;
}
@@ -18,16 +18,23 @@
// transaction, and functions never nest withTenantRLS() — internal composition
// goes through *WithTx(tx, ...) helpers that take the active transaction client.
import { CatalogError, foundationErrors } from "@toolctrl/foundation";
import { buildFileStorageKeys, buildUploadChunkKey, uploadChunkPrefix } from "@toolctrl/storage";
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { filesIndex } from "@hivegrid/search";
import { buildFileStorageKeys, buildUploadChunkKey, uploadChunkPrefix } from "@hivegrid/storage";
import {
FILE_UPLOAD_CHUNK_SIZE_BYTES,
FILE_UPLOAD_MAX_FILE_SIZE_BYTES,
} from "@toolctrl/view-models";
} from "@hivegrid/view-models";
import { publishFileSearchUpsert, publishSearchProjectionDelete } from "~/services/search/searchIndexProjection.server";
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import { assembleChunkedUpload, deleteFile, putBufferAsFile, resolveStorageBucket } from "./storageService";
import { getTenantUsers } from "~/utils/db/tenants.db.server";
import { fullName } from "~/utils/app/UserDisplayUtils";
import { createMediaDownloadUrl } from "./mediaSigning.server";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import { assembleChunkedUpload, deleteFile, putBufferAsFile, resolveStorageBucket, storeFile } from "./storageService";
import { enqueueFileScan } from "./fileScanQueue.server";
import { enqueueFilePreview } from "./filePreviewQueue.server";
import type { ScanContext } from "@hivegrid/storage";
/**
* Domain error carrying an i18n message key (M002 Klartext). Routes map
@@ -52,7 +59,8 @@ export type FileEntityType =
| "form_submission"
| "order"
| "task"
| "appointment";
| "appointment"
| "signature_document";
export type FileSource = "manual_upload" | "customer_portal" | "form_submission" | "email_attachment" | "automation" | "api";
@@ -286,7 +294,10 @@ export async function completeUpload(input: CompleteUploadInput): Promise<Comple
throw error instanceof FileServiceError ? error : new FileServiceError("files.error.assemblyFailed");
}
await withTenantRLS(input.tenantId, (tx) => tx.file.update({ where: { id: file.id }, data: { storageKey: original } }));
await withTenantRLS(input.tenantId, async (tx) => {
const updated = await tx.file.update({ where: { id: file.id }, data: { storageKey: original } });
await publishFileSearchUpsert(tx, updated);
});
// Clean up temp chunk objects (best-effort, S3 outside the tx) + mark the
// session done in one tenant-scoped transaction.
@@ -312,6 +323,89 @@ export async function completeUpload(input: CompleteUploadInput): Promise<Comple
return { id: file.id, displayName: file.displayName, mimeType: file.mimeType, sizeBytes: file.sizeBytes, storageKey: original };
}
export type CreateFileFromBytesInput = {
tenantId: string;
userId: string;
filename: string;
mimeType: string;
bytes: Uint8Array;
/** Pre-upload scan context (magic-bytes allow-list); defaults to mediaLibrary. */
scanContext?: ScanContext;
isDemoData?: boolean;
};
/**
* Single-request upload: create a File from an in-memory byte buffer (no chunked
* session). Mirrors the finalize tail of {@link completeUpload} — pending row →
* fail-closed magic-bytes scan + storage PUT → finalize storageKey + search
* upsert → fan out ClamAV (layer 2) + preview. Callers gate on their OWN
* permission (e.g. HR self-upload gates on hr.read_own, NOT files.write). A
* rejected scan throws {@link StorageScanRejectedError} and leaves no orphan row.
*/
export async function createFileFromBytes(input: CreateFileFromBytesInput): Promise<{ id: string; displayName: string; mimeType: string; sizeBytes: number }> {
const displayName = (input.filename || "upload").slice(0, 255);
const mimeType = input.mimeType || "application/octet-stream";
const sizeBytes = input.bytes.byteLength;
// 1. Pending File row (id needed for the storage key).
const file = await withTenantRLS(input.tenantId, (tx) =>
tx.file.create({
data: {
tenantId: input.tenantId,
createdByUserId: input.userId,
displayName,
mimeType,
sizeBytes,
storageKey: "",
source: "manual_upload",
isDemoData: input.isDemoData ?? false,
previewStatus: "pending",
scanStatus: "pending",
},
select: { id: true, displayName: true, mimeType: true, sizeBytes: true },
}),
);
const bucket = resolveStorageBucket();
const { original } = buildFileStorageKeys(input.tenantId, file.id);
// 2. Scan (fail-closed) + store the bytes. storeFile fetches the data: URI,
// runs the magic-bytes allow-list and PUTs to `original`; a rejected verdict
// throws StorageScanRejectedError. Roll the pending row back on any failure.
const dataUri = `data:${mimeType};base64,${Buffer.from(input.bytes).toString("base64")}`;
try {
await storeFile({
bucket,
id: original,
content: dataUri,
replace: true,
throwOnFailure: true,
scan: { context: input.scanContext ?? "mediaLibrary", declaredMimeType: mimeType, filename: displayName, tenantId: input.tenantId },
});
} catch (error) {
await withTenantRLS(input.tenantId, (tx) => tx.file.delete({ where: { id: file.id } }).catch(() => {})).catch(() => {});
throw error;
}
// 3. Finalize the storage key + publish to the search index.
await withTenantRLS(input.tenantId, async (tx) => {
const updated = await tx.file.update({ where: { id: file.id }, data: { storageKey: original } });
await publishFileSearchUpsert(tx, updated);
});
// 4. Fan out ClamAV (layer 2) + preview. When scanning is disabled, mark the
// file scanStatus=skipped so the fail-closed media proxy still serves it.
const scanResult = await enqueueFileScan({ bucket, key: original, tenantId: input.tenantId, contentType: mimeType, fileId: file.id }).catch(
() => ({ enqueued: false, reason: "queue-unavailable" }) as const,
);
if (!scanResult.enqueued && scanResult.reason === "scan-disabled") {
await withTenantRLS(input.tenantId, (tx) => tx.file.update({ where: { id: file.id }, data: { scanStatus: "skipped" } })).catch(() => {});
}
await enqueueFilePreview({ fileId: file.id, tenantId: input.tenantId, bucket, storageKey: original, mimeType }).catch(() => {});
return { id: file.id, displayName: file.displayName, mimeType: file.mimeType, sizeBytes: file.sizeBytes };
}
// --- Visibility / read ----------------------------------------------------
export type FileRow = {
@@ -405,6 +499,7 @@ export async function getVisibleFileWithLinks(
}
export type ListFilesFilter = {
entityType?: string | null;
mimeGroup?: string | null;
tags?: readonly string[];
assignedToUserId?: string | null;
@@ -427,24 +522,24 @@ export async function listFilesForBrowser(input: {
}): Promise<{ rows: FileRow[]; nextCursor: string | null }> {
const limit = Math.min(Math.max(input.limit ?? 50, 1), 100);
const filter = input.filter ?? {};
const visibility = hasPermission(input.ctx, "files.read_all")
? {}
: {
OR: [
{ createdByUserId: input.ctx.userId },
{ assignedToUserId: input.ctx.userId },
{ links: { some: { tenantId: input.tenantId } } },
],
};
const mimePrefix = filter.mimeGroup ? MIME_GROUP_PREFIX[filter.mimeGroup] : undefined;
const where = {
tenantId: input.tenantId,
...(filter.includeArchived ? {} : { archivedAt: null }),
...(filter.assignedToUserId ? { assignedToUserId: filter.assignedToUserId } : {}),
...(filter.tags && filter.tags.length > 0 ? { tags: { hasEvery: [...filter.tags] } } : {}),
...(mimePrefix ? { mimeType: { startsWith: mimePrefix } } : {}),
...visibility,
};
// Build the where clause on a typed mutable object (not spread-of-union) so the
// optional filters + visibility OR type-check cleanly against FileWhereInput.
const where: Prisma.FileWhereInput = { tenantId: input.tenantId };
if (!filter.includeArchived) where.archivedAt = null;
if (filter.assignedToUserId) where.assignedToUserId = filter.assignedToUserId;
if (filter.tags && filter.tags.length > 0) where.tags = { hasEvery: [...filter.tags] };
if (mimePrefix) where.mimeType = { startsWith: mimePrefix };
if (filter.entityType) {
where.links = { some: { tenantId: input.tenantId, entityType: filter.entityType as Prisma.FileEntityLinkWhereInput["entityType"] } };
}
if (!hasPermission(input.ctx, "files.read_all")) {
where.OR = [
{ createdByUserId: input.ctx.userId },
{ assignedToUserId: input.ctx.userId },
{ links: { some: { tenantId: input.tenantId } } },
];
}
const rows = await withTenantRLS(input.tenantId, (tx) =>
tx.file.findMany({
where,
@@ -457,6 +552,146 @@ export async function listFilesForBrowser(input: {
return { rows: rows.slice(0, limit) as FileRow[], nextCursor };
}
export type FileFilterOptions = {
/** Distinct entity types that are actually linked to files in this tenant. */
entityTypes: string[];
/** Distinct tags across (recent) tenant files, sorted. */
tags: string[];
/** Active tenant members, usable as assignee (Verantwortlicher) filter. */
assignees: { id: string; name: string }[];
};
/**
* Build the option lists for the browser filter dropdowns (tenant-scoped).
* Tags are scanned over the most recent files (capped) so the dropdown stays
* bounded; entity types come from the FileEntityLink distinct set; assignees are
* the tenant's active members.
*/
export async function listFileFilterOptions(input: { tenantId: string }): Promise<FileFilterOptions> {
const TAG_SCAN_LIMIT = 500;
const { tagRows, entityTypeRows } = await withTenantRLS(input.tenantId, async (tx) => {
const tagRows = await tx.file.findMany({
where: { tenantId: input.tenantId },
select: { tags: true },
orderBy: { createdAt: "desc" },
take: TAG_SCAN_LIMIT,
});
const entityTypeRows = await tx.fileEntityLink.findMany({
where: { tenantId: input.tenantId },
select: { entityType: true },
distinct: ["entityType"],
orderBy: { entityType: "asc" },
});
return { tagRows, entityTypeRows };
});
const tags = Array.from(new Set(tagRows.flatMap((row) => row.tags))).sort((a, b) => a.localeCompare(b));
const entityTypes = entityTypeRows.map((row) => row.entityType);
const members = await getTenantUsers(input.tenantId);
const assignees = members
.map((member) => ({ id: member.user.id, name: fullName(member.user) }))
.sort((a, b) => a.name.localeCompare(b.name));
return { entityTypes, tags, assignees };
}
// --- Bulk ZIP -------------------------------------------------------------
/** Max files a single bulk-ZIP may contain (defensive bound for the in-memory zip). */
export const BULK_ZIP_MAX_FILES = 50;
/** Max total original bytes a single bulk-ZIP may pull (in-memory safety). */
export const BULK_ZIP_MAX_TOTAL_BYTES = 200 * 1024 * 1024;
export type BulkZipEntry = { name: string; bytes: Uint8Array };
export type BulkZipResult = {
/** Zip entries for the buildable (visible + clean) files. */
entries: BulkZipEntry[];
/** Files that were requested but skipped (not visible / not clean / over the cap). */
skippedCount: number;
};
/**
* Collect the byte payloads for a bulk-ZIP download (tenant-scoped, fail-closed).
* Only files that are visible to the user AND scan-clean/skipped are included; an
* infected/pending/invisible/over-cap file is silently dropped (never leaked into
* the archive). Bytes are pulled via short-lived signed URLs (AD-23, no public
* bucket). Entry names are de-duplicated so the zip stays valid.
*/
export async function collectFilesForZip(input: {
tenantId: string;
ctx: FileVisibilityContext;
fileIds: readonly string[];
}): Promise<BulkZipResult> {
const ids = Array.from(new Set(input.fileIds)).slice(0, BULK_ZIP_MAX_FILES);
if (ids.length === 0) {
return { entries: [], skippedCount: 0 };
}
const where: Prisma.FileWhereInput = {
tenantId: input.tenantId,
id: { in: ids },
scanStatus: { in: ["clean", "skipped"] },
};
if (!hasPermission(input.ctx, "files.read_all")) {
where.OR = [
{ createdByUserId: input.ctx.userId },
{ assignedToUserId: input.ctx.userId },
{ links: { some: { tenantId: input.tenantId } } },
];
}
const files = await withTenantRLS(input.tenantId, (tx) =>
tx.file.findMany({ where, select: { id: true, displayName: true, storageKey: true, sizeBytes: true } }),
);
const usedNames = new Set<string>();
const entries: BulkZipEntry[] = [];
let totalBytes = 0;
let skippedCount = ids.length - files.length;
for (const file of files) {
if (!file.storageKey || totalBytes + file.sizeBytes > BULK_ZIP_MAX_TOTAL_BYTES) {
skippedCount += 1;
continue;
}
try {
const url = await createMediaDownloadUrl({ key: file.storageKey });
const response = await fetch(url);
if (!response.ok) {
skippedCount += 1;
continue;
}
const bytes = new Uint8Array(await response.arrayBuffer());
totalBytes += bytes.byteLength;
entries.push({ name: uniqueZipName(file.displayName, usedNames), bytes });
} catch {
skippedCount += 1;
}
}
return { entries, skippedCount };
}
/** Ensure a zip entry name is unique (append " (n)" before the extension). */
function uniqueZipName(rawName: string, used: Set<string>): string {
const safe = (rawName || "datei").replace(/[/\\]/g, "_");
if (!used.has(safe)) {
used.add(safe);
return safe;
}
const dot = safe.lastIndexOf(".");
const base = dot > 0 ? safe.slice(0, dot) : safe;
const ext = dot > 0 ? safe.slice(dot) : "";
let index = 2;
let candidate = `${base} (${index})${ext}`;
while (used.has(candidate)) {
index += 1;
candidate = `${base} (${index})${ext}`;
}
used.add(candidate);
return candidate;
}
// --- Mutations ------------------------------------------------------------
export async function linkFile(input: {
@@ -497,15 +732,25 @@ export async function unlinkFile(input: { tenantId: string; fileId: string; enti
}
export async function archiveFile(input: { tenantId: string; fileId: string }): Promise<void> {
await withTenantRLS(input.tenantId, (tx) =>
tx.file.updateMany({ where: { id: input.fileId, tenantId: input.tenantId }, data: { archivedAt: new Date() } }),
);
await withTenantRLS(input.tenantId, async (tx) => {
const file = await tx.file.findFirst({ where: { id: input.fileId, tenantId: input.tenantId }, select: { id: true } });
if (!file) {
throw new CatalogError(foundationErrors.notFound, { fileId: input.fileId });
}
await tx.file.update({ where: { id: file.id }, data: { archivedAt: new Date() } });
await publishSearchProjectionDelete(tx, { schema: filesIndex, tenantId: input.tenantId, entityType: "file", entityId: file.id });
});
}
export async function reactivateFile(input: { tenantId: string; fileId: string }): Promise<void> {
await withTenantRLS(input.tenantId, (tx) =>
tx.file.updateMany({ where: { id: input.fileId, tenantId: input.tenantId }, data: { archivedAt: null } }),
);
await withTenantRLS(input.tenantId, async (tx) => {
const file = await tx.file.findFirst({ where: { id: input.fileId, tenantId: input.tenantId }, select: { id: true } });
if (!file) {
throw new CatalogError(foundationErrors.notFound, { fileId: input.fileId });
}
const updated = await tx.file.update({ where: { id: file.id }, data: { archivedAt: null } });
await publishFileSearchUpsert(tx, updated);
});
}
export async function updateFileMeta(input: {
@@ -516,17 +761,22 @@ export async function updateFileMeta(input: {
assignedToUserId?: string | null;
displayName?: string;
}): Promise<void> {
await withTenantRLS(input.tenantId, (tx) =>
tx.file.updateMany({
where: { id: input.fileId, tenantId: input.tenantId },
await withTenantRLS(input.tenantId, async (tx) => {
const file = await tx.file.findFirst({ where: { id: input.fileId, tenantId: input.tenantId }, select: { id: true } });
if (!file) {
throw new CatalogError(foundationErrors.notFound, { fileId: input.fileId });
}
const updated = await tx.file.update({
where: { id: file.id },
data: {
...(input.tags !== undefined ? { tags: input.tags } : {}),
...(input.notes !== undefined ? { notes: input.notes } : {}),
...(input.assignedToUserId !== undefined ? { assignedToUserId: input.assignedToUserId } : {}),
...(input.displayName !== undefined ? { displayName: input.displayName.slice(0, 255) } : {}),
},
}),
);
});
await publishFileSearchUpsert(tx, updated);
});
}
export async function regenerateFilePreview(input: { tenantId: string; fileId: string }): Promise<void> {
@@ -567,7 +817,10 @@ export async function hardDeleteFile(input: { tenantId: string; fileId: string }
}
}
// FileEntityLink rows cascade on File delete (schema onDelete: Cascade).
await withTenantRLS(input.tenantId, (tx) => tx.file.delete({ where: { id: file.id } }));
await withTenantRLS(input.tenantId, async (tx) => {
await tx.file.delete({ where: { id: file.id } });
await publishSearchProjectionDelete(tx, { schema: filesIndex, tenantId: input.tenantId, entityType: "file", entityId: file.id });
});
}
/** Best-effort cleanup of all temp chunk objects of an upload session. */
@@ -0,0 +1,118 @@
// P17 HR-Hub core (AK-P17a) — shared loader/action guard for HR routes.
//
// Resolves the authenticated tenant context and the user's permission set once,
// so routes gate consistently (mirrors taskAccess.server.ts). Module-not-active
// handling differs by intent (Bauprinzip A.5.3, "404 vs locked"):
// - GET loaders pass `requireModule: false` and render a locked/empty VM when
// `hasModule` is false.
// - Write actions pass `requireModule: true` → 404 (CatalogError.notFound) when
// the module is off, and additionally require an explicit permission.
import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo } from "~/utils/session.server";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
import { HrServiceError } from "./hrService.server";
import { HR_MODULE_KEY } from "./hrRoutePaths";
// Re-exported for back-compat; the canonical definition lives in the client-safe
// hrRoutePaths module so route `handle` exports can reference it without pulling
// this server-only guard into the client bundle.
export { HR_MODULE_KEY };
export type HrRouteContext = {
tenantId: string;
userId: string;
/** The user's permission names for this tenant (from getPermissionsByUser). */
permissions: readonly string[];
hasModule: boolean;
};
export async function loadHrContext({
request,
params,
requireModule = false,
}: {
request: Request;
params: Record<string, string | undefined>;
requireModule?: boolean;
}): Promise<HrRouteContext> {
await requireAuth({ request, params });
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
if (!tenantId || !userInfo.userId) {
throw new CatalogError(foundationErrors.notFound);
}
const [hasModule, permissions] = await Promise.all([
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: HR_MODULE_KEY }),
getPermissionsByUser(userInfo.userId, tenantId),
]);
if (requireModule && !hasModule) {
// Mutations on a disabled module look "not found" (Bauprinzip A.5.3).
throw new CatalogError(foundationErrors.notFound, { module: HR_MODULE_KEY });
}
return { tenantId, userId: userInfo.userId, permissions, hasModule };
}
/** True if the user holds `permission` (or a broader bundle that implies it). */
export function hrHasPermission(ctx: HrRouteContext, permission: string): boolean {
if (ctx.permissions.includes(permission)) {
return true;
}
// Bundle implication (mirrors files/tasks): read_all ⊃ read_own; write ⊃
// read_all; admin ⊃ write. Expanded here at check time so callers register the
// flat permissions only.
if (permission === "hr.read_own") {
return ctx.permissions.includes("hr.read_all") || ctx.permissions.includes("hr.write") || ctx.permissions.includes("hr.admin");
}
if (permission === "hr.read_all") {
return ctx.permissions.includes("hr.write") || ctx.permissions.includes("hr.admin");
}
if (permission === "hr.write") {
return ctx.permissions.includes("hr.admin");
}
return false;
}
/** Require an hr.* permission (bundle-aware); throws 404 if missing. */
export function requireHrPermission(ctx: HrRouteContext, permission: string): HrRouteContext {
if (!hrHasPermission(ctx, permission)) {
// Permission-denied surfaces as 404, never 403 (Bauprinzip A.5.3).
throw new CatalogError(foundationErrors.notFound, { permission });
}
// Defensive: keep the central requirePermission audit/telemetry path warm for
// the exact-match case (no-op when hrHasPermission already passed via bundle).
if (ctx.permissions.includes(permission)) {
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, permission);
}
return ctx;
}
/**
* Bare 404 Response for throwing from HR loaders/actions. The body text is never
* shown to users (the route ErrorBoundary renders ServerError).
*/
export function notFoundResponse(): Response {
return new Response("Not Found", { status: 404 });
}
/** Bare 400 Response for invalid action input. */
export function badRequestResponse(): Response {
return new Response("Bad Request", { status: 400 });
}
/**
* Map an HR action error to a JSON Response for resource routes. CatalogError
* keeps its status + i18nKey; HrServiceError is a 400 with its Klartext message
* key. Unknown errors are rethrown (→ 500).
*/
export function hrActionErrorResponse(error: unknown): Response {
if (error instanceof CatalogError) {
return Response.json({ error: error.i18nKey, code: error.code }, { status: error.status });
}
if (error instanceof HrServiceError) {
return Response.json({ error: error.messageKey }, { status: 400 });
}
throw error;
}
@@ -0,0 +1,272 @@
// P17 HR-Hub workflows (AK-P17b) — announcements domain service.
//
// Company announcements with audience targeting, optional acknowledgement
// (read-receipt), reactions and single-level comments. NO React/UI imports.
// Every tenant access runs inside withTenantRLS(); content writes are audited
// (M001). Announcements are not CRM subjects, so no Activity-Stream entry
// (DoD 14 N/A); a required acknowledgement notifies the audience via M011 at the
// route layer when first published.
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { HrServiceError } from "./hrService.server";
const HR_AUDIT_MODULE = "hr";
const MAX_TITLE = 255;
const MAX_BODY = 20000;
const MAX_COMMENT = 4000;
export type HrAudienceKind = "all" | "team" | "location";
export type AnnouncementRow = {
id: string;
tenantId: string;
authorUserId: string;
title: string;
body: string;
audienceKind: HrAudienceKind;
audienceRef: string | null;
requiresAcknowledgement: boolean;
pinnedAt: Date | null;
publishAt: Date | null;
expiresAt: Date | null;
createdAt: Date;
updatedAt: Date;
archivedAt: Date | null;
};
async function audit(input: { tenantId: string; actorId: string; action: string; targetId: string }): Promise<void> {
await createAuditEvent({
tenantId: input.tenantId,
actorId: input.actorId,
actorType: "user",
action: input.action,
targetType: "HrAnnouncement",
targetId: input.targetId,
sourceModule: HR_AUDIT_MODULE,
outcome: "success",
});
}
/** True when an announcement targeting `kind`/`ref` is visible to a viewer in
* `team`/`locationId`. Pure helper, reused by feed filtering. */
export function isAnnouncementVisible(kind: HrAudienceKind, ref: string | null, viewer: { team: string | null; locationId: string | null }): boolean {
if (kind === "all") return true;
if (kind === "team") return ref != null && ref === viewer.team;
if (kind === "location") return ref != null && ref === viewer.locationId;
return false;
}
export type CreateAnnouncementInput = {
tenantId: string;
authorUserId: string;
title: string;
body: string;
audienceKind?: HrAudienceKind;
audienceRef?: string | null;
requiresAcknowledgement?: boolean;
pinned?: boolean;
publishAt?: Date | null;
expiresAt?: Date | null;
isDemoData?: boolean;
};
export async function createAnnouncement(input: CreateAnnouncementInput): Promise<AnnouncementRow> {
const title = input.title.trim();
const body = input.body.trim();
if (!title) throw new HrServiceError("hr.error.announcementTitleRequired");
if (!body) throw new HrServiceError("hr.error.announcementBodyRequired");
const created = (await withTenantRLS(input.tenantId, (tx) =>
tx.hrAnnouncement.create({
data: {
tenantId: input.tenantId,
authorUserId: input.authorUserId,
title: title.slice(0, MAX_TITLE),
body: body.slice(0, MAX_BODY),
audienceKind: input.audienceKind ?? "all",
audienceRef: input.audienceRef ?? null,
requiresAcknowledgement: input.requiresAcknowledgement ?? false,
pinnedAt: input.pinned ? new Date() : null,
publishAt: input.publishAt ?? null,
expiresAt: input.expiresAt ?? null,
isDemoData: input.isDemoData ?? false,
},
}),
)) as AnnouncementRow;
await audit({ tenantId: input.tenantId, actorId: input.authorUserId, action: "HR_ANNOUNCEMENT_CREATE", targetId: created.id });
return created;
}
export type UpdateAnnouncementInput = Partial<Omit<CreateAnnouncementInput, "tenantId" | "authorUserId">> & {
tenantId: string;
actorUserId: string;
announcementId: string;
};
export async function updateAnnouncement(input: UpdateAnnouncementInput): Promise<void> {
if (input.title !== undefined && !input.title.trim()) throw new HrServiceError("hr.error.announcementTitleRequired");
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.hrAnnouncement.findFirst({ where: { id: input.announcementId, tenantId: input.tenantId }, select: { id: true } });
if (!existing) throw new CatalogError(foundationErrors.notFound, { announcementId: input.announcementId });
await tx.hrAnnouncement.update({
where: { id: input.announcementId },
data: {
...(input.title !== undefined ? { title: input.title.trim().slice(0, MAX_TITLE) } : {}),
...(input.body !== undefined ? { body: input.body.trim().slice(0, MAX_BODY) } : {}),
...(input.audienceKind !== undefined ? { audienceKind: input.audienceKind } : {}),
...(input.audienceRef !== undefined ? { audienceRef: input.audienceRef } : {}),
...(input.requiresAcknowledgement !== undefined ? { requiresAcknowledgement: input.requiresAcknowledgement } : {}),
...(input.pinned !== undefined ? { pinnedAt: input.pinned ? new Date() : null } : {}),
...(input.publishAt !== undefined ? { publishAt: input.publishAt } : {}),
...(input.expiresAt !== undefined ? { expiresAt: input.expiresAt } : {}),
},
});
});
await audit({ tenantId: input.tenantId, actorId: input.actorUserId, action: "HR_ANNOUNCEMENT_UPDATE", targetId: input.announcementId });
}
export async function archiveAnnouncement(input: { tenantId: string; actorUserId: string; announcementId: string }): Promise<void> {
await withTenantRLS(input.tenantId, (tx) => tx.hrAnnouncement.updateMany({ where: { id: input.announcementId, tenantId: input.tenantId }, data: { archivedAt: new Date() } }));
await audit({ tenantId: input.tenantId, actorId: input.actorUserId, action: "HR_ANNOUNCEMENT_ARCHIVE", targetId: input.announcementId });
}
export type FeedEntry = AnnouncementRow & { isRead: boolean; isAcknowledged: boolean; reactionCount: number; commentCount: number };
/** Published, non-archived, non-expired announcements visible to the viewer,
* pinned first then newest, annotated with the viewer's read/ack state. */
export async function listFeed(input: { tenantId: string; userId: string; viewerTeam: string | null; viewerLocationId: string | null; now?: Date }): Promise<FeedEntry[]> {
const now = input.now ?? new Date();
return withTenantRLS(input.tenantId, async (tx) => {
const rows = (await tx.hrAnnouncement.findMany({
where: {
tenantId: input.tenantId,
archivedAt: null,
OR: [{ publishAt: null }, { publishAt: { lte: now } }],
AND: [{ OR: [{ expiresAt: null }, { expiresAt: { gt: now } }] }],
},
orderBy: [{ pinnedAt: "desc" }, { createdAt: "desc" }],
})) as AnnouncementRow[];
const visible = rows.filter((row) => isAnnouncementVisible(row.audienceKind, row.audienceRef, { team: input.viewerTeam, locationId: input.viewerLocationId }));
const ids = visible.map((row) => row.id);
const [reads, reactionCounts, commentCounts] = await Promise.all([
tx.hrAnnouncementRead.findMany({ where: { tenantId: input.tenantId, userId: input.userId, announcementId: { in: ids } } }),
tx.hrAnnouncementReaction.groupBy({ by: ["announcementId"], where: { tenantId: input.tenantId, announcementId: { in: ids } }, _count: { _all: true } }),
tx.hrAnnouncementComment.groupBy({ by: ["announcementId"], where: { tenantId: input.tenantId, announcementId: { in: ids }, archivedAt: null }, _count: { _all: true } }),
]);
const readByAnn = new Map(reads.map((r) => [r.announcementId, r]));
const reactionByAnn = new Map(reactionCounts.map((r) => [r.announcementId, r._count._all]));
const commentByAnn = new Map(commentCounts.map((c) => [c.announcementId, c._count._all]));
return visible.map((row) => ({
...row,
isRead: readByAnn.has(row.id),
isAcknowledged: Boolean(readByAnn.get(row.id)?.acknowledgedAt),
reactionCount: reactionByAnn.get(row.id) ?? 0,
commentCount: commentByAnn.get(row.id) ?? 0,
}));
});
}
/** Admin list of all non-archived announcements (incl. drafts/scheduled). */
export async function listAllAnnouncements(tenantId: string): Promise<AnnouncementRow[]> {
const rows = await withTenantRLS(tenantId, (tx) =>
tx.hrAnnouncement.findMany({ where: { tenantId, archivedAt: null }, orderBy: [{ pinnedAt: "desc" }, { createdAt: "desc" }] }),
);
return rows as AnnouncementRow[];
}
export async function getAnnouncementOrThrow(tenantId: string, announcementId: string): Promise<AnnouncementRow> {
const row = await withTenantRLS(tenantId, (tx) => tx.hrAnnouncement.findFirst({ where: { id: announcementId, tenantId, archivedAt: null } }));
if (!row) throw new CatalogError(foundationErrors.notFound, { announcementId });
return row as AnnouncementRow;
}
/** Mark an announcement read (idempotent). */
export async function markRead(input: { tenantId: string; announcementId: string; userId: string }): Promise<void> {
await withTenantRLS(input.tenantId, (tx) =>
tx.hrAnnouncementRead.upsert({
where: { announcementId_userId: { announcementId: input.announcementId, userId: input.userId } },
update: {},
create: { tenantId: input.tenantId, announcementId: input.announcementId, userId: input.userId },
}),
);
}
/** Acknowledge an announcement that requires it (idempotent, audited). */
export async function acknowledge(input: { tenantId: string; announcementId: string; userId: string }): Promise<void> {
await withTenantRLS(input.tenantId, (tx) =>
tx.hrAnnouncementRead.upsert({
where: { announcementId_userId: { announcementId: input.announcementId, userId: input.userId } },
update: { acknowledgedAt: new Date() },
create: { tenantId: input.tenantId, announcementId: input.announcementId, userId: input.userId, acknowledgedAt: new Date() },
}),
);
await audit({ tenantId: input.tenantId, actorId: input.userId, action: "HR_ANNOUNCEMENT_ACK", targetId: input.announcementId });
}
export type ReadReceiptRow = { userId: string; readAt: Date; acknowledgedAt: Date | null };
/** Manager view: who read / acknowledged an announcement. */
export async function listReadReceipts(tenantId: string, announcementId: string): Promise<ReadReceiptRow[]> {
const rows = await withTenantRLS(tenantId, (tx) =>
tx.hrAnnouncementRead.findMany({ where: { tenantId, announcementId }, select: { userId: true, createdAt: true, acknowledgedAt: true }, orderBy: { createdAt: "asc" } }),
);
return rows.map((r) => ({ userId: r.userId, readAt: r.createdAt, acknowledgedAt: r.acknowledgedAt }));
}
export type ReactionGroup = { reaction: string; count: number; mine: boolean };
/** Reactions grouped by emoji with a per-viewer `mine` flag. */
export async function getReactionGroups(tenantId: string, announcementId: string, userId: string): Promise<ReactionGroup[]> {
return withTenantRLS(tenantId, async (tx) => {
const all = await tx.hrAnnouncementReaction.findMany({ where: { tenantId, announcementId }, select: { reaction: true, userId: true } });
const map = new Map<string, { count: number; mine: boolean }>();
for (const r of all) {
const entry = map.get(r.reaction) ?? { count: 0, mine: false };
entry.count += 1;
if (r.userId === userId) entry.mine = true;
map.set(r.reaction, entry);
}
return [...map.entries()].map(([reaction, value]) => ({ reaction, count: value.count, mine: value.mine }));
});
}
/** Whether the viewer has acknowledged the announcement. */
export async function getUserAckState(tenantId: string, announcementId: string, userId: string): Promise<boolean> {
const row = await withTenantRLS(tenantId, (tx) =>
tx.hrAnnouncementRead.findUnique({ where: { announcementId_userId: { announcementId, userId } }, select: { acknowledgedAt: true } }),
);
return Boolean(row?.acknowledgedAt);
}
export async function toggleReaction(input: { tenantId: string; announcementId: string; userId: string; reaction: string }): Promise<void> {
const reaction = input.reaction.slice(0, 16);
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.hrAnnouncementReaction.findFirst({ where: { tenantId: input.tenantId, announcementId: input.announcementId, userId: input.userId, reaction } });
if (existing) {
await tx.hrAnnouncementReaction.delete({ where: { id: existing.id } });
} else {
await tx.hrAnnouncementReaction.create({ data: { tenantId: input.tenantId, announcementId: input.announcementId, userId: input.userId, reaction } });
}
});
}
export async function addComment(input: { tenantId: string; announcementId: string; userId: string; body: string }): Promise<void> {
const body = input.body.trim();
if (!body) throw new HrServiceError("hr.error.commentEmpty");
await withTenantRLS(input.tenantId, (tx) => tx.hrAnnouncementComment.create({ data: { tenantId: input.tenantId, announcementId: input.announcementId, userId: input.userId, body: body.slice(0, MAX_COMMENT) } }));
await audit({ tenantId: input.tenantId, actorId: input.userId, action: "HR_ANNOUNCEMENT_COMMENT", targetId: input.announcementId });
}
export type CommentRow = { id: string; userId: string; body: string; createdAt: Date };
export async function listComments(tenantId: string, announcementId: string): Promise<CommentRow[]> {
const rows = await withTenantRLS(tenantId, (tx) =>
tx.hrAnnouncementComment.findMany({ where: { tenantId, announcementId, archivedAt: null }, select: { id: true, userId: true, body: true, createdAt: true }, orderBy: { createdAt: "asc" } }),
);
return rows as CommentRow[];
}
export async function archiveComment(input: { tenantId: string; commentId: string; actorUserId: string }): Promise<void> {
await withTenantRLS(input.tenantId, (tx) => tx.hrAnnouncementComment.updateMany({ where: { id: input.commentId, tenantId: input.tenantId }, data: { archivedAt: new Date() } }));
}
@@ -0,0 +1,116 @@
// @vitest-environment node
import pg from "pg";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
// AK-P17a — HR field-crypto END-TO-END proof through the REAL services.
//
// After the R-P5 per-tenant envelope (getTenantFieldCrypto, AD-8) was bound into
// the hrFieldCrypto seam, this drives the actual HR services and asserts that
// sensitive values are persisted as ciphertext (never plaintext) and round-trip
// on the audited reveal path. The in-memory envelope unit test
// (packages/db/src/crypto/tenant-envelope.server.test.ts) proves the primitive in
// isolation; this proves the SERVICE WIRING — i.e. that setEmergencyContact /
// createEntry / revealEntryValue actually call the bound provider.
//
// Runs ONLY when HR_CRYPTO_TEST_DATABASE_URL points at a throwaway Postgres with
// the schema pushed. Skipped otherwise so the normal unit suite stays green
// without a DB. A plain superuser connection is fine: this exercises crypto, not
// RLS (the RLS confinement is covered by rls-hr-isolation.integration.test.ts).
//
// Setup:
// docker run -d --name hg-crypto-pg -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=hivegrid -p 5433:5432 pgvector/pgvector:pg16
// DIRECT_URL=postgresql://postgres:postgres@localhost:5433/hivegrid pnpm exec prisma db push
// HR_CRYPTO_TEST_DATABASE_URL=postgresql://postgres:postgres@localhost:5433/hivegrid pnpm vitest run hrFieldCrypto.roundtrip
const DB_URL = process.env.HR_CRYPTO_TEST_DATABASE_URL;
const describeIfDb = DB_URL ? describe : describe.skip;
const TENANT = "hrcrypto_tenant";
const OTHER_TENANT = "hrcrypto_other_tenant";
const USER = "hrcrypto_user";
describeIfDb("HR field crypto round-trip through services (getTenantFieldCrypto)", () => {
let raw: pg.Client;
let hr: typeof import("./hrService.server");
let safe: typeof import("./hrPasswordSafeService.server");
beforeAll(async () => {
// Point the app's Prisma client at the throwaway DB and configure the master
// key BEFORE importing the services (the db client is constructed on import,
// getTenantFieldCrypto wraps the DEK with CRYPTO_SECRET).
process.env.DATABASE_URL = DB_URL;
process.env.DIRECT_URL = DB_URL;
process.env.CRYPTO_SECRET ??= "hr-crypto-it-master-key-0123456789ab";
hr = await import("./hrService.server");
safe = await import("./hrPasswordSafeService.server");
raw = new pg.Client({ connectionString: DB_URL });
await raw.connect();
// Deterministic re-runs: clear this test's tenant rows (FK order).
await raw.query(`DELETE FROM "EmployeePasswordSafeEntry" WHERE "tenantId" = ANY($1)`, [[TENANT, OTHER_TENANT]]);
await raw.query(`DELETE FROM "EmployeePasswordSafeAccess" WHERE "tenantId" = ANY($1)`, [[TENANT, OTHER_TENANT]]);
await raw.query(`DELETE FROM "EmployeePasswordSafeVault" WHERE "tenantId" = ANY($1)`, [[TENANT, OTHER_TENANT]]);
await raw.query(`DELETE FROM "HrEmployeeProfile" WHERE "tenantId" = ANY($1)`, [[TENANT, OTHER_TENANT]]);
await raw.query(`DELETE FROM "TenantEncryptionKey" WHERE "tenantId" = ANY($1)`, [[TENANT, OTHER_TENANT]]);
});
afterAll(async () => {
await raw?.end();
});
it("emergency contact: stored as ciphertext, round-trips on reveal", async () => {
const contact = { name: "Jamie Doe", phone: "+49 151 23456789", relation: "partner" };
await hr.setEmergencyContact({ tenantId: TENANT, userId: USER, contact });
const { rows } = await raw.query(
`SELECT "emergencyContactCiphertext" AS c FROM "HrEmployeeProfile" WHERE "tenantId" = $1 AND "userId" = $2`,
[TENANT, USER],
);
const stored = rows[0]?.c as string | null;
expect(stored).toBeTruthy();
expect(stored).not.toContain("Jamie Doe");
expect(stored).not.toContain(JSON.stringify(contact));
expect(stored!.startsWith("v1:")).toBe(true);
const revealed = await hr.revealEmergencyContact({ tenantId: TENANT, userId: USER, revealerUserId: USER });
expect(revealed).toEqual(contact);
});
it("password-safe entry: secrets stored as ciphertext, reveal round-trips, list hides values", async () => {
const vault = await safe.createVault({ tenantId: TENANT, name: "Ops", createdByUserId: USER });
const secrets = { username: "ops-admin", password: "S3cr3t!pw", notes: "rotate quarterly" };
const { id: entryId } = await safe.createEntry({ tenantId: TENANT, vaultId: vault.id, userId: USER, title: "Router", secrets });
const { rows } = await raw.query(
`SELECT "usernameCiphertext" AS u, "passwordCiphertext" AS p, "notesCiphertext" AS n FROM "EmployeePasswordSafeEntry" WHERE id = $1`,
[entryId],
);
const stored = rows[0] as { u: string; p: string; n: string };
for (const [field, plaintext, column] of [
["username", secrets.username, stored.u],
["password", secrets.password, stored.p],
["notes", secrets.notes, stored.n],
] as const) {
expect(column, `${field} ciphertext present`).toBeTruthy();
expect(column, `${field} is not stored in cleartext`).not.toContain(plaintext);
expect(column.startsWith("v1:"), `${field} uses the envelope format`).toBe(true);
}
expect(await safe.revealEntryValue({ tenantId: TENANT, vaultId: vault.id, entryId, userId: USER, field: "username" })).toBe(secrets.username);
expect(await safe.revealEntryValue({ tenantId: TENANT, vaultId: vault.id, entryId, userId: USER, field: "password" })).toBe(secrets.password);
expect(await safe.revealEntryValue({ tenantId: TENANT, vaultId: vault.id, entryId, userId: USER, field: "notes" })).toBe(secrets.notes);
const list = await safe.listEntries({ tenantId: TENANT, vaultId: vault.id, userId: USER });
const listed = list.find((entry) => entry.id === entryId);
expect(listed).toMatchObject({ hasUsername: true, hasPassword: true, hasNotes: true });
// The list view must never carry a secret value.
expect(JSON.stringify(list)).not.toContain(secrets.password);
});
it("a foreign tenant cannot decrypt this tenant's ciphertext (per-tenant DEK)", async () => {
const envelope = await import("@hivegrid/db/crypto/tenant-envelope.server");
const cipher = await envelope.encryptTenantField(TENANT, "tenant-scoped-secret");
// OTHER_TENANT gets its own DEK, so opening TENANT's envelope fails the GCM tag.
await expect(envelope.decryptTenantField(OTHER_TENANT, cipher)).rejects.toThrow();
});
});
@@ -0,0 +1,41 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import { deferredHrFieldCrypto, getHrFieldCrypto, HrCryptoNotProvisionedError, type HrFieldCrypto } from "./hrFieldCrypto.server";
// AK-P17a — the AD-8 per-tenant envelope (R-P5 `getTenantFieldCrypto`) is wired:
// `getHrFieldCrypto()` returns a real provider. The deferred binding is retained
// as a fail-closed scaffold (refuse to touch a sensitive value with a Klartext
// M002 message rather than silently store plaintext).
describe("hrFieldCrypto seam (bound to the R-P5 per-tenant envelope)", () => {
it("the deferred fail-closed scaffold rejects encrypt with a Klartext error", async () => {
await expect(deferredHrFieldCrypto.encrypt("tenant_1", "secret")).rejects.toBeInstanceOf(HrCryptoNotProvisionedError);
});
it("the deferred fail-closed scaffold rejects decrypt with a Klartext error", async () => {
await expect(deferredHrFieldCrypto.decrypt("tenant_1", "cipher")).rejects.toBeInstanceOf(HrCryptoNotProvisionedError);
});
it("the error carries an i18n message key, not a bare string", async () => {
const error = await deferredHrFieldCrypto.encrypt("tenant_1", "x").catch((caught) => caught);
expect(error).toBeInstanceOf(HrCryptoNotProvisionedError);
expect((error as HrCryptoNotProvisionedError).messageKey).toBe("hr.error.cryptoNotProvisioned");
});
it("getHrFieldCrypto returns a real provider, not the deferred scaffold", () => {
const crypto = getHrFieldCrypto();
expect(crypto).not.toBe(deferredHrFieldCrypto);
expect(typeof crypto.encrypt).toBe("function");
expect(typeof crypto.decrypt).toBe("function");
});
it("a working provider can be injected (proves the seam is swap-ready)", async () => {
const reversible: HrFieldCrypto = {
encrypt: (_tenantId, plaintext) => Promise.resolve(`enc:${plaintext}`),
decrypt: (_tenantId, ciphertext) => Promise.resolve(ciphertext.replace(/^enc:/, "")),
};
const cipher = await reversible.encrypt("tenant_1", "hunter2");
expect(cipher).toBe("enc:hunter2");
expect(await reversible.decrypt("tenant_1", cipher)).toBe("hunter2");
});
});
@@ -0,0 +1,71 @@
// P17 HR-Hub (AK-P17a) — field-level crypto SEAM for sensitive HR values.
//
// AD-8 mandates a PER-TENANT DEK / KMS envelope for the password-safe secrets and
// the employee emergency contact. This module is the seam every HR service goes
// through, so the underlying envelope provider can be swapped without touching the
// services.
//
// The per-tenant envelope landed with R-P5 (`getTenantFieldCrypto` in
// @hivegrid/db, AD-8). `getHrFieldCrypto()` now binds to it, which lights up the
// previously deferred sensitive-field paths (vault entry secrets + emergency
// contacts). `deferredHrFieldCrypto` / `HrCryptoNotProvisionedError` are retained
// as a fail-closed scaffold: a future binding may reject with a Klartext (M002)
// error rather than silently store plaintext if the master key is unconfigured.
// Service functions still accept an explicit `HrFieldCrypto` override so unit
// tests can inject a working in-memory provider.
//
// IMPORTANT: this is a server-only module (node:crypto-adjacent). Never import it
// from packages/ui-app or view-models.
import { getTenantFieldCrypto } from "@hivegrid/db/crypto/tenant-envelope.server";
/**
* Field-level crypto contract: encrypts/decrypts a single sensitive string for a
* given tenant. Implementations MUST scope the key material per tenant (AD-8) so
* a tenant deletion can crypto-shred only that tenant's data (M165).
*/
export interface HrFieldCrypto {
/** Encrypt `plaintext` for `tenantId`; returns a self-describing envelope string. */
encrypt(tenantId: string, plaintext: string): Promise<string>;
/** Decrypt an envelope string produced by {@link encrypt} for `tenantId`. */
decrypt(tenantId: string, ciphertext: string): Promise<string>;
}
/**
* Domain error raised when a sensitive HR value is read/written before the AD-8
* per-tenant envelope layer (separate ticket) is wired. Carries an i18n message
* key (M002 Klartext) so routes surface "this needs the encryption module" — not
* a bare 500.
*/
export class HrCryptoNotProvisionedError extends Error {
readonly messageKey = "hr.error.cryptoNotProvisioned";
constructor() {
super("hr.error.cryptoNotProvisioned");
this.name = "HrCryptoNotProvisionedError";
}
}
/**
* Production binding until the AD-8 envelope ticket lands: every call defers
* (throws {@link HrCryptoNotProvisionedError}). Swapping this for the real
* per-tenant envelope is the ONLY change that follow-up ticket makes here.
*/
export const deferredHrFieldCrypto: HrFieldCrypto = {
encrypt() {
return Promise.reject(new HrCryptoNotProvisionedError());
},
decrypt() {
return Promise.reject(new HrCryptoNotProvisionedError());
},
};
/**
* The crypto binding HR services use by default: the R-P5 per-tenant envelope
* provider (AD-8). `TenantFieldCrypto` is structurally identical to
* `HrFieldCrypto`, so it satisfies this contract directly. Service functions
* accept an explicit `HrFieldCrypto` override so unit tests can inject a working
* in-memory provider.
*/
export function getHrFieldCrypto(): HrFieldCrypto {
return getTenantFieldCrypto();
}
@@ -0,0 +1,320 @@
// P17 HR-Hub workflows (AK-P17b) — leave/vacation approval domain service.
//
// Multi-step approval state machine for vacation/leave requests:
// submitted ⇄ clarification → approved | rejected, or → withdrawn (requester).
// Only `approved` requests count as an absence and are exposed to the R-P9b
// plantafel conflict feed (listApprovedAbsencesForRange). NO React/UI imports.
// Every tenant access runs inside withTenantRLS(); every state transition writes
// an audit event (M001) and best-effort notifications (M011, fail-open).
//
// Tenant isolation is twofold (mirrors hrService.server.ts): app-level
// `where: { tenantId }` + the RLS policies from prisma/rls/hr-isolation.sql.
// CalendarEvent sync (P16/M25) is deferred — `calendarEventId` stays null and
// R-P9b reads the conflict feed directly from approved requests meanwhile.
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { createNotificationDelivery } from "@hivegrid/db/notifications.server";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { HrServiceError } from "./hrService.server";
const HR_AUDIT_MODULE = "hr";
const MAX_NOTE_LENGTH = 2000;
export type HrVacationRequestKind = "vacation" | "special_leave" | "unpaid_leave" | "overtime_compensation";
export type HrLeaveRequestStatus = "submitted" | "clarification" | "approved" | "rejected" | "withdrawn";
const VACATION_REQUEST_KINDS: readonly HrVacationRequestKind[] = ["vacation", "special_leave", "unpaid_leave", "overtime_compensation"];
export type VacationRequestRow = {
id: string;
tenantId: string;
employeeUserId: string;
requestKind: HrVacationRequestKind;
startDate: Date;
endDate: Date;
note: string | null;
status: HrLeaveRequestStatus;
assignedApproverUserId: string | null;
clarificationNote: string | null;
decidedByUserId: string | null;
decidedAt: Date | null;
decisionNote: string | null;
withdrawnAt: Date | null;
calendarEventId: string | null;
createdAt: Date;
updatedAt: Date;
};
/** A single approved absence (vacation OR sick) for the R-P9b conflict feed. */
export type ApprovedAbsence = {
source: "vacation" | "sick";
id: string;
employeeUserId: string;
startDate: Date;
/** Inclusive end of the blocked window (sick uses returnDate ?? expectedReturnDate ?? startDate). */
endDate: Date;
kind: string;
};
/** Fire-and-forget IN_APP notification; a delivery failure must never fail the
* triggering HR action (fail-open, mirrors appsEngineService). */
async function notifyQuiet(input: { tenantId: string; userId: string | null; messageKey: string; sourceKey: string; payloadMetadata?: Record<string, string> }): Promise<void> {
if (!input.userId) {
return;
}
await createNotificationDelivery({
tenantId: input.tenantId,
userId: input.userId,
channel: "IN_APP",
category: "hr",
messageKey: input.messageKey,
sourceKey: input.sourceKey,
payloadMetadata: input.payloadMetadata ?? null,
}).catch(() => undefined);
}
async function auditTransition(input: { tenantId: string; actorId: string; action: string; targetId: string; metadata?: Record<string, string> }): Promise<void> {
await createAuditEvent({
tenantId: input.tenantId,
actorId: input.actorId,
actorType: "user",
action: input.action,
targetType: "EmployeeVacationRequest",
targetId: input.targetId,
sourceModule: HR_AUDIT_MODULE,
outcome: "success",
metadata: input.metadata ?? null,
});
}
function normaliseNote(note: string | null | undefined): string | null {
const trimmed = note?.trim();
return trimmed ? trimmed.slice(0, MAX_NOTE_LENGTH) : null;
}
// --- Reads ----------------------------------------------------------------
/** List the caller's OWN vacation requests, newest first. */
export async function listOwnVacationRequests(tenantId: string, employeeUserId: string): Promise<VacationRequestRow[]> {
const rows = await withTenantRLS(tenantId, (tx) =>
tx.employeeVacationRequest.findMany({ where: { tenantId, employeeUserId }, orderBy: { createdAt: "desc" } }),
);
return rows as VacationRequestRow[];
}
/** List requests awaiting THIS approver's decision (submitted/clarification). */
export async function listForApprover(tenantId: string, approverUserId: string): Promise<VacationRequestRow[]> {
const rows = await withTenantRLS(tenantId, (tx) =>
tx.employeeVacationRequest.findMany({
where: { tenantId, assignedApproverUserId: approverUserId, status: { in: ["submitted", "clarification"] } },
orderBy: { startDate: "asc" },
}),
);
return rows as VacationRequestRow[];
}
/**
* R-P9b CONTRACT — approved absences overlapping [from, to]. Returns vacation
* AND sick-leave windows. Only `approved` vacation and non-cancelled sick
* reports count; submitted/rejected/withdrawn never block. This is the stable
* shape the plantafel conflict detection consumes.
*/
export async function listApprovedAbsencesForRange(tenantId: string, from: Date, to: Date): Promise<ApprovedAbsence[]> {
return withTenantRLS(tenantId, async (tx) => {
const vacations = await tx.employeeVacationRequest.findMany({
where: { tenantId, status: "approved", startDate: { lte: to }, endDate: { gte: from } },
select: { id: true, employeeUserId: true, startDate: true, endDate: true, requestKind: true },
});
const sick = await tx.employeeSickLeaveReport.findMany({
where: { tenantId, status: { not: "cancelled" }, startDate: { lte: to } },
select: { id: true, employeeUserId: true, startDate: true, returnDate: true, expectedReturnDate: true },
});
const out: ApprovedAbsence[] = vacations.map((v) => ({
source: "vacation",
id: v.id,
employeeUserId: v.employeeUserId,
startDate: v.startDate,
endDate: v.endDate,
kind: v.requestKind,
}));
for (const s of sick) {
const end = s.returnDate ?? s.expectedReturnDate ?? s.startDate;
if (end >= from) {
out.push({ source: "sick", id: s.id, employeeUserId: s.employeeUserId, startDate: s.startDate, endDate: end, kind: "sick" });
}
}
return out;
});
}
/**
* For an approver row, count OTHER approved vacation requests whose window
* overlaps the given request (the "vorhandener Urlaub" conflict hint). Plantafel
* (schedule) conflicts are added by R-P9b once it lands.
*/
export async function countOverlappingApproved(tenantId: string, request: Pick<VacationRequestRow, "id" | "startDate" | "endDate">): Promise<number> {
return withTenantRLS(tenantId, (tx) =>
tx.employeeVacationRequest.count({
where: {
tenantId,
status: "approved",
id: { not: request.id },
startDate: { lte: request.endDate },
endDate: { gte: request.startDate },
},
}),
);
}
async function getRequestOrThrow(tenantId: string, requestId: string): Promise<VacationRequestRow> {
const row = await withTenantRLS(tenantId, (tx) => tx.employeeVacationRequest.findFirst({ where: { id: requestId, tenantId } }));
if (!row) {
throw new CatalogError(foundationErrors.notFound, { requestId });
}
return row as VacationRequestRow;
}
/** Load a request the caller is allowed to see (own, assigned approver, or has
* the approve capability). 404 otherwise (never 403). */
export async function getRequestForUser(input: { tenantId: string; requestId: string; userId: string; canApproveAny: boolean }): Promise<VacationRequestRow> {
const row = await getRequestOrThrow(input.tenantId, input.requestId);
const isOwner = row.employeeUserId === input.userId;
const isApprover = row.assignedApproverUserId === input.userId || input.canApproveAny;
if (!isOwner && !isApprover) {
throw new CatalogError(foundationErrors.notFound, { requestId: input.requestId });
}
return row;
}
// --- Writes / state machine ----------------------------------------------
export type SubmitVacationInput = {
tenantId: string;
employeeUserId: string;
requestKind: HrVacationRequestKind;
startDate: Date;
endDate: Date;
note?: string | null;
assignedApproverUserId?: string | null;
isDemoData?: boolean;
};
/** Submit a new vacation request (status = submitted). Notifies the approver. */
export async function submitVacationRequest(input: SubmitVacationInput): Promise<VacationRequestRow> {
if (!VACATION_REQUEST_KINDS.includes(input.requestKind)) {
throw new HrServiceError("hr.error.leaveKindInvalid");
}
if (input.endDate < input.startDate) {
throw new HrServiceError("hr.error.leaveRangeInvalid");
}
const created = (await withTenantRLS(input.tenantId, (tx) =>
tx.employeeVacationRequest.create({
data: {
tenantId: input.tenantId,
employeeUserId: input.employeeUserId,
requestKind: input.requestKind,
startDate: input.startDate,
endDate: input.endDate,
note: normaliseNote(input.note),
status: "submitted",
assignedApproverUserId: input.assignedApproverUserId ?? null,
isDemoData: input.isDemoData ?? false,
},
}),
)) as VacationRequestRow;
await auditTransition({ tenantId: input.tenantId, actorId: input.employeeUserId, action: "HR_LEAVE_SUBMIT", targetId: created.id, metadata: { requestKind: input.requestKind } });
await notifyQuiet({
tenantId: input.tenantId,
userId: created.assignedApproverUserId,
messageKey: "hr.notify.leave.submitted",
sourceKey: `hr-leave-submit:${created.id}`,
payloadMetadata: { requestId: created.id },
});
return created;
}
/** Common guard: a request must be in a decidable state and the caller must be
* its assigned approver or hold the approve capability. */
async function loadDecidable(input: { tenantId: string; requestId: string; deciderUserId: string; canApproveAny: boolean }): Promise<VacationRequestRow> {
const row = await getRequestOrThrow(input.tenantId, input.requestId);
const isApprover = row.assignedApproverUserId === input.deciderUserId || input.canApproveAny;
if (!isApprover) {
throw new CatalogError(foundationErrors.notFound, { requestId: input.requestId });
}
if (row.status !== "submitted" && row.status !== "clarification") {
throw new HrServiceError("hr.error.leaveNotDecidable");
}
return row;
}
export async function approveRequest(input: { tenantId: string; requestId: string; deciderUserId: string; canApproveAny: boolean; decisionNote?: string | null }): Promise<void> {
const row = await loadDecidable(input);
await withTenantRLS(input.tenantId, (tx) =>
tx.employeeVacationRequest.update({
where: { id: row.id },
data: { status: "approved", decidedByUserId: input.deciderUserId, decidedAt: new Date(), decisionNote: normaliseNote(input.decisionNote) },
}),
);
await auditTransition({ tenantId: input.tenantId, actorId: input.deciderUserId, action: "HR_LEAVE_APPROVE", targetId: row.id });
await notifyQuiet({ tenantId: input.tenantId, userId: row.employeeUserId, messageKey: "hr.notify.leave.approved", sourceKey: `hr-leave-approve:${row.id}`, payloadMetadata: { requestId: row.id } });
}
export async function rejectRequest(input: { tenantId: string; requestId: string; deciderUserId: string; canApproveAny: boolean; decisionNote?: string | null }): Promise<void> {
const row = await loadDecidable(input);
await withTenantRLS(input.tenantId, (tx) =>
tx.employeeVacationRequest.update({
where: { id: row.id },
data: { status: "rejected", decidedByUserId: input.deciderUserId, decidedAt: new Date(), decisionNote: normaliseNote(input.decisionNote) },
}),
);
await auditTransition({ tenantId: input.tenantId, actorId: input.deciderUserId, action: "HR_LEAVE_REJECT", targetId: row.id });
await notifyQuiet({ tenantId: input.tenantId, userId: row.employeeUserId, messageKey: "hr.notify.leave.rejected", sourceKey: `hr-leave-reject:${row.id}`, payloadMetadata: { requestId: row.id } });
}
export async function requestClarification(input: { tenantId: string; requestId: string; deciderUserId: string; canApproveAny: boolean; question: string }): Promise<void> {
const row = await loadDecidable(input);
const question = normaliseNote(input.question);
if (!question) {
throw new HrServiceError("hr.error.leaveClarificationEmpty");
}
await withTenantRLS(input.tenantId, (tx) =>
tx.employeeVacationRequest.update({ where: { id: row.id }, data: { status: "clarification", clarificationNote: question } }),
);
await auditTransition({ tenantId: input.tenantId, actorId: input.deciderUserId, action: "HR_LEAVE_CLARIFY", targetId: row.id });
await notifyQuiet({ tenantId: input.tenantId, userId: row.employeeUserId, messageKey: "hr.notify.leave.clarification", sourceKey: `hr-leave-clarify:${row.id}`, payloadMetadata: { requestId: row.id } });
}
/** Requester replies to a clarification → back to `submitted` for re-decision. */
export async function replyToClarification(input: { tenantId: string; requestId: string; employeeUserId: string; reply: string }): Promise<void> {
const row = await getRequestOrThrow(input.tenantId, input.requestId);
if (row.employeeUserId !== input.employeeUserId) {
throw new CatalogError(foundationErrors.notFound, { requestId: input.requestId });
}
if (row.status !== "clarification") {
throw new HrServiceError("hr.error.leaveNotClarifiable");
}
const reply = normaliseNote(input.reply);
const merged = reply ? `${row.note ? `${row.note}\n` : ""}↪ ${reply}` : row.note;
await withTenantRLS(input.tenantId, (tx) =>
tx.employeeVacationRequest.update({ where: { id: row.id }, data: { status: "submitted", note: merged?.slice(0, MAX_NOTE_LENGTH) ?? null } }),
);
await auditTransition({ tenantId: input.tenantId, actorId: input.employeeUserId, action: "HR_LEAVE_REPLY", targetId: row.id });
await notifyQuiet({ tenantId: input.tenantId, userId: row.assignedApproverUserId, messageKey: "hr.notify.leave.replied", sourceKey: `hr-leave-reply:${row.id}:${row.updatedAt.getTime()}`, payloadMetadata: { requestId: row.id } });
}
/** Requester withdraws a still-open request. */
export async function withdrawRequest(input: { tenantId: string; requestId: string; employeeUserId: string }): Promise<void> {
const row = await getRequestOrThrow(input.tenantId, input.requestId);
if (row.employeeUserId !== input.employeeUserId) {
throw new CatalogError(foundationErrors.notFound, { requestId: input.requestId });
}
if (row.status !== "submitted" && row.status !== "clarification") {
throw new HrServiceError("hr.error.leaveNotWithdrawable");
}
await withTenantRLS(input.tenantId, (tx) =>
tx.employeeVacationRequest.update({ where: { id: row.id }, data: { status: "withdrawn", withdrawnAt: new Date() } }),
);
await auditTransition({ tenantId: input.tenantId, actorId: input.employeeUserId, action: "HR_LEAVE_WITHDRAW", targetId: row.id });
await notifyQuiet({ tenantId: input.tenantId, userId: row.assignedApproverUserId, messageKey: "hr.notify.leave.withdrawn", sourceKey: `hr-leave-withdraw:${row.id}`, payloadMetadata: { requestId: row.id } });
}
@@ -0,0 +1,428 @@
// P17 HR-Hub core (AK-P17a) §S4 — encrypted team password-safe service.
//
// Security model (designer brief P17 + DoD #3):
// - A vault is visible ONLY to a user holding an EmployeePasswordSafeAccess row
// (read/write/admin) — tenant membership alone grants nothing. The tenant-wide
// admin view (/admin/hr/password-safe, gated by hr.passwordsafe.admin) can
// MANAGE vaults but NEVER sees entry contents without an access row.
// - Entry SECRET VALUES (username/password/notes) are ENVELOPE-ENCRYPTED (AD-8,
// via the hrFieldCrypto seam) and are NEVER selected into a list. Only an
// explicit, access-checked + AUDITED reveal decrypts a single value on demand.
// - DSGVO export decrypts a whole vault for the authorised user and is audited.
//
// RLS-ready (mirrors hrService): every tenant access runs inside withTenantRLS();
// internal composition reuses the active transaction via *WithTx helpers.
//
// Until the AD-8 envelope ticket lands, the crypto seam's production binding
// throws HrCryptoNotProvisionedError (M002 Klartext) — so creating an entry with
// secrets or revealing one surfaces "encryption module not provisioned" rather
// than storing plaintext. All NON-crypto paths (vault/entry/access structure,
// access checks, never-list-values, audit, listing) ship and are testable by
// injecting a working crypto provider.
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import { getHrFieldCrypto, type HrFieldCrypto } from "./hrFieldCrypto.server";
import { HrServiceError } from "./hrService.server";
const HR_AUDIT_MODULE = "hr";
export type PasswordSafePermissionLevel = "read" | "write" | "admin";
export type PasswordSafeSecretField = "username" | "password" | "notes";
const LEVEL_RANK: Record<PasswordSafePermissionLevel, number> = { read: 1, write: 2, admin: 3 };
function meetsLevel(have: PasswordSafePermissionLevel, need: PasswordSafePermissionLevel): boolean {
return LEVEL_RANK[have] >= LEVEL_RANK[need];
}
// --- Vault rows -----------------------------------------------------------
export type VaultRow = {
id: string;
tenantId: string;
name: string;
description: string | null;
createdByUserId: string;
isDemoData: boolean;
createdAt: Date;
updatedAt: Date;
archivedAt: Date | null;
};
/** An entry as shown in a list: titles/tags/url ONLY — secret values omitted,
* replaced by booleans signalling which fields hold a value. */
export type EntryListRow = {
id: string;
vaultId: string;
title: string;
tags: string[];
url: string | null;
hasUsername: boolean;
hasPassword: boolean;
hasNotes: boolean;
updatedAt: Date;
};
// --- Access resolution ----------------------------------------------------
async function resolveVaultAccessWithTx(tx: TenantRlsClient, tenantId: string, vaultId: string, userId: string): Promise<PasswordSafePermissionLevel | null> {
const access = await tx.employeePasswordSafeAccess.findFirst({
where: { tenantId, vaultId, userId },
select: { permissionLevel: true },
});
return (access?.permissionLevel as PasswordSafePermissionLevel | undefined) ?? null;
}
/** The caller's access level on a vault (or null if none). */
export async function resolveVaultAccess(tenantId: string, vaultId: string, userId: string): Promise<PasswordSafePermissionLevel | null> {
return withTenantRLS(tenantId, (tx) => resolveVaultAccessWithTx(tx, tenantId, vaultId, userId));
}
/** Load a vault the caller has access to (id + name + own access level), or null. */
export async function getVaultForUser(tenantId: string, vaultId: string, userId: string): Promise<{ id: string; name: string; accessLevel: PasswordSafePermissionLevel } | null> {
return withTenantRLS(tenantId, async (tx) => {
const vault = await tx.employeePasswordSafeVault.findFirst({ where: { id: vaultId, tenantId, archivedAt: null }, select: { id: true, name: true } });
if (!vault) {
return null;
}
const level = await resolveVaultAccessWithTx(tx, tenantId, vaultId, userId);
if (!level) {
return null;
}
return { id: vault.id, name: vault.name, accessLevel: level };
});
}
/** Load a vault and assert the caller has at least `need` access, else 404. */
async function requireVaultWithAccessWithTx(
tx: TenantRlsClient,
tenantId: string,
vaultId: string,
userId: string,
need: PasswordSafePermissionLevel,
): Promise<{ vault: VaultRow; level: PasswordSafePermissionLevel }> {
const vault = await tx.employeePasswordSafeVault.findFirst({ where: { id: vaultId, tenantId, archivedAt: null } });
if (!vault) {
throw new CatalogError(foundationErrors.notFound, { vaultId });
}
const level = await resolveVaultAccessWithTx(tx, tenantId, vaultId, userId);
// No access (or below the required level) reads as "not found" (A.5.3).
if (!level || !meetsLevel(level, need)) {
throw new CatalogError(foundationErrors.notFound, { vaultId });
}
return { vault: vault as VaultRow, level };
}
// --- Vault listing & management -------------------------------------------
/** Vaults the caller may see (has an access row for), newest first. */
export async function listAccessibleVaults(tenantId: string, userId: string): Promise<VaultRow[]> {
const rows = await withTenantRLS(tenantId, (tx) =>
tx.employeePasswordSafeVault.findMany({
where: { tenantId, archivedAt: null, access: { some: { tenantId, userId } } },
orderBy: { name: "asc" },
}),
);
return rows as VaultRow[];
}
/** Tenant-wide vault list for the admin view — metadata only, NO content access.
* The route gates this behind hr.passwordsafe.admin. */
export async function adminListAllVaults(tenantId: string, opts?: { includeArchived?: boolean }): Promise<Array<VaultRow & { entryCount: number; accessCount: number }>> {
return withTenantRLS(tenantId, async (tx) => {
const vaults = await tx.employeePasswordSafeVault.findMany({
where: { tenantId, ...(opts?.includeArchived ? {} : { archivedAt: null }) },
orderBy: { name: "asc" },
});
const withCounts = await Promise.all(
vaults.map(async (vault) => {
const [entryCount, accessCount] = await Promise.all([
tx.employeePasswordSafeEntry.count({ where: { tenantId, vaultId: vault.id, archivedAt: null } }),
tx.employeePasswordSafeAccess.count({ where: { tenantId, vaultId: vault.id } }),
]);
return { ...(vault as VaultRow), entryCount, accessCount };
}),
);
return withCounts;
});
}
export async function createVault(input: { tenantId: string; name: string; description?: string | null; createdByUserId: string; isDemoData?: boolean }): Promise<VaultRow> {
const name = input.name.trim();
if (!name) {
throw new HrServiceError("hr.error.vaultNameRequired");
}
return withTenantRLS(input.tenantId, async (tx) => {
const vault = await tx.employeePasswordSafeVault.create({
data: { tenantId: input.tenantId, name, description: input.description ?? null, createdByUserId: input.createdByUserId, isDemoData: input.isDemoData ?? false },
});
// Creator gets admin access by default so they can manage the new vault.
await tx.employeePasswordSafeAccess.create({
data: { tenantId: input.tenantId, vaultId: vault.id, userId: input.createdByUserId, permissionLevel: "admin", grantedByUserId: input.createdByUserId },
});
return vault as VaultRow;
});
}
/** Archive a vault. Allowed for a vault-admin OR a tenant password-safe admin. */
export async function archiveVault(input: { tenantId: string; vaultId: string; userId: string; isTenantPasswordSafeAdmin: boolean }): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
if (!input.isTenantPasswordSafeAdmin) {
await requireVaultWithAccessWithTx(tx, input.tenantId, input.vaultId, input.userId, "admin");
} else {
const exists = await tx.employeePasswordSafeVault.findFirst({ where: { id: input.vaultId, tenantId: input.tenantId }, select: { id: true } });
if (!exists) {
throw new CatalogError(foundationErrors.notFound, { vaultId: input.vaultId });
}
}
await tx.employeePasswordSafeVault.updateMany({ where: { id: input.vaultId, tenantId: input.tenantId }, data: { archivedAt: new Date() } });
});
}
// --- Access management -----------------------------------------------------
export async function grantAccess(input: {
tenantId: string;
vaultId: string;
targetUserId: string;
permissionLevel: PasswordSafePermissionLevel;
actorUserId: string;
isTenantPasswordSafeAdmin: boolean;
}): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
if (!input.isTenantPasswordSafeAdmin) {
await requireVaultWithAccessWithTx(tx, input.tenantId, input.vaultId, input.actorUserId, "admin");
}
await tx.employeePasswordSafeAccess.upsert({
where: { vaultId_userId: { vaultId: input.vaultId, userId: input.targetUserId } },
update: { permissionLevel: input.permissionLevel, grantedByUserId: input.actorUserId },
create: { tenantId: input.tenantId, vaultId: input.vaultId, userId: input.targetUserId, permissionLevel: input.permissionLevel, grantedByUserId: input.actorUserId },
});
});
}
export async function revokeAccess(input: { tenantId: string; vaultId: string; targetUserId: string; actorUserId: string; isTenantPasswordSafeAdmin: boolean }): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
if (!input.isTenantPasswordSafeAdmin) {
await requireVaultWithAccessWithTx(tx, input.tenantId, input.vaultId, input.actorUserId, "admin");
}
await tx.employeePasswordSafeAccess.deleteMany({ where: { tenantId: input.tenantId, vaultId: input.vaultId, userId: input.targetUserId } });
});
}
export type VaultAccessRow = { userId: string; permissionLevel: PasswordSafePermissionLevel; grantedByUserId: string };
export async function listVaultAccess(input: { tenantId: string; vaultId: string; userId: string; isTenantPasswordSafeAdmin: boolean }): Promise<VaultAccessRow[]> {
return withTenantRLS(input.tenantId, async (tx) => {
if (!input.isTenantPasswordSafeAdmin) {
await requireVaultWithAccessWithTx(tx, input.tenantId, input.vaultId, input.userId, "admin");
}
const rows = await tx.employeePasswordSafeAccess.findMany({
where: { tenantId: input.tenantId, vaultId: input.vaultId },
select: { userId: true, permissionLevel: true, grantedByUserId: true },
orderBy: { createdAt: "asc" },
});
return rows as VaultAccessRow[];
});
}
// --- Entries: list (NEVER values) ------------------------------------------
/** List a vault's entries WITHOUT secret values (read access required). */
export async function listEntries(input: { tenantId: string; vaultId: string; userId: string }): Promise<EntryListRow[]> {
return withTenantRLS(input.tenantId, async (tx) => {
await requireVaultWithAccessWithTx(tx, input.tenantId, input.vaultId, input.userId, "read");
const entries = await tx.employeePasswordSafeEntry.findMany({
where: { tenantId: input.tenantId, vaultId: input.vaultId, archivedAt: null },
// NOTE: ciphertext columns are deliberately NOT selected here.
select: { id: true, vaultId: true, title: true, tags: true, url: true, usernameCiphertext: true, passwordCiphertext: true, notesCiphertext: true, updatedAt: true },
orderBy: { title: "asc" },
});
return entries.map((entry) => ({
id: entry.id,
vaultId: entry.vaultId,
title: entry.title,
tags: entry.tags,
url: entry.url,
hasUsername: entry.usernameCiphertext != null,
hasPassword: entry.passwordCiphertext != null,
hasNotes: entry.notesCiphertext != null,
updatedAt: entry.updatedAt,
}));
});
}
// --- Entries: create / update (encrypt via seam) ---------------------------
export type EntrySecretInput = { username?: string | null; password?: string | null; notes?: string | null };
async function encryptSecrets(
tenantId: string,
secrets: EntrySecretInput,
crypto: HrFieldCrypto,
): Promise<{ usernameCiphertext?: string | null; passwordCiphertext?: string | null; notesCiphertext?: string | null }> {
const out: { usernameCiphertext?: string | null; passwordCiphertext?: string | null; notesCiphertext?: string | null } = {};
if (secrets.username !== undefined) {
out.usernameCiphertext = secrets.username ? await crypto.encrypt(tenantId, secrets.username) : null;
}
if (secrets.password !== undefined) {
out.passwordCiphertext = secrets.password ? await crypto.encrypt(tenantId, secrets.password) : null;
}
if (secrets.notes !== undefined) {
out.notesCiphertext = secrets.notes ? await crypto.encrypt(tenantId, secrets.notes) : null;
}
return out;
}
export async function createEntry(
input: { tenantId: string; vaultId: string; userId: string; title: string; tags?: string[]; url?: string | null; secrets: EntrySecretInput; isDemoData?: boolean },
crypto: HrFieldCrypto = getHrFieldCrypto(),
): Promise<{ id: string }> {
const title = input.title.trim();
if (!title) {
throw new HrServiceError("hr.error.entryTitleRequired");
}
return withTenantRLS(input.tenantId, async (tx) => {
await requireVaultWithAccessWithTx(tx, input.tenantId, input.vaultId, input.userId, "write");
const ciphertext = await encryptSecrets(input.tenantId, input.secrets, crypto);
const created = await tx.employeePasswordSafeEntry.create({
data: {
tenantId: input.tenantId,
vaultId: input.vaultId,
title,
tags: input.tags ?? [],
url: input.url ?? null,
usernameCiphertext: ciphertext.usernameCiphertext ?? null,
passwordCiphertext: ciphertext.passwordCiphertext ?? null,
notesCiphertext: ciphertext.notesCiphertext ?? null,
isDemoData: input.isDemoData ?? false,
},
select: { id: true },
});
return created;
});
}
export async function updateEntry(
input: { tenantId: string; vaultId: string; entryId: string; userId: string; title?: string; tags?: string[]; url?: string | null; secrets?: EntrySecretInput },
crypto: HrFieldCrypto = getHrFieldCrypto(),
): Promise<void> {
if (input.title !== undefined && !input.title.trim()) {
throw new HrServiceError("hr.error.entryTitleRequired");
}
await withTenantRLS(input.tenantId, async (tx) => {
await requireVaultWithAccessWithTx(tx, input.tenantId, input.vaultId, input.userId, "write");
const entry = await tx.employeePasswordSafeEntry.findFirst({ where: { id: input.entryId, tenantId: input.tenantId, vaultId: input.vaultId }, select: { id: true } });
if (!entry) {
throw new CatalogError(foundationErrors.notFound, { entryId: input.entryId });
}
const ciphertext = input.secrets ? await encryptSecrets(input.tenantId, input.secrets, crypto) : {};
await tx.employeePasswordSafeEntry.updateMany({
where: { id: input.entryId, tenantId: input.tenantId, vaultId: input.vaultId },
data: {
...(input.title !== undefined ? { title: input.title.trim() } : {}),
...(input.tags !== undefined ? { tags: input.tags } : {}),
...(input.url !== undefined ? { url: input.url } : {}),
...ciphertext,
},
});
});
}
export async function archiveEntry(input: { tenantId: string; vaultId: string; entryId: string; userId: string }): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
await requireVaultWithAccessWithTx(tx, input.tenantId, input.vaultId, input.userId, "write");
await tx.employeePasswordSafeEntry.updateMany({ where: { id: input.entryId, tenantId: input.tenantId, vaultId: input.vaultId }, data: { archivedAt: new Date() } });
});
}
// --- Reveal (decrypt single value) + audit ---------------------------------
/**
* Reveal ONE secret field of ONE entry. Requires read access. Writes a
* confidential audit event BEFORE decrypting/returning, so the reveal is logged
* even if decryption then fails. This is the audited, on-demand path the UI uses
* for "show"/"copy" (the UI clears the clipboard after 30s).
*/
export async function revealEntryValue(
input: { tenantId: string; vaultId: string; entryId: string; userId: string; field: PasswordSafeSecretField },
crypto: HrFieldCrypto = getHrFieldCrypto(),
): Promise<string | null> {
return withTenantRLS(input.tenantId, async (tx) => {
await requireVaultWithAccessWithTx(tx, input.tenantId, input.vaultId, input.userId, "read");
const entry = await tx.employeePasswordSafeEntry.findFirst({
where: { id: input.entryId, tenantId: input.tenantId, vaultId: input.vaultId, archivedAt: null },
select: { id: true, usernameCiphertext: true, passwordCiphertext: true, notesCiphertext: true },
});
if (!entry) {
throw new CatalogError(foundationErrors.notFound, { entryId: input.entryId });
}
const ciphertext =
input.field === "username" ? entry.usernameCiphertext : input.field === "password" ? entry.passwordCiphertext : entry.notesCiphertext;
await createAuditEvent({
tenantId: input.tenantId,
actorId: input.userId,
actorType: "user",
action: "HR_PASSWORD_SAFE_REVEAL",
targetType: "EmployeePasswordSafeEntry",
targetId: input.entryId,
sourceModule: HR_AUDIT_MODULE,
dataSensitivity: "confidential",
outcome: "success",
metadata: { vaultId: input.vaultId, field: input.field },
});
if (ciphertext == null) {
return null;
}
return crypto.decrypt(input.tenantId, ciphertext);
});
}
// --- DSGVO export ----------------------------------------------------------
export type ExportedEntry = { title: string; tags: string[]; url: string | null; username: string | null; password: string | null; notes: string | null };
/**
* Decrypt a whole vault for an authorised user (read access) — DSGVO export.
* Audited as a confidential bulk reveal.
*/
export async function exportVault(
input: { tenantId: string; vaultId: string; userId: string },
crypto: HrFieldCrypto = getHrFieldCrypto(),
): Promise<{ vaultName: string; entries: ExportedEntry[] }> {
return withTenantRLS(input.tenantId, async (tx) => {
const { vault } = await requireVaultWithAccessWithTx(tx, input.tenantId, input.vaultId, input.userId, "read");
const entries = await tx.employeePasswordSafeEntry.findMany({
where: { tenantId: input.tenantId, vaultId: input.vaultId, archivedAt: null },
orderBy: { title: "asc" },
});
await createAuditEvent({
tenantId: input.tenantId,
actorId: input.userId,
actorType: "user",
action: "HR_PASSWORD_SAFE_EXPORT",
targetType: "EmployeePasswordSafeVault",
targetId: input.vaultId,
sourceModule: HR_AUDIT_MODULE,
dataSensitivity: "confidential",
regulatoryScope: ["gdpr"],
outcome: "success",
metadata: { entryCount: entries.length },
});
const exported: ExportedEntry[] = await Promise.all(
entries.map(async (entry) => ({
title: entry.title,
tags: entry.tags,
url: entry.url,
username: entry.usernameCiphertext ? await crypto.decrypt(input.tenantId, entry.usernameCiphertext) : null,
password: entry.passwordCiphertext ? await crypto.decrypt(input.tenantId, entry.passwordCiphertext) : null,
notes: entry.notesCiphertext ? await crypto.decrypt(input.tenantId, entry.notesCiphertext) : null,
})),
);
return { vaultName: vault.name, entries: exported };
});
}
@@ -0,0 +1,157 @@
// P17 HR-Hub workflows (AK-P17b) — payslip domain service.
//
// Employees read their own payslips (opening a payslip marks it read AND writes
// a per-read audit event — payslips are confidential). HR uploads payslips
// singly or in bulk; the bulk auto-match itself is a pure function
// (matchPayslipFile in @hivegrid/view-models) the route runs over the resolved
// employee list — this service only persists the confirmed assignments.
// Every tenant access runs inside withTenantRLS().
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { HrServiceError } from "./hrService.server";
const HR_AUDIT_MODULE = "hr";
export type PayslipRow = {
id: string;
tenantId: string;
employeeUserId: string;
uploadedByUserId: string;
periodYear: number;
periodMonth: number;
fileId: string;
isRead: boolean;
readAt: Date | null;
createdAt: Date;
updatedAt: Date;
archivedAt: Date | null;
};
function assertPeriod(year: number, month: number): void {
if (!Number.isInteger(year) || year < 2000 || year > 2100) throw new HrServiceError("hr.error.payslipPeriodInvalid");
if (!Number.isInteger(month) || month < 1 || month > 12) throw new HrServiceError("hr.error.payslipPeriodInvalid");
}
/** List the caller's own payslips, newest period first. */
export async function listOwnPayslips(tenantId: string, employeeUserId: string): Promise<PayslipRow[]> {
const rows = await withTenantRLS(tenantId, (tx) =>
tx.employeePayslip.findMany({ where: { tenantId, employeeUserId, archivedAt: null }, orderBy: [{ periodYear: "desc" }, { periodMonth: "desc" }] }),
);
return rows as PayslipRow[];
}
/** HR view of all payslips (optionally for one employee). */
export async function adminListPayslips(tenantId: string, opts?: { employeeUserId?: string }): Promise<PayslipRow[]> {
const rows = await withTenantRLS(tenantId, (tx) =>
tx.employeePayslip.findMany({
where: { tenantId, archivedAt: null, ...(opts?.employeeUserId ? { employeeUserId: opts.employeeUserId } : {}) },
orderBy: [{ periodYear: "desc" }, { periodMonth: "desc" }],
}),
);
return rows as PayslipRow[];
}
/** Employees with their personal number, for the bulk auto-match (names are
* resolved separately via resolveUserLabels at the route layer). */
export async function listEmployeesForMatch(tenantId: string): Promise<Array<{ userId: string; personalNumber: string | null }>> {
return withTenantRLS(tenantId, (tx) => tx.hrEmployeeProfile.findMany({ where: { tenantId }, select: { userId: true, personalNumber: true } }));
}
async function getPayslipOrThrow(tenantId: string, payslipId: string): Promise<PayslipRow> {
const row = await withTenantRLS(tenantId, (tx) => tx.employeePayslip.findFirst({ where: { id: payslipId, tenantId, archivedAt: null } }));
if (!row) throw new CatalogError(foundationErrors.notFound, { payslipId });
return row as PayslipRow;
}
/**
* Resolve the File id of a payslip the caller may open (their own, or any if
* `canReadAll`), marking it read on first open and writing a per-read audit
* event. Returns the fileId for the route to stream.
*/
export async function openPayslip(input: { tenantId: string; payslipId: string; userId: string; canReadAll: boolean }): Promise<string> {
const row = await getPayslipOrThrow(input.tenantId, input.payslipId);
if (row.employeeUserId !== input.userId && !input.canReadAll) {
throw new CatalogError(foundationErrors.notFound, { payslipId: input.payslipId });
}
if (!row.isRead && row.employeeUserId === input.userId) {
await withTenantRLS(input.tenantId, (tx) => tx.employeePayslip.update({ where: { id: row.id }, data: { isRead: true, readAt: new Date() } }));
}
await createAuditEvent({
tenantId: input.tenantId,
actorId: input.userId,
actorType: "user",
action: "HR_PAYSLIP_READ",
targetType: "EmployeePayslip",
targetId: row.id,
sourceModule: HR_AUDIT_MODULE,
dataSensitivity: "confidential",
outcome: "success",
metadata: { period: `${row.periodYear}-${String(row.periodMonth).padStart(2, "0")}` },
});
return row.fileId;
}
export type CreatePayslipInput = {
tenantId: string;
employeeUserId: string;
uploadedByUserId: string;
periodYear: number;
periodMonth: number;
fileId: string;
isDemoData?: boolean;
};
/** Create (or replace) one payslip for an employee + period. Audited. */
export async function createPayslip(input: CreatePayslipInput): Promise<PayslipRow> {
assertPeriod(input.periodYear, input.periodMonth);
const created = (await withTenantRLS(input.tenantId, (tx) =>
tx.employeePayslip.upsert({
where: { tenantId_employeeUserId_periodYear_periodMonth: { tenantId: input.tenantId, employeeUserId: input.employeeUserId, periodYear: input.periodYear, periodMonth: input.periodMonth } },
update: { fileId: input.fileId, uploadedByUserId: input.uploadedByUserId, isRead: false, readAt: null, archivedAt: null },
create: {
tenantId: input.tenantId,
employeeUserId: input.employeeUserId,
uploadedByUserId: input.uploadedByUserId,
periodYear: input.periodYear,
periodMonth: input.periodMonth,
fileId: input.fileId,
isDemoData: input.isDemoData ?? false,
},
}),
)) as PayslipRow;
await createAuditEvent({
tenantId: input.tenantId,
actorId: input.uploadedByUserId,
actorType: "user",
action: "HR_PAYSLIP_UPLOAD",
targetType: "EmployeePayslip",
targetId: created.id,
sourceModule: HR_AUDIT_MODULE,
outcome: "success",
metadata: { employeeUserId: input.employeeUserId },
});
return created;
}
export type BulkAssignment = { employeeUserId: string; periodYear: number; periodMonth: number; fileId: string };
/** Persist confirmed bulk assignments (one payslip per assignment). Returns the
* count created. The match preview itself is computed by matchPayslipFile in the
* route before the admin confirms. */
export async function confirmBulkAssignments(input: { tenantId: string; uploadedByUserId: string; assignments: readonly BulkAssignment[] }): Promise<number> {
let count = 0;
for (const assignment of input.assignments) {
await createPayslip({
tenantId: input.tenantId,
employeeUserId: assignment.employeeUserId,
uploadedByUserId: input.uploadedByUserId,
periodYear: assignment.periodYear,
periodMonth: assignment.periodMonth,
fileId: assignment.fileId,
});
count += 1;
}
return count;
}
@@ -0,0 +1,204 @@
// P17 HR-Hub workflows (AK-P17b) — generic HR requests (expense/hardware/
// training/reference) with reusable templates.
//
// Until the M05 form renderer (AK-P16c) lands, the request payload is captured
// as a JSON string in `details` (transitional form) and `formSubmissionId` is
// wired in later. Approval mirrors the leave state machine. Every tenant access
// runs inside withTenantRLS(); transitions are audited (M001) and notify the
// counterpart (M011, fail-open).
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { createNotificationDelivery } from "@hivegrid/db/notifications.server";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { HrServiceError } from "./hrService.server";
const HR_AUDIT_MODULE = "hr";
export type HrRequestKind = "expense" | "hardware" | "training" | "reference";
export type HrRequestStatus = "submitted" | "clarification" | "approved" | "rejected" | "withdrawn";
const REQUEST_KINDS: readonly HrRequestKind[] = ["expense", "hardware", "training", "reference"];
export type RequestTemplateRow = {
id: string;
tenantId: string;
title: string;
requestKind: HrRequestKind;
description: string | null;
defaultApproverUserId: string | null;
linkedFormId: string | null;
isActive: boolean;
createdAt: Date;
updatedAt: Date;
archivedAt: Date | null;
};
export type RequestRow = {
id: string;
tenantId: string;
employeeUserId: string;
templateId: string | null;
requestKind: HrRequestKind;
title: string;
details: string | null;
formSubmissionId: string | null;
status: HrRequestStatus;
assignedApproverUserId: string | null;
clarificationNote: string | null;
decidedByUserId: string | null;
decidedAt: Date | null;
decisionNote: string | null;
withdrawnAt: Date | null;
createdAt: Date;
updatedAt: Date;
archivedAt: Date | null;
};
async function notifyQuiet(input: { tenantId: string; userId: string | null; messageKey: string; sourceKey: string }): Promise<void> {
if (!input.userId) return;
await createNotificationDelivery({ tenantId: input.tenantId, userId: input.userId, channel: "IN_APP", category: "hr", messageKey: input.messageKey, sourceKey: input.sourceKey }).catch(() => undefined);
}
async function audit(input: { tenantId: string; actorId: string; action: string; targetId: string }): Promise<void> {
await createAuditEvent({ tenantId: input.tenantId, actorId: input.actorId, actorType: "user", action: input.action, targetType: "HrRequest", targetId: input.targetId, sourceModule: HR_AUDIT_MODULE, outcome: "success" });
}
// --- Templates ------------------------------------------------------------
export async function listTemplates(tenantId: string, opts?: { includeArchived?: boolean }): Promise<RequestTemplateRow[]> {
const rows = await withTenantRLS(tenantId, (tx) =>
tx.hrRequestTemplate.findMany({ where: { tenantId, ...(opts?.includeArchived ? {} : { archivedAt: null }) }, orderBy: { title: "asc" } }),
);
return rows as RequestTemplateRow[];
}
export type CreateTemplateInput = { tenantId: string; actorUserId: string; title: string; requestKind: HrRequestKind; description?: string | null; defaultApproverUserId?: string | null; linkedFormId?: string | null; isDemoData?: boolean };
export async function createTemplate(input: CreateTemplateInput): Promise<RequestTemplateRow> {
const title = input.title.trim();
if (!title) throw new HrServiceError("hr.error.templateTitleRequired");
if (!REQUEST_KINDS.includes(input.requestKind)) throw new HrServiceError("hr.error.requestKindInvalid");
const created = (await withTenantRLS(input.tenantId, (tx) =>
tx.hrRequestTemplate.create({
data: { tenantId: input.tenantId, title: title.slice(0, 255), requestKind: input.requestKind, description: input.description ?? null, defaultApproverUserId: input.defaultApproverUserId ?? null, linkedFormId: input.linkedFormId ?? null, isDemoData: input.isDemoData ?? false },
}),
)) as RequestTemplateRow;
await createAuditEvent({ tenantId: input.tenantId, actorId: input.actorUserId, actorType: "user", action: "HR_REQUEST_TEMPLATE_CREATE", targetType: "HrRequestTemplate", targetId: created.id, sourceModule: HR_AUDIT_MODULE, outcome: "success" });
return created;
}
export type UpdateTemplateInput = Partial<Omit<CreateTemplateInput, "tenantId" | "actorUserId">> & { tenantId: string; actorUserId: string; templateId: string; isActive?: boolean };
export async function updateTemplate(input: UpdateTemplateInput): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.hrRequestTemplate.findFirst({ where: { id: input.templateId, tenantId: input.tenantId }, select: { id: true } });
if (!existing) throw new CatalogError(foundationErrors.notFound, { templateId: input.templateId });
await tx.hrRequestTemplate.update({
where: { id: input.templateId },
data: {
...(input.title !== undefined ? { title: input.title.trim().slice(0, 255) } : {}),
...(input.requestKind !== undefined ? { requestKind: input.requestKind } : {}),
...(input.description !== undefined ? { description: input.description } : {}),
...(input.defaultApproverUserId !== undefined ? { defaultApproverUserId: input.defaultApproverUserId } : {}),
...(input.linkedFormId !== undefined ? { linkedFormId: input.linkedFormId } : {}),
...(input.isActive !== undefined ? { isActive: input.isActive } : {}),
},
});
});
await createAuditEvent({ tenantId: input.tenantId, actorId: input.actorUserId, actorType: "user", action: "HR_REQUEST_TEMPLATE_UPDATE", targetType: "HrRequestTemplate", targetId: input.templateId, sourceModule: HR_AUDIT_MODULE, outcome: "success" });
}
export async function archiveTemplate(input: { tenantId: string; actorUserId: string; templateId: string }): Promise<void> {
await withTenantRLS(input.tenantId, (tx) => tx.hrRequestTemplate.updateMany({ where: { id: input.templateId, tenantId: input.tenantId }, data: { archivedAt: new Date(), isActive: false } }));
await createAuditEvent({ tenantId: input.tenantId, actorId: input.actorUserId, actorType: "user", action: "HR_REQUEST_TEMPLATE_ARCHIVE", targetType: "HrRequestTemplate", targetId: input.templateId, sourceModule: HR_AUDIT_MODULE, outcome: "success" });
}
// --- Requests -------------------------------------------------------------
export type SubmitRequestInput = { tenantId: string; employeeUserId: string; templateId?: string | null; requestKind: HrRequestKind; title: string; details?: string | null; assignedApproverUserId?: string | null; isDemoData?: boolean };
export async function submitRequest(input: SubmitRequestInput): Promise<RequestRow> {
if (!REQUEST_KINDS.includes(input.requestKind)) throw new HrServiceError("hr.error.requestKindInvalid");
const title = input.title.trim();
if (!title) throw new HrServiceError("hr.error.requestTitleRequired");
const created = (await withTenantRLS(input.tenantId, (tx) =>
tx.hrRequest.create({
data: {
tenantId: input.tenantId,
employeeUserId: input.employeeUserId,
templateId: input.templateId ?? null,
requestKind: input.requestKind,
title: title.slice(0, 255),
details: input.details?.slice(0, 8000) ?? null,
status: "submitted",
assignedApproverUserId: input.assignedApproverUserId ?? null,
isDemoData: input.isDemoData ?? false,
},
}),
)) as RequestRow;
await audit({ tenantId: input.tenantId, actorId: input.employeeUserId, action: "HR_REQUEST_SUBMIT", targetId: created.id });
await notifyQuiet({ tenantId: input.tenantId, userId: created.assignedApproverUserId, messageKey: "hr.notify.request.submitted", sourceKey: `hr-request-submit:${created.id}` });
return created;
}
export async function listOwnRequests(tenantId: string, employeeUserId: string): Promise<RequestRow[]> {
const rows = await withTenantRLS(tenantId, (tx) => tx.hrRequest.findMany({ where: { tenantId, employeeUserId, archivedAt: null }, orderBy: { createdAt: "desc" } }));
return rows as RequestRow[];
}
export async function listForApprover(tenantId: string, approverUserId: string): Promise<RequestRow[]> {
const rows = await withTenantRLS(tenantId, (tx) =>
tx.hrRequest.findMany({ where: { tenantId, assignedApproverUserId: approverUserId, status: { in: ["submitted", "clarification"] }, archivedAt: null }, orderBy: { createdAt: "asc" } }),
);
return rows as RequestRow[];
}
async function getRequestOrThrow(tenantId: string, requestId: string): Promise<RequestRow> {
const row = await withTenantRLS(tenantId, (tx) => tx.hrRequest.findFirst({ where: { id: requestId, tenantId, archivedAt: null } }));
if (!row) throw new CatalogError(foundationErrors.notFound, { requestId });
return row as RequestRow;
}
export async function getRequestForUser(input: { tenantId: string; requestId: string; userId: string; canApproveAny: boolean }): Promise<RequestRow> {
const row = await getRequestOrThrow(input.tenantId, input.requestId);
const isOwner = row.employeeUserId === input.userId;
const isApprover = row.assignedApproverUserId === input.userId || input.canApproveAny;
if (!isOwner && !isApprover) throw new CatalogError(foundationErrors.notFound, { requestId: input.requestId });
return row;
}
async function loadDecidable(input: { tenantId: string; requestId: string; deciderUserId: string; canApproveAny: boolean }): Promise<RequestRow> {
const row = await getRequestOrThrow(input.tenantId, input.requestId);
const isApprover = row.assignedApproverUserId === input.deciderUserId || input.canApproveAny;
if (!isApprover) throw new CatalogError(foundationErrors.notFound, { requestId: input.requestId });
if (row.status !== "submitted" && row.status !== "clarification") throw new HrServiceError("hr.error.requestNotDecidable");
return row;
}
export async function decideRequest(input: { tenantId: string; requestId: string; deciderUserId: string; canApproveAny: boolean; decision: "approved" | "rejected"; decisionNote?: string | null }): Promise<void> {
const row = await loadDecidable(input);
await withTenantRLS(input.tenantId, (tx) =>
tx.hrRequest.update({ where: { id: row.id }, data: { status: input.decision, decidedByUserId: input.deciderUserId, decidedAt: new Date(), decisionNote: input.decisionNote?.slice(0, 2000) ?? null } }),
);
await audit({ tenantId: input.tenantId, actorId: input.deciderUserId, action: input.decision === "approved" ? "HR_REQUEST_APPROVE" : "HR_REQUEST_REJECT", targetId: row.id });
await notifyQuiet({ tenantId: input.tenantId, userId: row.employeeUserId, messageKey: `hr.notify.request.${input.decision}`, sourceKey: `hr-request-${input.decision}:${row.id}` });
}
export async function requestClarification(input: { tenantId: string; requestId: string; deciderUserId: string; canApproveAny: boolean; question: string }): Promise<void> {
const row = await loadDecidable(input);
const question = input.question.trim();
if (!question) throw new HrServiceError("hr.error.requestClarificationEmpty");
await withTenantRLS(input.tenantId, (tx) => tx.hrRequest.update({ where: { id: row.id }, data: { status: "clarification", clarificationNote: question.slice(0, 2000) } }));
await audit({ tenantId: input.tenantId, actorId: input.deciderUserId, action: "HR_REQUEST_CLARIFY", targetId: row.id });
await notifyQuiet({ tenantId: input.tenantId, userId: row.employeeUserId, messageKey: "hr.notify.request.clarification", sourceKey: `hr-request-clarify:${row.id}` });
}
export async function withdrawRequest(input: { tenantId: string; requestId: string; employeeUserId: string }): Promise<void> {
const row = await getRequestOrThrow(input.tenantId, input.requestId);
if (row.employeeUserId !== input.employeeUserId) throw new CatalogError(foundationErrors.notFound, { requestId: input.requestId });
if (row.status !== "submitted" && row.status !== "clarification") throw new HrServiceError("hr.error.requestNotWithdrawable");
await withTenantRLS(input.tenantId, (tx) => tx.hrRequest.update({ where: { id: row.id }, data: { status: "withdrawn", withdrawnAt: new Date() } }));
await audit({ tenantId: input.tenantId, actorId: input.employeeUserId, action: "HR_REQUEST_WITHDRAW", targetId: row.id });
await notifyQuiet({ tenantId: input.tenantId, userId: row.assignedApproverUserId, messageKey: "hr.notify.request.withdrawn", sourceKey: `hr-request-withdraw:${row.id}` });
}
@@ -0,0 +1,129 @@
// P17 HR-Hub core (AK-P17a) — pure route-path builders for HR URLs. Loaders build
// these and pass them into the View-Models so the VMs stay routing-agnostic.
//
// NOTE on the admin password-safe path: the designer brief writes it as
// "/admin/hr/password-safe". The platform `admin/` area is for cross-tenant
// SuperAdmin/operator screens; the HR vault admin view is TENANT-scoped (gated by
// the tenant permission hr.passwordsafe.admin), so it correctly lives under the
// tenant app at `/<tenant>/hr/password-safe/admin`. (Confirm with David in the
// D-HR delta.)
// Tenant connector module key. It lives in this client-safe module (not in
// hrAccess.server) so a route `handle` export can reference it without dragging
// the server-only access guard into the client bundle (RR code-splitting only
// strips loader/action/middleware/headers, not `handle`).
export const HR_MODULE_KEY = "hr";
export function hrHubPath(tenantSlug: string): string {
return `/${tenantSlug}/hr`;
}
export function hrDirectoryPath(tenantSlug: string): string {
return `/${tenantSlug}/hr/directory`;
}
export function hrDirectoryDetailPath(tenantSlug: string, userId: string): string {
return `/${tenantSlug}/hr/directory/${userId}`;
}
export function hrLocationsPath(tenantSlug: string): string {
return `/${tenantSlug}/hr/locations`;
}
export function hrLocationDetailPath(tenantSlug: string, locationId: string): string {
return `/${tenantSlug}/hr/locations/${locationId}`;
}
export function hrMyDocumentsPath(tenantSlug: string): string {
return `/${tenantSlug}/hr/my-documents`;
}
export function hrPasswordSafePath(tenantSlug: string): string {
return `/${tenantSlug}/hr/password-safe`;
}
export function hrVaultDetailPath(tenantSlug: string, vaultId: string): string {
return `/${tenantSlug}/hr/password-safe/${vaultId}`;
}
export function hrVaultRevealPath(tenantSlug: string, vaultId: string): string {
return `/${tenantSlug}/hr/password-safe/${vaultId}/reveal`;
}
export function hrVaultExportPath(tenantSlug: string, vaultId: string): string {
return `/${tenantSlug}/hr/password-safe/${vaultId}/export`;
}
export function hrAdminPasswordSafePath(tenantSlug: string): string {
return `/${tenantSlug}/hr/admin/password-safe`;
}
// --- AK-P17b workflow paths ------------------------------------------------
export function hrLeavePath(tenantSlug: string): string {
return `/${tenantSlug}/hr/leave`;
}
export function hrLeaveDetailPath(tenantSlug: string, requestId: string): string {
return `/${tenantSlug}/hr/leave/${requestId}`;
}
export function hrSickPath(tenantSlug: string): string {
return `/${tenantSlug}/hr/sick`;
}
export function hrSickCertificatePath(tenantSlug: string, reportId: string): string {
return `/${tenantSlug}/hr/sick/${reportId}/certificate`;
}
export function hrAnnouncementsPath(tenantSlug: string): string {
return `/${tenantSlug}/hr/announcements`;
}
export function hrAnnouncementDetailPath(tenantSlug: string, announcementId: string): string {
return `/${tenantSlug}/hr/announcements/${announcementId}`;
}
export function hrAdminAnnouncementsPath(tenantSlug: string): string {
return `/${tenantSlug}/hr/admin/announcements`;
}
export function hrPayslipsPath(tenantSlug: string): string {
return `/${tenantSlug}/hr/payslips`;
}
export function hrAdminPayslipsPath(tenantSlug: string): string {
return `/${tenantSlug}/hr/admin/payslips`;
}
export function hrPayslipOpenPath(tenantSlug: string, payslipId: string): string {
return `/${tenantSlug}/hr/payslips/${payslipId}/open`;
}
export function hrRequestsPath(tenantSlug: string): string {
return `/${tenantSlug}/hr/requests`;
}
export function hrRequestDetailPath(tenantSlug: string, requestId: string): string {
return `/${tenantSlug}/hr/requests/${requestId}`;
}
export function hrAdminRequestTemplatesPath(tenantSlug: string): string {
return `/${tenantSlug}/hr/admin/request-templates`;
}
export function hrSurveysPath(tenantSlug: string): string {
return `/${tenantSlug}/hr/surveys`;
}
export function hrSurveyParticipatePath(tenantSlug: string, surveyId: string): string {
return `/${tenantSlug}/hr/surveys/${surveyId}`;
}
export function hrSurveyResultsPath(tenantSlug: string, surveyId: string): string {
return `/${tenantSlug}/hr/surveys/${surveyId}/results`;
}
export function hrAdminUploadRemindersPath(tenantSlug: string): string {
return `/${tenantSlug}/hr/admin/upload-reminders`;
}
@@ -0,0 +1,490 @@
// P17 HR-Hub core (AK-P17a) §S4 — domain service for employee master data,
// locations and personnel documents.
//
// Pure-ish server logic: builds/queries HR rows (always tenant-scoped), enforces
// the MA vs HR-admin split (self can edit a whitelist of own fields; HR-admin
// edits the rest), enforces visibility (404, not 403), and routes the sensitive
// emergency contact through the hrFieldCrypto seam (AD-8, deferred). NO React/UI
// imports. Routes call these from their loaders/actions and build the View-Model
// from the returned rows.
//
// Tenant isolation is enforced twofold: every query carries `where: { tenantId }`
// (app-level scoping) plus the RLS policies from prisma/rls/hr-isolation.sql
// (once R-P2b's `SET LOCAL app.tenant_id` is live). RLS-ready: every tenant
// access runs inside withTenantRLS(); internal composition reuses the active
// transaction via *WithTx helpers and never nests withTenantRLS(). The only
// unwrapped access is the GLOBAL User lookup (resolveUserLabels): User is not
// tenant-scoped, so it stays on the db singleton.
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { db } from "~/utils/db.server";
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import { getHrFieldCrypto, type HrFieldCrypto } from "./hrFieldCrypto.server";
const HR_AUDIT_MODULE = "hr";
/**
* Domain error carrying an i18n message key (M002 Klartext). Routes map
* `messageKey` to a catalog error / VM error branch — never a bare HTTP code.
*/
export class HrServiceError extends Error {
readonly messageKey: string;
constructor(messageKey: string) {
super(messageKey);
this.name = "HrServiceError";
this.messageKey = messageKey;
}
}
export type HrDocumentKind = "contract" | "certificate" | "identification" | "qualification" | "other";
export type HrDocumentVisibility = "employee" | "hr_only";
export type HrResourceKind = "link" | "file";
const MAX_NAME_LENGTH = 255;
/** The plaintext emergency contact triple (decrypted only on explicit reveal). */
export type EmergencyContact = {
name: string;
phone: string;
relation: string;
};
// --- Profile rows ---------------------------------------------------------
export type HrEmployeeProfileRow = {
id: string;
tenantId: string;
userId: string;
personalNumber: string | null;
hireDate: Date | null;
position: string | null;
team: string | null;
locationId: string | null;
managerUserId: string | null;
emergencyContactCiphertext: string | null;
isDemoData: boolean;
createdAt: Date;
updatedAt: Date;
};
/** Fields an employee may edit on their OWN profile (MA self-service). Everything
* else (personal number, hire date, manager, location) is HR-admin managed. */
const SELF_EDITABLE_FIELDS = ["position", "team"] as const;
export type SelfEditableProfileInput = Partial<Pick<HrEmployeeProfileRow, (typeof SELF_EDITABLE_FIELDS)[number]>>;
/** Load a single employee profile (tenant-scoped), or null. */
export async function getProfileByUser(tenantId: string, userId: string): Promise<HrEmployeeProfileRow | null> {
const row = await withTenantRLS(tenantId, (tx) => tx.hrEmployeeProfile.findFirst({ where: { tenantId, userId } }));
return (row as HrEmployeeProfileRow | null) ?? null;
}
export type DirectoryEntryRow = {
userId: string;
position: string | null;
team: string | null;
locationId: string | null;
managerUserId: string | null;
};
/** List the employee directory (tenant-scoped). Sensitive ciphertext is never
* selected here — the directory carries only non-sensitive display fields. */
export async function listDirectory(tenantId: string): Promise<DirectoryEntryRow[]> {
const rows = await withTenantRLS(tenantId, (tx) =>
tx.hrEmployeeProfile.findMany({
where: { tenantId },
select: { userId: true, position: true, team: true, locationId: true, managerUserId: true },
orderBy: { team: "asc" },
}),
);
return rows;
}
/** Upsert the caller's OWN profile, restricted to self-editable fields. */
export async function updateOwnProfile(input: { tenantId: string; userId: string; data: SelfEditableProfileInput }): Promise<void> {
const data: SelfEditableProfileInput = {};
for (const field of SELF_EDITABLE_FIELDS) {
if (input.data[field] !== undefined) {
data[field] = input.data[field]?.toString().slice(0, MAX_NAME_LENGTH) ?? null;
}
}
await withTenantRLS(input.tenantId, (tx) =>
tx.hrEmployeeProfile.upsert({
where: { tenantId_userId: { tenantId: input.tenantId, userId: input.userId } },
update: data,
create: { tenantId: input.tenantId, userId: input.userId, ...data },
}),
);
}
export type AdminProfileInput = {
tenantId: string;
userId: string;
personalNumber?: string | null;
hireDate?: Date | null;
position?: string | null;
team?: string | null;
locationId?: string | null;
managerUserId?: string | null;
isDemoData?: boolean;
};
/** HR-admin upsert of any employee's managed profile fields. */
export async function adminUpsertProfile(input: AdminProfileInput): Promise<void> {
const data = {
...(input.personalNumber !== undefined ? { personalNumber: input.personalNumber } : {}),
...(input.hireDate !== undefined ? { hireDate: input.hireDate } : {}),
...(input.position !== undefined ? { position: input.position } : {}),
...(input.team !== undefined ? { team: input.team } : {}),
...(input.locationId !== undefined ? { locationId: input.locationId } : {}),
...(input.managerUserId !== undefined ? { managerUserId: input.managerUserId } : {}),
...(input.isDemoData !== undefined ? { isDemoData: input.isDemoData } : {}),
};
await withTenantRLS(input.tenantId, (tx) =>
tx.hrEmployeeProfile.upsert({
where: { tenantId_userId: { tenantId: input.tenantId, userId: input.userId } },
update: data,
create: { tenantId: input.tenantId, userId: input.userId, ...data },
}),
);
}
/**
* Store an employee's emergency contact, ENVELOPE-ENCRYPTED (AD-8). Goes through
* the hrFieldCrypto seam — until the AD-8 envelope ticket lands the production
* binding throws HrCryptoNotProvisionedError (M002 Klartext). Tests inject a
* working `crypto`.
*/
export async function setEmergencyContact(
input: { tenantId: string; userId: string; contact: EmergencyContact },
crypto: HrFieldCrypto = getHrFieldCrypto(),
): Promise<void> {
const ciphertext = await crypto.encrypt(input.tenantId, JSON.stringify(input.contact));
await withTenantRLS(input.tenantId, (tx) =>
tx.hrEmployeeProfile.upsert({
where: { tenantId_userId: { tenantId: input.tenantId, userId: input.userId } },
update: { emergencyContactCiphertext: ciphertext },
create: { tenantId: input.tenantId, userId: input.userId, emergencyContactCiphertext: ciphertext },
}),
);
}
/**
* Reveal (decrypt) an employee's emergency contact ON DEMAND. Writes a
* pii/gdpr audit event BEFORE returning the plaintext. The caller must already
* have established that `revealerUserId` is the employee themselves or holds
* hr.read_all (enforced in the route).
*/
export async function revealEmergencyContact(
input: { tenantId: string; userId: string; revealerUserId: string },
crypto: HrFieldCrypto = getHrFieldCrypto(),
): Promise<EmergencyContact | null> {
const profile = await getProfileByUser(input.tenantId, input.userId);
if (!profile) {
throw new CatalogError(foundationErrors.notFound, { userId: input.userId });
}
if (!profile.emergencyContactCiphertext) {
return null;
}
await createAuditEvent({
tenantId: input.tenantId,
actorId: input.revealerUserId,
actorType: "user",
action: "HR_EMERGENCY_CONTACT_REVEAL",
targetType: "HrEmployeeProfile",
targetId: profile.id,
sourceModule: HR_AUDIT_MODULE,
dataSensitivity: "pii",
regulatoryScope: ["gdpr"],
outcome: "success",
metadata: { employeeUserId: input.userId },
});
const plaintext = await crypto.decrypt(input.tenantId, profile.emergencyContactCiphertext);
return JSON.parse(plaintext) as EmergencyContact;
}
// --- Locations ------------------------------------------------------------
export type HrLocationRow = {
id: string;
tenantId: string;
name: string;
addressLine1: string | null;
addressLine2: string | null;
postalCode: string | null;
city: string | null;
country: string | null;
phone: string | null;
latitude: number | null;
longitude: number | null;
imageFileId: string | null;
description: string | null;
isDefault: boolean;
isDemoData: boolean;
createdAt: Date;
updatedAt: Date;
archivedAt: Date | null;
};
export async function listLocations(tenantId: string, opts?: { includeArchived?: boolean }): Promise<HrLocationRow[]> {
const rows = await withTenantRLS(tenantId, (tx) =>
tx.hrLocation.findMany({
where: { tenantId, ...(opts?.includeArchived ? {} : { archivedAt: null }) },
orderBy: [{ isDefault: "desc" }, { name: "asc" }],
}),
);
return rows as HrLocationRow[];
}
export async function getLocationOrThrow(tenantId: string, locationId: string): Promise<HrLocationRow> {
const row = await withTenantRLS(tenantId, (tx) => tx.hrLocation.findFirst({ where: { id: locationId, tenantId } }));
if (!row) {
throw new CatalogError(foundationErrors.notFound, { locationId });
}
return row as HrLocationRow;
}
export type CreateLocationInput = {
tenantId: string;
name: string;
addressLine1?: string | null;
addressLine2?: string | null;
postalCode?: string | null;
city?: string | null;
country?: string | null;
phone?: string | null;
latitude?: number | null;
longitude?: number | null;
imageFileId?: string | null;
description?: string | null;
isDefault?: boolean;
isDemoData?: boolean;
};
export async function createLocation(input: CreateLocationInput): Promise<HrLocationRow> {
const name = input.name.trim();
if (!name) {
throw new HrServiceError("hr.error.locationNameRequired");
}
return withTenantRLS(input.tenantId, async (tx) => {
if (input.isDefault) {
await tx.hrLocation.updateMany({ where: { tenantId: input.tenantId, isDefault: true }, data: { isDefault: false } });
}
const created = await tx.hrLocation.create({
data: {
tenantId: input.tenantId,
name: name.slice(0, MAX_NAME_LENGTH),
addressLine1: input.addressLine1 ?? null,
addressLine2: input.addressLine2 ?? null,
postalCode: input.postalCode ?? null,
city: input.city ?? null,
country: input.country ?? null,
phone: input.phone ?? null,
latitude: input.latitude ?? null,
longitude: input.longitude ?? null,
imageFileId: input.imageFileId ?? null,
description: input.description ?? null,
isDefault: input.isDefault ?? false,
isDemoData: input.isDemoData ?? false,
},
});
return created as HrLocationRow;
});
}
export type UpdateLocationInput = Partial<Omit<CreateLocationInput, "tenantId">> & { tenantId: string; locationId: string };
export async function updateLocation(input: UpdateLocationInput): Promise<void> {
if (input.name !== undefined && !input.name.trim()) {
throw new HrServiceError("hr.error.locationNameRequired");
}
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.hrLocation.findFirst({ where: { id: input.locationId, tenantId: input.tenantId }, select: { id: true } });
if (!existing) {
throw new CatalogError(foundationErrors.notFound, { locationId: input.locationId });
}
if (input.isDefault) {
await tx.hrLocation.updateMany({ where: { tenantId: input.tenantId, isDefault: true, id: { not: input.locationId } }, data: { isDefault: false } });
}
await tx.hrLocation.updateMany({
where: { id: input.locationId, tenantId: input.tenantId },
data: {
...(input.name !== undefined ? { name: input.name.trim().slice(0, MAX_NAME_LENGTH) } : {}),
...(input.addressLine1 !== undefined ? { addressLine1: input.addressLine1 } : {}),
...(input.addressLine2 !== undefined ? { addressLine2: input.addressLine2 } : {}),
...(input.postalCode !== undefined ? { postalCode: input.postalCode } : {}),
...(input.city !== undefined ? { city: input.city } : {}),
...(input.country !== undefined ? { country: input.country } : {}),
...(input.phone !== undefined ? { phone: input.phone } : {}),
...(input.latitude !== undefined ? { latitude: input.latitude } : {}),
...(input.longitude !== undefined ? { longitude: input.longitude } : {}),
...(input.imageFileId !== undefined ? { imageFileId: input.imageFileId } : {}),
...(input.description !== undefined ? { description: input.description } : {}),
...(input.isDefault !== undefined ? { isDefault: input.isDefault } : {}),
},
});
});
}
export async function archiveLocation(input: { tenantId: string; locationId: string }): Promise<void> {
await withTenantRLS(input.tenantId, (tx) =>
tx.hrLocation.updateMany({ where: { id: input.locationId, tenantId: input.tenantId }, data: { archivedAt: new Date(), isDefault: false } }),
);
}
/** Reassign every employee at `fromLocationId` to `toLocationId` (admin bulk). */
export async function reassignLocationEmployees(input: { tenantId: string; fromLocationId: string; toLocationId: string }): Promise<number> {
if (input.fromLocationId === input.toLocationId) {
throw new HrServiceError("hr.error.locationReassignSame");
}
return withTenantRLS(input.tenantId, async (tx) => {
const target = await tx.hrLocation.findFirst({ where: { id: input.toLocationId, tenantId: input.tenantId, archivedAt: null }, select: { id: true } });
if (!target) {
throw new CatalogError(foundationErrors.notFound, { locationId: input.toLocationId });
}
const result = await tx.hrEmployeeProfile.updateMany({
where: { tenantId: input.tenantId, locationId: input.fromLocationId },
data: { locationId: input.toLocationId },
});
return result.count;
});
}
// --- Documents ------------------------------------------------------------
export type HrEmployeeDocumentRow = {
id: string;
tenantId: string;
employeeUserId: string;
uploadedByUserId: string;
title: string;
documentKind: HrDocumentKind;
fileId: string;
visibility: HrDocumentVisibility;
uploadedByOffice: boolean;
validUntil: Date | null;
isDemoData: boolean;
createdAt: Date;
updatedAt: Date;
archivedAt: Date | null;
};
/**
* List the documents for one employee. When `viewerIsEmployee` (the caller is the
* employee, not HR), `hr_only` documents are hidden — the employee only ever sees
* documents flagged `employee`-visible.
*/
export async function listEmployeeDocuments(input: {
tenantId: string;
employeeUserId: string;
viewerIsEmployee: boolean;
includeArchived?: boolean;
}): Promise<HrEmployeeDocumentRow[]> {
const rows = await withTenantRLS(input.tenantId, (tx) =>
tx.hrEmployeeDocument.findMany({
where: {
tenantId: input.tenantId,
employeeUserId: input.employeeUserId,
...(input.includeArchived ? {} : { archivedAt: null }),
...(input.viewerIsEmployee ? { visibility: "employee" } : {}),
},
orderBy: { createdAt: "desc" },
}),
);
return rows as HrEmployeeDocumentRow[];
}
export type CreateDocumentInput = {
tenantId: string;
employeeUserId: string;
uploadedByUserId: string;
title: string;
documentKind?: HrDocumentKind;
fileId: string;
visibility?: HrDocumentVisibility;
uploadedByOffice?: boolean;
validUntil?: Date | null;
isDemoData?: boolean;
};
export async function createDocument(input: CreateDocumentInput): Promise<HrEmployeeDocumentRow> {
const title = input.title.trim();
if (!title) {
throw new HrServiceError("hr.error.documentTitleRequired");
}
const created = await withTenantRLS(input.tenantId, (tx) =>
tx.hrEmployeeDocument.create({
data: {
tenantId: input.tenantId,
employeeUserId: input.employeeUserId,
uploadedByUserId: input.uploadedByUserId,
title: title.slice(0, MAX_NAME_LENGTH),
documentKind: input.documentKind ?? "other",
fileId: input.fileId,
visibility: input.visibility ?? "employee",
uploadedByOffice: input.uploadedByOffice ?? false,
validUntil: input.validUntil ?? null,
isDemoData: input.isDemoData ?? false,
},
}),
);
return created as HrEmployeeDocumentRow;
}
/**
* Archive a document. An employee may only archive their OWN, non-office
* documents (office-uploaded = read-only). HR (viewerIsEmployee=false) may
* archive any.
*/
export async function archiveDocument(input: {
tenantId: string;
documentId: string;
actorUserId: string;
viewerIsEmployee: boolean;
}): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const doc = await tx.hrEmployeeDocument.findFirst({
where: { id: input.documentId, tenantId: input.tenantId },
select: { id: true, employeeUserId: true, uploadedByOffice: true },
});
if (!doc) {
throw new CatalogError(foundationErrors.notFound, { documentId: input.documentId });
}
if (input.viewerIsEmployee) {
// Employee self-service: own document, and not an office upload.
if (doc.employeeUserId !== input.actorUserId) {
throw new CatalogError(foundationErrors.notFound, { documentId: input.documentId });
}
if (doc.uploadedByOffice) {
throw new HrServiceError("hr.error.documentReadOnly");
}
}
await tx.hrEmployeeDocument.updateMany({ where: { id: input.documentId, tenantId: input.tenantId }, data: { archivedAt: new Date() } });
});
}
// --- Directory helpers (display names) -------------------------------------
export type LabeledUser = { id: string; label: string; email: string };
function userLabel(user: { firstName: string; lastName: string; email: string }): string {
const name = `${user.firstName} ${user.lastName}`.trim();
return name || user.email;
}
/** Resolve display labels for a set of user ids (global User table, not tenant-scoped). */
export async function resolveUserLabels(userIds: readonly string[]): Promise<Map<string, LabeledUser>> {
const ids = [...new Set(userIds)].filter(Boolean);
if (ids.length === 0) {
return new Map();
}
const users = await db.user.findMany({
where: { id: { in: ids } },
select: { id: true, firstName: true, lastName: true, email: true },
});
return new Map(users.map((user) => [user.id, { id: user.id, label: userLabel(user), email: user.email }]));
}
// Re-export the transaction client type for the password-safe service (shared
// RLS transaction shape).
export type { TenantRlsClient };
@@ -0,0 +1,205 @@
// P17 HR-Hub workflows (AK-P17b) — sick-leave domain service.
//
// An employee files a sick-leave report themselves, or HR/office files it on
// their behalf (`reportedByUserId`). The AU certificate ("AU-Schein") is
// sensitive (AD-8): we envelope-encrypt the certificate File REFERENCE through
// the hrFieldCrypto seam and never return it without an explicit,
// permission-checked + audited reveal (mirrors hrService.revealEmergencyContact).
// NO React/UI imports. Every tenant access runs inside withTenantRLS().
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { getHrFieldCrypto, type HrFieldCrypto } from "./hrFieldCrypto.server";
import { HrServiceError } from "./hrService.server";
const HR_AUDIT_MODULE = "hr";
export type HrSickLeaveStatus = "reported" | "closed" | "cancelled";
export type SickLeaveRow = {
id: string;
tenantId: string;
employeeUserId: string;
reportedByUserId: string;
startDate: Date;
expectedReturnDate: Date | null;
returnDate: Date | null;
certificateRefCiphertext: string | null;
status: HrSickLeaveStatus;
note: string | null;
calendarEventId: string | null;
createdAt: Date;
updatedAt: Date;
};
export type ReportSickLeaveInput = {
tenantId: string;
employeeUserId: string;
/** The acting user — equals employeeUserId for self-reports, an HR/office user
* for on-behalf reports. */
reportedByUserId: string;
startDate: Date;
expectedReturnDate?: Date | null;
note?: string | null;
isDemoData?: boolean;
};
/** File a sick-leave report (self or on behalf of an employee). */
export async function reportSickLeave(input: ReportSickLeaveInput): Promise<SickLeaveRow> {
if (input.expectedReturnDate && input.expectedReturnDate < input.startDate) {
throw new HrServiceError("hr.error.sickRangeInvalid");
}
const created = (await withTenantRLS(input.tenantId, (tx) =>
tx.employeeSickLeaveReport.create({
data: {
tenantId: input.tenantId,
employeeUserId: input.employeeUserId,
reportedByUserId: input.reportedByUserId,
startDate: input.startDate,
expectedReturnDate: input.expectedReturnDate ?? null,
note: input.note?.trim().slice(0, 2000) || null,
status: "reported",
isDemoData: input.isDemoData ?? false,
},
}),
)) as SickLeaveRow;
await createAuditEvent({
tenantId: input.tenantId,
actorId: input.reportedByUserId,
actorType: "user",
action: input.reportedByUserId === input.employeeUserId ? "HR_SICK_REPORT_SELF" : "HR_SICK_REPORT_OFFICE",
targetType: "EmployeeSickLeaveReport",
targetId: created.id,
sourceModule: HR_AUDIT_MODULE,
outcome: "success",
metadata: { employeeUserId: input.employeeUserId },
});
return created;
}
async function getReportOrThrow(tenantId: string, reportId: string): Promise<SickLeaveRow> {
const row = await withTenantRLS(tenantId, (tx) => tx.employeeSickLeaveReport.findFirst({ where: { id: reportId, tenantId } }));
if (!row) {
throw new CatalogError(foundationErrors.notFound, { reportId });
}
return row as SickLeaveRow;
}
/**
* Attach (or replace) the AU certificate, storing the File reference
* ENVELOPE-ENCRYPTED. The plaintext fileId never lands in the column.
*/
export async function attachCertificate(
input: { tenantId: string; reportId: string; actorUserId: string; certificateFileId: string },
crypto: HrFieldCrypto = getHrFieldCrypto(),
): Promise<void> {
const row = await getReportOrThrow(input.tenantId, input.reportId);
const ciphertext = await crypto.encrypt(input.tenantId, input.certificateFileId);
await withTenantRLS(input.tenantId, (tx) =>
tx.employeeSickLeaveReport.update({ where: { id: row.id }, data: { certificateRefCiphertext: ciphertext } }),
);
await createAuditEvent({
tenantId: input.tenantId,
actorId: input.actorUserId,
actorType: "user",
action: "HR_SICK_CERTIFICATE_ATTACH",
targetType: "EmployeeSickLeaveReport",
targetId: row.id,
sourceModule: HR_AUDIT_MODULE,
dataSensitivity: "pii",
regulatoryScope: ["gdpr"],
outcome: "success",
metadata: { employeeUserId: row.employeeUserId },
});
}
/**
* Reveal (decrypt) the AU certificate File id ON DEMAND. Writes a pii/gdpr
* audit event BEFORE returning. The caller must already have established that
* `revealerUserId` is the employee themselves or holds hr.read_all (route).
*/
export async function revealCertificateFileId(
input: { tenantId: string; reportId: string; revealerUserId: string },
crypto: HrFieldCrypto = getHrFieldCrypto(),
): Promise<string | null> {
const row = await getReportOrThrow(input.tenantId, input.reportId);
if (!row.certificateRefCiphertext) {
return null;
}
await createAuditEvent({
tenantId: input.tenantId,
actorId: input.revealerUserId,
actorType: "user",
action: "HR_SICK_CERTIFICATE_REVEAL",
targetType: "EmployeeSickLeaveReport",
targetId: row.id,
sourceModule: HR_AUDIT_MODULE,
dataSensitivity: "pii",
regulatoryScope: ["gdpr"],
outcome: "success",
metadata: { employeeUserId: row.employeeUserId },
});
return crypto.decrypt(input.tenantId, row.certificateRefCiphertext);
}
/** Mark a sick-leave report closed with an actual return date. */
export async function closeSickLeave(input: { tenantId: string; reportId: string; actorUserId: string; returnDate: Date }): Promise<void> {
const row = await getReportOrThrow(input.tenantId, input.reportId);
if (row.status === "cancelled") {
throw new HrServiceError("hr.error.sickNotUpdatable");
}
if (input.returnDate < row.startDate) {
throw new HrServiceError("hr.error.sickRangeInvalid");
}
await withTenantRLS(input.tenantId, (tx) =>
tx.employeeSickLeaveReport.update({ where: { id: row.id }, data: { status: "closed", returnDate: input.returnDate } }),
);
await createAuditEvent({
tenantId: input.tenantId,
actorId: input.actorUserId,
actorType: "user",
action: "HR_SICK_CLOSE",
targetType: "EmployeeSickLeaveReport",
targetId: row.id,
sourceModule: HR_AUDIT_MODULE,
outcome: "success",
});
}
/** Cancel an erroneous sick-leave report (removes it from the absence feed). */
export async function cancelSickLeave(input: { tenantId: string; reportId: string; actorUserId: string }): Promise<void> {
const row = await getReportOrThrow(input.tenantId, input.reportId);
await withTenantRLS(input.tenantId, (tx) =>
tx.employeeSickLeaveReport.update({ where: { id: row.id }, data: { status: "cancelled" } }),
);
await createAuditEvent({
tenantId: input.tenantId,
actorId: input.actorUserId,
actorType: "user",
action: "HR_SICK_CANCEL",
targetType: "EmployeeSickLeaveReport",
targetId: row.id,
sourceModule: HR_AUDIT_MODULE,
outcome: "success",
});
}
/** List the caller's own sick-leave reports, newest first. */
export async function listOwnSickLeave(tenantId: string, employeeUserId: string): Promise<SickLeaveRow[]> {
const rows = await withTenantRLS(tenantId, (tx) =>
tx.employeeSickLeaveReport.findMany({ where: { tenantId, employeeUserId }, orderBy: { startDate: "desc" } }),
);
return rows as SickLeaveRow[];
}
/** HR/office view of all sick-leave reports (optionally only currently open). */
export async function listSickLeaveForOffice(tenantId: string, opts?: { onlyOpen?: boolean }): Promise<SickLeaveRow[]> {
const rows = await withTenantRLS(tenantId, (tx) =>
tx.employeeSickLeaveReport.findMany({
where: { tenantId, ...(opts?.onlyOpen ? { status: "reported" } : {}) },
orderBy: { startDate: "desc" },
}),
);
return rows as SickLeaveRow[];
}
@@ -0,0 +1,190 @@
// P17 HR-Hub workflows (AK-P17b) — surveys domain service.
//
// Surveys may be anonymous. For an anonymous survey the submission stores a
// non-reversible per-(tenant,survey,user) hash (`submitterHash`) instead of the
// user id, which enforces one-submission-per-user WITHOUT allowing
// re-identification. Aggregated results are gated by hr.surveys.results at the
// route layer. Every tenant access runs inside withTenantRLS().
import { createHash } from "node:crypto";
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { HrServiceError } from "./hrService.server";
const HR_AUDIT_MODULE = "hr";
export type HrSurveyItemType = "text" | "rating_5" | "nps" | "choice" | "boolean" | "date";
export type HrSurveyStatus = "draft" | "open" | "closed";
export type HrSurveyResultVisibility = "admins" | "participants" | "everyone";
export type HrAudienceKind = "all" | "team" | "location";
export type SurveyRow = {
id: string;
tenantId: string;
authorUserId: string;
title: string;
description: string | null;
isAnonymous: boolean;
resultVisibility: HrSurveyResultVisibility;
audienceKind: HrAudienceKind;
audienceRef: string | null;
status: HrSurveyStatus;
opensAt: Date | null;
closesAt: Date | null;
createdAt: Date;
updatedAt: Date;
archivedAt: Date | null;
};
export type SurveyItemRow = { id: string; surveyId: string; itemType: HrSurveyItemType; prompt: string; required: boolean; options: string[]; sortOrder: number };
/** Non-reversible submitter hash for anonymous dedup. Includes the tenant so the
* same user id in different tenants never collides; not reversible to the user. */
function submitterHashFor(tenantId: string, surveyId: string, userId: string): string {
return createHash("sha256").update(`${tenantId}:${surveyId}:${userId}`).digest("hex");
}
export type CreateSurveyInput = { tenantId: string; authorUserId: string; title: string; description?: string | null; isAnonymous?: boolean; resultVisibility?: HrSurveyResultVisibility; audienceKind?: HrAudienceKind; audienceRef?: string | null; isDemoData?: boolean };
export async function createSurvey(input: CreateSurveyInput): Promise<SurveyRow> {
const title = input.title.trim();
if (!title) throw new HrServiceError("hr.error.surveyTitleRequired");
const created = (await withTenantRLS(input.tenantId, (tx) =>
tx.hrSurvey.create({
data: { tenantId: input.tenantId, authorUserId: input.authorUserId, title: title.slice(0, 255), description: input.description ?? null, isAnonymous: input.isAnonymous ?? false, resultVisibility: input.resultVisibility ?? "admins", audienceKind: input.audienceKind ?? "all", audienceRef: input.audienceRef ?? null, isDemoData: input.isDemoData ?? false },
}),
)) as SurveyRow;
await createAuditEvent({ tenantId: input.tenantId, actorId: input.authorUserId, actorType: "user", action: "HR_SURVEY_CREATE", targetType: "HrSurvey", targetId: created.id, sourceModule: HR_AUDIT_MODULE, outcome: "success" });
return created;
}
export type UpdateSurveyInput = Partial<Omit<CreateSurveyInput, "tenantId" | "authorUserId">> & { tenantId: string; actorUserId: string; surveyId: string };
export async function updateSurvey(input: UpdateSurveyInput): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.hrSurvey.findFirst({ where: { id: input.surveyId, tenantId: input.tenantId }, select: { id: true } });
if (!existing) throw new CatalogError(foundationErrors.notFound, { surveyId: input.surveyId });
await tx.hrSurvey.update({
where: { id: input.surveyId },
data: {
...(input.title !== undefined ? { title: input.title.trim().slice(0, 255) } : {}),
...(input.description !== undefined ? { description: input.description } : {}),
...(input.isAnonymous !== undefined ? { isAnonymous: input.isAnonymous } : {}),
...(input.resultVisibility !== undefined ? { resultVisibility: input.resultVisibility } : {}),
...(input.audienceKind !== undefined ? { audienceKind: input.audienceKind } : {}),
...(input.audienceRef !== undefined ? { audienceRef: input.audienceRef } : {}),
},
});
});
}
export async function setSurveyStatus(input: { tenantId: string; actorUserId: string; surveyId: string; status: HrSurveyStatus }): Promise<void> {
await withTenantRLS(input.tenantId, (tx) =>
tx.hrSurvey.updateMany({
where: { id: input.surveyId, tenantId: input.tenantId },
data: { status: input.status, ...(input.status === "open" ? { opensAt: new Date() } : {}), ...(input.status === "closed" ? { closesAt: new Date() } : {}) },
}),
);
await createAuditEvent({ tenantId: input.tenantId, actorId: input.actorUserId, actorType: "user", action: "HR_SURVEY_STATUS", targetType: "HrSurvey", targetId: input.surveyId, sourceModule: HR_AUDIT_MODULE, outcome: "success", metadata: { status: input.status } });
}
export async function archiveSurvey(input: { tenantId: string; actorUserId: string; surveyId: string }): Promise<void> {
await withTenantRLS(input.tenantId, (tx) => tx.hrSurvey.updateMany({ where: { id: input.surveyId, tenantId: input.tenantId }, data: { archivedAt: new Date(), status: "closed" } }));
}
export async function addItem(input: { tenantId: string; surveyId: string; itemType: HrSurveyItemType; prompt: string; required?: boolean; options?: string[]; sortOrder?: number }): Promise<SurveyItemRow> {
const prompt = input.prompt.trim();
if (!prompt) throw new HrServiceError("hr.error.surveyPromptRequired");
if (input.itemType === "choice" && (!input.options || input.options.length === 0)) throw new HrServiceError("hr.error.surveyChoiceNeedsOptions");
const created = await withTenantRLS(input.tenantId, (tx) =>
tx.hrSurveyItem.create({ data: { tenantId: input.tenantId, surveyId: input.surveyId, itemType: input.itemType, prompt: prompt.slice(0, 1000), required: input.required ?? false, options: input.options ?? [], sortOrder: input.sortOrder ?? 0 } }),
);
return created as SurveyItemRow;
}
export async function removeItem(input: { tenantId: string; surveyId: string; itemId: string }): Promise<void> {
await withTenantRLS(input.tenantId, (tx) => tx.hrSurveyItem.deleteMany({ where: { id: input.itemId, tenantId: input.tenantId, surveyId: input.surveyId } }));
}
export async function listSurveys(tenantId: string, opts?: { includeArchived?: boolean }): Promise<SurveyRow[]> {
const rows = await withTenantRLS(tenantId, (tx) => tx.hrSurvey.findMany({ where: { tenantId, ...(opts?.includeArchived ? {} : { archivedAt: null }) }, orderBy: { createdAt: "desc" } }));
return rows as SurveyRow[];
}
export async function getSurveyWithItems(tenantId: string, surveyId: string): Promise<{ survey: SurveyRow; items: SurveyItemRow[] }> {
return withTenantRLS(tenantId, async (tx) => {
const survey = await tx.hrSurvey.findFirst({ where: { id: surveyId, tenantId, archivedAt: null } });
if (!survey) throw new CatalogError(foundationErrors.notFound, { surveyId });
const items = await tx.hrSurveyItem.findMany({ where: { tenantId, surveyId }, orderBy: { sortOrder: "asc" } });
return { survey: survey as SurveyRow, items: items as SurveyItemRow[] };
});
}
/** True when the caller already submitted (by identity or anonymous hash). */
export async function hasSubmitted(tenantId: string, surveyId: string, userId: string, isAnonymous: boolean): Promise<boolean> {
const where = isAnonymous ? { tenantId, surveyId, submitterHash: submitterHashFor(tenantId, surveyId, userId) } : { tenantId, surveyId, submitterUserId: userId };
const existing = await withTenantRLS(tenantId, (tx) => tx.hrSurveySubmission.findFirst({ where, select: { id: true } }));
return Boolean(existing);
}
export type SubmitResponseInput = { tenantId: string; surveyId: string; userId: string; answers: Record<string, unknown> };
export async function submitResponse(input: SubmitResponseInput): Promise<void> {
const { survey } = await getSurveyWithItems(input.tenantId, input.surveyId);
if (survey.status !== "open") throw new HrServiceError("hr.error.surveyNotOpen");
const submitterUserId = survey.isAnonymous ? null : input.userId;
const submitterHash = survey.isAnonymous ? submitterHashFor(input.tenantId, input.surveyId, input.userId) : null;
try {
await withTenantRLS(input.tenantId, (tx) =>
tx.hrSurveySubmission.create({ data: { tenantId: input.tenantId, surveyId: input.surveyId, submitterUserId, submitterHash, answers: input.answers as object } }),
);
} catch {
// Unique (surveyId, submitterUserId|submitterHash) violation ⇒ already done.
throw new HrServiceError("hr.error.surveyAlreadySubmitted");
}
// Audit WITHOUT the user id for anonymous surveys (no re-identification).
await createAuditEvent({ tenantId: input.tenantId, actorId: survey.isAnonymous ? null : input.userId, actorType: survey.isAnonymous ? "system" : "user", action: "HR_SURVEY_SUBMIT", targetType: "HrSurvey", targetId: input.surveyId, sourceModule: HR_AUDIT_MODULE, outcome: "success" });
}
export type SurveyItemResult = { itemId: string; itemType: HrSurveyItemType; prompt: string; responseCount: number; distribution: Record<string, number>; average: number | null; textResponses: string[] };
/** Aggregate results per item. Caller must hold hr.surveys.results (route gate).
* Returns raw numbers only — chart rendering is the VM/UI's job. */
export async function getResults(tenantId: string, surveyId: string): Promise<{ submissionCount: number; items: SurveyItemResult[] }> {
const { items } = await getSurveyWithItems(tenantId, surveyId);
const submissions = await withTenantRLS(tenantId, (tx) => tx.hrSurveySubmission.findMany({ where: { tenantId, surveyId }, select: { answers: true } }));
const results: SurveyItemResult[] = items.map((item) => {
const distribution: Record<string, number> = {};
const textResponses: string[] = [];
let sum = 0;
let numericCount = 0;
let responseCount = 0;
for (const submission of submissions) {
const answers = (submission.answers ?? {}) as Record<string, unknown>;
const value = answers[item.id];
if (value === undefined || value === null || value === "") continue;
responseCount += 1;
if (item.itemType === "text" || item.itemType === "date") {
textResponses.push(String(value).slice(0, 500));
} else if (item.itemType === "boolean") {
const key = value ? "true" : "false";
distribution[key] = (distribution[key] ?? 0) + 1;
} else if (item.itemType === "choice") {
const key = String(value);
distribution[key] = (distribution[key] ?? 0) + 1;
} else {
// rating_5 / nps — numeric distribution + average.
const num = Number(value);
if (Number.isFinite(num)) {
const key = String(num);
distribution[key] = (distribution[key] ?? 0) + 1;
sum += num;
numericCount += 1;
}
}
}
return { itemId: item.id, itemType: item.itemType, prompt: item.prompt, responseCount, distribution, average: numericCount > 0 ? sum / numericCount : null, textResponses };
});
return { submissionCount: submissions.length, items: results };
}
@@ -0,0 +1,223 @@
// P17 HR-Hub workflows (AK-P17b) — upload-reminder domain service.
//
// HR defines reminders (upload document X on a cadence). A BullMQ worker calls
// dispatchDueReminders() on a schedule; it creates per-employee dispatch rows
// (idempotent per reminder+employee+dueAt), notifies each employee (M011), and
// escalates overdue mandatory reminders to the manager. The cadence math itself
// is a pure function (computeNextDue in @hivegrid/view-models). Every tenant
// access runs inside withTenantRLS().
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { createNotificationDelivery } from "@hivegrid/db/notifications.server";
import { computeNextDue, type HrReminderCadenceKind } from "@hivegrid/view-models";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { HrServiceError } from "./hrService.server";
const HR_AUDIT_MODULE = "hr";
export type HrAudienceKind = "all" | "team" | "location";
export type HrDocumentKind = "contract" | "certificate" | "identification" | "qualification" | "other";
export type HrReminderStatus = "active" | "paused" | "completed";
export type ReminderRow = {
id: string;
tenantId: string;
title: string;
documentKind: HrDocumentKind;
cadenceKind: HrReminderCadenceKind;
intervalMonths: number | null;
audienceKind: HrAudienceKind;
audienceRef: string | null;
mandatory: boolean;
escalateToManager: boolean;
linkedFormId: string | null;
dueAt: Date | null;
status: HrReminderStatus;
createdAt: Date;
updatedAt: Date;
archivedAt: Date | null;
};
/** Audience member resolved by the worker (decoupled from this service). */
export type ReminderAudienceMember = { userId: string; managerUserId: string | null };
export type ResolveAudience = (reminder: ReminderRow) => Promise<ReminderAudienceMember[]>;
async function notifyQuiet(input: { tenantId: string; userId: string; messageKey: string; sourceKey: string; payloadMetadata?: Record<string, string> }): Promise<void> {
await createNotificationDelivery({
tenantId: input.tenantId,
userId: input.userId,
channel: "IN_APP",
category: "hr",
messageKey: input.messageKey,
sourceKey: input.sourceKey,
payloadMetadata: input.payloadMetadata ?? null,
}).catch(() => undefined);
}
export type CreateReminderInput = {
tenantId: string;
actorUserId: string;
title: string;
documentKind?: HrDocumentKind;
cadenceKind?: HrReminderCadenceKind;
intervalMonths?: number | null;
audienceKind?: HrAudienceKind;
audienceRef?: string | null;
mandatory?: boolean;
escalateToManager?: boolean;
linkedFormId?: string | null;
dueAt?: Date | null;
isDemoData?: boolean;
};
export async function createReminder(input: CreateReminderInput): Promise<ReminderRow> {
const title = input.title.trim();
if (!title) throw new HrServiceError("hr.error.reminderTitleRequired");
if ((input.cadenceKind ?? "once") === "every_n_months" && !(input.intervalMonths && input.intervalMonths > 0)) {
throw new HrServiceError("hr.error.reminderIntervalRequired");
}
const created = (await withTenantRLS(input.tenantId, (tx) =>
tx.employeeUploadReminder.create({
data: {
tenantId: input.tenantId,
title: title.slice(0, 255),
documentKind: input.documentKind ?? "other",
cadenceKind: input.cadenceKind ?? "once",
intervalMonths: input.intervalMonths ?? null,
audienceKind: input.audienceKind ?? "all",
audienceRef: input.audienceRef ?? null,
mandatory: input.mandatory ?? false,
escalateToManager: input.escalateToManager ?? false,
linkedFormId: input.linkedFormId ?? null,
dueAt: input.dueAt ?? null,
status: "active",
isDemoData: input.isDemoData ?? false,
},
}),
)) as ReminderRow;
await createAuditEvent({ tenantId: input.tenantId, actorId: input.actorUserId, actorType: "user", action: "HR_REMINDER_CREATE", targetType: "EmployeeUploadReminder", targetId: created.id, sourceModule: HR_AUDIT_MODULE, outcome: "success" });
return created;
}
export type UpdateReminderInput = Partial<Omit<CreateReminderInput, "tenantId" | "actorUserId">> & { tenantId: string; actorUserId: string; reminderId: string };
export async function updateReminder(input: UpdateReminderInput): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.employeeUploadReminder.findFirst({ where: { id: input.reminderId, tenantId: input.tenantId }, select: { id: true } });
if (!existing) throw new CatalogError(foundationErrors.notFound, { reminderId: input.reminderId });
await tx.employeeUploadReminder.update({
where: { id: input.reminderId },
data: {
...(input.title !== undefined ? { title: input.title.trim().slice(0, 255) } : {}),
...(input.documentKind !== undefined ? { documentKind: input.documentKind } : {}),
...(input.cadenceKind !== undefined ? { cadenceKind: input.cadenceKind } : {}),
...(input.intervalMonths !== undefined ? { intervalMonths: input.intervalMonths } : {}),
...(input.audienceKind !== undefined ? { audienceKind: input.audienceKind } : {}),
...(input.audienceRef !== undefined ? { audienceRef: input.audienceRef } : {}),
...(input.mandatory !== undefined ? { mandatory: input.mandatory } : {}),
...(input.escalateToManager !== undefined ? { escalateToManager: input.escalateToManager } : {}),
...(input.linkedFormId !== undefined ? { linkedFormId: input.linkedFormId } : {}),
...(input.dueAt !== undefined ? { dueAt: input.dueAt } : {}),
},
});
});
await createAuditEvent({ tenantId: input.tenantId, actorId: input.actorUserId, actorType: "user", action: "HR_REMINDER_UPDATE", targetType: "EmployeeUploadReminder", targetId: input.reminderId, sourceModule: HR_AUDIT_MODULE, outcome: "success" });
}
export async function setReminderStatus(input: { tenantId: string; actorUserId: string; reminderId: string; status: HrReminderStatus }): Promise<void> {
await withTenantRLS(input.tenantId, (tx) => tx.employeeUploadReminder.updateMany({ where: { id: input.reminderId, tenantId: input.tenantId }, data: { status: input.status } }));
await createAuditEvent({ tenantId: input.tenantId, actorId: input.actorUserId, actorType: "user", action: "HR_REMINDER_STATUS", targetType: "EmployeeUploadReminder", targetId: input.reminderId, sourceModule: HR_AUDIT_MODULE, outcome: "success", metadata: { status: input.status } });
}
export async function archiveReminder(input: { tenantId: string; actorUserId: string; reminderId: string }): Promise<void> {
await withTenantRLS(input.tenantId, (tx) => tx.employeeUploadReminder.updateMany({ where: { id: input.reminderId, tenantId: input.tenantId }, data: { archivedAt: new Date(), status: "completed" } }));
await createAuditEvent({ tenantId: input.tenantId, actorId: input.actorUserId, actorType: "user", action: "HR_REMINDER_ARCHIVE", targetType: "EmployeeUploadReminder", targetId: input.reminderId, sourceModule: HR_AUDIT_MODULE, outcome: "success" });
}
export async function listReminders(tenantId: string, opts?: { includeArchived?: boolean }): Promise<ReminderRow[]> {
const rows = await withTenantRLS(tenantId, (tx) =>
tx.employeeUploadReminder.findMany({ where: { tenantId, ...(opts?.includeArchived ? {} : { archivedAt: null }) }, orderBy: { createdAt: "desc" } }),
);
return rows as ReminderRow[];
}
export type DispatchRow = {
id: string;
reminderId: string;
employeeUserId: string;
dueAt: Date;
status: "pending" | "sent" | "escalated" | "acknowledged";
sentAt: Date | null;
acknowledgedAt: Date | null;
escalatedAt: Date | null;
};
export async function listDispatches(tenantId: string, reminderId: string): Promise<DispatchRow[]> {
const rows = await withTenantRLS(tenantId, (tx) => tx.employeeUploadReminderDispatch.findMany({ where: { tenantId, reminderId }, orderBy: { dueAt: "desc" } }));
return rows as DispatchRow[];
}
/**
* Worker entry point — dispatch all reminders due at/<= `now`. Idempotent: the
* unique (reminderId, employeeUserId, dueAt) means a re-run never double-sends.
* After dispatching, the reminder's `dueAt` advances by its cadence (or the
* reminder completes for a one-off). Returns the number of dispatches created.
*/
export async function dispatchDueReminders(input: { tenantId: string; now: Date; resolveAudience: ResolveAudience }): Promise<number> {
const due = await withTenantRLS(input.tenantId, (tx) =>
tx.employeeUploadReminder.findMany({ where: { tenantId: input.tenantId, status: "active", archivedAt: null, dueAt: { not: null, lte: input.now } } }),
);
let created = 0;
for (const reminder of due as ReminderRow[]) {
const members = await input.resolveAudience(reminder);
const dueAt = reminder.dueAt ?? input.now;
for (const member of members) {
const result = await withTenantRLS(input.tenantId, (tx) =>
tx.employeeUploadReminderDispatch.createMany({
data: [{ tenantId: input.tenantId, reminderId: reminder.id, employeeUserId: member.userId, dueAt, status: "sent", sentAt: input.now }],
skipDuplicates: true,
}),
);
if (result.count > 0) {
created += result.count;
await notifyQuiet({ tenantId: input.tenantId, userId: member.userId, messageKey: "hr.notify.reminder.due", sourceKey: `hr-reminder:${reminder.id}:${dueAt.getTime()}:${member.userId}`, payloadMetadata: { reminderId: reminder.id } });
}
}
const next = computeNextDue({ cadenceKind: reminder.cadenceKind, intervalMonths: reminder.intervalMonths, from: dueAt });
await withTenantRLS(input.tenantId, (tx) =>
tx.employeeUploadReminder.update({ where: { id: reminder.id }, data: next ? { dueAt: next } : { dueAt: null, status: "completed" } }),
);
}
return created;
}
/**
* Escalate still-pending mandatory dispatches older than `graceMs` to the
* employee's manager. The worker resolves the manager via `resolveAudience`.
*/
export async function escalateOverdueDispatches(input: { tenantId: string; now: Date; graceMs: number; resolveManager: (employeeUserId: string) => Promise<string | null> }): Promise<number> {
const cutoff = new Date(input.now.getTime() - input.graceMs);
const stale = await withTenantRLS(input.tenantId, (tx) =>
tx.employeeUploadReminderDispatch.findMany({
where: { tenantId: input.tenantId, status: "sent", dueAt: { lt: cutoff }, reminder: { escalateToManager: true, mandatory: true } },
}),
);
let escalated = 0;
for (const dispatch of stale as DispatchRow[]) {
const managerId = await input.resolveManager(dispatch.employeeUserId);
await withTenantRLS(input.tenantId, (tx) => tx.employeeUploadReminderDispatch.update({ where: { id: dispatch.id }, data: { status: "escalated", escalatedAt: input.now } }));
escalated += 1;
if (managerId) {
await notifyQuiet({ tenantId: input.tenantId, userId: managerId, messageKey: "hr.notify.reminder.escalated", sourceKey: `hr-reminder-escalate:${dispatch.id}`, payloadMetadata: { dispatchId: dispatch.id } });
}
}
return escalated;
}
/** Employee acknowledges (uploaded the requested document). */
export async function acknowledgeDispatch(input: { tenantId: string; dispatchId: string; userId: string }): Promise<void> {
await withTenantRLS(input.tenantId, (tx) =>
tx.employeeUploadReminderDispatch.updateMany({ where: { id: input.dispatchId, tenantId: input.tenantId, employeeUserId: input.userId }, data: { status: "acknowledged", acknowledgedAt: new Date() } }),
);
}
@@ -0,0 +1,84 @@
// R-P5 (P5) §P3 — shared loader/action guard for Apps-Engine routes (mirrors
// taskAccess/hrAccess). Resolves tenant context + permissions once; module-off
// renders a locked empty VM on GET, 404s on write (Bauprinzip A.5.3).
import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo } from "~/utils/session.server";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
import { AppsEngineServiceError } from "./appsEngineService.server";
import { INTEGRATIONS_MODULE_KEY } from "./integrationsRoutePaths";
// Re-exported for back-compat; the canonical definition lives in the client-safe
// integrationsRoutePaths module so route `handle` exports can reference it without
// pulling this server-only guard into the client bundle.
export { INTEGRATIONS_MODULE_KEY };
export type IntegrationsRouteContext = {
tenantId: string;
userId: string;
permissions: readonly string[];
hasModule: boolean;
};
export async function loadIntegrationsContext({
request,
params,
requireModule = false,
}: {
request: Request;
params: Record<string, string | undefined>;
requireModule?: boolean;
}): Promise<IntegrationsRouteContext> {
await requireAuth({ request, params });
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
if (!tenantId || !userInfo.userId) {
throw new CatalogError(foundationErrors.notFound);
}
const [hasModule, permissions] = await Promise.all([
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: INTEGRATIONS_MODULE_KEY }),
getPermissionsByUser(userInfo.userId, tenantId),
]);
if (requireModule && !hasModule) {
throw new CatalogError(foundationErrors.notFound, { module: INTEGRATIONS_MODULE_KEY });
}
return { tenantId, userId: userInfo.userId, permissions, hasModule };
}
/** True if the user holds `permission` or a broader bundle (`integrations.admin`
* implies everything). */
export function integrationsHasPermission(ctx: IntegrationsRouteContext, permission: string): boolean {
return ctx.permissions.includes(permission) || ctx.permissions.includes("integrations.admin");
}
/** Require an integrations.* permission (admin-aware); 404 if missing (A.5.3). */
export function requireIntegrationsPermission(ctx: IntegrationsRouteContext, permission: string): IntegrationsRouteContext {
if (!integrationsHasPermission(ctx, permission)) {
throw new CatalogError(foundationErrors.notFound, { permission });
}
if (ctx.permissions.includes(permission)) {
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, permission);
}
return ctx;
}
export function notFoundResponse(): Response {
return new Response("Not Found", { status: 404 });
}
export function badRequestResponse(): Response {
return new Response("Bad Request", { status: 400 });
}
/** Map an Apps-Engine action error to a JSON Response. */
export function integrationsActionErrorResponse(error: unknown): Response {
if (error instanceof CatalogError) {
return Response.json({ error: error.i18nKey, code: error.code }, { status: error.status });
}
if (error instanceof AppsEngineServiceError) {
return Response.json({ error: error.messageKey }, { status: 400 });
}
throw error;
}
@@ -0,0 +1,29 @@
// R-P5 (P5) §P3 — pure route-path builders for Apps-Engine URLs. Loaders build
// these and pass them into the VMs so the VMs stay routing-agnostic.
//
// NOTE: the designer brief writes "/admin/integrations"; since DataConnection is
// TENANT-scoped (tenant connector + integrations.* tenant permission), the screens
// live under the tenant app at /<tenant>/integrations. The platform-admin drift
// warning is a separate P19 surface. (Confirm with David in the D-P5 delta.)
// Tenant connector module key. It lives in this client-safe module (not in
// integrationsAccess.server) so a route `handle` export can reference it without
// dragging the server-only access guard into the client bundle (RR code-splitting
// only strips loader/action/middleware/headers, not `handle`).
export const INTEGRATIONS_MODULE_KEY = "integrations";
export function integrationsCatalogPath(tenantSlug: string): string {
return `/${tenantSlug}/integrations`;
}
export function integrationsAppPath(tenantSlug: string, appKey: string): string {
return `/${tenantSlug}/integrations/${appKey}`;
}
export function integrationsSyncsPath(tenantSlug: string, appKey: string, connectionId: string): string {
return `/${tenantSlug}/integrations/${appKey}/${connectionId}/syncs`;
}
export function integrationsSyncRunPath(tenantSlug: string, appKey: string, connectionId: string, runId: string): string {
return `/${tenantSlug}/integrations/${appKey}/${connectionId}/syncs/${runId}`;
}
@@ -0,0 +1,60 @@
import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo } from "~/utils/session.server";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
import { LEADS_MODULE_KEY } from "./leadRoutePaths";
import { LeadServiceError, type LeadVisibilityContext } from "./leadService.server";
export type LeadRouteContext = LeadVisibilityContext & {
tenantId: string;
hasModule: boolean;
};
export async function loadLeadContext({
request,
params,
requireModule = false,
}: {
request: Request;
params: Record<string, string | undefined>;
requireModule?: boolean;
}): Promise<LeadRouteContext> {
await requireAuth({ request, params });
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
if (!tenantId || !userInfo.userId) {
throw new CatalogError(foundationErrors.notFound);
}
const [hasModule, permissions] = await Promise.all([
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: LEADS_MODULE_KEY }),
getPermissionsByUser(userInfo.userId, tenantId),
]);
if (requireModule && !hasModule) {
throw new CatalogError(foundationErrors.notFound, { module: LEADS_MODULE_KEY });
}
return { tenantId, userId: userInfo.userId, permissions, hasModule };
}
export function requireLeadPermission(ctx: LeadRouteContext, permission: string): LeadRouteContext {
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, permission);
return ctx;
}
export function notFoundResponse(): Response {
return new Response("Not Found", { status: 404 });
}
export function badRequestResponse(): Response {
return new Response("Bad Request", { status: 400 });
}
export function leadActionErrorResponse(error: unknown): Response {
if (error instanceof CatalogError) {
return Response.json({ error: error.i18nKey, code: error.code }, { status: error.status });
}
if (error instanceof LeadServiceError) {
return Response.json({ error: error.messageKey }, { status: 400 });
}
throw error;
}
@@ -0,0 +1,65 @@
import type { JsonValue } from "@hivegrid/foundation";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { logActivity } from "@hivegrid/activity";
import type { LeadRouteContext } from "./leadAccess.server";
import type { LeadRow } from "./leadService.server";
export type LeadAuditAction =
| "lead.created"
| "lead.updated"
| "lead.status_changed"
| "lead.assigned"
| "lead.bulk_updated"
| "lead.qualified"
| "lead.convert_requested"
| "lead.source_created"
| "lead.source_updated"
| "lead.anti_spam_updated";
export async function auditLeadEvent(input: {
ctx: Pick<LeadRouteContext, "tenantId" | "userId">;
action: LeadAuditAction;
targetType: "lead" | "lead_source" | "lead_anti_spam";
targetId: string;
metadata?: Record<string, JsonValue>;
}): Promise<void> {
try {
await createAuditEvent({
tenantId: input.ctx.tenantId,
actorId: input.ctx.userId,
actorType: "user",
action: input.action,
targetType: input.targetType,
targetId: input.targetId,
metadata: input.metadata ?? null,
});
} catch {
// Best-effort: audit failures are reported upstream, not to the user action.
}
}
export async function logLeadActivity(input: {
ctx: Pick<LeadRouteContext, "tenantId" | "userId">;
leadId: string;
activityType: "lead_created" | "lead_updated" | "lead_qualified" | "assignee_changed" | "status_changed";
summaryText: string;
}): Promise<void> {
try {
await logActivity({
tenantId: input.ctx.tenantId,
actorUserId: input.ctx.userId,
actorKind: "user",
activityType: input.activityType,
subjectType: "lead",
subjectId: input.leadId,
summaryText: input.summaryText,
});
} catch {
// Activity is best-effort; never break the mutation.
}
}
export function leadDisplayName(row: Pick<LeadRow, "vorname" | "nachname" | "email" | "telefon" | "quelle">): string {
const name = `${row.vorname ?? ""} ${row.nachname ?? ""}`.trim();
return name || row.email || row.telefon || row.quelle;
}
@@ -0,0 +1,55 @@
import { createLead, type LeadRow } from "./leadService.server";
type BaseIngestionInput = {
tenantId: string;
userId?: string | null;
sourceId?: string | null;
zustaendigerUserId?: string | null;
vorname?: string | null;
nachname?: string | null;
email?: string | null;
telefon?: string | null;
message?: string | null;
submitterIpHash?: string | null;
isDemoData?: boolean;
};
export async function ingestFormLead(input: BaseIngestionInput & { formId: string; submissionId: string; values: Record<string, unknown> }): Promise<LeadRow> {
return createLead({
...input,
quelle: "form",
quelleDetail: { formId: input.formId, submissionId: input.submissionId },
sourceOrigin: `form:${input.formId}`,
rohdaten: { values: input.values, submissionId: input.submissionId },
});
}
export async function ingestEmailLead(input: BaseIngestionInput & { messageId: string; mailbox?: string | null; subject?: string | null }): Promise<LeadRow> {
return createLead({
...input,
quelle: "email",
quelleDetail: { messageId: input.messageId, mailbox: input.mailbox ?? null },
sourceOrigin: input.mailbox ? `email:${input.mailbox}` : "email",
rohdaten: { messageId: input.messageId, subject: input.subject ?? null },
});
}
export async function ingestAirCallLead(input: BaseIngestionInput & { callId: string; direction?: string | null; answeredAt?: string | null }): Promise<LeadRow> {
return createLead({
...input,
quelle: "aircall",
quelleDetail: { callId: input.callId, direction: input.direction ?? null },
sourceOrigin: "aircall",
rohdaten: { callId: input.callId, answeredAt: input.answeredAt ?? null },
});
}
export async function ingestCustomLead(input: BaseIngestionInput & { sourceKey: string; payload: Record<string, unknown> }): Promise<LeadRow> {
return createLead({
...input,
quelle: "custom",
quelleDetail: { sourceKey: input.sourceKey },
sourceOrigin: `custom:${input.sourceKey}`,
rohdaten: input.payload,
});
}
@@ -0,0 +1,65 @@
export type LeadStatus = "new" | "qualified" | "converted" | "lost" | "spam";
export type LeadQuelle = "form" | "email" | "aircall" | "manual" | "custom";
export type LeadSortField = "createdAt" | "status" | "quelle" | "spamScore";
export type SortDir = "asc" | "desc";
export interface LeadListFilter {
status: LeadStatus[] | null;
quelle: LeadQuelle | null;
zustaendigerUserId: string | null;
search: string | null;
includeSpam: boolean;
includeConverted: boolean;
}
export interface LeadListQuery {
filter: LeadListFilter;
sort: { field: LeadSortField; dir: SortDir };
cursor: string | null;
}
const STATUSES = new Set<LeadStatus>(["new", "qualified", "converted", "lost", "spam"]);
const QUELLEN = new Set<LeadQuelle>(["form", "email", "aircall", "manual", "custom"]);
const SORT_FIELDS = new Set<LeadSortField>(["createdAt", "status", "quelle", "spamScore"]);
function oneOf<T>(value: string | null, allowed: Set<T>): T | null {
return value && (allowed as Set<string>).has(value) ? (value as T) : null;
}
function parseStatuses(params: URLSearchParams): LeadStatus[] | null {
const values = [...params.getAll("status"), ...(params.get("statuses") ?? "").split(",")]
.map((value) => value.trim())
.filter((value): value is LeadStatus => STATUSES.has(value as LeadStatus));
const unique = [...new Set(values)];
return unique.length > 0 ? unique : null;
}
export function parseLeadListQuery(params: URLSearchParams): LeadListQuery {
const sortField = oneOf<LeadSortField>(params.get("sort"), SORT_FIELDS) ?? "createdAt";
return {
filter: {
status: parseStatuses(params),
quelle: oneOf<LeadQuelle>(params.get("quelle"), QUELLEN),
zustaendigerUserId: params.get("owner")?.trim() || null,
search: params.get("q")?.trim() || null,
includeSpam: params.get("spam") === "1",
includeConverted: params.get("converted") === "1",
},
sort: { field: sortField, dir: params.get("dir") === "asc" ? "asc" : "desc" },
cursor: params.get("cursor")?.trim() || null,
};
}
export function leadListQueryToParams(query: LeadListQuery): URLSearchParams {
const params = new URLSearchParams();
if (query.filter.status && query.filter.status.length > 0) params.set("statuses", query.filter.status.join(","));
if (query.filter.quelle) params.set("quelle", query.filter.quelle);
if (query.filter.zustaendigerUserId) params.set("owner", query.filter.zustaendigerUserId);
if (query.filter.search) params.set("q", query.filter.search);
if (query.filter.includeSpam) params.set("spam", "1");
if (query.filter.includeConverted) params.set("converted", "1");
if (query.sort.field !== "createdAt") params.set("sort", query.sort.field);
if (query.sort.dir !== "desc") params.set("dir", query.sort.dir);
if (query.cursor) params.set("cursor", query.cursor);
return params;
}
@@ -0,0 +1,29 @@
export const LEADS_MODULE_KEY = "leads";
export function leadsPath(tenantSlug: string): string {
return `/${tenantSlug}/leads`;
}
export function leadNewPath(tenantSlug: string): string {
return `/${tenantSlug}/leads/new`;
}
export function leadDetailPath(tenantSlug: string, leadId: string): string {
return `/${tenantSlug}/leads/${leadId}`;
}
export function leadStatisticsPath(tenantSlug: string): string {
return `/${tenantSlug}/leads/statistics`;
}
export function leadEventsPath(tenantSlug: string): string {
return `/${tenantSlug}/leads/events`;
}
export function leadSourcesAdminPath(tenantSlug: string): string {
return `/${tenantSlug}/admin/lead-sources`;
}
export function leadAntiSpamAdminPath(tenantSlug: string): string {
return `/${tenantSlug}/admin/lead-anti-spam`;
}
@@ -0,0 +1,779 @@
import { CatalogError, foundationErrors, notify } from "@hivegrid/foundation";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import { buildWorkflowTriggerOutboxEvent, type QueueJsonValue } from "@hivegrid/queue";
import { publishLeadSearchUpsert } from "~/services/search/searchIndexProjection.server";
import { db } from "~/utils/db.server";
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import type { LeadListFilter, LeadSortField, SortDir } from "./leadListQuery";
export class LeadServiceError extends Error {
readonly messageKey: string;
constructor(messageKey: string) {
super(messageKey);
this.name = "LeadServiceError";
this.messageKey = messageKey;
}
}
export type LeadQuelle = "form" | "email" | "aircall" | "manual" | "custom";
export type LeadStatus = "new" | "qualified" | "converted" | "lost" | "spam";
export type LeadWeiterverarbeitungFreigabe = "ja" | "nein" | "unklar";
export type LeadSourceType = "system" | "custom";
export type LeadAntiSpamMode = "quarantine" | "spam";
export type LeadVisibilityContext = {
userId: string;
permissions: readonly string[];
};
export function canReadAllLeads(ctx: LeadVisibilityContext): boolean {
return ctx.permissions.includes("leads.read_all");
}
export function ownerScopeWhere(ctx: LeadVisibilityContext): { zustaendigerUserId?: string } {
return canReadAllLeads(ctx) ? {} : { zustaendigerUserId: ctx.userId };
}
export type LeadRow = {
id: string;
tenantId: string;
createdByUserId: string | null;
zustaendigerUserId: string | null;
quelle: LeadQuelle;
quelleDetail: unknown;
sourceId: string | null;
sourceOrigin: string | null;
submitterIpHash: string | null;
status: LeadStatus;
weiterverarbeitungFreigabe: LeadWeiterverarbeitungFreigabe;
vorname: string | null;
nachname: string | null;
email: string | null;
telefon: string | null;
message: string | null;
rohdaten: unknown;
spamScore: number;
spamReason: string | null;
isQuarantined: boolean;
konvertiertProjektId: string | null;
verknuepfterKontaktId: string | null;
convertedAt: Date | null;
lostAt: Date | null;
spamMarkedAt: Date | null;
autoDeleteAt: Date | null;
isDemoData: boolean;
createdAt: Date;
updatedAt: Date;
archivedAt: Date | null;
};
export type LeadSourceRow = {
id: string;
tenantId: string;
type: LeadSourceType;
key: string;
name: string;
displayLabel: string;
defaultZustaendigerUserId: string | null;
defaultTags: unknown;
webhookTokenHash: string | null;
pausedAt: Date | null;
archivedAt: Date | null;
isDemoData: boolean;
createdAt: Date;
updatedAt: Date;
};
export type LeadAntiSpamConfigRow = {
id: string;
tenantId: string;
perSourcePerHourLimit: number;
perIpPerHourLimit: number;
anomalySpikeFactor: number;
mode: LeadAntiSpamMode;
disposableDomainEnabled: boolean;
honeypotEnabled: boolean;
fastSubmitEnabled: boolean;
lostAutoDeleteDays: number;
isDemoData: boolean;
createdAt: Date;
updatedAt: Date;
};
const DEFAULT_LIMIT = 50;
const SPAM_AUTO_DELETE_DAYS = 30;
const TERMINAL: ReadonlySet<LeadStatus> = new Set(["converted", "lost", "spam"]);
const ALLOWED_STATUS_TRANSITIONS: Readonly<Record<LeadStatus, readonly LeadStatus[]>> = {
new: ["qualified", "lost", "spam"],
qualified: ["converted", "lost", "spam"],
converted: [],
lost: [],
spam: [],
};
function normalizeEmail(email?: string | null): string | null {
const value = email?.trim().toLowerCase();
return value || null;
}
function normalizeTelefon(telefon?: string | null): string | null {
const value = telefon?.trim();
return value || null;
}
function leadNamePresent(input: { vorname?: string | null; nachname?: string | null; email?: string | null; telefon?: string | null; message?: string | null }): boolean {
return Boolean(input.vorname?.trim() || input.nachname?.trim() || input.email?.trim() || input.telefon?.trim() || input.message?.trim());
}
function normalizeOptionalText(value?: string | null): string | null {
const normalized = value?.trim();
return normalized || null;
}
async function ensureAntiSpamConfigWithTx(tx: TenantRlsClient, tenantId: string): Promise<LeadAntiSpamConfigRow> {
const existing = await tx.leadAntiSpamConfig.findUnique({ where: { tenantId } });
if (existing) return existing as LeadAntiSpamConfigRow;
const created = await tx.leadAntiSpamConfig.create({ data: { tenantId } });
return created as LeadAntiSpamConfigRow;
}
export function canTransitionLeadStatus(from: LeadStatus, to: LeadStatus): boolean {
return from === to || ALLOWED_STATUS_TRANSITIONS[from].includes(to);
}
function assertStatusTransition(from: LeadStatus, to: LeadStatus): void {
if (!canTransitionLeadStatus(from, to)) {
throw new LeadServiceError("leads.error.invalidStatusTransition");
}
}
function autoDeleteAtForStatus(status: LeadStatus, now: Date, config: Pick<LeadAntiSpamConfigRow, "lostAutoDeleteDays">): Date | null {
if (status === "spam") {
return new Date(now.getTime() + SPAM_AUTO_DELETE_DAYS * 24 * 60 * 60 * 1000);
}
if (status === "lost" && config.lostAutoDeleteDays > 0) {
return new Date(now.getTime() + config.lostAutoDeleteDays * 24 * 60 * 60 * 1000);
}
return null;
}
function statusTimestamps(status: LeadStatus, now: Date, config: Pick<LeadAntiSpamConfigRow, "lostAutoDeleteDays">) {
return {
...(status === "qualified" ? { weiterverarbeitungFreigabe: "ja" as const } : {}),
...(status === "converted" ? { convertedAt: now } : {}),
...(status === "lost" ? { lostAt: now } : {}),
...(status === "spam" ? { spamMarkedAt: now } : {}),
...(TERMINAL.has(status) ? { autoDeleteAt: autoDeleteAtForStatus(status, now, config) } : {}),
};
}
function toWorkflowPayload(input: {
lead: Pick<LeadRow, "id" | "tenantId" | "quelle" | "sourceId" | "status" | "weiterverarbeitungFreigabe" | "zustaendigerUserId" | "konvertiertProjektId" | "verknuepfterKontaktId" | "spamScore" | "isQuarantined">;
action: "created" | "qualified" | "status_changed" | "convert_requested" | "converted";
}): QueueJsonValue {
return {
leadId: input.lead.id,
tenantId: input.lead.tenantId,
action: input.action,
quelle: input.lead.quelle,
sourceId: input.lead.sourceId,
status: input.lead.status,
weiterverarbeitungFreigabe: input.lead.weiterverarbeitungFreigabe,
zustaendigerUserId: input.lead.zustaendigerUserId,
konvertiertProjektId: input.lead.konvertiertProjektId,
verknuepfterKontaktId: input.lead.verknuepfterKontaktId,
spamScore: input.lead.spamScore,
isQuarantined: input.lead.isQuarantined,
};
}
async function publishLeadWorkflowEvent(
tx: TenantRlsClient,
input: {
tenantId: string;
userId: string | null;
lead: LeadRow;
event: "lead.created" | "lead.qualified" | "lead.status_changed" | "lead.convert_requested" | "lead.converted";
action: "created" | "qualified" | "status_changed" | "convert_requested" | "converted";
},
): Promise<void> {
await publishOutboxEvent(
tx as unknown as OutboxPublisherTransaction,
buildWorkflowTriggerOutboxEvent({
tenantId: input.tenantId,
event: input.event,
data: toWorkflowPayload({ lead: input.lead, action: input.action }),
userId: input.userId,
sourceId: `lead:${input.lead.id}:${input.action}`,
}),
);
}
async function notifyLeadSourcePausedAdmins(
tx: TenantRlsClient,
input: { tenantId: string; source: Pick<LeadSourceRow, "id" | "key" | "name">; reason: string },
): Promise<void> {
try {
const admins = await tx.userRole.findMany({
where: {
tenantId: input.tenantId,
role: { permissions: { some: { permission: { name: "leads.admin" } } } },
},
select: { userId: true },
});
const userIds = [...new Set(admins.map((row) => row.userId))];
await Promise.all(
userIds.map((userId) =>
notify(
{
tenantId: input.tenantId,
userId,
channel: "IN_APP",
category: "leads",
messageKey: "leads.notification.sourcePaused",
sourceKey: `lead-source-paused:${input.source.id}`,
payloadMetadata: { sourceId: input.source.id, sourceKey: input.source.key, sourceName: input.source.name, reason: input.reason },
},
tx as unknown as Parameters<typeof notify>[1],
),
),
);
} catch {
// Notification failures must not lose the lead submission.
}
}
function computeSpam(input: {
email: string | null;
message?: string | null;
rohdaten?: unknown;
config: Pick<LeadAntiSpamConfigRow, "disposableDomainEnabled" | "honeypotEnabled" | "fastSubmitEnabled" | "mode">;
}): { score: number; reason: string | null; quarantine: boolean; spam: boolean } {
let score = 0;
const reasons: string[] = [];
const raw = typeof input.rohdaten === "object" && input.rohdaten ? (input.rohdaten as Record<string, unknown>) : {};
const emailDomain = input.email?.split("@")[1] ?? "";
if (input.config.disposableDomainEnabled && ["mailinator.com", "10minutemail.com", "example.invalid"].includes(emailDomain)) {
score += 45;
reasons.push("disposable_domain");
}
if (input.config.honeypotEnabled && typeof raw.honeypot === "string" && raw.honeypot.trim()) {
score += 60;
reasons.push("honeypot");
}
const submitSeconds = typeof raw.submitSeconds === "number" ? raw.submitSeconds : null;
if (input.config.fastSubmitEnabled && submitSeconds !== null && submitSeconds < 3) {
score += 35;
reasons.push("fast_submit");
}
const spam = score >= 80 && input.config.mode === "spam";
const quarantine = score >= 50 && !spam;
return { score, reason: reasons.length > 0 ? reasons.join(",") : null, quarantine, spam };
}
async function computeRateAndAnomalySignals(input: {
tx: TenantRlsClient;
tenantId: string;
config: Pick<LeadAntiSpamConfigRow, "perSourcePerHourLimit" | "perIpPerHourLimit" | "anomalySpikeFactor">;
source: LeadSourceRow | null;
quelle: LeadQuelle;
submitterIpHash: string | null;
now: Date;
}): Promise<{ score: number; reasons: string[]; pauseSource: boolean }> {
const oneHourAgo = new Date(input.now.getTime() - 60 * 60 * 1000);
const dayAgo = new Date(input.now.getTime() - 24 * 60 * 60 * 1000);
const sourceWhere = input.source
? { sourceId: input.source.id }
: { sourceId: null, quelle: input.quelle };
const [sourceHourCount, sourceDayCount, ipHourCount] = await Promise.all([
input.tx.inboxLead.count({ where: { tenantId: input.tenantId, createdAt: { gte: oneHourAgo }, ...sourceWhere } }),
input.tx.inboxLead.count({ where: { tenantId: input.tenantId, createdAt: { gte: dayAgo }, ...sourceWhere } }),
input.submitterIpHash
? input.tx.inboxLead.count({ where: { tenantId: input.tenantId, submitterIpHash: input.submitterIpHash, createdAt: { gte: oneHourAgo } } })
: Promise.resolve(0),
]);
const reasons: string[] = [];
let score = 0;
let pauseSource = false;
if (sourceHourCount >= input.config.perSourcePerHourLimit) {
score += 60;
reasons.push("source_rate_limit");
}
if (ipHourCount >= input.config.perIpPerHourLimit) {
score += 60;
reasons.push("ip_rate_limit");
}
const previousHoursAverage = Math.max(1, Math.ceil(Math.max(0, sourceDayCount - sourceHourCount) / 23));
if (sourceHourCount >= previousHoursAverage * input.config.anomalySpikeFactor && sourceHourCount >= input.config.anomalySpikeFactor) {
score += 80;
reasons.push("source_anomaly_spike");
pauseSource = Boolean(input.source);
}
return { score, reasons, pauseSource };
}
export type CreateLeadInput = {
tenantId: string;
userId?: string | null;
quelle: LeadQuelle;
quelleDetail?: unknown;
sourceId?: string | null;
sourceOrigin?: string | null;
submitterIpHash?: string | null;
vorname?: string | null;
nachname?: string | null;
email?: string | null;
telefon?: string | null;
message?: string | null;
rohdaten?: unknown;
zustaendigerUserId?: string | null;
weiterverarbeitungFreigabe?: LeadWeiterverarbeitungFreigabe;
isDemoData?: boolean;
};
export async function createLead(input: CreateLeadInput): Promise<LeadRow> {
if (!leadNamePresent(input)) {
throw new LeadServiceError("leads.error.identityRequired");
}
const lead = await withTenantRLS(input.tenantId, async (tx) => {
const now = new Date();
const config = await ensureAntiSpamConfigWithTx(tx, input.tenantId);
const source = input.sourceId
? await tx.leadSource.findFirst({ where: { id: input.sourceId, tenantId: input.tenantId, archivedAt: null } })
: null;
if (source?.pausedAt) {
throw new LeadServiceError("leads.error.sourcePaused");
}
const email = normalizeEmail(input.email);
const telefon = normalizeTelefon(input.telefon);
const submitterIpHash = normalizeOptionalText(input.submitterIpHash);
const spam = computeSpam({ email, message: input.message, rohdaten: input.rohdaten, config });
const rateSignals = await computeRateAndAnomalySignals({
tx,
tenantId: input.tenantId,
config,
source: source as LeadSourceRow | null,
quelle: input.quelle,
submitterIpHash,
now,
});
const spamScore = Math.min(100, spam.score + rateSignals.score);
const spamReasons = [...(spam.reason ? spam.reason.split(",") : []), ...rateSignals.reasons];
const status: LeadStatus = spamScore >= 80 && config.mode === "spam" ? "spam" : "new";
const isQuarantined = status !== "spam" && (spam.quarantine || spamScore >= 50);
if (source && rateSignals.pauseSource) {
await tx.leadSource.update({ where: { id: source.id }, data: { pausedAt: now } });
await notifyLeadSourcePausedAdmins(tx, { tenantId: input.tenantId, source: source as LeadSourceRow, reason: "source_anomaly_spike" });
}
const created = await tx.inboxLead.create({
data: {
tenantId: input.tenantId,
createdByUserId: input.userId ?? null,
zustaendigerUserId: input.zustaendigerUserId ?? source?.defaultZustaendigerUserId ?? input.userId ?? null,
quelle: input.quelle,
quelleDetail: input.quelleDetail ?? undefined,
sourceId: source?.id ?? null,
sourceOrigin: normalizeOptionalText(input.sourceOrigin),
submitterIpHash,
status,
weiterverarbeitungFreigabe: input.weiterverarbeitungFreigabe ?? "unklar",
vorname: input.vorname?.trim() || null,
nachname: input.nachname?.trim() || null,
email,
telefon,
message: input.message?.trim() || null,
rohdaten: input.rohdaten ?? undefined,
spamScore,
spamReason: spamReasons.length > 0 ? spamReasons.join(",") : null,
isQuarantined,
spamMarkedAt: status === "spam" ? now : null,
autoDeleteAt: autoDeleteAtForStatus(status, now, config),
isDemoData: input.isDemoData ?? false,
},
});
await publishLeadWorkflowEvent(tx, {
tenantId: input.tenantId,
userId: input.userId ?? null,
lead: created as LeadRow,
event: "lead.created",
action: "created",
});
await publishLeadSearchUpsert(tx, created as LeadRow);
return created;
});
return lead as LeadRow;
}
export type ListLeadsResult = { rows: LeadRow[]; nextCursor: string | null; total: number };
function effectiveStatuses(filter: LeadListFilter): LeadStatus[] {
if (filter.status?.length) return filter.status;
const base: LeadStatus[] = ["new", "qualified"];
if (filter.includeConverted) base.push("converted");
if (filter.includeSpam) base.push("spam");
return base;
}
function whereForLeadList(tenantId: string, ctx: LeadVisibilityContext, filter: LeadListFilter) {
return {
tenantId,
archivedAt: null,
...ownerScopeWhere(ctx),
status: { in: effectiveStatuses(filter) },
...(filter.quelle ? { quelle: filter.quelle } : {}),
...(filter.zustaendigerUserId ? { zustaendigerUserId: filter.zustaendigerUserId } : {}),
...(filter.search
? {
OR: [
{ vorname: { contains: filter.search, mode: "insensitive" as const } },
{ nachname: { contains: filter.search, mode: "insensitive" as const } },
{ email: { contains: filter.search, mode: "insensitive" as const } },
{ telefon: { contains: filter.search, mode: "insensitive" as const } },
{ message: { contains: filter.search, mode: "insensitive" as const } },
],
}
: {}),
};
}
function orderBy(sort: { field: LeadSortField; dir: SortDir }) {
if (sort.field === "status") return [{ status: sort.dir }, { createdAt: "desc" as const }, { id: "desc" as const }];
if (sort.field === "quelle") return [{ quelle: sort.dir }, { createdAt: "desc" as const }, { id: "desc" as const }];
if (sort.field === "spamScore") return [{ spamScore: sort.dir }, { createdAt: "desc" as const }, { id: "desc" as const }];
return [{ createdAt: sort.dir }, { id: "desc" as const }];
}
export async function listLeadsForBrowser(input: {
tenantId: string;
ctx: LeadVisibilityContext;
filter: LeadListFilter;
sort: { field: LeadSortField; dir: SortDir };
cursor?: string | null;
limit?: number;
}): Promise<ListLeadsResult> {
const take = Math.min(Math.max(input.limit ?? DEFAULT_LIMIT, 1), DEFAULT_LIMIT);
return withTenantRLS(input.tenantId, async (tx) => {
const where = whereForLeadList(input.tenantId, input.ctx, input.filter);
const [rows, total] = await Promise.all([
tx.inboxLead.findMany({
where,
orderBy: orderBy(input.sort),
take: take + 1,
...(input.cursor ? { cursor: { id: input.cursor }, skip: 1 } : {}),
}),
tx.inboxLead.count({ where }),
]);
const page = rows.slice(0, take);
return { rows: page as LeadRow[], nextCursor: rows.length > take ? (page.at(-1)?.id ?? null) : null, total };
});
}
export async function getVisibleLeadOrThrow(tenantId: string, leadId: string, ctx: LeadVisibilityContext): Promise<LeadRow> {
const lead = await withTenantRLS(tenantId, (tx) =>
tx.inboxLead.findFirst({ where: { id: leadId, tenantId, archivedAt: null, ...ownerScopeWhere(ctx) } }),
);
if (!lead) {
throw new CatalogError(foundationErrors.notFound, { leadId });
}
return lead as LeadRow;
}
export async function updateLead(input: {
tenantId: string;
ctx?: LeadVisibilityContext;
leadId: string;
vorname?: string | null;
nachname?: string | null;
email?: string | null;
telefon?: string | null;
message?: string | null;
weiterverarbeitungFreigabe?: LeadWeiterverarbeitungFreigabe;
zustaendigerUserId?: string | null;
}): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.inboxLead.findFirst({
where: { id: input.leadId, tenantId: input.tenantId, archivedAt: null, ...(input.ctx ? ownerScopeWhere(input.ctx) : {}) },
select: { id: true },
});
if (!existing) return;
const updated = await tx.inboxLead.update({
where: { id: existing.id },
data: {
...(input.vorname !== undefined ? { vorname: input.vorname?.trim() || null } : {}),
...(input.nachname !== undefined ? { nachname: input.nachname?.trim() || null } : {}),
...(input.email !== undefined ? { email: normalizeEmail(input.email) } : {}),
...(input.telefon !== undefined ? { telefon: normalizeTelefon(input.telefon) } : {}),
...(input.message !== undefined ? { message: input.message?.trim() || null } : {}),
...(input.weiterverarbeitungFreigabe !== undefined ? { weiterverarbeitungFreigabe: input.weiterverarbeitungFreigabe } : {}),
...(input.zustaendigerUserId !== undefined ? { zustaendigerUserId: input.zustaendigerUserId } : {}),
},
});
await publishLeadSearchUpsert(tx, updated as LeadRow);
});
}
export async function setLeadStatus(input: { tenantId: string; leadId: string; status: LeadStatus; ctx?: LeadVisibilityContext; userId?: string | null }): Promise<LeadRow> {
const now = new Date();
return withTenantRLS(input.tenantId, async (tx) => {
const config = await ensureAntiSpamConfigWithTx(tx, input.tenantId);
const current = await tx.inboxLead.findFirst({
where: { id: input.leadId, tenantId: input.tenantId, archivedAt: null, ...(input.ctx ? ownerScopeWhere(input.ctx) : {}) },
});
if (!current) {
throw new CatalogError(foundationErrors.notFound, { leadId: input.leadId });
}
assertStatusTransition(current.status as LeadStatus, input.status);
const updated = await tx.inboxLead.update({
where: { id: current.id },
data: {
status: input.status,
...statusTimestamps(input.status, now, config),
},
});
const lead = updated as LeadRow;
await publishLeadWorkflowEvent(tx, {
tenantId: input.tenantId,
userId: input.userId ?? input.ctx?.userId ?? null,
lead,
event: input.status === "qualified" ? "lead.qualified" : "lead.status_changed",
action: input.status === "qualified" ? "qualified" : "status_changed",
});
await publishLeadSearchUpsert(tx, lead);
return lead;
});
}
export async function bulkSetLeadStatus(input: { tenantId: string; ctx: LeadVisibilityContext; leadIds: string[]; status: LeadStatus }): Promise<number> {
if (input.leadIds.length === 0) return 0;
const now = new Date();
const result = await withTenantRLS(input.tenantId, async (tx) => {
const config = await ensureAntiSpamConfigWithTx(tx, input.tenantId);
const leads = await tx.inboxLead.findMany({
where: { id: { in: input.leadIds }, tenantId: input.tenantId, archivedAt: null, ...ownerScopeWhere(input.ctx) },
});
if (leads.some((lead) => !canTransitionLeadStatus(lead.status as LeadStatus, input.status))) {
throw new LeadServiceError("leads.error.invalidStatusTransition");
}
const updated = await tx.inboxLead.updateMany({
where: { id: { in: leads.map((lead) => lead.id) }, tenantId: input.tenantId },
data: { status: input.status, ...statusTimestamps(input.status, now, config) },
});
for (const lead of leads) {
const projectedLead = { ...(lead as LeadRow), status: input.status, ...statusTimestamps(input.status, now, config) } as LeadRow;
await publishLeadWorkflowEvent(tx, {
tenantId: input.tenantId,
userId: input.ctx.userId,
lead: projectedLead,
event: input.status === "qualified" ? "lead.qualified" : "lead.status_changed",
action: input.status === "qualified" ? "qualified" : "status_changed",
});
await publishLeadSearchUpsert(tx, projectedLead);
}
return updated;
});
return result.count;
}
export async function requestLeadProjectConversion(input: { tenantId: string; leadId: string; kontaktId?: string | null; ctx?: LeadVisibilityContext; userId?: string | null }): Promise<LeadRow> {
// P8 owns the Projekt model. P7 prepares and validates the conversion point so
// later code can atomically create Projekt + set konvertiertProjektId.
return withTenantRLS(input.tenantId, async (tx) => {
const current = await tx.inboxLead.findFirst({
where: { id: input.leadId, tenantId: input.tenantId, archivedAt: null, ...(input.ctx ? ownerScopeWhere(input.ctx) : {}) },
});
if (!current) {
throw new CatalogError(foundationErrors.notFound, { leadId: input.leadId });
}
assertStatusTransition(current.status as LeadStatus, "qualified");
const updated = await tx.inboxLead.update({
where: { id: current.id },
data: {
status: "qualified",
weiterverarbeitungFreigabe: "ja",
verknuepfterKontaktId: input.kontaktId ?? undefined,
},
});
const lead = updated as LeadRow;
await publishLeadWorkflowEvent(tx, {
tenantId: input.tenantId,
userId: input.userId ?? input.ctx?.userId ?? null,
lead,
event: "lead.convert_requested",
action: "convert_requested",
});
await publishLeadWorkflowEvent(tx, {
tenantId: input.tenantId,
userId: input.userId ?? input.ctx?.userId ?? null,
lead,
event: "lead.qualified",
action: "qualified",
});
await publishLeadSearchUpsert(tx, lead);
return lead;
});
}
export async function completeLeadProjectConversion(input: {
tenantId: string;
leadId: string;
projektId: string;
kontaktId?: string | null;
ctx?: LeadVisibilityContext;
userId?: string | null;
}): Promise<LeadRow> {
const projektId = normalizeOptionalText(input.projektId);
if (!projektId) {
throw new LeadServiceError("leads.error.projectRequired");
}
return withTenantRLS(input.tenantId, async (tx) => {
const current = await tx.inboxLead.findFirst({
where: { id: input.leadId, tenantId: input.tenantId, archivedAt: null, ...(input.ctx ? ownerScopeWhere(input.ctx) : {}) },
});
if (!current) {
throw new CatalogError(foundationErrors.notFound, { leadId: input.leadId });
}
assertStatusTransition(current.status as LeadStatus, "converted");
const updated = await tx.inboxLead.update({
where: { id: current.id },
data: {
status: "converted",
weiterverarbeitungFreigabe: "ja",
konvertiertProjektId: projektId,
verknuepfterKontaktId: input.kontaktId ?? current.verknuepfterKontaktId,
convertedAt: new Date(),
autoDeleteAt: null,
},
});
const lead = updated as LeadRow;
await publishLeadWorkflowEvent(tx, {
tenantId: input.tenantId,
userId: input.userId ?? input.ctx?.userId ?? null,
lead,
event: "lead.converted",
action: "converted",
});
await publishLeadSearchUpsert(tx, lead);
return lead;
});
}
export async function listAssignableUsers(tenantId: string): Promise<{ id: string; label: string }[]> {
const rows = await db.tenantUser.findMany({
where: { tenantId },
select: { userId: true, user: { select: { firstName: true, lastName: true, email: true } } },
orderBy: { createdAt: "asc" },
});
return rows.map((row) => ({
id: row.userId,
label: `${row.user.firstName ?? ""} ${row.user.lastName ?? ""}`.trim() || row.user.email,
}));
}
export async function resolveUserLabels(userIds: string[]): Promise<Map<string, string>> {
const unique = [...new Set(userIds.filter(Boolean))];
if (unique.length === 0) return new Map();
const users = await db.user.findMany({ where: { id: { in: unique } }, select: { id: true, firstName: true, lastName: true, email: true } });
return new Map(users.map((u) => [u.id, `${u.firstName ?? ""} ${u.lastName ?? ""}`.trim() || u.email]));
}
export async function listLeadSources(tenantId: string): Promise<LeadSourceRow[]> {
return withTenantRLS(tenantId, async (tx) =>
(await tx.leadSource.findMany({ where: { tenantId, archivedAt: null }, orderBy: [{ type: "asc" }, { name: "asc" }] })) as LeadSourceRow[],
);
}
export async function upsertLeadSource(input: {
tenantId: string;
key: string;
name: string;
displayLabel?: string | null;
type?: LeadSourceType;
defaultZustaendigerUserId?: string | null;
}): Promise<LeadSourceRow> {
const key = input.key.trim().toLowerCase();
if (!key || !input.name.trim()) {
throw new LeadServiceError("leads.error.sourceRequired");
}
const row = await withTenantRLS(input.tenantId, (tx) =>
tx.leadSource.upsert({
where: { tenantId_key: { tenantId: input.tenantId, key } },
update: {
name: input.name.trim(),
displayLabel: input.displayLabel?.trim() || input.name.trim(),
defaultZustaendigerUserId: input.defaultZustaendigerUserId ?? null,
},
create: {
tenantId: input.tenantId,
key,
name: input.name.trim(),
displayLabel: input.displayLabel?.trim() || input.name.trim(),
type: input.type ?? "custom",
defaultZustaendigerUserId: input.defaultZustaendigerUserId ?? null,
},
}),
);
return row as LeadSourceRow;
}
export async function getLeadAntiSpamConfig(tenantId: string): Promise<LeadAntiSpamConfigRow> {
return withTenantRLS(tenantId, (tx) => ensureAntiSpamConfigWithTx(tx, tenantId));
}
export async function updateLeadAntiSpamConfig(input: {
tenantId: string;
perSourcePerHourLimit?: number;
perIpPerHourLimit?: number;
anomalySpikeFactor?: number;
mode?: LeadAntiSpamMode;
disposableDomainEnabled?: boolean;
honeypotEnabled?: boolean;
fastSubmitEnabled?: boolean;
lostAutoDeleteDays?: number;
}): Promise<LeadAntiSpamConfigRow> {
const row = await withTenantRLS(input.tenantId, async (tx) => {
await ensureAntiSpamConfigWithTx(tx, input.tenantId);
return tx.leadAntiSpamConfig.update({
where: { tenantId: input.tenantId },
data: {
...(input.perSourcePerHourLimit !== undefined ? { perSourcePerHourLimit: Math.max(1, input.perSourcePerHourLimit) } : {}),
...(input.perIpPerHourLimit !== undefined ? { perIpPerHourLimit: Math.max(1, input.perIpPerHourLimit) } : {}),
...(input.anomalySpikeFactor !== undefined ? { anomalySpikeFactor: Math.max(2, input.anomalySpikeFactor) } : {}),
...(input.mode !== undefined ? { mode: input.mode } : {}),
...(input.disposableDomainEnabled !== undefined ? { disposableDomainEnabled: input.disposableDomainEnabled } : {}),
...(input.honeypotEnabled !== undefined ? { honeypotEnabled: input.honeypotEnabled } : {}),
...(input.fastSubmitEnabled !== undefined ? { fastSubmitEnabled: input.fastSubmitEnabled } : {}),
...(input.lostAutoDeleteDays !== undefined ? { lostAutoDeleteDays: Math.max(0, input.lostAutoDeleteDays) } : {}),
},
});
});
return row as LeadAntiSpamConfigRow;
}
export async function getLeadStatistics(input: { tenantId: string; ctx: LeadVisibilityContext }): Promise<{
total: number;
open: number;
converted: number;
spam: number;
byQuelle: { quelle: LeadQuelle; count: number }[];
byStatus: { status: LeadStatus; count: number }[];
}> {
return withTenantRLS(input.tenantId, async (tx) => {
const where = { tenantId: input.tenantId, archivedAt: null, ...ownerScopeWhere(input.ctx) };
const [total, open, converted, spam, byQuelleRaw, byStatusRaw] = await Promise.all([
tx.inboxLead.count({ where }),
tx.inboxLead.count({ where: { ...where, status: { in: ["new", "qualified"] } } }),
tx.inboxLead.count({ where: { ...where, status: "converted" } }),
tx.inboxLead.count({ where: { ...where, status: "spam" } }),
tx.inboxLead.groupBy({ by: ["quelle"], where, _count: { _all: true } }),
tx.inboxLead.groupBy({ by: ["status"], where, _count: { _all: true } }),
]);
return {
total,
open,
converted,
spam,
byQuelle: byQuelleRaw.map((row) => ({ quelle: row.quelle as LeadQuelle, count: row._count._all })),
byStatus: byStatusRaw.map((row) => ({ status: row.status as LeadStatus, count: row._count._all })),
};
});
}
@@ -0,0 +1,28 @@
import { describe, expect, test } from "vitest";
import { canTransitionLeadStatus, type LeadStatus } from "./leadService.server";
describe("lead status workflow", () => {
test.each<[LeadStatus, LeadStatus]>([
["new", "qualified"],
["new", "lost"],
["new", "spam"],
["qualified", "converted"],
["qualified", "lost"],
["qualified", "spam"],
])("allows %s -> %s", (from, to) => {
expect(canTransitionLeadStatus(from, to)).toBe(true);
});
test.each<[LeadStatus, LeadStatus]>([
["converted", "new"],
["converted", "qualified"],
["lost", "qualified"],
["spam", "qualified"],
])("blocks terminal transition %s -> %s", (from, to) => {
expect(canTransitionLeadStatus(from, to)).toBe(false);
});
test("allows idempotent status writes", () => {
expect(canTransitionLeadStatus("converted", "converted")).toBe(true);
});
});
@@ -1,10 +1,10 @@
// P4 Files (AK-P4a) §6 — web-side presigned download URL builder for the
// auth-proxy media route. Bucket stays private (AD-23); the proxy redirects an
// authorized request to a short-lived signed URL. Reuses the shared SigV4
// signer from @toolctrl/storage (no @aws-sdk/s3-request-presigner dependency).
// signer from @hivegrid/storage (no @aws-sdk/s3-request-presigner dependency).
import { loadRequiredWebConfig } from "@toolctrl/config";
import { createS3SignedUrlAdapter, createSigV4DownloadSigner, StorageAdapterError } from "@toolctrl/storage";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { createS3SignedUrlAdapter, createSigV4DownloadSigner, StorageAdapterError } from "@hivegrid/storage";
import { resolveStorageBucket } from "./storageService";
export const MEDIA_SIGNED_URL_TTL_SECONDS = 300;
@@ -0,0 +1,697 @@
import { randomUUID } from "node:crypto";
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { logActivity } from "@hivegrid/activity";
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import type { ProjektRow } from "./projectService.server";
export class AuftragServiceError extends Error {
readonly messageKey: string;
constructor(messageKey: string) {
super(messageKey);
this.name = "AuftragServiceError";
this.messageKey = messageKey;
}
}
export type ProjektMitgliedRolle = "monteur" | "projektleiter" | "zustaendig" | "beobachter";
export type ProjektTerminStatus = "geplant" | "bestaetigt" | "erledigt" | "abgesagt";
export type RechnungStatus = "entwurf" | "gestellt" | "bezahlt" | "storniert";
export type RechnungQuelle = "manuell" | "kwp";
export type ProjektChecklistTyp = "generisch" | "maengel" | "abnahme_doku";
export type ProjektChecklistItemStatus = "offen" | "erledigt" | "entfaellt";
export type AuftragVisibilityContext = {
userId: string;
permissions: readonly string[];
};
export type ProjektMitgliedRow = {
id: string;
tenantId: string;
projektId: string;
userId: string | null;
groupId: string | null;
rolle: ProjektMitgliedRolle;
createdByUserId: string | null;
createdAt: Date;
updatedAt: Date;
archivedAt: Date | null;
};
export type ProjektTerminRow = {
id: string;
tenantId: string;
projektId: string;
createdByUserId: string | null;
assignedToUserId: string | null;
assignedToGroupId: string | null;
titel: string;
beschreibung: string | null;
startAt: Date;
endAt: Date | null;
status: ProjektTerminStatus;
isDemoData: boolean;
createdAt: Date;
updatedAt: Date;
archivedAt: Date | null;
};
export type RechnungRow = {
id: string;
tenantId: string;
projektId: string;
createdByUserId: string | null;
rechnungsnummer: string;
betrag: unknown;
status: RechnungStatus;
datum: Date;
faelligAm: Date | null;
dateiId: string | null;
quelle: RechnungQuelle;
isDemoData: boolean;
createdAt: Date;
updatedAt: Date;
archivedAt: Date | null;
};
export type ProjektChecklistItemRow = {
id: string;
tenantId: string;
checklistId: string;
titel: string;
status: ProjektChecklistItemStatus;
maengelKlasse: string | null;
fotoFileId: string | null;
assignedToUserId: string | null;
dueAt: Date | null;
position: number;
createdAt: Date;
updatedAt: Date;
};
export type ProjektChecklistRow = {
id: string;
tenantId: string;
projektId: string;
createdByUserId: string | null;
titel: string;
typ: ProjektChecklistTyp;
isDemoData: boolean;
createdAt: Date;
updatedAt: Date;
archivedAt: Date | null;
items?: ProjektChecklistItemRow[];
};
export type AuftragPipelineStageConfigRow = {
id: string;
tenantId: string;
pipelineId: string;
stageId: string;
requiresAcceptanceProtocol: boolean;
acceptanceFormTemplateId: string | null;
autoArchiveAfterDays: number | null;
createdAt: Date;
updatedAt: Date;
};
export type AcceptanceFormTemplateRow = {
id: string;
tenantId: string;
name: string;
formId: string | null;
definition: unknown;
isDefault: boolean;
isDemoData: boolean;
createdAt: Date;
updatedAt: Date;
archivedAt: Date | null;
};
export type ProjectTemplateRow = {
id: string;
tenantId: string;
name: string;
defaultPipelineId: string | null;
defaultStageId: string | null;
defaultMembers: unknown;
defaultTasks: unknown;
customFields: unknown;
isDemoData: boolean;
createdAt: Date;
updatedAt: Date;
archivedAt: Date | null;
};
export type ProjectSubAreasVM = {
project: ProjektRow;
members: ProjektMitgliedRow[];
appointments: ProjektTerminRow[];
invoices: RechnungRow[];
checklists: ProjektChecklistRow[];
stageConfig: AuftragPipelineStageConfigRow | null;
acceptanceTemplates: AcceptanceFormTemplateRow[];
projectTemplates: ProjectTemplateRow[];
openDefects: number;
};
function normalizeText(value?: string | null): string | null {
const normalized = value?.trim();
return normalized || null;
}
function parseDate(value?: string | Date | null): Date | null {
if (!value) return null;
if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;
const parsed = new Date(value);
return Number.isNaN(parsed.getTime()) ? null : parsed;
}
function decimalToString(value: unknown): string {
if (value == null) return "0.00";
if (typeof value === "number") return Number.isFinite(value) ? value.toFixed(2) : "0.00";
if (typeof value === "string") {
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed.toFixed(2) : "0.00";
}
if (typeof value === "object" && "toString" in value && typeof value.toString === "function") {
const parsed = Number(value.toString());
return Number.isFinite(parsed) ? parsed.toFixed(2) : "0.00";
}
return "0.00";
}
function hasPermission(ctx: AuftragVisibilityContext | undefined, permission: string): boolean {
return ctx?.permissions.includes(permission) ?? false;
}
async function canReadProjectSubAreasWithTx(tx: TenantRlsClient, input: { tenantId: string; project: ProjektRow; ctx: AuftragVisibilityContext }): Promise<boolean> {
if (hasPermission(input.ctx, "projects.read_all")) return true;
if (hasPermission(input.ctx, "projects.read_own_pl") && input.project.projektleiterId === input.ctx.userId) return true;
if (hasPermission(input.ctx, "projects.read_own") && input.project.zustaendigePersonId === input.ctx.userId) return true;
if (!hasPermission(input.ctx, "projects.read_own_member")) return false;
const membership = await tx.projektMitglied.findFirst({
where: { tenantId: input.tenantId, projektId: input.project.id, userId: input.ctx.userId, archivedAt: null },
select: { id: true },
});
return Boolean(membership);
}
async function requireProjectSubAreaReadWithTx(tx: TenantRlsClient, input: { tenantId: string; projectId: string; ctx: AuftragVisibilityContext }): Promise<ProjektRow> {
const project = await tx.projekt.findFirst({ where: { id: input.projectId, tenantId: input.tenantId, archivedAt: null } });
if (!project) throw new CatalogError(foundationErrors.notFound, { projectId: input.projectId });
if (!(await canReadProjectSubAreasWithTx(tx, { tenantId: input.tenantId, project: project as ProjektRow, ctx: input.ctx }))) {
throw new CatalogError(foundationErrors.notFound, { projectId: input.projectId });
}
return project as ProjektRow;
}
function requireExactlyOnePrincipal(userId?: string | null, groupId?: string | null): void {
const hasUser = Boolean(normalizeText(userId));
const hasGroup = Boolean(normalizeText(groupId));
if (hasUser === hasGroup) throw new AuftragServiceError("projects.error.memberPrincipalRequired");
}
function invoiceNumber(prefix: string, nextNumber: number, padding: number): string {
return `${prefix}${String(nextNumber).padStart(padding, "0")}`;
}
async function requireProjectWithTx(tx: TenantRlsClient, input: { tenantId: string; projectId: string }): Promise<ProjektRow> {
const project = await tx.projekt.findFirst({ where: { id: input.projectId, tenantId: input.tenantId, archivedAt: null } });
if (!project) throw new CatalogError(foundationErrors.notFound, { projectId: input.projectId });
return project as ProjektRow;
}
async function reserveInvoiceNumberWithTx(tx: TenantRlsClient, tenantId: string): Promise<string> {
const sequenceId = `seq_${randomUUID()}`;
await tx.$executeRaw`
INSERT INTO "HiveNumberSeq" ("id", "tenantId", "entityType", "prefix", "nextNumber", "padding", "createdAt", "updatedAt")
VALUES (${sequenceId}, ${tenantId}, 'rechnung', 'R-', 1, 5, now(), now())
ON CONFLICT ("tenantId", "entityType") DO NOTHING
`;
const rows = await tx.$queryRaw<Array<{ nextNumber: number; padding: number; prefix: string }>>`
SELECT "nextNumber", "padding", "prefix"
FROM "HiveNumberSeq"
WHERE "tenantId" = ${tenantId} AND "entityType" = 'rechnung'
FOR UPDATE
`;
const current = rows[0];
if (!current) throw new AuftragServiceError("projects.error.invoiceNumberSequenceMissing");
await tx.hiveNumberSeq.update({
where: { tenantId_entityType: { tenantId, entityType: "rechnung" } },
data: { nextNumber: current.nextNumber + 1 },
});
return invoiceNumber(current.prefix || "R-", current.nextNumber, current.padding);
}
export async function ensureDefaultAcceptanceFormTemplate(input: { tenantId: string; userId?: string | null }): Promise<AcceptanceFormTemplateRow> {
return withTenantRLS(input.tenantId, (tx) => ensureDefaultAcceptanceFormTemplateWithTx(tx, input.tenantId));
}
export async function ensureDefaultProjectTemplate(input: { tenantId: string }): Promise<ProjectTemplateRow> {
return withTenantRLS(input.tenantId, (tx) => ensureDefaultProjectTemplateWithTx(tx, input.tenantId));
}
async function ensureDefaultAcceptanceFormTemplateWithTx(tx: TenantRlsClient, tenantId: string): Promise<AcceptanceFormTemplateRow> {
const row = await tx.acceptanceFormTemplate.upsert({
where: { tenantId_name: { tenantId, name: "SHK Standard-Abnahme" } },
update: { archivedAt: null, isDefault: true, isDemoData: true },
create: {
tenantId,
name: "SHK Standard-Abnahme",
definition: {
sections: [
{ key: "leistungen", labelKey: "projects.defaults.acceptance.sections.leistungen" },
{ key: "maengel", labelKey: "projects.defaults.acceptance.sections.maengel" },
{ key: "unterschrift", labelKey: "projects.defaults.acceptance.sections.unterschrift" },
],
},
isDefault: true,
isDemoData: true,
},
});
return row as AcceptanceFormTemplateRow;
}
async function ensureDefaultProjectTemplateWithTx(tx: TenantRlsClient, tenantId: string): Promise<ProjectTemplateRow> {
const row = await tx.projectTemplate.upsert({
where: { tenantId_name: { tenantId, name: "SHK Standard-Projekt" } },
update: { archivedAt: null, isDemoData: true },
create: {
tenantId,
name: "SHK Standard-Projekt",
defaultMembers: [],
defaultTasks: [
{ titleKey: "projects.defaults.tasks.prepareSite", priority: "normal" },
{ titleKey: "projects.defaults.tasks.checkMaterial", priority: "normal" },
{ titleKey: "projects.defaults.tasks.prepareAcceptance", priority: "high" },
],
customFields: {},
isDemoData: true,
},
});
return row as ProjectTemplateRow;
}
export async function loadProjectSubAreas(input: { tenantId: string; projectId: string; ctx: AuftragVisibilityContext }): Promise<ProjectSubAreasVM> {
return withTenantRLS(input.tenantId, async (tx) => {
const project = await requireProjectSubAreaReadWithTx(tx, input);
await Promise.all([ensureDefaultAcceptanceFormTemplateWithTx(tx, input.tenantId), ensureDefaultProjectTemplateWithTx(tx, input.tenantId)]);
const [members, appointments, invoices, checklists, stageConfig, acceptanceTemplates, projectTemplates, openDefects] = await Promise.all([
tx.projektMitglied.findMany({ where: { tenantId: input.tenantId, projektId: input.projectId, archivedAt: null }, orderBy: { createdAt: "asc" } }),
tx.projektTermin.findMany({ where: { tenantId: input.tenantId, projektId: input.projectId, archivedAt: null }, orderBy: { startAt: "asc" } }),
tx.rechnung.findMany({ where: { tenantId: input.tenantId, projektId: input.projectId, archivedAt: null }, orderBy: { createdAt: "desc" } }),
tx.projektChecklist.findMany({
where: { tenantId: input.tenantId, projektId: input.projectId, archivedAt: null },
include: { items: { orderBy: { position: "asc" } } },
orderBy: { createdAt: "asc" },
}),
tx.auftragPipelineStageConfig.findFirst({ where: { tenantId: input.tenantId, stageId: project.stageId } }),
tx.acceptanceFormTemplate.findMany({ where: { tenantId: input.tenantId, archivedAt: null }, orderBy: [{ isDefault: "desc" }, { name: "asc" }] }),
tx.projectTemplate.findMany({ where: { tenantId: input.tenantId, archivedAt: null }, orderBy: [{ isDemoData: "desc" }, { name: "asc" }] }),
tx.projektChecklistItem.count({
where: {
tenantId: input.tenantId,
status: "offen",
checklist: { projektId: input.projectId, typ: "maengel", archivedAt: null },
},
}),
]);
return {
project,
members: members as ProjektMitgliedRow[],
appointments: appointments as ProjektTerminRow[],
invoices: invoices as RechnungRow[],
checklists: checklists as ProjektChecklistRow[],
stageConfig: stageConfig as AuftragPipelineStageConfigRow | null,
acceptanceTemplates: acceptanceTemplates as AcceptanceFormTemplateRow[],
projectTemplates: projectTemplates as ProjectTemplateRow[],
openDefects,
};
});
}
export async function addProjectMember(input: {
tenantId: string;
projectId: string;
createdByUserId: string | null;
userId?: string | null;
groupId?: string | null;
rolle: ProjektMitgliedRolle;
}): Promise<ProjektMitgliedRow> {
requireExactlyOnePrincipal(input.userId, input.groupId);
return withTenantRLS(input.tenantId, async (tx) => {
await requireProjectWithTx(tx, input);
const row = await tx.projektMitglied.create({
data: {
tenantId: input.tenantId,
projektId: input.projectId,
createdByUserId: input.createdByUserId,
userId: normalizeText(input.userId),
groupId: normalizeText(input.groupId),
rolle: input.rolle,
},
});
await logActivity(
{
tenantId: input.tenantId,
actorUserId: input.createdByUserId,
actorKind: input.createdByUserId ? "user" : "system",
activityType: "project_member_added",
subjectType: "project",
subjectId: input.projectId,
summaryText: "Projektmitglied wurde hinzugefügt.",
metadata: { userId: input.userId ?? null, groupId: input.groupId ?? null, rolle: input.rolle },
},
{ client: tx },
);
return row as ProjektMitgliedRow;
});
}
export async function createProjectAppointment(input: {
tenantId: string;
projectId: string;
createdByUserId: string | null;
titel: string;
beschreibung?: string | null;
startAt: string | Date;
endAt?: string | Date | null;
assignedToUserId?: string | null;
assignedToGroupId?: string | null;
}): Promise<ProjektTerminRow> {
return withTenantRLS(input.tenantId, async (tx) => {
const title = normalizeText(input.titel);
const startAt = parseDate(input.startAt);
if (!title) throw new AuftragServiceError("projects.error.appointmentTitleRequired");
if (!startAt) throw new AuftragServiceError("projects.error.appointmentStartRequired");
await requireProjectWithTx(tx, input);
const row = await tx.projektTermin.create({
data: {
tenantId: input.tenantId,
projektId: input.projectId,
createdByUserId: input.createdByUserId,
assignedToUserId: normalizeText(input.assignedToUserId),
assignedToGroupId: normalizeText(input.assignedToGroupId),
titel: title,
beschreibung: normalizeText(input.beschreibung),
startAt,
endAt: parseDate(input.endAt),
},
});
await logActivity(
{
tenantId: input.tenantId,
actorUserId: input.createdByUserId,
actorKind: input.createdByUserId ? "user" : "system",
activityType: "project_appointment_created",
subjectType: "project",
subjectId: input.projectId,
summaryText: "Projekttermin wurde angelegt.",
metadata: { appointmentId: row.id, startAt: row.startAt.toISOString() },
},
{ client: tx },
);
return row as ProjektTerminRow;
});
}
export async function createProjectInvoice(input: {
tenantId: string;
projectId: string;
createdByUserId: string | null;
betrag: string | number;
datum?: string | Date | null;
faelligAm?: string | Date | null;
dateiId?: string | null;
quelle?: RechnungQuelle;
}): Promise<RechnungRow> {
return withTenantRLS(input.tenantId, async (tx) => {
await requireProjectWithTx(tx, input);
const rechnungsnummer = await reserveInvoiceNumberWithTx(tx, input.tenantId);
const row = await tx.rechnung.create({
data: {
tenantId: input.tenantId,
projektId: input.projectId,
createdByUserId: input.createdByUserId,
rechnungsnummer,
betrag: decimalToString(input.betrag),
datum: parseDate(input.datum) ?? new Date(),
faelligAm: parseDate(input.faelligAm),
dateiId: normalizeText(input.dateiId),
quelle: input.quelle ?? "manuell",
},
});
await logActivity(
{
tenantId: input.tenantId,
actorUserId: input.createdByUserId,
actorKind: input.createdByUserId ? "user" : "system",
activityType: "project_invoice_created",
subjectType: "project",
subjectId: input.projectId,
summaryText: `Rechnung ${row.rechnungsnummer} wurde angelegt.`,
metadata: { invoiceId: row.id, rechnungsnummer: row.rechnungsnummer },
},
{ client: tx },
);
return row as RechnungRow;
});
}
export async function updateProjectInvoiceStatus(input: { tenantId: string; invoiceId: string; userId: string | null; status: RechnungStatus }): Promise<RechnungRow> {
return withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.rechnung.findFirst({ where: { id: input.invoiceId, tenantId: input.tenantId, archivedAt: null } });
if (!existing) throw new CatalogError(foundationErrors.notFound, { invoiceId: input.invoiceId });
const row = await tx.rechnung.update({ where: { id: input.invoiceId }, data: { status: input.status } });
await logActivity(
{
tenantId: input.tenantId,
actorUserId: input.userId,
actorKind: input.userId ? "user" : "system",
activityType: "project_invoice_status_changed",
subjectType: "project",
subjectId: existing.projektId,
summaryText: `Rechnungsstatus wurde auf ${input.status} gesetzt.`,
metadata: { invoiceId: input.invoiceId, status: input.status },
},
{ client: tx },
);
return row as RechnungRow;
});
}
export async function createProjectChecklist(input: {
tenantId: string;
projectId: string;
createdByUserId: string | null;
titel: string;
typ?: ProjektChecklistTyp;
}): Promise<ProjektChecklistRow> {
return withTenantRLS(input.tenantId, async (tx) => {
const title = normalizeText(input.titel);
if (!title) throw new AuftragServiceError("projects.error.checklistTitleRequired");
await requireProjectWithTx(tx, input);
const row = await tx.projektChecklist.create({
data: {
tenantId: input.tenantId,
projektId: input.projectId,
createdByUserId: input.createdByUserId,
titel: title,
typ: input.typ ?? "generisch",
},
});
await logActivity(
{
tenantId: input.tenantId,
actorUserId: input.createdByUserId,
actorKind: input.createdByUserId ? "user" : "system",
activityType: "project_checklist_created",
subjectType: "project",
subjectId: input.projectId,
summaryText: "Projekt-Checkliste wurde angelegt.",
metadata: { checklistId: row.id, typ: row.typ },
},
{ client: tx },
);
return row as ProjektChecklistRow;
});
}
export async function upsertProjectChecklistItem(input: {
tenantId: string;
checklistId: string;
itemId?: string | null;
titel: string;
status?: ProjektChecklistItemStatus;
maengelKlasse?: string | null;
fotoFileId?: string | null;
assignedToUserId?: string | null;
dueAt?: string | Date | null;
position?: number;
}): Promise<ProjektChecklistItemRow> {
return withTenantRLS(input.tenantId, async (tx) => {
const title = normalizeText(input.titel);
if (!title) throw new AuftragServiceError("projects.error.checklistItemTitleRequired");
const checklist = await tx.projektChecklist.findFirst({ where: { id: input.checklistId, tenantId: input.tenantId, archivedAt: null } });
if (!checklist) throw new CatalogError(foundationErrors.notFound, { checklistId: input.checklistId });
const data = {
titel: title,
status: input.status ?? "offen",
maengelKlasse: normalizeText(input.maengelKlasse),
fotoFileId: normalizeText(input.fotoFileId),
assignedToUserId: normalizeText(input.assignedToUserId),
dueAt: parseDate(input.dueAt),
position: input.position ?? 0,
};
if (input.itemId) {
const row = await tx.projektChecklistItem.update({ where: { id: input.itemId }, data });
return row as ProjektChecklistItemRow;
}
const row = await tx.projektChecklistItem.create({
data: { tenantId: input.tenantId, checklistId: input.checklistId, ...data },
});
return row as ProjektChecklistItemRow;
});
}
export async function upsertAuftragPipelineStageConfig(input: {
tenantId: string;
pipelineId: string;
stageId: string;
requiresAcceptanceProtocol?: boolean;
acceptanceFormTemplateId?: string | null;
autoArchiveAfterDays?: number | null;
}): Promise<AuftragPipelineStageConfigRow> {
return withTenantRLS(input.tenantId, async (tx) => {
const stage = await tx.pipelineStage.findFirst({ where: { id: input.stageId, tenantId: input.tenantId, pipelineId: input.pipelineId, archivedAt: null } });
if (!stage) throw new CatalogError(foundationErrors.notFound, { stageId: input.stageId });
const row = await tx.auftragPipelineStageConfig.upsert({
where: { tenantId_stageId: { tenantId: input.tenantId, stageId: input.stageId } },
update: {
requiresAcceptanceProtocol: input.requiresAcceptanceProtocol ?? false,
acceptanceFormTemplateId: normalizeText(input.acceptanceFormTemplateId),
autoArchiveAfterDays: input.autoArchiveAfterDays ?? null,
},
create: {
tenantId: input.tenantId,
pipelineId: input.pipelineId,
stageId: input.stageId,
requiresAcceptanceProtocol: input.requiresAcceptanceProtocol ?? false,
acceptanceFormTemplateId: normalizeText(input.acceptanceFormTemplateId),
autoArchiveAfterDays: input.autoArchiveAfterDays ?? null,
},
});
return row as AuftragPipelineStageConfigRow;
});
}
export async function upsertAcceptanceFormTemplate(input: {
tenantId: string;
templateId?: string | null;
name: string;
formId?: string | null;
definition?: unknown;
isDefault?: boolean;
}): Promise<AcceptanceFormTemplateRow> {
return withTenantRLS(input.tenantId, async (tx) => {
const name = normalizeText(input.name);
if (!name) throw new AuftragServiceError("projects.error.acceptanceTemplateNameRequired");
if (input.templateId) {
const row = await tx.acceptanceFormTemplate.update({
where: { id: input.templateId },
data: { name, formId: normalizeText(input.formId), definition: input.definition ?? {}, isDefault: input.isDefault ?? false, archivedAt: null },
});
return row as AcceptanceFormTemplateRow;
}
const row = await tx.acceptanceFormTemplate.upsert({
where: { tenantId_name: { tenantId: input.tenantId, name } },
update: { formId: normalizeText(input.formId), definition: input.definition ?? {}, isDefault: input.isDefault ?? false, archivedAt: null },
create: { tenantId: input.tenantId, name, formId: normalizeText(input.formId), definition: input.definition ?? {}, isDefault: input.isDefault ?? false },
});
return row as AcceptanceFormTemplateRow;
});
}
export async function listAcceptanceFormTemplates(input: { tenantId: string }): Promise<AcceptanceFormTemplateRow[]> {
return withTenantRLS(input.tenantId, async (tx) => {
await ensureDefaultAcceptanceFormTemplateWithTx(tx, input.tenantId);
const rows = await tx.acceptanceFormTemplate.findMany({
where: { tenantId: input.tenantId, archivedAt: null },
orderBy: [{ isDefault: "desc" }, { name: "asc" }],
});
return rows as AcceptanceFormTemplateRow[];
});
}
export async function upsertProjectTemplate(input: {
tenantId: string;
templateId?: string | null;
name: string;
defaultPipelineId?: string | null;
defaultStageId?: string | null;
defaultMembers?: unknown;
defaultTasks?: unknown;
customFields?: unknown;
}): Promise<ProjectTemplateRow> {
return withTenantRLS(input.tenantId, async (tx) => {
const name = normalizeText(input.name);
if (!name) throw new AuftragServiceError("projects.error.projectTemplateNameRequired");
const data = {
name,
defaultPipelineId: normalizeText(input.defaultPipelineId),
defaultStageId: normalizeText(input.defaultStageId),
defaultMembers: input.defaultMembers ?? [],
defaultTasks: input.defaultTasks ?? [],
customFields: input.customFields ?? {},
archivedAt: null,
};
if (input.templateId) {
const row = await tx.projectTemplate.update({ where: { id: input.templateId }, data });
return row as ProjectTemplateRow;
}
const row = await tx.projectTemplate.upsert({
where: { tenantId_name: { tenantId: input.tenantId, name } },
update: data,
create: { tenantId: input.tenantId, ...data },
});
return row as ProjectTemplateRow;
});
}
export async function listProjectTemplates(input: { tenantId: string }): Promise<ProjectTemplateRow[]> {
return withTenantRLS(input.tenantId, async (tx) => {
await ensureDefaultProjectTemplateWithTx(tx, input.tenantId);
const rows = await tx.projectTemplate.findMany({
where: { tenantId: input.tenantId, archivedAt: null },
orderBy: [{ isDemoData: "desc" }, { name: "asc" }],
});
return rows as ProjectTemplateRow[];
});
}
export async function autoArchiveProjectsForStageConfigs(input: { tenantId: string; now?: Date; limit?: number }): Promise<{ archived: number }> {
const now = input.now ?? new Date();
return withTenantRLS(input.tenantId, async (tx) => {
const configs = await tx.auftragPipelineStageConfig.findMany({
where: { tenantId: input.tenantId, autoArchiveAfterDays: { not: null } },
take: Math.min(Math.max(input.limit ?? 100, 1), 500),
});
let archived = 0;
for (const config of configs) {
if (!config.autoArchiveAfterDays) continue;
const threshold = new Date(now.getTime() - config.autoArchiveAfterDays * 24 * 60 * 60 * 1000);
const result = await tx.projekt.updateMany({
where: {
tenantId: input.tenantId,
stageId: config.stageId,
archivedAt: null,
updatedAt: { lte: threshold },
},
data: { archivedAt: now },
});
archived += result.count;
}
return { archived };
});
}
@@ -0,0 +1,790 @@
import { createHash, randomUUID } from "node:crypto";
import i18next from "i18next";
import { buildFileStorageKeys } from "@hivegrid/storage";
import { buildPdfExportArtifact } from "@hivegrid/exports/pdf";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { logActivity } from "@hivegrid/activity";
import { createNotificationDelivery } from "@hivegrid/db/notifications.server";
import { ensureServerGlobalI18n } from "~/locale/i18next.global.server";
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import { putBufferAsFile, resolveStorageBucket } from "~/utils/integrations/storageService";
import { queueTransactionalEmail } from "~/modules/emails/services/TransactionalEmailQueue.server";
import { createTask } from "~/utils/integrations/taskService.server";
import { listApprovedAbsencesForRange, type ApprovedAbsence } from "~/utils/integrations/hrLeaveService.server";
import { AuftragServiceError } from "./auftragService.server";
import type { ProjektRow } from "./projectService.server";
export type ScheduleEntryStatus = "planned" | "confirmed" | "in_progress" | "done" | "cancelled";
export type ScheduleConflictType = "double_booking" | "absence" | "availability";
export type ScheduleConflictSeverity = "warning" | "blocking";
export type ScheduleSyncStatus = "pending" | "synced" | "failed";
export type AcceptanceKind = "full" | "with_defects" | "rejected";
export type AcceptanceSignerRole = "kunde" | "monteur";
export type OfflineSyncOperation = "schedule_upsert" | "schedule_status" | "acceptance_submit";
export type PlantafelContext = {
userId: string;
permissions: readonly string[];
};
export type ScheduleConflictRow = {
id: string;
tenantId: string;
entryId: string;
type: ScheduleConflictType;
severity: ScheduleConflictSeverity;
messageKey: string;
sourceKind: string | null;
sourceId: string | null;
createdAt: Date;
resolvedAt: Date | null;
overriddenAt: Date | null;
};
export type ScheduleEntryRow = {
id: string;
tenantId: string;
projektId: string;
assignedUserId: string;
createdByUserId: string | null;
title: string;
startAt: Date;
endAt: Date;
status: ScheduleEntryStatus;
calendarEventId: string | null;
syncStatus: ScheduleSyncStatus;
conflictOverrideReason: string | null;
clientMutationId: string | null;
isDemoData: boolean;
createdAt: Date;
updatedAt: Date;
archivedAt: Date | null;
conflicts?: ScheduleConflictRow[];
};
export type AbnahmeSignaturRow = {
id: string;
tenantId: string;
protokollId: string;
signerName: string;
signerRole: AcceptanceSignerRole;
signatureFileId: string | null;
signerIpHash: string | null;
signedAt: Date;
createdAt: Date;
};
export type AbnahmeProtokollRow = {
id: string;
tenantId: string;
projektId: string;
maengelChecklistId: string | null;
createdByUserId: string | null;
datum: Date;
acceptanceKind: AcceptanceKind;
anwesende: unknown;
druckprobe: unknown;
funktionspruefung: unknown;
zaehlerstaende: unknown;
dokumente: unknown;
bemerkungen: string | null;
pdfFileId: string | null;
customerEmail: string | null;
customerEmailQueuedAt: Date | null;
clientMutationId: string | null;
gesperrtAt: Date | null;
isDemoData: boolean;
createdAt: Date;
updatedAt: Date;
archivedAt: Date | null;
signatures?: AbnahmeSignaturRow[];
};
export type PlantafelVM = {
entries: ScheduleEntryRow[];
absences: ApprovedAbsence[];
generatedAt: string;
};
export type AcceptanceListVM = {
project: ProjektRow;
protocols: AbnahmeProtokollRow[];
};
export type AcceptanceDefectInput = {
classification: "critical" | "minor" | "cosmetic";
title?: string | null;
photoFileId?: string | null;
};
export type AcceptanceSignatureInput = {
signerName: string;
signerRole: AcceptanceSignerRole;
signatureFileId?: string | null;
signerIpAddress?: string | null;
};
const DEFAULT_WORKDAY_START_HOUR = 6;
const DEFAULT_WORKDAY_END_HOUR = 20;
function normalizeText(value?: string | null): string | null {
const normalized = value?.trim();
return normalized || null;
}
function hasPermission(ctx: PlantafelContext, permission: string): boolean {
return ctx.permissions.includes(permission);
}
function parseDate(value: string | Date | null | undefined): Date | null {
if (!value) return null;
if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;
const parsed = new Date(value);
return Number.isNaN(parsed.getTime()) ? null : parsed;
}
function ensureRange(startAt: Date | null, endAt: Date | null): { startAt: Date; endAt: Date } {
if (!startAt || !endAt || endAt <= startAt) {
throw new AuftragServiceError("projects.error.scheduleRangeInvalid");
}
return { startAt, endAt };
}
function intervalsOverlap(aStart: Date, aEnd: Date, bStart: Date, bEnd: Date): boolean {
return aStart < bEnd && aEnd > bStart;
}
function hashIpAddress(value?: string | null): string | null {
const normalized = normalizeText(value);
return normalized ? createHash("sha256").update(normalized).digest("hex") : null;
}
async function requireProjectWithTx(tx: TenantRlsClient, input: { tenantId: string; projectId: string }): Promise<ProjektRow> {
const project = await tx.projekt.findFirst({ where: { id: input.projectId, tenantId: input.tenantId, archivedAt: null } });
if (!project) throw new CatalogError(foundationErrors.notFound, { projectId: input.projectId });
return project as ProjektRow;
}
function canReadPlantafel(ctx: PlantafelContext): boolean {
return hasPermission(ctx, "plantafel.read_all") || hasPermission(ctx, "plantafel.read_own");
}
function canReadAllPlantafel(ctx: PlantafelContext): boolean {
return hasPermission(ctx, "plantafel.read_all");
}
function requirePlantafelRead(ctx: PlantafelContext): void {
if (!canReadPlantafel(ctx)) throw new CatalogError(foundationErrors.notFound);
}
function requireAcceptanceRead(ctx: PlantafelContext): void {
if (!hasPermission(ctx, "acceptance.read") && !hasPermission(ctx, "acceptance.write") && !hasPermission(ctx, "acceptance.admin")) {
throw new CatalogError(foundationErrors.notFound);
}
}
function normalizeClientMutationId(value?: string | null): string | null {
return normalizeText(value)?.slice(0, 120) ?? null;
}
function classifyAcceptanceKind(defects: readonly AcceptanceDefectInput[] = []): AcceptanceKind {
if (defects.some((defect) => defect.classification === "critical")) return "rejected";
if (defects.some((defect) => defect.classification === "minor")) return "with_defects";
return "full";
}
async function detectScheduleConflicts(input: {
tenantId: string;
assignedUserId: string;
startAt: Date;
endAt: Date;
excludeEntryId?: string | null;
}): Promise<Array<Omit<ScheduleConflictRow, "id" | "tenantId" | "entryId" | "createdAt" | "resolvedAt" | "overriddenAt">>> {
const [overlapping, absences] = await Promise.all([
withTenantRLS(input.tenantId, (tx) =>
tx.scheduleEntry.findMany({
where: {
tenantId: input.tenantId,
assignedUserId: input.assignedUserId,
archivedAt: null,
status: { not: "cancelled" },
startAt: { lt: input.endAt },
endAt: { gt: input.startAt },
...(input.excludeEntryId ? { id: { not: input.excludeEntryId } } : {}),
},
select: { id: true },
}),
),
listApprovedAbsencesForRange(input.tenantId, input.startAt, input.endAt),
]);
const conflicts: Array<Omit<ScheduleConflictRow, "id" | "tenantId" | "entryId" | "createdAt" | "resolvedAt" | "overriddenAt">> = [];
for (const entry of overlapping) {
conflicts.push({
type: "double_booking",
severity: "blocking",
messageKey: "projects.error.scheduleDoubleBooking",
sourceKind: "schedule_entry",
sourceId: entry.id,
});
}
for (const absence of absences) {
if (absence.employeeUserId === input.assignedUserId && intervalsOverlap(input.startAt, input.endAt, absence.startDate, absence.endDate)) {
conflicts.push({
type: "absence",
severity: "blocking",
messageKey: absence.source === "sick" ? "projects.error.scheduleSickConflict" : "projects.error.scheduleAbsenceConflict",
sourceKind: absence.source,
sourceId: absence.id,
});
}
}
const startsBeforeWorkday = input.startAt.getHours() < DEFAULT_WORKDAY_START_HOUR;
const endsAfterWorkday = input.endAt.getHours() > DEFAULT_WORKDAY_END_HOUR || (input.endAt.getHours() === DEFAULT_WORKDAY_END_HOUR && input.endAt.getMinutes() > 0);
if (startsBeforeWorkday || endsAfterWorkday) {
conflicts.push({
type: "availability",
severity: "warning",
messageKey: "projects.error.scheduleAvailabilityConflict",
sourceKind: "default_workday",
sourceId: null,
});
}
return conflicts;
}
async function replaceScheduleConflicts(input: {
tenantId: string;
entryId: string;
conflicts: Array<Omit<ScheduleConflictRow, "id" | "tenantId" | "entryId" | "createdAt" | "resolvedAt" | "overriddenAt">>;
overridden: boolean;
}): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
await tx.scheduleConflict.deleteMany({ where: { tenantId: input.tenantId, entryId: input.entryId } });
if (input.conflicts.length === 0) return;
const now = new Date();
await tx.scheduleConflict.createMany({
data: input.conflicts.map((conflict) => ({
tenantId: input.tenantId,
entryId: input.entryId,
type: conflict.type,
severity: conflict.severity,
messageKey: conflict.messageKey,
sourceKind: conflict.sourceKind,
sourceId: conflict.sourceId,
overriddenAt: input.overridden ? now : null,
})),
});
});
}
export async function loadPlantafel(input: { tenantId: string; ctx: PlantafelContext; from: Date; to: Date; assignedUserId?: string | null }): Promise<PlantafelVM> {
requirePlantafelRead(input.ctx);
const assignedUserId = canReadAllPlantafel(input.ctx) ? normalizeText(input.assignedUserId) : input.ctx.userId;
const [entries, absences] = await Promise.all([
withTenantRLS(input.tenantId, (tx) =>
tx.scheduleEntry.findMany({
where: {
tenantId: input.tenantId,
archivedAt: null,
startAt: { lt: input.to },
endAt: { gt: input.from },
...(assignedUserId ? { assignedUserId } : {}),
},
include: { conflicts: { where: { resolvedAt: null }, orderBy: { createdAt: "asc" } } },
orderBy: [{ startAt: "asc" }, { assignedUserId: "asc" }],
}),
),
listApprovedAbsencesForRange(input.tenantId, input.from, input.to),
]);
return {
entries: entries as ScheduleEntryRow[],
absences: canReadAllPlantafel(input.ctx) ? absences : absences.filter((absence) => absence.employeeUserId === input.ctx.userId),
generatedAt: new Date().toISOString(),
};
}
export async function upsertScheduleEntry(input: {
tenantId: string;
userId: string;
projektId: string;
assignedUserId: string;
title: string;
startAt: string | Date;
endAt: string | Date;
status?: ScheduleEntryStatus;
entryId?: string | null;
calendarEventId?: string | null;
conflictOverrideReason?: string | null;
clientMutationId?: string | null;
}): Promise<{ entry: ScheduleEntryRow; conflicts: ScheduleConflictRow[] }> {
const title = normalizeText(input.title);
const assignedUserId = normalizeText(input.assignedUserId);
const range = ensureRange(parseDate(input.startAt), parseDate(input.endAt));
if (!title) throw new AuftragServiceError("projects.error.scheduleTitleRequired");
if (!assignedUserId) throw new AuftragServiceError("projects.error.scheduleAssigneeRequired");
const clientMutationId = normalizeClientMutationId(input.clientMutationId);
if (clientMutationId) {
const existing = await withTenantRLS(input.tenantId, (tx) =>
tx.scheduleEntry.findUnique({ where: { tenantId_clientMutationId: { tenantId: input.tenantId, clientMutationId } }, include: { conflicts: true } }),
);
if (existing) return { entry: existing as ScheduleEntryRow, conflicts: (existing.conflicts ?? []) as ScheduleConflictRow[] };
}
const conflicts = await detectScheduleConflicts({
tenantId: input.tenantId,
assignedUserId,
startAt: range.startAt,
endAt: range.endAt,
excludeEntryId: input.entryId,
});
const blockingConflicts = conflicts.filter((conflict) => conflict.severity === "blocking");
const overrideReason = normalizeText(input.conflictOverrideReason);
if (blockingConflicts.length > 0 && !overrideReason) {
throw new AuftragServiceError("projects.error.scheduleConflictOverrideRequired");
}
const entry = await withTenantRLS(input.tenantId, async (tx) => {
const project = await requireProjectWithTx(tx, { tenantId: input.tenantId, projectId: input.projektId });
if (input.entryId) {
const existing = await tx.scheduleEntry.findFirst({ where: { id: input.entryId, tenantId: input.tenantId, archivedAt: null }, select: { id: true } });
if (!existing) throw new CatalogError(foundationErrors.notFound, { entryId: input.entryId });
return tx.scheduleEntry.update({
where: { id: input.entryId },
data: {
projektId: project.id,
assignedUserId,
title,
startAt: range.startAt,
endAt: range.endAt,
status: input.status ?? "planned",
calendarEventId: normalizeText(input.calendarEventId),
syncStatus: "pending",
conflictOverrideReason: overrideReason,
},
});
}
return tx.scheduleEntry.create({
data: {
tenantId: input.tenantId,
projektId: project.id,
assignedUserId,
createdByUserId: input.userId,
title,
startAt: range.startAt,
endAt: range.endAt,
status: input.status ?? "planned",
calendarEventId: normalizeText(input.calendarEventId),
conflictOverrideReason: overrideReason,
clientMutationId,
},
});
});
await replaceScheduleConflicts({ tenantId: input.tenantId, entryId: entry.id, conflicts, overridden: Boolean(overrideReason) });
await logActivity({
tenantId: input.tenantId,
actorUserId: input.userId,
actorKind: "user",
activityType: "project_schedule_changed",
subjectType: "project",
subjectId: input.projektId,
summaryText: "Plantafel-Termin wurde gespeichert.",
metadata: { scheduleEntryId: entry.id, assignedUserId },
}).catch(() => undefined);
const saved = await withTenantRLS(input.tenantId, (tx) => tx.scheduleEntry.findUniqueOrThrow({ where: { id: entry.id }, include: { conflicts: true } }));
return { entry: saved as ScheduleEntryRow, conflicts: (saved.conflicts ?? []) as ScheduleConflictRow[] };
}
export async function updateScheduleEntryStatus(input: {
tenantId: string;
userId: string;
entryId: string;
status: ScheduleEntryStatus;
clientMutationId?: string | null;
}): Promise<ScheduleEntryRow> {
const row = await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.scheduleEntry.findFirst({ where: { id: input.entryId, tenantId: input.tenantId, archivedAt: null } });
if (!existing) throw new CatalogError(foundationErrors.notFound, { entryId: input.entryId });
return tx.scheduleEntry.update({ where: { id: existing.id }, data: { status: input.status, syncStatus: "pending" } });
});
await logActivity({
tenantId: input.tenantId,
actorUserId: input.userId,
actorKind: "user",
activityType: "project_schedule_changed",
subjectType: "project",
subjectId: row.projektId,
summaryText: "Plantafel-Status wurde geändert.",
metadata: { scheduleEntryId: row.id, status: input.status },
}).catch(() => undefined);
return row as ScheduleEntryRow;
}
export async function bulkReassignScheduleEntries(input: {
tenantId: string;
userId: string;
entryIds: readonly string[];
assignedUserId: string;
conflictOverrideReason?: string | null;
}): Promise<{ updated: number }> {
const assignedUserId = normalizeText(input.assignedUserId);
if (!assignedUserId) throw new AuftragServiceError("projects.error.scheduleAssigneeRequired");
const overrideReason = normalizeText(input.conflictOverrideReason);
let updated = 0;
for (const entryId of input.entryIds) {
const existing = await withTenantRLS(input.tenantId, (tx) => tx.scheduleEntry.findFirst({ where: { id: entryId, tenantId: input.tenantId, archivedAt: null } }));
if (!existing) continue;
const conflicts = await detectScheduleConflicts({
tenantId: input.tenantId,
assignedUserId,
startAt: existing.startAt,
endAt: existing.endAt,
excludeEntryId: existing.id,
});
if (conflicts.some((conflict) => conflict.severity === "blocking") && !overrideReason) {
throw new AuftragServiceError("projects.error.scheduleConflictOverrideRequired");
}
await withTenantRLS(input.tenantId, (tx) =>
tx.scheduleEntry.update({ where: { id: existing.id }, data: { assignedUserId, syncStatus: "pending", conflictOverrideReason: overrideReason } }),
);
await replaceScheduleConflicts({ tenantId: input.tenantId, entryId: existing.id, conflicts, overridden: Boolean(overrideReason) });
updated += 1;
}
return { updated };
}
async function createAcceptancePdfFile(input: {
tenantId: string;
userId: string;
project: ProjektRow;
protocolId: string;
acceptanceKind: AcceptanceKind;
datum: Date;
signatures: readonly AcceptanceSignatureInput[];
}): Promise<{ fileId: string; storageKey: string; byteLength: number }> {
await ensureServerGlobalI18n();
const pdf = await buildPdfExportArtifact(
{
columns: [
{ key: "field", label: i18next.t("projects.acceptance.pdf.columns.field") },
{ key: "value", label: i18next.t("projects.acceptance.pdf.columns.value") },
],
rows: [
{ field: i18next.t("projects.acceptance.pdf.fields.project"), value: `${input.project.projektNummer} ${input.project.projektname}` },
{ field: i18next.t("projects.acceptance.pdf.fields.acceptance"), value: input.acceptanceKind },
{ field: i18next.t("projects.acceptance.pdf.fields.date"), value: input.datum.toISOString() },
{ field: i18next.t("projects.acceptance.pdf.fields.signatures"), value: input.signatures.map((signature) => `${signature.signerRole}:${signature.signerName}`).join(", ") },
],
},
{ title: i18next.t("projects.acceptance.pdf.title") },
);
const fileId = `file_${randomUUID()}`;
const { original } = buildFileStorageKeys(input.tenantId, fileId);
const storageKey = original;
await putBufferAsFile({ bucket: resolveStorageBucket(), key: storageKey, body: pdf.bytes, contentType: pdf.contentType });
await withTenantRLS(input.tenantId, async (tx) => {
await tx.file.create({
data: {
id: fileId,
tenantId: input.tenantId,
createdByUserId: input.userId,
displayName: `acceptance-${input.project.projektNummer}.pdf`,
mimeType: pdf.contentType,
sizeBytes: pdf.byteLength,
storageKey,
source: "automation",
scanStatus: "skipped",
previewStatus: "pending",
},
});
await tx.fileEntityLink.create({
data: {
tenantId: input.tenantId,
createdByUserId: input.userId,
fileId,
entityType: "project",
entityId: input.project.id,
linkRole: "acceptance_protocol",
},
});
});
return { fileId, storageKey, byteLength: pdf.byteLength };
}
async function notifyProjectLead(input: { tenantId: string; userId: string | null; messageKey: string; sourceKey: string; metadata: Record<string, string> }): Promise<void> {
if (!input.userId) return;
await createNotificationDelivery({
tenantId: input.tenantId,
userId: input.userId,
channel: "IN_APP",
category: "projects",
messageKey: input.messageKey,
sourceKey: input.sourceKey,
payloadMetadata: input.metadata,
}).catch(() => undefined);
}
async function moveRejectedProjectBackWithTx(tx: TenantRlsClient, input: { tenantId: string; project: ProjektRow }): Promise<void> {
const executionStage = await tx.pipelineStage.findFirst({
where: { tenantId: input.tenantId, pipelineId: input.project.pipelineId, stageKind: "offen", archivedAt: null },
orderBy: { position: "desc" },
select: { id: true },
});
if (!executionStage || executionStage.id === input.project.stageId) return;
await tx.projekt.update({ where: { id: input.project.id }, data: { stageId: executionStage.id, wonAt: null, lostAt: null, lostReasonId: null } });
}
export async function listAcceptanceProtocols(input: { tenantId: string; projectId: string; ctx: PlantafelContext }): Promise<AcceptanceListVM> {
requireAcceptanceRead(input.ctx);
return withTenantRLS(input.tenantId, async (tx) => {
const project = await requireProjectWithTx(tx, { tenantId: input.tenantId, projectId: input.projectId });
const protocols = await tx.abnahmeProtokoll.findMany({
where: { tenantId: input.tenantId, projektId: input.projectId, archivedAt: null },
include: { signatures: { orderBy: { signedAt: "asc" } } },
orderBy: { datum: "desc" },
});
return { project, protocols: protocols as AbnahmeProtokollRow[] };
});
}
export async function submitAcceptanceProtocol(input: {
tenantId: string;
userId: string;
projectId: string;
datum?: string | Date | null;
maengelChecklistId?: string | null;
defects?: readonly AcceptanceDefectInput[];
anwesende?: unknown;
druckprobe?: unknown;
funktionspruefung?: unknown;
zaehlerstaende?: unknown;
dokumente?: unknown;
bemerkungen?: string | null;
signatures: readonly AcceptanceSignatureInput[];
customerEmail?: string | null;
clientMutationId?: string | null;
}): Promise<AbnahmeProtokollRow> {
const clientMutationId = normalizeClientMutationId(input.clientMutationId);
if (clientMutationId) {
const existing = await withTenantRLS(input.tenantId, (tx) =>
tx.abnahmeProtokoll.findUnique({ where: { tenantId_clientMutationId: { tenantId: input.tenantId, clientMutationId } }, include: { signatures: true } }),
);
if (existing) return existing as AbnahmeProtokollRow;
}
const datum = parseDate(input.datum) ?? new Date();
const acceptanceKind = classifyAcceptanceKind(input.defects ?? []);
const signatures = input.signatures.map((signature) => ({
signerName: normalizeText(signature.signerName),
signerRole: signature.signerRole,
signatureFileId: normalizeText(signature.signatureFileId),
signerIpHash: hashIpAddress(signature.signerIpAddress),
}));
if (!signatures.some((signature) => signature.signerRole === "kunde" && signature.signerName)) {
throw new AuftragServiceError("projects.error.acceptanceCustomerSignatureRequired");
}
if (!signatures.some((signature) => signature.signerRole === "monteur" && signature.signerName)) {
throw new AuftragServiceError("projects.error.acceptanceTechnicianSignatureRequired");
}
const maengelChecklistId = normalizeText(input.maengelChecklistId);
const { project, checklistOk } = await withTenantRLS(input.tenantId, async (tx) => {
const project = await requireProjectWithTx(tx, { tenantId: input.tenantId, projectId: input.projectId });
if (!maengelChecklistId) return { project, checklistOk: acceptanceKind === "full" };
const checklist = await tx.projektChecklist.findFirst({
where: { id: maengelChecklistId, tenantId: input.tenantId, projektId: input.projectId, typ: "maengel", archivedAt: null },
select: { id: true },
});
return { project, checklistOk: Boolean(checklist) };
});
if (!checklistOk) throw new AuftragServiceError("projects.error.acceptanceDefectChecklistRequired");
const protocolId = `abn_${randomUUID()}`;
const pdfFile = await createAcceptancePdfFile({
tenantId: input.tenantId,
userId: input.userId,
project,
protocolId,
acceptanceKind,
datum,
signatures: input.signatures,
});
const protocol = await withTenantRLS(input.tenantId, async (tx) => {
await tx.abnahmeProtokoll.create({
data: {
id: protocolId,
tenantId: input.tenantId,
projektId: project.id,
maengelChecklistId,
createdByUserId: input.userId,
datum,
acceptanceKind,
anwesende: input.anwesende ?? [],
druckprobe: input.druckprobe ?? {},
funktionspruefung: input.funktionspruefung ?? {},
zaehlerstaende: input.zaehlerstaende ?? {},
dokumente: input.dokumente ?? [],
bemerkungen: normalizeText(input.bemerkungen),
pdfFileId: pdfFile.fileId,
customerEmail: normalizeText(input.customerEmail),
clientMutationId,
gesperrtAt: new Date(),
},
});
await tx.abnahmeSignatur.createMany({
data: signatures.map((signature) => ({
tenantId: input.tenantId,
protokollId: protocolId,
signerName: signature.signerName ?? "",
signerRole: signature.signerRole,
signatureFileId: signature.signatureFileId,
signerIpHash: signature.signerIpHash,
})),
});
if (acceptanceKind === "rejected") {
await moveRejectedProjectBackWithTx(tx, { tenantId: input.tenantId, project });
}
return tx.abnahmeProtokoll.findUniqueOrThrow({ where: { id: protocolId }, include: { signatures: true } });
});
if (acceptanceKind === "with_defects" || acceptanceKind === "rejected") {
await createTask({
tenantId: input.tenantId,
userId: input.userId,
title: "projects.defaults.tasks.resolveAcceptanceDefects",
description: protocol.id,
priority: acceptanceKind === "rejected" ? "urgent" : "high",
assignedToUserId: project.projektleiterId ?? project.zustaendigePersonId ?? input.userId,
linkedEntityType: "project",
linkedEntityId: project.id,
source: "automation",
sourceRef: protocol.id,
}).catch(() => undefined);
await notifyProjectLead({
tenantId: input.tenantId,
userId: project.projektleiterId ?? project.zustaendigePersonId,
messageKey: acceptanceKind === "rejected" ? "projects.notify.acceptance.rejected" : "projects.notify.acceptance.withDefects",
sourceKey: `acceptance:${protocol.id}:${acceptanceKind}`,
metadata: { projectId: project.id, protocolId: protocol.id },
});
}
const customerEmail = normalizeText(input.customerEmail);
if (customerEmail) {
await ensureServerGlobalI18n();
const queued = await queueTransactionalEmail({
tenantId: input.tenantId,
userId: input.userId,
to: customerEmail,
subject: i18next.t("projects.acceptance.email.subject"),
body: i18next.t("projects.acceptance.email.body", { pdfFileId: pdfFile.fileId }),
alias: "projects.acceptance.protocol",
data: { projectId: project.id, protocolId: protocol.id, pdfFileId: pdfFile.fileId },
priorityOverride: "normal",
}).then(
() => true,
() => false,
);
if (queued) {
await withTenantRLS(input.tenantId, (tx) => tx.abnahmeProtokoll.update({ where: { id: protocol.id }, data: { customerEmailQueuedAt: new Date() } })).catch(() => undefined);
}
}
await logActivity({
tenantId: input.tenantId,
actorUserId: input.userId,
actorKind: "user",
activityType: "project_acceptance_submitted",
subjectType: "project",
subjectId: project.id,
summaryText: "Abnahmeprotokoll wurde gespeichert.",
metadata: { protocolId: protocol.id, acceptanceKind, pdfFileId: pdfFile.fileId },
}).catch(() => undefined);
return withTenantRLS(input.tenantId, (tx) => tx.abnahmeProtokoll.findUniqueOrThrow({ where: { id: protocol.id }, include: { signatures: true } })) as Promise<AbnahmeProtokollRow>;
}
export async function archiveAcceptanceProtocol(input: { tenantId: string; protocolId: string; userId: string }): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const protocol = await tx.abnahmeProtokoll.findFirst({ where: { id: input.protocolId, tenantId: input.tenantId, archivedAt: null }, select: { id: true } });
if (!protocol) throw new CatalogError(foundationErrors.notFound, { protocolId: input.protocolId });
await tx.abnahmeProtokoll.update({ where: { id: protocol.id }, data: { archivedAt: new Date() } });
});
}
export async function hardDeleteAcceptanceProtocol(): Promise<never> {
throw new AuftragServiceError("projects.error.acceptanceHardDeleteBlocked");
}
export async function applyOfflineMutation(input: {
tenantId: string;
userId: string;
clientMutationId: string;
operation: OfflineSyncOperation;
payload: Record<string, unknown>;
}): Promise<{ entityType: string; entityId: string }> {
const clientMutationId = normalizeClientMutationId(input.clientMutationId);
if (!clientMutationId) throw new AuftragServiceError("projects.error.offlineMutationIdRequired");
const payloadJson = input.payload as Prisma.InputJsonValue;
const existing = await withTenantRLS(input.tenantId, (tx) =>
tx.offlineSyncMutation.findUnique({ where: { tenantId_clientMutationId: { tenantId: input.tenantId, clientMutationId } } }),
);
if (existing?.status === "applied" && existing.resultEntityType && existing.resultEntityId) {
return { entityType: existing.resultEntityType, entityId: existing.resultEntityId };
}
await withTenantRLS(input.tenantId, (tx) =>
tx.offlineSyncMutation.upsert({
where: { tenantId_clientMutationId: { tenantId: input.tenantId, clientMutationId } },
update: { payload: payloadJson, status: "pending", errorMessageKey: null },
create: {
tenantId: input.tenantId,
clientMutationId,
createdByUserId: input.userId,
operation: input.operation,
payload: payloadJson,
},
}),
);
try {
let result: { entityType: string; entityId: string };
if (input.operation === "schedule_upsert") {
const schedule = await upsertScheduleEntry({
tenantId: input.tenantId,
userId: input.userId,
projektId: String(input.payload.projektId ?? ""),
assignedUserId: String(input.payload.assignedUserId ?? ""),
title: String(input.payload.title ?? ""),
startAt: String(input.payload.startAt ?? ""),
endAt: String(input.payload.endAt ?? ""),
status: input.payload.status as ScheduleEntryStatus | undefined,
clientMutationId,
conflictOverrideReason: typeof input.payload.conflictOverrideReason === "string" ? input.payload.conflictOverrideReason : null,
});
result = { entityType: "schedule_entry", entityId: schedule.entry.id };
} else if (input.operation === "schedule_status") {
const schedule = await updateScheduleEntryStatus({
tenantId: input.tenantId,
userId: input.userId,
entryId: String(input.payload.entryId ?? ""),
status: input.payload.status as ScheduleEntryStatus,
clientMutationId,
});
result = { entityType: "schedule_entry", entityId: schedule.id };
} else {
const protocol = await submitAcceptanceProtocol({
tenantId: input.tenantId,
userId: input.userId,
projectId: String(input.payload.projectId ?? ""),
maengelChecklistId: typeof input.payload.maengelChecklistId === "string" ? input.payload.maengelChecklistId : null,
defects: Array.isArray(input.payload.defects) ? (input.payload.defects as AcceptanceDefectInput[]) : [],
signatures: Array.isArray(input.payload.signatures) ? (input.payload.signatures as AcceptanceSignatureInput[]) : [],
clientMutationId,
});
result = { entityType: "acceptance_protocol", entityId: protocol.id };
}
await withTenantRLS(input.tenantId, (tx) =>
tx.offlineSyncMutation.update({
where: { tenantId_clientMutationId: { tenantId: input.tenantId, clientMutationId } },
data: { status: "applied", resultEntityType: result.entityType, resultEntityId: result.entityId, appliedAt: new Date() },
}),
);
return result;
} catch (error) {
const messageKey = error instanceof AuftragServiceError ? error.messageKey : "projects.error.offlineMutationFailed";
await withTenantRLS(input.tenantId, (tx) =>
tx.offlineSyncMutation.update({ where: { tenantId_clientMutationId: { tenantId: input.tenantId, clientMutationId } }, data: { status: "failed", errorMessageKey: messageKey } }),
).catch(() => undefined);
throw error;
}
}
@@ -0,0 +1,62 @@
import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo } from "~/utils/session.server";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
import { PROJECTS_MODULE_KEY } from "./projectRoutePaths";
import { AuftragServiceError } from "./auftragService.server";
import { ProjectServiceError, type ProjectVisibilityContext } from "./projectService.server";
export type ProjectRouteContext = ProjectVisibilityContext & {
tenantId: string;
hasModule: boolean;
};
export async function loadProjectContext({
request,
params,
requireModule = false,
}: {
request: Request;
params: Record<string, string | undefined>;
requireModule?: boolean;
}): Promise<ProjectRouteContext> {
await requireAuth({ request, params });
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
if (!tenantId || !userInfo.userId) {
throw new CatalogError(foundationErrors.notFound);
}
const [hasModule, permissions] = await Promise.all([
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: PROJECTS_MODULE_KEY }),
getPermissionsByUser(userInfo.userId, tenantId),
]);
if (requireModule && !hasModule) {
throw new CatalogError(foundationErrors.notFound, { module: PROJECTS_MODULE_KEY });
}
return { tenantId, userId: userInfo.userId, permissions, hasModule };
}
export function requireProjectPermission(ctx: ProjectRouteContext, permission: string): ProjectRouteContext {
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, permission);
return ctx;
}
export function requireAnyProjectPermission(ctx: ProjectRouteContext, permissions: readonly string[]): ProjectRouteContext {
if (permissions.some((permission) => ctx.permissions.includes(permission))) return ctx;
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, permissions[0] ?? "projects.read_own");
return ctx;
}
export function projectActionErrorResponse(error: unknown): Response {
if (error instanceof CatalogError) {
return Response.json({ error: error.i18nKey, code: error.code }, { status: error.status });
}
if (error instanceof ProjectServiceError) {
return Response.json({ error: error.messageKey }, { status: 400 });
}
if (error instanceof AuftragServiceError) {
return Response.json({ error: error.messageKey }, { status: 400 });
}
throw error;
}
@@ -0,0 +1,49 @@
export const PROJECTS_MODULE_KEY = "projects";
export function projectsPath(tenantSlug: string): string {
return `/${tenantSlug}/projects`;
}
export function projectDetailPath(tenantSlug: string, projectId: string): string {
return `/${tenantSlug}/projects/${projectId}`;
}
export function projectsListPath(tenantSlug: string): string {
return `/${tenantSlug}/projects/list`;
}
export function projectPipelinePath(tenantSlug: string, pipelineId: string): string {
return `/${tenantSlug}/projects/pipelines/${pipelineId}`;
}
export function projectPipelineStreamPath(tenantSlug: string, pipelineId: string): string {
return `/${tenantSlug}/projects/pipelines/${pipelineId}/stream`;
}
export function projectPlantafelPath(tenantSlug: string): string {
return `/${tenantSlug}/projects/plantafel`;
}
export function projectAcceptancePath(tenantSlug: string, projectId: string): string {
return `/${tenantSlug}/projects/${projectId}/acceptance`;
}
export function projectAcceptanceNewPath(tenantSlug: string, projectId: string): string {
return `/${tenantSlug}/projects/${projectId}/acceptance/new`;
}
export function pipelinesAdminPath(tenantSlug: string): string {
return `/${tenantSlug}/admin/pipelines`;
}
export function lostReasonsAdminPath(tenantSlug: string): string {
return `/${tenantSlug}/admin/pipelines/lost-reasons`;
}
export function acceptanceFormsAdminPath(tenantSlug: string): string {
return `/${tenantSlug}/admin/projects/acceptance-forms`;
}
export function projectTemplatesAdminPath(tenantSlug: string): string {
return `/${tenantSlug}/admin/projects/templates`;
}
@@ -0,0 +1,336 @@
import { readFileSync } from "node:fs";
import { resolveRepoPath } from "~/utils/testing/repoPaths";
import { describe, expect, test } from "vitest";
import { ProjectServiceError, validatePipelineStages } from "./projectService.server";
describe("project pipeline validation", () => {
test("accepts a pipeline with at least one won and lost stage", () => {
expect(() =>
validatePipelineStages([
{ name: "Neu", stageKind: "offen" },
{ name: "Gewonnen", stageKind: "gewonnen" },
{ name: "Verloren", stageKind: "verloren" },
]),
).not.toThrow();
});
test("rejects pipelines without a won stage", () => {
expect(() =>
validatePipelineStages([
{ name: "Neu", stageKind: "offen" },
{ name: "Verloren", stageKind: "verloren" },
]),
).toThrow(ProjectServiceError);
});
test("rejects pipelines without a lost stage", () => {
expect(() =>
validatePipelineStages([
{ name: "Neu", stageKind: "offen" },
{ name: "Gewonnen", stageKind: "gewonnen" },
]),
).toThrow(ProjectServiceError);
});
});
describe("R-P8a project backend artifacts", () => {
test("reserves project numbers with a row lock and without database extensions", () => {
const source = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/projectService.server.ts"), "utf8");
expect(source).toContain('FROM "HiveNumberSeq"');
expect(source).toContain("FOR UPDATE");
expect(source).not.toContain("gen_random_uuid");
});
test("keeps all project models in the RLS rollout artifact", () => {
const source = readFileSync(resolveRepoPath("prisma/rls/projekt-isolation.sql"), "utf8");
[
"HiveNumberSeq",
"Pipeline",
"PipelineStage",
"PipelineAccess",
"PipelineFieldConfig",
"PipelineFieldVisibility",
"LostReason",
"Projekt",
"ProjektStageChange",
"PipelineAggregateSnapshot",
"ProjektKontakt",
].forEach((model) => {
expect(source).toContain(`'${model}'`);
});
expect(source).toContain("ENABLE ROW LEVEL SECURITY");
expect(source).toContain("FORCE ROW LEVEL SECURITY");
expect(source).toContain("hivegrid_app");
});
test("registers the project tenant models for snapshot and restore", () => {
const source = readFileSync(resolveRepoPath("packages/cli/src/commands/tenant/models.ts"), "utf8");
["HiveNumberSeq", "Pipeline", "PipelineStage", "Projekt", "ProjektStageChange", "PipelineAggregateSnapshot", "ProjektKontakt"].forEach((model) => {
expect(source).toContain(`model: "${model}"`);
expect(source).toContain('schema: "projekt.prisma"');
});
});
test("exposes server-side pipeline and lost-reason mutations for the later screen layer", () => {
const service = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/projectService.server.ts"), "utf8");
[
"export async function createPipeline",
"export async function updatePipeline",
"export async function archivePipeline",
"export async function duplicatePipeline",
"export async function upsertPipelineAccess",
"export async function upsertPipelineFieldConfig",
"export async function upsertPipelineFieldVisibility",
"export async function upsertLostReason",
"export async function archiveLostReason",
].forEach((exportName) => {
expect(service).toContain(exportName);
});
});
test("gates pipeline admin actions through the projects admin permission", () => {
const pipelineRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/admin.pipelines._index.tsx"), "utf8");
const lostReasonsRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/admin.pipelines.lost-reasons.tsx"), "utf8");
expect(pipelineRoute).toContain('"projects.admin"');
expect(pipelineRoute).toContain('intent === "duplicatePipeline"');
expect(pipelineRoute).toContain('intent === "upsertFieldVisibility"');
expect(lostReasonsRoute).toContain('"projects.admin"');
expect(lostReasonsRoute).toContain('intent === "upsertLostReason"');
expect(lostReasonsRoute).toContain('intent === "archiveLostReason"');
});
test("wires the lead conversion route into the P8 auto-project service", () => {
const route = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/leads.$id.tsx"), "utf8");
expect(route).toContain("createProjectFromQualifiedLead");
expect(route).toContain('intent === "convert"');
});
});
describe("R-P8b project board and forecast backend artifacts", () => {
test("persists stage history and aggregate cache in the project schema", () => {
const source = readFileSync(resolveRepoPath("prisma/schema/projekt.prisma"), "utf8");
expect(source).toContain("model ProjektStageChange");
expect(source).toContain("undoUntil");
expect(source).toContain("model PipelineAggregateSnapshot");
expect(source).toContain("weightedForecast");
expect(source).toContain("@@unique([tenantId, pipelineId, scopeKey])");
});
test("exposes board, list, forecast, stage move, undo, and CSV service contracts", () => {
const service = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/projectService.server.ts"), "utf8");
[
"export async function loadProjectBoard",
"export async function listProjectsForTable",
"export async function exportProjectListCsv",
"export async function rebuildPipelineAggregateCache",
"export async function getPipelineForecast",
"export async function moveProjectStage",
"export async function undoLastProjectStageChange",
].forEach((exportName) => {
expect(service).toContain(exportName);
});
expect(service).toContain('event: "deal.won"');
expect(service).toContain('"projects.error.lostReasonRequired"');
expect(service).toContain("pipelineFieldVisibility");
expect(service).toContain("deals.read_aggregates");
});
test("routes provide board actions, list CSV, pipeline forecast, and SSE stream contracts", () => {
const boardRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/projects._index.tsx"), "utf8");
const listRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/projects.list.tsx"), "utf8");
const pipelineRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/projects.pipelines.$pipelineId.tsx"), "utf8");
const streamRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/projects.pipelines.$pipelineId.stream.tsx"), "utf8");
expect(boardRoute).toContain("loadProjectBoard");
expect(boardRoute).toContain('intent === "moveStage"');
expect(boardRoute).toContain('intent === "undoStage"');
expect(listRoute).toContain('export") === "csv"');
expect(listRoute).toContain("text/csv; charset=utf-8");
expect(pipelineRoute).toContain("getPipelineForecast");
expect(streamRoute).toContain("eventStream");
expect(streamRoute).toContain("projects.board.snapshot");
});
});
describe("R-P9a order view and project sub-area backend artifacts", () => {
test("keeps order work as sub-areas on the existing project core", () => {
const source = readFileSync(resolveRepoPath("prisma/schema/auftrag.prisma"), "utf8");
[
"model ProjektMitglied",
"model ProjektTermin",
"model Rechnung",
"model ProjektChecklist",
"model ProjektChecklistItem",
"model AuftragPipelineStageConfig",
"model AcceptanceFormTemplate",
"model ProjectTemplate",
].forEach((model) => {
expect(source).toContain(model);
});
expect(source).toContain("projektId");
expect(source).not.toMatch(/^model\s+Auftrag\s+\{/m);
expect(source).not.toContain("ProjektExternesFeld");
});
test("reserves invoice numbers through HiveNumberSeq with a row lock", () => {
const source = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/auftragService.server.ts"), "utf8");
expect(source).toContain('FROM "HiveNumberSeq"');
expect(source).toContain("FOR UPDATE");
expect(source).toContain("entityType");
expect(source).toContain("rechnung");
expect(source).toContain('padStart(padding, "0")');
});
test("keeps all order sub-area models in the RLS rollout artifact", () => {
const source = readFileSync(resolveRepoPath("prisma/rls/auftrag-isolation.sql"), "utf8");
["ProjektMitglied", "ProjektTermin", "Rechnung", "ProjektChecklist", "ProjektChecklistItem", "AuftragPipelineStageConfig", "AcceptanceFormTemplate", "ProjectTemplate"].forEach(
(model) => {
expect(source).toContain(`'${model}'`);
},
);
expect(source).toContain("ENABLE ROW LEVEL SECURITY");
expect(source).toContain("FORCE ROW LEVEL SECURITY");
expect(source).toContain("hivegrid_app");
});
test("registers order sub-area tenant models for snapshot and restore", () => {
const source = readFileSync(resolveRepoPath("packages/cli/src/commands/tenant/models.ts"), "utf8");
["ProjektMitglied", "ProjektTermin", "Rechnung", "ProjektChecklist", "ProjektChecklistItem", "AuftragPipelineStageConfig", "AcceptanceFormTemplate", "ProjectTemplate"].forEach(
(model) => {
expect(source).toContain(`model: "${model}"`);
expect(source).toContain('schema: "auftrag.prisma"');
},
);
});
test("exposes order sub-area service contracts for the later screen layer", () => {
const service = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/auftragService.server.ts"), "utf8");
[
"export async function loadProjectSubAreas",
"export async function addProjectMember",
"export async function createProjectAppointment",
"export async function createProjectInvoice",
"export async function updateProjectInvoiceStatus",
"export async function createProjectChecklist",
"export async function upsertProjectChecklistItem",
"export async function upsertAuftragPipelineStageConfig",
"export async function listAcceptanceFormTemplates",
"export async function upsertAcceptanceFormTemplate",
"export async function listProjectTemplates",
"export async function upsertProjectTemplate",
"export async function autoArchiveProjectsForStageConfigs",
].forEach((exportName) => {
expect(service).toContain(exportName);
});
});
test("routes gate sub-area and template actions through the projects module and permissions", () => {
const detailRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/projects.$id.tsx"), "utf8");
const pipelineAdminRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/admin.pipelines._index.tsx"), "utf8");
const acceptanceFormsRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/admin.projects.acceptance-forms.tsx"), "utf8");
const templatesRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/admin.projects.templates.tsx"), "utf8");
expect(detailRoute).toContain("loadProjectSubAreas");
expect(detailRoute).toContain('"projects.read_own_member"');
expect(detailRoute).toContain('intent === "createInvoice"');
expect(detailRoute).toContain('intent === "upsertChecklistItem"');
expect(pipelineAdminRoute).toContain('intent === "upsertAuftragStageConfig"');
expect(acceptanceFormsRoute).toContain('"projects.admin"');
expect(acceptanceFormsRoute).toContain('intent === "upsertAcceptanceFormTemplate"');
expect(templatesRoute).toContain('"projects.admin"');
expect(templatesRoute).toContain('intent === "upsertProjectTemplate"');
});
test("seeds the additional projects permission needed by order memberships", () => {
const defaultPermissions = readFileSync(resolveRepoPath("apps/web/app/application/dtos/shared/DefaultPermissions.ts"), "utf8");
const permissionSeed = readFileSync(resolveRepoPath("packages/db/src/permissions-seed.server.ts"), "utf8");
expect(defaultPermissions).toContain('"projects.read_own_member"');
expect(permissionSeed).toContain('"projects.read_own_member"');
});
});
describe("R-P9b schedule board and acceptance backend artifacts", () => {
test("persists plantafel, acceptance, signature, and offline-sync models in the order schema", () => {
const source = readFileSync(resolveRepoPath("prisma/schema/auftrag.prisma"), "utf8");
[
"model ScheduleEntry",
"model ScheduleConflict",
"model AbnahmeProtokoll",
"model AbnahmeSignatur",
"model OfflineSyncMutation",
"enum AcceptanceKind",
"enum ScheduleEntryStatus",
].forEach((needle) => {
expect(source).toContain(needle);
});
expect(source).toContain("gesperrtAt");
expect(source).toContain("signerIpHash");
expect(source).toContain("@@unique([tenantId, clientMutationId])");
});
test("keeps all R-P9b models in RLS and tenant snapshot artifacts", () => {
const rls = readFileSync(resolveRepoPath("prisma/rls/auftrag-isolation.sql"), "utf8");
const tenantModels = readFileSync(resolveRepoPath("packages/cli/src/commands/tenant/models.ts"), "utf8");
["ScheduleEntry", "ScheduleConflict", "AbnahmeProtokoll", "AbnahmeSignatur", "OfflineSyncMutation"].forEach((model) => {
expect(rls).toContain(`'${model}'`);
expect(tenantModels).toContain(`model: "${model}"`);
expect(tenantModels).toContain('schema: "auftrag.prisma"');
});
});
test("exposes plantafel, acceptance, offline sync, PDF, and notification contracts", () => {
const service = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/plantafelAcceptanceService.server.ts"), "utf8");
[
"export async function loadPlantafel",
"export async function upsertScheduleEntry",
"export async function updateScheduleEntryStatus",
"export async function bulkReassignScheduleEntries",
"export async function listAcceptanceProtocols",
"export async function submitAcceptanceProtocol",
"export async function archiveAcceptanceProtocol",
"export async function hardDeleteAcceptanceProtocol",
"export async function applyOfflineMutation",
].forEach((exportName) => {
expect(service).toContain(exportName);
});
expect(service).toContain("listApprovedAbsencesForRange");
expect(service).toContain("buildPdfExportArtifact");
expect(service).toContain("queueTransactionalEmail");
expect(service).toContain("createNotificationDelivery");
expect(service).toContain("createTask");
});
test("blocks stage moves when a target stage requires an acceptance protocol", () => {
const service = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/projects/projectService.server.ts"), "utf8");
expect(service).toContain("requiresAcceptanceProtocol");
expect(service).toContain("abnahmeProtokoll.findFirst");
expect(service).toContain('"projects.error.acceptanceProtocolRequired"');
});
test("routes expose plantafel, acceptance list, and acceptance submit contracts behind module gates", () => {
const plantafelRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/projects.plantafel.tsx"), "utf8");
const acceptanceRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/projects.$id.acceptance._index.tsx"), "utf8");
const acceptanceNewRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/projects.$id.acceptance.new.tsx"), "utf8");
expect(plantafelRoute).toContain("loadPlantafel");
expect(plantafelRoute).toContain('intent === "upsertSchedule"');
expect(plantafelRoute).toContain('intent === "offlineSync"');
expect(plantafelRoute).toContain('"plantafel.bulk_reassign"');
expect(acceptanceRoute).toContain("listAcceptanceProtocols");
expect(acceptanceRoute).toContain('intent === "archiveAcceptanceProtocol"');
expect(acceptanceNewRoute).toContain("submitAcceptanceProtocol");
expect(acceptanceNewRoute).toContain('"acceptance.write"');
});
test("registers R-P9b permissions and labels", () => {
const defaultPermissions = readFileSync(resolveRepoPath("apps/web/app/application/dtos/shared/DefaultPermissions.ts"), "utf8");
const permissionSeed = readFileSync(resolveRepoPath("packages/db/src/permissions-seed.server.ts"), "utf8");
const roleDisplay = readFileSync(resolveRepoPath("apps/web/app/components/core/roles/roleDisplay.ts"), "utf8");
["plantafel.read_own", "plantafel.read_all", "plantafel.write", "plantafel.bulk_reassign", "acceptance.read", "acceptance.write", "acceptance.admin"].forEach(
(permission) => {
expect(defaultPermissions).toContain(`"${permission}"`);
expect(permissionSeed).toContain(`"${permission}"`);
},
);
expect(roleDisplay).toContain("bulk_reassign");
expect(roleDisplay).toContain("plantafel");
expect(roleDisplay).toContain("acceptance");
});
});
@@ -1,4 +1,4 @@
import type { PreUploadScanResult } from "@toolctrl/storage";
import type { PreUploadScanResult } from "@hivegrid/storage";
import { createAdminLog } from "~/utils/db/logs.db.server";
/**
@@ -1,4 +1,4 @@
import { loadRequiredWebConfig } from "@toolctrl/config";
import { loadRequiredWebConfig } from "@hivegrid/config";
import {
createLocalStorageAdapter,
createS3StorageAdapter,
@@ -9,7 +9,7 @@ import {
type PreUploadScanResult,
type ScanContext,
type StorageAdapter,
} from "@toolctrl/storage";
} from "@hivegrid/storage";
import { fetchOutboundHttpWithRedirects } from "~/utils/outboundHttp.server";
type StorageConfig = ReturnType<typeof loadRequiredWebConfig>["storage"];
@@ -72,7 +72,7 @@ export type StoreFileInput = {
onReject?: (verdict: PreUploadScanResult) => void | Promise<void>;
/**
* When true AND the layer-1 scan passes AND the storage PUT succeeds,
* storeFile enqueues a toolctrl.file-scan job so the worker runs ClamAV
* storeFile enqueues a hivegrid.file-scan job so the worker runs ClamAV
* (layer 2) over the stored object. Requires SCAN_QUEUE_ENABLED=true
* on the runtime; otherwise the enqueue is a no-op. Failures to enqueue
* are logged but never throw — the synchronous user-visible upload
@@ -8,7 +8,7 @@
// - Write actions pass `requireModule: true` → 404 (CatalogError.notFound) when
// the module is off, and additionally require an explicit permission.
import { CatalogError, foundationErrors, requirePermission } from "@toolctrl/foundation";
import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo } from "~/utils/session.server";
@@ -9,8 +9,8 @@
// entity's timeline with the task referenced; otherwise it hangs off the task's
// own timeline (`task` is itself a valid Activity subject).
import type { JsonValue } from "@toolctrl/foundation";
import { createAuditEvent } from "@toolctrl/db/audit-events.server";
import type { JsonValue } from "@hivegrid/foundation";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { logActivity, type ActivitySubjectType, type ActivityType } from "@hivegrid/activity";
import type { TasksRouteContext } from "./taskAccess.server";
import type { TaskEntityType } from "./taskService.server";
@@ -20,7 +20,9 @@
// global User lookup (resolveUserLabels): User is not tenant-scoped (a user can
// belong to several tenants), so it stays on the db singleton.
import { CatalogError, foundationErrors } from "@toolctrl/foundation";
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { tasksIndex } from "@hivegrid/search";
import { publishSearchProjectionDelete, publishTaskSearchUpsert } from "~/services/search/searchIndexProjection.server";
import { db } from "~/utils/db.server";
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
@@ -146,8 +148,8 @@ export async function createTask(input: CreateTaskInput): Promise<TaskRow> {
if ((linkedEntityType && !linkedEntityId) || (!linkedEntityType && linkedEntityId)) {
throw new TaskServiceError("tasks.error.invalidEntityLink");
}
const task = await withTenantRLS(input.tenantId, (tx) =>
tx.task.create({
const task = await withTenantRLS(input.tenantId, async (tx) => {
const created = await tx.task.create({
data: {
tenantId: input.tenantId,
createdByUserId: input.userId,
@@ -163,8 +165,10 @@ export async function createTask(input: CreateTaskInput): Promise<TaskRow> {
sourceRef: input.sourceRef ?? null,
isDemoData: input.isDemoData ?? false,
},
}),
);
});
await publishTaskSearchUpsert(tx, created);
return created;
});
return task as TaskRow;
}
@@ -197,8 +201,8 @@ export async function updateTask(input: UpdateTaskInput): Promise<void> {
if (!existing) {
throw new CatalogError(foundationErrors.notFound, { taskId: input.taskId });
}
await tx.task.updateMany({
where: { id: input.taskId, tenantId: input.tenantId },
const updated = await tx.task.update({
where: { id: existing.id },
data: {
...(input.title !== undefined ? { title: input.title.trim().slice(0, MAX_TITLE_LENGTH) } : {}),
...(input.description !== undefined ? { description: input.description } : {}),
@@ -210,6 +214,7 @@ export async function updateTask(input: UpdateTaskInput): Promise<void> {
...(completedAt !== undefined ? { completedAt } : {}),
},
});
await publishTaskSearchUpsert(tx, updated);
});
}
@@ -223,7 +228,7 @@ export async function reassignTask(input: {
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.task.findFirst({
where: { id: input.taskId, tenantId: input.tenantId },
select: { createdByUserId: true },
select: { id: true, createdByUserId: true },
});
if (!existing) {
throw new CatalogError(foundationErrors.notFound, { taskId: input.taskId });
@@ -233,28 +238,45 @@ export async function reassignTask(input: {
assignedToUserId: input.assignedToUserId,
assignedToGroupId: input.assignedToGroupId,
});
await tx.task.updateMany({
where: { id: input.taskId, tenantId: input.tenantId },
const updated = await tx.task.update({
where: { id: existing.id },
data: { assignedToUserId: assignment.assignedToUserId, assignedToGroupId: assignment.assignedToGroupId },
});
await publishTaskSearchUpsert(tx, updated);
});
}
export async function completeTask(input: { tenantId: string; taskId: string }): Promise<void> {
await withTenantRLS(input.tenantId, (tx) =>
tx.task.updateMany({
where: { id: input.taskId, tenantId: input.tenantId },
data: { status: "done", completedAt: new Date() },
}),
);
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.task.findFirst({ where: { id: input.taskId, tenantId: input.tenantId }, select: { id: true } });
if (!existing) {
throw new CatalogError(foundationErrors.notFound, { taskId: input.taskId });
}
const updated = await tx.task.update({ where: { id: existing.id }, data: { status: "done", completedAt: new Date() } });
await publishTaskSearchUpsert(tx, updated);
});
}
export async function archiveTask(input: { tenantId: string; taskId: string }): Promise<void> {
await withTenantRLS(input.tenantId, (tx) => tx.task.updateMany({ where: { id: input.taskId, tenantId: input.tenantId }, data: { archivedAt: new Date() } }));
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.task.findFirst({ where: { id: input.taskId, tenantId: input.tenantId }, select: { id: true } });
if (!existing) {
throw new CatalogError(foundationErrors.notFound, { taskId: input.taskId });
}
await tx.task.update({ where: { id: existing.id }, data: { archivedAt: new Date() } });
await publishSearchProjectionDelete(tx, { schema: tasksIndex, tenantId: input.tenantId, entityType: "task", entityId: existing.id });
});
}
export async function reactivateTask(input: { tenantId: string; taskId: string }): Promise<void> {
await withTenantRLS(input.tenantId, (tx) => tx.task.updateMany({ where: { id: input.taskId, tenantId: input.tenantId }, data: { archivedAt: null } }));
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.task.findFirst({ where: { id: input.taskId, tenantId: input.tenantId }, select: { id: true } });
if (!existing) {
throw new CatalogError(foundationErrors.notFound, { taskId: input.taskId });
}
const updated = await tx.task.update({ where: { id: existing.id }, data: { archivedAt: null } });
await publishTaskSearchUpsert(tx, updated);
});
}
export async function hardDeleteTask(input: { tenantId: string; taskId: string }): Promise<void> {
@@ -265,6 +287,7 @@ export async function hardDeleteTask(input: { tenantId: string; taskId: string }
}
// TaskWatcher rows cascade on Task delete (schema onDelete: Cascade).
await tx.task.delete({ where: { id: task.id } });
await publishSearchProjectionDelete(tx, { schema: tasksIndex, tenantId: input.tenantId, entityType: "task", entityId: task.id });
});
}
@@ -386,6 +409,7 @@ export type ListTasksFilter = {
linkedEntityId?: string | null;
source?: TaskSource | null;
includeArchived?: boolean;
includeDemoData?: boolean;
};
/**
@@ -431,6 +455,7 @@ export async function listTasksForBrowser(input: {
const where = {
tenantId: input.tenantId,
...(filter.includeArchived ? {} : { archivedAt: null }),
...(filter.includeDemoData ? {} : { isDemoData: false }),
...(filter.status ? { status: filter.status } : {}),
...(filter.priority ? { priority: filter.priority } : {}),
...(filter.assignedToUserId ? { assignedToUserId: filter.assignedToUserId } : {}),