Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+233
@@ -0,0 +1,233 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
connectionFindFirst: vi.fn(),
|
||||
connectionUpdateMany: vi.fn(async () => ({ count: 1 })),
|
||||
syncRunCreate: vi.fn(),
|
||||
syncRunFindMany: vi.fn(async () => []),
|
||||
syncRunFindFirst: vi.fn(),
|
||||
syncItemFindMany: vi.fn(async () => []),
|
||||
syncRunLogFindMany: vi.fn(async () => []),
|
||||
encryptTenantField: vi.fn(async () => "sealed"),
|
||||
createAuditEvent: vi.fn(async () => undefined),
|
||||
notify: vi.fn(async () => undefined),
|
||||
validateConnection: vi.fn(async () => ({
|
||||
ok: true,
|
||||
health: "active" as const,
|
||||
messageKey: "integrations.health.active",
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/foundation", async () => ({
|
||||
...(await vi.importActual<typeof import("@hivegrid/foundation")>("@hivegrid/foundation")),
|
||||
notify: mocks.notify,
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: async (_tenantId: string, callback: (tx: unknown) => Promise<unknown>) =>
|
||||
callback({
|
||||
dataConnection: {
|
||||
findFirst: mocks.connectionFindFirst,
|
||||
updateMany: mocks.connectionUpdateMany,
|
||||
},
|
||||
appSyncRun: {
|
||||
create: mocks.syncRunCreate,
|
||||
findMany: mocks.syncRunFindMany,
|
||||
findFirst: mocks.syncRunFindFirst,
|
||||
},
|
||||
appSyncItem: { findMany: mocks.syncItemFindMany },
|
||||
appSyncRunLog: { findMany: mocks.syncRunLogFindMany },
|
||||
}),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/crypto/tenant-envelope.server", () => ({
|
||||
decryptTenantField: vi.fn(),
|
||||
encryptTenantField: mocks.encryptTenantField,
|
||||
}));
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({ createAuditEvent: mocks.createAuditEvent }));
|
||||
vi.mock("~/utils/db.server", () => ({ db: {} }));
|
||||
vi.mock("@hivegrid/integrations", () => ({
|
||||
resolveAdapter: vi.fn(() => ({ validateConnection: mocks.validateConnection })),
|
||||
}));
|
||||
|
||||
import {
|
||||
disconnectConnection,
|
||||
checkConnectionHealth,
|
||||
getConnectionOrThrow,
|
||||
getSyncRunWithItems,
|
||||
listSyncRuns,
|
||||
reconnectConnection,
|
||||
runSyncForConnection,
|
||||
} from "./appsEngineService.server";
|
||||
|
||||
const CONNECTION_ROW = {
|
||||
id: "connection-1",
|
||||
tenantId: "tenant-1",
|
||||
appId: "sample-data-sync",
|
||||
label: "Sample",
|
||||
connectionStatus: "active",
|
||||
lastHealthCheck: null,
|
||||
healthMessageKey: null,
|
||||
tokenExpiresAt: null,
|
||||
createdByUserId: "user-1",
|
||||
isDemoData: false,
|
||||
createdAt: new Date("2026-07-20T10:00:00.000Z"),
|
||||
archivedAt: null,
|
||||
} as const;
|
||||
|
||||
describe("Apps Engine app/connection binding", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.connectionUpdateMany.mockResolvedValue({ count: 1 });
|
||||
mocks.syncRunFindMany.mockResolvedValue([]);
|
||||
mocks.syncItemFindMany.mockResolvedValue([]);
|
||||
mocks.syncRunLogFindMany.mockResolvedValue([]);
|
||||
mocks.encryptTenantField.mockResolvedValue("sealed");
|
||||
mocks.validateConnection.mockResolvedValue({
|
||||
ok: true,
|
||||
health: "active",
|
||||
messageKey: "integrations.health.active",
|
||||
});
|
||||
});
|
||||
|
||||
it("loads a connection only when tenant, id, and expected app all match", async () => {
|
||||
mocks.connectionFindFirst.mockResolvedValueOnce(CONNECTION_ROW);
|
||||
|
||||
await expect(getConnectionOrThrow("tenant-1", "connection-1", "sample-data-sync")).resolves.toMatchObject({
|
||||
id: "connection-1",
|
||||
appId: "sample-data-sync",
|
||||
});
|
||||
expect(mocks.connectionFindFirst).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { id: "connection-1", tenantId: "tenant-1", appId: "sample-data-sync" },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("binds reconnect and disconnect reads and writes to the expected app", async () => {
|
||||
mocks.connectionFindFirst.mockResolvedValue({ id: "connection-1", appId: "sample-data-sync" });
|
||||
|
||||
await reconnectConnection({
|
||||
tenantId: "tenant-1",
|
||||
connectionId: "connection-1",
|
||||
expectedAppId: "sample-data-sync",
|
||||
credentials: { apiKey: "fixture" },
|
||||
actorUserId: "user-1",
|
||||
});
|
||||
await disconnectConnection({
|
||||
tenantId: "tenant-1",
|
||||
connectionId: "connection-1",
|
||||
expectedAppId: "sample-data-sync",
|
||||
actorUserId: "user-1",
|
||||
});
|
||||
|
||||
expect(mocks.connectionFindFirst).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.connectionFindFirst).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({
|
||||
where: { id: "connection-1", tenantId: "tenant-1", appId: "sample-data-sync" },
|
||||
}),
|
||||
);
|
||||
expect(mocks.connectionFindFirst).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({
|
||||
where: { id: "connection-1", tenantId: "tenant-1", appId: "sample-data-sync" },
|
||||
}),
|
||||
);
|
||||
expect(mocks.connectionUpdateMany).toHaveBeenCalledTimes(2);
|
||||
for (const [input] of mocks.connectionUpdateMany.mock.calls) {
|
||||
expect(input).toEqual(
|
||||
expect.objectContaining({
|
||||
where: { id: "connection-1", tenantId: "tenant-1", appId: "sample-data-sync" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
expect(mocks.connectionUpdateMany).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({ credentialsCiphertext: null, tokenExpiresAt: null, connectionStatus: "revoked" }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects a manual sync before creating a run when the expected app does not match", async () => {
|
||||
mocks.connectionFindFirst.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
runSyncForConnection({
|
||||
tenantId: "tenant-1",
|
||||
connectionId: "kwp-connection",
|
||||
expectedAppId: "sample-data-sync",
|
||||
kind: "manual",
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
expect(mocks.connectionFindFirst).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { id: "kwp-connection", tenantId: "tenant-1", appId: "sample-data-sync" },
|
||||
}),
|
||||
);
|
||||
expect(mocks.syncRunCreate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("binds sync history and run detail to both the connection and its expected app", async () => {
|
||||
mocks.syncRunFindFirst.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(listSyncRuns("tenant-1", "connection-1", "sample-data-sync")).resolves.toEqual([]);
|
||||
expect(mocks.syncRunFindMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
tenantId: "tenant-1",
|
||||
dataConnectionId: "connection-1",
|
||||
dataConnection: { tenantId: "tenant-1", appId: "sample-data-sync" },
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 50,
|
||||
});
|
||||
|
||||
await expect(
|
||||
getSyncRunWithItems("tenant-1", "run-1", "connection-1", "sample-data-sync"),
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
expect(mocks.syncRunFindFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: "run-1",
|
||||
tenantId: "tenant-1",
|
||||
dataConnectionId: "connection-1",
|
||||
dataConnection: { tenantId: "tenant-1", appId: "sample-data-sync" },
|
||||
},
|
||||
});
|
||||
expect(mocks.syncItemFindMany).not.toHaveBeenCalled();
|
||||
expect(mocks.syncRunLogFindMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("links an unhealthy-connection notification to the affected connection settings", async () => {
|
||||
mocks.connectionFindFirst.mockResolvedValueOnce({
|
||||
id: "connection-1",
|
||||
appId: "aircall",
|
||||
connectionStatus: "active",
|
||||
credentialsCiphertext: null,
|
||||
createdByUserId: "user-1",
|
||||
});
|
||||
|
||||
await expect(
|
||||
checkConnectionHealth({
|
||||
tenantId: "tenant-1",
|
||||
connectionId: "connection-1",
|
||||
notificationDeeplink: "/acme/settings/integrations/telephony",
|
||||
}),
|
||||
).resolves.toEqual({ status: "broken", messageKey: "integrations.health.notConnected" });
|
||||
|
||||
expect(mocks.notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
tenantId: "tenant-1",
|
||||
userId: "user-1",
|
||||
messageKey: "integrations.notify.connectionUnhealthy",
|
||||
sourceKey: "integrations:connection-unhealthy:connection-1",
|
||||
payloadMetadata: expect.objectContaining({
|
||||
connectionId: "connection-1",
|
||||
health: "broken",
|
||||
deeplink: "/acme/settings/integrations/telephony",
|
||||
}),
|
||||
}),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
});
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
row: null as null | {
|
||||
id: string;
|
||||
appId: string;
|
||||
label: string;
|
||||
connectionStatus: "active" | "degraded" | "broken" | "revoked" | "pending";
|
||||
credentialsCiphertext: string | null;
|
||||
},
|
||||
decryptTenantField: vi.fn(async () => JSON.stringify({ accessToken: "fixture-token" })),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: async (_tenantId: string, callback: (tx: unknown) => Promise<unknown>) =>
|
||||
callback({ dataConnection: { findFirst: vi.fn(async () => mocks.row) } }),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/crypto/tenant-envelope.server", () => ({
|
||||
decryptTenantField: mocks.decryptTenantField,
|
||||
encryptTenantField: vi.fn(),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({ createAuditEvent: vi.fn() }));
|
||||
vi.mock("@hivegrid/db/notifications.server", () => ({ createNotificationDelivery: vi.fn() }));
|
||||
vi.mock("~/utils/db.server", () => ({ db: {} }));
|
||||
vi.mock("@hivegrid/integrations", () => ({ resolveAdapter: vi.fn() }));
|
||||
|
||||
import { AppsEngineServiceError, runWithConnectionCredentials } from "./appsEngineService.server";
|
||||
|
||||
describe("runWithConnectionCredentials", () => {
|
||||
beforeEach(() => {
|
||||
mocks.decryptTenantField.mockClear();
|
||||
mocks.row = {
|
||||
id: "connection-1",
|
||||
appId: "aircall",
|
||||
label: "Aircall",
|
||||
connectionStatus: "active",
|
||||
credentialsCiphertext: "sealed",
|
||||
};
|
||||
});
|
||||
|
||||
it("decrypts only after a tenant-scoped app match and passes frozen credentials to the callback", async () => {
|
||||
const result = await runWithConnectionCredentials(
|
||||
{ tenantId: "tenant-1", connectionId: "connection-1", expectedAppId: "aircall" },
|
||||
async (credentials, connection) => ({ credentials, connection }),
|
||||
);
|
||||
expect(result.connection).toEqual({ id: "connection-1", appId: "aircall", label: "Aircall" });
|
||||
expect(result.credentials).toEqual({ accessToken: "fixture-token" });
|
||||
expect(Object.isFrozen(result.credentials)).toBe(true);
|
||||
expect(mocks.decryptTenantField).toHaveBeenCalledWith(
|
||||
"tenant-1",
|
||||
"sealed",
|
||||
expect.objectContaining({ client: expect.objectContaining({ dataConnection: expect.any(Object) }) }),
|
||||
);
|
||||
});
|
||||
|
||||
it("hides a connection belonging to another app", async () => {
|
||||
await expect(
|
||||
runWithConnectionCredentials({ tenantId: "tenant-1", connectionId: "connection-1", expectedAppId: "google" }, async () => undefined),
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
expect(mocks.decryptTenantField).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects revoked or credential-less connections with a Klartext key", async () => {
|
||||
mocks.row = { ...mocks.row!, connectionStatus: "revoked", credentialsCiphertext: null };
|
||||
await expect(
|
||||
runWithConnectionCredentials(
|
||||
{ tenantId: "tenant-1", connectionId: "connection-1", expectedAppId: "aircall" },
|
||||
async () => undefined,
|
||||
),
|
||||
).rejects.toEqual(
|
||||
expect.objectContaining<Partial<AppsEngineServiceError>>({ messageKey: "integrations.error.connectionUnavailable" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
events: [] as string[],
|
||||
updateMany: vi.fn(async () => ({ count: 1 })),
|
||||
encryptTenantField: vi.fn(async () => "sealed-credentials"),
|
||||
createAuditEvent: vi.fn(async () => undefined),
|
||||
validateConnection: vi.fn(async () => ({
|
||||
ok: true,
|
||||
health: "active" as const,
|
||||
messageKey: "integrations.health.active",
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: async (_tenantId: string, callback: (tx: unknown) => Promise<unknown>) => {
|
||||
mocks.events.push("transaction");
|
||||
return callback({ dataConnection: { updateMany: mocks.updateMany } });
|
||||
},
|
||||
}));
|
||||
vi.mock("@hivegrid/db/crypto/tenant-envelope.server", () => ({
|
||||
decryptTenantField: vi.fn(),
|
||||
encryptTenantField: async (...args: unknown[]) => {
|
||||
mocks.events.push("encrypt");
|
||||
return mocks.encryptTenantField(...args);
|
||||
},
|
||||
}));
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({ createAuditEvent: mocks.createAuditEvent }));
|
||||
vi.mock("@hivegrid/db/notifications.server", () => ({ createNotificationDelivery: vi.fn() }));
|
||||
vi.mock("~/utils/db.server", () => ({ db: {} }));
|
||||
vi.mock("@hivegrid/integrations", () => ({
|
||||
resolveAdapter: vi.fn(() => ({
|
||||
key: "kwp",
|
||||
connectionType: "oauth2",
|
||||
validateConnection: async (...args: unknown[]) => {
|
||||
mocks.events.push("validate");
|
||||
return mocks.validateConnection(...args);
|
||||
},
|
||||
})),
|
||||
}));
|
||||
|
||||
import { activateOAuthConnection, AppsEngineServiceError } from "./appsEngineService.server";
|
||||
|
||||
describe("activateOAuthConnection", () => {
|
||||
beforeEach(() => {
|
||||
mocks.events.length = 0;
|
||||
mocks.updateMany.mockClear();
|
||||
mocks.encryptTenantField.mockClear();
|
||||
mocks.createAuditEvent.mockClear();
|
||||
mocks.validateConnection.mockClear();
|
||||
mocks.validateConnection.mockResolvedValue({
|
||||
ok: true,
|
||||
health: "active",
|
||||
messageKey: "integrations.health.active",
|
||||
});
|
||||
mocks.updateMany.mockResolvedValue({ count: 1 });
|
||||
});
|
||||
|
||||
it("validates outside the transaction and persists encrypted OAuth credentials with expiry", async () => {
|
||||
const tokenExpiresAt = new Date("2026-07-20T18:30:00.000Z");
|
||||
await activateOAuthConnection({
|
||||
tenantId: "tenant-1",
|
||||
connectionId: "connection-1",
|
||||
appId: "kwp",
|
||||
credentials: { accessToken: "access", refreshToken: "refresh" },
|
||||
tokenExpiresAt,
|
||||
actorUserId: "user-1",
|
||||
expectedUpdatedAt: new Date("2026-07-20T12:00:00.000Z"),
|
||||
});
|
||||
|
||||
expect(mocks.events).toEqual(["validate", "encrypt", "transaction"]);
|
||||
expect(mocks.encryptTenantField).toHaveBeenCalledWith(
|
||||
"tenant-1",
|
||||
JSON.stringify({ accessToken: "access", refreshToken: "refresh" }),
|
||||
);
|
||||
expect(mocks.updateMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: "connection-1",
|
||||
tenantId: "tenant-1",
|
||||
appId: "kwp",
|
||||
archivedAt: null,
|
||||
updatedAt: new Date("2026-07-20T12:00:00.000Z"),
|
||||
},
|
||||
data: expect.objectContaining({
|
||||
credentialsCiphertext: "sealed-credentials",
|
||||
tokenExpiresAt,
|
||||
connectionStatus: "active",
|
||||
healthMessageKey: "integrations.health.active",
|
||||
}),
|
||||
});
|
||||
expect(mocks.createAuditEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
tenantId: "tenant-1",
|
||||
actorId: "user-1",
|
||||
action: "INTEGRATION_OAUTH_CONNECT",
|
||||
targetId: "connection-1",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not persist credentials when the provider validation fails", async () => {
|
||||
mocks.validateConnection.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
health: "broken",
|
||||
messageKey: "integrations.health.scopeMissing",
|
||||
});
|
||||
|
||||
await expect(
|
||||
activateOAuthConnection({
|
||||
tenantId: "tenant-1",
|
||||
connectionId: "connection-1",
|
||||
appId: "kwp",
|
||||
credentials: {},
|
||||
tokenExpiresAt: null,
|
||||
actorUserId: "user-1",
|
||||
expectedUpdatedAt: new Date("2026-07-20T12:00:00.000Z"),
|
||||
}),
|
||||
).rejects.toEqual(
|
||||
expect.objectContaining<Partial<AppsEngineServiceError>>({
|
||||
messageKey: "integrations.health.scopeMissing",
|
||||
}),
|
||||
);
|
||||
expect(mocks.events).toEqual(["validate"]);
|
||||
expect(mocks.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects a slot that is not owned by the tenant and app", async () => {
|
||||
mocks.updateMany.mockResolvedValueOnce({ count: 0 });
|
||||
|
||||
await expect(
|
||||
activateOAuthConnection({
|
||||
tenantId: "tenant-1",
|
||||
connectionId: "foreign-slot",
|
||||
appId: "kwp",
|
||||
credentials: { accessToken: "access" },
|
||||
tokenExpiresAt: null,
|
||||
actorUserId: "user-1",
|
||||
expectedUpdatedAt: new Date("2026-07-20T12:00:00.000Z"),
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
expect(mocks.createAuditEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+191
-32
@@ -8,10 +8,9 @@
|
||||
// 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 { CatalogError, foundationErrors, notify, 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";
|
||||
@@ -86,8 +85,44 @@ async function encryptCredentials(tenantId: string, credentials: Record<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>;
|
||||
async function decryptCredentials(
|
||||
tenantId: string,
|
||||
ciphertext: string,
|
||||
client?: TenantRlsClient,
|
||||
): Promise<Record<string, unknown>> {
|
||||
return JSON.parse(
|
||||
await decryptTenantField(tenantId, ciphertext, client ? { client: client as never } : undefined),
|
||||
) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute provider work with one tenant-scoped DataConnection's decrypted
|
||||
* credentials. The callback is the only intended plaintext boundary and must
|
||||
* never return or persist the credential object. The database transaction ends
|
||||
* before external provider I/O starts.
|
||||
*/
|
||||
export async function runWithConnectionCredentials<T>(
|
||||
input: { tenantId: string; connectionId: string; expectedAppId: string },
|
||||
callback: (credentials: Readonly<Record<string, unknown>>, connection: { id: string; appId: string; label: string }) => Promise<T>,
|
||||
): Promise<T> {
|
||||
const loaded = await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const connection = await tx.dataConnection.findFirst({
|
||||
where: { id: input.connectionId, tenantId: input.tenantId, appId: input.expectedAppId, archivedAt: null },
|
||||
select: { id: true, appId: true, label: true, connectionStatus: true, credentialsCiphertext: true },
|
||||
});
|
||||
if (!connection || connection.appId !== input.expectedAppId) {
|
||||
throw new CatalogError(foundationErrors.notFound, { connectionId: input.connectionId });
|
||||
}
|
||||
if ((connection.connectionStatus !== "active" && connection.connectionStatus !== "degraded") || !connection.credentialsCiphertext) {
|
||||
throw new AppsEngineServiceError("integrations.error.connectionUnavailable");
|
||||
}
|
||||
|
||||
return {
|
||||
connection: { id: connection.id, appId: connection.appId, label: connection.label },
|
||||
credentials: Object.freeze(await decryptCredentials(input.tenantId, connection.credentialsCiphertext, tx)),
|
||||
};
|
||||
});
|
||||
return callback(loaded.credentials, loaded.connection);
|
||||
}
|
||||
|
||||
// --- Connection lifecycle (DoD #1/#6/#7) ----------------------------------
|
||||
@@ -108,8 +143,10 @@ export async function listConnections(tenantId: string, opts?: { appId?: string;
|
||||
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 }));
|
||||
export async function getConnectionOrThrow(tenantId: string, connectionId: string, expectedAppId: string): Promise<DataConnectionRow> {
|
||||
const row = await withTenantRLS(tenantId, (tx) =>
|
||||
tx.dataConnection.findFirst({ where: { id: connectionId, tenantId, appId: expectedAppId }, select: CONNECTION_SELECT }),
|
||||
);
|
||||
if (!row) {
|
||||
throw new CatalogError(foundationErrors.notFound, { connectionId });
|
||||
}
|
||||
@@ -125,6 +162,17 @@ export type CreateConnectionInput = {
|
||||
isDemoData?: boolean;
|
||||
};
|
||||
|
||||
export type ActivateOAuthConnectionInput = {
|
||||
tenantId: string;
|
||||
connectionId: string;
|
||||
appId: string;
|
||||
credentials: Record<string, unknown>;
|
||||
tokenExpiresAt: Date | null;
|
||||
actorUserId: string;
|
||||
/** DataConnection.updatedAt captured before redirecting to the provider. */
|
||||
expectedUpdatedAt: Date;
|
||||
};
|
||||
|
||||
/**
|
||||
* Connect a new DataConnection: validate the credentials via the app's adapter,
|
||||
* then store them envelope-encrypted with status `active`. Multiple connections
|
||||
@@ -165,11 +213,66 @@ export async function createConnection(input: CreateConnectionInput): Promise<{
|
||||
return created;
|
||||
}
|
||||
|
||||
/**
|
||||
* Activate a previously reserved OAuth connection after the provider callback.
|
||||
*
|
||||
* Provider validation deliberately finishes before the database transaction so
|
||||
* a slow or unavailable OAuth/resource endpoint never holds RLS database locks.
|
||||
* Only the validated credential bundle crosses the envelope-encryption boundary.
|
||||
*/
|
||||
export async function activateOAuthConnection(input: ActivateOAuthConnectionInput): Promise<void> {
|
||||
const adapter = resolveAdapter(input.appId);
|
||||
if (!adapter || adapter.connectionType !== "oauth2") {
|
||||
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 updated = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.dataConnection.updateMany({
|
||||
where: {
|
||||
id: input.connectionId,
|
||||
tenantId: input.tenantId,
|
||||
appId: input.appId,
|
||||
archivedAt: null,
|
||||
updatedAt: input.expectedUpdatedAt,
|
||||
},
|
||||
data: {
|
||||
credentialsCiphertext: ciphertext,
|
||||
tokenExpiresAt: input.tokenExpiresAt,
|
||||
connectionStatus: result.health,
|
||||
lastHealthCheck: new Date(),
|
||||
healthMessageKey: result.messageKey,
|
||||
},
|
||||
}),
|
||||
);
|
||||
if (updated.count !== 1) {
|
||||
throw new CatalogError(foundationErrors.notFound, { connectionId: input.connectionId });
|
||||
}
|
||||
|
||||
await audit(input.tenantId, input.actorUserId, "INTEGRATION_OAUTH_CONNECT", input.connectionId, {
|
||||
appId: input.appId,
|
||||
});
|
||||
}
|
||||
|
||||
/** 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> {
|
||||
export async function reconnectConnection(input: {
|
||||
tenantId: string;
|
||||
connectionId: string;
|
||||
expectedAppId: 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 } });
|
||||
const existing = await tx.dataConnection.findFirst({
|
||||
where: { id: input.connectionId, tenantId: input.tenantId, appId: input.expectedAppId },
|
||||
select: { id: true, appId: true },
|
||||
});
|
||||
if (!existing) {
|
||||
throw new CatalogError(foundationErrors.notFound, { connectionId: input.connectionId });
|
||||
}
|
||||
@@ -183,7 +286,7 @@ export async function reconnectConnection(input: { tenantId: string; connectionI
|
||||
}
|
||||
const ciphertext = await encryptCredentials(input.tenantId, input.credentials);
|
||||
await tx.dataConnection.updateMany({
|
||||
where: { id: input.connectionId, tenantId: input.tenantId },
|
||||
where: { id: input.connectionId, tenantId: input.tenantId, appId: input.expectedAppId },
|
||||
data: { credentialsCiphertext: ciphertext, connectionStatus: "active", lastHealthCheck: new Date(), healthMessageKey: result.messageKey, archivedAt: null },
|
||||
});
|
||||
});
|
||||
@@ -191,17 +294,26 @@ export async function reconnectConnection(input: { tenantId: string; connectionI
|
||||
}
|
||||
|
||||
/** Disconnect: set status `revoked` (NOT hard-delete → sync history preserved). */
|
||||
export async function disconnectConnection(input: { tenantId: string; connectionId: string; actorUserId: string }): Promise<void> {
|
||||
export async function disconnectConnection(input: { tenantId: string; connectionId: string; expectedAppId: 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 } });
|
||||
const existing = await tx.dataConnection.findFirst({
|
||||
where: { id: input.connectionId, tenantId: input.tenantId, appId: input.expectedAppId },
|
||||
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() },
|
||||
where: { id: input.connectionId, tenantId: input.tenantId, appId: input.expectedAppId },
|
||||
data: {
|
||||
connectionStatus: "revoked",
|
||||
credentialsCiphertext: null,
|
||||
tokenExpiresAt: null,
|
||||
healthMessageKey: "integrations.health.notConnected",
|
||||
lastHealthCheck: new Date(),
|
||||
},
|
||||
});
|
||||
});
|
||||
await audit(input.tenantId, input.actorUserId, "INTEGRATION_DISCONNECT", input.connectionId, {});
|
||||
@@ -230,9 +342,18 @@ export type AppSyncRunRow = {
|
||||
* 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 }> {
|
||||
export async function runSyncForConnection(input: {
|
||||
tenantId: string;
|
||||
connectionId: string;
|
||||
expectedAppId: 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 } });
|
||||
const connection = await tx.dataConnection.findFirst({
|
||||
where: { id: input.connectionId, tenantId: input.tenantId, appId: input.expectedAppId },
|
||||
select: { id: true, appId: true, connectionStatus: true, credentialsCiphertext: true },
|
||||
});
|
||||
if (!connection) {
|
||||
throw new CatalogError(foundationErrors.notFound, { connectionId: input.connectionId });
|
||||
}
|
||||
@@ -282,9 +403,13 @@ export async function runSyncForConnection(input: { tenantId: string; connection
|
||||
});
|
||||
}
|
||||
|
||||
export async function listSyncRuns(tenantId: string, connectionId: string, limit = 50): Promise<AppSyncRunRow[]> {
|
||||
export async function listSyncRuns(tenantId: string, connectionId: string, expectedAppId: 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) }),
|
||||
tx.appSyncRun.findMany({
|
||||
where: { tenantId, dataConnectionId: connectionId, dataConnection: { tenantId, appId: expectedAppId } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: Math.min(Math.max(limit, 1), 100),
|
||||
}),
|
||||
);
|
||||
return rows as AppSyncRunRow[];
|
||||
}
|
||||
@@ -307,9 +432,16 @@ export type AppSyncRunLogRowData = {
|
||||
createdAt: Date;
|
||||
};
|
||||
|
||||
export async function getSyncRunWithItems(tenantId: string, runId: string): Promise<{ run: AppSyncRunRow; items: AppSyncItemRowData[]; logs: AppSyncRunLogRowData[] }> {
|
||||
export async function getSyncRunWithItems(
|
||||
tenantId: string,
|
||||
runId: string,
|
||||
connectionId: string,
|
||||
expectedAppId: string,
|
||||
): Promise<{ run: AppSyncRunRow; items: AppSyncItemRowData[]; logs: AppSyncRunLogRowData[] }> {
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
const run = await tx.appSyncRun.findFirst({ where: { id: runId, tenantId } });
|
||||
const run = await tx.appSyncRun.findFirst({
|
||||
where: { id: runId, tenantId, dataConnectionId: connectionId, dataConnection: { tenantId, appId: expectedAppId } },
|
||||
});
|
||||
if (!run) {
|
||||
throw new CatalogError(foundationErrors.notFound, { runId });
|
||||
}
|
||||
@@ -342,9 +474,15 @@ const WEBHOOK_DEDUP_WINDOW_MS = 60_000;
|
||||
* `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 }> {
|
||||
export async function triggerWebhookSync(input: {
|
||||
tenantId: string;
|
||||
connectionId: string;
|
||||
expectedAppId: string;
|
||||
webhookEventKey: string;
|
||||
}): Promise<{ runId: string | null; status: SyncStatus | "replayed"; replayed: boolean }> {
|
||||
const result = await withIdempotency(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
scope: `integrations-webhook:${input.tenantId}:${input.connectionId}`,
|
||||
key: input.webhookEventKey,
|
||||
fingerprint: { connectionId: input.connectionId },
|
||||
@@ -354,7 +492,12 @@ export async function triggerWebhookSync(input: { tenantId: string; connectionId
|
||||
// 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" });
|
||||
const sync = await runSyncForConnection({
|
||||
tenantId: input.tenantId,
|
||||
connectionId: input.connectionId,
|
||||
expectedAppId: input.expectedAppId,
|
||||
kind: "webhook",
|
||||
});
|
||||
return { status: 200, body: { runId: sync.runId, status: sync.status } };
|
||||
},
|
||||
);
|
||||
@@ -369,7 +512,11 @@ export async function triggerWebhookSync(input: { tenantId: string; connectionId
|
||||
* 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 }> {
|
||||
export async function checkConnectionHealth(input: {
|
||||
tenantId: string;
|
||||
connectionId: string;
|
||||
notificationDeeplink: 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) {
|
||||
@@ -393,16 +540,28 @@ export async function checkConnectionHealth(input: { tenantId: string; connectio
|
||||
});
|
||||
|
||||
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);
|
||||
// Notify the owner through the M011 notify() contract on the request-scoped
|
||||
// db client (RLS context is bound by the surrounding request). Critical
|
||||
// category: a broken connection halts this tenant's sync, so the alert is
|
||||
// delivered regardless of preferences; the sourceKey dedupes repeated probes
|
||||
// into one delivery. A notify failure must not fail the probe.
|
||||
await notify(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
userId: outcome.ownerUserId,
|
||||
channel: "IN_APP",
|
||||
category: "critical",
|
||||
messageKey: "integrations.notify.connectionUnhealthy",
|
||||
sourceKey: `integrations:connection-unhealthy:${input.connectionId}`,
|
||||
payloadMetadata: {
|
||||
source: APPS_AUDIT_MODULE,
|
||||
connectionId: input.connectionId,
|
||||
health: outcome.status,
|
||||
deeplink: input.notificationDeeplink,
|
||||
},
|
||||
},
|
||||
db as unknown as Parameters<typeof notify>[1]
|
||||
).catch(() => undefined);
|
||||
}
|
||||
return { status: outcome.status, messageKey: outcome.messageKey };
|
||||
}
|
||||
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
// Avatar write-path (AD-23). Shared by the tenant profile and the admin profile
|
||||
// so both store the picture the same way: scanned bytes under a deterministic
|
||||
// key in the private media bucket, never a public object URL. The readable side
|
||||
// is the /avatars/:userId auth-proxy; see utils/app/avatarPaths.ts.
|
||||
|
||||
import { avatarStorageKey, isAvatarProxyPath } from "../app/avatarPaths";
|
||||
import { auditRejectedUpload } from "./storageAudit.server";
|
||||
import { StorageScanRejectedError, UploadContentReadError, deleteFile, resolveStorageBucket, storeFile } from "./storageService";
|
||||
|
||||
/**
|
||||
* An avatar runs through the magic-byte allow-list (png/jpeg/webp) and the
|
||||
* fail-closed malware scan before it is stored. Every rejection is an expected
|
||||
* outcome, not a crash: map it to a Klartext message (Bauprinzip A.1) so the
|
||||
* user learns what to do instead of getting a bare 500. A wrong file type, an
|
||||
* oversized image and an unreachable scanner are three different situations.
|
||||
* Genuine infrastructure faults (storage outage) return undefined on purpose so
|
||||
* the caller rethrows them.
|
||||
*/
|
||||
export function avatarUploadFailure(error: unknown): { key: string; status: number } | undefined {
|
||||
if (error instanceof StorageScanRejectedError) {
|
||||
if (error.scanResult.reason === "scanner_error") {
|
||||
return { key: "settings.profile.errors.avatarScanUnavailable", status: 503 };
|
||||
}
|
||||
if (error.scanResult.reason === "malware_detected") {
|
||||
return { key: "settings.profile.errors.avatarRejected", status: 422 };
|
||||
}
|
||||
return { key: "settings.profile.errors.avatarInvalid", status: 422 };
|
||||
}
|
||||
|
||||
if (error instanceof UploadContentReadError) {
|
||||
return error.code === "too_large"
|
||||
? { key: "settings.profile.errors.avatarTooLarge", status: 413 }
|
||||
: { key: "settings.profile.errors.avatarInvalid", status: 422 };
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan and store freshly picked avatar bytes. Rejections (wrong type, oversized,
|
||||
* malware, scanner down) surface as StorageScanRejectedError /
|
||||
* UploadContentReadError — the caller maps them to a Klartext message.
|
||||
*/
|
||||
export async function storeAvatar({
|
||||
request,
|
||||
userId,
|
||||
dataUri,
|
||||
auditContext,
|
||||
}: {
|
||||
request: Request;
|
||||
userId: string;
|
||||
dataUri: string;
|
||||
auditContext: string;
|
||||
}): Promise<void> {
|
||||
await storeFile({
|
||||
bucket: resolveStorageBucket(),
|
||||
content: dataUri,
|
||||
id: avatarStorageKey(userId),
|
||||
scan: {
|
||||
context: "avatar",
|
||||
requireMalwareScan: true,
|
||||
onReject: auditRejectedUpload(request, auditContext),
|
||||
filename: `${userId}.avatar`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Drop the stored object when the user clears their picture. */
|
||||
export async function removeStoredAvatar(currentAvatar: string | null | undefined, userId: string): Promise<void> {
|
||||
// Nothing is stored behind a legacy data: URI / absolute URL, or behind no
|
||||
// picture at all.
|
||||
if (!isAvatarProxyPath(currentAvatar)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await deleteFile({ bucket: resolveStorageBucket(), key: avatarStorageKey(userId) });
|
||||
} catch {
|
||||
// Clearing the reference is what removes the picture from every screen. A
|
||||
// failed object delete must not block that; the orphan bytes are no longer
|
||||
// reachable through the proxy.
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const DETAIL_SOURCE = readFileSync("apps/web/app/utils/integrations/crm/crmDetailRoute.server.ts", "utf8");
|
||||
const LIST_SOURCE = readFileSync("apps/web/app/utils/integrations/crm/crmListRoute.server.ts", "utf8");
|
||||
|
||||
describe("CRM activity i18n contract", () => {
|
||||
it("persists translation keys for machine-authored summaries", () => {
|
||||
const sources = `${DETAIL_SOURCE}\n${LIST_SOURCE}`;
|
||||
expect(sources).toContain('summaryText: "crm.activitySummary.basicsUpdated"');
|
||||
expect(sources).toContain('summaryText: "crm.activitySummary.bulkContactArchived"');
|
||||
expect(sources).not.toMatch(/summaryText: "(?:Stammdaten|Verantwortlicher|E-Mail|Telefonnummer|Verknüpfung|Tag|Kontakt) /);
|
||||
});
|
||||
});
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
// @vitest-environment node
|
||||
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
loadCrmContext: vi.fn(),
|
||||
getVisibleKontaktOrThrow: vi.fn(),
|
||||
validateCsrf: vi.fn(),
|
||||
invitePortalContact: vi.fn(),
|
||||
recordForeignTargetDenial: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("./crmAccess.server", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("./crmAccess.server")>();
|
||||
return { ...original, loadCrmContext: mocks.loadCrmContext };
|
||||
});
|
||||
|
||||
vi.mock("./crmService.server", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("./crmService.server")>();
|
||||
return { ...original, getVisibleKontaktOrThrow: mocks.getVisibleKontaktOrThrow };
|
||||
});
|
||||
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: mocks.validateCsrf }));
|
||||
|
||||
vi.mock("~/services/customer-portal/portal-invitation.server", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("~/services/customer-portal/portal-invitation.server")>();
|
||||
return {
|
||||
...original,
|
||||
invitePortalContact: mocks.invitePortalContact,
|
||||
recordPortalInvitationForeignTargetDenial: mocks.recordForeignTargetDenial,
|
||||
};
|
||||
});
|
||||
|
||||
import { handleKontaktDetailAction } from "./crmDetailRoute.server";
|
||||
|
||||
describe("contact portal invitation object authorization", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.loadCrmContext.mockResolvedValue({
|
||||
tenantId: "tenant-a",
|
||||
userId: "actor-a",
|
||||
permissions: ["crm.read_own", "portal.manage_users"],
|
||||
hasModule: true,
|
||||
});
|
||||
mocks.validateCsrf.mockResolvedValue(undefined);
|
||||
mocks.invitePortalContact.mockResolvedValue("portal-user-a");
|
||||
mocks.recordForeignTargetDenial.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("returns 404 and never invokes the invitation entrypoint for a hidden contact id", async () => {
|
||||
mocks.getVisibleKontaktOrThrow.mockRejectedValue(
|
||||
new CatalogError(foundationErrors.notFound, { kontaktId: "contact-hidden" }),
|
||||
);
|
||||
const request = new Request("https://app.example.test/acme/contacts/contact-hidden", {
|
||||
method: "POST",
|
||||
body: new URLSearchParams({ intent: "invitePortalContact", csrf: "token" }),
|
||||
});
|
||||
|
||||
const response = await handleKontaktDetailAction({
|
||||
request,
|
||||
params: { tenant: "acme", id: "contact-hidden" },
|
||||
variant: "contacts",
|
||||
});
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(mocks.getVisibleKontaktOrThrow).toHaveBeenCalledWith(
|
||||
"tenant-a",
|
||||
"contact-hidden",
|
||||
expect.objectContaining({ userId: "actor-a", permissions: ["crm.read_own", "portal.manage_users"] }),
|
||||
);
|
||||
expect(mocks.validateCsrf).toHaveBeenCalledBefore(mocks.getVisibleKontaktOrThrow);
|
||||
expect(mocks.recordForeignTargetDenial).toHaveBeenCalledWith({
|
||||
tenantId: "tenant-a",
|
||||
actorUserId: "actor-a",
|
||||
operation: "contact_invite",
|
||||
});
|
||||
expect(JSON.stringify(mocks.recordForeignTargetDenial.mock.calls)).not.toContain("contact-hidden");
|
||||
expect(mocks.invitePortalContact).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+146
-36
@@ -14,18 +14,15 @@ import {
|
||||
buildKontaktDetailVM,
|
||||
datentypLabelKey,
|
||||
type ActivityStreamVM,
|
||||
type ClickToCallVM,
|
||||
type KontaktDetailVM,
|
||||
} from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { loadTelephonyContext } from "~/modules/telephony/routes/telephonyAccess.server";
|
||||
import { loadTelephonyClickToCallVM, startTelephonyEntityCall, TelephonyServiceError } from "~/modules/telephony/services/TelephonyService.server";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import {
|
||||
badRequestResponse,
|
||||
crmActionErrorResponse,
|
||||
loadCrmContext,
|
||||
notFoundResponse,
|
||||
requireCrmPermission,
|
||||
type CrmRouteContext,
|
||||
} from "./crmAccess.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { badRequestResponse, crmActionErrorResponse, loadCrmContext, notFoundResponse, requireCrmPermission, type CrmRouteContext } from "./crmAccess.server";
|
||||
import {
|
||||
addKontaktEmail,
|
||||
addKontaktRelation,
|
||||
@@ -52,8 +49,13 @@ import {
|
||||
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 { companiesPath, contactDetailPath, contactsPath, companyDetailPath, tagsAdminPath } from "./crmRoutePaths";
|
||||
import { maskEmailActivitiesForViewer } from "~/modules/emailInbox/services/emailActivityMasking.server";
|
||||
import {
|
||||
canUsePortalInvitationEntrypoint,
|
||||
invitePortalContactFromEntrypoint,
|
||||
portalInvitationActionErrorResponse,
|
||||
} from "~/services/customer-portal/portal-invitation-entrypoint.server";
|
||||
|
||||
const KONTAKT_CUSTOM_FIELD_ENTITY = "kontakt";
|
||||
const KONTAKT_TAG_ENTITY_TYPE = "kontakt";
|
||||
@@ -71,8 +73,11 @@ export type KontaktDetailLoaderData = {
|
||||
detailVM: KontaktDetailVM;
|
||||
activityVM: ActivityStreamVM;
|
||||
allTags: { id: string; name: string; farbe: string }[];
|
||||
/** Set when the viewer may manage tags (crm.admin) — next action for the empty state. */
|
||||
tagsAdminHref: string | null;
|
||||
customFieldDefs: CustomFieldDefOption[];
|
||||
ownerOptions: { id: string; label: string }[];
|
||||
clickToCallVM: ClickToCallVM;
|
||||
};
|
||||
|
||||
type ActivityDbRow = {
|
||||
@@ -96,7 +101,7 @@ async function loadKontaktActivities(tenantId: string, subjectType: "contact" |
|
||||
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[];
|
||||
}
|
||||
@@ -128,13 +133,15 @@ export async function loadKontaktDetailData(args: {
|
||||
}
|
||||
const subjectType = detail.kontakt.kontaktTyp === "organisation" ? "company" : "contact";
|
||||
|
||||
const [customFields, tags, definitions, allTags, ownerOptions, activityRows] = await Promise.all([
|
||||
const portalInvitationAffordance = args.variant === "contacts" ? canUsePortalInvitationEntrypoint(ctx) : Promise.resolve(false);
|
||||
const [customFields, tags, definitions, allTags, ownerOptions, activityRows, canInviteToPortal] = 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),
|
||||
portalInvitationAffordance,
|
||||
]);
|
||||
|
||||
const actorIds = activityRows.map((row) => row.actorUserId).filter((id): id is string => Boolean(id));
|
||||
@@ -147,18 +154,44 @@ export async function loadKontaktDetailData(args: {
|
||||
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 }
|
||||
? {
|
||||
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 },
|
||||
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") },
|
||||
perms: {
|
||||
canWrite: ctx.permissions.includes("crm.write"),
|
||||
canDelete: ctx.permissions.includes("crm.delete"),
|
||||
canInviteToPortal,
|
||||
},
|
||||
tenantSlug,
|
||||
});
|
||||
const telephonyCtx = await loadTelephonyContext({ request: args.request, params: args.params, requireModule: false });
|
||||
const clickToCallVM = await loadTelephonyClickToCallVM(
|
||||
telephonyCtx,
|
||||
detail.telefone.map((phone) => ({
|
||||
id: phone.id,
|
||||
label: detailVM.data?.displayName ?? phone.telefon,
|
||||
e164: phone.telefon,
|
||||
primary: phone.primaer,
|
||||
}))
|
||||
);
|
||||
|
||||
// VA-P23 (M09 Block H): email activities are permission-masked — without
|
||||
// email.read_all only the viewer's OWN mailbox activities show details.
|
||||
@@ -193,6 +226,7 @@ export async function loadKontaktDetailData(args: {
|
||||
detailVM,
|
||||
activityVM,
|
||||
allTags: allTags.map((tag) => ({ id: tag.id, name: tag.name, farbe: tag.farbe })),
|
||||
tagsAdminHref: ctx.permissions.includes("crm.admin") ? tagsAdminPath(tenantSlug) : null,
|
||||
customFieldDefs: definitions.map((def) => ({
|
||||
id: def.id,
|
||||
key: def.key,
|
||||
@@ -201,6 +235,7 @@ export async function loadKontaktDetailData(args: {
|
||||
datentypLabelKey: datentypLabelKey(def.datentyp),
|
||||
})),
|
||||
ownerOptions,
|
||||
clickToCallVM,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -227,15 +262,43 @@ export async function handleKontaktDetailAction(args: {
|
||||
const listHref = args.variant === "companies" ? companiesPath(tenantSlug) : contactsPath(tenantSlug);
|
||||
|
||||
try {
|
||||
// Visibility + type are needed by almost every branch (activity subject).
|
||||
if (intent === "invitePortalContact") {
|
||||
if (args.variant !== "contacts") throw notFoundResponse();
|
||||
await invitePortalContactFromEntrypoint({
|
||||
request: args.request,
|
||||
formData: form,
|
||||
context: ctx,
|
||||
contactId: kontaktId,
|
||||
assertTargetVisible: async () => {
|
||||
await getVisibleKontaktOrThrow(ctx.tenantId, kontaktId, ctx);
|
||||
},
|
||||
});
|
||||
return Response.json({ ok: true, messageKey: "customerPortal.invitation.sent" });
|
||||
}
|
||||
|
||||
// Keep every detail action behind the canonical CRM object-visibility scope.
|
||||
const kontakt: KontaktRow = await getVisibleKontaktOrThrow(ctx.tenantId, kontaktId, ctx);
|
||||
|
||||
// Type is needed by almost every remaining branch (activity subject).
|
||||
const typ = kontakt.kontaktTyp;
|
||||
|
||||
if (intent === "startTelephonyCall") {
|
||||
await validateCSRFToken(args.request, { formData: form });
|
||||
const telephonyCtx = await loadTelephonyContext({ request: args.request, params: args.params, requireModule: true });
|
||||
await startTelephonyEntityCall(telephonyCtx, {
|
||||
entityType: "contact",
|
||||
entityId: kontaktId,
|
||||
numberId: field(form, "numberId"),
|
||||
destination: field(form, "destination"),
|
||||
});
|
||||
return Response.json({ ok: true, messageKey: "crm.toast.callStarted" });
|
||||
}
|
||||
|
||||
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);
|
||||
return redirect(`${listHref}?toast=${encodeURIComponent("crm.toast.contactDeleted")}`);
|
||||
}
|
||||
|
||||
requireCrmPermission(ctx, "crm.write");
|
||||
@@ -252,55 +315,67 @@ export async function handleKontaktDetailAction(args: {
|
||||
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" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "crm.activitySummary.basicsUpdated" });
|
||||
// The detail screen's single "Speichern" also carries the owner change,
|
||||
// but only sends `zustaendigerUserId` when it actually differs — so this
|
||||
// reassign runs at most once and never logs a spurious assignee change.
|
||||
if (form.has("zustaendigerUserId")) {
|
||||
const owner = optionalField(form, "zustaendigerUserId");
|
||||
if (owner) {
|
||||
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: "crm.activitySummary.assigneeChanged" });
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "addEmail": {
|
||||
await addKontaktEmail({ tenantId: ctx.tenantId, kontaktId, email: field(form, "email"), primaer: form.get("primaer") === "1" });
|
||||
await addKontaktEmail({ tenantId: ctx.tenantId, kontaktId, ctx, 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" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "crm.activitySummary.emailAdded" });
|
||||
break;
|
||||
}
|
||||
case "setPrimaryEmail": {
|
||||
await setPrimaryEmail({ tenantId: ctx.tenantId, emailId: field(form, "emailId") });
|
||||
await setPrimaryEmail({ tenantId: ctx.tenantId, kontaktId, ctx, 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 removeKontaktEmail({ tenantId: ctx.tenantId, kontaktId, ctx, 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 addKontaktTelefon({ tenantId: ctx.tenantId, kontaktId, ctx, 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" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "crm.activitySummary.phoneAdded" });
|
||||
break;
|
||||
}
|
||||
case "setPrimaryTelefon": {
|
||||
await setPrimaryTelefon({ tenantId: ctx.tenantId, telefonId: field(form, "telefonId") });
|
||||
await setPrimaryTelefon({ tenantId: ctx.tenantId, kontaktId, ctx, 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 removeKontaktTelefon({ tenantId: ctx.tenantId, kontaktId, ctx, 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,
|
||||
kontaktId,
|
||||
ctx,
|
||||
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" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "crm.activitySummary.relationAdded" });
|
||||
break;
|
||||
}
|
||||
case "removeRelation": {
|
||||
await removeKontaktRelation({ tenantId: ctx.tenantId, relationId: field(form, "relationId") });
|
||||
await removeKontaktRelation({ tenantId: ctx.tenantId, kontaktId, ctx, relationId: field(form, "relationId") });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.relation_removed", targetType: "kontakt", targetId: kontaktId });
|
||||
break;
|
||||
}
|
||||
@@ -311,27 +386,39 @@ export async function handleKontaktDetailAction(args: {
|
||||
}
|
||||
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" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "assignee_changed", summaryText: "crm.activitySummary.assigneeChanged" });
|
||||
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" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "tag_added", summaryText: "crm.activitySummary.tagAssigned" });
|
||||
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" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "tag_removed", summaryText: "crm.activitySummary.tagRemoved" });
|
||||
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") } });
|
||||
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": {
|
||||
@@ -346,24 +433,47 @@ export async function handleKontaktDetailAction(args: {
|
||||
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" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_archived", summaryText: "crm.activitySummary.contactArchived" });
|
||||
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" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "crm.activitySummary.contactReactivated" });
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw badRequestResponse();
|
||||
}
|
||||
|
||||
return redirect(detailHref);
|
||||
const messageKeyByIntent: Record<string, string> = {
|
||||
updateBasics: "crm.toast.contactSaved",
|
||||
addEmail: "crm.toast.emailAdded",
|
||||
setPrimaryEmail: "crm.toast.primaryEmailSet",
|
||||
removeEmail: "crm.toast.emailRemoved",
|
||||
addTelefon: "crm.toast.phoneAdded",
|
||||
setPrimaryTelefon: "crm.toast.primaryPhoneSet",
|
||||
removeTelefon: "crm.toast.phoneRemoved",
|
||||
addRelation: "crm.toast.relationAdded",
|
||||
removeRelation: "crm.toast.relationRemoved",
|
||||
reassign: "crm.toast.contactReassigned",
|
||||
addTag: "crm.toast.tagAssigned",
|
||||
removeTag: "crm.toast.tagRemoved",
|
||||
setCustomField: "crm.toast.customFieldSaved",
|
||||
addNote: "crm.toast.noteAdded",
|
||||
archive: "crm.toast.contactArchived",
|
||||
reactivate: "crm.toast.contactReactivated",
|
||||
};
|
||||
return redirect(`${detailHref}?toast=${encodeURIComponent(messageKeyByIntent[intent ?? ""] ?? "crm.toast.contactSaved")}`);
|
||||
} catch (error) {
|
||||
if (error instanceof Response) {
|
||||
throw error;
|
||||
}
|
||||
if (error instanceof TelephonyServiceError) {
|
||||
return Response.json({ error: error.messageKey }, { status: 400 });
|
||||
}
|
||||
const portalInvitationError = portalInvitationActionErrorResponse(error);
|
||||
if (portalInvitationError) return portalInvitationError;
|
||||
return crmActionErrorResponse(error);
|
||||
}
|
||||
}
|
||||
+104
-33
@@ -21,15 +21,28 @@ import {
|
||||
bulkReassignKontakte,
|
||||
getVisibleKontaktOrThrow,
|
||||
listAssignableUsers,
|
||||
listVisibleKontakteByIds,
|
||||
listKontakteForBrowser,
|
||||
normalizeBulkKontaktIds,
|
||||
reactivateKontakt,
|
||||
resolveUserLabels,
|
||||
type KontaktRow,
|
||||
} from "./crmService.server";
|
||||
import { assignTag, listTags, listTagsForEntity } from "./tagService.server";
|
||||
import { assignTag, listTags, listTagsForEntities, unassignTag } 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";
|
||||
import { isDemoDataUiEnabled } from "~/utils/services/.server/demoDataUi.server";
|
||||
import {
|
||||
companiesPath,
|
||||
companyDetailPath,
|
||||
contactDetailPath,
|
||||
contactNewPath,
|
||||
contactsExportPath,
|
||||
contactsPath,
|
||||
customFieldsAdminPath,
|
||||
duplicatesAdminPath,
|
||||
tagsAdminPath,
|
||||
} from "./crmRoutePaths";
|
||||
|
||||
// The canonical TagAssignment.entityType for a Kontakt (mirrors crmService).
|
||||
const KONTAKT_TAG_ENTITY_TYPE = "kontakt";
|
||||
@@ -49,7 +62,18 @@ export type KontaktListLoaderData = {
|
||||
query: KontaktListQuery;
|
||||
baseHref: string;
|
||||
newHref: string;
|
||||
/** Current user — pre-selected owner in the "Neuer Kontakt" dialog. */
|
||||
defaultOwnerId: string;
|
||||
exportHref: string;
|
||||
/** Top-level perms so the header CTA + admin nav work even on an empty list
|
||||
* (the VM is `empty` for 0 rows, so its data-derived perms are null then). */
|
||||
canWrite: boolean;
|
||||
canAdmin: boolean;
|
||||
contactsHref: string;
|
||||
companiesHref: string;
|
||||
customFieldsHref: string;
|
||||
tagsHref: string;
|
||||
duplicatesHref: string;
|
||||
};
|
||||
|
||||
function variantQuery(variant: KontaktListVariant, query: KontaktListQuery): KontaktListQuery {
|
||||
@@ -71,7 +95,12 @@ export async function loadKontaktListData(args: {
|
||||
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 parsed = variantQuery(args.variant, parseKontaktListQuery(url.searchParams));
|
||||
// Outside staging/dev the `demo=show` query param is ignored server-side
|
||||
// (demo data is a staging/dev-only affordance).
|
||||
const query = isDemoDataUiEnabled(undefined, { tenantId: ctx.tenantId, tenantSlug })
|
||||
? parsed
|
||||
: { ...parsed, filter: { ...parsed.filter, includeDemoData: false } };
|
||||
|
||||
const base: Omit<KontaktListLoaderData, "vm" | "tagOptions" | "ownerOptions"> = {
|
||||
title: `${t(titleKey)} | ${process.env.APP_NAME}`,
|
||||
@@ -80,7 +109,15 @@ export async function loadKontaktListData(args: {
|
||||
query,
|
||||
baseHref,
|
||||
newHref: contactNewPath(tenantSlug),
|
||||
defaultOwnerId: ctx.userId,
|
||||
exportHref: `${contactsExportPath(tenantSlug)}?${kontaktListQueryToParams(query).toString()}`,
|
||||
canWrite: ctx.permissions.includes("crm.write"),
|
||||
canAdmin: ctx.permissions.includes("crm.admin"),
|
||||
contactsHref: contactsPath(tenantSlug),
|
||||
companiesHref: companiesPath(tenantSlug),
|
||||
customFieldsHref: customFieldsAdminPath(tenantSlug),
|
||||
tagsHref: tagsAdminPath(tenantSlug),
|
||||
duplicatesHref: duplicatesAdminPath(tenantSlug),
|
||||
};
|
||||
|
||||
if (!ctx.hasModule) {
|
||||
@@ -106,15 +143,16 @@ export async function loadKontaktListData(args: {
|
||||
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 tagRowsByKontakt = await listTagsForEntities({
|
||||
tenantId: ctx.tenantId,
|
||||
entityType: KONTAKT_TAG_ENTITY_TYPE,
|
||||
entityIds: rows.map((row) => row.id),
|
||||
});
|
||||
const tagsByKontakt = new Map<string, KontaktTagOption[]>(
|
||||
[...tagRowsByKontakt].map(([entityId, tags]) => [
|
||||
entityId,
|
||||
tags.map((tag) => ({ id: tag.id, name: tag.name, farbe: tag.farbe })),
|
||||
]),
|
||||
);
|
||||
|
||||
const detailHrefFor = (row: { id: string }) =>
|
||||
@@ -166,21 +204,18 @@ function emptyVmInput(tenantSlug: string) {
|
||||
}
|
||||
|
||||
function parseIds(form: FormData): string[] {
|
||||
return [...new Set(form.getAll("kontaktId").map((v) => v.toString().trim()).filter(Boolean))];
|
||||
return normalizeBulkKontaktIds(form.getAll("kontaktId").map((value) => value.toString()));
|
||||
}
|
||||
|
||||
/** 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;
|
||||
async function visibleTargets(
|
||||
tenantId: string,
|
||||
ctx: Parameters<typeof getVisibleKontaktOrThrow>[2],
|
||||
ids: string[],
|
||||
options?: { includeArchived?: boolean },
|
||||
): Promise<KontaktRow[]> {
|
||||
return listVisibleKontakteByIds({ tenantId, ctx, kontaktIds: ids, includeArchived: options?.includeArchived });
|
||||
}
|
||||
|
||||
export async function handleKontaktListAction(args: {
|
||||
@@ -192,7 +227,8 @@ export async function handleKontaktListAction(args: {
|
||||
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));
|
||||
const baseHref = args.variant === "companies" ? companiesPath(tenantSlug) : contactsPath(tenantSlug);
|
||||
const redirectBack = (messageKey: string) => redirect(`${baseHref}?toast=${encodeURIComponent(messageKey)}`);
|
||||
|
||||
try {
|
||||
if (intent === "archive" || intent === "reactivate") {
|
||||
@@ -205,13 +241,13 @@ export async function handleKontaktListAction(args: {
|
||||
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" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: kontakt.kontaktTyp, activityType: "contact_archived", summaryText: "crm.activitySummary.contactArchived" });
|
||||
} 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" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: kontakt.kontaktTyp, activityType: "contact_updated", summaryText: "crm.activitySummary.contactReactivated" });
|
||||
}
|
||||
return redirectBack;
|
||||
return redirectBack(intent === "archive" ? "crm.toast.contactArchived" : "crm.toast.contactReactivated");
|
||||
}
|
||||
|
||||
if (intent === "bulkArchive") {
|
||||
@@ -222,10 +258,24 @@ export async function handleKontaktListAction(args: {
|
||||
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)" });
|
||||
await logKontaktActivity({ ctx, kontaktId: target.id, kontaktTyp: target.kontaktTyp, activityType: "contact_archived", summaryText: "crm.activitySummary.bulkContactArchived" });
|
||||
}
|
||||
}
|
||||
return redirectBack;
|
||||
return redirectBack("crm.toast.contactsArchived");
|
||||
}
|
||||
|
||||
if (intent === "bulkReactivate") {
|
||||
requireCrmPermission(ctx, "crm.write");
|
||||
// Archived rows are the whole point here, so opt into them explicitly.
|
||||
const targets = await visibleTargets(ctx.tenantId, ctx, parseIds(form), { includeArchived: true });
|
||||
// No bulk helper exists for reactivation — mirror the single-contact path
|
||||
// per target so audit + activity stay consistent with a manual un-archive.
|
||||
for (const target of targets) {
|
||||
await reactivateKontakt({ tenantId: ctx.tenantId, kontaktId: target.id });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.reactivated", targetType: "kontakt", targetId: target.id, metadata: { bulk: true } });
|
||||
await logKontaktActivity({ ctx, kontaktId: target.id, kontaktTyp: target.kontaktTyp, activityType: "contact_updated", summaryText: "crm.activitySummary.bulkContactReactivated" });
|
||||
}
|
||||
return redirectBack("crm.toast.contactsReactivated");
|
||||
}
|
||||
|
||||
if (intent === "bulkReassign") {
|
||||
@@ -240,10 +290,10 @@ export async function handleKontaktListAction(args: {
|
||||
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)" });
|
||||
await logKontaktActivity({ ctx, kontaktId: target.id, kontaktTyp: target.kontaktTyp, activityType: "assignee_changed", summaryText: "crm.activitySummary.bulkAssigneeChanged" });
|
||||
}
|
||||
}
|
||||
return redirectBack;
|
||||
return redirectBack("crm.toast.contactsReassigned");
|
||||
}
|
||||
|
||||
if (intent === "bulkTag") {
|
||||
@@ -256,9 +306,30 @@ export async function handleKontaktListAction(args: {
|
||||
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)" });
|
||||
await logKontaktActivity({ ctx, kontaktId: target.id, kontaktTyp: target.kontaktTyp, activityType: "tag_added", summaryText: "crm.activitySummary.bulkTagAssigned" });
|
||||
}
|
||||
return redirectBack;
|
||||
return redirectBack("crm.toast.contactsTagged");
|
||||
}
|
||||
|
||||
if (intent === "assignTag" || intent === "removeTag") {
|
||||
requireCrmPermission(ctx, "crm.write");
|
||||
const kontaktId = form.get("kontaktId")?.toString().trim();
|
||||
const tagId = form.get("tagId")?.toString().trim();
|
||||
if (!kontaktId || !tagId) {
|
||||
throw badRequestResponse();
|
||||
}
|
||||
// Owner visibility is enforced per contact (404 for a hidden one).
|
||||
const kontakt = await getVisibleKontaktOrThrow(ctx.tenantId, kontaktId, ctx);
|
||||
if (intent === "assignTag") {
|
||||
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: kontakt.kontaktTyp, activityType: "tag_added", summaryText: "crm.activitySummary.tagAssigned" });
|
||||
} else {
|
||||
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: kontakt.kontaktTyp, activityType: "tag_removed", summaryText: "crm.activitySummary.tagRemoved" });
|
||||
}
|
||||
return redirectBack(intent === "assignTag" ? "crm.toast.tagAssigned" : "crm.toast.tagRemoved");
|
||||
}
|
||||
|
||||
throw badRequestResponse();
|
||||
|
||||
+325
@@ -0,0 +1,325 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tx: {
|
||||
tenantUser: { findFirst: vi.fn() },
|
||||
kontakt: { findFirst: vi.fn(), findMany: vi.fn(), update: vi.fn(), updateMany: vi.fn() },
|
||||
kontaktEmail: { findFirst: vi.fn(), findMany: vi.fn(), updateMany: vi.fn(), deleteMany: vi.fn() },
|
||||
kontaktTelefon: { findFirst: vi.fn(), findMany: vi.fn(), updateMany: vi.fn(), deleteMany: vi.fn() },
|
||||
kontaktRelation: { findFirst: vi.fn(), findMany: vi.fn(), create: vi.fn(), deleteMany: vi.fn() },
|
||||
adresse: { findFirst: vi.fn() },
|
||||
},
|
||||
publishKontaktSearchUpsert: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: async (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
|
||||
}));
|
||||
vi.mock("~/utils/db.server", () => ({ db: {} }));
|
||||
vi.mock("~/services/search/searchIndexProjection.server", () => ({
|
||||
publishKontaktSearchUpsert: mocks.publishKontaktSearchUpsert,
|
||||
publishSearchProjectionDelete: vi.fn(),
|
||||
}));
|
||||
|
||||
import {
|
||||
addKontaktRelation,
|
||||
bulkReassignKontakte,
|
||||
CRM_BULK_MAX_CONTACTS,
|
||||
getKontaktDetail,
|
||||
getVisibleKontaktOrThrow,
|
||||
listRelationsForKontakt,
|
||||
listVisibleKontakteByIds,
|
||||
normalizeBulkKontaktIds,
|
||||
reassignKontakt,
|
||||
removeKontaktEmail,
|
||||
removeKontaktRelation,
|
||||
removeKontaktTelefon,
|
||||
setPrimaryEmail,
|
||||
setPrimaryTelefon,
|
||||
} from "./crmService.server";
|
||||
|
||||
describe("CRM assignee tenant boundary", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.tx.kontakt.findFirst.mockResolvedValue({ id: "contact-a" });
|
||||
mocks.tx.kontakt.findMany.mockResolvedValue([]);
|
||||
mocks.tx.kontakt.update.mockResolvedValue({ id: "contact-a" });
|
||||
mocks.tx.kontakt.updateMany.mockResolvedValue({ count: 1 });
|
||||
mocks.tx.kontaktEmail.findMany.mockResolvedValue([]);
|
||||
mocks.tx.kontaktTelefon.findMany.mockResolvedValue([]);
|
||||
mocks.tx.kontaktRelation.findMany.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("deduplicates bulk IDs and rejects payloads above the hard cap", () => {
|
||||
expect(normalizeBulkKontaktIds([" contact-a ", "contact-a", "", "contact-b"])).toEqual(["contact-a", "contact-b"]);
|
||||
expect(() => normalizeBulkKontaktIds(Array.from({ length: CRM_BULK_MAX_CONTACTS + 1 }, (_, index) => `contact-${index}`))).toThrow(
|
||||
"foundation.mass_action_exceeds_limit"
|
||||
);
|
||||
});
|
||||
|
||||
it("batch-loads visible contacts once and preserves the requested order", async () => {
|
||||
mocks.tx.kontakt.findMany.mockResolvedValue([
|
||||
{ id: "contact-b", tenantId: "tenant-a" },
|
||||
{ id: "contact-a", tenantId: "tenant-a" },
|
||||
]);
|
||||
|
||||
await expect(
|
||||
listVisibleKontakteByIds({
|
||||
tenantId: "tenant-a",
|
||||
ctx: { userId: "actor-a", permissions: ["crm.read_all"] },
|
||||
kontaktIds: ["contact-a", "contact-b", "contact-a"],
|
||||
})
|
||||
).resolves.toEqual([
|
||||
{ id: "contact-a", tenantId: "tenant-a" },
|
||||
{ id: "contact-b", tenantId: "tenant-a" },
|
||||
]);
|
||||
|
||||
expect(mocks.tx.kontakt.findMany).toHaveBeenCalledOnce();
|
||||
expect(mocks.tx.kontakt.findMany).toHaveBeenCalledWith({
|
||||
where: { id: { in: ["contact-a", "contact-b"] }, tenantId: "tenant-a", archivedAt: null },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a foreign or inactive assignee before changing a contact", async () => {
|
||||
mocks.tx.tenantUser.findFirst.mockResolvedValue(null);
|
||||
|
||||
await expect(reassignKontakt({ tenantId: "tenant-a", kontaktId: "contact-a", zustaendigerUserId: "foreign-user" })).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.tenantUser.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
tenantId: "tenant-a",
|
||||
userId: "foreign-user",
|
||||
status: TenantUserStatus.ACTIVE,
|
||||
user: { active: true },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.tx.kontakt.findFirst).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.kontakt.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("applies the same active tenant membership check to bulk reassignment", async () => {
|
||||
mocks.tx.tenantUser.findFirst.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
bulkReassignKontakte({
|
||||
tenantId: "tenant-a",
|
||||
ctx: { userId: "actor-a", permissions: ["crm.read_all"] },
|
||||
kontaktIds: ["contact-a"],
|
||||
zustaendigerUserId: "foreign-user",
|
||||
})
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.kontakt.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not let a creator retain crm.read_own visibility after reassignment", async () => {
|
||||
const reassignedContact = {
|
||||
id: "contact-b",
|
||||
tenantId: "tenant-a",
|
||||
createdByUserId: "actor-a",
|
||||
zustaendigerUserId: "actor-b",
|
||||
};
|
||||
mocks.tx.kontakt.findFirst.mockImplementation(async (args: { where?: { id?: string; tenantId?: string; zustaendigerUserId?: string } }) =>
|
||||
args.where?.id === reassignedContact.id &&
|
||||
args.where?.tenantId === reassignedContact.tenantId &&
|
||||
args.where?.zustaendigerUserId === reassignedContact.zustaendigerUserId
|
||||
? reassignedContact
|
||||
: null
|
||||
);
|
||||
|
||||
await expect(
|
||||
getVisibleKontaktOrThrow("tenant-a", "contact-b", {
|
||||
userId: "actor-a",
|
||||
permissions: ["crm.read_own"],
|
||||
})
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.kontakt.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: "contact-b",
|
||||
tenantId: "tenant-a",
|
||||
zustaendigerUserId: "actor-a",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("filters detail relations when the other contact is outside crm.read_own", async () => {
|
||||
mocks.tx.kontakt.findFirst.mockResolvedValue({
|
||||
id: "contact-a",
|
||||
tenantId: "tenant-a",
|
||||
adresseId: null,
|
||||
zustaendigerUserId: "actor-a",
|
||||
});
|
||||
mocks.tx.kontaktRelation.findMany.mockResolvedValue([
|
||||
{ id: "relation-a-b", vonKontaktId: "contact-a", zuKontaktId: "contact-b" },
|
||||
{ id: "relation-c-a", vonKontaktId: "contact-c", zuKontaktId: "contact-a" },
|
||||
]);
|
||||
mocks.tx.kontakt.findMany.mockResolvedValue([{ id: "contact-b" }]);
|
||||
|
||||
const detail = await getKontaktDetail("tenant-a", "contact-a", {
|
||||
userId: "actor-a",
|
||||
permissions: ["crm.read_own"],
|
||||
});
|
||||
|
||||
expect(detail.relationen).toEqual([{ id: "relation-a-b", vonKontaktId: "contact-a", zuKontaktId: "contact-b" }]);
|
||||
expect(mocks.tx.kontakt.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: { in: ["contact-b", "contact-c"] },
|
||||
tenantId: "tenant-a",
|
||||
zustaendigerUserId: "actor-a",
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("requires context and filters both relation directions in the direct relation API", async () => {
|
||||
mocks.tx.kontaktRelation.findMany.mockResolvedValue([
|
||||
{ id: "relation-a-b", vonKontaktId: "contact-a", zuKontaktId: "contact-b" },
|
||||
{ id: "relation-c-a", vonKontaktId: "contact-c", zuKontaktId: "contact-a" },
|
||||
]);
|
||||
mocks.tx.kontakt.findMany.mockResolvedValue([{ id: "contact-c" }]);
|
||||
|
||||
await expect(
|
||||
listRelationsForKontakt("tenant-a", "contact-a", {
|
||||
userId: "actor-a",
|
||||
permissions: ["crm.read_own"],
|
||||
})
|
||||
).resolves.toEqual([{ id: "relation-c-a", vonKontaktId: "contact-c", zuKontaktId: "contact-a" }]);
|
||||
|
||||
expect(mocks.tx.kontakt.findFirst).toHaveBeenCalledWith({
|
||||
where: { id: "contact-a", tenantId: "tenant-a", zustaendigerUserId: "actor-a" },
|
||||
});
|
||||
expect(mocks.tx.kontakt.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: { in: ["contact-b", "contact-c"] },
|
||||
tenantId: "tenant-a",
|
||||
zustaendigerUserId: "actor-a",
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("returns 404 before listing relations when the requested contact is outside the caller scope", async () => {
|
||||
mocks.tx.kontakt.findFirst.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
listRelationsForKontakt("tenant-a", "contact-from-tenant-b", {
|
||||
userId: "actor-a",
|
||||
permissions: ["crm.read_own"],
|
||||
})
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.kontaktRelation.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects email IDs from another contact before changing or deleting them", async () => {
|
||||
mocks.tx.kontaktEmail.findFirst.mockResolvedValue(null);
|
||||
const input = {
|
||||
tenantId: "tenant-a",
|
||||
kontaktId: "contact-a",
|
||||
ctx: { userId: "actor-a", permissions: ["crm.read_own"] },
|
||||
emailId: "email-from-contact-b",
|
||||
};
|
||||
|
||||
await expect(setPrimaryEmail(input)).rejects.toMatchObject({ status: 404 });
|
||||
await expect(removeKontaktEmail(input)).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
const scopedLookup = {
|
||||
where: {
|
||||
id: "email-from-contact-b",
|
||||
tenantId: "tenant-a",
|
||||
kontaktId: "contact-a",
|
||||
},
|
||||
select: { id: true, kontaktId: true },
|
||||
};
|
||||
expect(mocks.tx.kontaktEmail.findFirst).toHaveBeenNthCalledWith(1, scopedLookup);
|
||||
expect(mocks.tx.kontaktEmail.findFirst).toHaveBeenNthCalledWith(2, scopedLookup);
|
||||
expect(mocks.tx.kontaktEmail.updateMany).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.kontaktEmail.deleteMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects telephone IDs from another contact before changing or deleting them", async () => {
|
||||
mocks.tx.kontaktTelefon.findFirst.mockResolvedValue(null);
|
||||
const input = {
|
||||
tenantId: "tenant-a",
|
||||
kontaktId: "contact-a",
|
||||
ctx: { userId: "actor-a", permissions: ["crm.read_own"] },
|
||||
telefonId: "telephone-from-contact-b",
|
||||
};
|
||||
|
||||
await expect(setPrimaryTelefon(input)).rejects.toMatchObject({ status: 404 });
|
||||
await expect(removeKontaktTelefon(input)).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
const scopedLookup = {
|
||||
where: {
|
||||
id: "telephone-from-contact-b",
|
||||
tenantId: "tenant-a",
|
||||
kontaktId: "contact-a",
|
||||
},
|
||||
select: { id: true, kontaktId: true },
|
||||
};
|
||||
expect(mocks.tx.kontaktTelefon.findFirst).toHaveBeenNthCalledWith(1, scopedLookup);
|
||||
expect(mocks.tx.kontaktTelefon.findFirst).toHaveBeenNthCalledWith(2, scopedLookup);
|
||||
expect(mocks.tx.kontaktTelefon.updateMany).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.kontaktTelefon.deleteMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects adding a relation when the target contact is not visible", async () => {
|
||||
mocks.tx.kontakt.findFirst.mockImplementation(async (args: { where?: { id?: string; tenantId?: string; zustaendigerUserId?: string } }) =>
|
||||
args.where?.id === "contact-a" && args.where?.tenantId === "tenant-a" && args.where?.zustaendigerUserId === "actor-a" ? { id: "contact-a" } : null
|
||||
);
|
||||
|
||||
await expect(
|
||||
addKontaktRelation({
|
||||
tenantId: "tenant-a",
|
||||
kontaktId: "contact-a",
|
||||
ctx: { userId: "actor-a", permissions: ["crm.read_own"] },
|
||||
zuKontaktId: "contact-b",
|
||||
rolle: "hauptkontakt",
|
||||
})
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.kontakt.findFirst).toHaveBeenNthCalledWith(1, {
|
||||
where: { id: "contact-a", tenantId: "tenant-a", zustaendigerUserId: "actor-a" },
|
||||
});
|
||||
expect(mocks.tx.kontakt.findFirst).toHaveBeenNthCalledWith(2, {
|
||||
where: { id: "contact-b", tenantId: "tenant-a", zustaendigerUserId: "actor-a" },
|
||||
});
|
||||
expect(mocks.tx.kontaktRelation.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects removing a URL-contact relation when its other endpoint is not visible", async () => {
|
||||
mocks.tx.kontakt.findFirst.mockImplementation(async (args: { where?: { id?: string; tenantId?: string; zustaendigerUserId?: string } }) =>
|
||||
args.where?.id === "contact-a" && args.where?.tenantId === "tenant-a" && args.where?.zustaendigerUserId === "actor-a" ? { id: "contact-a" } : null
|
||||
);
|
||||
mocks.tx.kontaktRelation.findFirst.mockResolvedValue({
|
||||
id: "relation-a-b",
|
||||
vonKontaktId: "contact-a",
|
||||
zuKontaktId: "contact-b",
|
||||
});
|
||||
|
||||
await expect(
|
||||
removeKontaktRelation({
|
||||
tenantId: "tenant-a",
|
||||
kontaktId: "contact-a",
|
||||
ctx: { userId: "actor-a", permissions: ["crm.read_own"] },
|
||||
relationId: "relation-a-b",
|
||||
})
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.kontaktRelation.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: "relation-a-b",
|
||||
tenantId: "tenant-a",
|
||||
OR: [{ vonKontaktId: "contact-a" }, { zuKontaktId: "contact-a" }],
|
||||
},
|
||||
select: { id: true, vonKontaktId: true, zuKontaktId: true },
|
||||
});
|
||||
expect(mocks.tx.kontakt.findFirst).toHaveBeenLastCalledWith({
|
||||
where: { id: "contact-b", tenantId: "tenant-a", zustaendigerUserId: "actor-a" },
|
||||
});
|
||||
expect(mocks.tx.kontaktRelation.deleteMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+257
-76
@@ -14,8 +14,11 @@
|
||||
// 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 { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
|
||||
import { CatalogError, foundationErrors, massActionErrors } from "@hivegrid/foundation";
|
||||
import { buildWorkflowTriggerOutboxEvent } from "@hivegrid/queue";
|
||||
import { crmContactsIndex } from "@hivegrid/search";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
import { publishKontaktSearchUpsert, publishSearchProjectionDelete } from "~/services/search/searchIndexProjection.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
@@ -64,6 +67,16 @@ export function ownerScopeWhere(ctx: CrmVisibilityContext): { zustaendigerUserId
|
||||
return canReadAllKontakte(ctx) ? {} : { zustaendigerUserId: ctx.userId };
|
||||
}
|
||||
|
||||
async function requireActiveTenantUserWithTx(tx: TenantRlsClient, tenantId: string, userId: string): Promise<void> {
|
||||
const membership = await tx.tenantUser.findFirst({
|
||||
where: { tenantId, userId, status: TenantUserStatus.ACTIVE, user: { active: true } },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!membership) {
|
||||
throw new CatalogError(foundationErrors.notFound, { userId });
|
||||
}
|
||||
}
|
||||
|
||||
// --- Row types (returned to routes; relation fields excluded) --------------
|
||||
|
||||
export type KontaktRow = {
|
||||
@@ -142,7 +155,9 @@ export type AdresseInput = {
|
||||
* 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[]): {
|
||||
function pickPrimary<T extends { value: string; primaer?: boolean }>(
|
||||
items: readonly T[]
|
||||
): {
|
||||
primaryValue: string | null;
|
||||
flags: boolean[];
|
||||
} {
|
||||
@@ -243,6 +258,39 @@ function hasAddressData(adresse?: AdresseInput | null): boolean {
|
||||
return Boolean(adresse.strasse?.trim() || adresse.hausnummer?.trim() || adresse.plz?.trim() || adresse.ort?.trim() || adresse.land?.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* R-P12c: kontakt domain events feed the generic automation trigger bus via
|
||||
* the durable workflow-trigger outbox (same delivery as lead/project events).
|
||||
* Published inside the mutation transaction so event and write commit together.
|
||||
*/
|
||||
async function publishKontaktWorkflowEvent(
|
||||
tx: TenantRlsClient,
|
||||
input: {
|
||||
tenantId: string;
|
||||
userId: string | null;
|
||||
event: "kontakt.created" | "kontakt.updated";
|
||||
kontakt: { id: string; kontaktTyp: string; kontaktStatus: string; updatedAt?: Date };
|
||||
changedFields?: readonly string[];
|
||||
}
|
||||
): Promise<void> {
|
||||
const suffix = input.event === "kontakt.updated" ? `:${input.kontakt.updatedAt?.getTime() ?? Date.now()}` : "";
|
||||
await publishOutboxEvent(
|
||||
tx as unknown as OutboxPublisherTransaction,
|
||||
buildWorkflowTriggerOutboxEvent({
|
||||
tenantId: input.tenantId,
|
||||
event: input.event,
|
||||
data: {
|
||||
kontaktId: input.kontakt.id,
|
||||
kontaktTyp: input.kontakt.kontaktTyp,
|
||||
kontaktStatus: input.kontakt.kontaktStatus,
|
||||
...(input.changedFields ? { changedFields: [...input.changedFields] } : {}),
|
||||
},
|
||||
userId: input.userId,
|
||||
sourceId: `kontakt:${input.kontakt.id}:${input.event}${suffix}`,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -251,6 +299,8 @@ export async function createKontakt(input: CreateKontaktInput): Promise<KontaktR
|
||||
const primaryTelefon = pickPrimary(telefonItems);
|
||||
|
||||
const kontakt = await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const responsibleUserId = input.zustaendigerUserId ?? input.userId;
|
||||
await requireActiveTenantUserWithTx(tx, input.tenantId, responsibleUserId);
|
||||
let adresseId: string | null = null;
|
||||
if (hasAddressData(input.adresse)) {
|
||||
const adresse = await tx.adresse.create({
|
||||
@@ -280,7 +330,7 @@ export async function createKontakt(input: CreateKontaktInput): Promise<KontaktR
|
||||
primaerEmail: primaryEmail.primaryValue,
|
||||
primaerTelefon: primaryTelefon.primaryValue,
|
||||
adresseId,
|
||||
zustaendigerUserId: input.zustaendigerUserId ?? input.userId,
|
||||
zustaendigerUserId: responsibleUserId,
|
||||
isDemoData: input.isDemoData ?? false,
|
||||
},
|
||||
});
|
||||
@@ -289,9 +339,17 @@ export async function createKontakt(input: CreateKontaktInput): Promise<KontaktR
|
||||
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 tx.kontaktTelefon.create({
|
||||
data: { tenantId: input.tenantId, kontaktId: created.id, telefon: telefonItems[i].value, primaer: primaryTelefon.flags[i] },
|
||||
});
|
||||
}
|
||||
await publishKontaktSearchUpsert(tx, created);
|
||||
await publishKontaktWorkflowEvent(tx, {
|
||||
tenantId: input.tenantId,
|
||||
userId: input.userId,
|
||||
event: "kontakt.created",
|
||||
kontakt: created,
|
||||
});
|
||||
return created;
|
||||
});
|
||||
return kontakt as KontaktRow;
|
||||
@@ -324,6 +382,16 @@ export async function updateKontakt(input: UpdateKontaktInput): Promise<void> {
|
||||
},
|
||||
});
|
||||
await publishKontaktSearchUpsert(tx, updated);
|
||||
const changedFields = (["kontaktStatus", "vorname", "nachname", "orgName", "orgMerkmal"] as const).filter(
|
||||
(field) => input[field] !== undefined
|
||||
);
|
||||
await publishKontaktWorkflowEvent(tx, {
|
||||
tenantId: input.tenantId,
|
||||
userId: null,
|
||||
event: "kontakt.updated",
|
||||
kontakt: updated,
|
||||
changedFields,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -374,6 +442,7 @@ export async function hardDeleteKontakt(input: { tenantId: string; kontaktId: st
|
||||
|
||||
export async function reassignKontakt(input: { tenantId: string; kontaktId: string; zustaendigerUserId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
await requireActiveTenantUserWithTx(tx, input.tenantId, input.zustaendigerUserId);
|
||||
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 });
|
||||
@@ -385,108 +454,124 @@ export async function reassignKontakt(input: { tenantId: string; kontaktId: stri
|
||||
|
||||
// --- Email channels --------------------------------------------------------
|
||||
|
||||
export async function addKontaktEmail(input: { tenantId: string; kontaktId: string; email: string; primaer?: boolean }): Promise<KontaktEmailRow> {
|
||||
type KontaktScopedMutationInput = {
|
||||
tenantId: string;
|
||||
kontaktId: string;
|
||||
ctx: CrmVisibilityContext;
|
||||
};
|
||||
|
||||
export async function addKontaktEmail(input: KontaktScopedMutationInput & { 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 } });
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const created = await tx.kontaktEmail.create({ data: { tenantId: input.tenantId, kontaktId: kontakt.id, email, primaer: false } });
|
||||
await syncPrimaryEmailWithTx(tx, input.tenantId, kontakt.id, input.primaer ? created.id : undefined);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: kontakt.id, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
return created as KontaktEmailRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function setPrimaryEmail(input: { tenantId: string; emailId: string }): Promise<void> {
|
||||
export async function setPrimaryEmail(input: KontaktScopedMutationInput & { 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 } });
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const email = await tx.kontaktEmail.findFirst({
|
||||
where: { id: input.emailId, tenantId: input.tenantId, kontaktId: kontakt.id },
|
||||
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 } });
|
||||
await syncPrimaryEmailWithTx(tx, input.tenantId, kontakt.id, email.id);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: kontakt.id, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeKontaktEmail(input: { tenantId: string; emailId: string }): Promise<void> {
|
||||
export async function removeKontaktEmail(input: KontaktScopedMutationInput & { 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 } });
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const email = await tx.kontaktEmail.findFirst({
|
||||
where: { id: input.emailId, tenantId: input.tenantId, kontaktId: kontakt.id },
|
||||
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 } });
|
||||
await tx.kontaktEmail.deleteMany({ where: { id: email.id, tenantId: input.tenantId, kontaktId: kontakt.id } });
|
||||
await syncPrimaryEmailWithTx(tx, input.tenantId, kontakt.id);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: kontakt.id, 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> {
|
||||
export async function addKontaktTelefon(input: KontaktScopedMutationInput & { 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 } });
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const created = await tx.kontaktTelefon.create({ data: { tenantId: input.tenantId, kontaktId: kontakt.id, telefon, primaer: false } });
|
||||
await syncPrimaryTelefonWithTx(tx, input.tenantId, kontakt.id, input.primaer ? created.id : undefined);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: kontakt.id, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
return created as KontaktTelefonRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function setPrimaryTelefon(input: { tenantId: string; telefonId: string }): Promise<void> {
|
||||
export async function setPrimaryTelefon(input: KontaktScopedMutationInput & { 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 } });
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const telefon = await tx.kontaktTelefon.findFirst({
|
||||
where: { id: input.telefonId, tenantId: input.tenantId, kontaktId: kontakt.id },
|
||||
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 } });
|
||||
await syncPrimaryTelefonWithTx(tx, input.tenantId, kontakt.id, telefon.id);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: kontakt.id, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeKontaktTelefon(input: { tenantId: string; telefonId: string }): Promise<void> {
|
||||
export async function removeKontaktTelefon(input: KontaktScopedMutationInput & { 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 } });
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const telefon = await tx.kontaktTelefon.findFirst({
|
||||
where: { id: input.telefonId, tenantId: input.tenantId, kontaktId: kontakt.id },
|
||||
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 } });
|
||||
await tx.kontaktTelefon.deleteMany({ where: { id: telefon.id, tenantId: input.tenantId, kontaktId: kontakt.id } });
|
||||
await syncPrimaryTelefonWithTx(tx, input.tenantId, kontakt.id);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: kontakt.id, 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) {
|
||||
export async function addKontaktRelation(
|
||||
input: KontaktScopedMutationInput & { zuKontaktId: string; rolle: KontaktArt; kontext?: string | null }
|
||||
): Promise<KontaktRelationRow> {
|
||||
if (input.kontaktId === 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 });
|
||||
}
|
||||
const source = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const target = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.zuKontaktId, input.ctx);
|
||||
try {
|
||||
const created = await tx.kontaktRelation.create({
|
||||
data: { tenantId: input.tenantId, vonKontaktId: input.vonKontaktId, zuKontaktId: input.zuKontaktId, rolle: input.rolle, kontext: input.kontext ?? null },
|
||||
data: { tenantId: input.tenantId, vonKontaktId: source.id, zuKontaktId: target.id, rolle: input.rolle, kontext: input.kontext ?? null },
|
||||
});
|
||||
return created as KontaktRelationRow;
|
||||
} catch (error) {
|
||||
@@ -498,30 +583,37 @@ export async function addKontaktRelation(input: { tenantId: string; vonKontaktId
|
||||
});
|
||||
}
|
||||
|
||||
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[];
|
||||
export async function removeKontaktRelation(input: KontaktScopedMutationInput & { relationId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const relation = await tx.kontaktRelation.findFirst({
|
||||
where: {
|
||||
id: input.relationId,
|
||||
tenantId: input.tenantId,
|
||||
OR: [{ vonKontaktId: kontakt.id }, { zuKontaktId: kontakt.id }],
|
||||
},
|
||||
select: { id: true, vonKontaktId: true, zuKontaktId: true },
|
||||
});
|
||||
if (!relation) {
|
||||
throw new CatalogError(foundationErrors.notFound, { relationId: input.relationId });
|
||||
}
|
||||
const otherKontaktId = relation.vonKontaktId === kontakt.id ? relation.zuKontaktId : relation.vonKontaktId;
|
||||
await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, otherKontaktId, input.ctx);
|
||||
await tx.kontaktRelation.deleteMany({
|
||||
where: {
|
||||
id: relation.id,
|
||||
tenantId: input.tenantId,
|
||||
OR: [{ vonKontaktId: kontakt.id }, { zuKontaktId: kontakt.id }],
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// --- 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)) {
|
||||
const kontakt = await tx.kontakt.findFirst({ where: { id: kontaktId, tenantId, ...ownerScopeWhere(ctx) } });
|
||||
if (!kontakt) {
|
||||
throw new CatalogError(foundationErrors.notFound, { kontaktId });
|
||||
}
|
||||
return kontakt as KontaktRow;
|
||||
@@ -532,6 +624,35 @@ export async function getVisibleKontaktOrThrow(tenantId: string, kontaktId: stri
|
||||
return withTenantRLS(tenantId, (tx) => getVisibleKontaktOrThrowWithTx(tx, tenantId, kontaktId, ctx));
|
||||
}
|
||||
|
||||
async function listVisibleRelationsForKontaktWithTx(
|
||||
tx: TenantRlsClient,
|
||||
tenantId: string,
|
||||
kontaktId: string,
|
||||
ctx: CrmVisibilityContext
|
||||
): Promise<KontaktRelationRow[]> {
|
||||
const rows = await tx.kontaktRelation.findMany({
|
||||
where: { tenantId, OR: [{ vonKontaktId: kontaktId }, { zuKontaktId: kontaktId }] },
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
if (rows.length === 0) return [];
|
||||
|
||||
const otherKontaktIds = [...new Set(rows.map((row) => (row.vonKontaktId === kontaktId ? row.zuKontaktId : row.vonKontaktId)))];
|
||||
const visibleContacts = await tx.kontakt.findMany({
|
||||
where: { id: { in: otherKontaktIds }, tenantId, ...ownerScopeWhere(ctx) },
|
||||
select: { id: true },
|
||||
});
|
||||
const visibleIds = new Set(visibleContacts.map(({ id }) => id));
|
||||
return rows.filter((row) => visibleIds.has(row.vonKontaktId === kontaktId ? row.zuKontaktId : row.vonKontaktId)) as KontaktRelationRow[];
|
||||
}
|
||||
|
||||
/** All relations whose source and target contacts are visible to the caller. */
|
||||
export async function listRelationsForKontakt(tenantId: string, kontaktId: string, ctx: CrmVisibilityContext): Promise<KontaktRelationRow[]> {
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
await getVisibleKontaktOrThrowWithTx(tx, tenantId, kontaktId, ctx);
|
||||
return listVisibleRelationsForKontaktWithTx(tx, tenantId, kontaktId, ctx);
|
||||
});
|
||||
}
|
||||
|
||||
export type KontaktDetail = {
|
||||
kontakt: KontaktRow;
|
||||
emails: KontaktEmailRow[];
|
||||
@@ -547,7 +668,7 @@ export async function getKontaktDetail(tenantId: string, kontaktId: string, 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" } }),
|
||||
listVisibleRelationsForKontaktWithTx(tx, tenantId, kontaktId, ctx),
|
||||
kontakt.adresseId ? tx.adresse.findFirst({ where: { id: kontakt.adresseId, tenantId } }) : Promise.resolve(null),
|
||||
]);
|
||||
return {
|
||||
@@ -604,7 +725,7 @@ async function resolveKontaktBrowserWhereWithTx(
|
||||
tx: TenantRlsClient,
|
||||
tenantId: string,
|
||||
ctx: CrmVisibilityContext,
|
||||
filter: ListKontakteFilter,
|
||||
filter: ListKontakteFilter
|
||||
): Promise<{ where: Record<string, unknown>; empty: boolean }> {
|
||||
const search = filter.search?.trim();
|
||||
let tagScopedIds: string[] | undefined;
|
||||
@@ -681,7 +802,12 @@ export async function listKontakteForBrowser(input: {
|
||||
|
||||
/** 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[]> {
|
||||
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);
|
||||
@@ -719,7 +845,10 @@ export async function findDuplicateKontakte(input: DuplicateCheckInput): Promise
|
||||
|
||||
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 } } } });
|
||||
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 } } });
|
||||
@@ -750,26 +879,75 @@ export async function findDuplicateKontakte(input: DuplicateCheckInput): Promise
|
||||
|
||||
// --- Bulk actions (DoD 2) --------------------------------------------------
|
||||
|
||||
export const CRM_BULK_MAX_CONTACTS = 100;
|
||||
|
||||
export function normalizeBulkKontaktIds(kontaktIds: readonly string[]): string[] {
|
||||
if (kontaktIds.length > CRM_BULK_MAX_CONTACTS) {
|
||||
throw new CatalogError(massActionErrors.exceedsLimit, {
|
||||
affected: kontaktIds.length,
|
||||
hardLimit: CRM_BULK_MAX_CONTACTS,
|
||||
});
|
||||
}
|
||||
return [...new Set(kontaktIds.map((id) => id.trim()).filter(Boolean))];
|
||||
}
|
||||
|
||||
export async function listVisibleKontakteByIds(input: {
|
||||
tenantId: string;
|
||||
ctx: CrmVisibilityContext;
|
||||
kontaktIds: readonly string[];
|
||||
/** Archived contacts are excluded by default; set for the un-archive path. */
|
||||
includeArchived?: boolean;
|
||||
}): Promise<KontaktRow[]> {
|
||||
const kontaktIds = normalizeBulkKontaktIds(input.kontaktIds);
|
||||
if (kontaktIds.length === 0) return [];
|
||||
const rows = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.kontakt.findMany({
|
||||
where: {
|
||||
id: { in: kontaktIds },
|
||||
tenantId: input.tenantId,
|
||||
...(input.includeArchived ? {} : { archivedAt: null }),
|
||||
...ownerScopeWhere(input.ctx),
|
||||
},
|
||||
})
|
||||
);
|
||||
const rowById = new Map(rows.map((row) => [row.id, row as KontaktRow]));
|
||||
return kontaktIds.flatMap((id) => {
|
||||
const row = rowById.get(id);
|
||||
return row ? [row] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/** 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) {
|
||||
const kontaktIds = normalizeBulkKontaktIds(input.kontaktIds);
|
||||
if (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() } }),
|
||||
tx.kontakt.updateMany({ where: { id: { in: 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) {
|
||||
export async function bulkReassignKontakte(input: {
|
||||
tenantId: string;
|
||||
ctx: CrmVisibilityContext;
|
||||
kontaktIds: string[];
|
||||
zustaendigerUserId: string;
|
||||
}): Promise<{ affected: number }> {
|
||||
const kontaktIds = normalizeBulkKontaktIds(input.kontaktIds);
|
||||
if (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 } }),
|
||||
);
|
||||
const result = await withTenantRLS(input.tenantId, async (tx) => {
|
||||
await requireActiveTenantUserWithTx(tx, input.tenantId, input.zustaendigerUserId);
|
||||
return tx.kontakt.updateMany({
|
||||
where: { id: { in: kontaktIds }, tenantId: input.tenantId, ...ownerScopeWhere(input.ctx) },
|
||||
data: { zustaendigerUserId: input.zustaendigerUserId },
|
||||
});
|
||||
});
|
||||
return { affected: result.count };
|
||||
}
|
||||
|
||||
@@ -795,7 +973,10 @@ export async function resolveUserLabels(userIds: readonly string[]): Promise<Map
|
||||
/** 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 } } } }),
|
||||
tx.tenantUser.findMany({
|
||||
where: { tenantId, status: TenantUserStatus.ACTIVE, user: { active: true } },
|
||||
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) }));
|
||||
}
|
||||
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
// WF-P8 S05 field-type picker — the guard that keeps a retype from silently
|
||||
// reinterpreting stored values. Only the decision is under test here, so the
|
||||
// transaction client is a stub; the point is which calls the guard makes and
|
||||
// when it refuses.
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
withTenantRLS: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
count: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({ withTenantRLS: mocks.withTenantRLS }));
|
||||
|
||||
import { updateCustomFieldDefinition } from "./customFieldService.server";
|
||||
import { CrmServiceError } from "./crmService.server";
|
||||
|
||||
const tx = {
|
||||
customFieldDefinition: { findFirst: mocks.findFirst, updateMany: mocks.updateMany },
|
||||
customFieldValue: { count: mocks.count },
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.withTenantRLS.mockImplementation(async (_tenantId: string, callback: (client: unknown) => unknown) => callback(tx));
|
||||
mocks.findFirst.mockResolvedValue({ id: "def_1", datentyp: "datum" });
|
||||
mocks.count.mockResolvedValue(0);
|
||||
});
|
||||
|
||||
describe("updateCustomFieldDefinition retype guard", () => {
|
||||
it("refuses a retype once values are stored, instead of reinterpreting them", async () => {
|
||||
mocks.count.mockResolvedValue(3);
|
||||
|
||||
await expect(updateCustomFieldDefinition({ tenantId: "t1", definitionId: "def_1", datentyp: "zahl" })).rejects.toBeInstanceOf(CrmServiceError);
|
||||
expect(mocks.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("allows the retype while the field holds no values yet", async () => {
|
||||
await expect(updateCustomFieldDefinition({ tenantId: "t1", definitionId: "def_1", datentyp: "zahl" })).resolves.toBeUndefined();
|
||||
expect(mocks.updateMany).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ datentyp: "zahl" }) }));
|
||||
});
|
||||
|
||||
it("lets select and multiselect swap even with values, because both hold option values", async () => {
|
||||
mocks.findFirst.mockResolvedValue({ id: "def_1", datentyp: "select" });
|
||||
mocks.count.mockResolvedValue(7);
|
||||
|
||||
await expect(updateCustomFieldDefinition({ tenantId: "t1", definitionId: "def_1", datentyp: "multiselect" })).resolves.toBeUndefined();
|
||||
// The compatible pair must not even ask for the value count.
|
||||
expect(mocks.count).not.toHaveBeenCalled();
|
||||
expect(mocks.updateMany).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not count values when the submitted type equals the stored one", async () => {
|
||||
mocks.count.mockResolvedValue(9);
|
||||
|
||||
await updateCustomFieldDefinition({ tenantId: "t1", definitionId: "def_1", datentyp: "datum" });
|
||||
|
||||
expect(mocks.count).not.toHaveBeenCalled();
|
||||
expect(mocks.updateMany).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("writes options without touching the type guard", async () => {
|
||||
await updateCustomFieldDefinition({ tenantId: "t1", definitionId: "def_1", optionen: { options: [{ value: "a", label: "A", color: null }] } });
|
||||
|
||||
expect(mocks.count).not.toHaveBeenCalled();
|
||||
expect(mocks.updateMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ data: expect.objectContaining({ optionen: { options: [{ value: "a", label: "A", color: null }] } }) })
|
||||
);
|
||||
});
|
||||
});
|
||||
+60
-23
@@ -8,7 +8,7 @@
|
||||
|
||||
import { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import { CatalogError, foundationErrors, type JsonValue } from "@hivegrid/foundation";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
import { CrmServiceError } from "./crmService.server";
|
||||
|
||||
export type CustomFieldEntityType = "projekt" | "kontakt" | "lead" | "rechnung";
|
||||
@@ -24,7 +24,13 @@ export type CustomFieldDatentyp =
|
||||
| "boolean"
|
||||
| "email"
|
||||
| "telefon"
|
||||
| "datei";
|
||||
| "datei"
|
||||
// WF-P8 S05 additions; see the enum comment in crm.prisma.
|
||||
| "prozent"
|
||||
| "datum_zeit"
|
||||
| "person_team"
|
||||
| "adresse"
|
||||
| "link";
|
||||
|
||||
export type CustomFieldDefinitionRow = {
|
||||
id: string;
|
||||
@@ -100,18 +106,34 @@ export async function updateCustomFieldDefinition(input: {
|
||||
tenantId: string;
|
||||
definitionId: string;
|
||||
label?: string;
|
||||
datentyp?: CustomFieldDatentyp;
|
||||
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 } });
|
||||
const existing = await tx.customFieldDefinition.findFirst({
|
||||
where: { id: input.definitionId, tenantId: input.tenantId },
|
||||
select: { id: true, datentyp: true },
|
||||
});
|
||||
if (!existing) {
|
||||
throw new CatalogError(foundationErrors.notFound, { definitionId: input.definitionId });
|
||||
}
|
||||
// Retyping a field reinterprets every value already stored under it: a date
|
||||
// read as a number, a select value with no matching option. select <-> multiselect
|
||||
// is the exception, both hold option values, so the data keeps its meaning.
|
||||
if (input.datentyp !== undefined && input.datentyp !== existing.datentyp) {
|
||||
const optionTypes = new Set(["select", "multiselect"]);
|
||||
const staysCompatible = optionTypes.has(input.datentyp) && optionTypes.has(existing.datentyp);
|
||||
if (!staysCompatible) {
|
||||
const valueCount = await tx.customFieldValue.count({ where: { tenantId: input.tenantId, definitionId: input.definitionId } });
|
||||
if (valueCount > 0) throw new CrmServiceError("crm.error.customFieldTypeLocked");
|
||||
}
|
||||
}
|
||||
await tx.customFieldDefinition.updateMany({
|
||||
where: { id: input.definitionId, tenantId: input.tenantId },
|
||||
data: {
|
||||
...(input.label !== undefined ? { label: input.label.trim() } : {}),
|
||||
...(input.datentyp !== undefined ? { datentyp: input.datentyp } : {}),
|
||||
...(input.optionen !== undefined ? { optionen: toJsonInput(input.optionen) } : {}),
|
||||
...(input.archiviert !== undefined ? { archiviert: input.archiviert } : {}),
|
||||
},
|
||||
@@ -192,37 +214,52 @@ export type ShkCustomFieldTemplateEntry = {
|
||||
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.
|
||||
* Idempotently create the SHK template fields for a tenant. Tenant-created
|
||||
* defaults are normal rows; only an explicit demo seed may opt into demo rows.
|
||||
* 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 }> {
|
||||
export type SeedShkCustomFieldTemplateInput = { tenantId: string; isDemoData?: boolean };
|
||||
|
||||
export async function seedShkCustomFieldTemplateWithTx(
|
||||
tx: TenantRlsClient,
|
||||
input: SeedShkCustomFieldTemplateInput,
|
||||
): Promise<{ created: number }> {
|
||||
let created = 0;
|
||||
const isDemoData = input.isDemoData ?? false;
|
||||
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 } }),
|
||||
);
|
||||
const exists = await 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,
|
||||
},
|
||||
}),
|
||||
);
|
||||
await 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,
|
||||
},
|
||||
});
|
||||
created += 1;
|
||||
}
|
||||
return { created };
|
||||
}
|
||||
|
||||
export async function seedShkCustomFieldTemplate(input: SeedShkCustomFieldTemplateInput): Promise<{ created: number }> {
|
||||
// Avoid opening an RLS transaction while the versioned template is empty.
|
||||
// Once entries exist, the wrapper still binds the tenant before any query.
|
||||
if (SHK_CUSTOM_FIELD_TEMPLATE.length === 0) {
|
||||
return { created: 0 };
|
||||
}
|
||||
return withTenantRLS(input.tenantId, (tx) => seedShkCustomFieldTemplateWithTx(tx, input));
|
||||
}
|
||||
|
||||
/** 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 } }));
|
||||
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
withTenantRLS: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
create: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({ withTenantRLS: mocks.withTenantRLS }));
|
||||
|
||||
import { seedShkCustomFieldTemplate, seedShkCustomFieldTemplateWithTx, SHK_CUSTOM_FIELD_TEMPLATE } from "./customFieldService.server";
|
||||
|
||||
const tx = {
|
||||
customFieldDefinition: {
|
||||
findFirst: mocks.findFirst,
|
||||
create: mocks.create,
|
||||
},
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.withTenantRLS.mockImplementation(async (_tenantId, callback) => callback(tx));
|
||||
});
|
||||
|
||||
describe("SHK custom-field template transaction boundary", () => {
|
||||
it("keeps the intentionally empty template as a no-op in an existing transaction", async () => {
|
||||
const result = await seedShkCustomFieldTemplateWithTx(tx as never, { tenantId: "tenant-atomic-bootstrap" });
|
||||
|
||||
expect(SHK_CUSTOM_FIELD_TEMPLATE).toEqual([]);
|
||||
expect(result).toEqual({ created: 0 });
|
||||
expect(mocks.withTenantRLS).not.toHaveBeenCalled();
|
||||
expect(mocks.findFirst).not.toHaveBeenCalled();
|
||||
expect(mocks.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("avoids an RLS transaction while the versioned template is empty", async () => {
|
||||
await expect(seedShkCustomFieldTemplate({ tenantId: "tenant-wrapper" })).resolves.toEqual({ created: 0 });
|
||||
|
||||
expect(mocks.withTenantRLS).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { countTagUsageByTagIds, listTagsForEntities } from "./tagService.server";
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("tag service batch reads", () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
test("loads assignments for an entity page with one query", async () => {
|
||||
const findMany = vi.fn(async () => [
|
||||
{ entityId: "contact-1", tag: { id: "tag-1", tenantId: "tenant-1", name: "Hot", farbe: "#f00", createdAt: new Date(0) } },
|
||||
{ entityId: "contact-2", tag: { id: "tag-2", tenantId: "tenant-1", name: "Warm", farbe: "#fa0", createdAt: new Date(0) } },
|
||||
]);
|
||||
vi.mocked(withTenantRLS).mockImplementation(async (_tenantId, callback) =>
|
||||
callback({ tagAssignment: { findMany } } as never),
|
||||
);
|
||||
|
||||
const result = await listTagsForEntities({
|
||||
tenantId: "tenant-1",
|
||||
entityType: "kontakt",
|
||||
entityIds: ["contact-1", "contact-2", "contact-1"],
|
||||
});
|
||||
|
||||
expect(findMany).toHaveBeenCalledOnce();
|
||||
expect(findMany).toHaveBeenCalledWith(expect.objectContaining({
|
||||
where: expect.objectContaining({ entityId: { in: ["contact-1", "contact-2"] } }),
|
||||
}));
|
||||
expect(result.get("contact-1")?.map((tag) => tag.id)).toEqual(["tag-1"]);
|
||||
expect(result.get("contact-2")?.map((tag) => tag.id)).toEqual(["tag-2"]);
|
||||
});
|
||||
|
||||
test("loads all per-tag usage counts with one grouped query", async () => {
|
||||
const groupBy = vi.fn(async () => [{ tagId: "tag-1", _count: { _all: 3 } }]);
|
||||
vi.mocked(withTenantRLS).mockImplementation(async (_tenantId, callback) =>
|
||||
callback({ tagAssignment: { groupBy } } as never),
|
||||
);
|
||||
|
||||
const result = await countTagUsageByTagIds("tenant-1", ["tag-1", "tag-2", "tag-1"]);
|
||||
|
||||
expect(groupBy).toHaveBeenCalledOnce();
|
||||
expect(result).toEqual(new Map([["tag-1", 3], ["tag-2", 0]]));
|
||||
});
|
||||
});
|
||||
+40
@@ -104,10 +104,50 @@ export async function listTagsForEntity(input: { tenantId: string; entityType: s
|
||||
return assignments.map((assignment) => assignment.tag as TagRow);
|
||||
}
|
||||
|
||||
export async function listTagsForEntities(input: {
|
||||
tenantId: string;
|
||||
entityType: string;
|
||||
entityIds: readonly string[];
|
||||
}): Promise<Map<string, TagRow[]>> {
|
||||
const entityIds = [...new Set(input.entityIds.filter(Boolean))];
|
||||
const tagsByEntity = new Map(entityIds.map((entityId) => [entityId, [] as TagRow[]]));
|
||||
if (entityIds.length === 0) return tagsByEntity;
|
||||
|
||||
const assignments = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.tagAssignment.findMany({
|
||||
where: { tenantId: input.tenantId, entityType: input.entityType, entityId: { in: entityIds } },
|
||||
include: { tag: true },
|
||||
orderBy: { createdAt: "asc" },
|
||||
}),
|
||||
);
|
||||
for (const assignment of assignments) {
|
||||
tagsByEntity.get(assignment.entityId)?.push(assignment.tag as TagRow);
|
||||
}
|
||||
return tagsByEntity;
|
||||
}
|
||||
|
||||
export async function countTagUsage(tenantId: string, tagId: string): Promise<number> {
|
||||
return withTenantRLS(tenantId, (tx) => tx.tagAssignment.count({ where: { tenantId, tagId } }));
|
||||
}
|
||||
|
||||
export async function countTagUsageByTagIds(tenantId: string, tagIds: readonly string[]): Promise<Map<string, number>> {
|
||||
const ids = [...new Set(tagIds.filter(Boolean))];
|
||||
const usageCounts = new Map(ids.map((tagId) => [tagId, 0]));
|
||||
if (ids.length === 0) return usageCounts;
|
||||
|
||||
const counts = await withTenantRLS(tenantId, (tx) =>
|
||||
tx.tagAssignment.groupBy({
|
||||
by: ["tagId"],
|
||||
where: { tenantId, tagId: { in: ids } },
|
||||
_count: { _all: true },
|
||||
}),
|
||||
);
|
||||
for (const row of counts) {
|
||||
usageCounts.set(row.tagId, row._count._all);
|
||||
}
|
||||
return usageCounts;
|
||||
}
|
||||
|
||||
// --- internal --------------------------------------------------------------
|
||||
|
||||
function isUniqueConstraintError(error: unknown): boolean {
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { isValidTimeZone, parseScheduledAt } from "./campaignSchedule";
|
||||
|
||||
describe("isValidTimeZone", () => {
|
||||
it("accepts IANA zones and rejects garbage", () => {
|
||||
expect(isValidTimeZone("Europe/Berlin")).toBe(true);
|
||||
expect(isValidTimeZone("America/New_York")).toBe(true);
|
||||
expect(isValidTimeZone("Mars/Olympus")).toBe(false);
|
||||
expect(isValidTimeZone("")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseScheduledAt", () => {
|
||||
it("returns null for empty input", () => {
|
||||
expect(parseScheduledAt(null, "Europe/Berlin")).toEqual({ ok: true, date: null });
|
||||
});
|
||||
|
||||
it("interprets wall-clock time in the campaign timezone, not server time", () => {
|
||||
const berlin = parseScheduledAt("2026-07-20T09:00", "Europe/Berlin");
|
||||
const newYork = parseScheduledAt("2026-07-20T09:00", "America/New_York");
|
||||
if (!berlin.ok || !newYork.ok) throw new Error("expected ok results");
|
||||
// CEST is UTC+2 in July, EDT is UTC-4 — same wall clock, 6h apart.
|
||||
expect(berlin.date?.toISOString()).toBe("2026-07-20T07:00:00.000Z");
|
||||
expect(newYork.date?.toISOString()).toBe("2026-07-20T13:00:00.000Z");
|
||||
});
|
||||
|
||||
it("respects winter/summer offsets of the same zone", () => {
|
||||
const summer = parseScheduledAt("2026-07-20T09:00", "Europe/Berlin");
|
||||
const winter = parseScheduledAt("2026-01-20T09:00", "Europe/Berlin");
|
||||
if (!summer.ok || !winter.ok) throw new Error("expected ok results");
|
||||
expect(summer.date?.toISOString()).toBe("2026-07-20T07:00:00.000Z");
|
||||
expect(winter.date?.toISOString()).toBe("2026-01-20T08:00:00.000Z");
|
||||
});
|
||||
|
||||
it("keeps explicit offsets untouched", () => {
|
||||
const zulu = parseScheduledAt("2026-07-20T09:00:00Z", "America/New_York");
|
||||
const offset = parseScheduledAt("2026-07-20T09:00:00+02:00", "America/New_York");
|
||||
if (!zulu.ok || !offset.ok) throw new Error("expected ok results");
|
||||
expect(zulu.date?.toISOString()).toBe("2026-07-20T09:00:00.000Z");
|
||||
expect(offset.date?.toISOString()).toBe("2026-07-20T07:00:00.000Z");
|
||||
});
|
||||
|
||||
it("rejects invalid timezone or unparseable date", () => {
|
||||
expect(parseScheduledAt("2026-07-20T09:00", "Mars/Olympus")).toEqual({ ok: false });
|
||||
expect(parseScheduledAt("not-a-date", "Europe/Berlin")).toEqual({ ok: false });
|
||||
});
|
||||
});
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
import { fromZonedTime } from "date-fns-tz";
|
||||
|
||||
// Wall-clock inputs ("2026-07-20T09:00") carry no offset; anything with an
|
||||
// explicit offset or Z suffix is already an absolute instant.
|
||||
const EXPLICIT_OFFSET = /(?:Z|[+-]\d{2}:?\d{2})$/i;
|
||||
|
||||
export function isValidTimeZone(timeZone: string): boolean {
|
||||
try {
|
||||
new Intl.DateTimeFormat("en-US", { timeZone });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export type ParsedScheduledAt = { ok: true; date: Date | null } | { ok: false };
|
||||
|
||||
/**
|
||||
* Resolves the campaign "scheduledAt" form value to a UTC instant.
|
||||
* Wall-clock strings are interpreted in the campaign's IANA timezone —
|
||||
* NOT in the server's local timezone (that was the pre-fix behavior and
|
||||
* shifted scheduled sends by the server/tz offset difference).
|
||||
*/
|
||||
export function parseScheduledAt(value: string | null, timeZone: string): ParsedScheduledAt {
|
||||
if (!value) return { ok: true, date: null };
|
||||
if (!isValidTimeZone(timeZone)) return { ok: false };
|
||||
const date = EXPLICIT_OFFSET.test(value) ? new Date(value) : fromZonedTime(value, timeZone);
|
||||
if (Number.isNaN(date.getTime())) return { ok: false };
|
||||
return { ok: true, date };
|
||||
}
|
||||
+47
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildKontaktWhere,
|
||||
buildKontaktSqlPredicate,
|
||||
collectLookupRefs,
|
||||
lookupRefKey,
|
||||
MAX_SEGMENT_DEPTH,
|
||||
@@ -36,6 +37,20 @@ describe("validateSegmentTree", () => {
|
||||
expect(validateSegmentTree({ field: "kontaktStatus", in: ["bogus"] })).toEqual({ ok: false, errorKey: SEGMENT_FILTER_ERRORS.invalidLeaf });
|
||||
});
|
||||
|
||||
it("deduplicates an abusive status list to the three semantic enum values", () => {
|
||||
const result = validateSegmentTree({
|
||||
field: "kontaktStatus",
|
||||
in: Array.from({ length: 70_000 }, (_, index) => ["kontakt", "kunde", "bestandskunde"][index % 3]),
|
||||
});
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
tree: { field: "kontaktStatus", in: ["kontakt", "kunde", "bestandskunde"] },
|
||||
});
|
||||
if (result.ok) {
|
||||
expect(buildKontaktSqlPredicate(result.tree).parameters).toHaveLength(3);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects a group missing children", () => {
|
||||
expect(validateSegmentTree({ op: "and" })).toEqual({ ok: false, errorKey: SEGMENT_FILTER_ERRORS.invalidShape });
|
||||
});
|
||||
@@ -107,3 +122,35 @@ describe("buildKontaktWhere", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildKontaktSqlPredicate", () => {
|
||||
it("compiles lookup leaves to tenant-correlated EXISTS clauses with bounded bind parameters", () => {
|
||||
const predicate = buildKontaktSqlPredicate({
|
||||
op: "and",
|
||||
children: [
|
||||
{ field: "tag", tagId: "tag-1" },
|
||||
{
|
||||
op: "or",
|
||||
children: [
|
||||
{ field: "customFieldExists", definitionId: "field-1" },
|
||||
{ field: "customFieldEquals", definitionId: "field-2", value: "DE" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(predicate.sql).toContain('FROM "TagAssignment" AS ta');
|
||||
expect(predicate.sql).toContain('ta."tenantId" = k."tenantId"');
|
||||
expect(predicate.sql).toContain('FROM "CustomFieldValue" AS cf');
|
||||
expect(predicate.sql).toContain('cf."tenantId" = k."tenantId"');
|
||||
expect(predicate.sql).toContain('cf."wert" = $4::jsonb');
|
||||
expect(predicate.sql).not.toContain("tag-1");
|
||||
expect(predicate.sql).not.toContain("field-1");
|
||||
expect(predicate.parameters).toEqual(["tag-1", "field-1", "field-2", '"DE"']);
|
||||
});
|
||||
|
||||
it("preserves empty AND/OR semantics without adding parameters", () => {
|
||||
expect(buildKontaktSqlPredicate({ op: "and", children: [] })).toEqual({ sql: "TRUE", parameters: [] });
|
||||
expect(buildKontaktSqlPredicate({ op: "or", children: [] })).toEqual({ sql: "FALSE", parameters: [] });
|
||||
});
|
||||
});
|
||||
+81
-2
@@ -71,8 +71,11 @@ function validateLeaf(raw: Record<string, unknown>): SegmentLeaf | 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;
|
||||
if (!raw.in.every((value) => allowed.includes(value as KontaktStatus))) return null;
|
||||
// Duplicates do not change IN semantics. Normalize them here so a remote
|
||||
// filter cannot turn one logical node into an unbounded bind list.
|
||||
const values = [...new Set(raw.in as KontaktStatus[])];
|
||||
return { field, in: values };
|
||||
}
|
||||
case "zustaendigerUserId":
|
||||
return typeof raw.eq === "string" && raw.eq.length > 0 ? { field, eq: raw.eq } : null;
|
||||
@@ -173,6 +176,14 @@ export function collectLookupRefs(node: SegmentNode): LookupRef[] {
|
||||
/** A Prisma.KontaktWhereInput-shaped fragment (kept loose to stay DB-free). */
|
||||
export type KontaktWhereFragment = Record<string, unknown>;
|
||||
|
||||
/** A fully parameterized PostgreSQL predicate for the Kontakt alias `k`.
|
||||
* Lookup leaves use correlated EXISTS clauses, so no entity-id collection is
|
||||
* materialized into an `IN (...)` list. */
|
||||
export type KontaktSqlPredicate = {
|
||||
sql: string;
|
||||
parameters: readonly unknown[];
|
||||
};
|
||||
|
||||
function leafToWhere(leaf: SegmentLeaf, resolved: ReadonlyMap<string, readonly string[]>): KontaktWhereFragment {
|
||||
switch (leaf.field) {
|
||||
case "kontaktTyp":
|
||||
@@ -209,3 +220,71 @@ export function buildKontaktWhere(node: SegmentNode, resolved: ReadonlyMap<strin
|
||||
}
|
||||
return leafToWhere(node, resolved);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compile a validated segment tree to bounded, parameterized PostgreSQL. Only
|
||||
* static identifiers and validated operators enter the SQL text; all remote
|
||||
* values remain bind parameters. The validation caps the tree at 200 nodes,
|
||||
* which also bounds the number of SQL parameters independently of audience
|
||||
* size.
|
||||
*/
|
||||
export function buildKontaktSqlPredicate(node: SegmentNode): KontaktSqlPredicate {
|
||||
const parameters: unknown[] = [];
|
||||
const bind = (value: unknown): string => {
|
||||
parameters.push(value);
|
||||
return `$${parameters.length}`;
|
||||
};
|
||||
|
||||
const compile = (current: SegmentNode): string => {
|
||||
if (isGroup(current)) {
|
||||
if (current.children.length === 0) return current.op === "and" ? "TRUE" : "FALSE";
|
||||
const operator = current.op === "and" ? " AND " : " OR ";
|
||||
return `(${current.children.map(compile).join(operator)})`;
|
||||
}
|
||||
|
||||
switch (current.field) {
|
||||
case "kontaktTyp":
|
||||
return `k."kontaktTyp" = ${bind(current.eq)}::"KontaktTyp"`;
|
||||
case "kontaktStatus":
|
||||
return `k."kontaktStatus" IN (${current.in.map((value) => `${bind(value)}::"KontaktStatus"`).join(", ")})`;
|
||||
case "zustaendigerUserId":
|
||||
return `k."zustaendigerUserId" = ${bind(current.eq)}`;
|
||||
case "createdBefore":
|
||||
return `k."createdAt" < ${bind(new Date(current.value))}`;
|
||||
case "createdAfter":
|
||||
return `k."createdAt" > ${bind(new Date(current.value))}`;
|
||||
case "hasPrimaerEmail":
|
||||
return current.value ? `k."primaerEmail" IS NOT NULL` : `k."primaerEmail" IS NULL`;
|
||||
case "tag":
|
||||
return `EXISTS (
|
||||
SELECT 1
|
||||
FROM "TagAssignment" AS ta
|
||||
WHERE ta."tenantId" = k."tenantId"
|
||||
AND ta."entityType" = 'kontakt'
|
||||
AND ta."entityId" = k."id"
|
||||
AND ta."tagId" = ${bind(current.tagId)}
|
||||
)`;
|
||||
case "customFieldExists":
|
||||
return `EXISTS (
|
||||
SELECT 1
|
||||
FROM "CustomFieldValue" AS cf
|
||||
WHERE cf."tenantId" = k."tenantId"
|
||||
AND cf."entityType" = 'kontakt'::"CustomFieldEntityType"
|
||||
AND cf."entityId" = k."id"
|
||||
AND cf."definitionId" = ${bind(current.definitionId)}
|
||||
)`;
|
||||
case "customFieldEquals":
|
||||
return `EXISTS (
|
||||
SELECT 1
|
||||
FROM "CustomFieldValue" AS cf
|
||||
WHERE cf."tenantId" = k."tenantId"
|
||||
AND cf."entityType" = 'kontakt'::"CustomFieldEntityType"
|
||||
AND cf."entityId" = k."id"
|
||||
AND cf."definitionId" = ${bind(current.definitionId)}
|
||||
AND cf."wert" = ${bind(JSON.stringify(current.value))}::jsonb
|
||||
)`;
|
||||
}
|
||||
};
|
||||
|
||||
return { sql: compile(node), parameters };
|
||||
}
|
||||
+6
@@ -13,11 +13,13 @@
|
||||
|
||||
import { createMailjetDnsProvisioner, type MailjetDnsProvisioner } from "@hivegrid/mail";
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { featureKeys } from "@hivegrid/entitlements";
|
||||
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";
|
||||
import { requireTenantProductAccess } from "~/utils/entitlements/.server/productAccess.server";
|
||||
|
||||
const BCC_LOCAL_PART = "crm";
|
||||
const BCC_INBOUND_HOST = "bcc.hivegrid.de";
|
||||
@@ -37,6 +39,10 @@ export async function loadEmailDomainContext({ request, params }: { request: Req
|
||||
if (!tenantId || !userInfo.userId) {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
// Child resource routes can be called directly without executing their
|
||||
// layout loader. Enforce the paid add-on and billing status at the shared
|
||||
// context boundary every email-marketing route already uses.
|
||||
await requireTenantProductAccess({ request, params, featureKey: featureKeys.emailMarketing });
|
||||
const permissions = await getPermissionsByUser(userInfo.userId, tenantId);
|
||||
return { tenantId, userId: userInfo.userId, permissions };
|
||||
}
|
||||
|
||||
+32
-5
@@ -11,9 +11,22 @@
|
||||
// P5 cutover). EntityLink is the only table this service touches, so each function
|
||||
// is a single withTenantRLS() block (no nested transactions to worry about).
|
||||
|
||||
import type { DbTransactionClient } from "@hivegrid/db/transactions.server";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
|
||||
export type LinkableEntityType = "contact" | "company" | "lead" | "deal" | "project" | "task" | "file" | "user" | "order" | "appointment" | "form_submission";
|
||||
export type LinkableEntityType =
|
||||
| "contact"
|
||||
| "company"
|
||||
| "lead"
|
||||
| "deal"
|
||||
| "project"
|
||||
| "task"
|
||||
| "file"
|
||||
| "user"
|
||||
| "order"
|
||||
| "appointment"
|
||||
| "form_submission"
|
||||
| "chat_message";
|
||||
|
||||
export type EntityLinkRow = {
|
||||
id: string;
|
||||
@@ -41,8 +54,23 @@ export async function linkEntities(input: {
|
||||
targetId: string;
|
||||
linkRole?: string | null;
|
||||
}): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.entityLink.upsert({
|
||||
await withTenantRLS(input.tenantId, (tx) => linkEntitiesWithTx(tx, input));
|
||||
}
|
||||
|
||||
/** Idempotently links entities through the caller's active RLS transaction. */
|
||||
export async function linkEntitiesWithTx(
|
||||
tx: DbTransactionClient,
|
||||
input: {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
sourceType: LinkableEntityType;
|
||||
sourceId: string;
|
||||
targetType: LinkableEntityType;
|
||||
targetId: string;
|
||||
linkRole?: string | null;
|
||||
}
|
||||
): Promise<void> {
|
||||
await tx.entityLink.upsert({
|
||||
where: {
|
||||
tenantId_sourceType_sourceId_targetType_targetId: {
|
||||
tenantId: input.tenantId,
|
||||
@@ -62,8 +90,7 @@ export async function linkEntities(input: {
|
||||
targetId: input.targetId,
|
||||
linkRole: input.linkRole ?? null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** Remove a directed link between two entities (no-op if absent). */
|
||||
|
||||
+6
-1
@@ -45,7 +45,12 @@ export async function loadFilesContext({
|
||||
// Mutations on a disabled module look "not found" (Bauprinzip A.5.3).
|
||||
throw new CatalogError(foundationErrors.notFound, { module: FILES_MODULE_KEY });
|
||||
}
|
||||
return { tenantId, userId: userInfo.userId, permissions, hasModule };
|
||||
return {
|
||||
tenantId,
|
||||
userId: userInfo.userId,
|
||||
permissions,
|
||||
hasModule,
|
||||
};
|
||||
}
|
||||
|
||||
/** Require a files.* permission; throws 404 (CatalogError.notFound) if missing. */
|
||||
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
// P4 Files — candidates for the "Datei verknüpfen" dialog.
|
||||
//
|
||||
// The dialog used to ask for a raw record id, which nobody carries in their
|
||||
// head. This resolves the pickable records per entity type instead: one small
|
||||
// query per type, tenant-scoped through RLS, newest first, narrowed by a
|
||||
// substring search over whatever that record is recognised by.
|
||||
//
|
||||
// Not every linkable type has something to search by (an appointment has no
|
||||
// title of its own, a form submission no name), so the set of searchable types
|
||||
// is declared here and the dialog falls back to the plain id field for the rest.
|
||||
// Better an honest "no picker for this type" than a picker that lists nothing.
|
||||
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
import type { FileEntityType } from "./fileService.server";
|
||||
|
||||
/** One pickable record: what gets linked, and how a human recognises it. */
|
||||
export type FileLinkTarget = { id: string; label: string; hint: string | null };
|
||||
|
||||
/** Entity types the picker can search. Everything else keeps the id field. */
|
||||
export const SEARCHABLE_LINK_TYPES = ["contact", "company", "lead", "project", "task", "user"] as const;
|
||||
export type SearchableLinkType = (typeof SEARCHABLE_LINK_TYPES)[number];
|
||||
|
||||
export function isSearchableLinkType(value: string): value is SearchableLinkType {
|
||||
return (SEARCHABLE_LINK_TYPES as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
/** Enough rows to pick from, few enough to stay a single cheap query. */
|
||||
const RESULT_LIMIT = 20;
|
||||
|
||||
function contains(search: string) {
|
||||
return { contains: search, mode: "insensitive" as const };
|
||||
}
|
||||
|
||||
/** Join the parts of a name that are actually there, without stray separators. */
|
||||
function joinLabel(parts: readonly (string | null | undefined)[], fallback: string): string {
|
||||
const label = parts.map((part) => part?.trim()).filter(Boolean).join(" ");
|
||||
return label || fallback;
|
||||
}
|
||||
|
||||
/** Key of one link, so a resolved label can be looked up per (type, id). */
|
||||
export function fileLinkKey(entityType: string, entityId: string): string {
|
||||
return `${entityType}:${entityId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Names for records that are already linked, so the list of links reads
|
||||
* "Kontakt · Markus Weber" instead of just "Kontakt". A record that no longer
|
||||
* exists (or has no searchable name) simply has no label — the list falls back
|
||||
* to the type, which is what it showed before.
|
||||
*/
|
||||
export async function resolveFileLinkLabels(input: {
|
||||
tenantId: string;
|
||||
links: readonly { entityType: string; entityId: string }[];
|
||||
}): Promise<Map<string, string>> {
|
||||
const labels = new Map<string, string>();
|
||||
const byType = new Map<SearchableLinkType, string[]>();
|
||||
for (const link of input.links) {
|
||||
if (!isSearchableLinkType(link.entityType)) continue;
|
||||
const ids = byType.get(link.entityType) ?? [];
|
||||
ids.push(link.entityId);
|
||||
byType.set(link.entityType, ids);
|
||||
}
|
||||
if (byType.size === 0) return labels;
|
||||
|
||||
await Promise.all(
|
||||
[...byType.entries()].map(async ([entityType, ids]) => {
|
||||
// Reuse the picker's own labelling, so a link reads exactly like the entry
|
||||
// it was picked from.
|
||||
const rows = await searchFileLinkTargets({ tenantId: input.tenantId, entityType, search: "", ids });
|
||||
for (const row of rows) labels.set(fileLinkKey(entityType, row.id), row.label);
|
||||
})
|
||||
);
|
||||
return labels;
|
||||
}
|
||||
|
||||
/**
|
||||
* Records of `entityType` the current user may link this file to, filtered by
|
||||
* `search`, or exactly the records in `ids` when the caller is resolving known
|
||||
* links. An empty search returns the newest records rather than nothing:
|
||||
* opening the dialog should show something to click.
|
||||
*
|
||||
* Visibility note: this runs inside the tenant's RLS context, so the rows are
|
||||
* tenant-scoped by the database. Per-record read scopes (project pipelines, CRM
|
||||
* owner scope) are deliberately NOT re-implemented here — linking is a
|
||||
* `files.write` action on the file, and the label of a tenant record is not the
|
||||
* record. The link itself is written by `linkFile`, which keeps its own checks.
|
||||
*/
|
||||
export async function searchFileLinkTargets(input: {
|
||||
tenantId: string;
|
||||
entityType: FileEntityType;
|
||||
search: string;
|
||||
/** Restrict to these records (label resolution) instead of searching. */
|
||||
ids?: readonly string[];
|
||||
}): Promise<FileLinkTarget[]> {
|
||||
const { tenantId, entityType } = input;
|
||||
const search = input.search.trim();
|
||||
if (!isSearchableLinkType(entityType)) return [];
|
||||
if (input.ids && input.ids.length === 0) return [];
|
||||
/** Restriction to the requested ids, merged into every model's where clause. */
|
||||
const onlyIds = input.ids ? { id: { in: [...input.ids] } } : {};
|
||||
|
||||
return withTenantRLS(tenantId, async (tx: TenantRlsClient) => {
|
||||
switch (entityType) {
|
||||
case "contact":
|
||||
case "company": {
|
||||
// One model carries both: a Kontakt is either a person or an
|
||||
// organisation (AD-20), so "company" is the organisation half of it.
|
||||
const kontaktTyp = entityType === "company" ? "organisation" : "privatperson";
|
||||
const rows = await tx.kontakt.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
kontaktTyp,
|
||||
...onlyIds,
|
||||
...(search
|
||||
? {
|
||||
OR: [
|
||||
{ vorname: contains(search) },
|
||||
{ nachname: contains(search) },
|
||||
{ orgName: contains(search) },
|
||||
{ primaerEmail: contains(search) },
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: RESULT_LIMIT,
|
||||
select: { id: true, vorname: true, nachname: true, orgName: true, primaerEmail: true },
|
||||
});
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
label: joinLabel(entityType === "company" ? [row.orgName] : [row.vorname, row.nachname], row.primaerEmail ?? row.id),
|
||||
hint: row.primaerEmail ?? null,
|
||||
}));
|
||||
}
|
||||
case "lead": {
|
||||
// The tenant's own lead inbox (P7). `Lead` in marketingLeads is the
|
||||
// platform's acquisition lead and has no tenant at all.
|
||||
const rows = await tx.inboxLead.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
...onlyIds,
|
||||
...(search ? { OR: [{ vorname: contains(search) }, { nachname: contains(search) }, { email: contains(search) }] } : {}),
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: RESULT_LIMIT,
|
||||
select: { id: true, vorname: true, nachname: true, email: true },
|
||||
});
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
label: joinLabel([row.vorname, row.nachname], row.email ?? row.id),
|
||||
hint: row.email,
|
||||
}));
|
||||
}
|
||||
case "project": {
|
||||
const rows = await tx.projekt.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
...onlyIds,
|
||||
...(search ? { OR: [{ projektname: contains(search) }, { projektNummer: contains(search) }] } : {}),
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: RESULT_LIMIT,
|
||||
select: { id: true, projektname: true, projektNummer: true },
|
||||
});
|
||||
return rows.map((row) => ({ id: row.id, label: row.projektname, hint: row.projektNummer }));
|
||||
}
|
||||
case "task": {
|
||||
const rows = await tx.task.findMany({
|
||||
where: { tenantId, ...onlyIds, ...(search ? { title: contains(search) } : {}) },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: RESULT_LIMIT,
|
||||
select: { id: true, title: true },
|
||||
});
|
||||
return rows.map((row) => ({ id: row.id, label: row.title, hint: null }));
|
||||
}
|
||||
case "user": {
|
||||
// Members of this tenant, not every user row in the database.
|
||||
const rows = await tx.tenantUser.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
...(input.ids ? { userId: { in: [...input.ids] } } : {}),
|
||||
...(search ? { user: { is: { OR: [{ firstName: contains(search) }, { lastName: contains(search) }, { email: contains(search) }] } } } : {}),
|
||||
},
|
||||
take: RESULT_LIMIT,
|
||||
select: { user: { select: { id: true, firstName: true, lastName: true, email: true } } },
|
||||
});
|
||||
return rows.map((row) => ({
|
||||
id: row.user.id,
|
||||
label: joinLabel([row.user.firstName, row.user.lastName], row.user.email),
|
||||
hint: row.user.email,
|
||||
}));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
// 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.
|
||||
// call enqueueFilePreview(...) only for the explicit "regenerate preview"
|
||||
// action. Initial previews are enqueued by the worker after a persisted clean
|
||||
// AV verdict, never by the upload request itself.
|
||||
// Mirrors fileScanQueue.server.ts so the queue lifecycle is the same shared
|
||||
// pattern. Unlike the scan queue there is no enable-flag: preview generation is
|
||||
// always desired; if Redis is unreachable the enqueue is a no-op and the file
|
||||
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { isFileScanDeliverable } from "./fileScanPolicy";
|
||||
|
||||
describe("file scan delivery policy", () => {
|
||||
it.each(["pending", "infected", "skipped", "unknown", ""])("fails closed for %s", (scanStatus) => {
|
||||
expect(isFileScanDeliverable(scanStatus)).toBe(false);
|
||||
});
|
||||
|
||||
it("allows files only after a clean scanner verdict", () => {
|
||||
expect(isFileScanDeliverable("clean")).toBe(true);
|
||||
});
|
||||
});
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
export function isFileScanDeliverable(scanStatus: string): boolean {
|
||||
return scanStatus === "clean";
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { readBulkZipResponseBytes } from "./fileService.server";
|
||||
|
||||
describe("bulk ZIP response bounds", () => {
|
||||
test("reads a response up to the declared file size", async () => {
|
||||
const response = new Response(new Uint8Array([1, 2, 3]), {
|
||||
headers: { "content-length": "3" },
|
||||
});
|
||||
|
||||
await expect(readBulkZipResponseBytes(response, 3)).resolves.toEqual(new Uint8Array([1, 2, 3]));
|
||||
});
|
||||
|
||||
test("rejects an oversized content-length before buffering", async () => {
|
||||
const response = new Response(new Uint8Array([1, 2, 3]), {
|
||||
headers: { "content-length": "3" },
|
||||
});
|
||||
|
||||
await expect(readBulkZipResponseBytes(response, 2)).rejects.toMatchObject({
|
||||
name: "FileServiceError",
|
||||
messageKey: "files.errors.downloadFailed",
|
||||
});
|
||||
});
|
||||
|
||||
test("rejects actual streamed bytes when content-length understates the body", async () => {
|
||||
const response = new Response(new Uint8Array([1, 2, 3]), {
|
||||
headers: { "content-length": "2" },
|
||||
});
|
||||
|
||||
await expect(readBulkZipResponseBytes(response, 2)).rejects.toMatchObject({
|
||||
name: "FileServiceError",
|
||||
messageKey: "files.errors.downloadFailed",
|
||||
});
|
||||
});
|
||||
});
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { FILE_UPLOAD_CHUNK_SIZE_BYTES } from "@hivegrid/view-models";
|
||||
import { assertUploadChunkManifest, expectedUploadChunkSize, FileServiceError } from "./fileService.server";
|
||||
|
||||
describe("chunked file upload integrity", () => {
|
||||
it("requires full-sized intermediate chunks and the exact final remainder", () => {
|
||||
const totalSizeBytes = FILE_UPLOAD_CHUNK_SIZE_BYTES * 2 + 17;
|
||||
|
||||
expect(expectedUploadChunkSize({ totalSizeBytes, totalChunks: 3, chunkIndex: 0 })).toBe(FILE_UPLOAD_CHUNK_SIZE_BYTES);
|
||||
expect(expectedUploadChunkSize({ totalSizeBytes, totalChunks: 3, chunkIndex: 1 })).toBe(FILE_UPLOAD_CHUNK_SIZE_BYTES);
|
||||
expect(expectedUploadChunkSize({ totalSizeBytes, totalChunks: 3, chunkIndex: 2 })).toBe(17);
|
||||
});
|
||||
|
||||
it("accepts only a contiguous manifest whose byte sum matches the session", () => {
|
||||
const totalSizeBytes = FILE_UPLOAD_CHUNK_SIZE_BYTES + 7;
|
||||
|
||||
expect(() =>
|
||||
assertUploadChunkManifest({
|
||||
totalSizeBytes,
|
||||
totalChunks: 2,
|
||||
chunks: [
|
||||
{ chunkIndex: 0, sizeBytes: FILE_UPLOAD_CHUNK_SIZE_BYTES },
|
||||
{ chunkIndex: 1, sizeBytes: 7 },
|
||||
],
|
||||
})
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "under-declared first chunk",
|
||||
chunks: [
|
||||
{ chunkIndex: 0, sizeBytes: FILE_UPLOAD_CHUNK_SIZE_BYTES - 1 },
|
||||
{ chunkIndex: 1, sizeBytes: 7 },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "wrong final remainder",
|
||||
chunks: [
|
||||
{ chunkIndex: 0, sizeBytes: FILE_UPLOAD_CHUNK_SIZE_BYTES },
|
||||
{ chunkIndex: 1, sizeBytes: 8 },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "non-contiguous index",
|
||||
chunks: [
|
||||
{ chunkIndex: 0, sizeBytes: FILE_UPLOAD_CHUNK_SIZE_BYTES },
|
||||
{ chunkIndex: 2, sizeBytes: 7 },
|
||||
],
|
||||
},
|
||||
])("rejects $name", ({ chunks }) => {
|
||||
expect(() =>
|
||||
assertUploadChunkManifest({
|
||||
totalSizeBytes: FILE_UPLOAD_CHUNK_SIZE_BYTES + 7,
|
||||
totalChunks: 2,
|
||||
chunks,
|
||||
})
|
||||
).toThrow(
|
||||
expect.objectContaining<FileServiceError>({
|
||||
messageKey: "files.error.uploadIncomplete",
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
deleteFile: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
deleteRow: vi.fn(),
|
||||
publishSearchProjectionDelete: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("./storageService", () => ({
|
||||
assembleChunkedUpload: vi.fn(),
|
||||
deleteFile: mocks.deleteFile,
|
||||
putBufferAsFile: vi.fn(),
|
||||
resolveStorageBucket: () => "tenant-files",
|
||||
storeFile: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/storage", () => ({
|
||||
buildFileStorageKeys: vi.fn(),
|
||||
buildUploadChunkKey: vi.fn(),
|
||||
uploadChunkPrefix: vi.fn(),
|
||||
createMagicBytesScanAdapter: () => ({ scan: vi.fn() }),
|
||||
DEFAULT_ALLOW_LIST: { formUpload: [] },
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: async (_tenantId: string, callback: (tx: unknown) => Promise<unknown>) =>
|
||||
callback({ file: { findFirst: mocks.findFirst, delete: mocks.deleteRow } }),
|
||||
}));
|
||||
|
||||
vi.mock("~/services/search/searchIndexProjection.server", () => ({
|
||||
publishFileSearchUpsert: vi.fn(),
|
||||
publishSearchProjectionDelete: mocks.publishSearchProjectionDelete,
|
||||
}));
|
||||
|
||||
import { hardDeleteFile } from "./fileService.server";
|
||||
|
||||
describe("hardDeleteFile", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.findFirst.mockResolvedValue({
|
||||
id: "file_1",
|
||||
storageKey: "tenants/tenant_1/files/file_1/original.pdf",
|
||||
previewStorageKey: "tenants/tenant_1/files/file_1/preview.png",
|
||||
thumbnailStorageKey: "tenants/tenant_1/files/file_1/thumbnail.png",
|
||||
});
|
||||
mocks.deleteFile.mockResolvedValue(undefined);
|
||||
mocks.deleteRow.mockResolvedValue({ id: "file_1" });
|
||||
mocks.publishSearchProjectionDelete.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("removes every stored artifact before releasing the database quota", async () => {
|
||||
await expect(hardDeleteFile({ tenantId: "tenant_1", fileId: "file_1" })).resolves.toBeUndefined();
|
||||
|
||||
expect(mocks.deleteFile).toHaveBeenNthCalledWith(1, {
|
||||
bucket: "tenant-files",
|
||||
key: "tenants/tenant_1/files/file_1/original.pdf",
|
||||
});
|
||||
expect(mocks.deleteFile).toHaveBeenNthCalledWith(2, {
|
||||
bucket: "tenant-files",
|
||||
key: "tenants/tenant_1/files/file_1/preview.png",
|
||||
});
|
||||
expect(mocks.deleteFile).toHaveBeenNthCalledWith(3, {
|
||||
bucket: "tenant-files",
|
||||
key: "tenants/tenant_1/files/file_1/thumbnail.png",
|
||||
});
|
||||
expect(mocks.deleteRow).toHaveBeenCalledWith({ where: { id: "file_1" } });
|
||||
expect(mocks.deleteFile.mock.invocationCallOrder[2]).toBeLessThan(mocks.deleteRow.mock.invocationCallOrder[0]!);
|
||||
});
|
||||
|
||||
it("keeps the database row when object deletion fails so accounting cannot lose the object", async () => {
|
||||
mocks.deleteFile.mockRejectedValueOnce(new Error("object storage unavailable"));
|
||||
|
||||
await expect(hardDeleteFile({ tenantId: "tenant_1", fileId: "file_1" })).rejects.toThrow("object storage unavailable");
|
||||
|
||||
expect(mocks.deleteRow).not.toHaveBeenCalled();
|
||||
expect(mocks.publishSearchProjectionDelete).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { normalizeUploadMimeType } from "./fileService.server";
|
||||
|
||||
describe("normalizeUploadMimeType", () => {
|
||||
it("accepts browser MediaRecorder codec parameters through the canonical Files allow-list value", () => {
|
||||
expect(normalizeUploadMimeType("audio/webm;codecs=opus")).toBe("audio/webm");
|
||||
expect(normalizeUploadMimeType(" Audio/OGG ; codecs=opus ")).toBe("audio/ogg");
|
||||
expect(normalizeUploadMimeType("audio/x-m4a")).toBe("audio/mp4");
|
||||
});
|
||||
});
|
||||
+534
-196
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// Pure-ish server logic: builds/queries File rows (always tenant-scoped),
|
||||
// orchestrates chunked upload + assembly, enforces visibility (404, not 403),
|
||||
// and fans out to the scan/preview queues. NO React/UI imports. Routes call
|
||||
// and starts the scan -> clean -> preview queue chain. NO React/UI imports. Routes call
|
||||
// these functions from their loaders/actions and build the View-Model from the
|
||||
// returned rows.
|
||||
//
|
||||
@@ -19,12 +19,11 @@
|
||||
// goes through *WithTx(tx, ...) helpers that take the active transaction client.
|
||||
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
|
||||
import { buildPortalDocumentReadyOutboxEvent } from "@hivegrid/queue";
|
||||
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 "@hivegrid/view-models";
|
||||
import { FILE_UPLOAD_CHUNK_SIZE_BYTES, FILE_UPLOAD_MAX_FILE_SIZE_BYTES } from "@hivegrid/view-models";
|
||||
import { publishFileSearchUpsert, publishSearchProjectionDelete } from "~/services/search/searchIndexProjection.server";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
import { getTenantUsers } from "~/utils/db/tenants.db.server";
|
||||
@@ -34,7 +33,18 @@ 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";
|
||||
import { assertTenantStorageReservation, TenantStorageCapacityError } from "~/services/billing/storage-capacity.server";
|
||||
import { createMagicBytesScanAdapter, DEFAULT_ALLOW_LIST, type PreUploadScanAdapter, type ScanContext } from "@hivegrid/storage";
|
||||
import {
|
||||
assertFileLinkTargetVisibleWithTx,
|
||||
createFileVisibilityQueryState,
|
||||
fileReadScopeWhereWithTx,
|
||||
filterVisibleFileLinksWithTx,
|
||||
type FileVisibilityContext,
|
||||
type FileVisibilityQueryState,
|
||||
} from "./fileVisibility.server";
|
||||
|
||||
export type { FileVisibilityContext } from "./fileVisibility.server";
|
||||
|
||||
/**
|
||||
* Domain error carrying an i18n message key (M002 Klartext). Routes map
|
||||
@@ -60,7 +70,9 @@ export type FileEntityType =
|
||||
| "order"
|
||||
| "task"
|
||||
| "appointment"
|
||||
| "signature_document";
|
||||
| "signature_document"
|
||||
| "email_message"
|
||||
| "chat_message";
|
||||
|
||||
export type FileSource = "manual_upload" | "customer_portal" | "form_submission" | "email_attachment" | "automation" | "api";
|
||||
|
||||
@@ -78,6 +90,11 @@ export const FILES_ALLOWED_MIME_TYPES: ReadonlySet<string> = new Set([
|
||||
"image/gif",
|
||||
"image/heic",
|
||||
"image/heif",
|
||||
"audio/webm",
|
||||
"audio/ogg",
|
||||
"audio/mpeg",
|
||||
"audio/mp4",
|
||||
"audio/wav",
|
||||
"application/pdf",
|
||||
"text/plain",
|
||||
"text/markdown",
|
||||
@@ -87,15 +104,13 @@ export const FILES_ALLOWED_MIME_TYPES: ReadonlySet<string> = new Set([
|
||||
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||
]);
|
||||
|
||||
export type FileVisibilityContext = {
|
||||
userId: string;
|
||||
/** The user's permission names for this tenant (from getPermissionsByUser). */
|
||||
permissions: readonly string[];
|
||||
};
|
||||
|
||||
function hasPermission(ctx: FileVisibilityContext, permission: string): boolean {
|
||||
return ctx.permissions.includes(permission);
|
||||
}
|
||||
const filesMagicBytesScanner: PreUploadScanAdapter = createMagicBytesScanAdapter({
|
||||
allowList: {
|
||||
...DEFAULT_ALLOW_LIST,
|
||||
formUpload: [...FILES_ALLOWED_MIME_TYPES],
|
||||
},
|
||||
enabled: process.env.STORAGE_SCAN_LAYER1_ENABLED !== "false",
|
||||
});
|
||||
|
||||
// --- Upload session -------------------------------------------------------
|
||||
|
||||
@@ -120,29 +135,48 @@ export async function createUploadSession(input: CreateUploadSessionInput): Prom
|
||||
if (input.totalSizeBytes > FILE_UPLOAD_MAX_FILE_SIZE_BYTES) {
|
||||
throw new FileServiceError("files.error.tooLarge");
|
||||
}
|
||||
if (!FILES_ALLOWED_MIME_TYPES.has(input.mimeType)) {
|
||||
const mimeType = normalizeUploadMimeType(input.mimeType);
|
||||
if (!FILES_ALLOWED_MIME_TYPES.has(mimeType)) {
|
||||
throw new FileServiceError("files.error.mimeBlocked");
|
||||
}
|
||||
const totalChunks = Math.max(1, Math.ceil(input.totalSizeBytes / FILE_UPLOAD_CHUNK_SIZE_BYTES));
|
||||
const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000);
|
||||
const upload = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.fileUpload.create({
|
||||
const upload = await withTenantRLS(input.tenantId, async (tx) => {
|
||||
try {
|
||||
await assertTenantStorageReservation(tx, input.tenantId, input.totalSizeBytes);
|
||||
} catch (error) {
|
||||
if (error instanceof TenantStorageCapacityError) {
|
||||
throw new FileServiceError(
|
||||
error.code === "STORAGE_PLAN_REQUIRED" ? "files.error.storagePlanRequired" : "files.error.storageQuotaExceeded",
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return tx.fileUpload.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
createdByUserId: input.userId,
|
||||
originalFilename: input.originalFilename,
|
||||
totalSizeBytes: input.totalSizeBytes,
|
||||
mimeType: input.mimeType,
|
||||
mimeType,
|
||||
totalChunks,
|
||||
status: "in_progress",
|
||||
expiresAt,
|
||||
},
|
||||
select: { id: true },
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
return { uploadId: upload.id, chunkSize: FILE_UPLOAD_CHUNK_SIZE_BYTES, totalChunks };
|
||||
}
|
||||
|
||||
/** Browsers commonly append codec parameters to MediaRecorder MIME values. */
|
||||
export function normalizeUploadMimeType(value: string): string {
|
||||
const mimeType = value.split(";", 1)[0]?.trim().toLowerCase() ?? "";
|
||||
if (mimeType === "audio/x-m4a") return "audio/mp4";
|
||||
if (mimeType === "audio/x-wav") return "audio/wav";
|
||||
return mimeType;
|
||||
}
|
||||
|
||||
export type StoreUploadChunkInput = {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
@@ -151,12 +185,75 @@ export type StoreUploadChunkInput = {
|
||||
bytes: Uint8Array;
|
||||
};
|
||||
|
||||
export function expectedUploadChunkSize({
|
||||
totalSizeBytes,
|
||||
totalChunks,
|
||||
chunkIndex,
|
||||
}: {
|
||||
totalSizeBytes: number;
|
||||
totalChunks: number;
|
||||
chunkIndex: number;
|
||||
}): number {
|
||||
if (
|
||||
!Number.isSafeInteger(totalSizeBytes) ||
|
||||
totalSizeBytes <= 0 ||
|
||||
!Number.isSafeInteger(totalChunks) ||
|
||||
totalChunks <= 0 ||
|
||||
!Number.isSafeInteger(chunkIndex) ||
|
||||
chunkIndex < 0 ||
|
||||
chunkIndex >= totalChunks
|
||||
) {
|
||||
throw new FileServiceError("files.error.uploadIncomplete");
|
||||
}
|
||||
const expectedTotalChunks = Math.ceil(totalSizeBytes / FILE_UPLOAD_CHUNK_SIZE_BYTES);
|
||||
if (totalChunks !== expectedTotalChunks) {
|
||||
throw new FileServiceError("files.error.uploadIncomplete");
|
||||
}
|
||||
if (chunkIndex < totalChunks - 1) {
|
||||
return FILE_UPLOAD_CHUNK_SIZE_BYTES;
|
||||
}
|
||||
return totalSizeBytes - FILE_UPLOAD_CHUNK_SIZE_BYTES * (totalChunks - 1);
|
||||
}
|
||||
|
||||
export function assertUploadChunkManifest({
|
||||
totalSizeBytes,
|
||||
totalChunks,
|
||||
chunks,
|
||||
}: {
|
||||
totalSizeBytes: number;
|
||||
totalChunks: number;
|
||||
chunks: readonly { chunkIndex: number; sizeBytes: number }[];
|
||||
}): void {
|
||||
if (chunks.length !== totalChunks) {
|
||||
throw new FileServiceError("files.error.uploadIncomplete");
|
||||
}
|
||||
let receivedSizeBytes = 0;
|
||||
for (let index = 0; index < chunks.length; index += 1) {
|
||||
const chunk = chunks[index];
|
||||
if (chunk.chunkIndex !== index || chunk.sizeBytes !== expectedUploadChunkSize({ totalSizeBytes, totalChunks, chunkIndex: index })) {
|
||||
throw new FileServiceError("files.error.uploadIncomplete");
|
||||
}
|
||||
receivedSizeBytes += chunk.sizeBytes;
|
||||
}
|
||||
if (receivedSizeBytes !== totalSizeBytes) {
|
||||
throw new FileServiceError("files.error.uploadIncomplete");
|
||||
}
|
||||
}
|
||||
|
||||
export async function storeUploadChunk(input: StoreUploadChunkInput): Promise<{ receivedChunks: number; totalChunks: number }> {
|
||||
const upload = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.fileUpload.findFirst({
|
||||
where: { id: input.uploadId, tenantId: input.tenantId, createdByUserId: input.userId },
|
||||
select: { id: true, status: true, totalChunks: true, expiresAt: true },
|
||||
}),
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
totalChunks: true,
|
||||
totalSizeBytes: true,
|
||||
originalFilename: true,
|
||||
mimeType: true,
|
||||
expiresAt: true,
|
||||
},
|
||||
})
|
||||
);
|
||||
if (!upload) {
|
||||
throw new CatalogError(foundationErrors.notFound, { uploadId: input.uploadId });
|
||||
@@ -170,6 +267,25 @@ export async function storeUploadChunk(input: StoreUploadChunkInput): Promise<{
|
||||
if (input.chunkIndex < 0 || input.chunkIndex >= upload.totalChunks) {
|
||||
throw new FileServiceError("files.error.chunkIndexOutOfRange");
|
||||
}
|
||||
const expectedSizeBytes = expectedUploadChunkSize({
|
||||
totalSizeBytes: upload.totalSizeBytes,
|
||||
totalChunks: upload.totalChunks,
|
||||
chunkIndex: input.chunkIndex,
|
||||
});
|
||||
if (input.bytes.byteLength !== expectedSizeBytes) {
|
||||
throw new FileServiceError("files.error.uploadIncomplete");
|
||||
}
|
||||
if (input.chunkIndex === 0) {
|
||||
const scanResult = await filesMagicBytesScanner.scan({
|
||||
buffer: input.bytes,
|
||||
declaredMimeType: upload.mimeType,
|
||||
filename: upload.originalFilename,
|
||||
context: "formUpload",
|
||||
});
|
||||
if (scanResult.status === "rejected") {
|
||||
throw new FileServiceError("files.error.mimeBlocked");
|
||||
}
|
||||
}
|
||||
|
||||
const bucket = resolveStorageBucket();
|
||||
const chunkKey = buildUploadChunkKey(input.tenantId, input.uploadId, input.chunkIndex);
|
||||
@@ -244,17 +360,13 @@ export async function completeUpload(input: CompleteUploadInput): Promise<Comple
|
||||
const manifest = await tx.fileUploadChunk.findMany({
|
||||
where: { uploadId: input.uploadId, tenantId: input.tenantId },
|
||||
orderBy: { chunkIndex: "asc" },
|
||||
select: { chunkIndex: true, storageKey: true },
|
||||
select: { chunkIndex: true, storageKey: true, sizeBytes: true },
|
||||
});
|
||||
assertUploadChunkManifest({
|
||||
totalSizeBytes: session.totalSizeBytes,
|
||||
totalChunks: session.totalChunks,
|
||||
chunks: manifest,
|
||||
});
|
||||
if (manifest.length !== session.totalChunks) {
|
||||
throw new FileServiceError("files.error.uploadIncomplete");
|
||||
}
|
||||
// Verify contiguous 0..totalChunks-1 ordering.
|
||||
for (let index = 0; index < manifest.length; index += 1) {
|
||||
if (manifest[index].chunkIndex !== index) {
|
||||
throw new FileServiceError("files.error.uploadIncomplete");
|
||||
}
|
||||
}
|
||||
|
||||
const created = await tx.file.create({
|
||||
data: {
|
||||
@@ -307,18 +419,10 @@ export async function completeUpload(input: CompleteUploadInput): Promise<Comple
|
||||
await tx.fileUpload.update({ where: { id: input.uploadId }, data: { status: "completed", targetFileId: file.id } });
|
||||
});
|
||||
|
||||
// Fan out async scan (ClamAV, layer 2) + preview generation. When scanning is
|
||||
// disabled (dev / SCAN_QUEUE_ENABLED!=true) the enqueue is a no-op; in that
|
||||
// case mark the file scanStatus=skipped so the fail-closed media proxy (§6)
|
||||
// still serves it. In prod the file stays scanStatus=pending until the worker
|
||||
// writes a clean/infected verdict.
|
||||
const scanResult = await enqueueFileScan({ bucket, key: original, tenantId: input.tenantId, contentType: upload.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: upload.mimeType }).catch(() => {});
|
||||
// Enqueue only ClamAV here. The scan worker persists a clean verdict before
|
||||
// it enqueues the first preview, so untrusted bytes can never race an image
|
||||
// or PDF decoder. Queue failures leave the file pending/non-deliverable.
|
||||
await enqueueFileScan({ bucket, key: original, tenantId: input.tenantId, contentType: upload.mimeType, fileId: file.id }).catch(() => undefined);
|
||||
|
||||
return { id: file.id, displayName: file.displayName, mimeType: file.mimeType, sizeBytes: file.sizeBytes, storageKey: original };
|
||||
}
|
||||
@@ -338,7 +442,8 @@ export type CreateFileFromBytesInput = {
|
||||
* 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
|
||||
* upsert → enqueue ClamAV (layer 2), which schedules preview only after a
|
||||
* clean verdict. 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.
|
||||
*/
|
||||
@@ -348,8 +453,18 @@ export async function createFileFromBytes(input: CreateFileFromBytesInput): Prom
|
||||
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({
|
||||
const file = await withTenantRLS(input.tenantId, async (tx) => {
|
||||
try {
|
||||
await assertTenantStorageReservation(tx, input.tenantId, sizeBytes);
|
||||
} catch (error) {
|
||||
if (error instanceof TenantStorageCapacityError) {
|
||||
throw new FileServiceError(
|
||||
error.code === "STORAGE_PLAN_REQUIRED" ? "files.error.storagePlanRequired" : "files.error.storageQuotaExceeded",
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return tx.file.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
createdByUserId: input.userId,
|
||||
@@ -363,8 +478,8 @@ export async function createFileFromBytes(input: CreateFileFromBytesInput): Prom
|
||||
scanStatus: "pending",
|
||||
},
|
||||
select: { id: true, displayName: true, mimeType: true, sizeBytes: true },
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const bucket = resolveStorageBucket();
|
||||
const { original } = buildFileStorageKeys(input.tenantId, file.id);
|
||||
@@ -393,15 +508,8 @@ export async function createFileFromBytes(input: CreateFileFromBytesInput): Prom
|
||||
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(() => {});
|
||||
// 4. Enqueue ClamAV only. The clean-verdict worker schedules the preview.
|
||||
await enqueueFileScan({ bucket, key: original, tenantId: input.tenantId, contentType: mimeType, fileId: file.id }).catch(() => undefined);
|
||||
|
||||
return { id: file.id, displayName: file.displayName, mimeType: file.mimeType, sizeBytes: file.sizeBytes };
|
||||
}
|
||||
@@ -428,49 +536,62 @@ export type FileRow = {
|
||||
archivedAt: Date | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Owner/link visibility for files.read_own (§7). Visible when the user owns or
|
||||
* is assigned the file, OR holds files.read_all, OR a readable FileEntityLink
|
||||
* exists. v1 link-readability is minimal (the link's mere existence in-tenant);
|
||||
* full transitive entity-permission checks are v2.
|
||||
*/
|
||||
export type OwnedFileScanStatus = "pending" | "clean" | "infected" | "skipped";
|
||||
|
||||
/** Narrow post-upload status lookup for callers that created the File. It is
|
||||
* tenant-scoped, owner-scoped and RLS-bound so polling cannot become a generic
|
||||
* File enumeration side channel. */
|
||||
export async function getOwnedFileScanStatus(input: { tenantId: string; userId: string; fileId: string }): Promise<OwnedFileScanStatus> {
|
||||
const file = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.file.findFirst({
|
||||
where: {
|
||||
id: input.fileId,
|
||||
tenantId: input.tenantId,
|
||||
createdByUserId: input.userId,
|
||||
archivedAt: null,
|
||||
},
|
||||
select: { scanStatus: true },
|
||||
})
|
||||
);
|
||||
if (!file) throw new CatalogError(foundationErrors.notFound, { fileId: input.fileId });
|
||||
return file.scanStatus as OwnedFileScanStatus;
|
||||
}
|
||||
|
||||
// Internal: visibility check on an already-loaded file, using the active RLS
|
||||
// transaction client (no own transaction → safe to call inside withTenantRLS).
|
||||
async function isFileVisibleWithTx(
|
||||
tx: TenantRlsClient,
|
||||
file: Pick<FileRow, "id" | "tenantId" | "createdByUserId" | "assignedToUserId">,
|
||||
ctx: FileVisibilityContext,
|
||||
ctx: FileVisibilityContext
|
||||
): Promise<boolean> {
|
||||
if (hasPermission(ctx, "files.read_all")) {
|
||||
return true;
|
||||
}
|
||||
if (file.createdByUserId === ctx.userId || file.assignedToUserId === ctx.userId) {
|
||||
return true;
|
||||
}
|
||||
const link = await tx.fileEntityLink.findFirst({
|
||||
where: { fileId: file.id, tenantId: file.tenantId },
|
||||
const visibility = await fileReadScopeWhereWithTx(tx, file.tenantId, ctx, [file.id]);
|
||||
const visible = await tx.file.findFirst({
|
||||
where: { id: file.id, tenantId: file.tenantId, ...visibility },
|
||||
select: { id: true },
|
||||
});
|
||||
return Boolean(link);
|
||||
return Boolean(visible);
|
||||
}
|
||||
|
||||
export async function isFileVisible(file: Pick<FileRow, "id" | "tenantId" | "createdByUserId" | "assignedToUserId">, ctx: FileVisibilityContext): Promise<boolean> {
|
||||
// Fast paths need no DB; only the link lookup opens a tenant-scoped transaction.
|
||||
if (hasPermission(ctx, "files.read_all") || file.createdByUserId === ctx.userId || file.assignedToUserId === ctx.userId) {
|
||||
return true;
|
||||
}
|
||||
export async function isFileVisible(
|
||||
file: Pick<FileRow, "id" | "tenantId" | "createdByUserId" | "assignedToUserId">,
|
||||
ctx: FileVisibilityContext
|
||||
): Promise<boolean> {
|
||||
return withTenantRLS(file.tenantId, (tx) => isFileVisibleWithTx(tx, file, ctx));
|
||||
}
|
||||
|
||||
// Internal: load + visibility on the active transaction client (no own tx).
|
||||
async function getVisibleFileOrThrowWithTx(tx: TenantRlsClient, tenantId: string, fileId: string, ctx: FileVisibilityContext): Promise<FileRow> {
|
||||
const file = await tx.file.findFirst({ where: { id: fileId, tenantId } });
|
||||
async function getVisibleFileOrThrowWithTx(
|
||||
tx: TenantRlsClient,
|
||||
tenantId: string,
|
||||
fileId: string,
|
||||
ctx: FileVisibilityContext,
|
||||
queryState?: FileVisibilityQueryState
|
||||
): Promise<FileRow> {
|
||||
const visibility = await fileReadScopeWhereWithTx(tx, tenantId, ctx, [fileId], queryState);
|
||||
const file = await tx.file.findFirst({ where: { id: fileId, tenantId, ...visibility } });
|
||||
if (!file) {
|
||||
throw new CatalogError(foundationErrors.notFound, { fileId });
|
||||
}
|
||||
if (!(await isFileVisibleWithTx(tx, file as FileRow, ctx))) {
|
||||
throw new CatalogError(foundationErrors.notFound, { fileId });
|
||||
}
|
||||
return file as FileRow;
|
||||
}
|
||||
|
||||
@@ -482,19 +603,17 @@ export async function getVisibleFileOrThrow(tenantId: string, fileId: string, ct
|
||||
export type FileLink = { entityType: string; entityId: string; linkRole: string | null };
|
||||
|
||||
/** Load a file with its entity links (tenant-scoped + visibility), else 404. */
|
||||
export async function getVisibleFileWithLinks(
|
||||
tenantId: string,
|
||||
fileId: string,
|
||||
ctx: FileVisibilityContext,
|
||||
): Promise<{ file: FileRow; links: FileLink[] }> {
|
||||
export async function getVisibleFileWithLinks(tenantId: string, fileId: string, ctx: FileVisibilityContext): Promise<{ file: FileRow; links: FileLink[] }> {
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
const file = await getVisibleFileOrThrowWithTx(tx, tenantId, fileId, ctx);
|
||||
const queryState = createFileVisibilityQueryState();
|
||||
const file = await getVisibleFileOrThrowWithTx(tx, tenantId, fileId, ctx, queryState);
|
||||
const links = await tx.fileEntityLink.findMany({
|
||||
where: { fileId, tenantId },
|
||||
select: { entityType: true, entityId: true, linkRole: true },
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
return { file, links: links as FileLink[] };
|
||||
const visibleLinks = await filterVisibleFileLinksWithTx(tx, tenantId, links, ctx, queryState);
|
||||
return { file, links: visibleLinks };
|
||||
});
|
||||
}
|
||||
|
||||
@@ -504,52 +623,129 @@ export type ListFilesFilter = {
|
||||
tags?: readonly string[];
|
||||
assignedToUserId?: string | null;
|
||||
includeArchived?: boolean;
|
||||
/** Free-text search over the display name (case-insensitive substring). */
|
||||
q?: string | null;
|
||||
};
|
||||
|
||||
const MIME_GROUP_PREFIX: Record<string, string> = { image: "image/", pdf: "application/pdf", text: "text/" };
|
||||
const FILE_TAG_SCAN_LIMIT = 500;
|
||||
/** Rows per browser page — one screenful of grid tiles, not an endless table. */
|
||||
export const FILE_BROWSER_PAGE_SIZE = 24;
|
||||
|
||||
/**
|
||||
* List files for the browser (tenant-scoped + read_own visibility), newest
|
||||
* first, cursor-paginated. Visibility for non-read_all users: owner/assignee or
|
||||
* any linked file (v1 minimal, §7).
|
||||
*/
|
||||
export async function listFilesForBrowser(input: {
|
||||
function canListFileAssignees(ctx: FileVisibilityContext): boolean {
|
||||
return ["files.read_all", "files.admin", "app.settings.members.view"].some((permission) => ctx.permissions.includes(permission));
|
||||
}
|
||||
|
||||
export type ListFilesForBrowserInput = {
|
||||
tenantId: string;
|
||||
ctx: FileVisibilityContext;
|
||||
filter?: ListFilesFilter;
|
||||
cursor?: string | null;
|
||||
/** 1-based page of the browser listing. Out-of-range values clamp to page 1. */
|
||||
page?: number | null;
|
||||
limit?: number;
|
||||
}): Promise<{ rows: FileRow[]; nextCursor: string | null }> {
|
||||
const limit = Math.min(Math.max(input.limit ?? 50, 1), 100);
|
||||
};
|
||||
|
||||
/** Rows of one page plus what a page footer needs to say where the user is. */
|
||||
export type FileBrowserPage = { rows: FileRow[]; total: number; page: number; pageCount: number; pageSize: number };
|
||||
|
||||
function buildFileBrowserWhere(input: ListFilesForBrowserInput, visibility: Prisma.FileWhereInput): Prisma.FileWhereInput {
|
||||
const filter = input.filter ?? {};
|
||||
const mimePrefix = filter.mimeGroup ? MIME_GROUP_PREFIX[filter.mimeGroup] : undefined;
|
||||
// Build the where clause on a typed mutable object (not spread-of-union) so the
|
||||
// optional filters + visibility OR type-check cleanly against FileWhereInput.
|
||||
// Keep optional filters on a typed mutable object so they compose cleanly
|
||||
// with the central visibility scope.
|
||||
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 };
|
||||
// The search box matches what the browser actually shows — the display name.
|
||||
// A blank query is no filter at all, not a match on the empty string.
|
||||
const q = filter.q?.trim();
|
||||
if (q) where.displayName = { contains: q, mode: "insensitive" };
|
||||
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,
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: limit + 1,
|
||||
...(input.cursor ? { cursor: { id: input.cursor }, skip: 1 } : {}),
|
||||
}),
|
||||
);
|
||||
const nextCursor = rows.length > limit ? rows[limit - 1].id : null;
|
||||
return { rows: rows.slice(0, limit) as FileRow[], nextCursor };
|
||||
Object.assign(where, visibility);
|
||||
return where;
|
||||
}
|
||||
|
||||
async function listFilesForBrowserWithTx(
|
||||
tx: TenantRlsClient,
|
||||
input: ListFilesForBrowserInput,
|
||||
visibility: Prisma.FileWhereInput
|
||||
): Promise<FileBrowserPage> {
|
||||
const pageSize = Math.min(Math.max(input.limit ?? FILE_BROWSER_PAGE_SIZE, 1), 100);
|
||||
const where = buildFileBrowserWhere(input, visibility);
|
||||
const total = await tx.file.count({ where });
|
||||
const pageCount = Math.max(1, Math.ceil(total / pageSize));
|
||||
// A page number past the end (stale link, filter narrowed after paging) must
|
||||
// land on a page that exists instead of on an empty list that reads like
|
||||
// "no files".
|
||||
const requested = Math.trunc(input.page ?? 1);
|
||||
const page = Math.min(Math.max(Number.isFinite(requested) ? requested : 1, 1), pageCount);
|
||||
const rows = await tx.file.findMany({
|
||||
where,
|
||||
// `id` breaks ties: two files uploaded in the same millisecond would
|
||||
// otherwise be free to swap places between two page queries and appear
|
||||
// twice, or not at all.
|
||||
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
});
|
||||
return { rows: rows as FileRow[], total, page, pageCount, pageSize };
|
||||
}
|
||||
|
||||
/**
|
||||
* List one page of files for the browser (tenant-scoped + read_own visibility),
|
||||
* newest first. Project links only extend visibility when their target project
|
||||
* is readable under the same project and pipeline access rules.
|
||||
*/
|
||||
export async function listFilesForBrowser(input: ListFilesForBrowserInput): Promise<FileBrowserPage> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const visibility = await fileReadScopeWhereWithTx(tx, input.tenantId, input.ctx);
|
||||
return listFilesForBrowserWithTx(tx, input, visibility);
|
||||
});
|
||||
}
|
||||
|
||||
/** Ids of the files sitting next to one file in the browser's own ordering. */
|
||||
export type FileNeighbours = { previousId: string | null; nextId: string | null };
|
||||
|
||||
/**
|
||||
* The file before and after `fileId` in the browser's order (newest first, id as
|
||||
* tie-break), so the detail view can page through the library without going back
|
||||
* to the list. Same visibility scope as the browser: a neighbour the reader may
|
||||
* not open is not a neighbour. Archived files stay among their own kind — from
|
||||
* an archived file the reader pages through the archive, not into the live list.
|
||||
*/
|
||||
export async function findFileNeighbours(input: { tenantId: string; ctx: FileVisibilityContext; fileId: string }): Promise<FileNeighbours> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const visibility = await fileReadScopeWhereWithTx(tx, input.tenantId, input.ctx);
|
||||
const current = await tx.file.findFirst({
|
||||
where: { id: input.fileId, tenantId: input.tenantId, ...visibility },
|
||||
select: { id: true, createdAt: true, archivedAt: true },
|
||||
});
|
||||
if (!current) return { previousId: null, nextId: null };
|
||||
const base: Prisma.FileWhereInput = {
|
||||
tenantId: input.tenantId,
|
||||
...(current.archivedAt ? { NOT: { archivedAt: null } } : { archivedAt: null }),
|
||||
...visibility,
|
||||
};
|
||||
// Composite (createdAt, id) comparison — `createdAt` alone would skip or
|
||||
// repeat files uploaded within the same millisecond.
|
||||
const [previous, next] = await Promise.all([
|
||||
tx.file.findFirst({
|
||||
where: { ...base, OR: [{ createdAt: { gt: current.createdAt } }, { createdAt: current.createdAt, id: { gt: current.id } }] },
|
||||
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
|
||||
select: { id: true },
|
||||
}),
|
||||
tx.file.findFirst({
|
||||
where: { ...base, OR: [{ createdAt: { lt: current.createdAt } }, { createdAt: current.createdAt, id: { lt: current.id } }] },
|
||||
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
|
||||
select: { id: true },
|
||||
}),
|
||||
]);
|
||||
return { previousId: previous?.id ?? null, nextId: next?.id ?? null };
|
||||
});
|
||||
}
|
||||
|
||||
export type FileFilterOptions = {
|
||||
@@ -561,46 +757,89 @@ export type FileFilterOptions = {
|
||||
assignees: { id: string; name: string }[];
|
||||
};
|
||||
|
||||
type FileFilterRows = {
|
||||
tagRows: Array<{ tags: string[] }>;
|
||||
entityTypeRows: Array<{ entityType: string }>;
|
||||
};
|
||||
|
||||
async function loadFileFilterRowsWithTx(tx: TenantRlsClient, tenantId: string, visibility: Prisma.FileWhereInput): Promise<FileFilterRows> {
|
||||
const [tagRows, entityTypeRows] = await Promise.all([
|
||||
tx.file.findMany({
|
||||
where: { tenantId, ...visibility },
|
||||
select: { tags: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: FILE_TAG_SCAN_LIMIT,
|
||||
}),
|
||||
tx.fileEntityLink.findMany({
|
||||
where: { tenantId, file: { is: { tenantId, ...visibility } } },
|
||||
select: { entityType: true },
|
||||
distinct: ["entityType"],
|
||||
orderBy: { entityType: "asc" },
|
||||
}),
|
||||
]);
|
||||
return { tagRows, entityTypeRows };
|
||||
}
|
||||
|
||||
function buildFileFilterOptions(rows: FileFilterRows, members: Awaited<ReturnType<typeof getTenantUsers>>): FileFilterOptions {
|
||||
const tags = Array.from(new Set(rows.tagRows.flatMap((row) => row.tags))).sort((a, b) => a.localeCompare(b));
|
||||
const entityTypes = rows.entityTypeRows.map((row) => row.entityType);
|
||||
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 };
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
export async function listFileFilterOptions(input: { tenantId: string; ctx: FileVisibilityContext }): Promise<FileFilterOptions> {
|
||||
if (!input.ctx.permissions.some((permission) => ["files.read_own", "files.read_all"].includes(permission))) {
|
||||
return { entityTypes: [], tags: [], assignees: [] };
|
||||
}
|
||||
const [rows, members] = await Promise.all([
|
||||
withTenantRLS(input.tenantId, async (tx) => {
|
||||
const visibility = await fileReadScopeWhereWithTx(tx, input.tenantId, input.ctx);
|
||||
return loadFileFilterRowsWithTx(tx, input.tenantId, visibility);
|
||||
}),
|
||||
canListFileAssignees(input.ctx) ? getTenantUsers(input.tenantId) : Promise.resolve<Awaited<ReturnType<typeof getTenantUsers>>>([]),
|
||||
]);
|
||||
return buildFileFilterOptions(rows, members);
|
||||
}
|
||||
|
||||
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 };
|
||||
/**
|
||||
* Load browser rows and filter metadata from one visibility snapshot. This
|
||||
* avoids rebuilding project/file visibility independently for the two queries.
|
||||
*/
|
||||
export async function loadFileBrowserData(
|
||||
input: ListFilesForBrowserInput
|
||||
): Promise<FileBrowserPage & { filterOptions: FileFilterOptions }> {
|
||||
const canReadFiles = input.ctx.permissions.some((permission) => ["files.read_own", "files.read_all"].includes(permission));
|
||||
const [scopedData, members] = await Promise.all([
|
||||
withTenantRLS(input.tenantId, async (tx) => {
|
||||
const visibility = await fileReadScopeWhereWithTx(tx, input.tenantId, input.ctx);
|
||||
const [browser, filterRows] = await Promise.all([
|
||||
listFilesForBrowserWithTx(tx, input, visibility),
|
||||
canReadFiles ? loadFileFilterRowsWithTx(tx, input.tenantId, visibility) : Promise.resolve<FileFilterRows>({ tagRows: [], entityTypeRows: [] }),
|
||||
]);
|
||||
return { browser, filterRows };
|
||||
}),
|
||||
canReadFiles && canListFileAssignees(input.ctx) ? getTenantUsers(input.tenantId) : Promise.resolve<Awaited<ReturnType<typeof getTenantUsers>>>([]),
|
||||
]);
|
||||
return {
|
||||
...scopedData.browser,
|
||||
filterOptions: buildFileFilterOptions(scopedData.filterRows, members),
|
||||
};
|
||||
}
|
||||
|
||||
// --- Bulk ZIP -------------------------------------------------------------
|
||||
|
||||
/** Max files a single bulk-ZIP may contain (defensive bound for the in-memory zip). */
|
||||
/** Max files a single bulk-ZIP may contain. */
|
||||
export const BULK_ZIP_MAX_FILES = 50;
|
||||
/** Max total original bytes a single bulk-ZIP may pull (in-memory safety). */
|
||||
/** Max total original bytes a single bulk-ZIP may pull. */
|
||||
export const BULK_ZIP_MAX_TOTAL_BYTES = 200 * 1024 * 1024;
|
||||
export const BULK_ZIP_DOWNLOAD_CONCURRENCY = 4;
|
||||
export const BULK_ZIP_DOWNLOAD_TIMEOUT_MS = 15_000;
|
||||
|
||||
export type BulkZipEntry = { name: string; bytes: Uint8Array };
|
||||
export type BulkZipResult = {
|
||||
@@ -610,18 +849,51 @@ export type BulkZipResult = {
|
||||
skippedCount: number;
|
||||
};
|
||||
|
||||
export async function readBulkZipResponseBytes(response: Response, maxBytes: number): Promise<Uint8Array> {
|
||||
if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {
|
||||
throw new TypeError("Bulk ZIP response limit must be a non-negative safe integer.");
|
||||
}
|
||||
|
||||
const contentLength = response.headers.get("content-length");
|
||||
if (contentLength && /^\d+$/u.test(contentLength) && Number(contentLength) > maxBytes) {
|
||||
await response.body?.cancel().catch(() => undefined);
|
||||
throw new FileServiceError("files.errors.downloadFailed");
|
||||
}
|
||||
if (!response.body) {
|
||||
return new Uint8Array();
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
let totalBytes = 0;
|
||||
while (true) {
|
||||
const chunk = await reader.read();
|
||||
if (chunk.done) break;
|
||||
totalBytes += chunk.value.byteLength;
|
||||
if (totalBytes > maxBytes) {
|
||||
await reader.cancel().catch(() => undefined);
|
||||
throw new FileServiceError("files.errors.downloadFailed");
|
||||
}
|
||||
chunks.push(chunk.value);
|
||||
}
|
||||
|
||||
const bytes = new Uint8Array(totalBytes);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
bytes.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* Only files that are visible to the user AND scan-clean 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> {
|
||||
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 };
|
||||
@@ -630,43 +902,59 @@ export async function collectFilesForZip(input: {
|
||||
const where: Prisma.FileWhereInput = {
|
||||
tenantId: input.tenantId,
|
||||
id: { in: ids },
|
||||
scanStatus: { in: ["clean", "skipped"] },
|
||||
scanStatus: "clean",
|
||||
};
|
||||
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, async (tx) => {
|
||||
Object.assign(where, await fileReadScopeWhereWithTx(tx, input.tenantId, input.ctx, ids));
|
||||
return tx.file.findMany({ where, select: { id: true, displayName: true, storageKey: true, sizeBytes: true } });
|
||||
});
|
||||
|
||||
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;
|
||||
const candidates: typeof files = [];
|
||||
let reservedBytes = 0;
|
||||
let skippedCount = ids.length - files.length;
|
||||
|
||||
for (const file of files) {
|
||||
if (!file.storageKey || totalBytes + file.sizeBytes > BULK_ZIP_MAX_TOTAL_BYTES) {
|
||||
if (!file.storageKey || file.sizeBytes < 0 || reservedBytes + 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 {
|
||||
reservedBytes += file.sizeBytes;
|
||||
candidates.push(file);
|
||||
}
|
||||
|
||||
const downloaded: Array<{ file: (typeof files)[number]; bytes: Uint8Array } | null> = [];
|
||||
for (let offset = 0; offset < candidates.length; offset += BULK_ZIP_DOWNLOAD_CONCURRENCY) {
|
||||
const batch = candidates.slice(offset, offset + BULK_ZIP_DOWNLOAD_CONCURRENCY);
|
||||
downloaded.push(
|
||||
...(await Promise.all(
|
||||
batch.map(async (file) => {
|
||||
try {
|
||||
const url = await createMediaDownloadUrl({ key: file.storageKey! });
|
||||
const response = await fetch(url, {
|
||||
redirect: "error",
|
||||
signal: AbortSignal.timeout(BULK_ZIP_DOWNLOAD_TIMEOUT_MS),
|
||||
});
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel().catch(() => undefined);
|
||||
return null;
|
||||
}
|
||||
return { file, bytes: await readBulkZipResponseBytes(response, file.sizeBytes) };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
const usedNames = new Set<string>();
|
||||
const entries: BulkZipEntry[] = [];
|
||||
for (const result of downloaded) {
|
||||
if (!result) {
|
||||
skippedCount += 1;
|
||||
continue;
|
||||
}
|
||||
entries.push({ name: uniqueZipName(result.file.displayName, usedNames), bytes: result.bytes });
|
||||
}
|
||||
|
||||
return { entries, skippedCount };
|
||||
@@ -701,14 +989,12 @@ export async function linkFile(input: {
|
||||
entityType: FileEntityType;
|
||||
entityId: string;
|
||||
linkRole?: string | null;
|
||||
ctx: FileVisibilityContext;
|
||||
}): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
// Ensure the file belongs to the tenant before linking.
|
||||
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.fileEntityLink.upsert({
|
||||
await getVisibleFileOrThrowWithTx(tx, input.tenantId, input.fileId, input.ctx);
|
||||
await assertFileLinkTargetVisibleWithTx(tx, input.tenantId, input.entityType, input.entityId, input.ctx);
|
||||
const link = await tx.fileEntityLink.upsert({
|
||||
where: { fileId_entityType_entityId: { fileId: input.fileId, entityType: input.entityType, entityId: input.entityId } },
|
||||
update: { linkRole: input.linkRole ?? null },
|
||||
create: {
|
||||
@@ -719,16 +1005,51 @@ export async function linkFile(input: {
|
||||
entityId: input.entityId,
|
||||
linkRole: input.linkRole ?? null,
|
||||
},
|
||||
select: { id: true, createdAt: true },
|
||||
});
|
||||
if (input.entityType === "project") {
|
||||
const readyInternalFile = await tx.file.findFirst({
|
||||
where: {
|
||||
id: input.fileId,
|
||||
tenantId: input.tenantId,
|
||||
archivedAt: null,
|
||||
scanStatus: "clean",
|
||||
createdByPortalUserId: null,
|
||||
source: { not: "customer_portal" },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
if (readyInternalFile) {
|
||||
await publishOutboxEvent(
|
||||
tx as unknown as OutboxPublisherTransaction,
|
||||
buildPortalDocumentReadyOutboxEvent({
|
||||
tenantId: input.tenantId,
|
||||
projectId: input.entityId,
|
||||
fileId: input.fileId,
|
||||
fileEntityLinkId: link.id,
|
||||
linkVersion: link.createdAt,
|
||||
userId: input.userId,
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function unlinkFile(input: { tenantId: string; fileId: string; entityType: FileEntityType; entityId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.fileEntityLink.deleteMany({
|
||||
export async function unlinkFile(input: {
|
||||
tenantId: string;
|
||||
fileId: string;
|
||||
entityType: FileEntityType;
|
||||
entityId: string;
|
||||
ctx: FileVisibilityContext;
|
||||
}): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
await getVisibleFileOrThrowWithTx(tx, input.tenantId, input.fileId, input.ctx);
|
||||
await assertFileLinkTargetVisibleWithTx(tx, input.tenantId, input.entityType, input.entityId, input.ctx);
|
||||
await tx.fileEntityLink.deleteMany({
|
||||
where: { tenantId: input.tenantId, fileId: input.fileId, entityType: input.entityType, entityId: input.entityId },
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function archiveFile(input: { tenantId: string; fileId: string }): Promise<void> {
|
||||
@@ -783,7 +1104,7 @@ export async function regenerateFilePreview(input: { tenantId: string; fileId: s
|
||||
const file = await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const row = await tx.file.findFirst({
|
||||
where: { id: input.fileId, tenantId: input.tenantId },
|
||||
select: { id: true, storageKey: true, mimeType: true, previewStatus: true },
|
||||
select: { id: true, storageKey: true, mimeType: true, previewStatus: true, scanStatus: true },
|
||||
});
|
||||
if (!row) {
|
||||
throw new CatalogError(foundationErrors.notFound, { fileId: input.fileId });
|
||||
@@ -791,12 +1112,25 @@ export async function regenerateFilePreview(input: { tenantId: string; fileId: s
|
||||
if (row.previewStatus !== "failed") {
|
||||
throw new FileServiceError("files.error.previewNotRegenerable");
|
||||
}
|
||||
if (row.scanStatus !== "clean") {
|
||||
throw new FileServiceError("files.error.previewNotRegenerable");
|
||||
}
|
||||
await tx.file.update({ where: { id: row.id }, data: { previewStatus: "pending" } });
|
||||
return row;
|
||||
});
|
||||
const bucket = resolveStorageBucket();
|
||||
// Enqueue stays OUTSIDE the RLS transaction.
|
||||
await enqueueFilePreview({ fileId: file.id, tenantId: input.tenantId, bucket, storageKey: file.storageKey, mimeType: file.mimeType }).catch(() => {});
|
||||
try {
|
||||
const result = await enqueueFilePreview({ fileId: file.id, tenantId: input.tenantId, bucket, storageKey: file.storageKey, mimeType: file.mimeType });
|
||||
if (!result.enqueued) {
|
||||
throw new Error("File preview queue is unavailable");
|
||||
}
|
||||
} catch {
|
||||
await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.file.updateMany({ where: { id: file.id, tenantId: input.tenantId, previewStatus: "pending" }, data: { previewStatus: "failed" } })
|
||||
).catch(() => {});
|
||||
throw new FileServiceError("files.error.previewNotRegenerable");
|
||||
}
|
||||
}
|
||||
|
||||
export async function hardDeleteFile(input: { tenantId: string; fileId: string }): Promise<void> {
|
||||
@@ -804,7 +1138,7 @@ export async function hardDeleteFile(input: { tenantId: string; fileId: string }
|
||||
tx.file.findFirst({
|
||||
where: { id: input.fileId, tenantId: input.tenantId },
|
||||
select: { id: true, storageKey: true, previewStorageKey: true, thumbnailStorageKey: true },
|
||||
}),
|
||||
})
|
||||
);
|
||||
if (!file) {
|
||||
throw new CatalogError(foundationErrors.notFound, { fileId: input.fileId });
|
||||
@@ -813,7 +1147,11 @@ export async function hardDeleteFile(input: { tenantId: string; fileId: string }
|
||||
// S3 deletes stay OUTSIDE the RLS transaction.
|
||||
for (const key of [file.storageKey, file.previewStorageKey, file.thumbnailStorageKey]) {
|
||||
if (key) {
|
||||
await deleteFile({ bucket, key }).catch(() => {});
|
||||
// Keep the database row (and therefore the tenant's quota accounting)
|
||||
// until every durable object has been removed. S3 deletes are
|
||||
// idempotent, so a failed request can safely be retried without leaving
|
||||
// an untracked, still-billable object behind.
|
||||
await deleteFile({ bucket, key });
|
||||
}
|
||||
}
|
||||
// FileEntityLink rows cascade on File delete (schema onDelete: Cascade).
|
||||
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveRepoPath } from "~/utils/testing/repoPaths";
|
||||
|
||||
const fileService = readFileSync(resolveRepoPath("apps/web/app/utils/integrations/fileService.server.ts"), "utf8");
|
||||
const searchService = readFileSync(resolveRepoPath("apps/web/app/services/search/globalSearch.server.ts"), "utf8");
|
||||
const mediaRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/media.$fileId.$variant.tsx"), "utf8");
|
||||
const browserRoute = readFileSync(resolveRepoPath("apps/web/app/routes/app.$tenant/files._index.tsx"), "utf8");
|
||||
|
||||
function section(source: string, start: string, end: string): string {
|
||||
return source.split(start)[1]?.split(end)[0] ?? "";
|
||||
}
|
||||
|
||||
describe("central file visibility boundary", () => {
|
||||
it("routes detail visibility through the authoritative scope without owner/read_all fast paths", () => {
|
||||
const detailGuard = section(fileService, "async function getVisibleFileOrThrowWithTx", "/** Load a single file");
|
||||
|
||||
expect(detailGuard).toContain("fileReadScopeWhereWithTx(tx, tenantId, ctx, [fileId], queryState)");
|
||||
expect(detailGuard.match(/tx\.file\.findFirst/g)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("shares one project-principal query state across detail and linked-target visibility", () => {
|
||||
const linkedDetail = section(fileService, "export async function getVisibleFileWithLinks", "export type ListFilesFilter");
|
||||
|
||||
expect(linkedDetail).toContain("const queryState = createFileVisibilityQueryState()");
|
||||
expect(linkedDetail).toContain("getVisibleFileOrThrowWithTx(tx, tenantId, fileId, ctx, queryState)");
|
||||
expect(linkedDetail).toContain("filterVisibleFileLinksWithTx(tx, tenantId, links, ctx, queryState)");
|
||||
});
|
||||
|
||||
it("routes the browser rows and filter metadata through the same scope", () => {
|
||||
const browser = section(fileService, "export async function loadFileBrowserData", "// --- Bulk ZIP");
|
||||
|
||||
expect(browser.match(/fileReadScopeWhereWithTx\(tx, input\.tenantId, input\.ctx\)/g)).toHaveLength(1);
|
||||
expect(browser).toContain("listFilesForBrowserWithTx(tx, input, visibility)");
|
||||
expect(browser).toContain("loadFileFilterRowsWithTx(tx, input.tenantId, visibility)");
|
||||
expect(browserRoute).toContain("await loadFileBrowserData({");
|
||||
expect(browserRoute).not.toContain("listFileFilterOptions");
|
||||
});
|
||||
|
||||
it("routes bulk ZIP candidate selection through the same scope", () => {
|
||||
const bulkZip = section(fileService, "export async function collectFilesForZip", "/** Ensure a zip entry name is unique");
|
||||
|
||||
expect(bulkZip).toContain("fileReadScopeWhereWithTx(tx, input.tenantId, input.ctx, ids)");
|
||||
});
|
||||
|
||||
it("routes SQL search and Meilisearch revalidation through the same scope", () => {
|
||||
const sqlFiles = section(searchService, "async function searchFiles", "type TaskVisibilityCondition");
|
||||
const revalidation = section(searchService, 'case "file": {', 'case "task": {');
|
||||
|
||||
expect(sqlFiles).toContain("fileReadScopeWhereWithTx(database, ctx.tenantId, ctx)");
|
||||
expect(revalidation).toContain("fileReadScopeWhereWithTx(input.database, input.ctx.tenantId, input.ctx, ids)");
|
||||
});
|
||||
|
||||
it("requires the visibility-checked file loader before media signing", () => {
|
||||
const visibility = mediaRoute.indexOf("await getVisibleFileOrThrow(ctx.tenantId, fileId, ctx)");
|
||||
const signing = mediaRoute.indexOf("await createMediaDownloadUrl");
|
||||
|
||||
expect(visibility).toBeGreaterThan(-1);
|
||||
expect(signing).toBeGreaterThan(visibility);
|
||||
});
|
||||
});
|
||||
+693
@@ -0,0 +1,693 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
import {
|
||||
assertFileLinkTargetVisibleWithTx,
|
||||
createFileVisibilityQueryState,
|
||||
fileReadScopeWhereWithTx,
|
||||
filterVisibleFileLinksWithTx,
|
||||
type FileVisibilityContext,
|
||||
} from "./fileVisibility.server";
|
||||
import type { FileEntityType } from "./fileService.server";
|
||||
|
||||
function transaction() {
|
||||
return {
|
||||
fileEntityLink: { findMany: vi.fn() },
|
||||
projekt: { findMany: vi.fn(), findFirst: vi.fn() },
|
||||
kontakt: { findFirst: vi.fn(), findMany: vi.fn() },
|
||||
inboxLead: { findFirst: vi.fn(), findMany: vi.fn() },
|
||||
tenantUser: { findFirst: vi.fn(), findMany: vi.fn() },
|
||||
formSubmission: { findFirst: vi.fn(), findMany: vi.fn() },
|
||||
task: { findFirst: vi.fn(), findMany: vi.fn() },
|
||||
appointment: { findFirst: vi.fn(), findMany: vi.fn() },
|
||||
projektSignatureDocument: { findFirst: vi.fn(), findMany: vi.fn() },
|
||||
userRole: { findMany: vi.fn() },
|
||||
groupUser: { findMany: vi.fn() },
|
||||
projektMitglied: { findMany: vi.fn() },
|
||||
teamChatMessage: { findMany: vi.fn(), findFirst: vi.fn() },
|
||||
};
|
||||
}
|
||||
|
||||
describe("fileReadScopeWhereWithTx", () => {
|
||||
const ownUserLink = {
|
||||
links: { some: { tenantId: "tenant_1", entityType: "user", entityId: "user_1" } },
|
||||
};
|
||||
const nonForeignHrLink = {
|
||||
links: { none: { tenantId: "tenant_1", entityType: "user", entityId: { not: "user_1" } } },
|
||||
};
|
||||
|
||||
it("does not treat an arbitrary in-tenant entity link as files.read_own access", async () => {
|
||||
const tx = transaction();
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: ["files.read_own"] };
|
||||
|
||||
await expect(fileReadScopeWhereWithTx(tx as never, "tenant_1", ctx, ["file_1"])).resolves.toEqual({
|
||||
AND: [{ OR: [{ createdByUserId: "user_1" }, { assignedToUserId: "user_1" }, ownUserLink] }, nonForeignHrLink],
|
||||
});
|
||||
expect(tx.fileEntityLink.findMany).not.toHaveBeenCalled();
|
||||
expect(tx.projekt.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("transitively authorizes only links to projects visible through membership and PipelineAccess", async () => {
|
||||
const tx = transaction();
|
||||
tx.fileEntityLink.findMany.mockResolvedValue([{ entityId: "project_visible" }, { entityId: "project_denied" }]);
|
||||
tx.projekt.findMany.mockResolvedValue([{ id: "project_visible" }]);
|
||||
const ctx: FileVisibilityContext = {
|
||||
userId: "user_1",
|
||||
permissions: ["files.read_own", "projects.read_own_member"],
|
||||
roleIds: ["role_1"],
|
||||
groupIds: ["group_1"],
|
||||
};
|
||||
|
||||
await expect(fileReadScopeWhereWithTx(tx as never, "tenant_1", ctx, ["file_1"])).resolves.toEqual({
|
||||
AND: [
|
||||
{
|
||||
OR: [
|
||||
{ createdByUserId: "user_1" },
|
||||
{ assignedToUserId: "user_1" },
|
||||
{
|
||||
links: {
|
||||
some: {
|
||||
tenantId: "tenant_1",
|
||||
entityType: "project",
|
||||
entityId: { in: ["project_visible"] },
|
||||
},
|
||||
},
|
||||
},
|
||||
ownUserLink,
|
||||
],
|
||||
},
|
||||
nonForeignHrLink,
|
||||
],
|
||||
});
|
||||
expect(tx.fileEntityLink.findMany).toHaveBeenCalledWith({
|
||||
where: { tenantId: "tenant_1", entityType: "project", fileId: { in: ["file_1"] } },
|
||||
select: { entityId: true },
|
||||
distinct: ["entityId"],
|
||||
});
|
||||
expect(tx.projekt.findMany.mock.calls[0]?.[0].where).toEqual({
|
||||
tenantId: "tenant_1",
|
||||
id: { in: ["project_visible", "project_denied"] },
|
||||
archivedAt: null,
|
||||
AND: [
|
||||
{
|
||||
OR: [
|
||||
{
|
||||
mitglieder: {
|
||||
some: {
|
||||
tenantId: "tenant_1",
|
||||
archivedAt: null,
|
||||
OR: [{ userId: "user_1" }, { groupId: { in: ["group_1"] } }],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
pipeline: {
|
||||
accessRules: {
|
||||
none: {
|
||||
tenantId: "tenant_1",
|
||||
kannSehen: false,
|
||||
OR: [
|
||||
{ principalType: "user", principalId: "user_1" },
|
||||
{ principalType: "role", principalId: "role_1" },
|
||||
{ principalType: "group", principalId: "group_1" },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps foreign user-linked HR files hidden even for files.read_all", async () => {
|
||||
const tx = transaction();
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: ["files.read_all"] };
|
||||
|
||||
await expect(fileReadScopeWhereWithTx(tx as never, "tenant_1", ctx)).resolves.toEqual(nonForeignHrLink);
|
||||
expect(tx.fileEntityLink.findMany).not.toHaveBeenCalled();
|
||||
expect(tx.projekt.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps PipelineAccess deny filtering when project permission is read_all", async () => {
|
||||
const tx = transaction();
|
||||
tx.projekt.findMany.mockResolvedValue([]);
|
||||
const ctx: FileVisibilityContext = {
|
||||
userId: "user_1",
|
||||
permissions: ["files.read_own", "projects.read_all"],
|
||||
roleIds: ["role_1"],
|
||||
groupIds: ["group_1"],
|
||||
};
|
||||
|
||||
await expect(fileReadScopeWhereWithTx(tx as never, "tenant_1", ctx)).resolves.toEqual({
|
||||
AND: [{ OR: [{ createdByUserId: "user_1" }, { assignedToUserId: "user_1" }, ownUserLink] }, nonForeignHrLink],
|
||||
});
|
||||
expect(tx.projekt.findMany.mock.calls[0]?.[0].where).toEqual({
|
||||
tenantId: "tenant_1",
|
||||
archivedAt: null,
|
||||
pipeline: {
|
||||
accessRules: {
|
||||
none: {
|
||||
tenantId: "tenant_1",
|
||||
kannSehen: false,
|
||||
OR: [
|
||||
{ principalType: "user", principalId: "user_1" },
|
||||
{ principalType: "role", principalId: "role_1" },
|
||||
{ principalType: "group", principalId: "group_1" },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(tx.fileEntityLink.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("hydrates project principals only when a project-linked file scope needs them", async () => {
|
||||
const tx = transaction();
|
||||
tx.fileEntityLink.findMany.mockResolvedValue([{ entityId: "project_1" }]);
|
||||
tx.userRole.findMany.mockResolvedValue([{ roleId: "role_1" }]);
|
||||
tx.groupUser.findMany.mockResolvedValue([{ groupId: "group_1" }]);
|
||||
tx.projekt.findMany.mockResolvedValue([{ id: "project_1" }]);
|
||||
const ctx: FileVisibilityContext = {
|
||||
userId: "user_1",
|
||||
permissions: ["files.read_own", "projects.read_own_member"],
|
||||
};
|
||||
|
||||
await fileReadScopeWhereWithTx(tx as never, "tenant_1", ctx, ["file_1"]);
|
||||
|
||||
expect(tx.userRole.findMany).toHaveBeenCalledWith({
|
||||
where: { tenantId: "tenant_1", userId: "user_1" },
|
||||
select: { roleId: true },
|
||||
});
|
||||
expect(tx.groupUser.findMany).toHaveBeenCalledWith({
|
||||
where: { userId: "user_1", group: { tenantId: "tenant_1" } },
|
||||
select: { groupId: true },
|
||||
});
|
||||
expect(tx.projektMitglied.findMany).not.toHaveBeenCalled();
|
||||
expect(tx.projekt.findMany.mock.calls[0]?.[0].where.AND[0]).toEqual({
|
||||
OR: [
|
||||
{
|
||||
mitglieder: {
|
||||
some: {
|
||||
tenantId: "tenant_1",
|
||||
archivedAt: null,
|
||||
OR: [{ userId: "user_1" }, { groupId: { in: ["group_1"] } }],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(JSON.stringify(tx.projekt.findMany.mock.calls[0]?.[0]?.where)).toContain('"principalId":"role_1"');
|
||||
});
|
||||
|
||||
it.each(["hr.read_all", "hr.admin"])("allows tenant-wide HR readers through the user-link override via %s", async (permission) => {
|
||||
const tx = transaction();
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: ["files.read_all", permission] };
|
||||
|
||||
await expect(fileReadScopeWhereWithTx(tx as never, "tenant_1", ctx)).resolves.toEqual({});
|
||||
expect(tx.fileEntityLink.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["files.write", "files.admin"])("does not infer a read grant from %s", async (permission) => {
|
||||
const tx = transaction();
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: [permission] };
|
||||
|
||||
await expect(fileReadScopeWhereWithTx(tx as never, "tenant_1", ctx)).resolves.toEqual({ id: { in: [] } });
|
||||
});
|
||||
|
||||
it("does not infer the HR override from hr.write", async () => {
|
||||
const tx = transaction();
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: ["files.read_all", "hr.write"] };
|
||||
|
||||
await expect(fileReadScopeWhereWithTx(tx as never, "tenant_1", ctx)).resolves.toEqual(nonForeignHrLink);
|
||||
});
|
||||
|
||||
it("fails closed without any effective Files read permission", async () => {
|
||||
const tx = transaction();
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: ["hr.admin"] };
|
||||
|
||||
await expect(fileReadScopeWhereWithTx(tx as never, "tenant_1", ctx, ["file_1"])).resolves.toEqual({ id: { in: [] } });
|
||||
expect(tx.fileEntityLink.findMany).not.toHaveBeenCalled();
|
||||
expect(tx.projekt.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not let an own user link or HR privilege replace a Files read permission", async () => {
|
||||
const tx = transaction();
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: ["files.write", "hr.admin"] };
|
||||
|
||||
await expect(fileReadScopeWhereWithTx(tx as never, "tenant_1", ctx, ["own_hr_file"])).resolves.toEqual({ id: { in: [] } });
|
||||
expect(tx.fileEntityLink.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("grants only attachment files linked to messages in the caller's active chats", async () => {
|
||||
const tx = transaction();
|
||||
tx.fileEntityLink.findMany.mockResolvedValue([{ entityId: "message_visible" }, { entityId: "message_hidden" }]);
|
||||
tx.teamChatMessage.findMany.mockResolvedValue([{ id: "message_visible" }]);
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: ["chat.read_own_channels"] };
|
||||
|
||||
await expect(fileReadScopeWhereWithTx(tx as never, "tenant_1", ctx, ["file_1"])).resolves.toEqual({
|
||||
AND: [
|
||||
{
|
||||
OR: [
|
||||
{
|
||||
links: {
|
||||
some: {
|
||||
tenantId: "tenant_1",
|
||||
entityType: "chat_message",
|
||||
entityId: { in: ["message_visible"] },
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
nonForeignHrLink,
|
||||
],
|
||||
});
|
||||
expect(tx.teamChatMessage.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
tenantId: "tenant_1",
|
||||
id: { in: ["message_visible", "message_hidden"] },
|
||||
chat: { tenantId: "tenant_1", members: { some: { tenantId: "tenant_1", userId: "user_1", leftAt: null } } },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("does not turn chat.read_all_channels into an unaudited Files download bypass", async () => {
|
||||
const tx = transaction();
|
||||
tx.fileEntityLink.findMany.mockResolvedValue([{ entityId: "message_visible" }, { entityId: "message_foreign" }]);
|
||||
tx.teamChatMessage.findMany.mockResolvedValue([{ id: "message_visible" }]);
|
||||
const ctx: FileVisibilityContext = { userId: "admin_1", permissions: ["chat.read_all_channels"] };
|
||||
|
||||
await fileReadScopeWhereWithTx(tx as never, "tenant_1", ctx, ["file_1"]);
|
||||
|
||||
expect(tx.teamChatMessage.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
tenantId: "tenant_1",
|
||||
id: { in: ["message_visible", "message_foreign"] },
|
||||
chat: { tenantId: "tenant_1", members: { some: { tenantId: "tenant_1", userId: "admin_1", leftAt: null } } },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterVisibleFileLinksWithTx", () => {
|
||||
it("filters audit administrators' chat links by ordinary active membership", async () => {
|
||||
const tx = transaction();
|
||||
tx.teamChatMessage.findMany.mockResolvedValue([{ id: "message_member" }]);
|
||||
const links = [
|
||||
{ entityType: "chat_message" as const, entityId: "message_member", linkRole: "visible" },
|
||||
{ entityType: "chat_message" as const, entityId: "message_foreign", linkRole: "hidden" },
|
||||
];
|
||||
|
||||
await expect(
|
||||
filterVisibleFileLinksWithTx(tx as never, "tenant_1", links, {
|
||||
userId: "admin_1",
|
||||
permissions: ["chat.read_all_channels"],
|
||||
})
|
||||
).resolves.toEqual([links[0]]);
|
||||
|
||||
expect(tx.teamChatMessage.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: { in: ["message_member", "message_foreign"] },
|
||||
tenantId: "tenant_1",
|
||||
chat: { tenantId: "tenant_1", members: { some: { tenantId: "tenant_1", userId: "admin_1", leftAt: null } } },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("batches each target type, preserves source order, and fails unknown targets closed", async () => {
|
||||
const tx = transaction();
|
||||
tx.kontakt.findMany.mockImplementation(async ({ where }: { where: { kontaktTyp: string } }) =>
|
||||
where.kontaktTyp === "privatperson" ? [{ id: "contact_visible" }] : [{ id: "company_visible" }]
|
||||
);
|
||||
tx.inboxLead.findMany.mockResolvedValue([{ id: "lead_visible" }]);
|
||||
tx.tenantUser.findMany.mockResolvedValue([{ userId: "user_1" }]);
|
||||
tx.formSubmission.findMany.mockResolvedValue([{ id: "submission_visible" }]);
|
||||
tx.task.findMany.mockResolvedValue([{ id: "task_visible" }]);
|
||||
tx.appointment.findMany.mockResolvedValue([{ id: "appointment_visible" }]);
|
||||
const links = [
|
||||
{ entityType: "task", entityId: "task_visible", linkRole: "first" },
|
||||
{ entityType: "contact", entityId: "contact_hidden", linkRole: "hidden" },
|
||||
{ entityType: "company", entityId: "company_visible", linkRole: "second" },
|
||||
{ entityType: "email_message", entityId: "message_unknown", linkRole: "unknown" },
|
||||
{ entityType: "contact", entityId: "contact_visible", linkRole: "third" },
|
||||
{ entityType: "lead", entityId: "lead_visible", linkRole: "fourth" },
|
||||
{ entityType: "user", entityId: "user_1", linkRole: "fifth" },
|
||||
{ entityType: "form_submission", entityId: "submission_visible", linkRole: "sixth" },
|
||||
{ entityType: "appointment", entityId: "appointment_visible", linkRole: "seventh" },
|
||||
{ entityType: "contact", entityId: "contact_visible", linkRole: "duplicate" },
|
||||
];
|
||||
const ctx: FileVisibilityContext = {
|
||||
userId: "user_1",
|
||||
permissions: ["crm.read_all", "leads.read_all", "tasks.read_all", "forms.admin", "bookings.read_all"],
|
||||
groupIds: [],
|
||||
};
|
||||
|
||||
await expect(filterVisibleFileLinksWithTx(tx as never, "tenant_1", links, ctx)).resolves.toEqual([
|
||||
links[0],
|
||||
links[2],
|
||||
links[4],
|
||||
links[5],
|
||||
links[6],
|
||||
links[7],
|
||||
links[8],
|
||||
links[9],
|
||||
]);
|
||||
expect(tx.kontakt.findMany).toHaveBeenCalledTimes(2);
|
||||
expect(tx.inboxLead.findMany).toHaveBeenCalledTimes(1);
|
||||
expect(tx.tenantUser.findMany).toHaveBeenCalledTimes(1);
|
||||
expect(tx.formSubmission.findMany).toHaveBeenCalledTimes(1);
|
||||
expect(tx.task.findMany).toHaveBeenCalledTimes(1);
|
||||
expect(tx.appointment.findMany).toHaveBeenCalledTimes(1);
|
||||
expect(tx.groupUser.findMany).not.toHaveBeenCalled();
|
||||
expect(tx.projekt.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("hydrates project principals once and checks project aliases plus signatures in one project batch", async () => {
|
||||
const tx = transaction();
|
||||
tx.userRole.findMany.mockResolvedValue([{ roleId: "role_1" }]);
|
||||
tx.groupUser.findMany.mockResolvedValue([{ groupId: "group_1" }]);
|
||||
tx.projektSignatureDocument.findMany.mockResolvedValue([
|
||||
{ id: "signature_visible", projektId: "signature_project_visible" },
|
||||
{ id: "signature_hidden", projektId: "signature_project_hidden" },
|
||||
]);
|
||||
tx.projekt.findMany.mockResolvedValue([{ id: "project_visible" }, { id: "deal_visible" }, { id: "signature_project_visible" }]);
|
||||
const links = [
|
||||
{ entityType: "signature_document", entityId: "signature_visible", linkRole: null },
|
||||
{ entityType: "order", entityId: "order_hidden", linkRole: null },
|
||||
{ entityType: "deal", entityId: "deal_visible", linkRole: null },
|
||||
{ entityType: "signature_document", entityId: "signature_hidden", linkRole: null },
|
||||
{ entityType: "project", entityId: "project_visible", linkRole: null },
|
||||
];
|
||||
const ctx: FileVisibilityContext = {
|
||||
userId: "user_1",
|
||||
permissions: ["projects.read_own_member", "signature.read"],
|
||||
};
|
||||
|
||||
await expect(filterVisibleFileLinksWithTx(tx as never, "tenant_1", links, ctx)).resolves.toEqual([links[0], links[2], links[4]]);
|
||||
expect(tx.userRole.findMany).toHaveBeenCalledTimes(1);
|
||||
expect(tx.groupUser.findMany).toHaveBeenCalledTimes(1);
|
||||
expect(tx.projektMitglied.findMany).not.toHaveBeenCalled();
|
||||
expect(tx.projektSignatureDocument.findMany).toHaveBeenCalledTimes(1);
|
||||
expect(tx.projekt.findMany).toHaveBeenCalledTimes(1);
|
||||
expect(tx.projekt.findMany.mock.calls[0]?.[0]).not.toHaveProperty("take");
|
||||
expect(tx.projekt.findMany.mock.calls[0]?.[0].where.id.in).toEqual([
|
||||
"project_visible",
|
||||
"deal_visible",
|
||||
"order_hidden",
|
||||
"signature_project_visible",
|
||||
"signature_project_hidden",
|
||||
]);
|
||||
});
|
||||
|
||||
it("reuses project principals between file scope and detail-link filtering", async () => {
|
||||
const tx = transaction();
|
||||
tx.fileEntityLink.findMany.mockResolvedValue([{ entityId: "project_visible" }]);
|
||||
tx.userRole.findMany.mockResolvedValue([{ roleId: "role_1" }]);
|
||||
tx.groupUser.findMany.mockResolvedValue([{ groupId: "group_1" }]);
|
||||
tx.projekt.findMany.mockResolvedValue([{ id: "project_visible" }]);
|
||||
const ctx: FileVisibilityContext = {
|
||||
userId: "user_1",
|
||||
permissions: ["files.read_own", "projects.read_own_member"],
|
||||
};
|
||||
const queryState = createFileVisibilityQueryState();
|
||||
|
||||
await fileReadScopeWhereWithTx(tx as never, "tenant_1", ctx, ["file_1"], queryState);
|
||||
await filterVisibleFileLinksWithTx(tx as never, "tenant_1", [{ entityType: "project", entityId: "project_visible", linkRole: null }], ctx, queryState);
|
||||
|
||||
expect(tx.userRole.findMany).toHaveBeenCalledTimes(1);
|
||||
expect(tx.groupUser.findMany).toHaveBeenCalledTimes(1);
|
||||
expect(tx.projektMitglied.findMany).not.toHaveBeenCalled();
|
||||
expect(tx.projekt.findMany).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("does not truncate a large set of links", async () => {
|
||||
const tx = transaction();
|
||||
const links = Array.from({ length: 600 }, (_, index) => ({
|
||||
entityType: "contact",
|
||||
entityId: `contact_${index}`,
|
||||
linkRole: index % 2 === 0 ? "primary" : null,
|
||||
}));
|
||||
tx.kontakt.findMany.mockResolvedValue(links.map(({ entityId }) => ({ id: entityId })));
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: ["crm.read_all"] };
|
||||
|
||||
const result = await filterVisibleFileLinksWithTx(tx as never, "tenant_1", links, ctx);
|
||||
|
||||
expect(result).toEqual(links);
|
||||
expect(tx.kontakt.findMany).toHaveBeenCalledTimes(1);
|
||||
expect(tx.kontakt.findMany.mock.calls[0]?.[0]).not.toHaveProperty("take");
|
||||
expect(tx.kontakt.findMany.mock.calls[0]?.[0].where.id.in).toHaveLength(600);
|
||||
});
|
||||
|
||||
it("does not keep a reassigned contact visible to its creator", async () => {
|
||||
const tx = transaction();
|
||||
tx.kontakt.findMany.mockResolvedValue([]);
|
||||
const link = { entityType: "contact", entityId: "contact_reassigned", linkRole: null };
|
||||
const ctx: FileVisibilityContext = { userId: "former_creator", permissions: ["crm.read_own"] };
|
||||
|
||||
await expect(filterVisibleFileLinksWithTx(tx as never, "tenant_1", [link], ctx)).resolves.toEqual([]);
|
||||
expect(tx.kontakt.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: { in: ["contact_reassigned"] },
|
||||
tenantId: "tenant_1",
|
||||
archivedAt: null,
|
||||
kontaktTyp: "privatperson",
|
||||
zustaendigerUserId: "former_creator",
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("assertFileLinkTargetVisibleWithTx", () => {
|
||||
const projectContext: FileVisibilityContext = {
|
||||
userId: "user_1",
|
||||
permissions: ["projects.read_own_member"],
|
||||
roleIds: ["role_1"],
|
||||
groupIds: ["group_1"],
|
||||
};
|
||||
|
||||
it.each(["project", "deal", "order"] as const)("uses the central project and PipelineAccess scope for %s targets", async (entityType) => {
|
||||
const tx = transaction();
|
||||
tx.projekt.findFirst.mockResolvedValue({ id: "project_1" });
|
||||
|
||||
await expect(assertFileLinkTargetVisibleWithTx(tx as never, "tenant_1", entityType, "project_1", projectContext)).resolves.toBeUndefined();
|
||||
expect(tx.projekt.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: "project_1",
|
||||
tenantId: "tenant_1",
|
||||
archivedAt: null,
|
||||
AND: [
|
||||
{
|
||||
OR: [
|
||||
{
|
||||
mitglieder: {
|
||||
some: {
|
||||
tenantId: "tenant_1",
|
||||
archivedAt: null,
|
||||
OR: [{ userId: "user_1" }, { groupId: { in: ["group_1"] } }],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
pipeline: {
|
||||
accessRules: {
|
||||
none: {
|
||||
tenantId: "tenant_1",
|
||||
kannSehen: false,
|
||||
OR: [
|
||||
{ principalType: "user", principalId: "user_1" },
|
||||
{ principalType: "role", principalId: "role_1" },
|
||||
{ principalType: "group", principalId: "group_1" },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["contact", "privatperson"],
|
||||
["company", "organisation"],
|
||||
] as const)("requires current CRM assignment and the correct discriminator for %s targets", async (entityType, kontaktTyp) => {
|
||||
const tx = transaction();
|
||||
tx.kontakt.findFirst.mockResolvedValue({ id: "contact_1" });
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: ["crm.read_own"] };
|
||||
|
||||
await expect(assertFileLinkTargetVisibleWithTx(tx as never, "tenant_1", entityType, "contact_1", ctx)).resolves.toBeUndefined();
|
||||
expect(tx.kontakt.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: "contact_1",
|
||||
tenantId: "tenant_1",
|
||||
archivedAt: null,
|
||||
kontaktTyp,
|
||||
zustaendigerUserId: "user_1",
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("enforces lead owner visibility", async () => {
|
||||
const tx = transaction();
|
||||
tx.inboxLead.findFirst.mockResolvedValue({ id: "lead_1" });
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: ["leads.read_own"] };
|
||||
|
||||
await expect(assertFileLinkTargetVisibleWithTx(tx as never, "tenant_1", "lead", "lead_1", ctx)).resolves.toBeUndefined();
|
||||
expect(tx.inboxLead.findFirst).toHaveBeenCalledWith({
|
||||
where: { id: "lead_1", tenantId: "tenant_1", archivedAt: null, zustaendigerUserId: "user_1" },
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("enforces task owner, watcher, assignee, and tenant-group visibility", async () => {
|
||||
const tx = transaction();
|
||||
tx.task.findFirst.mockResolvedValue({ id: "task_1" });
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: ["tasks.read_own"], groupIds: ["group_1"] };
|
||||
|
||||
await expect(assertFileLinkTargetVisibleWithTx(tx as never, "tenant_1", "task", "task_1", ctx)).resolves.toBeUndefined();
|
||||
expect(tx.task.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: "task_1",
|
||||
tenantId: "tenant_1",
|
||||
archivedAt: null,
|
||||
OR: [
|
||||
{ createdByUserId: "user_1" },
|
||||
{ assignedToUserId: "user_1" },
|
||||
{ watchers: { some: { tenantId: "tenant_1", userId: "user_1" } } },
|
||||
{ assignedToGroupId: { in: ["group_1"] } },
|
||||
],
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("allows linking to the caller's own active tenant membership", async () => {
|
||||
const tx = transaction();
|
||||
tx.tenantUser.findFirst.mockResolvedValue({ id: "membership_1" });
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: [] };
|
||||
|
||||
await expect(assertFileLinkTargetVisibleWithTx(tx as never, "tenant_1", "user", "user_1", ctx)).resolves.toBeUndefined();
|
||||
expect(tx.tenantUser.findFirst).toHaveBeenCalledWith({
|
||||
where: { tenantId: "tenant_1", userId: "user_1", status: TenantUserStatus.ACTIVE, user: { active: true } },
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("does not let member-directory access substitute for HR access to another user", async () => {
|
||||
const tx = transaction();
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: ["app.settings.members.view"] };
|
||||
|
||||
await expect(assertFileLinkTargetVisibleWithTx(tx as never, "tenant_1", "user", "user_2", ctx)).rejects.toMatchObject({ status: 404 });
|
||||
expect(tx.tenantUser.findFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["hr.read_all", "hr.admin"])("allows %s to link an active employee target", async (permission) => {
|
||||
const tx = transaction();
|
||||
tx.tenantUser.findFirst.mockResolvedValue({ id: "membership_2" });
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: [permission] };
|
||||
|
||||
await expect(assertFileLinkTargetVisibleWithTx(tx as never, "tenant_1", "user", "user_2", ctx)).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not infer access to another employee from hr.write", async () => {
|
||||
const tx = transaction();
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: ["hr.write"] };
|
||||
|
||||
await expect(assertFileLinkTargetVisibleWithTx(tx as never, "tenant_1", "user", "user_2", ctx)).rejects.toMatchObject({ status: 404 });
|
||||
expect(tx.tenantUser.findFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("scopes form submissions through a readable owned form", async () => {
|
||||
const tx = transaction();
|
||||
tx.formSubmission.findFirst.mockResolvedValue({ id: "submission_1" });
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: ["forms.basic"] };
|
||||
|
||||
await expect(assertFileLinkTargetVisibleWithTx(tx as never, "tenant_1", "form_submission", "submission_1", ctx)).resolves.toBeUndefined();
|
||||
expect(tx.formSubmission.findFirst).toHaveBeenCalledWith({
|
||||
where: { id: "submission_1", tenantId: "tenant_1", form: { tenantId: "tenant_1", createdByUserId: "user_1" } },
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("owner-scopes appointments unless the caller has tenant-wide booking read access", async () => {
|
||||
const tx = transaction();
|
||||
tx.appointment.findFirst.mockResolvedValue({ id: "appointment_1" });
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: ["bookings.read_own"] };
|
||||
|
||||
await expect(assertFileLinkTargetVisibleWithTx(tx as never, "tenant_1", "appointment", "appointment_1", ctx)).resolves.toBeUndefined();
|
||||
expect(tx.appointment.findFirst).toHaveBeenCalledWith({
|
||||
where: { id: "appointment_1", tenantId: "tenant_1", providerUserId: "user_1" },
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("requires both signature and project visibility for signature documents", async () => {
|
||||
const tx = transaction();
|
||||
tx.projektSignatureDocument.findFirst.mockResolvedValue({ id: "document_1", projektId: "project_1" });
|
||||
tx.projekt.findFirst.mockResolvedValue({ id: "project_1" });
|
||||
const ctx: FileVisibilityContext = {
|
||||
userId: "user_1",
|
||||
permissions: ["signature.read", "projects.read_all"],
|
||||
roleIds: [],
|
||||
groupIds: [],
|
||||
};
|
||||
|
||||
await expect(assertFileLinkTargetVisibleWithTx(tx as never, "tenant_1", "signature_document", "document_1", ctx)).resolves.toBeUndefined();
|
||||
expect(tx.projektSignatureDocument.findFirst).toHaveBeenCalledWith({
|
||||
where: { id: "document_1", tenantId: "tenant_1", archivedAt: null },
|
||||
select: { id: true, projektId: true },
|
||||
});
|
||||
expect(tx.projekt.findFirst.mock.calls[0]?.[0].where).toMatchObject({ id: "project_1", tenantId: "tenant_1", archivedAt: null });
|
||||
});
|
||||
|
||||
it("fails closed before querying when the target permission is missing", async () => {
|
||||
const tx = transaction();
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: [] };
|
||||
|
||||
await expect(assertFileLinkTargetVisibleWithTx(tx as never, "tenant_1", "contact", "contact_1", ctx)).rejects.toMatchObject({ status: 404 });
|
||||
expect(tx.kontakt.findFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails closed when the scoped target does not exist", async () => {
|
||||
const tx = transaction();
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: ["bookings.read_all"] };
|
||||
|
||||
await expect(assertFileLinkTargetVisibleWithTx(tx as never, "tenant_1", "appointment", "foreign_appointment", ctx)).rejects.toMatchObject({
|
||||
status: 404,
|
||||
});
|
||||
});
|
||||
|
||||
it("authorizes a chat-message target only through active channel membership, even for read-all admins", async () => {
|
||||
const tx = transaction();
|
||||
tx.teamChatMessage.findFirst.mockResolvedValue({ id: "message_1" });
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: ["chat.read_all_channels"] };
|
||||
|
||||
await expect(assertFileLinkTargetVisibleWithTx(tx as never, "tenant_1", "chat_message", "message_1", ctx)).resolves.toBeUndefined();
|
||||
expect(tx.teamChatMessage.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: "message_1",
|
||||
tenantId: "tenant_1",
|
||||
chat: { tenantId: "tenant_1", members: { some: { tenantId: "tenant_1", userId: "user_1", leftAt: null } } },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("fails closed for a runtime entity type unsupported by the typed Files service", async () => {
|
||||
const tx = transaction();
|
||||
const ctx: FileVisibilityContext = { userId: "user_1", permissions: ["files.admin"] };
|
||||
|
||||
await expect(assertFileLinkTargetVisibleWithTx(tx as never, "tenant_1", "email_message" as FileEntityType, "message_1", ctx)).rejects.toMatchObject({
|
||||
status: 404,
|
||||
});
|
||||
});
|
||||
});
|
||||
+604
@@ -0,0 +1,604 @@
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import type { TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
import { projectReadScopeWhere, type ProjectVisibilityContext } from "./projects/projectService.server";
|
||||
import type { FileEntityType } from "./fileService.server";
|
||||
|
||||
export type FileVisibilityContext = ProjectVisibilityContext & {
|
||||
/** The user's permission names for this tenant (from getPermissionsByUser). */
|
||||
permissions: readonly string[];
|
||||
};
|
||||
|
||||
export type FileVisibilityQueryState = {
|
||||
projectContext?: Promise<ProjectVisibilityContext>;
|
||||
};
|
||||
|
||||
export function createFileVisibilityQueryState(): FileVisibilityQueryState {
|
||||
return {};
|
||||
}
|
||||
|
||||
const PROJECT_READ_PERMISSIONS = ["projects.read_all", "projects.read_own", "projects.read_own_pl", "projects.read_own_member"] as const;
|
||||
const CRM_READ_PERMISSIONS = ["crm.read_all", "crm.read_own"] as const;
|
||||
const LEAD_READ_PERMISSIONS = ["leads.read_all", "leads.read_own"] as const;
|
||||
const TASK_READ_PERMISSIONS = ["tasks.read_all", "tasks.read_own"] as const;
|
||||
const BOOKING_READ_PERMISSIONS = ["bookings.read_all", "bookings.read_own", "bookings.write", "bookings.admin"] as const;
|
||||
const SIGNATURE_READ_PERMISSIONS = ["signature.read", "signature.send", "signature.admin"] as const;
|
||||
const FILE_READ_PERMISSIONS = ["files.read_own", "files.read_all"] as const;
|
||||
const CHAT_READ_PERMISSIONS = ["chat.read_own_channels", "chat.read_all_channels"] as const;
|
||||
const HR_READ_ALL_PERMISSIONS = ["hr.read_all", "hr.admin"] as const;
|
||||
const FILE_ENTITY_TYPES = new Set<FileEntityType>([
|
||||
"contact",
|
||||
"company",
|
||||
"lead",
|
||||
"deal",
|
||||
"project",
|
||||
"user",
|
||||
"form_submission",
|
||||
"order",
|
||||
"task",
|
||||
"appointment",
|
||||
"signature_document",
|
||||
"email_message",
|
||||
"chat_message",
|
||||
]);
|
||||
|
||||
function hasPermission(ctx: FileVisibilityContext, permission: string): boolean {
|
||||
return ctx.permissions.includes(permission);
|
||||
}
|
||||
|
||||
function hasAnyPermission(ctx: FileVisibilityContext, permissions: readonly string[]): boolean {
|
||||
return permissions.some((permission) => hasPermission(ctx, permission));
|
||||
}
|
||||
|
||||
function canReadAllHrFiles(ctx: FileVisibilityContext): boolean {
|
||||
return hasAnyPermission(ctx, HR_READ_ALL_PERMISSIONS);
|
||||
}
|
||||
|
||||
function targetNotFound(entityType: FileEntityType, entityId: string): CatalogError {
|
||||
return new CatalogError(foundationErrors.notFound, { entityType, entityId });
|
||||
}
|
||||
|
||||
async function hydrateProjectVisibilityContextWithTx(tx: TenantRlsClient, tenantId: string, ctx: FileVisibilityContext): Promise<ProjectVisibilityContext> {
|
||||
const [roleIds, groupIds] = await Promise.all([
|
||||
ctx.roleIds === undefined
|
||||
? tx.userRole.findMany({ where: { tenantId, userId: ctx.userId }, select: { roleId: true } }).then((rows) => rows.map(({ roleId }) => roleId))
|
||||
: Promise.resolve([...ctx.roleIds]),
|
||||
ctx.groupIds === undefined
|
||||
? tx.groupUser
|
||||
.findMany({ where: { userId: ctx.userId, group: { tenantId } }, select: { groupId: true } })
|
||||
.then((rows) => rows.map(({ groupId }) => groupId))
|
||||
: Promise.resolve([...ctx.groupIds]),
|
||||
]);
|
||||
return { ...ctx, roleIds, groupIds };
|
||||
}
|
||||
|
||||
function getProjectVisibilityContextWithTx(
|
||||
tx: TenantRlsClient,
|
||||
tenantId: string,
|
||||
ctx: FileVisibilityContext,
|
||||
queryState?: FileVisibilityQueryState
|
||||
): Promise<ProjectVisibilityContext> {
|
||||
if (!queryState) return hydrateProjectVisibilityContextWithTx(tx, tenantId, ctx);
|
||||
queryState.projectContext ??= hydrateProjectVisibilityContextWithTx(tx, tenantId, ctx);
|
||||
return queryState.projectContext;
|
||||
}
|
||||
|
||||
type FileLinkTarget = {
|
||||
entityType: string;
|
||||
entityId: string;
|
||||
};
|
||||
|
||||
function isFileEntityType(value: string): value is FileEntityType {
|
||||
return FILE_ENTITY_TYPES.has(value as FileEntityType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter an ordered set of polymorphic file links through the same target
|
||||
* scopes used for mutations. Targets are grouped so each entity type needs at
|
||||
* most one query; unsupported runtime types fail closed without a query.
|
||||
*/
|
||||
export async function filterVisibleFileLinksWithTx<T extends FileLinkTarget>(
|
||||
tx: TenantRlsClient,
|
||||
tenantId: string,
|
||||
links: readonly T[],
|
||||
ctx: FileVisibilityContext,
|
||||
queryState?: FileVisibilityQueryState
|
||||
): Promise<T[]> {
|
||||
if (links.length === 0) return [];
|
||||
|
||||
const candidateIds = new Map<FileEntityType, Set<string>>();
|
||||
for (const link of links) {
|
||||
if (!isFileEntityType(link.entityType)) continue;
|
||||
const ids = candidateIds.get(link.entityType) ?? new Set<string>();
|
||||
ids.add(link.entityId);
|
||||
candidateIds.set(link.entityType, ids);
|
||||
}
|
||||
|
||||
const idsFor = (entityType: FileEntityType): string[] => [...(candidateIds.get(entityType) ?? [])];
|
||||
const visibleIds = new Map<FileEntityType, Set<string>>();
|
||||
const markVisible = (entityType: FileEntityType, ids: readonly string[]): void => {
|
||||
if (ids.length === 0) return;
|
||||
visibleIds.set(entityType, new Set(ids));
|
||||
};
|
||||
|
||||
const directProjectIds = [...new Set([...idsFor("project"), ...idsFor("deal"), ...idsFor("order")])];
|
||||
const signatureDocumentIds = idsFor("signature_document");
|
||||
const chatMessageIds = idsFor("chat_message");
|
||||
const canReadProjects = hasAnyPermission(ctx, PROJECT_READ_PERMISSIONS);
|
||||
const canReadSignatures = hasAnyPermission(ctx, SIGNATURE_READ_PERMISSIONS);
|
||||
const needsProjectContext = canReadProjects && (directProjectIds.length > 0 || (canReadSignatures && signatureDocumentIds.length > 0));
|
||||
const projectContextPromise = needsProjectContext ? getProjectVisibilityContextWithTx(tx, tenantId, ctx, queryState) : undefined;
|
||||
|
||||
const independentQueries: Promise<void>[] = [];
|
||||
|
||||
if (chatMessageIds.length > 0 && hasAnyPermission(ctx, CHAT_READ_PERMISSIONS)) {
|
||||
independentQueries.push(
|
||||
tx.teamChatMessage
|
||||
.findMany({
|
||||
where: {
|
||||
id: { in: chatMessageIds },
|
||||
tenantId,
|
||||
chat: { tenantId, members: { some: { tenantId, userId: ctx.userId, leftAt: null } } },
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
.then((rows) =>
|
||||
markVisible(
|
||||
"chat_message",
|
||||
rows.map(({ id }) => id)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
for (const [entityType, kontaktTyp] of [
|
||||
["contact", "privatperson"],
|
||||
["company", "organisation"],
|
||||
] as const) {
|
||||
const ids = idsFor(entityType);
|
||||
if (ids.length === 0 || !hasAnyPermission(ctx, CRM_READ_PERMISSIONS)) continue;
|
||||
independentQueries.push(
|
||||
tx.kontakt
|
||||
.findMany({
|
||||
where: {
|
||||
id: { in: ids },
|
||||
tenantId,
|
||||
archivedAt: null,
|
||||
kontaktTyp,
|
||||
...(hasPermission(ctx, "crm.read_all") ? {} : { zustaendigerUserId: ctx.userId }),
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
.then((rows) =>
|
||||
markVisible(
|
||||
entityType,
|
||||
rows.map(({ id }) => id)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const leadIds = idsFor("lead");
|
||||
if (leadIds.length > 0 && hasAnyPermission(ctx, LEAD_READ_PERMISSIONS)) {
|
||||
independentQueries.push(
|
||||
tx.inboxLead
|
||||
.findMany({
|
||||
where: {
|
||||
id: { in: leadIds },
|
||||
tenantId,
|
||||
archivedAt: null,
|
||||
...(hasPermission(ctx, "leads.read_all") ? {} : { zustaendigerUserId: ctx.userId }),
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
.then((rows) =>
|
||||
markVisible(
|
||||
"lead",
|
||||
rows.map(({ id }) => id)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const userIds = idsFor("user");
|
||||
const readableUserIds = canReadAllHrFiles(ctx) ? userIds : userIds.filter((userId) => userId === ctx.userId);
|
||||
if (readableUserIds.length > 0) {
|
||||
independentQueries.push(
|
||||
tx.tenantUser
|
||||
.findMany({
|
||||
where: { tenantId, userId: { in: readableUserIds }, status: TenantUserStatus.ACTIVE, user: { active: true } },
|
||||
select: { userId: true },
|
||||
})
|
||||
.then((rows) =>
|
||||
markVisible(
|
||||
"user",
|
||||
rows.map(({ userId }) => userId)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const submissionIds = idsFor("form_submission");
|
||||
if (submissionIds.length > 0 && (hasPermission(ctx, "forms.basic") || hasPermission(ctx, "forms.admin"))) {
|
||||
independentQueries.push(
|
||||
tx.formSubmission
|
||||
.findMany({
|
||||
where: {
|
||||
id: { in: submissionIds },
|
||||
tenantId,
|
||||
form: { tenantId, ...(hasPermission(ctx, "forms.admin") ? {} : { createdByUserId: ctx.userId }) },
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
.then((rows) =>
|
||||
markVisible(
|
||||
"form_submission",
|
||||
rows.map(({ id }) => id)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const taskIds = idsFor("task");
|
||||
if (taskIds.length > 0 && hasAnyPermission(ctx, TASK_READ_PERMISSIONS)) {
|
||||
const groupIdsPromise = hasPermission(ctx, "tasks.read_all")
|
||||
? Promise.resolve([] as string[])
|
||||
: ctx.groupIds !== undefined
|
||||
? Promise.resolve([...ctx.groupIds])
|
||||
: projectContextPromise
|
||||
? projectContextPromise.then((projectCtx) => [...(projectCtx.groupIds ?? [])])
|
||||
: tx.groupUser
|
||||
.findMany({ where: { userId: ctx.userId, group: { tenantId } }, select: { groupId: true } })
|
||||
.then((rows) => rows.map(({ groupId }) => groupId));
|
||||
independentQueries.push(
|
||||
groupIdsPromise.then(async (groupIds) => {
|
||||
const rows = await tx.task.findMany({
|
||||
where: {
|
||||
id: { in: taskIds },
|
||||
tenantId,
|
||||
archivedAt: null,
|
||||
...(hasPermission(ctx, "tasks.read_all")
|
||||
? {}
|
||||
: {
|
||||
OR: [
|
||||
{ createdByUserId: ctx.userId },
|
||||
{ assignedToUserId: ctx.userId },
|
||||
{ watchers: { some: { tenantId, userId: ctx.userId } } },
|
||||
...(groupIds.length > 0 ? [{ assignedToGroupId: { in: groupIds } }] : []),
|
||||
],
|
||||
}),
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
markVisible(
|
||||
"task",
|
||||
rows.map(({ id }) => id)
|
||||
);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
const appointmentIds = idsFor("appointment");
|
||||
if (appointmentIds.length > 0 && hasAnyPermission(ctx, BOOKING_READ_PERMISSIONS)) {
|
||||
independentQueries.push(
|
||||
tx.appointment
|
||||
.findMany({
|
||||
where: {
|
||||
id: { in: appointmentIds },
|
||||
tenantId,
|
||||
...(hasPermission(ctx, "bookings.read_all") || hasPermission(ctx, "bookings.admin") ? {} : { providerUserId: ctx.userId }),
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
.then((rows) =>
|
||||
markVisible(
|
||||
"appointment",
|
||||
rows.map(({ id }) => id)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const signatureDocumentsPromise =
|
||||
signatureDocumentIds.length > 0 && canReadSignatures && canReadProjects
|
||||
? tx.projektSignatureDocument.findMany({
|
||||
where: { id: { in: signatureDocumentIds }, tenantId, archivedAt: null },
|
||||
select: { id: true, projektId: true },
|
||||
})
|
||||
: Promise.resolve([] as Array<{ id: string; projektId: string }>);
|
||||
|
||||
const [, signatureDocuments] = await Promise.all([Promise.all(independentQueries), signatureDocumentsPromise]);
|
||||
const projectIdsToCheck = [...new Set([...directProjectIds, ...signatureDocuments.map(({ projektId }) => projektId)])];
|
||||
if (projectIdsToCheck.length > 0 && projectContextPromise) {
|
||||
const projectCtx = await projectContextPromise;
|
||||
const projects = await tx.projekt.findMany({
|
||||
where: {
|
||||
id: { in: projectIdsToCheck },
|
||||
tenantId,
|
||||
archivedAt: null,
|
||||
...projectReadScopeWhere(tenantId, projectCtx),
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
const visibleProjectIds = new Set(projects.map(({ id }) => id));
|
||||
for (const entityType of ["project", "deal", "order"] as const) {
|
||||
markVisible(
|
||||
entityType,
|
||||
idsFor(entityType).filter((id) => visibleProjectIds.has(id))
|
||||
);
|
||||
}
|
||||
markVisible(
|
||||
"signature_document",
|
||||
signatureDocuments.filter(({ projektId }) => visibleProjectIds.has(projektId)).map(({ id }) => id)
|
||||
);
|
||||
}
|
||||
|
||||
return links.filter((link) => isFileEntityType(link.entityType) && Boolean(visibleIds.get(link.entityType)?.has(link.entityId)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that a polymorphic FileEntityLink target both exists in this tenant and
|
||||
* is readable by the current user. Unknown or not-yet-typed targets fail closed.
|
||||
*/
|
||||
export async function assertFileLinkTargetVisibleWithTx(
|
||||
tx: TenantRlsClient,
|
||||
tenantId: string,
|
||||
entityType: FileEntityType,
|
||||
entityId: string,
|
||||
ctx: FileVisibilityContext
|
||||
): Promise<void> {
|
||||
let target: { id: string } | null = null;
|
||||
|
||||
switch (entityType) {
|
||||
case "contact":
|
||||
case "company":
|
||||
if (!hasAnyPermission(ctx, CRM_READ_PERMISSIONS)) throw targetNotFound(entityType, entityId);
|
||||
target = await tx.kontakt.findFirst({
|
||||
where: {
|
||||
id: entityId,
|
||||
tenantId,
|
||||
archivedAt: null,
|
||||
kontaktTyp: entityType === "company" ? "organisation" : "privatperson",
|
||||
...(hasPermission(ctx, "crm.read_all") ? {} : { zustaendigerUserId: ctx.userId }),
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
break;
|
||||
case "lead":
|
||||
if (!hasAnyPermission(ctx, LEAD_READ_PERMISSIONS)) throw targetNotFound(entityType, entityId);
|
||||
target = await tx.inboxLead.findFirst({
|
||||
where: {
|
||||
id: entityId,
|
||||
tenantId,
|
||||
archivedAt: null,
|
||||
...(hasPermission(ctx, "leads.read_all") ? {} : { zustaendigerUserId: ctx.userId }),
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
break;
|
||||
case "project":
|
||||
case "deal":
|
||||
case "order": {
|
||||
if (!hasAnyPermission(ctx, PROJECT_READ_PERMISSIONS)) throw targetNotFound(entityType, entityId);
|
||||
const projectCtx = await hydrateProjectVisibilityContextWithTx(tx, tenantId, ctx);
|
||||
target = await tx.projekt.findFirst({
|
||||
where: { id: entityId, tenantId, archivedAt: null, ...projectReadScopeWhere(tenantId, projectCtx) },
|
||||
select: { id: true },
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "user":
|
||||
if (entityId !== ctx.userId && !canReadAllHrFiles(ctx)) throw targetNotFound(entityType, entityId);
|
||||
target = await tx.tenantUser.findFirst({
|
||||
where: { tenantId, userId: entityId, status: TenantUserStatus.ACTIVE, user: { active: true } },
|
||||
select: { id: true },
|
||||
});
|
||||
break;
|
||||
case "form_submission":
|
||||
if (!hasPermission(ctx, "forms.basic") && !hasPermission(ctx, "forms.admin")) throw targetNotFound(entityType, entityId);
|
||||
target = await tx.formSubmission.findFirst({
|
||||
where: {
|
||||
id: entityId,
|
||||
tenantId,
|
||||
form: { tenantId, ...(hasPermission(ctx, "forms.admin") ? {} : { createdByUserId: ctx.userId }) },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
break;
|
||||
case "task": {
|
||||
if (!hasAnyPermission(ctx, TASK_READ_PERMISSIONS)) throw targetNotFound(entityType, entityId);
|
||||
const groupIds =
|
||||
ctx.groupIds === undefined
|
||||
? await tx.groupUser
|
||||
.findMany({ where: { userId: ctx.userId, group: { tenantId } }, select: { groupId: true } })
|
||||
.then((rows) => rows.map(({ groupId }) => groupId))
|
||||
: [...ctx.groupIds];
|
||||
target = await tx.task.findFirst({
|
||||
where: {
|
||||
id: entityId,
|
||||
tenantId,
|
||||
archivedAt: null,
|
||||
...(hasPermission(ctx, "tasks.read_all")
|
||||
? {}
|
||||
: {
|
||||
OR: [
|
||||
{ createdByUserId: ctx.userId },
|
||||
{ assignedToUserId: ctx.userId },
|
||||
{ watchers: { some: { tenantId, userId: ctx.userId } } },
|
||||
...(groupIds.length > 0 ? [{ assignedToGroupId: { in: groupIds } }] : []),
|
||||
],
|
||||
}),
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "appointment":
|
||||
if (!hasAnyPermission(ctx, BOOKING_READ_PERMISSIONS)) throw targetNotFound(entityType, entityId);
|
||||
target = await tx.appointment.findFirst({
|
||||
where: {
|
||||
id: entityId,
|
||||
tenantId,
|
||||
...(hasPermission(ctx, "bookings.read_all") || hasPermission(ctx, "bookings.admin") ? {} : { providerUserId: ctx.userId }),
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
break;
|
||||
case "signature_document": {
|
||||
if (!hasAnyPermission(ctx, SIGNATURE_READ_PERMISSIONS)) throw targetNotFound(entityType, entityId);
|
||||
if (!hasAnyPermission(ctx, PROJECT_READ_PERMISSIONS)) throw targetNotFound(entityType, entityId);
|
||||
const projectCtx = await hydrateProjectVisibilityContextWithTx(tx, tenantId, ctx);
|
||||
const document = await tx.projektSignatureDocument.findFirst({
|
||||
where: { id: entityId, tenantId, archivedAt: null },
|
||||
select: { id: true, projektId: true },
|
||||
});
|
||||
if (document) {
|
||||
const project = await tx.projekt.findFirst({
|
||||
where: { id: document.projektId, tenantId, archivedAt: null, ...projectReadScopeWhere(tenantId, projectCtx) },
|
||||
select: { id: true },
|
||||
});
|
||||
target = project ? { id: document.id } : null;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "chat_message":
|
||||
if (!hasAnyPermission(ctx, CHAT_READ_PERMISSIONS)) throw targetNotFound(entityType, entityId);
|
||||
target = await tx.teamChatMessage.findFirst({
|
||||
where: {
|
||||
id: entityId,
|
||||
tenantId,
|
||||
chat: { tenantId, members: { some: { tenantId, userId: ctx.userId, leftAt: null } } },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
break;
|
||||
default:
|
||||
throw targetNotFound(entityType, entityId);
|
||||
}
|
||||
|
||||
if (!target) throw targetNotFound(entityType, entityId);
|
||||
}
|
||||
|
||||
async function loadVisibleLinkedProjectIdsWithTx(
|
||||
tx: TenantRlsClient,
|
||||
tenantId: string,
|
||||
ctx: FileVisibilityContext,
|
||||
candidateFileIds?: readonly string[],
|
||||
queryState?: FileVisibilityQueryState
|
||||
): Promise<string[]> {
|
||||
if (!PROJECT_READ_PERMISSIONS.some((permission) => hasPermission(ctx, permission))) return [];
|
||||
let projectIds: string[] | undefined;
|
||||
if (candidateFileIds !== undefined) {
|
||||
if (candidateFileIds.length === 0) return [];
|
||||
const links = await tx.fileEntityLink.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
entityType: "project",
|
||||
fileId: { in: [...candidateFileIds] },
|
||||
},
|
||||
select: { entityId: true },
|
||||
distinct: ["entityId"],
|
||||
});
|
||||
projectIds = [...new Set(links.map(({ entityId }) => entityId))];
|
||||
if (projectIds.length === 0) return [];
|
||||
}
|
||||
const projectCtx = await getProjectVisibilityContextWithTx(tx, tenantId, ctx, queryState);
|
||||
const visibleProjects = await tx.projekt.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
...(projectIds ? { id: { in: projectIds } } : {}),
|
||||
archivedAt: null,
|
||||
...projectReadScopeWhere(tenantId, projectCtx),
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
return visibleProjects.map(({ id }) => id);
|
||||
}
|
||||
|
||||
async function loadVisibleLinkedChatMessageIdsWithTx(
|
||||
tx: TenantRlsClient,
|
||||
tenantId: string,
|
||||
ctx: FileVisibilityContext,
|
||||
candidateFileIds?: readonly string[]
|
||||
): Promise<string[]> {
|
||||
if (!hasAnyPermission(ctx, CHAT_READ_PERMISSIONS)) return [];
|
||||
let messageIds: string[] | undefined;
|
||||
if (candidateFileIds !== undefined) {
|
||||
if (candidateFileIds.length === 0) return [];
|
||||
const links = await tx.fileEntityLink.findMany({
|
||||
where: { tenantId, entityType: "chat_message", fileId: { in: [...candidateFileIds] } },
|
||||
select: { entityId: true },
|
||||
distinct: ["entityId"],
|
||||
});
|
||||
messageIds = [...new Set(links.map(({ entityId }) => entityId))];
|
||||
if (messageIds.length === 0) return [];
|
||||
}
|
||||
const messages = await tx.teamChatMessage.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
...(messageIds ? { id: { in: messageIds } } : {}),
|
||||
chat: { tenantId, members: { some: { tenantId, userId: ctx.userId, leftAt: null } } },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
return messages.map(({ id }) => id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the authoritative file read scope. A polymorphic link never grants
|
||||
* access by itself: only project links whose target project is currently
|
||||
* readable (including PipelineAccess deny rules) extend files.read_own.
|
||||
*/
|
||||
export async function fileReadScopeWhereWithTx(
|
||||
tx: TenantRlsClient,
|
||||
tenantId: string,
|
||||
ctx: FileVisibilityContext,
|
||||
candidateFileIds?: readonly string[],
|
||||
queryState?: FileVisibilityQueryState
|
||||
): Promise<Prisma.FileWhereInput> {
|
||||
const canReadFiles = hasAnyPermission(ctx, FILE_READ_PERMISSIONS);
|
||||
const canReadChat = hasAnyPermission(ctx, CHAT_READ_PERMISSIONS);
|
||||
if (!canReadFiles && !canReadChat) return { id: { in: [] } };
|
||||
|
||||
const readsAllFiles = canReadFiles && hasPermission(ctx, "files.read_all");
|
||||
const readsAllHrFiles = canReadAllHrFiles(ctx);
|
||||
const [projectIds, chatMessageIds] = readsAllFiles
|
||||
? [[], []]
|
||||
: await Promise.all([
|
||||
canReadFiles ? loadVisibleLinkedProjectIdsWithTx(tx, tenantId, ctx, candidateFileIds, queryState) : Promise.resolve([]),
|
||||
canReadChat ? loadVisibleLinkedChatMessageIdsWithTx(tx, tenantId, ctx, candidateFileIds) : Promise.resolve([]),
|
||||
]);
|
||||
const scopedBranches: Prisma.FileWhereInput[] = [
|
||||
...(canReadFiles
|
||||
? [
|
||||
{ createdByUserId: ctx.userId },
|
||||
{ assignedToUserId: ctx.userId },
|
||||
...(projectIds.length > 0 ? [{ links: { some: { tenantId, entityType: "project" as const, entityId: { in: projectIds } } } }] : []),
|
||||
{
|
||||
links: {
|
||||
some: {
|
||||
tenantId,
|
||||
entityType: "user" as const,
|
||||
...(readsAllHrFiles ? {} : { entityId: ctx.userId }),
|
||||
},
|
||||
},
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(chatMessageIds.length > 0 ? [{ links: { some: { tenantId, entityType: "chat_message" as const, entityId: { in: chatMessageIds } } } }] : []),
|
||||
];
|
||||
const baseScope: Prisma.FileWhereInput = readsAllFiles ? {} : scopedBranches.length > 0 ? { OR: scopedBranches } : { id: { in: [] } };
|
||||
|
||||
if (readsAllHrFiles) return baseScope;
|
||||
const hrScope: Prisma.FileWhereInput = {
|
||||
links: {
|
||||
none: {
|
||||
tenantId,
|
||||
entityType: "user",
|
||||
entityId: { not: ctx.userId },
|
||||
},
|
||||
},
|
||||
};
|
||||
return Object.keys(baseScope).length === 0 ? hrScope : { AND: [baseScope, hrScope] };
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
// @vitest-environment node
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const SOURCES = [
|
||||
"hrService.server.ts",
|
||||
"hrLeaveService.server.ts",
|
||||
"hrPayslipService.server.ts",
|
||||
"hrRequestService.server.ts",
|
||||
"hrSickLeaveService.server.ts",
|
||||
].map((file) => readFileSync(`apps/web/app/utils/integrations/${file}`, "utf8"));
|
||||
|
||||
describe("HR activity i18n contract", () => {
|
||||
it("persists semantic keys for every machine-authored HR summary", () => {
|
||||
const summaries = SOURCES.flatMap((source) =>
|
||||
[...source.matchAll(/summaryText:\s*"([^"]+)"/gu)].map((match) => match[1]),
|
||||
);
|
||||
|
||||
expect(summaries).toEqual(
|
||||
expect.arrayContaining([
|
||||
"activity.runtime.hr.documentUploaded",
|
||||
"activity.runtime.hr.leaveRequested",
|
||||
"activity.runtime.hr.payslipProvided",
|
||||
"activity.runtime.hr.requestSubmitted",
|
||||
"activity.runtime.hr.sickLeaveRecorded",
|
||||
]),
|
||||
);
|
||||
expect(summaries.every((summary) => summary.startsWith("activity.runtime.hr."))).toBe(true);
|
||||
});
|
||||
});
|
||||
+20
-13
@@ -10,6 +10,7 @@
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { isHrAudienceVisible, requireValidHrAudienceWithTx } from "./hrAudience.server";
|
||||
import { HrServiceError } from "./hrService.server";
|
||||
|
||||
const HR_AUDIT_MODULE = "hr";
|
||||
@@ -52,10 +53,7 @@ async function audit(input: { tenantId: string; actorId: string; action: string;
|
||||
/** 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;
|
||||
return isHrAudienceVisible(kind, ref, viewer);
|
||||
}
|
||||
|
||||
export type CreateAnnouncementInput = {
|
||||
@@ -77,23 +75,26 @@ export async function createAnnouncement(input: CreateAnnouncementInput): Promis
|
||||
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({
|
||||
const audienceKind = input.audienceKind ?? "all";
|
||||
const audienceRef = audienceKind === "all" ? null : (input.audienceRef ?? null);
|
||||
const created = (await withTenantRLS(input.tenantId, async (tx) => {
|
||||
await requireValidHrAudienceWithTx(tx, { tenantId: input.tenantId, kind: audienceKind, ref: audienceRef });
|
||||
return 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,
|
||||
audienceKind,
|
||||
audienceRef,
|
||||
requiresAcknowledgement: input.requiresAcknowledgement ?? false,
|
||||
pinnedAt: input.pinned ? new Date() : null,
|
||||
publishAt: input.publishAt ?? null,
|
||||
expiresAt: input.expiresAt ?? null,
|
||||
isDemoData: input.isDemoData ?? false,
|
||||
},
|
||||
}),
|
||||
)) as AnnouncementRow;
|
||||
});
|
||||
})) as AnnouncementRow;
|
||||
await audit({ tenantId: input.tenantId, actorId: input.authorUserId, action: "HR_ANNOUNCEMENT_CREATE", targetId: created.id });
|
||||
return created;
|
||||
}
|
||||
@@ -107,15 +108,21 @@ export type UpdateAnnouncementInput = Partial<Omit<CreateAnnouncementInput, "ten
|
||||
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 } });
|
||||
const existing = await tx.hrAnnouncement.findFirst({
|
||||
where: { id: input.announcementId, tenantId: input.tenantId },
|
||||
select: { id: true, audienceKind: true, audienceRef: true },
|
||||
});
|
||||
if (!existing) throw new CatalogError(foundationErrors.notFound, { announcementId: input.announcementId });
|
||||
const audienceKind = input.audienceKind ?? existing.audienceKind;
|
||||
const audienceRef = audienceKind === "all" ? null : input.audienceRef !== undefined ? input.audienceRef : existing.audienceRef;
|
||||
await requireValidHrAudienceWithTx(tx, { tenantId: input.tenantId, kind: audienceKind, ref: audienceRef });
|
||||
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 } : {}),
|
||||
audienceKind,
|
||||
audienceRef,
|
||||
...(input.requiresAcknowledgement !== undefined ? { requiresAcknowledgement: input.requiresAcknowledgement } : {}),
|
||||
...(input.pinned !== undefined ? { pinnedAt: input.pinned ? new Date() : null } : {}),
|
||||
...(input.publishAt !== undefined ? { publishAt: input.publishAt } : {}),
|
||||
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tx: {
|
||||
hrEmployeeProfile: { findFirst: vi.fn(), findMany: vi.fn() },
|
||||
hrLocation: { findFirst: vi.fn(), findMany: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: (_tenantId: string, callback: (tx: typeof mocks.tx) => unknown) => callback(mocks.tx),
|
||||
}));
|
||||
|
||||
import {
|
||||
isHrAudienceVisible,
|
||||
listHrAudienceOptions,
|
||||
requireHrAudienceViewer,
|
||||
requireValidHrAudience,
|
||||
} from "./hrAudience.server";
|
||||
|
||||
describe("HR audience object access", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.tx.hrEmployeeProfile.findFirst.mockResolvedValue(null);
|
||||
mocks.tx.hrEmployeeProfile.findMany.mockResolvedValue([]);
|
||||
mocks.tx.hrLocation.findFirst.mockResolvedValue(null);
|
||||
mocks.tx.hrLocation.findMany.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("matches only the viewer's exact team or location", () => {
|
||||
const viewer = { team: "Montage Nord", locationId: "location-1" };
|
||||
expect(isHrAudienceVisible("all", null, viewer)).toBe(true);
|
||||
expect(isHrAudienceVisible("team", "Montage Nord", viewer)).toBe(true);
|
||||
expect(isHrAudienceVisible("team", "Montage Süd", viewer)).toBe(false);
|
||||
expect(isHrAudienceVisible("location", "location-1", viewer)).toBe(true);
|
||||
expect(isHrAudienceVisible("location", "location-2", viewer)).toBe(false);
|
||||
});
|
||||
|
||||
it("returns 404 semantics for a direct audience URL outside the viewer scope", async () => {
|
||||
mocks.tx.hrEmployeeProfile.findFirst.mockResolvedValue({ team: "Montage Nord", locationId: "location-1" });
|
||||
await expect(
|
||||
requireHrAudienceViewer({
|
||||
tenantId: "tenant-1",
|
||||
userId: "employee-1",
|
||||
kind: "team",
|
||||
ref: "Montage Süd",
|
||||
canManage: false,
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("rejects an audience reference that does not belong to the tenant", async () => {
|
||||
await expect(
|
||||
requireValidHrAudience({
|
||||
tenantId: "tenant-1",
|
||||
kind: "location",
|
||||
ref: "foreign-location",
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("builds named team and location options without exposing raw labels as UI copy", async () => {
|
||||
mocks.tx.hrEmployeeProfile.findMany.mockResolvedValue([{ team: "Montage Nord" }, { team: "Service" }]);
|
||||
mocks.tx.hrLocation.findMany.mockResolvedValue([{ id: "location-1", name: "Zentrale Köln" }]);
|
||||
await expect(listHrAudienceOptions("tenant-1")).resolves.toEqual([
|
||||
{ kind: "team", ref: "Montage Nord", label: "Montage Nord" },
|
||||
{ kind: "team", ref: "Service", label: "Service" },
|
||||
{ kind: "location", ref: "location-1", label: "Zentrale Köln" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
|
||||
export type HrAudienceKind = "all" | "team" | "location";
|
||||
|
||||
export type HrAudienceViewer = {
|
||||
team: string | null;
|
||||
locationId: string | null;
|
||||
};
|
||||
|
||||
export type HrAudienceOption = {
|
||||
kind: Exclude<HrAudienceKind, "all">;
|
||||
ref: string;
|
||||
label: string;
|
||||
};
|
||||
|
||||
export function isHrAudienceVisible(
|
||||
kind: HrAudienceKind,
|
||||
ref: string | null,
|
||||
viewer: HrAudienceViewer,
|
||||
): boolean {
|
||||
if (kind === "all") return true;
|
||||
if (kind === "team") return ref != null && ref === viewer.team;
|
||||
return ref != null && ref === viewer.locationId;
|
||||
}
|
||||
|
||||
export async function requireValidHrAudienceWithTx(
|
||||
tx: TenantRlsClient,
|
||||
input: { tenantId: string; kind: HrAudienceKind; ref: string | null },
|
||||
): Promise<void> {
|
||||
if (input.kind === "all") {
|
||||
if (input.ref) {
|
||||
throw new CatalogError(foundationErrors.notFound, { audienceRef: input.ref });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!input.ref) {
|
||||
throw new CatalogError(foundationErrors.notFound, { audienceKind: input.kind });
|
||||
}
|
||||
if (input.kind === "team") {
|
||||
const team = await tx.hrEmployeeProfile.findFirst({
|
||||
where: { tenantId: input.tenantId, team: input.ref },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!team) throw new CatalogError(foundationErrors.notFound, { audienceRef: input.ref });
|
||||
return;
|
||||
}
|
||||
const location = await tx.hrLocation.findFirst({
|
||||
where: { tenantId: input.tenantId, id: input.ref, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!location) throw new CatalogError(foundationErrors.notFound, { audienceRef: input.ref });
|
||||
}
|
||||
|
||||
export async function requireValidHrAudience(input: {
|
||||
tenantId: string;
|
||||
kind: HrAudienceKind;
|
||||
ref: string | null;
|
||||
}): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, (tx) => requireValidHrAudienceWithTx(tx, input));
|
||||
}
|
||||
|
||||
export async function requireHrAudienceViewer(input: {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
kind: HrAudienceKind;
|
||||
ref: string | null;
|
||||
canManage: boolean;
|
||||
}): Promise<void> {
|
||||
if (input.canManage || input.kind === "all") return;
|
||||
const profile = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.hrEmployeeProfile.findFirst({
|
||||
where: { tenantId: input.tenantId, userId: input.userId },
|
||||
select: { team: true, locationId: true },
|
||||
}),
|
||||
);
|
||||
if (!profile || !isHrAudienceVisible(input.kind, input.ref, profile)) {
|
||||
throw new CatalogError(foundationErrors.notFound, { audienceRef: input.ref });
|
||||
}
|
||||
}
|
||||
|
||||
export async function listHrAudienceOptions(tenantId: string): Promise<HrAudienceOption[]> {
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
const [teams, locations] = await Promise.all([
|
||||
tx.hrEmployeeProfile.findMany({
|
||||
where: { tenantId, team: { not: null } },
|
||||
select: { team: true },
|
||||
distinct: ["team"],
|
||||
orderBy: { team: "asc" },
|
||||
}),
|
||||
tx.hrLocation.findMany({
|
||||
where: { tenantId, archivedAt: null },
|
||||
select: { id: true, name: true },
|
||||
orderBy: { name: "asc" },
|
||||
}),
|
||||
]);
|
||||
return [
|
||||
...teams.flatMap(({ team }) => (team ? [{ kind: "team" as const, ref: team, label: team }] : [])),
|
||||
...locations.map(({ id, name }) => ({ kind: "location" as const, ref: id, label: name })),
|
||||
];
|
||||
});
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tx: {
|
||||
employeeVacationRequest: { findFirst: vi.fn(), update: vi.fn() },
|
||||
calendarEvent: { create: vi.fn() },
|
||||
outboxEvent: { findUnique: vi.fn(), create: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: async (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({ createAuditEvent: vi.fn().mockResolvedValue(undefined) }));
|
||||
vi.mock("@hivegrid/db/notifications.server", () => ({ createNotificationDelivery: vi.fn().mockResolvedValue(undefined) }));
|
||||
|
||||
import { approveRequest, rejectRequest } from "./hrLeaveService.server";
|
||||
|
||||
const baseRow = {
|
||||
id: "req-1",
|
||||
tenantId: "tenant-a",
|
||||
employeeUserId: "user-employee",
|
||||
requestKind: "vacation",
|
||||
startDate: new Date("2026-08-03T00:00:00.000Z"),
|
||||
endDate: new Date("2026-08-14T00:00:00.000Z"),
|
||||
note: null,
|
||||
status: "submitted",
|
||||
assignedApproverUserId: "user-approver",
|
||||
isDemoData: false,
|
||||
};
|
||||
|
||||
describe("leave approval calendar sync (P16/M25)", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.tx.employeeVacationRequest.findFirst.mockResolvedValue({ ...baseRow });
|
||||
mocks.tx.employeeVacationRequest.update.mockResolvedValue({});
|
||||
mocks.tx.calendarEvent.create.mockResolvedValue({ id: "event-1" });
|
||||
mocks.tx.outboxEvent.findUnique.mockResolvedValue(null);
|
||||
mocks.tx.outboxEvent.create.mockResolvedValue({ id: "outbox-1" });
|
||||
});
|
||||
|
||||
it("creates an internal all-day absence event and links it on approval", async () => {
|
||||
await approveRequest({
|
||||
tenantId: "tenant-a",
|
||||
requestId: "req-1",
|
||||
deciderUserId: "user-approver",
|
||||
canApproveAny: false,
|
||||
absenceTitleByKind: { vacation: "Urlaub" },
|
||||
});
|
||||
|
||||
expect(mocks.tx.calendarEvent.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
tenantId: "tenant-a",
|
||||
userId: "user-employee",
|
||||
source: "hivegrid_internal",
|
||||
title: "Urlaub",
|
||||
startsAt: baseRow.startDate,
|
||||
endsAt: baseRow.endDate,
|
||||
isAllDay: true,
|
||||
isBusyForAvailability: true,
|
||||
internalEntityLink: { type: "hr_vacation_request", id: "req-1" },
|
||||
isDemoData: false,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.tx.employeeVacationRequest.update).toHaveBeenCalledWith({
|
||||
where: { id: "req-1" },
|
||||
data: expect.objectContaining({ status: "approved", calendarEventId: "event-1" }),
|
||||
});
|
||||
expect(mocks.tx.outboxEvent.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
tenantId: "tenant-a",
|
||||
eventType: "workflow.trigger.event",
|
||||
dispatchKey: "workflow-trigger:calendar:event-1:created",
|
||||
payload: expect.objectContaining({ event: "calendar.event_created", data: expect.objectContaining({ calendarKey: "urlaubskalender" }) }),
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to a title-less event when no resolved title is passed", async () => {
|
||||
await approveRequest({ tenantId: "tenant-a", requestId: "req-1", deciderUserId: "user-approver", canApproveAny: false });
|
||||
|
||||
expect(mocks.tx.calendarEvent.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ title: null }) }));
|
||||
});
|
||||
|
||||
it("does not create a calendar event on rejection", async () => {
|
||||
await rejectRequest({ tenantId: "tenant-a", requestId: "req-1", deciderUserId: "user-approver", canApproveAny: false });
|
||||
|
||||
expect(mocks.tx.calendarEvent.create).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.employeeVacationRequest.update).toHaveBeenCalledWith({
|
||||
where: { id: "req-1" },
|
||||
data: expect.objectContaining({ status: "rejected" }),
|
||||
});
|
||||
});
|
||||
});
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tx: {
|
||||
hrEmployeeProfile: { findMany: vi.fn() },
|
||||
employeeVacationRequest: { findMany: vi.fn() },
|
||||
employeeSickLeaveReport: { findMany: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: async (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
|
||||
}));
|
||||
|
||||
import { listApprovedAbsencesForRange, listApprovedAbsencesForTeamRange } from "./hrLeaveService.server";
|
||||
|
||||
describe("approved absence range queries", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.tx.employeeVacationRequest.findMany.mockResolvedValue([]);
|
||||
mocks.tx.employeeSickLeaveReport.findMany.mockResolvedValue([]);
|
||||
mocks.tx.hrEmployeeProfile.findMany.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("filters closed sick-leave history in SQL instead of scanning it in memory", async () => {
|
||||
const from = new Date("2026-07-01T00:00:00.000Z");
|
||||
const to = new Date("2026-07-31T23:59:59.999Z");
|
||||
|
||||
await listApprovedAbsencesForRange("tenant-a", from, to);
|
||||
|
||||
expect(mocks.tx.employeeSickLeaveReport.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
tenantId: "tenant-a",
|
||||
status: { not: "cancelled" },
|
||||
startDate: { lte: to },
|
||||
OR: [
|
||||
{ returnDate: { gte: from } },
|
||||
{ returnDate: null, expectedReturnDate: { gte: from } },
|
||||
{ returnDate: null, expectedReturnDate: null, startDate: { gte: from } },
|
||||
],
|
||||
},
|
||||
select: { id: true, employeeUserId: true, startDate: true, returnDate: true, expectedReturnDate: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("limits the team feed to direct reports in SQL", async () => {
|
||||
mocks.tx.hrEmployeeProfile.findMany.mockResolvedValue([{ userId: "employee-a" }, { userId: "employee-b" }]);
|
||||
const from = new Date("2026-07-01T00:00:00.000Z");
|
||||
const to = new Date("2026-07-31T23:59:59.999Z");
|
||||
|
||||
await listApprovedAbsencesForTeamRange({
|
||||
tenantId: "tenant-a",
|
||||
viewerUserId: "manager-a",
|
||||
canReadAll: false,
|
||||
from,
|
||||
to,
|
||||
});
|
||||
|
||||
expect(mocks.tx.hrEmployeeProfile.findMany).toHaveBeenCalledWith({
|
||||
where: { tenantId: "tenant-a", managerUserId: "manager-a" },
|
||||
select: { userId: true },
|
||||
});
|
||||
expect(mocks.tx.employeeVacationRequest.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
tenantId: "tenant-a",
|
||||
employeeUserId: { in: ["employee-a", "employee-b"] },
|
||||
status: "approved",
|
||||
startDate: { lte: to },
|
||||
endDate: { gte: from },
|
||||
},
|
||||
select: { id: true, employeeUserId: true, startDate: true, endDate: true, requestKind: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("returns no team absence without querying tenant-wide rows when no direct reports exist", async () => {
|
||||
await expect(
|
||||
listApprovedAbsencesForTeamRange({
|
||||
tenantId: "tenant-a",
|
||||
viewerUserId: "manager-a",
|
||||
canReadAll: false,
|
||||
from: new Date("2026-07-01T00:00:00.000Z"),
|
||||
to: new Date("2026-07-31T23:59:59.999Z"),
|
||||
}),
|
||||
).resolves.toEqual([]);
|
||||
expect(mocks.tx.employeeVacationRequest.findMany).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.employeeSickLeaveReport.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+268
-70
@@ -9,14 +9,22 @@
|
||||
//
|
||||
// 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.
|
||||
// CalendarEvent sync (P16/M25): approving a request creates an internal all-day
|
||||
// calendar event for the employee (source hivegrid_internal, busy for
|
||||
// availability) and stores its id in `calendarEventId`. Approval is terminal in
|
||||
// this state machine (reject/withdraw only leave submitted/clarification), so
|
||||
// there is no post-approval cleanup path. R-P9b keeps reading the conflict feed
|
||||
// from approved requests directly — the event mirrors, it does not replace.
|
||||
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { CatalogError, foundationErrors, notify } from "@hivegrid/foundation";
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { createNotificationDelivery } from "@hivegrid/db/notifications.server";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
import { buildCalendarCreatedWorkflowEvent } from "~/services/automation/automation.producer-events.server";
|
||||
import { HrServiceError } from "./hrService.server";
|
||||
import type { HrM05Values } from "./hrM05Forms";
|
||||
import { createSystemHrSubmissionWithTx } from "./hrM05Submission.server";
|
||||
|
||||
const HR_AUDIT_MODULE = "hr";
|
||||
const MAX_NOTE_LENGTH = 2000;
|
||||
@@ -59,22 +67,39 @@ export type ApprovedAbsence = {
|
||||
|
||||
/** 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> {
|
||||
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);
|
||||
await withTenantRLS(input.tenantId, (tx) =>
|
||||
notify(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
userId: input.userId,
|
||||
channel: "IN_APP",
|
||||
category: "hr",
|
||||
messageKey: input.messageKey,
|
||||
sourceKey: input.sourceKey,
|
||||
payloadMetadata: input.payloadMetadata,
|
||||
},
|
||||
tx as unknown as Parameters<typeof notify>[1]
|
||||
)
|
||||
).catch(() => undefined);
|
||||
}
|
||||
|
||||
async function auditTransition(input: { tenantId: string; actorId: string; action: string; targetId: string; metadata?: Record<string, string> }): Promise<void> {
|
||||
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,
|
||||
@@ -98,7 +123,7 @@ function normaliseNote(note: string | null | undefined): string | null {
|
||||
/** 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" } }),
|
||||
tx.employeeVacationRequest.findMany({ where: { tenantId, employeeUserId }, orderBy: { createdAt: "desc" } })
|
||||
);
|
||||
return rows as VacationRequestRow[];
|
||||
}
|
||||
@@ -109,7 +134,7 @@ export async function listForApprover(tenantId: string, approverUserId: string):
|
||||
tx.employeeVacationRequest.findMany({
|
||||
where: { tenantId, assignedApproverUserId: approverUserId, status: { in: ["submitted", "clarification"] } },
|
||||
orderBy: { startDate: "asc" },
|
||||
}),
|
||||
})
|
||||
);
|
||||
return rows as VacationRequestRow[];
|
||||
}
|
||||
@@ -121,33 +146,79 @@ export async function listForApprover(tenantId: string, approverUserId: string):
|
||||
* 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;
|
||||
return withTenantRLS(tenantId, (tx) => listApprovedAbsencesForRangeWithTx(tx, tenantId, from, to));
|
||||
}
|
||||
|
||||
/**
|
||||
* R-UX3 team view. Unlike the stable Plantafel feed above, this always applies
|
||||
* an employee object scope: direct reports for a team lead, or the tenant when
|
||||
* an explicit HR-wide permission was already established by the route.
|
||||
*/
|
||||
export async function listApprovedAbsencesForTeamRange(input: {
|
||||
tenantId: string;
|
||||
viewerUserId: string;
|
||||
canReadAll: boolean;
|
||||
from: Date;
|
||||
to: Date;
|
||||
}): Promise<ApprovedAbsence[]> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const employeeUserIds = input.canReadAll
|
||||
? null
|
||||
: (
|
||||
await tx.hrEmployeeProfile.findMany({
|
||||
where: { tenantId: input.tenantId, managerUserId: input.viewerUserId },
|
||||
select: { userId: true },
|
||||
})
|
||||
).map(({ userId }) => userId);
|
||||
if (employeeUserIds?.length === 0) return [];
|
||||
return listApprovedAbsencesForRangeWithTx(tx, input.tenantId, input.from, input.to, employeeUserIds ?? undefined);
|
||||
});
|
||||
}
|
||||
|
||||
/** Reuse the caller's tenant transaction for race-free schedule conflict checks. */
|
||||
export async function listApprovedAbsencesForRangeWithTx(
|
||||
tx: TenantRlsClient,
|
||||
tenantId: string,
|
||||
from: Date,
|
||||
to: Date,
|
||||
employeeUserIds?: readonly string[]
|
||||
): Promise<ApprovedAbsence[]> {
|
||||
const employeeScope = employeeUserIds ? { employeeUserId: { in: [...employeeUserIds] } } : {};
|
||||
const [vacations, sick] = await Promise.all([
|
||||
tx.employeeVacationRequest.findMany({
|
||||
where: { tenantId, ...employeeScope, status: "approved", startDate: { lte: to }, endDate: { gte: from } },
|
||||
select: { id: true, employeeUserId: true, startDate: true, endDate: true, requestKind: true },
|
||||
}),
|
||||
tx.employeeSickLeaveReport.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
...employeeScope,
|
||||
status: { not: "cancelled" },
|
||||
startDate: { lte: to },
|
||||
OR: [
|
||||
{ returnDate: { gte: from } },
|
||||
{ returnDate: null, expectedReturnDate: { gte: from } },
|
||||
{ returnDate: null, expectedReturnDate: null, startDate: { gte: from } },
|
||||
],
|
||||
},
|
||||
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;
|
||||
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
|
||||
@@ -163,7 +234,7 @@ export async function countOverlappingApproved(tenantId: string, request: Pick<V
|
||||
startDate: { lte: request.endDate },
|
||||
endDate: { gte: request.startDate },
|
||||
},
|
||||
}),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -198,6 +269,7 @@ export type SubmitVacationInput = {
|
||||
note?: string | null;
|
||||
assignedApproverUserId?: string | null;
|
||||
isDemoData?: boolean;
|
||||
formValues?: HrM05Values;
|
||||
};
|
||||
|
||||
/** Submit a new vacation request (status = submitted). Notifies the approver. */
|
||||
@@ -208,8 +280,8 @@ export async function submitVacationRequest(input: SubmitVacationInput): Promise
|
||||
if (input.endDate < input.startDate) {
|
||||
throw new HrServiceError("hr.error.leaveRangeInvalid");
|
||||
}
|
||||
const created = (await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.employeeVacationRequest.create({
|
||||
const created = (await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const request = await tx.employeeVacationRequest.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
employeeUserId: input.employeeUserId,
|
||||
@@ -221,15 +293,52 @@ export async function submitVacationRequest(input: SubmitVacationInput): Promise
|
||||
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({
|
||||
});
|
||||
if (input.formValues) {
|
||||
await createSystemHrSubmissionWithTx(tx, {
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.employeeUserId,
|
||||
process: "leave",
|
||||
linkedEntityType: "hr_leave_request",
|
||||
linkedEntityId: request.id,
|
||||
values: input.formValues,
|
||||
});
|
||||
}
|
||||
await logActivity(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.employeeUserId,
|
||||
actorKind: "user",
|
||||
activityType: "form_submitted",
|
||||
subjectType: "tenant",
|
||||
subjectId: input.tenantId,
|
||||
summaryText: "activity.runtime.hr.leaveRequested",
|
||||
metadata: { requestId: request.id, process: "leave" },
|
||||
},
|
||||
{ client: tx }
|
||||
);
|
||||
if (request.assignedApproverUserId) {
|
||||
await notify(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
userId: request.assignedApproverUserId,
|
||||
channel: "IN_APP",
|
||||
category: "hr",
|
||||
messageKey: "hr.notify.leave.submitted",
|
||||
sourceKey: `hr-leave-submit:${request.id}`,
|
||||
payloadMetadata: { requestId: request.id },
|
||||
},
|
||||
tx as unknown as Parameters<typeof notify>[1]
|
||||
).catch(() => undefined);
|
||||
}
|
||||
return request;
|
||||
})) as VacationRequestRow;
|
||||
await auditTransition({
|
||||
tenantId: input.tenantId,
|
||||
userId: created.assignedApproverUserId,
|
||||
messageKey: "hr.notify.leave.submitted",
|
||||
sourceKey: `hr-leave-submit:${created.id}`,
|
||||
payloadMetadata: { requestId: created.id },
|
||||
actorId: input.employeeUserId,
|
||||
action: "HR_LEAVE_SUBMIT",
|
||||
targetId: created.id,
|
||||
metadata: { requestKind: input.requestKind },
|
||||
});
|
||||
return created;
|
||||
}
|
||||
@@ -248,41 +357,118 @@ async function loadDecidable(input: { tenantId: string; requestId: string; decid
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function approveRequest(input: { tenantId: string; requestId: string; deciderUserId: string; canApproveAny: boolean; decisionNote?: string | null }): Promise<void> {
|
||||
export async function approveRequest(input: {
|
||||
tenantId: string;
|
||||
requestId: string;
|
||||
deciderUserId: string;
|
||||
canApproveAny: boolean;
|
||||
decisionNote?: string | null;
|
||||
/** Resolved, locale-aware calendar titles per request kind (the service has
|
||||
* no i18n access — the route passes them, mirroring booking's pageTitle). */
|
||||
absenceTitleByKind?: Partial<Record<HrVacationRequestKind, string>>;
|
||||
}): Promise<void> {
|
||||
const row = await loadDecidable(input);
|
||||
await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.employeeVacationRequest.update({
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
// P16/M25 sync: the approved absence becomes an internal all-day event so
|
||||
// calendar/availability surfaces block the window (same convention as the
|
||||
// booking module: source hivegrid_internal + internalEntityLink).
|
||||
const event = await tx.calendarEvent.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
userId: row.employeeUserId,
|
||||
source: "hivegrid_internal",
|
||||
title: input.absenceTitleByKind?.[row.requestKind] ?? null,
|
||||
startsAt: row.startDate,
|
||||
endsAt: row.endDate,
|
||||
isAllDay: true,
|
||||
isBusyForAvailability: true,
|
||||
internalEntityLink: { type: "hr_vacation_request", id: row.id },
|
||||
isDemoData: (row as VacationRequestRow & { isDemoData?: boolean }).isDemoData ?? false,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
await tx.employeeVacationRequest.update({
|
||||
where: { id: row.id },
|
||||
data: { status: "approved", decidedByUserId: input.deciderUserId, decidedAt: new Date(), decisionNote: normaliseNote(input.decisionNote) },
|
||||
}),
|
||||
);
|
||||
data: {
|
||||
status: "approved",
|
||||
decidedByUserId: input.deciderUserId,
|
||||
decidedAt: new Date(),
|
||||
decisionNote: normaliseNote(input.decisionNote),
|
||||
calendarEventId: event.id,
|
||||
},
|
||||
});
|
||||
await publishOutboxEvent(
|
||||
tx as unknown as OutboxPublisherTransaction,
|
||||
buildCalendarCreatedWorkflowEvent({
|
||||
tenantId: input.tenantId,
|
||||
calendarEventId: event.id,
|
||||
userId: input.deciderUserId,
|
||||
calendarKey: "urlaubskalender",
|
||||
eventKind: "termin",
|
||||
source: "hr_leave",
|
||||
sourceEntityId: row.id,
|
||||
startsAt: row.startDate,
|
||||
endsAt: row.endDate,
|
||||
})
|
||||
);
|
||||
});
|
||||
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 } });
|
||||
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> {
|
||||
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 } });
|
||||
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> {
|
||||
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 } }),
|
||||
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 } });
|
||||
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. */
|
||||
@@ -297,10 +483,16 @@ export async function replyToClarification(input: { tenantId: string; requestId:
|
||||
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 } }),
|
||||
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 } });
|
||||
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. */
|
||||
@@ -313,8 +505,14 @@ export async function withdrawRequest(input: { tenantId: string; requestId: stri
|
||||
throw new HrServiceError("hr.error.leaveNotWithdrawable");
|
||||
}
|
||||
await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.employeeVacationRequest.update({ where: { id: row.id }, data: { status: "withdrawn", withdrawnAt: new Date() } }),
|
||||
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 } });
|
||||
await notifyQuiet({
|
||||
tenantId: input.tenantId,
|
||||
userId: row.assignedApproverUserId,
|
||||
messageKey: "hr.notify.leave.withdrawn",
|
||||
sourceKey: `hr-leave-withdraw:${row.id}`,
|
||||
payloadMetadata: { requestId: row.id },
|
||||
});
|
||||
}
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
import {
|
||||
FormDefinitionSchema,
|
||||
FormSubmissionPayloadSchema,
|
||||
type FormDefinition,
|
||||
type FormSubmissionPayload,
|
||||
} from "@hivegrid/form-widget";
|
||||
|
||||
export type HrM05Process = "leave" | "sick" | "request";
|
||||
export type HrM05Values = FormSubmissionPayload["values"];
|
||||
export type HrM05Translate = (key: string) => string;
|
||||
export type HrM05MemberOption = {
|
||||
userId: string;
|
||||
displayName: string;
|
||||
team: string | null;
|
||||
roleNames: readonly string[];
|
||||
};
|
||||
|
||||
const identity: HrM05Translate = (key) => key;
|
||||
|
||||
/**
|
||||
* `FormFieldSchema.options` accepts at most 50 entries. A tenant with more
|
||||
* active members used to overflow that cap, which made `FormDefinitionSchema`
|
||||
* throw inside the loader and turned /hr/leave, /hr/sick and /hr/requests into
|
||||
* 500s. Capping keeps the routes alive; the picker itself stays server-validated
|
||||
* (`requireActiveHrMember`), so a member beyond the cap is still a legal target.
|
||||
*/
|
||||
const MAX_PICKER_OPTIONS = 50;
|
||||
|
||||
function cappedMembers(
|
||||
members: readonly HrM05MemberOption[],
|
||||
reservedOptions = 0,
|
||||
): readonly HrM05MemberOption[] {
|
||||
return members.slice(0, Math.max(0, MAX_PICKER_OPTIONS - reservedOptions));
|
||||
}
|
||||
|
||||
export function parseHrM05Values(raw: string): HrM05Values | null {
|
||||
try {
|
||||
const parsed = FormSubmissionPayloadSchema.safeParse({
|
||||
values: JSON.parse(raw) as unknown,
|
||||
});
|
||||
return parsed.success ? parsed.data.values : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function buildHrLeaveFormDefinition(
|
||||
t: HrM05Translate = identity,
|
||||
members: readonly HrM05MemberOption[] = [],
|
||||
): FormDefinition {
|
||||
return FormDefinitionSchema.parse({
|
||||
title: t("hr.leave.action.new"),
|
||||
description: t("hr.m05.leaveDescription"),
|
||||
submitLabel: t("hr.leave.action.submit"),
|
||||
successMessage: t("hr.m05.success"),
|
||||
gdprConsentLabel: t("hr.m05.internalConsent"),
|
||||
captchaEnabled: false,
|
||||
fields: [
|
||||
{
|
||||
key: "requestKind",
|
||||
type: "select",
|
||||
label: t("hr.leave.field.kind"),
|
||||
required: true,
|
||||
options: [
|
||||
"vacation",
|
||||
"special_leave",
|
||||
"unpaid_leave",
|
||||
"overtime_compensation",
|
||||
].map((value) => ({ value, label: t(`hr.leave.kind.${value}`) })),
|
||||
},
|
||||
{
|
||||
key: "startDate",
|
||||
type: "date",
|
||||
label: t("hr.leave.field.start"),
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
key: "endDate",
|
||||
type: "date",
|
||||
label: t("hr.leave.field.end"),
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
key: "note",
|
||||
type: "textarea",
|
||||
label: t("hr.leave.field.note"),
|
||||
required: false,
|
||||
validationRules: { maxLength: 2000 },
|
||||
},
|
||||
...(members.length > 0
|
||||
? [
|
||||
{
|
||||
key: "approverUserId",
|
||||
type: "select" as const,
|
||||
label: t("hr.leave.field.approver"),
|
||||
required: false,
|
||||
options: [
|
||||
{ value: "__none__", label: t("hr.picker.noApprover") },
|
||||
...cappedMembers(members, 1).map((member) => ({
|
||||
value: member.userId,
|
||||
label: `${member.displayName} · ${member.team ?? t("hr.picker.noTeam")} · ${
|
||||
member.roleNames.join(", ") || t("hr.picker.noRole")
|
||||
}`,
|
||||
})),
|
||||
],
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
export function buildHrSickFormDefinition(
|
||||
t: HrM05Translate = identity,
|
||||
employeeOptions: readonly HrM05MemberOption[] = [],
|
||||
): FormDefinition {
|
||||
return FormDefinitionSchema.parse({
|
||||
title: t("hr.sick.action.report"),
|
||||
description: t("hr.m05.sickDescription"),
|
||||
submitLabel: t("hr.sick.action.report"),
|
||||
successMessage: t("hr.m05.success"),
|
||||
gdprConsentLabel: t("hr.m05.internalConsent"),
|
||||
captchaEnabled: false,
|
||||
fields: [
|
||||
{
|
||||
key: "startDate",
|
||||
type: "date",
|
||||
label: t("hr.sick.field.start"),
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
key: "expectedReturnDate",
|
||||
type: "date",
|
||||
label: t("hr.sick.field.expectedReturn"),
|
||||
required: false,
|
||||
},
|
||||
{
|
||||
key: "note",
|
||||
type: "textarea",
|
||||
label: t("hr.leave.field.note"),
|
||||
required: false,
|
||||
validationRules: { maxLength: 2000 },
|
||||
},
|
||||
...(employeeOptions.length > 0
|
||||
? [
|
||||
{
|
||||
key: "employeeUserId",
|
||||
type: "select" as const,
|
||||
label: t("hr.sick.field.employee"),
|
||||
required: true,
|
||||
options: cappedMembers(employeeOptions).map((member) => ({
|
||||
value: member.userId,
|
||||
label: `${member.displayName} · ${member.team ?? t("hr.picker.noTeam")} · ${
|
||||
member.roleNames.join(", ") || t("hr.picker.noRole")
|
||||
}`,
|
||||
})),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
export function buildHrRequestFormDefinition(
|
||||
t: HrM05Translate = identity,
|
||||
members: readonly HrM05MemberOption[] = [],
|
||||
): FormDefinition {
|
||||
return FormDefinitionSchema.parse({
|
||||
title: t("hr.requests.action.new"),
|
||||
description: t("hr.m05.requestDescription"),
|
||||
submitLabel: t("hr.requests.action.submit"),
|
||||
successMessage: t("hr.m05.success"),
|
||||
gdprConsentLabel: t("hr.m05.internalConsent"),
|
||||
captchaEnabled: false,
|
||||
fields: [
|
||||
{
|
||||
key: "requestKind",
|
||||
type: "select",
|
||||
label: t("hr.requests.field.kind"),
|
||||
required: true,
|
||||
options: ["expense", "hardware", "training", "reference"].map((value) => ({
|
||||
value,
|
||||
label: t(`hr.requests.kind.${value}`),
|
||||
})),
|
||||
},
|
||||
{
|
||||
key: "title",
|
||||
type: "text",
|
||||
label: t("hr.requests.field.title"),
|
||||
required: true,
|
||||
validationRules: { maxLength: 255 },
|
||||
},
|
||||
{
|
||||
key: "details",
|
||||
type: "textarea",
|
||||
label: t("hr.requests.field.details"),
|
||||
required: false,
|
||||
validationRules: { maxLength: 8000 },
|
||||
},
|
||||
...(members.length > 0
|
||||
? [
|
||||
{
|
||||
key: "approverUserId",
|
||||
type: "select" as const,
|
||||
label: t("hr.requests.field.approver"),
|
||||
required: false,
|
||||
options: [
|
||||
{ value: "__none__", label: t("hr.picker.noApprover") },
|
||||
...cappedMembers(members, 1).map((member) => ({
|
||||
value: member.userId,
|
||||
label: `${member.displayName} · ${member.team ?? t("hr.picker.noTeam")} · ${
|
||||
member.roleNames.join(", ") || t("hr.picker.noRole")
|
||||
}`,
|
||||
})),
|
||||
],
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
});
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tx: {
|
||||
form: {
|
||||
upsert: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
},
|
||||
formSubmission: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
hrRequestTemplate: {
|
||||
findFirst: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import {
|
||||
createSystemHrSubmissionWithTx,
|
||||
createTemplateHrRequestSubmissionWithTx,
|
||||
} from "./hrM05Submission.server";
|
||||
import { buildHrRequestFormDefinition } from "./hrM05Forms";
|
||||
|
||||
describe("internal HR M05 submission contract", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.tx.form.upsert.mockResolvedValue({ id: "system-form" });
|
||||
mocks.tx.formSubmission.create.mockResolvedValue({ id: "submission-1" });
|
||||
mocks.tx.hrRequestTemplate.findFirst.mockResolvedValue({
|
||||
linkedFormId: "template-form",
|
||||
});
|
||||
mocks.tx.form.findFirst.mockResolvedValue({
|
||||
id: "template-form",
|
||||
definition: buildHrRequestFormDefinition(),
|
||||
});
|
||||
});
|
||||
|
||||
it("upserts a private internal form and links a validated leave submission", async () => {
|
||||
const submissionId = await createSystemHrSubmissionWithTx(
|
||||
mocks.tx as never,
|
||||
{
|
||||
tenantId: "tenant-1",
|
||||
actorUserId: "employee-1",
|
||||
process: "leave",
|
||||
linkedEntityType: "hr_leave_request",
|
||||
linkedEntityId: "leave-1",
|
||||
values: {
|
||||
requestKind: "vacation",
|
||||
startDate: "2026-07-28",
|
||||
endDate: "2026-07-31",
|
||||
note: "",
|
||||
approverUserId: "manager-1",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(submissionId).toBe("submission-1");
|
||||
expect(mocks.tx.form.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: {
|
||||
tenantId_slug: {
|
||||
tenantId: "tenant-1",
|
||||
slug: "__hivegrid_hr_leave",
|
||||
},
|
||||
},
|
||||
update: expect.objectContaining({
|
||||
subtype: "internal",
|
||||
status: "published",
|
||||
isPublic: false,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(mocks.tx.formSubmission.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
formId: "system-form",
|
||||
tenantId: "tenant-1",
|
||||
createdByUserId: "employee-1",
|
||||
payload: {
|
||||
values: {
|
||||
requestKind: "vacation",
|
||||
startDate: "2026-07-28",
|
||||
endDate: "2026-07-31",
|
||||
note: "",
|
||||
},
|
||||
},
|
||||
status: "received",
|
||||
linkedEntityType: "hr_leave_request",
|
||||
linkedEntityId: "leave-1",
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects an incomplete payload before persisting a submission", async () => {
|
||||
await expect(
|
||||
createSystemHrSubmissionWithTx(mocks.tx as never, {
|
||||
tenantId: "tenant-1",
|
||||
actorUserId: "employee-1",
|
||||
process: "sick",
|
||||
linkedEntityType: "hr_sick_leave",
|
||||
linkedEntityId: "sick-1",
|
||||
values: { expectedReturnDate: "2026-07-31" },
|
||||
}),
|
||||
).rejects.toThrow("hr.m05.validation.FIELD_REQUIRED");
|
||||
|
||||
expect(mocks.tx.formSubmission.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("requires an active published hr_request form for templates", async () => {
|
||||
mocks.tx.hrRequestTemplate.findFirst.mockResolvedValue({
|
||||
linkedFormId: "missing-form",
|
||||
});
|
||||
mocks.tx.form.findFirst.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
createTemplateHrRequestSubmissionWithTx(mocks.tx as never, {
|
||||
tenantId: "tenant-1",
|
||||
actorUserId: "employee-1",
|
||||
templateId: "template-1",
|
||||
linkedEntityId: "request-1",
|
||||
values: {
|
||||
requestKind: "hardware",
|
||||
title: "Notebook",
|
||||
details: "",
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("hr.m05.templateFormUnavailable");
|
||||
|
||||
expect(mocks.tx.form.findFirst).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({
|
||||
tenantId: "tenant-1",
|
||||
subtype: "hr_request",
|
||||
status: "published",
|
||||
isEnabled: true,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
import {
|
||||
filterVisibleFields,
|
||||
FormDefinitionSchema,
|
||||
validateFormValues,
|
||||
type FormDefinition,
|
||||
type FormSubmissionPayload,
|
||||
} from "@hivegrid/form-widget";
|
||||
import type { TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
import { HrServiceError } from "./hrService.server";
|
||||
import {
|
||||
buildHrLeaveFormDefinition,
|
||||
buildHrRequestFormDefinition,
|
||||
buildHrSickFormDefinition,
|
||||
type HrM05Process,
|
||||
} from "./hrM05Forms";
|
||||
|
||||
type HrM05Values = FormSubmissionPayload["values"];
|
||||
|
||||
const SYSTEM_DEFINITIONS: Record<HrM05Process, () => FormDefinition> = {
|
||||
leave: buildHrLeaveFormDefinition,
|
||||
sick: buildHrSickFormDefinition,
|
||||
request: buildHrRequestFormDefinition,
|
||||
};
|
||||
|
||||
function validatedValues(
|
||||
definition: FormDefinition,
|
||||
values: HrM05Values,
|
||||
): HrM05Values {
|
||||
const parsed = FormDefinitionSchema.parse(definition);
|
||||
const visibleKeys = new Set(filterVisibleFields(parsed.fields, values).map((field) => field.key));
|
||||
const filtered = Object.fromEntries(
|
||||
Object.entries(values).filter(([key]) => visibleKeys.has(key)),
|
||||
) as HrM05Values;
|
||||
const validationError = validateFormValues(filtered, parsed);
|
||||
if (validationError) {
|
||||
throw new HrServiceError(`hr.m05.validation.${validationError.code}`);
|
||||
}
|
||||
return filtered;
|
||||
}
|
||||
|
||||
async function ensureSystemFormWithTx(
|
||||
tx: TenantRlsClient,
|
||||
input: {
|
||||
tenantId: string;
|
||||
actorUserId: string;
|
||||
process: HrM05Process;
|
||||
},
|
||||
): Promise<{ id: string; definition: FormDefinition }> {
|
||||
const definition = SYSTEM_DEFINITIONS[input.process]();
|
||||
const slug = `__hivegrid_hr_${input.process}`;
|
||||
const form = await tx.form.upsert({
|
||||
where: { tenantId_slug: { tenantId: input.tenantId, slug } },
|
||||
update: {
|
||||
name: `Internal HR ${input.process}`,
|
||||
subtype: "internal",
|
||||
status: "published",
|
||||
isPublic: false,
|
||||
isEnabled: true,
|
||||
definition: definition as object,
|
||||
},
|
||||
create: {
|
||||
tenantId: input.tenantId,
|
||||
createdByUserId: input.actorUserId,
|
||||
name: `Internal HR ${input.process}`,
|
||||
slug,
|
||||
subtype: "internal",
|
||||
status: "published",
|
||||
publishedAt: new Date(),
|
||||
isPublic: false,
|
||||
isEnabled: true,
|
||||
definition: definition as object,
|
||||
allowedOrigins: [],
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
return { id: form.id, definition };
|
||||
}
|
||||
|
||||
export async function createSystemHrSubmissionWithTx(
|
||||
tx: TenantRlsClient,
|
||||
input: {
|
||||
tenantId: string;
|
||||
actorUserId: string;
|
||||
process: HrM05Process;
|
||||
linkedEntityType: string;
|
||||
linkedEntityId: string;
|
||||
values: HrM05Values;
|
||||
},
|
||||
): Promise<string> {
|
||||
const form = await ensureSystemFormWithTx(tx, input);
|
||||
const values = validatedValues(form.definition, input.values);
|
||||
const submission = await tx.formSubmission.create({
|
||||
data: {
|
||||
formId: form.id,
|
||||
tenantId: input.tenantId,
|
||||
createdByUserId: input.actorUserId,
|
||||
payload: { values },
|
||||
status: "received",
|
||||
linkedEntityType: input.linkedEntityType,
|
||||
linkedEntityId: input.linkedEntityId,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
return submission.id;
|
||||
}
|
||||
|
||||
export async function createTemplateHrRequestSubmissionWithTx(
|
||||
tx: TenantRlsClient,
|
||||
input: {
|
||||
tenantId: string;
|
||||
actorUserId: string;
|
||||
templateId: string;
|
||||
linkedEntityId: string;
|
||||
values: HrM05Values;
|
||||
},
|
||||
): Promise<string> {
|
||||
const template = await tx.hrRequestTemplate.findFirst({
|
||||
where: {
|
||||
id: input.templateId,
|
||||
tenantId: input.tenantId,
|
||||
archivedAt: null,
|
||||
isActive: true,
|
||||
},
|
||||
select: {
|
||||
linkedFormId: true,
|
||||
},
|
||||
});
|
||||
if (!template?.linkedFormId) {
|
||||
throw new HrServiceError("hr.m05.templateFormRequired");
|
||||
}
|
||||
const form = await tx.form.findFirst({
|
||||
where: {
|
||||
id: template.linkedFormId,
|
||||
tenantId: input.tenantId,
|
||||
subtype: "hr_request",
|
||||
status: "published",
|
||||
isEnabled: true,
|
||||
},
|
||||
select: { id: true, definition: true },
|
||||
});
|
||||
if (!form) {
|
||||
throw new HrServiceError("hr.m05.templateFormUnavailable");
|
||||
}
|
||||
const parsedDefinition = FormDefinitionSchema.safeParse(form.definition);
|
||||
if (!parsedDefinition.success) {
|
||||
throw new HrServiceError("hr.m05.templateFormInvalid");
|
||||
}
|
||||
const values = validatedValues(parsedDefinition.data, input.values);
|
||||
const submission = await tx.formSubmission.create({
|
||||
data: {
|
||||
formId: form.id,
|
||||
tenantId: input.tenantId,
|
||||
createdByUserId: input.actorUserId,
|
||||
payload: { values },
|
||||
status: "received",
|
||||
linkedEntityType: "hr_request",
|
||||
linkedEntityId: input.linkedEntityId,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
return submission.id;
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tx: {
|
||||
employeePasswordSafeVault: { findFirst: vi.fn(), findMany: vi.fn(), updateMany: vi.fn() },
|
||||
employeePasswordSafeAccess: { findFirst: vi.fn() },
|
||||
employeePasswordSafeEntry: { findMany: vi.fn(), updateMany: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: (_tenantId: string, callback: (tx: typeof mocks.tx) => unknown) => callback(mocks.tx),
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({ createAuditEvent: vi.fn() }));
|
||||
|
||||
import { archiveVault, listAccessibleVaults, listEntries, restoreEntry, restoreVault } from "./hrPasswordSafeService.server";
|
||||
|
||||
describe("password-safe archive lifecycle", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.tx.employeePasswordSafeVault.findFirst.mockResolvedValue({ id: "vault-1" });
|
||||
mocks.tx.employeePasswordSafeAccess.findFirst.mockResolvedValue({ permissionLevel: "write" });
|
||||
mocks.tx.employeePasswordSafeEntry.findMany.mockResolvedValue([]);
|
||||
mocks.tx.employeePasswordSafeEntry.updateMany.mockResolvedValue({ count: 1 });
|
||||
mocks.tx.employeePasswordSafeVault.updateMany.mockResolvedValue({ count: 1 });
|
||||
mocks.tx.employeePasswordSafeVault.findMany.mockResolvedValue([
|
||||
{
|
||||
id: "vault-1",
|
||||
tenantId: "tenant-1",
|
||||
name: "Operations",
|
||||
description: null,
|
||||
createdByUserId: "user-1",
|
||||
isDemoData: false,
|
||||
createdAt: new Date(0),
|
||||
updatedAt: new Date(0),
|
||||
archivedAt: null,
|
||||
access: [{ permissionLevel: "admin" }],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("lists active and archived entries through separate metadata-only queries", async () => {
|
||||
await listEntries({ tenantId: "tenant-1", vaultId: "vault-1", userId: "user-1" });
|
||||
expect(mocks.tx.employeePasswordSafeEntry.findMany).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ where: { tenantId: "tenant-1", vaultId: "vault-1", archivedAt: null } })
|
||||
);
|
||||
|
||||
await listEntries({ tenantId: "tenant-1", vaultId: "vault-1", userId: "user-1", archived: true });
|
||||
expect(mocks.tx.employeePasswordSafeEntry.findMany).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ where: { tenantId: "tenant-1", vaultId: "vault-1", archivedAt: { not: null } } })
|
||||
);
|
||||
const select = mocks.tx.employeePasswordSafeEntry.findMany.mock.calls.at(-1)?.[0].select;
|
||||
expect(select).not.toHaveProperty("username");
|
||||
expect(select).not.toHaveProperty("password");
|
||||
expect(select).not.toHaveProperty("notes");
|
||||
});
|
||||
|
||||
it("returns the caller's actual access level with each accessible vault", async () => {
|
||||
await expect(listAccessibleVaults("tenant-1", "user-1")).resolves.toEqual([expect.objectContaining({ id: "vault-1", accessLevel: "admin" })]);
|
||||
expect(mocks.tx.employeePasswordSafeVault.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { tenantId: "tenant-1", archivedAt: null, access: { some: { tenantId: "tenant-1", userId: "user-1" } } },
|
||||
include: { access: { where: { tenantId: "tenant-1", userId: "user-1" }, select: { permissionLevel: true }, take: 1 } },
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("restores only an archived entry in the caller's tenant and vault", async () => {
|
||||
await restoreEntry({ tenantId: "tenant-1", vaultId: "vault-1", entryId: "entry-1", userId: "user-1" });
|
||||
expect(mocks.tx.employeePasswordSafeEntry.updateMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: "entry-1",
|
||||
tenantId: "tenant-1",
|
||||
vaultId: "vault-1",
|
||||
archivedAt: { not: null },
|
||||
},
|
||||
data: { archivedAt: null },
|
||||
});
|
||||
});
|
||||
|
||||
it("does not report a missing or already-active entry as restored", async () => {
|
||||
mocks.tx.employeePasswordSafeEntry.updateMany.mockResolvedValue({ count: 0 });
|
||||
await expect(restoreEntry({ tenantId: "tenant-1", vaultId: "vault-1", entryId: "missing", userId: "user-1" })).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("archives and restores a vault only through inverse lifecycle filters", async () => {
|
||||
await archiveVault({ tenantId: "tenant-1", vaultId: "vault-1", userId: "admin-1", isTenantPasswordSafeAdmin: true });
|
||||
expect(mocks.tx.employeePasswordSafeVault.updateMany).toHaveBeenLastCalledWith({
|
||||
where: { id: "vault-1", tenantId: "tenant-1", archivedAt: null },
|
||||
data: { archivedAt: expect.any(Date) },
|
||||
});
|
||||
|
||||
await restoreVault({ tenantId: "tenant-1", vaultId: "vault-1", userId: "admin-1", isTenantPasswordSafeAdmin: true });
|
||||
expect(mocks.tx.employeePasswordSafeVault.updateMany).toHaveBeenLastCalledWith({
|
||||
where: { id: "vault-1", tenantId: "tenant-1", archivedAt: { not: null } },
|
||||
data: { archivedAt: null },
|
||||
});
|
||||
});
|
||||
|
||||
it("does not restore a vault without the tenant-wide admin capability", async () => {
|
||||
await expect(restoreVault({ tenantId: "tenant-1", vaultId: "vault-1", userId: "user-1", isTenantPasswordSafeAdmin: false })).rejects.toThrow();
|
||||
expect(mocks.tx.employeePasswordSafeVault.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
audit: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
tx: {
|
||||
employeePasswordSafeVault: { findFirst: vi.fn(), findMany: vi.fn() },
|
||||
employeePasswordSafeAccess: {
|
||||
findFirst: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
count: vi.fn(),
|
||||
upsert: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
},
|
||||
employeePasswordSafeEntry: { findFirst: vi.fn(), findMany: vi.fn(), updateMany: vi.fn() },
|
||||
tenantUser: { findFirst: vi.fn(), findMany: vi.fn() },
|
||||
userRole: { findMany: vi.fn() },
|
||||
auditEvent: { findMany: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: (_tenantId: string, callback: (tx: typeof mocks.tx) => unknown) => callback(mocks.tx),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({ createAuditEvent: mocks.audit }));
|
||||
vi.mock("@hivegrid/foundation", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@hivegrid/foundation")>()),
|
||||
notify: mocks.notify,
|
||||
}));
|
||||
|
||||
import {
|
||||
archiveEntry,
|
||||
copyEntryValue,
|
||||
exportVault,
|
||||
getVaultForUser,
|
||||
grantAccess,
|
||||
listAccessibleVaults,
|
||||
listPasswordSafeActivity,
|
||||
revokeAccess,
|
||||
} from "./hrPasswordSafeService.server";
|
||||
|
||||
const crypto = {
|
||||
encrypt: vi.fn(async (_tenantId: string, value: string) => `cipher:${value}`),
|
||||
decrypt: vi.fn(async (_tenantId: string, value: string) => value.replace("cipher:", "")),
|
||||
};
|
||||
|
||||
describe("password-safe object permissions and command auditing", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.tx.employeePasswordSafeVault.findFirst.mockResolvedValue({ id: "vault-1", tenantId: "tenant-1", name: "Ops", archivedAt: null });
|
||||
mocks.tx.employeePasswordSafeVault.findMany.mockResolvedValue([]);
|
||||
mocks.tx.employeePasswordSafeAccess.findFirst.mockResolvedValue({ permissionLevel: "admin" });
|
||||
mocks.tx.employeePasswordSafeAccess.findMany.mockResolvedValue([]);
|
||||
mocks.tx.employeePasswordSafeAccess.count.mockResolvedValue(2);
|
||||
mocks.tx.employeePasswordSafeAccess.upsert.mockResolvedValue({ id: "access-1" });
|
||||
mocks.tx.employeePasswordSafeAccess.deleteMany.mockResolvedValue({ count: 1 });
|
||||
mocks.tx.employeePasswordSafeEntry.findMany.mockResolvedValue([]);
|
||||
mocks.tx.employeePasswordSafeEntry.updateMany.mockResolvedValue({ count: 1 });
|
||||
mocks.tx.tenantUser.findFirst.mockResolvedValue({ id: "member-1" });
|
||||
mocks.tx.tenantUser.findMany.mockResolvedValue([]);
|
||||
mocks.tx.userRole.findMany.mockResolvedValue([]);
|
||||
mocks.tx.auditEvent.findMany.mockResolvedValue([]);
|
||||
mocks.audit.mockResolvedValue({ id: "audit-1" });
|
||||
mocks.notify.mockResolvedValue({ id: "notification-1" });
|
||||
});
|
||||
|
||||
it("rejects a grant target outside the active tenant membership", async () => {
|
||||
mocks.tx.tenantUser.findFirst.mockResolvedValue(null);
|
||||
await expect(
|
||||
grantAccess({ tenantId: "tenant-1", vaultId: "vault-1", targetUserId: "outsider", permissionLevel: "read", actorUserId: "admin-1" })
|
||||
).rejects.toThrow();
|
||||
expect(mocks.tx.employeePasswordSafeAccess.upsert).not.toHaveBeenCalled();
|
||||
expect(mocks.audit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("prevents downgrading or revoking the last vault admin", async () => {
|
||||
mocks.tx.employeePasswordSafeAccess.count.mockResolvedValue(1);
|
||||
await expect(
|
||||
grantAccess({ tenantId: "tenant-1", vaultId: "vault-1", targetUserId: "admin-1", permissionLevel: "write", actorUserId: "admin-1" })
|
||||
).rejects.toMatchObject({ messageKey: "hr.error.lastVaultAdmin" });
|
||||
expect(mocks.tx.employeePasswordSafeAccess.upsert).not.toHaveBeenCalled();
|
||||
|
||||
mocks.tx.employeePasswordSafeAccess.findFirst.mockResolvedValue({ permissionLevel: "admin" });
|
||||
await expect(
|
||||
revokeAccess({ tenantId: "tenant-1", vaultId: "vault-1", targetUserId: "admin-1", actorUserId: "admin-1" })
|
||||
).rejects.toMatchObject({ messageKey: "hr.error.lastVaultAdmin" });
|
||||
expect(mocks.tx.employeePasswordSafeAccess.deleteMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("audits and notifies a named access change without secret material", async () => {
|
||||
mocks.tx.employeePasswordSafeAccess.findFirst
|
||||
.mockResolvedValueOnce({ permissionLevel: "admin" })
|
||||
.mockResolvedValueOnce(null);
|
||||
await grantAccess({ tenantId: "tenant-1", vaultId: "vault-1", targetUserId: "member-1", permissionLevel: "read", actorUserId: "admin-1" });
|
||||
expect(mocks.audit).toHaveBeenCalledWith(expect.objectContaining({ action: "HR_PASSWORD_SAFE_ACCESS_GRANT", dataSensitivity: "internal" }));
|
||||
expect(mocks.notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ userId: "member-1", messageKey: "hr.passwordSafe.notification.accessGranted" }),
|
||||
mocks.tx
|
||||
);
|
||||
expect(JSON.stringify(mocks.audit.mock.calls)).not.toMatch(/passwordCiphertext|usernameCiphertext|notesCiphertext/u);
|
||||
});
|
||||
|
||||
it("copy re-checks read access and writes a distinct confidential audit event", async () => {
|
||||
mocks.tx.employeePasswordSafeAccess.findFirst.mockResolvedValue({ permissionLevel: "read" });
|
||||
mocks.tx.employeePasswordSafeEntry.findFirst.mockResolvedValue({
|
||||
id: "entry-1",
|
||||
usernameCiphertext: "cipher:alice",
|
||||
passwordCiphertext: "cipher:secret",
|
||||
notesCiphertext: null,
|
||||
});
|
||||
await expect(
|
||||
copyEntryValue({ tenantId: "tenant-1", vaultId: "vault-1", entryId: "entry-1", userId: "member-1", field: "password" }, crypto)
|
||||
).resolves.toBe("secret");
|
||||
expect(mocks.audit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ action: "HR_PASSWORD_SAFE_COPY", dataSensitivity: "confidential", metadata: { vaultId: "vault-1", field: "password" } })
|
||||
);
|
||||
});
|
||||
|
||||
it("enforces read, write and admin as separate object roles and grants no content access to a metadata admin", async () => {
|
||||
mocks.tx.employeePasswordSafeAccess.findFirst.mockResolvedValue({ permissionLevel: "read" });
|
||||
await expect(
|
||||
archiveEntry({ tenantId: "tenant-1", vaultId: "vault-1", entryId: "entry-1", userId: "reader-1" })
|
||||
).rejects.toThrow();
|
||||
expect(mocks.tx.employeePasswordSafeEntry.updateMany).not.toHaveBeenCalled();
|
||||
|
||||
mocks.tx.employeePasswordSafeAccess.findFirst.mockResolvedValue({ permissionLevel: "write" });
|
||||
await expect(
|
||||
archiveEntry({ tenantId: "tenant-1", vaultId: "vault-1", entryId: "entry-1", userId: "writer-1" })
|
||||
).resolves.toBeUndefined();
|
||||
await expect(
|
||||
grantAccess({ tenantId: "tenant-1", vaultId: "vault-1", targetUserId: "member-1", permissionLevel: "read", actorUserId: "writer-1" })
|
||||
).rejects.toThrow();
|
||||
|
||||
mocks.tx.employeePasswordSafeAccess.findFirst.mockResolvedValue(null);
|
||||
await expect(getVaultForUser("tenant-1", "vault-1", "metadata-admin-1")).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("keeps metadata search access-scoped and never queries entry secrets", async () => {
|
||||
await listAccessibleVaults("tenant-1", "member-1", { search: "router" });
|
||||
expect(mocks.tx.employeePasswordSafeVault.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: {
|
||||
tenantId: "tenant-1",
|
||||
archivedAt: null,
|
||||
access: { some: { tenantId: "tenant-1", userId: "member-1" } },
|
||||
OR: [
|
||||
{ name: { contains: "router", mode: "insensitive" } },
|
||||
{ description: { contains: "router", mode: "insensitive" } },
|
||||
],
|
||||
},
|
||||
})
|
||||
);
|
||||
expect(mocks.tx.employeePasswordSafeEntry.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns a redacted activity timeline without audit metadata or raw actor ids", async () => {
|
||||
mocks.tx.auditEvent.findMany.mockResolvedValue([{
|
||||
id: "audit-1",
|
||||
createdAt: new Date("2026-07-25T10:00:00Z"),
|
||||
action: "HR_PASSWORD_SAFE_REVEAL",
|
||||
actorId: "opaque-user-id",
|
||||
outcome: "success",
|
||||
metadata: { field: "password", entryId: "secret-entry-id" },
|
||||
}]);
|
||||
mocks.tx.tenantUser.findMany.mockResolvedValue([{
|
||||
userId: "opaque-user-id",
|
||||
user: { firstName: "Mira", lastName: "Beispiel", email: "mira@example.test" },
|
||||
}]);
|
||||
const timeline = await listPasswordSafeActivity({
|
||||
tenantId: "tenant-1",
|
||||
userId: "metadata-admin-1",
|
||||
isTenantPasswordSafeAdmin: true,
|
||||
});
|
||||
expect(timeline).toEqual([expect.objectContaining({ action: "HR_PASSWORD_SAFE_REVEAL", actorLabel: "Mira Beispiel" })]);
|
||||
expect(JSON.stringify(timeline)).not.toMatch(/opaque-user-id|secret-entry-id|entryId|field/u);
|
||||
});
|
||||
|
||||
it("fails closed in the service when the separate export permission is absent", async () => {
|
||||
await expect(
|
||||
exportVault({ tenantId: "tenant-1", vaultId: "vault-1", userId: "member-1", hasExportPermission: false }, crypto)
|
||||
).rejects.toThrow();
|
||||
expect(mocks.tx.employeePasswordSafeEntry.findMany).not.toHaveBeenCalled();
|
||||
expect(mocks.audit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("exports only with the separate permission and records a confidential GDPR audit event", async () => {
|
||||
mocks.tx.employeePasswordSafeAccess.findFirst.mockResolvedValue({ permissionLevel: "read" });
|
||||
await expect(
|
||||
exportVault({ tenantId: "tenant-1", vaultId: "vault-1", userId: "member-1", hasExportPermission: true }, crypto)
|
||||
).resolves.toEqual({ vaultName: "Ops", entries: [] });
|
||||
expect(mocks.audit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: "HR_PASSWORD_SAFE_EXPORT",
|
||||
dataSensitivity: "confidential",
|
||||
regulatoryScope: ["gdpr"],
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
+514
-69
@@ -3,7 +3,7 @@
|
||||
// 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
|
||||
// admin view (/password-safe/admin, 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
|
||||
@@ -13,20 +13,19 @@
|
||||
// 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.
|
||||
// The production crypto binding uses the tenant envelope provider. If its key
|
||||
// material is unavailable, the M002 catalog error is surfaced fail-closed rather
|
||||
// than storing or returning plaintext.
|
||||
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { CatalogError, foundationErrors, notify } from "@hivegrid/foundation";
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
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";
|
||||
const PASSWORD_SAFE_AUDIT_PREFIX = "HR_PASSWORD_SAFE_";
|
||||
|
||||
export type PasswordSafePermissionLevel = "read" | "write" | "admin";
|
||||
export type PasswordSafeSecretField = "username" | "password" | "notes";
|
||||
@@ -37,6 +36,31 @@ function meetsLevel(have: PasswordSafePermissionLevel, need: PasswordSafePermiss
|
||||
return LEVEL_RANK[have] >= LEVEL_RANK[need];
|
||||
}
|
||||
|
||||
async function auditPasswordSafe(input: {
|
||||
tenantId: string;
|
||||
actorUserId: string;
|
||||
action: string;
|
||||
targetType: "EmployeePasswordSafeVault" | "EmployeePasswordSafeEntry" | "EmployeePasswordSafeAccess";
|
||||
targetId: string;
|
||||
metadata?: Record<string, string | number | boolean | null>;
|
||||
confidential?: boolean;
|
||||
regulatoryScope?: Array<"gdpr">;
|
||||
}): Promise<void> {
|
||||
await createAuditEvent({
|
||||
tenantId: input.tenantId,
|
||||
actorId: input.actorUserId,
|
||||
actorType: "user",
|
||||
action: `${PASSWORD_SAFE_AUDIT_PREFIX}${input.action}`,
|
||||
targetType: input.targetType,
|
||||
targetId: input.targetId,
|
||||
sourceModule: HR_AUDIT_MODULE,
|
||||
dataSensitivity: input.confidential ? "confidential" : "internal",
|
||||
regulatoryScope: input.regulatoryScope,
|
||||
outcome: "success",
|
||||
metadata: input.metadata,
|
||||
});
|
||||
}
|
||||
|
||||
// --- Vault rows -----------------------------------------------------------
|
||||
|
||||
export type VaultRow = {
|
||||
@@ -81,7 +105,11 @@ export async function resolveVaultAccess(tenantId: string, vaultId: string, user
|
||||
}
|
||||
|
||||
/** 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> {
|
||||
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) {
|
||||
@@ -101,7 +129,7 @@ async function requireVaultWithAccessWithTx(
|
||||
tenantId: string,
|
||||
vaultId: string,
|
||||
userId: string,
|
||||
need: PasswordSafePermissionLevel,
|
||||
need: PasswordSafePermissionLevel
|
||||
): Promise<{ vault: VaultRow; level: PasswordSafePermissionLevel }> {
|
||||
const vault = await tx.employeePasswordSafeVault.findFirst({ where: { id: vaultId, tenantId, archivedAt: null } });
|
||||
if (!vault) {
|
||||
@@ -118,22 +146,58 @@ async function requireVaultWithAccessWithTx(
|
||||
// --- 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[]> {
|
||||
export async function listAccessibleVaults(
|
||||
tenantId: string,
|
||||
userId: string,
|
||||
opts?: { search?: string }
|
||||
): Promise<Array<VaultRow & { accessLevel: PasswordSafePermissionLevel }>> {
|
||||
const search = opts?.search?.trim().slice(0, 100) ?? "";
|
||||
const rows = await withTenantRLS(tenantId, (tx) =>
|
||||
tx.employeePasswordSafeVault.findMany({
|
||||
where: { tenantId, archivedAt: null, access: { some: { tenantId, userId } } },
|
||||
where: {
|
||||
tenantId,
|
||||
archivedAt: null,
|
||||
access: { some: { tenantId, userId } },
|
||||
...(search
|
||||
? {
|
||||
OR: [
|
||||
{ name: { contains: search, mode: "insensitive" } },
|
||||
{ description: { contains: search, mode: "insensitive" } },
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
include: { access: { where: { tenantId, userId }, select: { permissionLevel: true }, take: 1 } },
|
||||
orderBy: { name: "asc" },
|
||||
}),
|
||||
})
|
||||
);
|
||||
return rows as VaultRow[];
|
||||
return rows.map(({ access, ...vault }) => ({
|
||||
...(vault as VaultRow),
|
||||
accessLevel: (access[0]?.permissionLevel as PasswordSafePermissionLevel | undefined) ?? "read",
|
||||
}));
|
||||
}
|
||||
|
||||
/** 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 }>> {
|
||||
export async function adminListAllVaults(
|
||||
tenantId: string,
|
||||
opts?: { includeArchived?: boolean; userId?: string; search?: string }
|
||||
): Promise<Array<VaultRow & { entryCount: number; accessCount: number; hasContentAccess: boolean }>> {
|
||||
const search = opts?.search?.trim().slice(0, 100) ?? "";
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
const vaults = await tx.employeePasswordSafeVault.findMany({
|
||||
where: { tenantId, ...(opts?.includeArchived ? {} : { archivedAt: null }) },
|
||||
where: {
|
||||
tenantId,
|
||||
...(opts?.includeArchived ? {} : { archivedAt: null }),
|
||||
...(search
|
||||
? {
|
||||
OR: [
|
||||
{ name: { contains: search, mode: "insensitive" } },
|
||||
{ description: { contains: search, mode: "insensitive" } },
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
const withCounts = await Promise.all(
|
||||
@@ -142,26 +206,53 @@ export async function adminListAllVaults(tenantId: string, opts?: { includeArchi
|
||||
tx.employeePasswordSafeEntry.count({ where: { tenantId, vaultId: vault.id, archivedAt: null } }),
|
||||
tx.employeePasswordSafeAccess.count({ where: { tenantId, vaultId: vault.id } }),
|
||||
]);
|
||||
return { ...(vault as VaultRow), entryCount, accessCount };
|
||||
}),
|
||||
const hasContentAccess = opts?.userId
|
||||
? Boolean(
|
||||
await tx.employeePasswordSafeAccess.findFirst({
|
||||
where: { tenantId, vaultId: vault.id, userId: opts.userId },
|
||||
select: { id: true },
|
||||
})
|
||||
)
|
||||
: false;
|
||||
return { ...(vault as VaultRow), entryCount, accessCount, hasContentAccess };
|
||||
})
|
||||
);
|
||||
return withCounts;
|
||||
});
|
||||
}
|
||||
|
||||
export async function createVault(input: { tenantId: string; name: string; description?: string | null; createdByUserId: string; isDemoData?: boolean }): Promise<VaultRow> {
|
||||
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 },
|
||||
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 },
|
||||
});
|
||||
await auditPasswordSafe({
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.createdByUserId,
|
||||
action: "VAULT_CREATE",
|
||||
targetType: "EmployeePasswordSafeVault",
|
||||
targetId: vault.id,
|
||||
});
|
||||
return vault as VaultRow;
|
||||
});
|
||||
}
|
||||
@@ -177,67 +268,274 @@ export async function archiveVault(input: { tenantId: string; vaultId: string; u
|
||||
throw new CatalogError(foundationErrors.notFound, { vaultId: input.vaultId });
|
||||
}
|
||||
}
|
||||
await tx.employeePasswordSafeVault.updateMany({ where: { id: input.vaultId, tenantId: input.tenantId }, data: { archivedAt: new Date() } });
|
||||
const result = await tx.employeePasswordSafeVault.updateMany({
|
||||
where: { id: input.vaultId, tenantId: input.tenantId, archivedAt: null },
|
||||
data: { archivedAt: new Date() },
|
||||
});
|
||||
if (result.count === 0) {
|
||||
throw new CatalogError(foundationErrors.notFound, { vaultId: input.vaultId });
|
||||
}
|
||||
await auditPasswordSafe({
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.userId,
|
||||
action: "VAULT_ARCHIVE",
|
||||
targetType: "EmployeePasswordSafeVault",
|
||||
targetId: input.vaultId,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Restore an archived vault. This tenant-wide operation never grants content
|
||||
* access; existing per-vault access rows remain authoritative. */
|
||||
export async function restoreVault(input: { tenantId: string; vaultId: string; userId: string; isTenantPasswordSafeAdmin: boolean }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
if (!input.isTenantPasswordSafeAdmin) {
|
||||
throw new CatalogError(foundationErrors.notFound, { vaultId: input.vaultId });
|
||||
}
|
||||
const result = await tx.employeePasswordSafeVault.updateMany({
|
||||
where: { id: input.vaultId, tenantId: input.tenantId, archivedAt: { not: null } },
|
||||
data: { archivedAt: null },
|
||||
});
|
||||
if (result.count === 0) {
|
||||
throw new CatalogError(foundationErrors.notFound, { vaultId: input.vaultId });
|
||||
}
|
||||
await auditPasswordSafe({
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.userId,
|
||||
action: "VAULT_RESTORE",
|
||||
targetType: "EmployeePasswordSafeVault",
|
||||
targetId: input.vaultId,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// --- Access management -----------------------------------------------------
|
||||
|
||||
async function requireActiveTenantMemberWithTx(tx: TenantRlsClient, tenantId: string, userId: string): Promise<void> {
|
||||
const membership = await tx.tenantUser.findFirst({
|
||||
where: { tenantId, userId, status: TenantUserStatus.ACTIVE, user: { active: true } },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!membership) throw new CatalogError(foundationErrors.notFound, { userId });
|
||||
}
|
||||
|
||||
async function requireVaultAdminWithTx(tx: TenantRlsClient, tenantId: string, vaultId: string, userId: string): Promise<void> {
|
||||
await requireVaultWithAccessWithTx(tx, tenantId, vaultId, userId, "admin");
|
||||
}
|
||||
|
||||
async function protectLastVaultAdminWithTx(
|
||||
tx: TenantRlsClient,
|
||||
input: { tenantId: string; vaultId: string; targetUserId: string; nextLevel?: PasswordSafePermissionLevel }
|
||||
): Promise<void> {
|
||||
const current = await tx.employeePasswordSafeAccess.findFirst({
|
||||
where: { tenantId: input.tenantId, vaultId: input.vaultId, userId: input.targetUserId },
|
||||
select: { permissionLevel: true },
|
||||
});
|
||||
if (current?.permissionLevel !== "admin" || input.nextLevel === "admin") return;
|
||||
const adminCount = await tx.employeePasswordSafeAccess.count({
|
||||
where: { tenantId: input.tenantId, vaultId: input.vaultId, permissionLevel: "admin" },
|
||||
});
|
||||
if (adminCount <= 1) throw new HrServiceError("hr.error.lastVaultAdmin");
|
||||
}
|
||||
|
||||
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 requireVaultAdminWithTx(tx, input.tenantId, input.vaultId, input.actorUserId);
|
||||
await requireActiveTenantMemberWithTx(tx, input.tenantId, input.targetUserId);
|
||||
await protectLastVaultAdminWithTx(tx, { ...input, nextLevel: input.permissionLevel });
|
||||
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 },
|
||||
create: {
|
||||
tenantId: input.tenantId,
|
||||
vaultId: input.vaultId,
|
||||
userId: input.targetUserId,
|
||||
permissionLevel: input.permissionLevel,
|
||||
grantedByUserId: input.actorUserId,
|
||||
},
|
||||
});
|
||||
await auditPasswordSafe({
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.actorUserId,
|
||||
action: "ACCESS_GRANT",
|
||||
targetType: "EmployeePasswordSafeAccess",
|
||||
targetId: `${input.vaultId}:${input.targetUserId}`,
|
||||
metadata: { vaultId: input.vaultId, targetUserId: input.targetUserId, permissionLevel: input.permissionLevel },
|
||||
});
|
||||
if (input.targetUserId !== input.actorUserId) {
|
||||
try {
|
||||
await notify(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
userId: input.targetUserId,
|
||||
channel: "IN_APP",
|
||||
category: "hr",
|
||||
messageKey: "hr.passwordSafe.notification.accessGranted",
|
||||
sourceKey: `password-safe-access:${input.vaultId}:${input.targetUserId}:${input.permissionLevel}`,
|
||||
payloadMetadata: { vaultId: input.vaultId, permissionLevel: input.permissionLevel },
|
||||
},
|
||||
tx as unknown as Parameters<typeof notify>[1]
|
||||
);
|
||||
} catch {
|
||||
// Access changes remain authoritative when notification delivery fails.
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function revokeAccess(input: { tenantId: string; vaultId: string; targetUserId: string; actorUserId: string; isTenantPasswordSafeAdmin: boolean }): Promise<void> {
|
||||
export async function revokeAccess(input: {
|
||||
tenantId: string;
|
||||
vaultId: string;
|
||||
targetUserId: string;
|
||||
actorUserId: string;
|
||||
}): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
if (!input.isTenantPasswordSafeAdmin) {
|
||||
await requireVaultWithAccessWithTx(tx, input.tenantId, input.vaultId, input.actorUserId, "admin");
|
||||
await requireVaultAdminWithTx(tx, input.tenantId, input.vaultId, input.actorUserId);
|
||||
await protectLastVaultAdminWithTx(tx, input);
|
||||
const deleted = await tx.employeePasswordSafeAccess.deleteMany({
|
||||
where: { tenantId: input.tenantId, vaultId: input.vaultId, userId: input.targetUserId },
|
||||
});
|
||||
if (deleted.count === 0) throw new CatalogError(foundationErrors.notFound, { userId: input.targetUserId });
|
||||
await auditPasswordSafe({
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.actorUserId,
|
||||
action: "ACCESS_REVOKE",
|
||||
targetType: "EmployeePasswordSafeAccess",
|
||||
targetId: `${input.vaultId}:${input.targetUserId}`,
|
||||
metadata: { vaultId: input.vaultId, targetUserId: input.targetUserId },
|
||||
});
|
||||
if (input.targetUserId !== input.actorUserId) {
|
||||
try {
|
||||
await notify(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
userId: input.targetUserId,
|
||||
channel: "IN_APP",
|
||||
category: "hr",
|
||||
messageKey: "hr.passwordSafe.notification.accessRevoked",
|
||||
sourceKey: `password-safe-access-revoked:${input.vaultId}:${input.targetUserId}`,
|
||||
payloadMetadata: { vaultId: input.vaultId },
|
||||
},
|
||||
tx as unknown as Parameters<typeof notify>[1]
|
||||
);
|
||||
} catch {
|
||||
// Access changes remain authoritative when notification delivery fails.
|
||||
}
|
||||
}
|
||||
await tx.employeePasswordSafeAccess.deleteMany({ where: { tenantId: input.tenantId, vaultId: input.vaultId, userId: input.targetUserId } });
|
||||
});
|
||||
}
|
||||
|
||||
export type VaultAccessRow = { userId: string; permissionLevel: PasswordSafePermissionLevel; grantedByUserId: string };
|
||||
export type VaultAccessRow = {
|
||||
userId: string;
|
||||
displayName: string;
|
||||
email: string;
|
||||
roleNames: string[];
|
||||
permissionLevel: PasswordSafePermissionLevel;
|
||||
};
|
||||
|
||||
export async function listVaultAccess(input: { tenantId: string; vaultId: string; userId: string; isTenantPasswordSafeAdmin: boolean }): Promise<VaultAccessRow[]> {
|
||||
export type VaultMemberOption = {
|
||||
userId: string;
|
||||
displayName: string;
|
||||
email: string;
|
||||
roleNames: string[];
|
||||
hasAccess: boolean;
|
||||
};
|
||||
|
||||
export async function listVaultAccess(input: {
|
||||
tenantId: string;
|
||||
vaultId: string;
|
||||
userId: string;
|
||||
}): Promise<VaultAccessRow[]> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
if (!input.isTenantPasswordSafeAdmin) {
|
||||
await requireVaultWithAccessWithTx(tx, input.tenantId, input.vaultId, input.userId, "admin");
|
||||
}
|
||||
await requireVaultAdminWithTx(tx, input.tenantId, input.vaultId, input.userId);
|
||||
const rows = await tx.employeePasswordSafeAccess.findMany({
|
||||
where: { tenantId: input.tenantId, vaultId: input.vaultId },
|
||||
select: { userId: true, permissionLevel: true, grantedByUserId: true },
|
||||
select: { userId: true, permissionLevel: true },
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
return rows as VaultAccessRow[];
|
||||
const memberships = await tx.tenantUser.findMany({
|
||||
where: { tenantId: input.tenantId, userId: { in: rows.map(({ userId }) => userId) }, status: TenantUserStatus.ACTIVE },
|
||||
select: { userId: true, user: { select: { firstName: true, lastName: true, email: true } } },
|
||||
});
|
||||
const roles = await tx.userRole.findMany({
|
||||
where: { tenantId: input.tenantId, userId: { in: rows.map(({ userId }) => userId) } },
|
||||
select: { userId: true, role: { select: { name: true } } },
|
||||
});
|
||||
const membershipByUser = new Map(memberships.map((membership) => [membership.userId, membership.user]));
|
||||
return rows.flatMap((row) => {
|
||||
const user = membershipByUser.get(row.userId);
|
||||
if (!user) return [];
|
||||
const name = `${user.firstName} ${user.lastName}`.trim();
|
||||
return [{
|
||||
userId: row.userId,
|
||||
displayName: name || user.email,
|
||||
email: user.email,
|
||||
roleNames: roles.filter((role) => role.userId === row.userId).map((role) => role.role.name),
|
||||
permissionLevel: row.permissionLevel as PasswordSafePermissionLevel,
|
||||
}];
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function listVaultMemberOptions(input: { tenantId: string; vaultId: string; userId: string }): Promise<VaultMemberOption[]> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
await requireVaultAdminWithTx(tx, input.tenantId, input.vaultId, input.userId);
|
||||
const [memberships, access, roles] = await Promise.all([
|
||||
tx.tenantUser.findMany({
|
||||
where: { tenantId: input.tenantId, status: TenantUserStatus.ACTIVE, user: { active: true } },
|
||||
select: { userId: true, user: { select: { firstName: true, lastName: true, email: true } } },
|
||||
orderBy: { user: { lastName: "asc" } },
|
||||
}),
|
||||
tx.employeePasswordSafeAccess.findMany({
|
||||
where: { tenantId: input.tenantId, vaultId: input.vaultId },
|
||||
select: { userId: true },
|
||||
}),
|
||||
tx.userRole.findMany({
|
||||
where: { tenantId: input.tenantId },
|
||||
select: { userId: true, role: { select: { name: true } } },
|
||||
}),
|
||||
]);
|
||||
const usersWithAccess = new Set(access.map(({ userId }) => userId));
|
||||
return memberships.map(({ userId, user }) => ({
|
||||
userId,
|
||||
displayName: `${user.firstName} ${user.lastName}`.trim() || user.email,
|
||||
email: user.email,
|
||||
roleNames: roles.filter((role) => role.userId === userId).map((role) => role.role.name),
|
||||
hasAccess: usersWithAccess.has(userId),
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
// --- 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[]> {
|
||||
export async function listEntries(input: { tenantId: string; vaultId: string; userId: string; archived?: boolean }): 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 },
|
||||
where: {
|
||||
tenantId: input.tenantId,
|
||||
vaultId: input.vaultId,
|
||||
archivedAt: input.archived ? { not: null } : 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 },
|
||||
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) => ({
|
||||
@@ -261,7 +559,7 @@ export type EntrySecretInput = { username?: string | null; password?: string | n
|
||||
async function encryptSecrets(
|
||||
tenantId: string,
|
||||
secrets: EntrySecretInput,
|
||||
crypto: HrFieldCrypto,
|
||||
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) {
|
||||
@@ -277,8 +575,17 @@ async function encryptSecrets(
|
||||
}
|
||||
|
||||
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(),
|
||||
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) {
|
||||
@@ -301,25 +608,45 @@ export async function createEntry(
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
await auditPasswordSafe({
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.userId,
|
||||
action: "ENTRY_CREATE",
|
||||
targetType: "EmployeePasswordSafeEntry",
|
||||
targetId: created.id,
|
||||
metadata: { vaultId: input.vaultId },
|
||||
});
|
||||
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(),
|
||||
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 } });
|
||||
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({
|
||||
const updated = await tx.employeePasswordSafeEntry.updateMany({
|
||||
where: { id: input.entryId, tenantId: input.tenantId, vaultId: input.vaultId },
|
||||
data: {
|
||||
...(input.title !== undefined ? { title: input.title.trim() } : {}),
|
||||
@@ -328,13 +655,61 @@ export async function updateEntry(
|
||||
...ciphertext,
|
||||
},
|
||||
});
|
||||
if (updated.count === 0) throw new CatalogError(foundationErrors.notFound, { entryId: input.entryId });
|
||||
await auditPasswordSafe({
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.userId,
|
||||
action: "ENTRY_UPDATE",
|
||||
targetType: "EmployeePasswordSafeEntry",
|
||||
targetId: input.entryId,
|
||||
metadata: { vaultId: input.vaultId },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
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() } });
|
||||
const archived = await tx.employeePasswordSafeEntry.updateMany({
|
||||
where: { id: input.entryId, tenantId: input.tenantId, vaultId: input.vaultId, archivedAt: null },
|
||||
data: { archivedAt: new Date() },
|
||||
});
|
||||
if (archived.count === 0) throw new CatalogError(foundationErrors.notFound, { entryId: input.entryId });
|
||||
await auditPasswordSafe({
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.userId,
|
||||
action: "ENTRY_ARCHIVE",
|
||||
targetType: "EmployeePasswordSafeEntry",
|
||||
targetId: input.entryId,
|
||||
metadata: { vaultId: input.vaultId },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Restore an archived entry. Write access is required, matching archive. */
|
||||
export async function restoreEntry(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");
|
||||
const restored = await tx.employeePasswordSafeEntry.updateMany({
|
||||
where: {
|
||||
id: input.entryId,
|
||||
tenantId: input.tenantId,
|
||||
vaultId: input.vaultId,
|
||||
archivedAt: { not: null },
|
||||
},
|
||||
data: { archivedAt: null },
|
||||
});
|
||||
if (restored.count === 0) {
|
||||
throw new CatalogError(foundationErrors.notFound, { entryId: input.entryId });
|
||||
}
|
||||
await auditPasswordSafe({
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.userId,
|
||||
action: "ENTRY_RESTORE",
|
||||
targetType: "EmployeePasswordSafeEntry",
|
||||
targetId: input.entryId,
|
||||
metadata: { vaultId: input.vaultId },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -346,9 +721,10 @@ export async function archiveEntry(input: { tenantId: string; vaultId: string; e
|
||||
* 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(
|
||||
async function readEntryValue(
|
||||
input: { tenantId: string; vaultId: string; entryId: string; userId: string; field: PasswordSafeSecretField },
|
||||
crypto: HrFieldCrypto = getHrFieldCrypto(),
|
||||
auditAction: "REVEAL" | "COPY",
|
||||
crypto: HrFieldCrypto = getHrFieldCrypto()
|
||||
): Promise<string | null> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
await requireVaultWithAccessWithTx(tx, input.tenantId, input.vaultId, input.userId, "read");
|
||||
@@ -359,19 +735,15 @@ export async function revealEntryValue(
|
||||
if (!entry) {
|
||||
throw new CatalogError(foundationErrors.notFound, { entryId: input.entryId });
|
||||
}
|
||||
const ciphertext =
|
||||
input.field === "username" ? entry.usernameCiphertext : input.field === "password" ? entry.passwordCiphertext : entry.notesCiphertext;
|
||||
const ciphertext = input.field === "username" ? entry.usernameCiphertext : input.field === "password" ? entry.passwordCiphertext : entry.notesCiphertext;
|
||||
|
||||
await createAuditEvent({
|
||||
await auditPasswordSafe({
|
||||
tenantId: input.tenantId,
|
||||
actorId: input.userId,
|
||||
actorType: "user",
|
||||
action: "HR_PASSWORD_SAFE_REVEAL",
|
||||
actorUserId: input.userId,
|
||||
action: auditAction,
|
||||
targetType: "EmployeePasswordSafeEntry",
|
||||
targetId: input.entryId,
|
||||
sourceModule: HR_AUDIT_MODULE,
|
||||
dataSensitivity: "confidential",
|
||||
outcome: "success",
|
||||
confidential: true,
|
||||
metadata: { vaultId: input.vaultId, field: input.field },
|
||||
});
|
||||
|
||||
@@ -382,6 +754,22 @@ export async function revealEntryValue(
|
||||
});
|
||||
}
|
||||
|
||||
export async function revealEntryValue(
|
||||
input: { tenantId: string; vaultId: string; entryId: string; userId: string; field: PasswordSafeSecretField },
|
||||
crypto: HrFieldCrypto = getHrFieldCrypto()
|
||||
): Promise<string | null> {
|
||||
return readEntryValue(input, "REVEAL", crypto);
|
||||
}
|
||||
|
||||
/** Copy is a distinct command so its own permission re-check and audit event
|
||||
* cannot be replaced by a client-only clipboard operation. */
|
||||
export async function copyEntryValue(
|
||||
input: { tenantId: string; vaultId: string; entryId: string; userId: string; field: PasswordSafeSecretField },
|
||||
crypto: HrFieldCrypto = getHrFieldCrypto()
|
||||
): Promise<string | null> {
|
||||
return readEntryValue(input, "COPY", crypto);
|
||||
}
|
||||
|
||||
// --- DSGVO export ----------------------------------------------------------
|
||||
|
||||
export type ExportedEntry = { title: string; tags: string[]; url: string | null; username: string | null; password: string | null; notes: string | null };
|
||||
@@ -391,26 +779,24 @@ export type ExportedEntry = { title: string; tags: string[]; url: string | null;
|
||||
* Audited as a confidential bulk reveal.
|
||||
*/
|
||||
export async function exportVault(
|
||||
input: { tenantId: string; vaultId: string; userId: string },
|
||||
crypto: HrFieldCrypto = getHrFieldCrypto(),
|
||||
input: { tenantId: string; vaultId: string; userId: string; hasExportPermission: boolean },
|
||||
crypto: HrFieldCrypto = getHrFieldCrypto()
|
||||
): Promise<{ vaultName: string; entries: ExportedEntry[] }> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
if (!input.hasExportPermission) throw new CatalogError(foundationErrors.notFound, { permission: "hr.passwordsafe.export" });
|
||||
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({
|
||||
await auditPasswordSafe({
|
||||
tenantId: input.tenantId,
|
||||
actorId: input.userId,
|
||||
actorType: "user",
|
||||
action: "HR_PASSWORD_SAFE_EXPORT",
|
||||
actorUserId: input.userId,
|
||||
action: "EXPORT",
|
||||
targetType: "EmployeePasswordSafeVault",
|
||||
targetId: input.vaultId,
|
||||
sourceModule: HR_AUDIT_MODULE,
|
||||
dataSensitivity: "confidential",
|
||||
confidential: true,
|
||||
regulatoryScope: ["gdpr"],
|
||||
outcome: "success",
|
||||
metadata: { entryCount: entries.length },
|
||||
});
|
||||
const exported: ExportedEntry[] = await Promise.all(
|
||||
@@ -421,8 +807,67 @@ export async function exportVault(
|
||||
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 };
|
||||
});
|
||||
}
|
||||
|
||||
export type PasswordSafeActivityRow = {
|
||||
id: string;
|
||||
createdAt: Date;
|
||||
action: string;
|
||||
actorLabel: string;
|
||||
outcome: string;
|
||||
};
|
||||
|
||||
/** Redacted audit timeline. No metadata is returned because even permitted
|
||||
* metadata such as entry ids is unnecessary for the user-facing activity tab. */
|
||||
export async function listPasswordSafeActivity(input: {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
vaultId?: string;
|
||||
isTenantPasswordSafeAdmin?: boolean;
|
||||
}): Promise<PasswordSafeActivityRow[]> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
if (input.vaultId) {
|
||||
await requireVaultWithAccessWithTx(tx, input.tenantId, input.vaultId, input.userId, "read");
|
||||
} else if (!input.isTenantPasswordSafeAdmin) {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
const rows = await tx.auditEvent.findMany({
|
||||
where: {
|
||||
tenantId: input.tenantId,
|
||||
action: { startsWith: PASSWORD_SAFE_AUDIT_PREFIX },
|
||||
...(input.vaultId
|
||||
? {
|
||||
OR: [
|
||||
{ targetType: "EmployeePasswordSafeVault", targetId: input.vaultId },
|
||||
{ metadata: { path: ["vaultId"], equals: input.vaultId } },
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
select: { id: true, createdAt: true, action: true, actorId: true, outcome: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 100,
|
||||
});
|
||||
const actorIds = [...new Set(rows.map(({ actorId }) => actorId).filter((actorId): actorId is string => Boolean(actorId)))];
|
||||
const actors = actorIds.length
|
||||
? await tx.tenantUser.findMany({
|
||||
where: { tenantId: input.tenantId, userId: { in: actorIds } },
|
||||
select: { userId: true, user: { select: { firstName: true, lastName: true, email: true } } },
|
||||
})
|
||||
: [];
|
||||
const actorById = new Map(
|
||||
actors.map(({ userId, user }) => [userId, `${user.firstName} ${user.lastName}`.trim() || user.email])
|
||||
);
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
createdAt: row.createdAt,
|
||||
action: row.action,
|
||||
actorLabel: row.actorId ? actorById.get(row.actorId) ?? "System" : "System",
|
||||
outcome: row.outcome,
|
||||
}));
|
||||
});
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
employeeFindFirst: vi.fn(),
|
||||
fileFindFirst: vi.fn(),
|
||||
payslipFindUnique: vi.fn(),
|
||||
payslipUpsert: vi.fn(),
|
||||
linkDeleteMany: vi.fn(),
|
||||
linkUpsert: vi.fn(),
|
||||
activity: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
audit: vi.fn(),
|
||||
}));
|
||||
|
||||
const tx = {
|
||||
hrEmployeeProfile: { findFirst: mocks.employeeFindFirst },
|
||||
file: { findFirst: mocks.fileFindFirst },
|
||||
employeePayslip: {
|
||||
findUnique: mocks.payslipFindUnique,
|
||||
upsert: mocks.payslipUpsert,
|
||||
},
|
||||
fileEntityLink: {
|
||||
deleteMany: mocks.linkDeleteMany,
|
||||
upsert: mocks.linkUpsert,
|
||||
},
|
||||
};
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: vi.fn(async (_tenantId: string, callback: (client: typeof tx) => Promise<unknown>) => callback(tx)),
|
||||
}));
|
||||
vi.mock("@hivegrid/activity", () => ({ logActivity: mocks.activity }));
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({
|
||||
createAuditEvent: mocks.audit,
|
||||
createAuditEventInExistingTransaction: mocks.audit,
|
||||
}));
|
||||
vi.mock("@hivegrid/foundation", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@hivegrid/foundation")>();
|
||||
return { ...actual, notify: mocks.notify };
|
||||
});
|
||||
|
||||
import { createPayslip } from "./hrPayslipService.server";
|
||||
|
||||
describe("createPayslip atomic file ownership", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.employeeFindFirst.mockResolvedValue({ userId: "employee_1" });
|
||||
mocks.fileFindFirst.mockResolvedValue({ id: "file_new" });
|
||||
mocks.payslipFindUnique.mockResolvedValue({ fileId: "file_old" });
|
||||
mocks.payslipUpsert.mockResolvedValue({
|
||||
id: "payslip_1",
|
||||
tenantId: "tenant_1",
|
||||
employeeUserId: "employee_1",
|
||||
uploadedByUserId: "hr_1",
|
||||
periodYear: 2026,
|
||||
periodMonth: 7,
|
||||
fileId: "file_new",
|
||||
isRead: false,
|
||||
readAt: null,
|
||||
createdAt: new Date("2026-07-25T10:00:00.000Z"),
|
||||
updatedAt: new Date("2026-07-25T10:00:00.000Z"),
|
||||
archivedAt: null,
|
||||
});
|
||||
mocks.linkDeleteMany.mockResolvedValue({ count: 1 });
|
||||
mocks.linkUpsert.mockResolvedValue({ id: "link_1" });
|
||||
mocks.activity.mockResolvedValue(undefined);
|
||||
mocks.notify.mockResolvedValue(undefined);
|
||||
mocks.audit.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("validates tenant-owned targets and links the uploaded file in the payslip transaction", async () => {
|
||||
await createPayslip({
|
||||
tenantId: "tenant_1",
|
||||
employeeUserId: "employee_1",
|
||||
uploadedByUserId: "hr_1",
|
||||
periodYear: 2026,
|
||||
periodMonth: 7,
|
||||
fileId: "file_new",
|
||||
});
|
||||
|
||||
expect(mocks.employeeFindFirst).toHaveBeenCalledWith({
|
||||
where: { tenantId: "tenant_1", userId: "employee_1" },
|
||||
select: { userId: true },
|
||||
});
|
||||
expect(mocks.fileFindFirst).toHaveBeenCalledWith({
|
||||
where: { tenantId: "tenant_1", id: "file_new", archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.linkUpsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
create: expect.objectContaining({
|
||||
tenantId: "tenant_1",
|
||||
fileId: "file_new",
|
||||
entityType: "user",
|
||||
entityId: "employee_1",
|
||||
linkRole: "hr_payslip",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(mocks.activity).toHaveBeenCalledOnce();
|
||||
expect(mocks.notify).toHaveBeenCalledOnce();
|
||||
expect(mocks.audit).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("fails closed before persistence for a cross-tenant employee or file", async () => {
|
||||
mocks.employeeFindFirst.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
createPayslip({
|
||||
tenantId: "tenant_1",
|
||||
employeeUserId: "employee_foreign",
|
||||
uploadedByUserId: "hr_1",
|
||||
periodYear: 2026,
|
||||
periodMonth: 7,
|
||||
fileId: "file_new",
|
||||
}),
|
||||
).rejects.toMatchObject({ name: "CatalogError" });
|
||||
|
||||
expect(mocks.payslipUpsert).not.toHaveBeenCalled();
|
||||
expect(mocks.linkUpsert).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+103
-17
@@ -7,8 +7,9 @@
|
||||
// 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 { CatalogError, foundationErrors, notify } from "@hivegrid/foundation";
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
import { createAuditEvent, createAuditEventInExistingTransaction } from "@hivegrid/db/audit-events.server";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { HrServiceError } from "./hrService.server";
|
||||
|
||||
@@ -106,8 +107,32 @@ export type CreatePayslipInput = {
|
||||
/** 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({
|
||||
const created = (await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const [employee, file, previous] = await Promise.all([
|
||||
tx.hrEmployeeProfile.findFirst({
|
||||
where: { tenantId: input.tenantId, userId: input.employeeUserId },
|
||||
select: { userId: true },
|
||||
}),
|
||||
tx.file.findFirst({
|
||||
where: { tenantId: input.tenantId, id: input.fileId, archivedAt: null },
|
||||
select: { id: true },
|
||||
}),
|
||||
tx.employeePayslip.findUnique({
|
||||
where: {
|
||||
tenantId_employeeUserId_periodYear_periodMonth: {
|
||||
tenantId: input.tenantId,
|
||||
employeeUserId: input.employeeUserId,
|
||||
periodYear: input.periodYear,
|
||||
periodMonth: input.periodMonth,
|
||||
},
|
||||
},
|
||||
select: { fileId: true },
|
||||
}),
|
||||
]);
|
||||
if (!employee || !file) {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
const payslip = await 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: {
|
||||
@@ -119,19 +144,80 @@ export async function createPayslip(input: CreatePayslipInput): Promise<PayslipR
|
||||
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 },
|
||||
});
|
||||
});
|
||||
if (previous?.fileId && previous.fileId !== input.fileId) {
|
||||
await tx.fileEntityLink.deleteMany({
|
||||
where: {
|
||||
tenantId: input.tenantId,
|
||||
fileId: previous.fileId,
|
||||
entityType: "user",
|
||||
entityId: input.employeeUserId,
|
||||
linkRole: "hr_payslip",
|
||||
},
|
||||
});
|
||||
}
|
||||
await tx.fileEntityLink.upsert({
|
||||
where: {
|
||||
fileId_entityType_entityId: {
|
||||
fileId: input.fileId,
|
||||
entityType: "user",
|
||||
entityId: input.employeeUserId,
|
||||
},
|
||||
},
|
||||
update: { linkRole: "hr_payslip" },
|
||||
create: {
|
||||
tenantId: input.tenantId,
|
||||
createdByUserId: input.uploadedByUserId,
|
||||
fileId: input.fileId,
|
||||
entityType: "user",
|
||||
entityId: input.employeeUserId,
|
||||
linkRole: "hr_payslip",
|
||||
},
|
||||
});
|
||||
await logActivity(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.uploadedByUserId,
|
||||
actorKind: "user",
|
||||
activityType: "file_uploaded",
|
||||
subjectType: "tenant",
|
||||
subjectId: input.tenantId,
|
||||
summaryText: "activity.runtime.hr.payslipProvided",
|
||||
metadata: {
|
||||
payslipId: payslip.id,
|
||||
employeeUserId: input.employeeUserId,
|
||||
period: `${input.periodYear}-${String(input.periodMonth).padStart(2, "0")}`,
|
||||
},
|
||||
},
|
||||
{ client: tx },
|
||||
);
|
||||
await notify(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
userId: input.employeeUserId,
|
||||
channel: "IN_APP",
|
||||
category: "hr",
|
||||
messageKey: "hr.notify.payslip.uploaded",
|
||||
sourceKey: `hr-payslip:${payslip.id}:${payslip.updatedAt.toISOString()}`,
|
||||
},
|
||||
tx as unknown as Parameters<typeof notify>[1],
|
||||
).catch(() => undefined);
|
||||
await createAuditEventInExistingTransaction(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
actorId: input.uploadedByUserId,
|
||||
actorType: "user",
|
||||
action: "HR_PAYSLIP_UPLOAD",
|
||||
targetType: "EmployeePayslip",
|
||||
targetId: payslip.id,
|
||||
sourceModule: HR_AUDIT_MODULE,
|
||||
outcome: "success",
|
||||
metadata: { employeeUserId: input.employeeUserId },
|
||||
},
|
||||
tx as unknown as Parameters<typeof createAuditEventInExistingTransaction>[1],
|
||||
);
|
||||
return payslip;
|
||||
})) as PayslipRow;
|
||||
return created;
|
||||
}
|
||||
|
||||
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tx: {
|
||||
hrRequest: { create: vi.fn(), update: vi.fn() },
|
||||
hrRequestTemplate: { findFirst: vi.fn() },
|
||||
form: { findFirst: vi.fn(), findMany: vi.fn(), upsert: vi.fn() },
|
||||
formSubmission: { create: vi.fn() },
|
||||
activity: { create: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: async (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({ createAuditEvent: vi.fn().mockResolvedValue(undefined) }));
|
||||
vi.mock("@hivegrid/db/notifications.server", () => ({ createNotificationDelivery: vi.fn().mockResolvedValue(undefined) }));
|
||||
|
||||
import { listLinkableHrRequestForms, submitRequest } from "./hrRequestService.server";
|
||||
import { buildHrRequestFormDefinition } from "./hrM05Forms";
|
||||
|
||||
const createdRequest = {
|
||||
id: "request-1",
|
||||
tenantId: "tenant-a",
|
||||
employeeUserId: "user-employee",
|
||||
templateId: "template-1",
|
||||
requestKind: "hardware",
|
||||
title: "Neues Notebook",
|
||||
details: '{"budget":"1200"}',
|
||||
formSubmissionId: null,
|
||||
status: "submitted",
|
||||
assignedApproverUserId: null,
|
||||
};
|
||||
|
||||
describe("HR request M05 form reuse (AK-P16c)", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.tx.hrRequest.create.mockResolvedValue({ ...createdRequest });
|
||||
mocks.tx.hrRequest.update.mockImplementation(async ({ data }: { data: Record<string, unknown> }) => ({ ...createdRequest, ...data }));
|
||||
mocks.tx.hrRequestTemplate.findFirst.mockResolvedValue({
|
||||
id: "template-1",
|
||||
title: "Hardware",
|
||||
requestKind: "hardware",
|
||||
defaultApproverUserId: null,
|
||||
linkedFormId: "form-1",
|
||||
});
|
||||
mocks.tx.form.findFirst.mockResolvedValue({
|
||||
id: "form-1",
|
||||
definition: buildHrRequestFormDefinition(),
|
||||
});
|
||||
mocks.tx.form.upsert.mockResolvedValue({ id: "system-form-1" });
|
||||
mocks.tx.formSubmission.create.mockResolvedValue({ id: "submission-1" });
|
||||
mocks.tx.activity.create.mockResolvedValue({ id: "activity-1" });
|
||||
});
|
||||
|
||||
it("persists a FormSubmission and wires formSubmissionId when the template links a form", async () => {
|
||||
const row = await submitRequest({
|
||||
tenantId: "tenant-a",
|
||||
employeeUserId: "user-employee",
|
||||
templateId: "template-1",
|
||||
requestKind: "hardware",
|
||||
title: "Neues Notebook",
|
||||
details: '{"budget":"1200"}',
|
||||
formValues: {
|
||||
requestKind: "hardware",
|
||||
title: "Neues Notebook",
|
||||
details: '{"budget":"1200"}',
|
||||
},
|
||||
});
|
||||
|
||||
expect(mocks.tx.formSubmission.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
formId: "form-1",
|
||||
tenantId: "tenant-a",
|
||||
createdByUserId: "user-employee",
|
||||
payload: { values: { title: "Neues Notebook", details: '{"budget":"1200"}', requestKind: "hardware" } },
|
||||
status: "received",
|
||||
linkedEntityType: "hr_request",
|
||||
linkedEntityId: "request-1",
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.tx.hrRequest.update).toHaveBeenCalledWith({ where: { id: "request-1" }, data: { formSubmissionId: "submission-1" } });
|
||||
expect(row.formSubmissionId).toBe("submission-1");
|
||||
});
|
||||
|
||||
it("fails closed when a selected template has no linked form", async () => {
|
||||
mocks.tx.hrRequestTemplate.findFirst
|
||||
.mockResolvedValueOnce({
|
||||
id: "template-1",
|
||||
title: "Hardware",
|
||||
requestKind: "hardware",
|
||||
defaultApproverUserId: null,
|
||||
})
|
||||
.mockResolvedValueOnce({ linkedFormId: null });
|
||||
|
||||
await expect(
|
||||
submitRequest({
|
||||
tenantId: "tenant-a",
|
||||
employeeUserId: "user-employee",
|
||||
templateId: "template-1",
|
||||
requestKind: "hardware",
|
||||
title: "Neues Notebook",
|
||||
formValues: {
|
||||
requestKind: "hardware",
|
||||
title: "Neues Notebook",
|
||||
details: "",
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("hr.m05.templateFormRequired");
|
||||
|
||||
expect(mocks.tx.formSubmission.create).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.hrRequest.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails closed when the linked form no longer exists", async () => {
|
||||
mocks.tx.form.findFirst.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
submitRequest({
|
||||
tenantId: "tenant-a",
|
||||
employeeUserId: "user-employee",
|
||||
templateId: "template-1",
|
||||
requestKind: "hardware",
|
||||
title: "Neues Notebook",
|
||||
formValues: {
|
||||
requestKind: "hardware",
|
||||
title: "Neues Notebook",
|
||||
details: "",
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("hr.m05.templateFormUnavailable");
|
||||
|
||||
expect(mocks.tx.formSubmission.create).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.hrRequest.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the system M05 form for a request without a template", async () => {
|
||||
mocks.tx.hrRequest.create.mockResolvedValue({
|
||||
...createdRequest,
|
||||
templateId: null,
|
||||
});
|
||||
|
||||
await submitRequest({
|
||||
tenantId: "tenant-a",
|
||||
employeeUserId: "user-employee",
|
||||
requestKind: "hardware",
|
||||
title: "Neues Notebook",
|
||||
formValues: {
|
||||
requestKind: "hardware",
|
||||
title: "Neues Notebook",
|
||||
details: "",
|
||||
},
|
||||
});
|
||||
|
||||
expect(mocks.tx.form.upsert).toHaveBeenCalled();
|
||||
expect(mocks.tx.formSubmission.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
formId: "system-form-1",
|
||||
linkedEntityType: "hr_request",
|
||||
linkedEntityId: "request-1",
|
||||
}),
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("lists only published hr_request forms as linkable", async () => {
|
||||
mocks.tx.form.findMany.mockResolvedValue([{ id: "form-1", name: "Spesenantrag" }]);
|
||||
|
||||
const forms = await listLinkableHrRequestForms("tenant-a");
|
||||
|
||||
expect(mocks.tx.form.findMany).toHaveBeenCalledWith({
|
||||
where: { tenantId: "tenant-a", subtype: "hr_request", status: "published" },
|
||||
select: { id: true, name: true },
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
expect(forms).toEqual([{ id: "form-1", name: "Spesenantrag" }]);
|
||||
});
|
||||
});
|
||||
+170
-20
@@ -1,17 +1,26 @@
|
||||
// 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).
|
||||
// M05 reuse (AK-P16c): a template may link a published `hr_request` form. When
|
||||
// it does, submitting a request also persists the payload as a real
|
||||
// FormSubmission (linkedEntityType "hr_request") and wires `formSubmissionId`.
|
||||
// The lightweight dialog fields stay as the capture surface; the linked form is
|
||||
// the canonical submission store. Requests without a linked form keep the
|
||||
// transitional `details` JSON string. 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 { CatalogError, foundationErrors, notify } from "@hivegrid/foundation";
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { createNotificationDelivery } from "@hivegrid/db/notifications.server";
|
||||
import { FormDefinitionSchema, type FormDefinition } from "@hivegrid/form-widget";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { HrServiceError } from "./hrService.server";
|
||||
import type { HrM05Values } from "./hrM05Forms";
|
||||
import {
|
||||
createSystemHrSubmissionWithTx,
|
||||
createTemplateHrRequestSubmissionWithTx,
|
||||
} from "./hrM05Submission.server";
|
||||
|
||||
const HR_AUDIT_MODULE = "hr";
|
||||
|
||||
@@ -57,7 +66,19 @@ export type RequestRow = {
|
||||
|
||||
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);
|
||||
await withTenantRLS(input.tenantId, (tx) =>
|
||||
notify(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
userId: input.userId,
|
||||
channel: "IN_APP",
|
||||
category: "hr",
|
||||
messageKey: input.messageKey,
|
||||
sourceKey: input.sourceKey,
|
||||
},
|
||||
tx as unknown as Parameters<typeof notify>[1],
|
||||
),
|
||||
).catch(() => undefined);
|
||||
}
|
||||
|
||||
async function audit(input: { tenantId: string; actorId: string; action: string; targetId: string }): Promise<void> {
|
||||
@@ -73,6 +94,60 @@ export async function listTemplates(tenantId: string, opts?: { includeArchived?:
|
||||
return rows as RequestTemplateRow[];
|
||||
}
|
||||
|
||||
/** Published `hr_request` forms a template can link (M05 reuse, AK-P16c). */
|
||||
export async function listLinkableHrRequestForms(tenantId: string): Promise<{ id: string; name: string }[]> {
|
||||
return withTenantRLS(tenantId, (tx) =>
|
||||
tx.form.findMany({
|
||||
where: { tenantId, subtype: "hr_request", status: "published" },
|
||||
select: { id: true, name: true },
|
||||
orderBy: { name: "asc" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function listRequestTemplateDefinitions(
|
||||
tenantId: string,
|
||||
): Promise<Map<string, FormDefinition>> {
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
const templates = await tx.hrRequestTemplate.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
archivedAt: null,
|
||||
isActive: true,
|
||||
linkedFormId: { not: null },
|
||||
},
|
||||
select: { id: true, linkedFormId: true },
|
||||
});
|
||||
const formIds = templates.flatMap((template) =>
|
||||
template.linkedFormId ? [template.linkedFormId] : [],
|
||||
);
|
||||
if (formIds.length === 0) return new Map();
|
||||
const forms = await tx.form.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
id: { in: formIds },
|
||||
subtype: "hr_request",
|
||||
status: "published",
|
||||
isEnabled: true,
|
||||
},
|
||||
select: { id: true, definition: true },
|
||||
});
|
||||
const byFormId = new Map<string, FormDefinition>();
|
||||
for (const form of forms) {
|
||||
const parsed = FormDefinitionSchema.safeParse(form.definition);
|
||||
if (parsed.success) byFormId.set(form.id, parsed.data);
|
||||
}
|
||||
return new Map(
|
||||
templates.flatMap((template) => {
|
||||
const definition = template.linkedFormId
|
||||
? byFormId.get(template.linkedFormId)
|
||||
: undefined;
|
||||
return definition ? [[template.id, definition] as const] : [];
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
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> {
|
||||
@@ -116,29 +191,104 @@ export async function archiveTemplate(input: { tenantId: string; actorUserId: st
|
||||
|
||||
// --- Requests -------------------------------------------------------------
|
||||
|
||||
export type SubmitRequestInput = { tenantId: string; employeeUserId: string; templateId?: string | null; requestKind: HrRequestKind; title: string; details?: string | null; assignedApproverUserId?: string | null; isDemoData?: boolean };
|
||||
export type SubmitRequestInput = { tenantId: string; employeeUserId: string; templateId?: string | null; requestKind: HrRequestKind; title: string; details?: string | null; assignedApproverUserId?: string | null; isDemoData?: boolean; formValues?: HrM05Values };
|
||||
|
||||
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({
|
||||
if (!input.templateId && !title) throw new HrServiceError("hr.error.requestTitleRequired");
|
||||
const created = (await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const template = input.templateId
|
||||
? await tx.hrRequestTemplate.findFirst({
|
||||
where: {
|
||||
id: input.templateId,
|
||||
tenantId: input.tenantId,
|
||||
archivedAt: null,
|
||||
isActive: true,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
requestKind: true,
|
||||
defaultApproverUserId: true,
|
||||
},
|
||||
})
|
||||
: null;
|
||||
if (input.templateId && !template) {
|
||||
throw new CatalogError(foundationErrors.notFound, {
|
||||
templateId: input.templateId,
|
||||
});
|
||||
}
|
||||
const effectiveTitle = template?.title ?? title;
|
||||
const effectiveKind = (template?.requestKind ?? input.requestKind) as HrRequestKind;
|
||||
const request = await 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,
|
||||
templateId: template?.id ?? null,
|
||||
requestKind: effectiveKind,
|
||||
title: effectiveTitle.slice(0, 255),
|
||||
details:
|
||||
input.details?.slice(0, 8000) ??
|
||||
(input.formValues ? JSON.stringify(input.formValues).slice(0, 8000) : null),
|
||||
status: "submitted",
|
||||
assignedApproverUserId: input.assignedApproverUserId ?? null,
|
||||
assignedApproverUserId:
|
||||
input.assignedApproverUserId ?? template?.defaultApproverUserId ?? null,
|
||||
isDemoData: input.isDemoData ?? false,
|
||||
},
|
||||
}),
|
||||
)) as RequestRow;
|
||||
});
|
||||
let linkedRequest = request;
|
||||
if (input.formValues) {
|
||||
const submissionId = template
|
||||
? await createTemplateHrRequestSubmissionWithTx(tx, {
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.employeeUserId,
|
||||
templateId: template.id,
|
||||
linkedEntityId: request.id,
|
||||
values: input.formValues,
|
||||
})
|
||||
: await createSystemHrSubmissionWithTx(tx, {
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.employeeUserId,
|
||||
process: "request",
|
||||
linkedEntityType: "hr_request",
|
||||
linkedEntityId: request.id,
|
||||
values: input.formValues,
|
||||
});
|
||||
linkedRequest = await tx.hrRequest.update({
|
||||
where: { id: request.id },
|
||||
data: { formSubmissionId: submissionId },
|
||||
});
|
||||
}
|
||||
await logActivity(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.employeeUserId,
|
||||
actorKind: "user",
|
||||
activityType: "form_submitted",
|
||||
subjectType: "tenant",
|
||||
subjectId: input.tenantId,
|
||||
summaryText: "activity.runtime.hr.requestSubmitted",
|
||||
metadata: { requestId: request.id, process: "request" },
|
||||
},
|
||||
{ client: tx },
|
||||
);
|
||||
if (linkedRequest.assignedApproverUserId) {
|
||||
await notify(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
userId: linkedRequest.assignedApproverUserId,
|
||||
channel: "IN_APP",
|
||||
category: "hr",
|
||||
messageKey: "hr.notify.request.submitted",
|
||||
sourceKey: `hr-request-submit:${request.id}`,
|
||||
},
|
||||
tx as unknown as Parameters<typeof notify>[1],
|
||||
).catch(() => undefined);
|
||||
}
|
||||
return linkedRequest;
|
||||
})) 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;
|
||||
}
|
||||
|
||||
|
||||
-47
@@ -1,13 +1,6 @@
|
||||
// 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
|
||||
@@ -30,52 +23,20 @@ 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`;
|
||||
}
|
||||
@@ -96,18 +57,10 @@ 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`;
|
||||
}
|
||||
|
||||
+233
@@ -0,0 +1,233 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tx: {
|
||||
hrEmployeeProfile: {
|
||||
findFirst: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
hrEmployeeDocument: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
file: {
|
||||
findFirst: vi.fn(),
|
||||
},
|
||||
fileEntityLink: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
activity: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
tenantUser: {
|
||||
findFirst: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
userRole: {
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: (_tenantId: string, callback: (tx: typeof mocks.tx) => unknown) => callback(mocks.tx),
|
||||
}));
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: { user: { findMany: vi.fn().mockResolvedValue([]) } },
|
||||
}));
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({ createAuditEvent: vi.fn() }));
|
||||
vi.mock("./hrFieldCrypto.server", () => ({ getHrFieldCrypto: vi.fn() }));
|
||||
|
||||
import {
|
||||
createDocumentWithLink,
|
||||
listHrMemberOptions,
|
||||
listDirectoryForViewer,
|
||||
requireActiveHrMember,
|
||||
requireEmployeeObjectAccess,
|
||||
} from "./hrService.server";
|
||||
|
||||
describe("HR employee object access", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.tx.hrEmployeeProfile.findMany.mockResolvedValue([]);
|
||||
mocks.tx.hrEmployeeProfile.findFirst.mockResolvedValue(null);
|
||||
mocks.tx.hrEmployeeDocument.create.mockResolvedValue({
|
||||
id: "document-1",
|
||||
tenantId: "tenant-1",
|
||||
employeeUserId: "employee-1",
|
||||
uploadedByUserId: "employee-1",
|
||||
title: "Bescheinigung",
|
||||
documentKind: "certificate",
|
||||
fileId: "file-1",
|
||||
visibility: "employee",
|
||||
uploadedByOffice: false,
|
||||
validUntil: null,
|
||||
isDemoData: false,
|
||||
createdAt: new Date("2026-07-25T12:00:00.000Z"),
|
||||
updatedAt: new Date("2026-07-25T12:00:00.000Z"),
|
||||
archivedAt: null,
|
||||
});
|
||||
mocks.tx.file.findFirst.mockResolvedValue({ id: "file-1" });
|
||||
mocks.tx.fileEntityLink.create.mockResolvedValue({ id: "link-1" });
|
||||
mocks.tx.activity.create.mockResolvedValue({ id: "activity-1" });
|
||||
mocks.tx.tenantUser.findFirst.mockResolvedValue({ id: "membership-1" });
|
||||
mocks.tx.tenantUser.findMany.mockResolvedValue([]);
|
||||
mocks.tx.userRole.findMany.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("limits the regular directory query to self and direct reports", async () => {
|
||||
await listDirectoryForViewer({
|
||||
tenantId: "tenant-1",
|
||||
viewerUserId: "manager-1",
|
||||
canReadAll: false,
|
||||
});
|
||||
|
||||
expect(mocks.tx.hrEmployeeProfile.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
tenantId: "tenant-1",
|
||||
OR: [{ userId: "manager-1" }, { managerUserId: "manager-1" }],
|
||||
},
|
||||
select: {
|
||||
userId: true,
|
||||
position: true,
|
||||
team: true,
|
||||
locationId: true,
|
||||
managerUserId: true,
|
||||
},
|
||||
orderBy: [{ team: "asc" }, { userId: "asc" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("does not infer tenant-wide HR visibility from a generic tenant role", async () => {
|
||||
mocks.tx.hrEmployeeProfile.findFirst.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
requireEmployeeObjectAccess({
|
||||
tenantId: "tenant-1",
|
||||
viewerUserId: "tenant-admin-1",
|
||||
employeeUserId: "employee-1",
|
||||
canReadAll: false,
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
|
||||
expect(mocks.tx.hrEmployeeProfile.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
tenantId: "tenant-1",
|
||||
userId: "employee-1",
|
||||
managerUserId: "tenant-admin-1",
|
||||
},
|
||||
select: { userId: true, managerUserId: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("allows self, direct-report and explicit HR-wide access without changing tenant scope", async () => {
|
||||
mocks.tx.hrEmployeeProfile.findFirst
|
||||
.mockResolvedValueOnce({ userId: "employee-1", managerUserId: "manager-1" })
|
||||
.mockResolvedValueOnce({ userId: "employee-2", managerUserId: "someone-else" });
|
||||
|
||||
await expect(
|
||||
requireEmployeeObjectAccess({
|
||||
tenantId: "tenant-1",
|
||||
viewerUserId: "manager-1",
|
||||
employeeUserId: "manager-1",
|
||||
canReadAll: false,
|
||||
}),
|
||||
).resolves.toEqual({ isSelf: true, isDirectReport: false });
|
||||
expect(mocks.tx.hrEmployeeProfile.findFirst).not.toHaveBeenCalled();
|
||||
await expect(
|
||||
requireEmployeeObjectAccess({
|
||||
tenantId: "tenant-1",
|
||||
viewerUserId: "manager-1",
|
||||
employeeUserId: "employee-1",
|
||||
canReadAll: false,
|
||||
}),
|
||||
).resolves.toEqual({ isSelf: false, isDirectReport: true });
|
||||
await expect(
|
||||
requireEmployeeObjectAccess({
|
||||
tenantId: "tenant-1",
|
||||
viewerUserId: "hr-1",
|
||||
employeeUserId: "employee-2",
|
||||
canReadAll: true,
|
||||
}),
|
||||
).resolves.toEqual({ isSelf: false, isDirectReport: false });
|
||||
});
|
||||
|
||||
it("creates the HR document and user link inside one tenant transaction", async () => {
|
||||
await createDocumentWithLink({
|
||||
tenantId: "tenant-1",
|
||||
employeeUserId: "employee-1",
|
||||
uploadedByUserId: "employee-1",
|
||||
title: " Bescheinigung ",
|
||||
documentKind: "certificate",
|
||||
fileId: "file-1",
|
||||
});
|
||||
|
||||
expect(mocks.tx.hrEmployeeDocument.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
tenantId: "tenant-1",
|
||||
employeeUserId: "employee-1",
|
||||
uploadedByUserId: "employee-1",
|
||||
title: "Bescheinigung",
|
||||
fileId: "file-1",
|
||||
}),
|
||||
});
|
||||
expect(mocks.tx.fileEntityLink.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
tenantId: "tenant-1",
|
||||
createdByUserId: "employee-1",
|
||||
fileId: "file-1",
|
||||
entityType: "user",
|
||||
entityId: "employee-1",
|
||||
linkRole: "hr_employee_document",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a file from outside the tenant before creating a document", async () => {
|
||||
mocks.tx.file.findFirst.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
createDocumentWithLink({
|
||||
tenantId: "tenant-1",
|
||||
employeeUserId: "employee-1",
|
||||
uploadedByUserId: "employee-1",
|
||||
title: "Bescheinigung",
|
||||
documentKind: "certificate",
|
||||
fileId: "foreign-file",
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
|
||||
expect(mocks.tx.hrEmployeeDocument.create).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.fileEntityLink.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("resolves picker labels with team, position and roles", async () => {
|
||||
mocks.tx.tenantUser.findMany.mockResolvedValue([
|
||||
{
|
||||
userId: "employee-1",
|
||||
user: { firstName: "Mira", lastName: "Beispiel", email: "mira@example.test" },
|
||||
},
|
||||
]);
|
||||
mocks.tx.hrEmployeeProfile.findMany.mockResolvedValue([
|
||||
{ userId: "employee-1", team: "Montage", position: "Teamleitung" },
|
||||
]);
|
||||
mocks.tx.userRole.findMany.mockResolvedValue([
|
||||
{ userId: "employee-1", role: { name: "Projektleiter" } },
|
||||
]);
|
||||
|
||||
await expect(listHrMemberOptions("tenant-1")).resolves.toEqual([
|
||||
{
|
||||
userId: "employee-1",
|
||||
displayName: "Mira Beispiel",
|
||||
email: "mira@example.test",
|
||||
team: "Montage",
|
||||
position: "Teamleitung",
|
||||
roleNames: ["Projektleiter"],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects a posted picker target outside the active tenant", async () => {
|
||||
mocks.tx.tenantUser.findFirst.mockResolvedValue(null);
|
||||
await expect(requireActiveHrMember("tenant-1", "foreign-user")).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
+202
-3
@@ -17,10 +17,12 @@
|
||||
// tenant-scoped, so it stays on the db singleton.
|
||||
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
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";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
|
||||
const HR_AUDIT_MODULE = "hr";
|
||||
|
||||
@@ -68,9 +70,9 @@ export type HrEmployeeProfileRow = {
|
||||
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;
|
||||
/** Fields an employee may edit on their OWN profile (MA self-service). Team,
|
||||
* personal number, hire date, manager and location are HR-managed assignments. */
|
||||
const SELF_EDITABLE_FIELDS = ["position"] as const;
|
||||
export type SelfEditableProfileInput = Partial<Pick<HrEmployeeProfileRow, (typeof SELF_EDITABLE_FIELDS)[number]>>;
|
||||
|
||||
/** Load a single employee profile (tenant-scoped), or null. */
|
||||
@@ -100,6 +102,60 @@ export async function listDirectory(tenantId: string): Promise<DirectoryEntryRow
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Directory visibility for one viewer. HR readers see the full tenant;
|
||||
* employees see only themselves and their direct reports. This is deliberately
|
||||
* a server-side predicate so query-string filters cannot widen the audience.
|
||||
*/
|
||||
export async function listDirectoryForViewer(input: {
|
||||
tenantId: string;
|
||||
viewerUserId: string;
|
||||
canReadAll: boolean;
|
||||
}): Promise<DirectoryEntryRow[]> {
|
||||
const rows = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.hrEmployeeProfile.findMany({
|
||||
where: {
|
||||
tenantId: input.tenantId,
|
||||
...(input.canReadAll
|
||||
? {}
|
||||
: {
|
||||
OR: [{ userId: input.viewerUserId }, { managerUserId: input.viewerUserId }],
|
||||
}),
|
||||
},
|
||||
select: { userId: true, position: true, team: true, locationId: true, managerUserId: true },
|
||||
orderBy: [{ team: "asc" }, { userId: "asc" }],
|
||||
}),
|
||||
);
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** Fail closed when an employee target is outside self/direct-team/HR scope. */
|
||||
export async function requireEmployeeObjectAccess(input: {
|
||||
tenantId: string;
|
||||
viewerUserId: string;
|
||||
employeeUserId: string;
|
||||
canReadAll: boolean;
|
||||
}): Promise<{ isSelf: boolean; isDirectReport: boolean }> {
|
||||
const isSelf = input.viewerUserId === input.employeeUserId;
|
||||
if (isSelf) {
|
||||
return { isSelf: true, isDirectReport: false };
|
||||
}
|
||||
const row = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.hrEmployeeProfile.findFirst({
|
||||
where: {
|
||||
tenantId: input.tenantId,
|
||||
userId: input.employeeUserId,
|
||||
...(input.canReadAll ? {} : { managerUserId: input.viewerUserId }),
|
||||
},
|
||||
select: { userId: true, managerUserId: true },
|
||||
}),
|
||||
);
|
||||
if (!row) {
|
||||
throw new CatalogError(foundationErrors.notFound, { userId: input.employeeUserId });
|
||||
}
|
||||
return { isSelf, isDirectReport: row.managerUserId === input.viewerUserId };
|
||||
}
|
||||
|
||||
/** 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 = {};
|
||||
@@ -431,6 +487,84 @@ export async function createDocument(input: CreateDocumentInput): Promise<HrEmpl
|
||||
return created as HrEmployeeDocumentRow;
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically creates the HR document row and its Files ownership link after the
|
||||
* object bytes have been accepted by the file service. Callers must hard-delete
|
||||
* the newly-created File as compensation when this transaction fails.
|
||||
*/
|
||||
export async function createDocumentWithLink(input: CreateDocumentInput): Promise<HrEmployeeDocumentRow> {
|
||||
const title = input.title.trim();
|
||||
if (!title) {
|
||||
throw new HrServiceError("hr.error.documentTitleRequired");
|
||||
}
|
||||
const created = await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const file = await tx.file.findFirst({
|
||||
where: { id: input.fileId, tenantId: input.tenantId, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!file) {
|
||||
throw new CatalogError(foundationErrors.notFound, { fileId: input.fileId });
|
||||
}
|
||||
const document = await 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,
|
||||
},
|
||||
});
|
||||
await tx.fileEntityLink.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
createdByUserId: input.uploadedByUserId,
|
||||
fileId: input.fileId,
|
||||
entityType: "user",
|
||||
entityId: input.employeeUserId,
|
||||
linkRole: "hr_employee_document",
|
||||
},
|
||||
});
|
||||
await logActivity(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.uploadedByUserId,
|
||||
actorKind: "user",
|
||||
activityType: "file_uploaded",
|
||||
subjectType: "tenant",
|
||||
subjectId: input.tenantId,
|
||||
summaryText: "activity.runtime.hr.documentUploaded",
|
||||
metadata: {
|
||||
documentId: document.id,
|
||||
employeeUserId: input.employeeUserId,
|
||||
process: "hr_document",
|
||||
},
|
||||
},
|
||||
{ client: tx },
|
||||
);
|
||||
return document as HrEmployeeDocumentRow;
|
||||
});
|
||||
await createAuditEvent({
|
||||
tenantId: input.tenantId,
|
||||
actorId: input.uploadedByUserId,
|
||||
actorType: "user",
|
||||
action: "HR_DOCUMENT_CREATE",
|
||||
targetType: "HrEmployeeDocument",
|
||||
targetId: created.id,
|
||||
sourceModule: HR_AUDIT_MODULE,
|
||||
outcome: "success",
|
||||
metadata: {
|
||||
employeeUserId: input.employeeUserId,
|
||||
documentKind: created.documentKind,
|
||||
},
|
||||
});
|
||||
return created;
|
||||
}
|
||||
|
||||
/**
|
||||
* Archive a document. An employee may only archive their OWN, non-office
|
||||
* documents (office-uploaded = read-only). HR (viewerIsEmployee=false) may
|
||||
@@ -467,6 +601,71 @@ export async function archiveDocument(input: {
|
||||
|
||||
export type LabeledUser = { id: string; label: string; email: string };
|
||||
|
||||
export type HrMemberOption = {
|
||||
userId: string;
|
||||
displayName: string;
|
||||
email: string;
|
||||
team: string | null;
|
||||
position: string | null;
|
||||
roleNames: string[];
|
||||
};
|
||||
|
||||
/** Active tenant members for named employee/approver pickers. */
|
||||
export async function listHrMemberOptions(tenantId: string): Promise<HrMemberOption[]> {
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
const [memberships, profiles, roles] = await Promise.all([
|
||||
tx.tenantUser.findMany({
|
||||
where: { tenantId, status: TenantUserStatus.ACTIVE, user: { active: true } },
|
||||
select: {
|
||||
userId: true,
|
||||
user: { select: { firstName: true, lastName: true, email: true } },
|
||||
},
|
||||
orderBy: { user: { lastName: "asc" } },
|
||||
}),
|
||||
tx.hrEmployeeProfile.findMany({
|
||||
where: { tenantId },
|
||||
select: { userId: true, team: true, position: true },
|
||||
}),
|
||||
tx.userRole.findMany({
|
||||
where: { tenantId },
|
||||
select: { userId: true, role: { select: { name: true } } },
|
||||
}),
|
||||
]);
|
||||
const profileByUser = new Map(profiles.map((profile) => [profile.userId, profile]));
|
||||
const roleNamesByUser = new Map<string, string[]>();
|
||||
for (const role of roles) {
|
||||
const names = roleNamesByUser.get(role.userId) ?? [];
|
||||
names.push(role.role.name);
|
||||
roleNamesByUser.set(role.userId, names);
|
||||
}
|
||||
return memberships.map(({ userId, user }) => {
|
||||
const profile = profileByUser.get(userId);
|
||||
const name = `${user.firstName} ${user.lastName}`.trim();
|
||||
return {
|
||||
userId,
|
||||
displayName: name || user.email,
|
||||
email: user.email,
|
||||
team: profile?.team ?? null,
|
||||
position: profile?.position ?? null,
|
||||
roleNames: roleNamesByUser.get(userId) ?? [],
|
||||
};
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Validates a posted picker target against the active tenant membership. */
|
||||
export async function requireActiveHrMember(tenantId: string, userId: string): Promise<void> {
|
||||
const member = await withTenantRLS(tenantId, (tx) =>
|
||||
tx.tenantUser.findFirst({
|
||||
where: { tenantId, userId, status: TenantUserStatus.ACTIVE, user: { active: true } },
|
||||
select: { id: true },
|
||||
}),
|
||||
);
|
||||
if (!member) {
|
||||
throw new CatalogError(foundationErrors.notFound, { userId });
|
||||
}
|
||||
}
|
||||
|
||||
function userLabel(user: { firstName: string; lastName: string; email: string }): string {
|
||||
const name = `${user.firstName} ${user.lastName}`.trim();
|
||||
return name || user.email;
|
||||
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
audit: vi.fn(),
|
||||
crypto: {
|
||||
encrypt: vi.fn(async (_tenantId: string, value: string) => `cipher:${value}`),
|
||||
decrypt: vi.fn(async (_tenantId: string, value: string) => value.replace("cipher:", "")),
|
||||
},
|
||||
tx: {
|
||||
employeeSickLeaveReport: {
|
||||
findFirst: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
file: { findFirst: vi.fn() },
|
||||
fileEntityLink: { upsert: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: (_tenantId: string, callback: (tx: typeof mocks.tx) => unknown) => callback(mocks.tx),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({ createAuditEvent: mocks.audit }));
|
||||
vi.mock("./hrFieldCrypto.server", () => ({ getHrFieldCrypto: () => mocks.crypto }));
|
||||
|
||||
import {
|
||||
attachCertificate,
|
||||
cancelSickLeave,
|
||||
closeSickLeave,
|
||||
revealCertificateFileId,
|
||||
} from "./hrSickLeaveService.server";
|
||||
|
||||
const report = {
|
||||
id: "report-1",
|
||||
tenantId: "tenant-1",
|
||||
employeeUserId: "employee-1",
|
||||
reportedByUserId: "employee-1",
|
||||
startDate: new Date("2026-07-20"),
|
||||
expectedReturnDate: null,
|
||||
returnDate: null,
|
||||
certificateRefCiphertext: "cipher:file-1",
|
||||
status: "reported",
|
||||
note: null,
|
||||
calendarEventId: null,
|
||||
createdAt: new Date("2026-07-20"),
|
||||
updatedAt: new Date("2026-07-20"),
|
||||
};
|
||||
|
||||
describe("sick-leave object access", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.tx.employeeSickLeaveReport.findFirst.mockResolvedValue(report);
|
||||
mocks.tx.employeeSickLeaveReport.update.mockResolvedValue(report);
|
||||
mocks.tx.file.findFirst.mockResolvedValue({ id: "file-2" });
|
||||
mocks.tx.fileEntityLink.upsert.mockResolvedValue({ id: "link-1" });
|
||||
mocks.audit.mockResolvedValue({ id: "audit-1" });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["attach", () => attachCertificate({ tenantId: "tenant-1", reportId: "report-1", actorUserId: "other-user", certificateFileId: "file-2", canManageAny: false })],
|
||||
["reveal", () => revealCertificateFileId({ tenantId: "tenant-1", reportId: "report-1", revealerUserId: "other-user", canManageAny: false })],
|
||||
["close", () => closeSickLeave({ tenantId: "tenant-1", reportId: "report-1", actorUserId: "other-user", returnDate: new Date("2026-07-22"), canManageAny: false })],
|
||||
["cancel", () => cancelSickLeave({ tenantId: "tenant-1", reportId: "report-1", actorUserId: "other-user", canManageAny: false })],
|
||||
])("returns not-found semantics for a foreign report on %s", async (_name, action) => {
|
||||
await expect(action()).rejects.toThrow();
|
||||
expect(mocks.tx.employeeSickLeaveReport.update).not.toHaveBeenCalled();
|
||||
expect(mocks.audit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("allows the owner and an explicitly authorised HR writer", async () => {
|
||||
await expect(
|
||||
revealCertificateFileId({
|
||||
tenantId: "tenant-1",
|
||||
reportId: "report-1",
|
||||
revealerUserId: "employee-1",
|
||||
canManageAny: false,
|
||||
}),
|
||||
).resolves.toBe("file-1");
|
||||
await expect(
|
||||
closeSickLeave({
|
||||
tenantId: "tenant-1",
|
||||
reportId: "report-1",
|
||||
actorUserId: "hr-user",
|
||||
returnDate: new Date("2026-07-22"),
|
||||
canManageAny: true,
|
||||
}),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
+95
-12
@@ -7,11 +7,14 @@
|
||||
// permission-checked + audited reveal (mirrors hrService.revealEmergencyContact).
|
||||
// NO React/UI imports. Every tenant access runs inside withTenantRLS().
|
||||
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { CatalogError, foundationErrors, notify } from "@hivegrid/foundation";
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
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";
|
||||
import type { HrM05Values } from "./hrM05Forms";
|
||||
import { createSystemHrSubmissionWithTx } from "./hrM05Submission.server";
|
||||
|
||||
const HR_AUDIT_MODULE = "hr";
|
||||
|
||||
@@ -43,6 +46,7 @@ export type ReportSickLeaveInput = {
|
||||
expectedReturnDate?: Date | null;
|
||||
note?: string | null;
|
||||
isDemoData?: boolean;
|
||||
formValues?: HrM05Values;
|
||||
};
|
||||
|
||||
/** File a sick-leave report (self or on behalf of an employee). */
|
||||
@@ -50,8 +54,8 @@ export async function reportSickLeave(input: ReportSickLeaveInput): Promise<Sick
|
||||
if (input.expectedReturnDate && input.expectedReturnDate < input.startDate) {
|
||||
throw new HrServiceError("hr.error.sickRangeInvalid");
|
||||
}
|
||||
const created = (await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.employeeSickLeaveReport.create({
|
||||
const created = (await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const report = await tx.employeeSickLeaveReport.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
employeeUserId: input.employeeUserId,
|
||||
@@ -62,8 +66,45 @@ export async function reportSickLeave(input: ReportSickLeaveInput): Promise<Sick
|
||||
status: "reported",
|
||||
isDemoData: input.isDemoData ?? false,
|
||||
},
|
||||
}),
|
||||
)) as SickLeaveRow;
|
||||
});
|
||||
if (input.formValues) {
|
||||
await createSystemHrSubmissionWithTx(tx, {
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.reportedByUserId,
|
||||
process: "sick",
|
||||
linkedEntityType: "hr_sick_leave",
|
||||
linkedEntityId: report.id,
|
||||
values: input.formValues,
|
||||
});
|
||||
}
|
||||
await logActivity(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.reportedByUserId,
|
||||
actorKind: "user",
|
||||
activityType: "form_submitted",
|
||||
subjectType: "tenant",
|
||||
subjectId: input.tenantId,
|
||||
summaryText: "activity.runtime.hr.sickLeaveRecorded",
|
||||
metadata: { reportId: report.id, process: "sick" },
|
||||
},
|
||||
{ client: tx },
|
||||
);
|
||||
if (input.reportedByUserId !== input.employeeUserId) {
|
||||
await notify(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
userId: input.employeeUserId,
|
||||
channel: "IN_APP",
|
||||
category: "hr",
|
||||
messageKey: "hr.notify.sick.reportedFor",
|
||||
sourceKey: `hr-sick-reported:${report.id}`,
|
||||
},
|
||||
tx as unknown as Parameters<typeof notify>[1],
|
||||
).catch(() => undefined);
|
||||
}
|
||||
return report;
|
||||
})) as SickLeaveRow;
|
||||
await createAuditEvent({
|
||||
tenantId: input.tenantId,
|
||||
actorId: input.reportedByUserId,
|
||||
@@ -86,19 +127,54 @@ async function getReportOrThrow(tenantId: string, reportId: string): Promise<Sic
|
||||
return row as SickLeaveRow;
|
||||
}
|
||||
|
||||
function requireReportActor(
|
||||
row: SickLeaveRow,
|
||||
input: { actorUserId: string; canManageAny: boolean; reportId: string },
|
||||
): void {
|
||||
if (row.employeeUserId !== input.actorUserId && !input.canManageAny) {
|
||||
throw new CatalogError(foundationErrors.notFound, { reportId: input.reportId });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 },
|
||||
input: { tenantId: string; reportId: string; actorUserId: string; certificateFileId: string; canManageAny: boolean },
|
||||
crypto: HrFieldCrypto = getHrFieldCrypto(),
|
||||
): Promise<void> {
|
||||
const row = await getReportOrThrow(input.tenantId, input.reportId);
|
||||
requireReportActor(row, input);
|
||||
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 withTenantRLS(input.tenantId, async (tx) => {
|
||||
const file = await tx.file.findFirst({
|
||||
where: { id: input.certificateFileId, tenantId: input.tenantId, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!file) {
|
||||
throw new CatalogError(foundationErrors.notFound, { fileId: input.certificateFileId });
|
||||
}
|
||||
await tx.employeeSickLeaveReport.update({ where: { id: row.id }, data: { certificateRefCiphertext: ciphertext } });
|
||||
await tx.fileEntityLink.upsert({
|
||||
where: {
|
||||
fileId_entityType_entityId: {
|
||||
fileId: input.certificateFileId,
|
||||
entityType: "user",
|
||||
entityId: row.employeeUserId,
|
||||
},
|
||||
},
|
||||
update: { linkRole: "hr_sick_certificate" },
|
||||
create: {
|
||||
tenantId: input.tenantId,
|
||||
createdByUserId: input.actorUserId,
|
||||
fileId: input.certificateFileId,
|
||||
entityType: "user",
|
||||
entityId: row.employeeUserId,
|
||||
linkRole: "hr_sick_certificate",
|
||||
},
|
||||
});
|
||||
});
|
||||
await createAuditEvent({
|
||||
tenantId: input.tenantId,
|
||||
actorId: input.actorUserId,
|
||||
@@ -120,10 +196,15 @@ export async function attachCertificate(
|
||||
* `revealerUserId` is the employee themselves or holds hr.read_all (route).
|
||||
*/
|
||||
export async function revealCertificateFileId(
|
||||
input: { tenantId: string; reportId: string; revealerUserId: string },
|
||||
input: { tenantId: string; reportId: string; revealerUserId: string; canManageAny: boolean },
|
||||
crypto: HrFieldCrypto = getHrFieldCrypto(),
|
||||
): Promise<string | null> {
|
||||
const row = await getReportOrThrow(input.tenantId, input.reportId);
|
||||
requireReportActor(row, {
|
||||
actorUserId: input.revealerUserId,
|
||||
canManageAny: input.canManageAny,
|
||||
reportId: input.reportId,
|
||||
});
|
||||
if (!row.certificateRefCiphertext) {
|
||||
return null;
|
||||
}
|
||||
@@ -144,8 +225,9 @@ export async function revealCertificateFileId(
|
||||
}
|
||||
|
||||
/** 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> {
|
||||
export async function closeSickLeave(input: { tenantId: string; reportId: string; actorUserId: string; returnDate: Date; canManageAny: boolean }): Promise<void> {
|
||||
const row = await getReportOrThrow(input.tenantId, input.reportId);
|
||||
requireReportActor(row, input);
|
||||
if (row.status === "cancelled") {
|
||||
throw new HrServiceError("hr.error.sickNotUpdatable");
|
||||
}
|
||||
@@ -168,8 +250,9 @@ export async function closeSickLeave(input: { tenantId: string; reportId: string
|
||||
}
|
||||
|
||||
/** 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> {
|
||||
export async function cancelSickLeave(input: { tenantId: string; reportId: string; actorUserId: string; canManageAny: boolean }): Promise<void> {
|
||||
const row = await getReportOrThrow(input.tenantId, input.reportId);
|
||||
requireReportActor(row, input);
|
||||
await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.employeeSickLeaveReport.update({ where: { id: row.id }, data: { status: "cancelled" } }),
|
||||
);
|
||||
|
||||
+18
-8
@@ -10,6 +10,7 @@ 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 { requireValidHrAudienceWithTx } from "./hrAudience.server";
|
||||
import { HrServiceError } from "./hrService.server";
|
||||
|
||||
const HR_AUDIT_MODULE = "hr";
|
||||
@@ -50,11 +51,14 @@ export type CreateSurveyInput = { tenantId: string; authorUserId: string; title:
|
||||
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;
|
||||
const audienceKind = input.audienceKind ?? "all";
|
||||
const audienceRef = audienceKind === "all" ? null : (input.audienceRef ?? null);
|
||||
const created = (await withTenantRLS(input.tenantId, async (tx) => {
|
||||
await requireValidHrAudienceWithTx(tx, { tenantId: input.tenantId, kind: audienceKind, ref: audienceRef });
|
||||
return 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, audienceRef, 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;
|
||||
}
|
||||
@@ -63,8 +67,14 @@ export type UpdateSurveyInput = Partial<Omit<CreateSurveyInput, "tenantId" | "au
|
||||
|
||||
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 } });
|
||||
const existing = await tx.hrSurvey.findFirst({
|
||||
where: { id: input.surveyId, tenantId: input.tenantId },
|
||||
select: { id: true, audienceKind: true, audienceRef: true },
|
||||
});
|
||||
if (!existing) throw new CatalogError(foundationErrors.notFound, { surveyId: input.surveyId });
|
||||
const audienceKind = input.audienceKind ?? existing.audienceKind;
|
||||
const audienceRef = audienceKind === "all" ? null : input.audienceRef !== undefined ? input.audienceRef : existing.audienceRef;
|
||||
await requireValidHrAudienceWithTx(tx, { tenantId: input.tenantId, kind: audienceKind, ref: audienceRef });
|
||||
await tx.hrSurvey.update({
|
||||
where: { id: input.surveyId },
|
||||
data: {
|
||||
@@ -72,8 +82,8 @@ export async function updateSurvey(input: UpdateSurveyInput): Promise<void> {
|
||||
...(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 } : {}),
|
||||
audienceKind,
|
||||
audienceRef,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
integrationsAppPath,
|
||||
integrationsCatalogPath,
|
||||
integrationsSyncRunPath,
|
||||
integrationsSyncsPath,
|
||||
KWP_OAUTH_CALLBACK_PATH,
|
||||
KWP_SETUP_PATH,
|
||||
kwpMandantSelectionPath,
|
||||
kwpSetupPath,
|
||||
legacyIntegrationsRedirectPath,
|
||||
} from "./integrationsRoutePaths";
|
||||
|
||||
describe("integrationsRoutePaths", () => {
|
||||
it("keeps integration management inside the tenant settings workspace", () => {
|
||||
expect(integrationsCatalogPath("acme")).toBe("/acme/settings/integrations");
|
||||
expect(integrationsAppPath("acme", "google")).toBe("/acme/settings/integrations/google");
|
||||
expect(integrationsSyncsPath("acme", "google", "connection-1")).toBe("/acme/settings/integrations/google/connection-1/syncs");
|
||||
expect(integrationsSyncRunPath("acme", "google", "connection-1", "run-1")).toBe(
|
||||
"/acme/settings/integrations/google/connection-1/syncs/run-1"
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the registered KWP callback fixed and encodes the setup tenant", () => {
|
||||
expect(KWP_OAUTH_CALLBACK_PATH).toBe("/integrations/kwp/oauth/callback");
|
||||
expect(KWP_SETUP_PATH).toBe("/integrations/kwp/setup");
|
||||
expect(kwpSetupPath()).toBe(KWP_SETUP_PATH);
|
||||
expect(kwpSetupPath("acme & co")).toBe("/integrations/kwp/setup?tenant=acme%20%26%20co");
|
||||
expect(kwpMandantSelectionPath("acme", "connection-1")).toBe(
|
||||
"/integrations/kwp/setup?tenant=acme&connection=connection-1",
|
||||
);
|
||||
});
|
||||
|
||||
it("maps legacy integration UI URLs to settings while preserving the query", () => {
|
||||
expect(legacyIntegrationsRedirectPath("https://app.example.test/acme/integrations/google?tab=connections", "acme")).toBe(
|
||||
"/acme/settings/integrations/google?tab=connections"
|
||||
);
|
||||
expect(legacyIntegrationsRedirectPath("https://app.example.test/acme/settings/integrations/google", "acme")).toBeNull();
|
||||
});
|
||||
});
|
||||
+33
-8
@@ -1,29 +1,54 @@
|
||||
// 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.)
|
||||
// NOTE: DataConnection is tenant-scoped (tenant connector + integrations.* tenant
|
||||
// permission), so its management screens live in the tenant settings workspace.
|
||||
// OAuth callbacks remain outside the settings workspace under /integrations/:provider.
|
||||
|
||||
// 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 const KWP_SETUP_PATH = "/integrations/kwp/setup";
|
||||
export const KWP_OAUTH_CALLBACK_PATH = "/integrations/kwp/oauth/callback";
|
||||
|
||||
export function integrationsCatalogPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/integrations`;
|
||||
return `/${tenantSlug}/settings/integrations`;
|
||||
}
|
||||
|
||||
export function integrationsAppPath(tenantSlug: string, appKey: string): string {
|
||||
return `/${tenantSlug}/integrations/${appKey}`;
|
||||
return `/${tenantSlug}/settings/integrations/${appKey}`;
|
||||
}
|
||||
|
||||
export function kwpProjectImportPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/settings/integrations/kwp/import`;
|
||||
}
|
||||
|
||||
export function kwpSetupPath(tenantSlug?: string): string {
|
||||
const normalizedTenantSlug = tenantSlug?.trim();
|
||||
return normalizedTenantSlug ? `${KWP_SETUP_PATH}?tenant=${encodeURIComponent(normalizedTenantSlug)}` : KWP_SETUP_PATH;
|
||||
}
|
||||
|
||||
export function kwpMandantSelectionPath(tenantSlug: string, connectionId: string): string {
|
||||
const query = new URLSearchParams({ tenant: tenantSlug.trim(), connection: connectionId.trim() });
|
||||
return `${KWP_SETUP_PATH}?${query.toString()}`;
|
||||
}
|
||||
|
||||
export function integrationsSyncsPath(tenantSlug: string, appKey: string, connectionId: string): string {
|
||||
return `/${tenantSlug}/integrations/${appKey}/${connectionId}/syncs`;
|
||||
return `/${tenantSlug}/settings/integrations/${appKey}/${connectionId}/syncs`;
|
||||
}
|
||||
|
||||
export function integrationsSyncRunPath(tenantSlug: string, appKey: string, connectionId: string, runId: string): string {
|
||||
return `/${tenantSlug}/integrations/${appKey}/${connectionId}/syncs/${runId}`;
|
||||
return `/${tenantSlug}/settings/integrations/${appKey}/${connectionId}/syncs/${runId}`;
|
||||
}
|
||||
|
||||
export function legacyIntegrationsRedirectPath(requestUrl: string, tenantSlug: string): string | null {
|
||||
const url = new URL(requestUrl);
|
||||
const legacyPrefix = `/${tenantSlug}/integrations`;
|
||||
if (url.pathname !== legacyPrefix && !url.pathname.startsWith(`${legacyPrefix}/`)) {
|
||||
return null;
|
||||
}
|
||||
const settingsSuffix = url.pathname.slice(legacyPrefix.length);
|
||||
return `/${tenantSlug}/settings/integrations${settingsSuffix}${url.search}${url.hash}`;
|
||||
}
|
||||
+1
@@ -14,6 +14,7 @@ export type LeadAuditAction =
|
||||
| "lead.convert_requested"
|
||||
| "lead.source_created"
|
||||
| "lead.source_updated"
|
||||
| "lead.source_archived"
|
||||
| "lead.anti_spam_updated";
|
||||
|
||||
export async function auditLeadEvent(input: {
|
||||
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
// Pure query helpers for the lead inbox: the status dropdown maps a single UI
|
||||
// value onto the query's status list (and back), and the statistics tiles turn a
|
||||
// KPI into the search params that reproduce exactly what that tile counted.
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
canTransitionLeadStatus,
|
||||
leadStatisticsKpiParams,
|
||||
leadStatusFilterFromQuery,
|
||||
leadStatusFilterToQuery,
|
||||
parseLeadListQuery,
|
||||
} from "./leadListQuery";
|
||||
|
||||
describe("lead status filter mapping", () => {
|
||||
it("round-trips every value the dropdown can hold", () => {
|
||||
for (const value of ["any", "new", "qualified", "converted", "lost", "spam"] as const) {
|
||||
expect(leadStatusFilterFromQuery(leadStatusFilterToQuery(value))).toBe(value);
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back to 'any' for a combination it cannot name", () => {
|
||||
// The dropdown is single-select, so any multi-status query would be
|
||||
// misreported by naming just one of them.
|
||||
expect(leadStatusFilterFromQuery(["new", "qualified"])).toBe("any");
|
||||
expect(leadStatusFilterFromQuery(["new", "spam", "lost"])).toBe("any");
|
||||
expect(leadStatusFilterFromQuery([])).toBe("any");
|
||||
expect(leadStatusFilterFromQuery(null)).toBe("any");
|
||||
});
|
||||
});
|
||||
|
||||
describe("leadStatisticsKpiParams", () => {
|
||||
const parse = (kpi: Parameters<typeof leadStatisticsKpiParams>[0]) => parseLeadListQuery(leadStatisticsKpiParams(kpi));
|
||||
|
||||
it("links 'total' to an unfiltered list that also shows spam and converted", () => {
|
||||
const query = parse("total");
|
||||
expect(query.filter.status).toBeNull();
|
||||
expect(query.filter.includeSpam).toBe(true);
|
||||
expect(query.filter.includeConverted).toBe(true);
|
||||
});
|
||||
|
||||
it("links the 'new' tile to exactly the new status it counts", () => {
|
||||
expect(parse("new").filter.status).toEqual(["new"]);
|
||||
});
|
||||
|
||||
it("makes the spam and converted tiles reveal what they count", () => {
|
||||
// Both are hidden by default — without flipping visibility the tile would
|
||||
// link to an empty table.
|
||||
const spam = parse("spam");
|
||||
expect(spam.filter.status).toEqual(["spam"]);
|
||||
expect(spam.filter.includeSpam).toBe(true);
|
||||
|
||||
const converted = parse("converted");
|
||||
expect(converted.filter.status).toEqual(["converted"]);
|
||||
expect(converted.filter.includeConverted).toBe(true);
|
||||
});
|
||||
|
||||
it("survives the round trip through the dropdown value", () => {
|
||||
expect(leadStatusFilterFromQuery(parse("new").filter.status)).toBe("new");
|
||||
expect(leadStatusFilterFromQuery(parse("spam").filter.status)).toBe("spam");
|
||||
expect(leadStatusFilterFromQuery(parse("total").filter.status)).toBe("any");
|
||||
});
|
||||
});
|
||||
|
||||
describe("canTransitionLeadStatus", () => {
|
||||
it("allows the forward moves and blocks every exit from a terminal status", () => {
|
||||
expect(canTransitionLeadStatus("new", "qualified")).toBe(true);
|
||||
expect(canTransitionLeadStatus("qualified", "converted")).toBe(true);
|
||||
expect(canTransitionLeadStatus("qualified", "new")).toBe(false);
|
||||
for (const terminal of ["converted", "lost", "spam"] as const) {
|
||||
expect(canTransitionLeadStatus(terminal, "qualified")).toBe(false);
|
||||
// Staying put is not a transition.
|
||||
expect(canTransitionLeadStatus(terminal, terminal)).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
+39
-1
@@ -1,4 +1,11 @@
|
||||
export type LeadStatus = "new" | "qualified" | "converted" | "lost" | "spam";
|
||||
import {
|
||||
ALLOWED_LEAD_STATUS_TRANSITIONS,
|
||||
canTransitionLeadStatus,
|
||||
type LeadStatus,
|
||||
} from "@hivegrid/db/lead-status-contract";
|
||||
|
||||
export { ALLOWED_LEAD_STATUS_TRANSITIONS, canTransitionLeadStatus };
|
||||
export type { LeadStatus };
|
||||
export type LeadQuelle = "form" | "email" | "aircall" | "manual" | "custom";
|
||||
export type LeadSortField = "createdAt" | "status" | "quelle" | "spamScore";
|
||||
export type SortDir = "asc" | "desc";
|
||||
@@ -18,6 +25,37 @@ export interface LeadListQuery {
|
||||
cursor: string | null;
|
||||
}
|
||||
|
||||
/** What the single status dropdown in the inbox can stand for. */
|
||||
export type LeadStatusFilterValue = "any" | LeadStatus;
|
||||
|
||||
export function leadStatusFilterToQuery(value: LeadStatusFilterValue): LeadStatus[] | null {
|
||||
return value === "any" ? null : [value];
|
||||
}
|
||||
|
||||
/** Inverse of the above; anything it cannot name exactly falls back to "any". */
|
||||
export function leadStatusFilterFromQuery(status: readonly LeadStatus[] | null | undefined): LeadStatusFilterValue {
|
||||
return status && status.length === 1 ? status[0] : "any";
|
||||
}
|
||||
|
||||
/**
|
||||
* Search params that make the inbox show exactly what a statistics KPI tile
|
||||
* counts. Spam and converted leads are hidden by default, so the two tiles that
|
||||
* count them have to turn their visibility on as well — otherwise the tile links
|
||||
* to an empty table.
|
||||
*/
|
||||
export function leadStatisticsKpiParams(kpi: "total" | "new" | "converted" | "spam"): URLSearchParams {
|
||||
const base = { quelle: null, zustaendigerUserId: null, search: null };
|
||||
const filter: LeadListFilter =
|
||||
kpi === "total"
|
||||
? { ...base, status: null, includeSpam: true, includeConverted: true }
|
||||
: kpi === "new"
|
||||
? { ...base, status: ["new"], includeSpam: false, includeConverted: false }
|
||||
: kpi === "converted"
|
||||
? { ...base, status: ["converted"], includeSpam: false, includeConverted: true }
|
||||
: { ...base, status: ["spam"], includeSpam: true, includeConverted: false };
|
||||
return leadListQueryToParams({ filter, sort: { field: "createdAt", dir: "desc" }, cursor: 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"]);
|
||||
|
||||
+7
-1
@@ -12,8 +12,14 @@ export function leadDetailPath(tenantSlug: string, leadId: string): string {
|
||||
return `/${tenantSlug}/leads/${leadId}`;
|
||||
}
|
||||
|
||||
// Own top-level path (not /leads/statistics): the statistics screen is reached
|
||||
// through the leads sub-sidenav, not from inside the inbox route family.
|
||||
export function leadStatisticsPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/leads/statistics`;
|
||||
return `/${tenantSlug}/leads-statistics`;
|
||||
}
|
||||
|
||||
export function leadBoardPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/leads/board`;
|
||||
}
|
||||
|
||||
export function leadEventsPath(tenantSlug: string): string {
|
||||
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tx: {
|
||||
inboxLead: { findFirst: vi.fn(), update: vi.fn() },
|
||||
kontakt: { findFirst: vi.fn() },
|
||||
projekt: { findFirst: vi.fn() },
|
||||
userRole: { findMany: vi.fn() },
|
||||
groupUser: { findMany: vi.fn() },
|
||||
},
|
||||
publishOutboxEvent: vi.fn(),
|
||||
publishLeadSearchUpsert: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: async (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
|
||||
}));
|
||||
vi.mock("~/utils/db.server", () => ({ db: {} }));
|
||||
vi.mock("@hivegrid/db/outbox", () => ({ publishOutboxEvent: mocks.publishOutboxEvent }));
|
||||
vi.mock("@hivegrid/queue", () => ({ buildWorkflowTriggerOutboxEvent: vi.fn(() => ({})) }));
|
||||
vi.mock("~/services/search/searchIndexProjection.server", () => ({
|
||||
publishLeadSearchUpsert: mocks.publishLeadSearchUpsert,
|
||||
publishProjectSearchUpsert: vi.fn(),
|
||||
}));
|
||||
|
||||
import { completeLeadProjectConversion, requestLeadProjectConversion } from "./leadService.server";
|
||||
|
||||
const qualifiedLead = {
|
||||
id: "lead-a",
|
||||
tenantId: "tenant-a",
|
||||
createdByUserId: "actor-a",
|
||||
zustaendigerUserId: "actor-a",
|
||||
quelle: "manual",
|
||||
quelleDetail: null,
|
||||
sourceId: null,
|
||||
sourceOrigin: null,
|
||||
submitterIpHash: null,
|
||||
status: "qualified",
|
||||
weiterverarbeitungFreigabe: "ja",
|
||||
vorname: "Marie",
|
||||
nachname: "Muster",
|
||||
email: "marie@example.test",
|
||||
telefon: null,
|
||||
message: null,
|
||||
rohdaten: null,
|
||||
spamScore: 0,
|
||||
spamReason: null,
|
||||
isQuarantined: false,
|
||||
konvertiertProjektId: null,
|
||||
verknuepfterKontaktId: null,
|
||||
convertedAt: null,
|
||||
lostAt: null,
|
||||
spamMarkedAt: null,
|
||||
autoDeleteAt: null,
|
||||
isDemoData: false,
|
||||
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
archivedAt: null,
|
||||
} as const;
|
||||
|
||||
describe("lead conversion target visibility", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.tx.inboxLead.findFirst.mockResolvedValue(qualifiedLead);
|
||||
mocks.tx.inboxLead.update.mockImplementation(async ({ data }: { data: Record<string, unknown> }) => ({
|
||||
...qualifiedLead,
|
||||
...data,
|
||||
}));
|
||||
mocks.tx.kontakt.findFirst.mockResolvedValue({ id: "contact-a" });
|
||||
mocks.tx.projekt.findFirst.mockResolvedValue({ id: "project-a" });
|
||||
mocks.tx.userRole.findMany.mockResolvedValue([{ roleId: "role-a" }]);
|
||||
mocks.tx.groupUser.findMany.mockResolvedValue([{ groupId: "group-a" }]);
|
||||
});
|
||||
|
||||
it("returns 404 before mutation when a requested contact is outside crm.read_own", async () => {
|
||||
mocks.tx.kontakt.findFirst.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
requestLeadProjectConversion({
|
||||
tenantId: "tenant-a",
|
||||
leadId: "lead-a",
|
||||
kontaktId: " contact-from-tenant-b ",
|
||||
ctx: { userId: "actor-a", permissions: ["leads.read_own", "leads.write", "crm.read_own"] },
|
||||
})
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.kontakt.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: "contact-from-tenant-b",
|
||||
tenantId: "tenant-a",
|
||||
archivedAt: null,
|
||||
zustaendigerUserId: "actor-a",
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.tx.inboxLead.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 404 before mutation when the project is outside the project read scope", async () => {
|
||||
mocks.tx.projekt.findFirst.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
completeLeadProjectConversion({
|
||||
tenantId: "tenant-a",
|
||||
leadId: "lead-a",
|
||||
projektId: "project-from-tenant-b",
|
||||
ctx: {
|
||||
userId: "actor-a",
|
||||
permissions: ["leads.read_own", "leads.write", "projects.read_all"],
|
||||
roleIds: ["role-a"],
|
||||
groupIds: ["group-a"],
|
||||
},
|
||||
})
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.projekt.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: "project-from-tenant-b",
|
||||
tenantId: "tenant-a",
|
||||
archivedAt: null,
|
||||
pipeline: {
|
||||
accessRules: {
|
||||
none: {
|
||||
tenantId: "tenant-a",
|
||||
kannSehen: false,
|
||||
OR: [
|
||||
{ principalType: "user", principalId: "actor-a" },
|
||||
{ principalType: "role", principalId: "role-a" },
|
||||
{ principalType: "group", principalId: "group-a" },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.tx.inboxLead.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 404 when the actor has no project read permission", async () => {
|
||||
await expect(
|
||||
completeLeadProjectConversion({
|
||||
tenantId: "tenant-a",
|
||||
leadId: "lead-a",
|
||||
projektId: "project-a",
|
||||
ctx: { userId: "actor-a", permissions: ["leads.read_own", "leads.write"] },
|
||||
})
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.projekt.findFirst).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.inboxLead.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("validates and stores only visible normalized conversion targets", async () => {
|
||||
await expect(
|
||||
completeLeadProjectConversion({
|
||||
tenantId: "tenant-a",
|
||||
leadId: "lead-a",
|
||||
projektId: " project-a ",
|
||||
kontaktId: " contact-a ",
|
||||
ctx: {
|
||||
userId: "actor-a",
|
||||
permissions: ["leads.read_own", "leads.write", "projects.read_all", "crm.read_own"],
|
||||
roleIds: [],
|
||||
groupIds: [],
|
||||
},
|
||||
})
|
||||
).resolves.toMatchObject({
|
||||
status: "converted",
|
||||
konvertiertProjektId: "project-a",
|
||||
verknuepfterKontaktId: "contact-a",
|
||||
});
|
||||
|
||||
expect(mocks.tx.kontakt.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: "contact-a",
|
||||
tenantId: "tenant-a",
|
||||
archivedAt: null,
|
||||
zustaendigerUserId: "actor-a",
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.tx.inboxLead.update).toHaveBeenCalledWith({
|
||||
where: { id: "lead-a", tenantId: "tenant-a" },
|
||||
data: {
|
||||
status: "converted",
|
||||
weiterverarbeitungFreigabe: "ja",
|
||||
konvertiertProjektId: "project-a",
|
||||
verknuepfterKontaktId: "contact-a",
|
||||
convertedAt: expect.any(Date),
|
||||
autoDeleteAt: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
+219
-73
@@ -1,9 +1,13 @@
|
||||
import { CatalogError, foundationErrors, notify } from "@hivegrid/foundation";
|
||||
import { CatalogError, foundationErrors, massActionErrors, notify } from "@hivegrid/foundation";
|
||||
import { leadStatusTimestampData } from "@hivegrid/db/lead-status-contract";
|
||||
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
|
||||
import { buildWorkflowTriggerOutboxEvent, type QueueJsonValue } from "@hivegrid/queue";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
import { publishLeadSearchUpsert } from "~/services/search/searchIndexProjection.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
import { projectReadScopeWhere, type ProjectVisibilityContext } from "~/utils/integrations/projects/projectService.server";
|
||||
import { canTransitionLeadStatus } from "./leadListQuery";
|
||||
import type { LeadListFilter, LeadSortField, SortDir } from "./leadListQuery";
|
||||
|
||||
export class LeadServiceError extends Error {
|
||||
@@ -21,10 +25,7 @@ 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 type LeadVisibilityContext = ProjectVisibilityContext;
|
||||
|
||||
export function canReadAllLeads(ctx: LeadVisibilityContext): boolean {
|
||||
return ctx.permissions.includes("leads.read_all");
|
||||
@@ -34,6 +35,70 @@ export function ownerScopeWhere(ctx: LeadVisibilityContext): { zustaendigerUserI
|
||||
return canReadAllLeads(ctx) ? {} : { zustaendigerUserId: ctx.userId };
|
||||
}
|
||||
|
||||
async function requireActiveTenantUserWithTx(tx: TenantRlsClient, tenantId: string, userId: string): Promise<void> {
|
||||
const membership = await tx.tenantUser.findFirst({
|
||||
where: { tenantId, userId, status: TenantUserStatus.ACTIVE, user: { active: true } },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!membership) throw new CatalogError(foundationErrors.notFound, { userId });
|
||||
}
|
||||
|
||||
async function hydrateProjectVisibilityContextWithTx(tx: TenantRlsClient, tenantId: string, ctx: LeadVisibilityContext): Promise<ProjectVisibilityContext> {
|
||||
const [roleIds, groupIds] = await Promise.all([
|
||||
ctx.roleIds === undefined
|
||||
? tx.userRole.findMany({ where: { tenantId, userId: ctx.userId }, select: { roleId: true } }).then((rows) => rows.map(({ roleId }) => roleId))
|
||||
: Promise.resolve([...ctx.roleIds]),
|
||||
ctx.groupIds === undefined
|
||||
? tx.groupUser
|
||||
.findMany({ where: { userId: ctx.userId, group: { tenantId } }, select: { groupId: true } })
|
||||
.then((rows) => rows.map(({ groupId }) => groupId))
|
||||
: Promise.resolve([...ctx.groupIds]),
|
||||
]);
|
||||
return { ...ctx, roleIds, groupIds };
|
||||
}
|
||||
|
||||
async function requireVisibleConversionProjectWithTx(tx: TenantRlsClient, tenantId: string, projectId: string, ctx: LeadVisibilityContext): Promise<void> {
|
||||
if (
|
||||
!ctx.permissions.some((permission) => ["projects.read_all", "projects.read_own", "projects.read_own_pl", "projects.read_own_member"].includes(permission))
|
||||
) {
|
||||
throw new CatalogError(foundationErrors.notFound, { projectId });
|
||||
}
|
||||
const projectCtx = await hydrateProjectVisibilityContextWithTx(tx, tenantId, ctx);
|
||||
const project = await tx.projekt.findFirst({
|
||||
where: {
|
||||
id: projectId,
|
||||
tenantId,
|
||||
archivedAt: null,
|
||||
...projectReadScopeWhere(tenantId, projectCtx),
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
if (!project) throw new CatalogError(foundationErrors.notFound, { projectId });
|
||||
}
|
||||
|
||||
async function requireVisibleConversionContactWithTx(
|
||||
tx: TenantRlsClient,
|
||||
tenantId: string,
|
||||
kontaktId: string | null,
|
||||
ctx: LeadVisibilityContext
|
||||
): Promise<void> {
|
||||
if (!kontaktId) return;
|
||||
const canReadAll = ctx.permissions.includes("crm.read_all");
|
||||
if (!canReadAll && !ctx.permissions.includes("crm.read_own")) {
|
||||
throw new CatalogError(foundationErrors.notFound, { kontaktId });
|
||||
}
|
||||
const kontakt = await tx.kontakt.findFirst({
|
||||
where: {
|
||||
id: kontaktId,
|
||||
tenantId,
|
||||
archivedAt: null,
|
||||
...(canReadAll ? {} : { zustaendigerUserId: ctx.userId }),
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
if (!kontakt) throw new CatalogError(foundationErrors.notFound, { kontaktId });
|
||||
}
|
||||
|
||||
export type LeadRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
@@ -101,15 +166,6 @@ export type LeadAntiSpamConfigRow = {
|
||||
};
|
||||
|
||||
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();
|
||||
@@ -121,7 +177,13 @@ function normalizeTelefon(telefon?: string | null): string | null {
|
||||
return value || null;
|
||||
}
|
||||
|
||||
function leadNamePresent(input: { vorname?: string | null; nachname?: string | null; email?: string | null; telefon?: string | null; message?: string | null }): boolean {
|
||||
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());
|
||||
}
|
||||
|
||||
@@ -137,9 +199,7 @@ async function ensureAntiSpamConfigWithTx(tx: TenantRlsClient, tenantId: string)
|
||||
return created as LeadAntiSpamConfigRow;
|
||||
}
|
||||
|
||||
export function canTransitionLeadStatus(from: LeadStatus, to: LeadStatus): boolean {
|
||||
return from === to || ALLOWED_STATUS_TRANSITIONS[from].includes(to);
|
||||
}
|
||||
export { canTransitionLeadStatus };
|
||||
|
||||
function assertStatusTransition(from: LeadStatus, to: LeadStatus): void {
|
||||
if (!canTransitionLeadStatus(from, to)) {
|
||||
@@ -148,27 +208,29 @@ function assertStatusTransition(from: LeadStatus, to: LeadStatus): void {
|
||||
}
|
||||
|
||||
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;
|
||||
const data = leadStatusTimestampData(status, now, config.lostAutoDeleteDays);
|
||||
return "autoDeleteAt" in data ? (data.autoDeleteAt ?? null) : 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) } : {}),
|
||||
};
|
||||
return leadStatusTimestampData(status, now, config.lostAutoDeleteDays);
|
||||
}
|
||||
|
||||
function toWorkflowPayload(input: {
|
||||
lead: Pick<LeadRow, "id" | "tenantId" | "quelle" | "sourceId" | "status" | "weiterverarbeitungFreigabe" | "zustaendigerUserId" | "konvertiertProjektId" | "verknuepfterKontaktId" | "spamScore" | "isQuarantined">;
|
||||
lead: Pick<
|
||||
LeadRow,
|
||||
| "id"
|
||||
| "tenantId"
|
||||
| "quelle"
|
||||
| "sourceId"
|
||||
| "status"
|
||||
| "weiterverarbeitungFreigabe"
|
||||
| "zustaendigerUserId"
|
||||
| "konvertiertProjektId"
|
||||
| "verknuepfterKontaktId"
|
||||
| "spamScore"
|
||||
| "isQuarantined"
|
||||
>;
|
||||
action: "created" | "qualified" | "status_changed" | "convert_requested" | "converted";
|
||||
}): QueueJsonValue {
|
||||
return {
|
||||
@@ -195,7 +257,7 @@ async function publishLeadWorkflowEvent(
|
||||
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,
|
||||
@@ -205,13 +267,13 @@ async function publishLeadWorkflowEvent(
|
||||
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 },
|
||||
input: { tenantId: string; source: Pick<LeadSourceRow, "id" | "key" | "name">; reason: string }
|
||||
): Promise<void> {
|
||||
try {
|
||||
const admins = await tx.userRole.findMany({
|
||||
@@ -234,9 +296,9 @@ async function notifyLeadSourcePausedAdmins(
|
||||
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],
|
||||
),
|
||||
),
|
||||
tx as unknown as Parameters<typeof notify>[1]
|
||||
)
|
||||
)
|
||||
);
|
||||
} catch {
|
||||
// Notification failures must not lose the lead submission.
|
||||
@@ -282,9 +344,7 @@ async function computeRateAndAnomalySignals(input: {
|
||||
}): 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 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 } }),
|
||||
@@ -338,9 +398,7 @@ export async function createLead(input: CreateLeadInput): Promise<LeadRow> {
|
||||
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;
|
||||
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");
|
||||
}
|
||||
@@ -361,6 +419,8 @@ export async function createLead(input: CreateLeadInput): Promise<LeadRow> {
|
||||
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);
|
||||
const responsibleUserId = input.zustaendigerUserId ?? source?.defaultZustaendigerUserId ?? input.userId ?? null;
|
||||
if (responsibleUserId) await requireActiveTenantUserWithTx(tx, input.tenantId, responsibleUserId);
|
||||
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" });
|
||||
@@ -369,7 +429,7 @@ export async function createLead(input: CreateLeadInput): Promise<LeadRow> {
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
createdByUserId: input.userId ?? null,
|
||||
zustaendigerUserId: input.zustaendigerUserId ?? source?.defaultZustaendigerUserId ?? input.userId ?? null,
|
||||
zustaendigerUserId: responsibleUserId,
|
||||
quelle: input.quelle,
|
||||
quelleDetail: input.quelleDetail ?? undefined,
|
||||
sourceId: source?.id ?? null,
|
||||
@@ -468,10 +528,40 @@ export async function listLeadsForBrowser(input: {
|
||||
});
|
||||
}
|
||||
|
||||
export async function listLeadsForBoard(input: {
|
||||
tenantId: string;
|
||||
ctx: LeadVisibilityContext;
|
||||
statuses: readonly LeadStatus[];
|
||||
search?: string | null;
|
||||
limitPerStatus?: number;
|
||||
}): Promise<{ rows: LeadRow[]; countsByStatus: Partial<Record<LeadStatus, number>> }> {
|
||||
const limitPerStatus = Math.min(Math.max(input.limitPerStatus ?? DEFAULT_LIMIT, 1), DEFAULT_LIMIT);
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const queries = input.statuses.map(async (status) => {
|
||||
const where = whereForLeadList(input.tenantId, input.ctx, {
|
||||
status: [status],
|
||||
quelle: null,
|
||||
zustaendigerUserId: null,
|
||||
search: input.search?.trim() || null,
|
||||
includeSpam: false,
|
||||
includeConverted: true,
|
||||
});
|
||||
const [rows, count] = await Promise.all([
|
||||
tx.inboxLead.findMany({ where, orderBy: [{ createdAt: "desc" }, { id: "desc" }], take: limitPerStatus }),
|
||||
tx.inboxLead.count({ where }),
|
||||
]);
|
||||
return { status, rows: rows as LeadRow[], count };
|
||||
});
|
||||
const results = await Promise.all(queries);
|
||||
return {
|
||||
rows: results.flatMap((result) => result.rows),
|
||||
countsByStatus: Object.fromEntries(results.map((result) => [result.status, result.count])) as Partial<Record<LeadStatus, number>>,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
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) } }),
|
||||
);
|
||||
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 });
|
||||
}
|
||||
@@ -491,6 +581,9 @@ export async function updateLead(input: {
|
||||
zustaendigerUserId?: string | null;
|
||||
}): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
if (input.zustaendigerUserId) {
|
||||
await requireActiveTenantUserWithTx(tx, input.tenantId, input.zustaendigerUserId);
|
||||
}
|
||||
const existing = await tx.inboxLead.findFirst({
|
||||
where: { id: input.leadId, tenantId: input.tenantId, archivedAt: null, ...(input.ctx ? ownerScopeWhere(input.ctx) : {}) },
|
||||
select: { id: true },
|
||||
@@ -512,7 +605,13 @@ export async function updateLead(input: {
|
||||
});
|
||||
}
|
||||
|
||||
export async function setLeadStatus(input: { tenantId: string; leadId: string; status: LeadStatus; ctx?: LeadVisibilityContext; userId?: string | null }): Promise<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);
|
||||
@@ -544,12 +643,13 @@ export async function setLeadStatus(input: { tenantId: string; leadId: string; s
|
||||
}
|
||||
|
||||
export async function bulkSetLeadStatus(input: { tenantId: string; ctx: LeadVisibilityContext; leadIds: string[]; status: LeadStatus }): Promise<number> {
|
||||
if (input.leadIds.length === 0) return 0;
|
||||
const leadIds = normalizeBulkLeadIds(input.leadIds);
|
||||
if (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) },
|
||||
where: { id: { in: 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");
|
||||
@@ -574,7 +674,25 @@ export async function bulkSetLeadStatus(input: { tenantId: string; ctx: LeadVisi
|
||||
return result.count;
|
||||
}
|
||||
|
||||
export async function requestLeadProjectConversion(input: { tenantId: string; leadId: string; kontaktId?: string | null; ctx?: LeadVisibilityContext; userId?: string | null }): Promise<LeadRow> {
|
||||
export const LEAD_BULK_MAX_ENTRIES = 100;
|
||||
|
||||
export function normalizeBulkLeadIds(leadIds: readonly string[]): string[] {
|
||||
if (leadIds.length > LEAD_BULK_MAX_ENTRIES) {
|
||||
throw new CatalogError(massActionErrors.exceedsLimit, {
|
||||
affected: leadIds.length,
|
||||
hardLimit: LEAD_BULK_MAX_ENTRIES,
|
||||
});
|
||||
}
|
||||
return [...new Set(leadIds.map((id) => id.trim()).filter(Boolean))];
|
||||
}
|
||||
|
||||
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) => {
|
||||
@@ -585,12 +703,14 @@ export async function requestLeadProjectConversion(input: { tenantId: string; le
|
||||
throw new CatalogError(foundationErrors.notFound, { leadId: input.leadId });
|
||||
}
|
||||
assertStatusTransition(current.status as LeadStatus, "qualified");
|
||||
const kontaktId = normalizeOptionalText(input.kontaktId);
|
||||
await requireVisibleConversionContactWithTx(tx, input.tenantId, kontaktId, input.ctx);
|
||||
const updated = await tx.inboxLead.update({
|
||||
where: { id: current.id },
|
||||
where: { id: current.id, tenantId: input.tenantId },
|
||||
data: {
|
||||
status: "qualified",
|
||||
weiterverarbeitungFreigabe: "ja",
|
||||
verknuepfterKontaktId: input.kontaktId ?? undefined,
|
||||
verknuepfterKontaktId: kontaktId ?? undefined,
|
||||
},
|
||||
});
|
||||
const lead = updated as LeadRow;
|
||||
@@ -601,13 +721,17 @@ export async function requestLeadProjectConversion(input: { tenantId: string; le
|
||||
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",
|
||||
});
|
||||
// Only when qualification actually happened here. Re-announcing it for an
|
||||
// already-qualified lead is both untrue and a duplicate dispatch key.
|
||||
if (current.status !== "qualified") {
|
||||
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;
|
||||
});
|
||||
@@ -618,7 +742,7 @@ export async function completeLeadProjectConversion(input: {
|
||||
leadId: string;
|
||||
projektId: string;
|
||||
kontaktId?: string | null;
|
||||
ctx?: LeadVisibilityContext;
|
||||
ctx: LeadVisibilityContext;
|
||||
userId?: string | null;
|
||||
}): Promise<LeadRow> {
|
||||
const projektId = normalizeOptionalText(input.projektId);
|
||||
@@ -633,13 +757,18 @@ export async function completeLeadProjectConversion(input: {
|
||||
throw new CatalogError(foundationErrors.notFound, { leadId: input.leadId });
|
||||
}
|
||||
assertStatusTransition(current.status as LeadStatus, "converted");
|
||||
const kontaktId = normalizeOptionalText(input.kontaktId) ?? current.verknuepfterKontaktId;
|
||||
await Promise.all([
|
||||
requireVisibleConversionProjectWithTx(tx, input.tenantId, projektId, input.ctx),
|
||||
requireVisibleConversionContactWithTx(tx, input.tenantId, kontaktId, input.ctx),
|
||||
]);
|
||||
const updated = await tx.inboxLead.update({
|
||||
where: { id: current.id },
|
||||
where: { id: current.id, tenantId: input.tenantId },
|
||||
data: {
|
||||
status: "converted",
|
||||
weiterverarbeitungFreigabe: "ja",
|
||||
konvertiertProjektId: projektId,
|
||||
verknuepfterKontaktId: input.kontaktId ?? current.verknuepfterKontaktId,
|
||||
verknuepfterKontaktId: kontaktId,
|
||||
convertedAt: new Date(),
|
||||
autoDeleteAt: null,
|
||||
},
|
||||
@@ -659,7 +788,7 @@ export async function completeLeadProjectConversion(input: {
|
||||
|
||||
export async function listAssignableUsers(tenantId: string): Promise<{ id: string; label: string }[]> {
|
||||
const rows = await db.tenantUser.findMany({
|
||||
where: { tenantId },
|
||||
where: { tenantId, status: TenantUserStatus.ACTIVE, user: { active: true } },
|
||||
select: { userId: true, user: { select: { firstName: true, lastName: true, email: true } } },
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
@@ -677,8 +806,9 @@ export async function resolveUserLabels(userIds: string[]): Promise<Map<string,
|
||||
}
|
||||
|
||||
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[],
|
||||
return withTenantRLS(
|
||||
tenantId,
|
||||
async (tx) => (await tx.leadSource.findMany({ where: { tenantId, archivedAt: null }, orderBy: [{ type: "asc" }, { name: "asc" }] })) as LeadSourceRow[]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -710,11 +840,27 @@ export async function upsertLeadSource(input: {
|
||||
type: input.type ?? "custom",
|
||||
defaultZustaendigerUserId: input.defaultZustaendigerUserId ?? null,
|
||||
},
|
||||
}),
|
||||
})
|
||||
);
|
||||
return row as LeadSourceRow;
|
||||
}
|
||||
|
||||
/**
|
||||
* Soft-delete of a lead source: sets archivedAt so it drops out of the admin
|
||||
* list and cannot be assigned to new leads, while leads already captured
|
||||
* through it keep pointing at a row that still exists.
|
||||
*/
|
||||
export async function archiveLeadSource(input: { tenantId: string; sourceId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const existing = await tx.leadSource.findFirst({
|
||||
where: { id: input.sourceId, tenantId: input.tenantId, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!existing) throw new LeadServiceError("leads.error.sourceNotFound");
|
||||
await tx.leadSource.updateMany({ where: { id: input.sourceId, tenantId: input.tenantId }, data: { archivedAt: new Date() } });
|
||||
});
|
||||
}
|
||||
|
||||
export async function getLeadAntiSpamConfig(tenantId: string): Promise<LeadAntiSpamConfigRow> {
|
||||
return withTenantRLS(tenantId, (tx) => ensureAntiSpamConfigWithTx(tx, tenantId));
|
||||
}
|
||||
@@ -751,7 +897,7 @@ export async function updateLeadAntiSpamConfig(input: {
|
||||
|
||||
export async function getLeadStatistics(input: { tenantId: string; ctx: LeadVisibilityContext }): Promise<{
|
||||
total: number;
|
||||
open: number;
|
||||
new: number;
|
||||
converted: number;
|
||||
spam: number;
|
||||
byQuelle: { quelle: LeadQuelle; count: number }[];
|
||||
@@ -759,9 +905,9 @@ export async function getLeadStatistics(input: { tenantId: string; ctx: LeadVisi
|
||||
}> {
|
||||
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([
|
||||
const [total, neu, 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: "new" } }),
|
||||
tx.inboxLead.count({ where: { ...where, status: "converted" } }),
|
||||
tx.inboxLead.count({ where: { ...where, status: "spam" } }),
|
||||
tx.inboxLead.groupBy({ by: ["quelle"], where, _count: { _all: true } }),
|
||||
@@ -769,7 +915,7 @@ export async function getLeadStatistics(input: { tenantId: string; ctx: LeadVisi
|
||||
]);
|
||||
return {
|
||||
total,
|
||||
open,
|
||||
new: neu,
|
||||
converted,
|
||||
spam,
|
||||
byQuelle: byQuelleRaw.map((row) => ({ quelle: row.quelle as LeadQuelle, count: row._count._all })),
|
||||
|
||||
+8
-1
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { canTransitionLeadStatus, type LeadStatus } from "./leadService.server";
|
||||
import { canTransitionLeadStatus, LEAD_BULK_MAX_ENTRIES, normalizeBulkLeadIds, type LeadStatus } from "./leadService.server";
|
||||
|
||||
describe("lead status workflow", () => {
|
||||
test.each<[LeadStatus, LeadStatus]>([
|
||||
@@ -25,4 +25,11 @@ describe("lead status workflow", () => {
|
||||
test("allows idempotent status writes", () => {
|
||||
expect(canTransitionLeadStatus("converted", "converted")).toBe(true);
|
||||
});
|
||||
|
||||
test("bounds and deduplicates bulk lead IDs", () => {
|
||||
expect(normalizeBulkLeadIds([" lead-a ", "lead-a", "", "lead-b"])).toEqual(["lead-a", "lead-b"]);
|
||||
expect(() => normalizeBulkLeadIds(Array.from({ length: LEAD_BULK_MAX_ENTRIES + 1 }, (_, index) => `lead-${index}`))).toThrow(
|
||||
"foundation.mass_action_exceeds_limit"
|
||||
);
|
||||
});
|
||||
});
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
import { redirect, type LoaderFunctionArgs } from "react-router";
|
||||
import { loadHrContext, notFoundResponse, requireHrPermission } from "./hrAccess.server";
|
||||
import { getVaultForUser } from "./hrPasswordSafeService.server";
|
||||
import { passwordSafeAdminPath, passwordSafePath, passwordSafeVaultPath } from "./passwordSafeRoutePaths";
|
||||
|
||||
type LegacyPasswordSafeTarget = "list" | "vault" | "admin";
|
||||
|
||||
/**
|
||||
* Permission-aware one-hop redirects for bookmarks from the former HR and
|
||||
* `/password-safe` route families. Detail redirects resolve the caller's
|
||||
* object access before revealing the canonical location.
|
||||
*/
|
||||
export function legacyPasswordSafeRedirectLoader(target: LegacyPasswordSafeTarget) {
|
||||
return async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const ctx = await loadHrContext({ request, params });
|
||||
if (!ctx.hasModule) throw notFoundResponse();
|
||||
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const search = new URL(request.url).search;
|
||||
try {
|
||||
if (target === "admin") {
|
||||
requireHrPermission(ctx, "hr.passwordsafe.admin");
|
||||
throw redirect(`${passwordSafeAdminPath(tenantSlug)}${search}`, 302);
|
||||
}
|
||||
|
||||
requireHrPermission(ctx, "hr.passwordsafe.use");
|
||||
if (target === "vault") {
|
||||
const vaultId = params.vaultId ?? "";
|
||||
const vault = await getVaultForUser(ctx.tenantId, vaultId, ctx.userId);
|
||||
if (!vault) throw notFoundResponse();
|
||||
throw redirect(`${passwordSafeVaultPath(tenantSlug, vaultId)}${search}`, 302);
|
||||
}
|
||||
throw redirect(`${passwordSafePath(tenantSlug)}${search}`, 302);
|
||||
} catch (error) {
|
||||
if (error instanceof Response) throw error;
|
||||
throw notFoundResponse();
|
||||
}
|
||||
};
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
loadContext: vi.fn(),
|
||||
requirePermission: vi.fn(),
|
||||
getVault: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("./hrAccess.server", () => ({
|
||||
loadHrContext: mocks.loadContext,
|
||||
requireHrPermission: mocks.requirePermission,
|
||||
notFoundResponse: () => new Response("Not Found", { status: 404 }),
|
||||
}));
|
||||
vi.mock("./hrPasswordSafeService.server", () => ({ getVaultForUser: mocks.getVault }));
|
||||
|
||||
import { legacyPasswordSafeRedirectLoader } from "./passwordSafeLegacyRedirect.server";
|
||||
|
||||
function args(path: string, params: Record<string, string>) {
|
||||
return { request: new Request(`https://app.example.test${path}`), params, context: {} } as never;
|
||||
}
|
||||
|
||||
describe("permission-aware password legacy redirects", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.loadContext.mockResolvedValue({ tenantId: "tenant-1", userId: "user-1", permissions: [], hasModule: true });
|
||||
mocks.getVault.mockResolvedValue({ id: "vault-1", name: "Ops", accessLevel: "read" });
|
||||
});
|
||||
|
||||
it("redirects an authorised HR bookmark in one hop and preserves the query", async () => {
|
||||
const loader = legacyPasswordSafeRedirectLoader("vault");
|
||||
await expect(loader(args("/acme/hr/password-safe/vault-1?tab=entries", { tenant: "acme", vaultId: "vault-1" }))).rejects.toMatchObject({ status: 302 });
|
||||
try {
|
||||
await loader(args("/acme/hr/password-safe/vault-1?tab=entries", { tenant: "acme", vaultId: "vault-1" }));
|
||||
} catch (response) {
|
||||
expect((response as Response).headers.get("location")).toBe("/acme/passwords/vault-1?tab=entries");
|
||||
}
|
||||
expect(mocks.requirePermission).toHaveBeenCalledWith(expect.anything(), "hr.passwordsafe.use");
|
||||
expect(mocks.getVault).toHaveBeenCalledWith("tenant-1", "vault-1", "user-1");
|
||||
});
|
||||
|
||||
it("returns 404 before redirecting when the module or object access is absent", async () => {
|
||||
mocks.loadContext.mockResolvedValueOnce({ tenantId: "tenant-1", userId: "user-1", permissions: [], hasModule: false });
|
||||
await expect(legacyPasswordSafeRedirectLoader("list")(args("/acme/hr/password-safe", { tenant: "acme" }))).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
mocks.getVault.mockResolvedValueOnce(null);
|
||||
await expect(
|
||||
legacyPasswordSafeRedirectLoader("vault")(args("/acme/hr/password-safe/foreign", { tenant: "acme", vaultId: "foreign" }))
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
});
|
||||
|
||||
it("requires the tenant metadata-admin permission for the old admin URL", async () => {
|
||||
await expect(legacyPasswordSafeRedirectLoader("admin")(args("/acme/hr/admin/password-safe", { tenant: "acme" }))).rejects.toMatchObject({ status: 302 });
|
||||
expect(mocks.requirePermission).toHaveBeenCalledWith(expect.anything(), "hr.passwordsafe.admin");
|
||||
});
|
||||
});
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveRepoPath } from "~/utils/testing/repoPaths";
|
||||
import { passwordSafeAdminPath, passwordSafeExportPath, passwordSafePath, passwordSafeRevealPath, passwordSafeVaultPath } from "./passwordSafeRoutePaths";
|
||||
|
||||
describe("password-safe canonical route paths", () => {
|
||||
it("keeps every password-safe surface outside the HR route tree", () => {
|
||||
expect(passwordSafePath("acme")).toBe("/acme/passwords");
|
||||
expect(passwordSafeVaultPath("acme", "vault-1")).toBe("/acme/passwords/vault-1");
|
||||
expect(passwordSafeRevealPath("acme", "vault-1")).toBe("/acme/passwords/vault-1/reveal");
|
||||
expect(passwordSafeExportPath("acme", "vault-1")).toBe("/acme/passwords/vault-1/export");
|
||||
expect(passwordSafeAdminPath("acme")).toBe("/acme/passwords/admin");
|
||||
});
|
||||
|
||||
it("registers canonical routes and explicit compatibility redirects", () => {
|
||||
[
|
||||
"apps/web/app/routes/app.$tenant/passwords._index.tsx",
|
||||
"apps/web/app/routes/app.$tenant/passwords.$vaultId._index.tsx",
|
||||
"apps/web/app/routes/app.$tenant/passwords.$vaultId.reveal.tsx",
|
||||
"apps/web/app/routes/app.$tenant/passwords.$vaultId.export.tsx",
|
||||
"apps/web/app/routes/app.$tenant/passwords.admin.tsx",
|
||||
].forEach((routeFile) => expect(existsSync(resolveRepoPath(routeFile)), routeFile).toBe(true));
|
||||
|
||||
[
|
||||
"apps/web/app/routes/app.$tenant/hr/password-safe._index.tsx",
|
||||
"apps/web/app/routes/app.$tenant/hr/password-safe.$vaultId._index.tsx",
|
||||
"apps/web/app/routes/app.$tenant/hr/admin.password-safe._index.tsx",
|
||||
].forEach((legacyRouteFile) => expect(existsSync(resolveRepoPath(legacyRouteFile)), legacyRouteFile).toBe(true));
|
||||
});
|
||||
});
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Canonical tenant-scoped password-safe routes.
|
||||
*
|
||||
* The safe is an organisation capability, not a personal/HR screen. Keep the
|
||||
* permission and service names stable for now, but do not route it below `/hr`.
|
||||
*/
|
||||
export function passwordSafePath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/passwords`;
|
||||
}
|
||||
|
||||
export function passwordSafeVaultPath(tenantSlug: string, vaultId: string): string {
|
||||
return `/${tenantSlug}/passwords/${vaultId}`;
|
||||
}
|
||||
|
||||
export function passwordSafeRevealPath(tenantSlug: string, vaultId: string): string {
|
||||
return `/${tenantSlug}/passwords/${vaultId}/reveal`;
|
||||
}
|
||||
|
||||
export function passwordSafeExportPath(tenantSlug: string, vaultId: string): string {
|
||||
return `/${tenantSlug}/passwords/${vaultId}/export`;
|
||||
}
|
||||
|
||||
export function passwordSafeAdminPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/passwords/admin`;
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
withTenantRLS: vi.fn(),
|
||||
acceptanceUpsert: vi.fn(),
|
||||
projectUpsert: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({ withTenantRLS: mocks.withTenantRLS }));
|
||||
vi.mock("@hivegrid/activity", () => ({ logActivity: vi.fn() }));
|
||||
|
||||
import {
|
||||
ensureDefaultAcceptanceFormTemplate,
|
||||
ensureDefaultAcceptanceFormTemplateWithTx,
|
||||
ensureDefaultProjectTemplate,
|
||||
ensureDefaultProjectTemplateWithTx,
|
||||
} from "./auftragService.server";
|
||||
|
||||
const tx = {
|
||||
acceptanceFormTemplate: { upsert: mocks.acceptanceUpsert },
|
||||
projectTemplate: { upsert: mocks.projectUpsert },
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.acceptanceUpsert.mockResolvedValue({ id: "acceptance-default" });
|
||||
mocks.projectUpsert.mockResolvedValue({ id: "project-default" });
|
||||
mocks.withTenantRLS.mockImplementation(async (_tenantId, callback) => callback(tx));
|
||||
});
|
||||
|
||||
describe("order defaults transaction boundary", () => {
|
||||
it("uses a caller-provided transaction and preserves the acceptance defaults", async () => {
|
||||
await expect(ensureDefaultAcceptanceFormTemplateWithTx(tx as never, "tenant-atomic-bootstrap")).resolves.toEqual({
|
||||
id: "acceptance-default",
|
||||
});
|
||||
|
||||
expect(mocks.withTenantRLS).not.toHaveBeenCalled();
|
||||
expect(mocks.acceptanceUpsert).toHaveBeenCalledWith({
|
||||
where: { tenantId_name: { tenantId: "tenant-atomic-bootstrap", name: "SHK Standard-Abnahme" } },
|
||||
update: { archivedAt: null, isDefault: true, isDemoData: false },
|
||||
create: {
|
||||
tenantId: "tenant-atomic-bootstrap",
|
||||
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: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("uses a caller-provided transaction and preserves the project defaults", async () => {
|
||||
await expect(ensureDefaultProjectTemplateWithTx(tx as never, "tenant-atomic-bootstrap")).resolves.toEqual({
|
||||
id: "project-default",
|
||||
});
|
||||
|
||||
expect(mocks.withTenantRLS).not.toHaveBeenCalled();
|
||||
expect(mocks.projectUpsert).toHaveBeenCalledWith({
|
||||
where: { tenantId_name: { tenantId: "tenant-atomic-bootstrap", name: "SHK Standard-Projekt" } },
|
||||
update: { archivedAt: null, isDemoData: false },
|
||||
create: {
|
||||
tenantId: "tenant-atomic-bootstrap",
|
||||
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: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the existing wrappers and binds one RLS transaction per call", async () => {
|
||||
await ensureDefaultAcceptanceFormTemplate({ tenantId: "tenant-wrapper" });
|
||||
await ensureDefaultProjectTemplate({ tenantId: "tenant-wrapper" });
|
||||
|
||||
expect(mocks.withTenantRLS).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.withTenantRLS).toHaveBeenNthCalledWith(1, "tenant-wrapper", expect.any(Function));
|
||||
expect(mocks.withTenantRLS).toHaveBeenNthCalledWith(2, "tenant-wrapper", expect.any(Function));
|
||||
});
|
||||
});
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tx: {
|
||||
projekt: { findFirst: vi.fn() },
|
||||
projektMitglied: { findFirst: vi.fn() },
|
||||
fileEntityLink: { findMany: vi.fn() },
|
||||
file: { findFirst: vi.fn() },
|
||||
projektChecklist: { findFirst: vi.fn() },
|
||||
projektChecklistItem: { findFirst: vi.fn(), create: vi.fn(), update: vi.fn() },
|
||||
acceptanceFormTemplate: { findFirst: vi.fn(), update: vi.fn() },
|
||||
tenantUser: { findFirst: vi.fn() },
|
||||
rechnung: { create: vi.fn() },
|
||||
hiveNumberSeq: { update: vi.fn() },
|
||||
$executeRaw: vi.fn(),
|
||||
$queryRaw: vi.fn(),
|
||||
},
|
||||
logActivity: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: async (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/activity", () => ({ logActivity: mocks.logActivity }));
|
||||
|
||||
import { createProjectInvoice, upsertAcceptanceFormTemplate, upsertProjectChecklistItem, type AuftragVisibilityContext } from "./auftragService.server";
|
||||
|
||||
const TENANT_ID = "tenant-a";
|
||||
const PROJECT_ID = "project-a";
|
||||
|
||||
function context(extraPermissions: readonly string[] = []): AuftragVisibilityContext {
|
||||
return {
|
||||
userId: "actor-a",
|
||||
permissions: ["projects.read_all", ...extraPermissions],
|
||||
roleIds: ["role-a"],
|
||||
groupIds: ["group-a"],
|
||||
};
|
||||
}
|
||||
|
||||
describe("order file-reference authorization", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.tx.projekt.findFirst.mockResolvedValue({
|
||||
id: PROJECT_ID,
|
||||
tenantId: TENANT_ID,
|
||||
projektleiterId: null,
|
||||
zustaendigePersonId: null,
|
||||
});
|
||||
mocks.tx.fileEntityLink.findMany.mockResolvedValue([]);
|
||||
mocks.tx.projektChecklist.findFirst.mockResolvedValue({ id: "checklist-a", tenantId: TENANT_ID, projektId: PROJECT_ID });
|
||||
mocks.tx.projektChecklistItem.create.mockResolvedValue({ id: "item-a", tenantId: TENANT_ID, checklistId: "checklist-a" });
|
||||
});
|
||||
|
||||
it("rejects an invoice file id when the actor has no Files read permission", async () => {
|
||||
mocks.tx.file.findFirst.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
createProjectInvoice({
|
||||
tenantId: TENANT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
ctx: context(),
|
||||
createdByUserId: "actor-a",
|
||||
betrag: "1250.00",
|
||||
dateiId: "guessed-file",
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.file.findFirst).toHaveBeenCalledWith({
|
||||
where: { id: { in: [] }, tenantId: TENANT_ID, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.tx.$executeRaw).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.rechnung.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps invoice file lookup tenant-scoped for a tenant-wide Files reader", async () => {
|
||||
mocks.tx.file.findFirst.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
createProjectInvoice({
|
||||
tenantId: TENANT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
ctx: context(["files.read_all"]),
|
||||
createdByUserId: "actor-a",
|
||||
betrag: "1250.00",
|
||||
dateiId: "file-from-tenant-b",
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.file.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: "file-from-tenant-b",
|
||||
tenantId: TENANT_ID,
|
||||
archivedAt: null,
|
||||
links: { none: { tenantId: TENANT_ID, entityType: "user", entityId: { not: "actor-a" } } },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.tx.rechnung.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects a checklist photo id outside the actor's authoritative Files scope", async () => {
|
||||
mocks.tx.file.findFirst.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
upsertProjectChecklistItem({
|
||||
tenantId: TENANT_ID,
|
||||
checklistId: "checklist-a",
|
||||
ctx: context(),
|
||||
titel: "Photo evidence",
|
||||
fotoFileId: "guessed-photo",
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.file.findFirst).toHaveBeenCalledWith({
|
||||
where: { id: { in: [] }, tenantId: TENANT_ID, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.tx.projektChecklistItem.create).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.projektChecklistItem.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("accepts a checklist photo only through the current actor's own-file scope", async () => {
|
||||
mocks.tx.file.findFirst.mockResolvedValueOnce({ id: "own-photo" });
|
||||
|
||||
await upsertProjectChecklistItem({
|
||||
tenantId: TENANT_ID,
|
||||
checklistId: "checklist-a",
|
||||
ctx: context(["files.read_own"]),
|
||||
titel: "Own photo evidence",
|
||||
fotoFileId: "own-photo",
|
||||
});
|
||||
|
||||
expect(mocks.tx.file.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: "own-photo",
|
||||
tenantId: TENANT_ID,
|
||||
archivedAt: null,
|
||||
AND: [
|
||||
{
|
||||
OR: [
|
||||
{ createdByUserId: "actor-a" },
|
||||
{ assignedToUserId: "actor-a" },
|
||||
{ links: { some: { tenantId: TENANT_ID, entityType: "user", entityId: "actor-a" } } },
|
||||
],
|
||||
},
|
||||
{ links: { none: { tenantId: TENANT_ID, entityType: "user", entityId: { not: "actor-a" } } } },
|
||||
],
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.tx.projektChecklistItem.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
tenantId: TENANT_ID,
|
||||
checklistId: "checklist-a",
|
||||
fotoFileId: "own-photo",
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects an acceptance template id outside the current tenant before updating", async () => {
|
||||
mocks.tx.acceptanceFormTemplate.findFirst.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
upsertAcceptanceFormTemplate({
|
||||
tenantId: TENANT_ID,
|
||||
templateId: "template-from-tenant-b",
|
||||
name: "Hidden template",
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.acceptanceFormTemplate.findFirst).toHaveBeenCalledWith({
|
||||
where: { id: "template-from-tenant-b", tenantId: TENANT_ID, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.tx.acceptanceFormTemplate.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
withTenantRLS: vi.fn(),
|
||||
invoiceFindFirst: vi.fn(),
|
||||
invoiceUpdate: vi.fn(),
|
||||
requireAccess: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({ withTenantRLS: mocks.withTenantRLS }));
|
||||
vi.mock("@hivegrid/activity", () => ({ logActivity: vi.fn() }));
|
||||
|
||||
import { updateProjectInvoiceStatus } from "./auftragService.server";
|
||||
|
||||
const tx = {
|
||||
rechnung: { findFirst: mocks.invoiceFindFirst, update: mocks.invoiceUpdate },
|
||||
projekt: { findFirst: mocks.requireAccess },
|
||||
projektMitglied: { findFirst: vi.fn().mockResolvedValue(null) },
|
||||
};
|
||||
|
||||
const ctx = { tenantId: "tenant-1", userId: "user-1", permissions: ["projects.read_all", "projects.write", "projects.admin"] };
|
||||
|
||||
function invoice(overrides: Record<string, unknown> = {}) {
|
||||
return { id: "invoice-1", tenantId: "tenant-1", projektId: "project-1", status: "gestellt", bezahltAm: null, ...overrides };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.withTenantRLS.mockImplementation(async (_tenantId: string, callback: (client: unknown) => unknown) => callback(tx));
|
||||
mocks.requireAccess.mockResolvedValue({ id: "project-1", tenantId: "tenant-1", archivedAt: null });
|
||||
mocks.invoiceUpdate.mockImplementation(async ({ data }: { data: Record<string, unknown> }) => ({ ...invoice(), ...data }));
|
||||
});
|
||||
|
||||
describe("invoice payment date", () => {
|
||||
it("stamps the payment date when an invoice is marked paid", async () => {
|
||||
mocks.invoiceFindFirst.mockResolvedValue(invoice());
|
||||
|
||||
const before = Date.now();
|
||||
const row = await updateProjectInvoiceStatus({
|
||||
tenantId: "tenant-1",
|
||||
invoiceId: "invoice-1",
|
||||
ctx: ctx as never,
|
||||
userId: "user-1",
|
||||
status: "bezahlt",
|
||||
});
|
||||
|
||||
const stamped = mocks.invoiceUpdate.mock.calls[0]![0].data.bezahltAm as Date;
|
||||
expect(stamped).toBeInstanceOf(Date);
|
||||
expect(stamped.getTime()).toBeGreaterThanOrEqual(before);
|
||||
expect(row.bezahltAm).toBe(stamped);
|
||||
});
|
||||
|
||||
it("keeps the original payment date when a paid invoice is saved as paid again", async () => {
|
||||
const paidAt = new Date("2026-07-01T10:00:00.000Z");
|
||||
mocks.invoiceFindFirst.mockResolvedValue(invoice({ status: "bezahlt", bezahltAm: paidAt }));
|
||||
|
||||
await updateProjectInvoiceStatus({
|
||||
tenantId: "tenant-1",
|
||||
invoiceId: "invoice-1",
|
||||
ctx: ctx as never,
|
||||
userId: "user-1",
|
||||
status: "bezahlt",
|
||||
});
|
||||
|
||||
expect(mocks.invoiceUpdate.mock.calls[0]![0].data.bezahltAm).toBe(paidAt);
|
||||
});
|
||||
|
||||
it("clears the payment date when a paid invoice moves back to unpaid", async () => {
|
||||
mocks.invoiceFindFirst.mockResolvedValue(invoice({ status: "bezahlt", bezahltAm: new Date("2026-07-01T10:00:00.000Z") }));
|
||||
|
||||
for (const status of ["gestellt", "storniert", "entwurf"] as const) {
|
||||
mocks.invoiceUpdate.mockClear();
|
||||
await updateProjectInvoiceStatus({
|
||||
tenantId: "tenant-1",
|
||||
invoiceId: "invoice-1",
|
||||
ctx: ctx as never,
|
||||
userId: "user-1",
|
||||
status,
|
||||
});
|
||||
expect(mocks.invoiceUpdate.mock.calls[0]![0].data).toEqual({ status, bezahltAm: null });
|
||||
}
|
||||
});
|
||||
});
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tx: {
|
||||
projekt: { findFirst: vi.fn() },
|
||||
projektMitglied: { findMany: vi.fn() },
|
||||
projektTermin: { findMany: vi.fn() },
|
||||
rechnung: { findMany: vi.fn() },
|
||||
projektChecklist: { findMany: vi.fn() },
|
||||
auftragPipelineStageConfig: { findFirst: vi.fn() },
|
||||
acceptanceFormTemplate: { upsert: vi.fn(), findMany: vi.fn() },
|
||||
projectTemplate: { upsert: vi.fn(), findMany: vi.fn() },
|
||||
projektChecklistItem: { count: vi.fn() },
|
||||
task: { findMany: vi.fn() },
|
||||
fileEntityLink: { findMany: vi.fn() },
|
||||
group: { findMany: vi.fn() },
|
||||
kwpMaterialPosition: { findMany: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: async (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
|
||||
}));
|
||||
|
||||
import { loadProjectSubAreas } from "./auftragService.server";
|
||||
|
||||
describe("KWP material project sub-area", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.tx.projekt.findFirst.mockResolvedValue({
|
||||
id: "project-1",
|
||||
tenantId: "tenant-1",
|
||||
projektleiterId: null,
|
||||
zustaendigePersonId: null,
|
||||
stageId: "stage-1",
|
||||
});
|
||||
mocks.tx.acceptanceFormTemplate.upsert.mockResolvedValue({ id: "acceptance-default" });
|
||||
mocks.tx.projectTemplate.upsert.mockResolvedValue({ id: "project-default" });
|
||||
mocks.tx.projektMitglied.findMany.mockResolvedValue([]);
|
||||
mocks.tx.projektTermin.findMany.mockResolvedValue([]);
|
||||
mocks.tx.rechnung.findMany.mockResolvedValue([]);
|
||||
mocks.tx.projektChecklist.findMany.mockResolvedValue([]);
|
||||
mocks.tx.auftragPipelineStageConfig.findFirst.mockResolvedValue(null);
|
||||
mocks.tx.acceptanceFormTemplate.findMany.mockResolvedValue([]);
|
||||
mocks.tx.projectTemplate.findMany.mockResolvedValue([]);
|
||||
mocks.tx.projektChecklistItem.count.mockResolvedValue(0);
|
||||
mocks.tx.task.findMany.mockResolvedValue([]);
|
||||
mocks.tx.fileEntityLink.findMany.mockResolvedValue([]);
|
||||
mocks.tx.group.findMany.mockResolvedValue([]);
|
||||
mocks.tx.kwpMaterialPosition.findMany.mockResolvedValue([
|
||||
{
|
||||
id: "material-1",
|
||||
positionNumber: "01.01",
|
||||
text: "Ventil",
|
||||
longText: "DN 20",
|
||||
quantity: "2",
|
||||
unit: "Stk",
|
||||
unitPrice: "12.50",
|
||||
totalPrice: "25.00",
|
||||
lastSyncedAt: new Date("2026-07-24T10:00:00.000Z"),
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("loads only active material positions from the bound tenant and project", async () => {
|
||||
const result = await loadProjectSubAreas({
|
||||
tenantId: "tenant-1",
|
||||
projectId: "project-1",
|
||||
ctx: {
|
||||
userId: "user-1",
|
||||
permissions: ["projects.read_all"],
|
||||
roleIds: [],
|
||||
groupIds: [],
|
||||
},
|
||||
});
|
||||
|
||||
expect(mocks.tx.kwpMaterialPosition.findMany).toHaveBeenCalledWith({
|
||||
where: { tenantId: "tenant-1", projektId: "project-1", archivedAt: null },
|
||||
select: {
|
||||
id: true,
|
||||
positionNumber: true,
|
||||
text: true,
|
||||
longText: true,
|
||||
quantity: true,
|
||||
unit: true,
|
||||
unitPrice: true,
|
||||
totalPrice: true,
|
||||
lastSyncedAt: true,
|
||||
},
|
||||
orderBy: [{ positionNumber: "asc" }, { externalId: "asc" }],
|
||||
take: 500,
|
||||
});
|
||||
expect(result.materials).toEqual([expect.objectContaining({ id: "material-1", text: "Ventil", totalPrice: "25.00" })]);
|
||||
});
|
||||
});
|
||||
+374
-67
@@ -1,8 +1,18 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
import { archiveProjectChannelIfEnabledWithTx, ensureAndSyncProjectChannelIfEnabledWithTx } from "@hivegrid/chat/project-sync.server";
|
||||
import { autoArchiveProjectsForTenantWithTx } from "@hivegrid/db/project-auto-archive.server";
|
||||
import { lockPermissionGroupsWithTx } from "@hivegrid/chat/sync-locks.server";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
import type { ProjektRow } from "./projectService.server";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
import { fileReadScopeWhereWithTx } from "../fileVisibility.server";
|
||||
import {
|
||||
projectEditScopeWhere,
|
||||
projectReadScopeWhere,
|
||||
type ProjectVisibilityContext,
|
||||
type ProjektRow,
|
||||
} from "./projectService.server";
|
||||
|
||||
export class AuftragServiceError extends Error {
|
||||
readonly messageKey: string;
|
||||
@@ -15,15 +25,14 @@ export class AuftragServiceError extends Error {
|
||||
|
||||
export type ProjektMitgliedRolle = "monteur" | "projektleiter" | "zustaendig" | "beobachter";
|
||||
export type ProjektTerminStatus = "geplant" | "bestaetigt" | "erledigt" | "abgesagt";
|
||||
/** WF-P8 S02-T appointment kind. */
|
||||
export type ProjektTerminTyp = "vor_ort" | "telefon" | "online";
|
||||
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 AuftragVisibilityContext = ProjectVisibilityContext;
|
||||
|
||||
export type ProjektMitgliedRow = {
|
||||
id: string;
|
||||
@@ -50,6 +59,7 @@ export type ProjektTerminRow = {
|
||||
startAt: Date;
|
||||
endAt: Date | null;
|
||||
status: ProjektTerminStatus;
|
||||
typ: ProjektTerminTyp;
|
||||
isDemoData: boolean;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
@@ -66,6 +76,8 @@ export type RechnungRow = {
|
||||
status: RechnungStatus;
|
||||
datum: Date;
|
||||
faelligAm: Date | null;
|
||||
/** Null for invoices marked paid before the field existed — never treat null as "today". */
|
||||
bezahltAm: Date | null;
|
||||
dateiId: string | null;
|
||||
quelle: RechnungQuelle;
|
||||
isDemoData: boolean;
|
||||
@@ -143,12 +155,47 @@ export type ProjectTemplateRow = {
|
||||
archivedAt: Date | null;
|
||||
};
|
||||
|
||||
export type ProjectSubAreaTaskRow = {
|
||||
id: string;
|
||||
title: string;
|
||||
status: string;
|
||||
priority: string;
|
||||
deadline: Date | null;
|
||||
assignedToUserId: string | null;
|
||||
assignedToGroupId: string | null;
|
||||
};
|
||||
|
||||
export type ProjectSubAreaDocumentRow = {
|
||||
id: string;
|
||||
displayName: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
linkRole: string | null;
|
||||
createdAt: Date;
|
||||
};
|
||||
|
||||
export type ProjectSubAreaMaterialRow = {
|
||||
id: string;
|
||||
positionNumber: string | null;
|
||||
text: string;
|
||||
longText: string | null;
|
||||
quantity: unknown;
|
||||
unit: string | null;
|
||||
unitPrice: unknown;
|
||||
totalPrice: unknown;
|
||||
lastSyncedAt: Date;
|
||||
};
|
||||
|
||||
export type ProjectSubAreasVM = {
|
||||
project: ProjektRow;
|
||||
members: ProjektMitgliedRow[];
|
||||
appointments: ProjektTerminRow[];
|
||||
invoices: RechnungRow[];
|
||||
checklists: ProjektChecklistRow[];
|
||||
tasks: ProjectSubAreaTaskRow[];
|
||||
documents: ProjectSubAreaDocumentRow[];
|
||||
materials: ProjectSubAreaMaterialRow[];
|
||||
groupOptions: { id: string; name: string }[];
|
||||
stageConfig: AuftragPipelineStageConfigRow | null;
|
||||
acceptanceTemplates: AcceptanceFormTemplateRow[];
|
||||
projectTemplates: ProjectTemplateRow[];
|
||||
@@ -185,20 +232,41 @@ function hasPermission(ctx: AuftragVisibilityContext | undefined, permission: st
|
||||
return ctx?.permissions.includes(permission) ?? false;
|
||||
}
|
||||
|
||||
async function canReadProjectSubAreasWithTx(tx: TenantRlsClient, input: { tenantId: string; project: ProjektRow; ctx: AuftragVisibilityContext }): Promise<boolean> {
|
||||
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 },
|
||||
where: {
|
||||
tenantId: input.tenantId,
|
||||
projektId: input.project.id,
|
||||
archivedAt: null,
|
||||
OR: [
|
||||
{ userId: input.ctx.userId },
|
||||
...((input.ctx.groupIds?.length ?? 0) > 0 ? [{ groupId: { in: [...(input.ctx.groupIds ?? [])] } }] : []),
|
||||
],
|
||||
},
|
||||
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 } });
|
||||
async function requireProjectSubAreaAccessWithTx(
|
||||
tx: TenantRlsClient,
|
||||
input: { tenantId: string; projectId: string; ctx: AuftragVisibilityContext; editable: boolean }
|
||||
): Promise<ProjektRow> {
|
||||
const project = await tx.projekt.findFirst({
|
||||
where: {
|
||||
id: input.projectId,
|
||||
tenantId: input.tenantId,
|
||||
archivedAt: null,
|
||||
...(input.editable ? projectEditScopeWhere(input.tenantId, input.ctx) : projectReadScopeWhere(input.tenantId, input.ctx)),
|
||||
},
|
||||
});
|
||||
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 });
|
||||
@@ -206,6 +274,13 @@ async function requireProjectSubAreaReadWithTx(tx: TenantRlsClient, input: { ten
|
||||
return project as ProjektRow;
|
||||
}
|
||||
|
||||
async function requireProjectSubAreaReadWithTx(
|
||||
tx: TenantRlsClient,
|
||||
input: { tenantId: string; projectId: string; ctx: AuftragVisibilityContext }
|
||||
): Promise<ProjektRow> {
|
||||
return requireProjectSubAreaAccessWithTx(tx, { ...input, editable: false });
|
||||
}
|
||||
|
||||
function requireExactlyOnePrincipal(userId?: string | null, groupId?: string | null): void {
|
||||
const hasUser = Boolean(normalizeText(userId));
|
||||
const hasGroup = Boolean(normalizeText(groupId));
|
||||
@@ -216,10 +291,37 @@ function invoiceNumber(prefix: string, nextNumber: number, padding: number): str
|
||||
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 assertTenantUserWithTx(tx: TenantRlsClient, tenantId: string, userId?: string | null): Promise<void> {
|
||||
const normalized = normalizeText(userId);
|
||||
if (!normalized) return;
|
||||
const membership = await tx.tenantUser.findFirst({
|
||||
where: { tenantId, userId: normalized, status: TenantUserStatus.ACTIVE, user: { active: true } },
|
||||
select: { userId: true },
|
||||
});
|
||||
if (!membership) throw new CatalogError(foundationErrors.notFound, { userId: normalized });
|
||||
}
|
||||
|
||||
async function assertTenantGroupWithTx(tx: TenantRlsClient, tenantId: string, groupId?: string | null): Promise<void> {
|
||||
const normalized = normalizeText(groupId);
|
||||
if (!normalized) return;
|
||||
const group = await tx.group.findFirst({ where: { id: normalized, tenantId }, select: { id: true } });
|
||||
if (!group) throw new CatalogError(foundationErrors.notFound, { groupId: normalized });
|
||||
}
|
||||
|
||||
async function assertVisibleTenantFileWithTx(
|
||||
tx: TenantRlsClient,
|
||||
tenantId: string,
|
||||
fileId: string | null | undefined,
|
||||
ctx: AuftragVisibilityContext,
|
||||
): Promise<void> {
|
||||
const normalized = normalizeText(fileId);
|
||||
if (!normalized) return;
|
||||
const visibility = await fileReadScopeWhereWithTx(tx, tenantId, ctx, [normalized]);
|
||||
const file = await tx.file.findFirst({
|
||||
where: { id: normalized, tenantId, archivedAt: null, ...visibility },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!file) throw new CatalogError(foundationErrors.notFound, { fileId: normalized });
|
||||
}
|
||||
|
||||
async function reserveInvoiceNumberWithTx(tx: TenantRlsClient, tenantId: string): Promise<string> {
|
||||
@@ -252,10 +354,10 @@ export async function ensureDefaultProjectTemplate(input: { tenantId: string }):
|
||||
return withTenantRLS(input.tenantId, (tx) => ensureDefaultProjectTemplateWithTx(tx, input.tenantId));
|
||||
}
|
||||
|
||||
async function ensureDefaultAcceptanceFormTemplateWithTx(tx: TenantRlsClient, tenantId: string): Promise<AcceptanceFormTemplateRow> {
|
||||
export 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 },
|
||||
update: { archivedAt: null, isDefault: true, isDemoData: false },
|
||||
create: {
|
||||
tenantId,
|
||||
name: "SHK Standard-Abnahme",
|
||||
@@ -267,16 +369,16 @@ async function ensureDefaultAcceptanceFormTemplateWithTx(tx: TenantRlsClient, te
|
||||
],
|
||||
},
|
||||
isDefault: true,
|
||||
isDemoData: true,
|
||||
isDemoData: false,
|
||||
},
|
||||
});
|
||||
return row as AcceptanceFormTemplateRow;
|
||||
}
|
||||
|
||||
async function ensureDefaultProjectTemplateWithTx(tx: TenantRlsClient, tenantId: string): Promise<ProjectTemplateRow> {
|
||||
export 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 },
|
||||
update: { archivedAt: null, isDemoData: false },
|
||||
create: {
|
||||
tenantId,
|
||||
name: "SHK Standard-Projekt",
|
||||
@@ -287,7 +389,7 @@ async function ensureDefaultProjectTemplateWithTx(tx: TenantRlsClient, tenantId:
|
||||
{ titleKey: "projects.defaults.tasks.prepareAcceptance", priority: "high" },
|
||||
],
|
||||
customFields: {},
|
||||
isDemoData: true,
|
||||
isDemoData: false,
|
||||
},
|
||||
});
|
||||
return row as ProjectTemplateRow;
|
||||
@@ -317,12 +419,72 @@ export async function loadProjectSubAreas(input: { tenantId: string; projectId:
|
||||
},
|
||||
}),
|
||||
]);
|
||||
// R-P9a DoD 2 — tasks + documents sub-areas. Tasks are the tasks-module
|
||||
// rows linked to this project; documents are the files linked through
|
||||
// FileEntityLink, filtered by file visibility.
|
||||
const [tasks, fileLinks, groups, materials] = await Promise.all([
|
||||
tx.task.findMany({
|
||||
where: { tenantId: input.tenantId, linkedEntityType: "project", linkedEntityId: input.projectId, archivedAt: null },
|
||||
select: { id: true, title: true, status: true, priority: true, deadline: true, assignedToUserId: true, assignedToGroupId: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 100,
|
||||
}),
|
||||
tx.fileEntityLink.findMany({
|
||||
where: { tenantId: input.tenantId, entityType: "project", entityId: input.projectId },
|
||||
select: { fileId: true, linkRole: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 200,
|
||||
}),
|
||||
tx.group.findMany({ where: { tenantId: input.tenantId }, select: { id: true, name: true }, orderBy: { name: "asc" } }),
|
||||
tx.kwpMaterialPosition.findMany({
|
||||
where: { tenantId: input.tenantId, projektId: input.projectId, archivedAt: null },
|
||||
select: {
|
||||
id: true,
|
||||
positionNumber: true,
|
||||
text: true,
|
||||
longText: true,
|
||||
quantity: true,
|
||||
unit: true,
|
||||
unitPrice: true,
|
||||
totalPrice: true,
|
||||
lastSyncedAt: true,
|
||||
},
|
||||
orderBy: [{ positionNumber: "asc" }, { externalId: "asc" }],
|
||||
take: 500,
|
||||
}),
|
||||
]);
|
||||
let documents: ProjectSubAreaDocumentRow[] = [];
|
||||
if (fileLinks.length > 0) {
|
||||
const visibility = await fileReadScopeWhereWithTx(
|
||||
tx,
|
||||
input.tenantId,
|
||||
input.ctx,
|
||||
fileLinks.map((link) => link.fileId)
|
||||
);
|
||||
const files = await tx.file.findMany({
|
||||
where: { id: { in: fileLinks.map((link) => link.fileId) }, tenantId: input.tenantId, archivedAt: null, ...visibility },
|
||||
select: { id: true, displayName: true, mimeType: true, sizeBytes: true, createdAt: true },
|
||||
});
|
||||
const linkRoleByFileId = new Map(fileLinks.map((link) => [link.fileId, link.linkRole]));
|
||||
documents = files.map((file) => ({
|
||||
id: file.id,
|
||||
displayName: file.displayName,
|
||||
mimeType: file.mimeType,
|
||||
sizeBytes: file.sizeBytes,
|
||||
linkRole: linkRoleByFileId.get(file.id) ?? null,
|
||||
createdAt: file.createdAt,
|
||||
}));
|
||||
}
|
||||
return {
|
||||
project,
|
||||
members: members as ProjektMitgliedRow[],
|
||||
appointments: appointments as ProjektTerminRow[],
|
||||
invoices: invoices as RechnungRow[],
|
||||
checklists: checklists as ProjektChecklistRow[],
|
||||
tasks: tasks as ProjectSubAreaTaskRow[],
|
||||
documents,
|
||||
materials: materials as ProjectSubAreaMaterialRow[],
|
||||
groupOptions: groups,
|
||||
stageConfig: stageConfig as AuftragPipelineStageConfigRow | null,
|
||||
acceptanceTemplates: acceptanceTemplates as AcceptanceFormTemplateRow[],
|
||||
projectTemplates: projectTemplates as ProjectTemplateRow[],
|
||||
@@ -334,6 +496,7 @@ export async function loadProjectSubAreas(input: { tenantId: string; projectId:
|
||||
export async function addProjectMember(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
ctx: AuftragVisibilityContext;
|
||||
createdByUserId: string | null;
|
||||
userId?: string | null;
|
||||
groupId?: string | null;
|
||||
@@ -341,14 +504,20 @@ export async function addProjectMember(input: {
|
||||
}): Promise<ProjektMitgliedRow> {
|
||||
requireExactlyOnePrincipal(input.userId, input.groupId);
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
await requireProjectWithTx(tx, input);
|
||||
await requireProjectSubAreaAccessWithTx(tx, { ...input, editable: true });
|
||||
const normalizedGroupId = normalizeText(input.groupId);
|
||||
await lockPermissionGroupsWithTx(tx, input.tenantId, normalizedGroupId ? [normalizedGroupId] : []);
|
||||
await Promise.all([
|
||||
assertTenantUserWithTx(tx, input.tenantId, input.userId),
|
||||
assertTenantGroupWithTx(tx, input.tenantId, normalizedGroupId),
|
||||
]);
|
||||
const row = await tx.projektMitglied.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
projektId: input.projectId,
|
||||
createdByUserId: input.createdByUserId,
|
||||
userId: normalizeText(input.userId),
|
||||
groupId: normalizeText(input.groupId),
|
||||
groupId: normalizedGroupId,
|
||||
rolle: input.rolle,
|
||||
},
|
||||
});
|
||||
@@ -360,18 +529,73 @@ export async function addProjectMember(input: {
|
||||
activityType: "project_member_added",
|
||||
subjectType: "project",
|
||||
subjectId: input.projectId,
|
||||
summaryText: "Projektmitglied wurde hinzugefügt.",
|
||||
summaryText: "activity.runtime.projects.memberAdded",
|
||||
metadata: { userId: input.userId ?? null, groupId: input.groupId ?? null, rolle: input.rolle },
|
||||
},
|
||||
{ client: tx },
|
||||
{ client: tx }
|
||||
);
|
||||
await ensureAndSyncProjectChannelIfEnabledWithTx(tx, {
|
||||
tenantId: input.tenantId,
|
||||
projectId: input.projectId,
|
||||
actorUserId: input.createdByUserId,
|
||||
requestId: `project:${input.projectId}:member:${row.id}:chat-add`,
|
||||
});
|
||||
return row as ProjektMitgliedRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeProjectMember(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
memberId: string;
|
||||
ctx: AuftragVisibilityContext;
|
||||
removedByUserId: string | null;
|
||||
}): Promise<{ id: string }> {
|
||||
const memberId = normalizeText(input.memberId);
|
||||
if (!memberId) throw new CatalogError(foundationErrors.notFound, { memberId: input.memberId });
|
||||
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
await requireProjectSubAreaAccessWithTx(tx, { ...input, editable: true });
|
||||
const member = await tx.projektMitglied.findFirst({
|
||||
where: { id: memberId, tenantId: input.tenantId, projektId: input.projectId, archivedAt: null },
|
||||
select: { id: true, userId: true, groupId: true, rolle: true },
|
||||
});
|
||||
if (!member) throw new CatalogError(foundationErrors.notFound, { memberId });
|
||||
|
||||
const archivedAt = new Date();
|
||||
const archived = await tx.projektMitglied.updateMany({
|
||||
where: { id: member.id, tenantId: input.tenantId, projektId: input.projectId, archivedAt: null },
|
||||
data: { archivedAt },
|
||||
});
|
||||
if (archived.count !== 1) throw new CatalogError(foundationErrors.notFound, { memberId });
|
||||
|
||||
await logActivity(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.removedByUserId,
|
||||
actorKind: input.removedByUserId ? "user" : "system",
|
||||
activityType: "project_member_removed",
|
||||
subjectType: "project",
|
||||
subjectId: input.projectId,
|
||||
summaryText: "activity.runtime.projects.memberRemoved",
|
||||
metadata: { memberId: member.id, userId: member.userId, groupId: member.groupId, rolle: member.rolle },
|
||||
},
|
||||
{ client: tx }
|
||||
);
|
||||
await ensureAndSyncProjectChannelIfEnabledWithTx(tx, {
|
||||
tenantId: input.tenantId,
|
||||
projectId: input.projectId,
|
||||
actorUserId: input.removedByUserId,
|
||||
requestId: `project:${input.projectId}:member:${member.id}:chat-remove`,
|
||||
});
|
||||
return { id: member.id };
|
||||
});
|
||||
}
|
||||
|
||||
export async function createProjectAppointment(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
ctx: AuftragVisibilityContext;
|
||||
createdByUserId: string | null;
|
||||
titel: string;
|
||||
beschreibung?: string | null;
|
||||
@@ -379,13 +603,18 @@ export async function createProjectAppointment(input: {
|
||||
endAt?: string | Date | null;
|
||||
assignedToUserId?: string | null;
|
||||
assignedToGroupId?: string | null;
|
||||
typ?: ProjektTerminTyp;
|
||||
}): 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);
|
||||
await requireProjectSubAreaAccessWithTx(tx, { ...input, editable: true });
|
||||
await Promise.all([
|
||||
assertTenantUserWithTx(tx, input.tenantId, input.assignedToUserId),
|
||||
assertTenantGroupWithTx(tx, input.tenantId, input.assignedToGroupId),
|
||||
]);
|
||||
const row = await tx.projektTermin.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
@@ -397,6 +626,7 @@ export async function createProjectAppointment(input: {
|
||||
beschreibung: normalizeText(input.beschreibung),
|
||||
startAt,
|
||||
endAt: parseDate(input.endAt),
|
||||
...(input.typ ? { typ: input.typ } : {}),
|
||||
},
|
||||
});
|
||||
await logActivity(
|
||||
@@ -407,10 +637,10 @@ export async function createProjectAppointment(input: {
|
||||
activityType: "project_appointment_created",
|
||||
subjectType: "project",
|
||||
subjectId: input.projectId,
|
||||
summaryText: "Projekttermin wurde angelegt.",
|
||||
summaryText: "activity.runtime.projects.appointmentCreated",
|
||||
metadata: { appointmentId: row.id, startAt: row.startAt.toISOString() },
|
||||
},
|
||||
{ client: tx },
|
||||
{ client: tx }
|
||||
);
|
||||
return row as ProjektTerminRow;
|
||||
});
|
||||
@@ -419,6 +649,7 @@ export async function createProjectAppointment(input: {
|
||||
export async function createProjectInvoice(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
ctx: AuftragVisibilityContext;
|
||||
createdByUserId: string | null;
|
||||
betrag: string | number;
|
||||
datum?: string | Date | null;
|
||||
@@ -427,7 +658,8 @@ export async function createProjectInvoice(input: {
|
||||
quelle?: RechnungQuelle;
|
||||
}): Promise<RechnungRow> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
await requireProjectWithTx(tx, input);
|
||||
await requireProjectSubAreaAccessWithTx(tx, { ...input, editable: true });
|
||||
await assertVisibleTenantFileWithTx(tx, input.tenantId, input.dateiId, input.ctx);
|
||||
const rechnungsnummer = await reserveInvoiceNumberWithTx(tx, input.tenantId);
|
||||
const row = await tx.rechnung.create({
|
||||
data: {
|
||||
@@ -450,20 +682,39 @@ export async function createProjectInvoice(input: {
|
||||
activityType: "project_invoice_created",
|
||||
subjectType: "project",
|
||||
subjectId: input.projectId,
|
||||
summaryText: `Rechnung ${row.rechnungsnummer} wurde angelegt.`,
|
||||
summaryText: "activity.runtime.projects.invoiceCreated",
|
||||
metadata: { invoiceId: row.id, rechnungsnummer: row.rechnungsnummer },
|
||||
},
|
||||
{ client: tx },
|
||||
{ client: tx }
|
||||
);
|
||||
return row as RechnungRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateProjectInvoiceStatus(input: { tenantId: string; invoiceId: string; userId: string | null; status: RechnungStatus }): Promise<RechnungRow> {
|
||||
export async function updateProjectInvoiceStatus(input: {
|
||||
tenantId: string;
|
||||
invoiceId: string;
|
||||
ctx: AuftragVisibilityContext;
|
||||
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 requireProjectSubAreaAccessWithTx(tx, {
|
||||
tenantId: input.tenantId,
|
||||
projectId: existing.projektId,
|
||||
ctx: input.ctx,
|
||||
editable: true,
|
||||
});
|
||||
// Stamp the payment date on the transition into `bezahlt` and clear it on the
|
||||
// way out, so revenue by payment date stays truthful when a payment is undone.
|
||||
// Re-setting an already-paid invoice to `bezahlt` keeps the original date.
|
||||
const bezahltAm = input.status === "bezahlt" ? (existing.bezahltAm ?? new Date()) : null;
|
||||
const row = await tx.rechnung.update({
|
||||
where: { id: input.invoiceId, tenantId: input.tenantId },
|
||||
data: { status: input.status, bezahltAm },
|
||||
});
|
||||
await logActivity(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
@@ -472,10 +723,10 @@ export async function updateProjectInvoiceStatus(input: { tenantId: string; invo
|
||||
activityType: "project_invoice_status_changed",
|
||||
subjectType: "project",
|
||||
subjectId: existing.projektId,
|
||||
summaryText: `Rechnungsstatus wurde auf ${input.status} gesetzt.`,
|
||||
summaryText: "activity.runtime.projects.invoiceStatusChanged",
|
||||
metadata: { invoiceId: input.invoiceId, status: input.status },
|
||||
},
|
||||
{ client: tx },
|
||||
{ client: tx }
|
||||
);
|
||||
return row as RechnungRow;
|
||||
});
|
||||
@@ -484,6 +735,7 @@ export async function updateProjectInvoiceStatus(input: { tenantId: string; invo
|
||||
export async function createProjectChecklist(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
ctx: AuftragVisibilityContext;
|
||||
createdByUserId: string | null;
|
||||
titel: string;
|
||||
typ?: ProjektChecklistTyp;
|
||||
@@ -491,7 +743,7 @@ export async function createProjectChecklist(input: {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const title = normalizeText(input.titel);
|
||||
if (!title) throw new AuftragServiceError("projects.error.checklistTitleRequired");
|
||||
await requireProjectWithTx(tx, input);
|
||||
await requireProjectSubAreaAccessWithTx(tx, { ...input, editable: true });
|
||||
const row = await tx.projektChecklist.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
@@ -509,10 +761,10 @@ export async function createProjectChecklist(input: {
|
||||
activityType: "project_checklist_created",
|
||||
subjectType: "project",
|
||||
subjectId: input.projectId,
|
||||
summaryText: "Projekt-Checkliste wurde angelegt.",
|
||||
summaryText: "activity.runtime.projects.checklistCreated",
|
||||
metadata: { checklistId: row.id, typ: row.typ },
|
||||
},
|
||||
{ client: tx },
|
||||
{ client: tx }
|
||||
);
|
||||
return row as ProjektChecklistRow;
|
||||
});
|
||||
@@ -521,6 +773,7 @@ export async function createProjectChecklist(input: {
|
||||
export async function upsertProjectChecklistItem(input: {
|
||||
tenantId: string;
|
||||
checklistId: string;
|
||||
ctx: AuftragVisibilityContext;
|
||||
itemId?: string | null;
|
||||
titel: string;
|
||||
status?: ProjektChecklistItemStatus;
|
||||
@@ -535,6 +788,16 @@ export async function upsertProjectChecklistItem(input: {
|
||||
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 });
|
||||
await requireProjectSubAreaAccessWithTx(tx, {
|
||||
tenantId: input.tenantId,
|
||||
projectId: checklist.projektId,
|
||||
ctx: input.ctx,
|
||||
editable: true,
|
||||
});
|
||||
await Promise.all([
|
||||
assertTenantUserWithTx(tx, input.tenantId, input.assignedToUserId),
|
||||
assertVisibleTenantFileWithTx(tx, input.tenantId, input.fotoFileId, input.ctx),
|
||||
]);
|
||||
const data = {
|
||||
titel: title,
|
||||
status: input.status ?? "offen",
|
||||
@@ -545,7 +808,15 @@ export async function upsertProjectChecklistItem(input: {
|
||||
position: input.position ?? 0,
|
||||
};
|
||||
if (input.itemId) {
|
||||
const row = await tx.projektChecklistItem.update({ where: { id: input.itemId }, data });
|
||||
const existingItem = await tx.projektChecklistItem.findFirst({
|
||||
where: { id: input.itemId, tenantId: input.tenantId, checklistId: input.checklistId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!existingItem) throw new CatalogError(foundationErrors.notFound, { itemId: input.itemId });
|
||||
const row = await tx.projektChecklistItem.update({
|
||||
where: { id: input.itemId, tenantId: input.tenantId, checklistId: input.checklistId },
|
||||
data,
|
||||
});
|
||||
return row as ProjektChecklistItemRow;
|
||||
}
|
||||
const row = await tx.projektChecklistItem.create({
|
||||
@@ -566,11 +837,19 @@ export async function upsertAuftragPipelineStageConfig(input: {
|
||||
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 acceptanceFormTemplateId = normalizeText(input.acceptanceFormTemplateId);
|
||||
if (acceptanceFormTemplateId) {
|
||||
const template = await tx.acceptanceFormTemplate.findFirst({
|
||||
where: { id: acceptanceFormTemplateId, tenantId: input.tenantId, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!template) throw new CatalogError(foundationErrors.notFound, { acceptanceFormTemplateId });
|
||||
}
|
||||
const row = await tx.auftragPipelineStageConfig.upsert({
|
||||
where: { tenantId_stageId: { tenantId: input.tenantId, stageId: input.stageId } },
|
||||
update: {
|
||||
requiresAcceptanceProtocol: input.requiresAcceptanceProtocol ?? false,
|
||||
acceptanceFormTemplateId: normalizeText(input.acceptanceFormTemplateId),
|
||||
acceptanceFormTemplateId,
|
||||
autoArchiveAfterDays: input.autoArchiveAfterDays ?? null,
|
||||
},
|
||||
create: {
|
||||
@@ -578,7 +857,7 @@ export async function upsertAuftragPipelineStageConfig(input: {
|
||||
pipelineId: input.pipelineId,
|
||||
stageId: input.stageId,
|
||||
requiresAcceptanceProtocol: input.requiresAcceptanceProtocol ?? false,
|
||||
acceptanceFormTemplateId: normalizeText(input.acceptanceFormTemplateId),
|
||||
acceptanceFormTemplateId,
|
||||
autoArchiveAfterDays: input.autoArchiveAfterDays ?? null,
|
||||
},
|
||||
});
|
||||
@@ -598,9 +877,22 @@ export async function upsertAcceptanceFormTemplate(input: {
|
||||
const name = normalizeText(input.name);
|
||||
if (!name) throw new AuftragServiceError("projects.error.acceptanceTemplateNameRequired");
|
||||
if (input.templateId) {
|
||||
const existing = await tx.acceptanceFormTemplate.findFirst({
|
||||
where: { id: input.templateId, tenantId: input.tenantId, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!existing) throw new CatalogError(foundationErrors.notFound, { templateId: input.templateId });
|
||||
// Partial update: absent fields stay untouched (undefined = no-op in
|
||||
// Prisma) so e.g. a make-default toggle cannot wipe the definition.
|
||||
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 },
|
||||
where: { id: existing.id, tenantId: input.tenantId },
|
||||
data: {
|
||||
name,
|
||||
formId: input.formId === undefined ? undefined : normalizeText(input.formId),
|
||||
definition: input.definition === undefined ? undefined : input.definition ?? {},
|
||||
isDefault: input.isDefault,
|
||||
archivedAt: null,
|
||||
},
|
||||
});
|
||||
return row as AcceptanceFormTemplateRow;
|
||||
}
|
||||
@@ -637,17 +929,44 @@ export async function upsertProjectTemplate(input: {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const name = normalizeText(input.name);
|
||||
if (!name) throw new AuftragServiceError("projects.error.projectTemplateNameRequired");
|
||||
const defaultPipelineId = normalizeText(input.defaultPipelineId);
|
||||
const defaultStageId = normalizeText(input.defaultStageId);
|
||||
if (defaultStageId && !defaultPipelineId) throw new AuftragServiceError("projects.error.pipelineRequired");
|
||||
if (defaultStageId && defaultPipelineId) {
|
||||
const stage = await tx.pipelineStage.findFirst({
|
||||
where: {
|
||||
id: defaultStageId,
|
||||
tenantId: input.tenantId,
|
||||
pipelineId: defaultPipelineId,
|
||||
archivedAt: null,
|
||||
pipeline: { tenantId: input.tenantId, archivedAt: null },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
if (!stage) throw new CatalogError(foundationErrors.notFound, { defaultPipelineId, defaultStageId });
|
||||
} else if (defaultPipelineId) {
|
||||
const pipeline = await tx.pipeline.findFirst({
|
||||
where: { id: defaultPipelineId, tenantId: input.tenantId, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!pipeline) throw new CatalogError(foundationErrors.notFound, { defaultPipelineId });
|
||||
}
|
||||
const data = {
|
||||
name,
|
||||
defaultPipelineId: normalizeText(input.defaultPipelineId),
|
||||
defaultStageId: normalizeText(input.defaultStageId),
|
||||
defaultPipelineId,
|
||||
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 });
|
||||
const existing = await tx.projectTemplate.findFirst({
|
||||
where: { id: input.templateId, tenantId: input.tenantId, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!existing) throw new CatalogError(foundationErrors.notFound, { templateId: input.templateId });
|
||||
const row = await tx.projectTemplate.update({ where: { id: existing.id, tenantId: input.tenantId }, data });
|
||||
return row as ProjectTemplateRow;
|
||||
}
|
||||
const row = await tx.projectTemplate.upsert({
|
||||
@@ -670,28 +989,16 @@ export async function listProjectTemplates(input: { tenantId: string }): Promise
|
||||
});
|
||||
}
|
||||
|
||||
// R-P9a DoD 4 — the sweep logic is shared with the worker cron via
|
||||
// @hivegrid/db/project-auto-archive.server; this wrapper only binds the tenant
|
||||
// RLS context and injects the chat-channel archive side effect (AK-P15b).
|
||||
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 };
|
||||
});
|
||||
return withTenantRLS(input.tenantId, (tx) =>
|
||||
autoArchiveProjectsForTenantWithTx(tx as unknown as Parameters<typeof autoArchiveProjectsForTenantWithTx>[0], {
|
||||
tenantId: input.tenantId,
|
||||
now: input.now,
|
||||
limit: input.limit,
|
||||
archiveChannel: (channelInput) => archiveProjectChannelIfEnabledWithTx(tx, channelInput),
|
||||
})
|
||||
);
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tx: {
|
||||
pipeline: { findFirst: vi.fn() },
|
||||
pipelineStage: { findFirst: vi.fn() },
|
||||
acceptanceFormTemplate: { findFirst: vi.fn() },
|
||||
auftragPipelineStageConfig: { upsert: vi.fn() },
|
||||
projectTemplate: { findFirst: vi.fn(), update: vi.fn(), upsert: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: async (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
|
||||
}));
|
||||
vi.mock("@hivegrid/activity", () => ({ logActivity: vi.fn() }));
|
||||
|
||||
import { upsertAuftragPipelineStageConfig, upsertProjectTemplate } from "./auftragService.server";
|
||||
|
||||
describe("order/project template parent ownership boundaries", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.tx.pipeline.findFirst.mockResolvedValue({ id: "pipeline-a" });
|
||||
mocks.tx.pipelineStage.findFirst.mockResolvedValue({ id: "stage-a" });
|
||||
mocks.tx.acceptanceFormTemplate.findFirst.mockResolvedValue({ id: "acceptance-a" });
|
||||
mocks.tx.projectTemplate.findFirst.mockResolvedValue({ id: "template-a" });
|
||||
mocks.tx.projectTemplate.update.mockResolvedValue({ id: "template-a" });
|
||||
});
|
||||
|
||||
it("rejects a cross-tenant acceptance template on stage-config upsert", async () => {
|
||||
mocks.tx.acceptanceFormTemplate.findFirst.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
upsertAuftragPipelineStageConfig({
|
||||
tenantId: "tenant-a",
|
||||
pipelineId: "pipeline-a",
|
||||
stageId: "stage-a",
|
||||
acceptanceFormTemplateId: "acceptance-from-tenant-b",
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
|
||||
expect(mocks.tx.auftragPipelineStageConfig.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects a project template stage outside its tenant pipeline", async () => {
|
||||
mocks.tx.pipelineStage.findFirst.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
upsertProjectTemplate({
|
||||
tenantId: "tenant-a",
|
||||
name: "Foreign defaults",
|
||||
defaultPipelineId: "pipeline-a",
|
||||
defaultStageId: "stage-from-tenant-b",
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
|
||||
expect(mocks.tx.projectTemplate.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects a foreign template target and tenant-scopes a valid update", async () => {
|
||||
mocks.tx.projectTemplate.findFirst.mockResolvedValueOnce(null);
|
||||
await expect(
|
||||
upsertProjectTemplate({
|
||||
tenantId: "tenant-a",
|
||||
templateId: "template-from-tenant-b",
|
||||
name: "Foreign target",
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
expect(mocks.tx.projectTemplate.update).not.toHaveBeenCalled();
|
||||
|
||||
await upsertProjectTemplate({ tenantId: "tenant-a", templateId: "template-a", name: "Safe update" });
|
||||
expect(mocks.tx.projectTemplate.update).toHaveBeenCalledWith({
|
||||
where: { id: "template-a", tenantId: "tenant-a" },
|
||||
data: {
|
||||
name: "Safe update",
|
||||
defaultPipelineId: null,
|
||||
defaultStageId: null,
|
||||
defaultMembers: [],
|
||||
defaultTasks: [],
|
||||
customFields: {},
|
||||
archivedAt: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
// WF-P8 Subframe delta (S00 boards start page) — server helper for
|
||||
// `/projects/boards`. Lists the viewer-visible pipelines (listPipelines applies
|
||||
// the deny-based pipeline access scope) and adds stage/project counts. Project
|
||||
// counts use the same read scope as the board/list (projectReadScopeWhere) so
|
||||
// the numbers match what the viewer sees on the board; demo rows are excluded
|
||||
// like the list default. Server-only (.server) — never imported by a component.
|
||||
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { listPipelines, projectReadScopeWhere } from "./projectService.server";
|
||||
import type { ProjectRouteContext } from "./projectAccess.server";
|
||||
|
||||
export type BoardsStartPipeline = {
|
||||
id: string;
|
||||
name: string;
|
||||
typHint: "sales" | "auftrag" | "custom";
|
||||
isDefault: boolean;
|
||||
stageCount: number;
|
||||
projectCount: number;
|
||||
};
|
||||
|
||||
export async function loadBoardsStartPipelines({
|
||||
tenantId,
|
||||
ctx,
|
||||
}: {
|
||||
tenantId: string;
|
||||
ctx: ProjectRouteContext;
|
||||
}): Promise<BoardsStartPipeline[]> {
|
||||
const [pipelines, projectTotals] = await Promise.all([
|
||||
listPipelines({ tenantId, ctx }),
|
||||
withTenantRLS(tenantId, async (tx) =>
|
||||
tx.projekt.groupBy({
|
||||
by: ["pipelineId"],
|
||||
where: {
|
||||
tenantId,
|
||||
archivedAt: null,
|
||||
isDemoData: false,
|
||||
...projectReadScopeWhere(tenantId, ctx),
|
||||
},
|
||||
_count: { _all: true },
|
||||
}),
|
||||
),
|
||||
]);
|
||||
const countsByPipeline = new Map(projectTotals.map((total) => [total.pipelineId, total._count._all]));
|
||||
return pipelines.map((pipeline) => ({
|
||||
id: pipeline.id,
|
||||
name: pipeline.name,
|
||||
typHint: pipeline.typHint,
|
||||
isDefault: pipeline.isDefault,
|
||||
stageCount: pipeline.stages.length,
|
||||
projectCount: countsByPipeline.get(pipeline.id) ?? 0,
|
||||
}));
|
||||
}
|
||||
+241
@@ -0,0 +1,241 @@
|
||||
// WF-P8 Subframe delta — pipelineAccessRequest.server unit test. The Prisma
|
||||
// client is mocked, but NOT as an answer-everything stub: the withTenantRLS
|
||||
// mock binds a tenant context and every tx method re-checks the queried
|
||||
// tenantId against the bound context (mirroring the hg_*_all RLS policy), so
|
||||
// a query for a foreign tenant yields no rows instead of leaking fixtures.
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const TENANT = "tenant-a";
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
const state = {
|
||||
boundTenantId: null as string | null,
|
||||
pipelines: [] as Array<Record<string, unknown>>,
|
||||
requests: [] as Array<Record<string, unknown>>,
|
||||
admins: [] as Array<{ userId: string }>,
|
||||
projectCounts: [] as Array<{ pipelineId: string; _count: { _all: number } }>,
|
||||
};
|
||||
// RLS-shaped guard: rows only exist when the bound context matches the
|
||||
// tenant in the query (no context / wrong tenant -> zero rows, like Postgres).
|
||||
const visible = (whereTenantId: unknown) => state.boundTenantId !== null && whereTenantId === state.boundTenantId;
|
||||
const ownRows = <T extends { tenantId?: unknown }>(rows: T[]) => rows.filter((row) => row.tenantId === state.boundTenantId);
|
||||
const tx = {
|
||||
pipeline: {
|
||||
findMany: vi.fn(async (args: { where: { tenantId: string } }) => (visible(args.where.tenantId) ? ownRows(state.pipelines) : [])),
|
||||
findFirst: vi.fn(async (args: { where: { tenantId: string; id: string } }) => {
|
||||
if (!visible(args.where.tenantId)) return null;
|
||||
return ownRows(state.pipelines).find((pipeline) => pipeline.id === args.where.id) ?? null;
|
||||
}),
|
||||
},
|
||||
projekt: {
|
||||
groupBy: vi.fn(async (args: { where: { tenantId: string } }) => (visible(args.where.tenantId) ? state.projectCounts : [])),
|
||||
},
|
||||
pipelineAccessRequest: {
|
||||
findMany: vi.fn(async (args: { where: { tenantId: string; requestedByUserId: string; status: string } }) => {
|
||||
if (!visible(args.where.tenantId)) return [];
|
||||
return state.requests.filter(
|
||||
(request) => request.requestedByUserId === args.where.requestedByUserId && request.status === args.where.status
|
||||
);
|
||||
}),
|
||||
findFirst: vi.fn(
|
||||
async (args: { where: { tenantId: string; pipelineId: string; requestedByUserId: string; status: string } }) => {
|
||||
if (!visible(args.where.tenantId)) return null;
|
||||
return (
|
||||
state.requests.find(
|
||||
(request) =>
|
||||
request.pipelineId === args.where.pipelineId &&
|
||||
request.requestedByUserId === args.where.requestedByUserId &&
|
||||
request.status === args.where.status
|
||||
) ?? null
|
||||
);
|
||||
}
|
||||
),
|
||||
create: vi.fn(async (args: { data: Record<string, unknown> }) => {
|
||||
if (!visible(args.data.tenantId)) throw new Error("rls: insert with unbound/foreign tenant context denied");
|
||||
const row = { id: "req-new", status: "open", createdAt: new Date(), resolvedAt: null, resolvedByUserId: null, ...args.data };
|
||||
state.requests.push(row);
|
||||
return row;
|
||||
}),
|
||||
updateMany: vi.fn(async (args: { where: { tenantId: string } }) => {
|
||||
if (!visible(args.where.tenantId)) return { count: 0 };
|
||||
return { count: 1 };
|
||||
}),
|
||||
},
|
||||
userRole: {
|
||||
findMany: vi.fn(async (args: { where: { tenantId: string } }) => (visible(args.where.tenantId) ? state.admins : [])),
|
||||
},
|
||||
};
|
||||
return {
|
||||
state,
|
||||
tx,
|
||||
notify: vi.fn(async () => undefined),
|
||||
createAuditEvent: vi.fn(async () => ({ id: "audit-1" })),
|
||||
withTenantRLS: vi.fn(async (tenantId: string, fn: (tx: unknown) => Promise<unknown>) => {
|
||||
state.boundTenantId = tenantId;
|
||||
try {
|
||||
return await fn(tx);
|
||||
} finally {
|
||||
state.boundTenantId = null;
|
||||
}
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({ withTenantRLS: mocks.withTenantRLS }));
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({ createAuditEvent: mocks.createAuditEvent }));
|
||||
vi.mock("@hivegrid/foundation", async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
notify: mocks.notify,
|
||||
}));
|
||||
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import {
|
||||
listLockedPipelinesForViewer,
|
||||
requestPipelineAccess,
|
||||
resolveOpenAccessRequests,
|
||||
} from "./pipelineAccessRequest.server";
|
||||
import type { ProjectRouteContext } from "./projectAccess.server";
|
||||
|
||||
function ctx(overrides: Partial<ProjectRouteContext> = {}): ProjectRouteContext {
|
||||
return {
|
||||
tenantId: TENANT,
|
||||
userId: "user-a",
|
||||
permissions: ["projects.read_own"],
|
||||
roleIds: ["role-1"],
|
||||
groupIds: ["group-1"],
|
||||
hasModule: true,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.state.boundTenantId = null;
|
||||
mocks.state.pipelines = [
|
||||
{ id: "pl-locked", tenantId: TENANT, name: "Geschaeftsleitung", typHint: "sales", isDefault: false, stages: [{ id: "s1" }, { id: "s2" }] },
|
||||
];
|
||||
mocks.state.requests = [];
|
||||
mocks.state.admins = [{ userId: "admin-1" }, { userId: "admin-1" }, { userId: "admin-2" }];
|
||||
mocks.state.projectCounts = [{ pipelineId: "pl-locked", _count: { _all: 7 } }];
|
||||
});
|
||||
|
||||
describe("listLockedPipelinesForViewer", () => {
|
||||
it("lists locked pipelines with counts and the deny-rule scope", async () => {
|
||||
const rows = await listLockedPipelinesForViewer({ tenantId: TENANT, ctx: ctx() });
|
||||
expect(rows).toEqual([
|
||||
{
|
||||
id: "pl-locked",
|
||||
name: "Geschaeftsleitung",
|
||||
typHint: "sales",
|
||||
isDefault: false,
|
||||
stageCount: 2,
|
||||
projectCount: 7,
|
||||
requestPending: false,
|
||||
},
|
||||
]);
|
||||
// The query must match pipelines with an explicit deny rule for one of the
|
||||
// viewer's effective principals (inverse of the visibility scope).
|
||||
const where = mocks.tx.pipeline.findMany.mock.calls[0][0].where as Record<string, unknown>;
|
||||
expect(where.archivedAt).toBeNull();
|
||||
expect(where.accessRules).toEqual({
|
||||
some: {
|
||||
tenantId: TENANT,
|
||||
kannSehen: false,
|
||||
OR: [
|
||||
{ principalType: "user", principalId: "user-a" },
|
||||
{ principalType: "role", principalId: "role-1" },
|
||||
{ principalType: "group", principalId: "group-1" },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("flags pipelines with an open request by the viewer as pending", async () => {
|
||||
mocks.state.requests = [{ id: "req-1", pipelineId: "pl-locked", requestedByUserId: "user-a", status: "open" }];
|
||||
const rows = await listLockedPipelinesForViewer({ tenantId: TENANT, ctx: ctx() });
|
||||
expect(rows[0]?.requestPending).toBe(true);
|
||||
});
|
||||
|
||||
it("yields no rows for a foreign tenant (RLS context mismatch)", async () => {
|
||||
// The fixture pipelines belong to tenant-a; binding tenant-b's context
|
||||
// must answer with zero rows, like the RLS policy in Postgres.
|
||||
const rows = await listLockedPipelinesForViewer({ tenantId: "tenant-b", ctx: ctx({ tenantId: "tenant-b" }) });
|
||||
expect(rows).toEqual([]);
|
||||
expect(mocks.withTenantRLS).toHaveBeenCalledWith("tenant-b", expect.any(Function));
|
||||
});
|
||||
});
|
||||
|
||||
describe("requestPipelineAccess", () => {
|
||||
it("rejects a pipeline that is not locked for the viewer with catalog notFound", async () => {
|
||||
mocks.tx.pipeline.findFirst.mockResolvedValueOnce(null);
|
||||
await expect(
|
||||
requestPipelineAccess({ tenantId: TENANT, pipelineId: "pl-open", userId: "user-a", ctx: ctx() })
|
||||
).rejects.toBeInstanceOf(CatalogError);
|
||||
expect(mocks.tx.pipelineAccessRequest.create).not.toHaveBeenCalled();
|
||||
expect(mocks.notify).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("creates a request, notifies deduped projects.admin users and audits", async () => {
|
||||
const result = await requestPipelineAccess({ tenantId: TENANT, pipelineId: "pl-locked", userId: "user-a", ctx: ctx() });
|
||||
expect(result.created).toBe(true);
|
||||
expect(result.request.pipelineId).toBe("pl-locked");
|
||||
// Fan-out deduped: admin-1 appears twice in the role rows but is notified once.
|
||||
expect(mocks.notify).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.notify.mock.calls.map((call) => (call[0] as { userId: string }).userId).sort()).toEqual(["admin-1", "admin-2"]);
|
||||
expect(mocks.notify.mock.calls[0][0]).toMatchObject({
|
||||
tenantId: TENANT,
|
||||
channel: "IN_APP",
|
||||
category: "projects",
|
||||
messageKey: "projects.notification.pipelineAccessRequested",
|
||||
sourceKey: "pipeline-access-request:req-new",
|
||||
payloadMetadata: { pipelineId: "pl-locked", pipelineName: "Geschaeftsleitung", requesterUserId: "user-a" },
|
||||
});
|
||||
expect(mocks.createAuditEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
tenantId: TENANT,
|
||||
actorId: "user-a",
|
||||
action: "pipeline.access_requested",
|
||||
targetType: "pipeline",
|
||||
targetId: "pl-locked",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("is idempotent for an existing open request of the same user", async () => {
|
||||
mocks.state.requests = [{ id: "req-1", pipelineId: "pl-locked", requestedByUserId: "user-a", status: "open" }];
|
||||
const result = await requestPipelineAccess({ tenantId: TENANT, pipelineId: "pl-locked", userId: "user-a", ctx: ctx() });
|
||||
expect(result.created).toBe(false);
|
||||
expect(result.request.id).toBe("req-1");
|
||||
expect(mocks.tx.pipelineAccessRequest.create).not.toHaveBeenCalled();
|
||||
expect(mocks.notify).not.toHaveBeenCalled();
|
||||
expect(mocks.createAuditEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stays best-effort when notify or audit fail", async () => {
|
||||
mocks.notify.mockRejectedValueOnce(new Error("smtp down"));
|
||||
mocks.createAuditEvent.mockRejectedValueOnce(new Error("audit down"));
|
||||
const result = await requestPipelineAccess({ tenantId: TENANT, pipelineId: "pl-locked", userId: "user-a", ctx: ctx() });
|
||||
expect(result.created).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveOpenAccessRequests", () => {
|
||||
it("marks the user's open requests for the pipeline as approved", async () => {
|
||||
const count = await resolveOpenAccessRequests({
|
||||
tenantId: TENANT,
|
||||
pipelineId: "pl-locked",
|
||||
userId: "user-a",
|
||||
resolvedByUserId: "admin-1",
|
||||
status: "approved",
|
||||
});
|
||||
expect(count).toBe(1);
|
||||
const args = mocks.tx.pipelineAccessRequest.updateMany.mock.calls[0][0] as {
|
||||
where: Record<string, unknown>;
|
||||
data: Record<string, unknown>;
|
||||
};
|
||||
expect(args.where).toEqual({ tenantId: TENANT, pipelineId: "pl-locked", requestedByUserId: "user-a", status: "open" });
|
||||
expect(args.data).toMatchObject({ status: "approved", resolvedByUserId: "admin-1" });
|
||||
expect(args.data.resolvedAt).toBeInstanceOf(Date);
|
||||
});
|
||||
});
|
||||
+242
@@ -0,0 +1,242 @@
|
||||
// WF-P8 Subframe delta (S00 boards start page) — pipeline access requests.
|
||||
//
|
||||
// The pipeline access model is deny-based (PipelineAccess with
|
||||
// kannSehen=false). The Subframe design keeps locked boards visible on the
|
||||
// boards start page (greyed out, "Nutzung anfragen"), so this module lists
|
||||
// the pipelines the viewer is locked OUT of and lets the viewer file an
|
||||
// access request. projects.admin users get an IN_APP notification (M011) and
|
||||
// every request is audited (M001). Server-only (.server) — never imported by
|
||||
// a component.
|
||||
|
||||
import { CatalogError, foundationErrors, notify } from "@hivegrid/foundation";
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
import { effectivePipelinePrincipals } from "./projectService.server";
|
||||
import type { ProjectRouteContext } from "./projectAccess.server";
|
||||
|
||||
export type PipelineAccessRequestResolution = "approved" | "dismissed";
|
||||
|
||||
export type LockedBoardsStartPipeline = {
|
||||
id: string;
|
||||
name: string;
|
||||
typHint: "sales" | "auftrag" | "custom";
|
||||
isDefault: boolean;
|
||||
stageCount: number;
|
||||
projectCount: number;
|
||||
/** The viewer already has an open access request for this pipeline. */
|
||||
requestPending: boolean;
|
||||
};
|
||||
|
||||
export type PipelineAccessRequestRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
pipelineId: string;
|
||||
requestedByUserId: string;
|
||||
status: "open" | PipelineAccessRequestResolution;
|
||||
createdAt: Date;
|
||||
resolvedAt: Date | null;
|
||||
resolvedByUserId: string | null;
|
||||
};
|
||||
|
||||
/** Deny-rule match: the viewer is locked out when ANY rule with
|
||||
* kannSehen=false targets one of their effective principals (inverse of
|
||||
* pipelineVisibilityScopeWhere). */
|
||||
function lockedPipelineScopeWhere(tenantId: string, ctx: ProjectRouteContext): Record<string, unknown> {
|
||||
return {
|
||||
accessRules: {
|
||||
some: {
|
||||
tenantId,
|
||||
kannSehen: false,
|
||||
OR: effectivePipelinePrincipals(ctx),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the non-archived pipelines the viewer is locked out of, with the same
|
||||
* stage/project count shape as loadBoardsStartPipelines. Project counts are
|
||||
* board totals (active, non-demo) WITHOUT the viewer read scope on purpose:
|
||||
* the viewer cannot read any project on a locked board, so the viewer-scoped
|
||||
* count would always be 0 — the greyed-out row shows the board's size, which
|
||||
* the design treats as non-sensitive (like the board name itself).
|
||||
*/
|
||||
export async function listLockedPipelinesForViewer({
|
||||
tenantId,
|
||||
ctx,
|
||||
}: {
|
||||
tenantId: string;
|
||||
ctx: ProjectRouteContext;
|
||||
}): Promise<LockedBoardsStartPipeline[]> {
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
const pipelines = await tx.pipeline.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
archivedAt: null,
|
||||
...lockedPipelineScopeWhere(tenantId, ctx),
|
||||
},
|
||||
include: { stages: { where: { archivedAt: null }, select: { id: true } } },
|
||||
orderBy: { position: "asc" },
|
||||
});
|
||||
if (pipelines.length === 0) return [];
|
||||
const pipelineIds = pipelines.map((pipeline) => pipeline.id);
|
||||
const [projectTotals, openRequests] = await Promise.all([
|
||||
tx.projekt.groupBy({
|
||||
by: ["pipelineId"],
|
||||
where: { tenantId, pipelineId: { in: pipelineIds }, archivedAt: null, isDemoData: false },
|
||||
_count: { _all: true },
|
||||
}),
|
||||
tx.pipelineAccessRequest.findMany({
|
||||
where: { tenantId, pipelineId: { in: pipelineIds }, requestedByUserId: ctx.userId, status: "open" },
|
||||
select: { pipelineId: true },
|
||||
}),
|
||||
]);
|
||||
const countsByPipeline = new Map(projectTotals.map((total) => [total.pipelineId, total._count._all]));
|
||||
const pendingPipelineIds = new Set(openRequests.map((request) => request.pipelineId));
|
||||
return pipelines.map((pipeline) => ({
|
||||
id: pipeline.id,
|
||||
name: pipeline.name,
|
||||
typHint: pipeline.typHint,
|
||||
isDefault: pipeline.isDefault,
|
||||
stageCount: pipeline.stages.length,
|
||||
projectCount: countsByPipeline.get(pipeline.id) ?? 0,
|
||||
requestPending: pendingPipelineIds.has(pipeline.id),
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
/** Best-effort M011 fan-out to every projects.admin user (same recipient
|
||||
* pattern as leadService's notifyLeadSourcePausedAdmins). */
|
||||
async function notifyProjectsAdmins(
|
||||
tx: TenantRlsClient,
|
||||
input: { tenantId: string; requestId: string; pipelineId: string; pipelineName: string; requesterUserId: string }
|
||||
): Promise<void> {
|
||||
try {
|
||||
const admins = await tx.userRole.findMany({
|
||||
where: {
|
||||
tenantId: input.tenantId,
|
||||
role: { permissions: { some: { permission: { name: "projects.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: "projects",
|
||||
messageKey: "projects.notification.pipelineAccessRequested",
|
||||
sourceKey: `pipeline-access-request:${input.requestId}`,
|
||||
payloadMetadata: {
|
||||
pipelineId: input.pipelineId,
|
||||
pipelineName: input.pipelineName,
|
||||
requesterUserId: input.requesterUserId,
|
||||
},
|
||||
},
|
||||
tx as unknown as Parameters<typeof notify>[1]
|
||||
)
|
||||
)
|
||||
);
|
||||
} catch {
|
||||
// Notification failures must not lose the access request.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Files an access request for a pipeline the viewer is locked out of.
|
||||
* 404-semantics: a pipeline that does not exist, is archived or is NOT locked
|
||||
* for this viewer answers with the catalog notFound error (a locked-out
|
||||
* viewer must not be able to probe which pipelines exist). Idempotent: an
|
||||
* existing open request by the same user is returned instead of duplicated.
|
||||
*/
|
||||
export async function requestPipelineAccess({
|
||||
tenantId,
|
||||
pipelineId,
|
||||
userId,
|
||||
ctx,
|
||||
}: {
|
||||
tenantId: string;
|
||||
pipelineId: string;
|
||||
userId: string;
|
||||
ctx: ProjectRouteContext;
|
||||
}): Promise<{ request: PipelineAccessRequestRow; created: boolean }> {
|
||||
const result = await withTenantRLS(tenantId, async (tx) => {
|
||||
const pipeline = await tx.pipeline.findFirst({
|
||||
where: {
|
||||
tenantId,
|
||||
id: pipelineId,
|
||||
archivedAt: null,
|
||||
...lockedPipelineScopeWhere(tenantId, ctx),
|
||||
},
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
if (!pipeline) {
|
||||
throw new CatalogError(foundationErrors.notFound, { pipelineId });
|
||||
}
|
||||
const existing = await tx.pipelineAccessRequest.findFirst({
|
||||
where: { tenantId, pipelineId, requestedByUserId: userId, status: "open" },
|
||||
});
|
||||
if (existing) {
|
||||
return { request: existing as PipelineAccessRequestRow, created: false, pipelineName: pipeline.name };
|
||||
}
|
||||
const request = await tx.pipelineAccessRequest.create({
|
||||
data: { tenantId, pipelineId, requestedByUserId: userId },
|
||||
});
|
||||
await notifyProjectsAdmins(tx, {
|
||||
tenantId,
|
||||
requestId: request.id,
|
||||
pipelineId,
|
||||
pipelineName: pipeline.name,
|
||||
requesterUserId: userId,
|
||||
});
|
||||
return { request: request as PipelineAccessRequestRow, created: true, pipelineName: pipeline.name };
|
||||
});
|
||||
if (result.created) {
|
||||
// Best-effort audit (M001) — same pattern as auditCrmEvent: the audit
|
||||
// writer manages its own client/chain, failure never breaks the request.
|
||||
try {
|
||||
await createAuditEvent({
|
||||
tenantId,
|
||||
actorId: userId,
|
||||
actorType: "user",
|
||||
action: "pipeline.access_requested",
|
||||
targetType: "pipeline",
|
||||
targetId: pipelineId,
|
||||
metadata: { requestId: result.request.id, pipelineName: result.pipelineName },
|
||||
});
|
||||
} catch {
|
||||
// Audit must never break the user action; the failure is logged upstream.
|
||||
}
|
||||
}
|
||||
return { request: result.request, created: result.created };
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks all open access requests of a user for a pipeline as approved or
|
||||
* dismissed. Called best-effort from the pipeline admin action after a
|
||||
* user-scoped PipelineAccess rule with kannSehen=true was upserted.
|
||||
*/
|
||||
export async function resolveOpenAccessRequests({
|
||||
tenantId,
|
||||
pipelineId,
|
||||
userId,
|
||||
resolvedByUserId,
|
||||
status,
|
||||
}: {
|
||||
tenantId: string;
|
||||
pipelineId: string;
|
||||
userId: string;
|
||||
resolvedByUserId: string;
|
||||
status: PipelineAccessRequestResolution;
|
||||
}): Promise<number> {
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
const result = await tx.pipelineAccessRequest.updateMany({
|
||||
where: { tenantId, pipelineId, requestedByUserId: userId, status: "open" },
|
||||
data: { status, resolvedAt: new Date(), resolvedByUserId },
|
||||
});
|
||||
return result.count;
|
||||
});
|
||||
}
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
// WF-P8 board admin write path. Shared by the S07 board table
|
||||
// (admin.pipelines._index) and the S04 board settings
|
||||
// (admin.pipelines.$pipelineId._index): both screens mutate the same boards,
|
||||
// columns, access rules and field configs, so they must not grow two copies of
|
||||
// the intent handling that can drift apart.
|
||||
//
|
||||
// Every handler is keyed by the ids in the form data and re-checks
|
||||
// `projects.admin` through the caller's context, so a route cannot widen the
|
||||
// permission by forwarding here.
|
||||
|
||||
import { upsertAuftragPipelineStageConfig } from "~/utils/integrations/projects/auftragService.server";
|
||||
import { resolveOpenAccessRequests } from "~/utils/integrations/projects/pipelineAccessRequest.server";
|
||||
import { projectActionErrorResponse } from "~/utils/integrations/projects/projectAccess.server";
|
||||
import {
|
||||
archivePipeline,
|
||||
archivePipelineStage,
|
||||
createPipeline,
|
||||
duplicatePipeline,
|
||||
reorderPipelineStages,
|
||||
updatePipeline,
|
||||
upsertPipelineAccess,
|
||||
upsertPipelineFieldConfig,
|
||||
upsertPipelineFieldVisibility,
|
||||
upsertPipelineStage,
|
||||
type CreatePipelineStageInput,
|
||||
type PipelinePrincipalType,
|
||||
type PipelineStageKind,
|
||||
type PipelineTypHint,
|
||||
} from "~/utils/integrations/projects/projectService.server";
|
||||
|
||||
export function formString(formData: FormData, name: string): string | null {
|
||||
const value = formData.get(name);
|
||||
return typeof value === "string" ? value : null;
|
||||
}
|
||||
|
||||
export function formBoolean(formData: FormData, name: string): boolean | undefined {
|
||||
const value = formString(formData, name);
|
||||
if (value === null) return undefined;
|
||||
return value === "true" || value === "1" || value === "on";
|
||||
}
|
||||
|
||||
export function formNumber(formData: FormData, name: string): number | undefined {
|
||||
const value = formString(formData, name);
|
||||
if (!value) return undefined;
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : undefined;
|
||||
}
|
||||
|
||||
function formStages(formData: FormData): CreatePipelineStageInput[] {
|
||||
const raw = formString(formData, "stages");
|
||||
if (!raw) return [];
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.filter((stage): stage is CreatePipelineStageInput => typeof stage === "object" && stage !== null && "name" in stage && "stageKind" in stage);
|
||||
}
|
||||
|
||||
function formStageIds(formData: FormData): string[] {
|
||||
const raw = formString(formData, "stageIds");
|
||||
if (!raw) return [];
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.filter((id): id is string => typeof id === "string");
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs one board-admin intent. Returns the Response the route hands back, so an
|
||||
* unknown intent stays a 400 here instead of silently succeeding.
|
||||
*/
|
||||
export async function handlePipelineAdminAction(input: {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
formData: FormData;
|
||||
}): Promise<Response> {
|
||||
const { tenantId, userId, formData } = input;
|
||||
const intent = formString(formData, "_action");
|
||||
const success = (messageKey: string, payload: Record<string, unknown> = {}) => Response.json({ ok: true, intent, messageKey, ...payload });
|
||||
try {
|
||||
if (intent === "createPipeline") {
|
||||
const pipeline = await createPipeline({
|
||||
tenantId,
|
||||
userId,
|
||||
name: formString(formData, "name") ?? "",
|
||||
typHint: (formString(formData, "typHint") as PipelineTypHint | null) ?? "custom",
|
||||
position: formNumber(formData, "position"),
|
||||
stages: formStages(formData),
|
||||
});
|
||||
return success("projects.toast.pipelineCreated", { pipeline });
|
||||
}
|
||||
if (intent === "updatePipeline") {
|
||||
const pipeline = await updatePipeline({
|
||||
tenantId,
|
||||
pipelineId: formString(formData, "pipelineId") ?? "",
|
||||
name: formString(formData, "name"),
|
||||
position: formNumber(formData, "position"),
|
||||
typHint: formString(formData, "typHint") as PipelineTypHint | null,
|
||||
// Only forward the successor when the form actually carried the field,
|
||||
// so the rename form does not silently clear it.
|
||||
...(formData.has("nachfolgePipelineId") ? { nachfolgePipelineId: formString(formData, "nachfolgePipelineId") } : {}),
|
||||
});
|
||||
return success("projects.toast.pipelineSaved", { pipeline });
|
||||
}
|
||||
if (intent === "archivePipeline") {
|
||||
const pipeline = await archivePipeline({ tenantId, pipelineId: formString(formData, "pipelineId") ?? "" });
|
||||
return success("projects.toast.pipelineArchived", { pipeline });
|
||||
}
|
||||
if (intent === "duplicatePipeline") {
|
||||
const pipeline = await duplicatePipeline({
|
||||
tenantId,
|
||||
userId,
|
||||
pipelineId: formString(formData, "pipelineId") ?? "",
|
||||
name: formString(formData, "name") ?? "",
|
||||
});
|
||||
return success("projects.toast.pipelineDuplicated", { pipeline });
|
||||
}
|
||||
if (intent === "upsertStage") {
|
||||
await upsertPipelineStage({
|
||||
tenantId,
|
||||
pipelineId: formString(formData, "pipelineId") ?? "",
|
||||
stageId: formString(formData, "stageId"),
|
||||
name: formString(formData, "name") ?? "",
|
||||
stageKind: (formString(formData, "stageKind") as PipelineStageKind | null) ?? "offen",
|
||||
winProbability: formNumber(formData, "winProbability"),
|
||||
color: formString(formData, "color") ?? undefined,
|
||||
position: formNumber(formData, "position"),
|
||||
});
|
||||
return success("projects.toast.pipelineStageSaved");
|
||||
}
|
||||
if (intent === "archiveStage") {
|
||||
await archivePipelineStage({ tenantId, stageId: formString(formData, "stageId") ?? "" });
|
||||
return success("projects.toast.pipelineStageArchived");
|
||||
}
|
||||
if (intent === "reorderStages") {
|
||||
await reorderPipelineStages({
|
||||
tenantId,
|
||||
pipelineId: formString(formData, "pipelineId") ?? "",
|
||||
stageIds: formStageIds(formData),
|
||||
});
|
||||
return success("projects.toast.pipelineStagesReordered");
|
||||
}
|
||||
if (intent === "upsertAccess") {
|
||||
const pipelineId = formString(formData, "pipelineId") ?? "";
|
||||
const principalType = formString(formData, "principalType") as PipelinePrincipalType;
|
||||
const principalId = formString(formData, "principalId") ?? "";
|
||||
const kannSehen = formBoolean(formData, "kannSehen");
|
||||
await upsertPipelineAccess({
|
||||
tenantId,
|
||||
pipelineId,
|
||||
principalType,
|
||||
principalId,
|
||||
kannSehen,
|
||||
kannBearbeiten: formBoolean(formData, "kannBearbeiten"),
|
||||
});
|
||||
if (principalType === "user" && kannSehen === true && principalId) {
|
||||
// Granting a user visibility approves that user's open access
|
||||
// requests for this pipeline (best-effort: the grant already stands).
|
||||
try {
|
||||
await resolveOpenAccessRequests({
|
||||
tenantId,
|
||||
pipelineId,
|
||||
userId: principalId,
|
||||
resolvedByUserId: userId,
|
||||
status: "approved",
|
||||
});
|
||||
} catch {
|
||||
// Best-effort: an unresolved request marker never blocks the grant.
|
||||
}
|
||||
}
|
||||
return success("projects.toast.pipelineAccessSaved");
|
||||
}
|
||||
if (intent === "upsertFieldConfig") {
|
||||
await upsertPipelineFieldConfig({
|
||||
tenantId,
|
||||
pipelineId: formString(formData, "pipelineId") ?? "",
|
||||
stageId: formString(formData, "stageId"),
|
||||
fieldKey: formString(formData, "fieldKey") ?? "",
|
||||
sichtbar: formBoolean(formData, "sichtbar"),
|
||||
pflicht: formBoolean(formData, "pflicht"),
|
||||
reihenfolge: formNumber(formData, "reihenfolge"),
|
||||
});
|
||||
return success("projects.toast.pipelineFieldConfigSaved");
|
||||
}
|
||||
if (intent === "upsertFieldVisibility") {
|
||||
await upsertPipelineFieldVisibility({
|
||||
tenantId,
|
||||
fieldConfigId: formString(formData, "fieldConfigId") ?? "",
|
||||
principalType: formString(formData, "principalType") as PipelinePrincipalType,
|
||||
principalId: formString(formData, "principalId") ?? "",
|
||||
kannSehen: formBoolean(formData, "kannSehen"),
|
||||
kannBearbeiten: formBoolean(formData, "kannBearbeiten"),
|
||||
});
|
||||
return success("projects.toast.pipelineFieldVisibilitySaved");
|
||||
}
|
||||
if (intent === "upsertAuftragStageConfig") {
|
||||
await upsertAuftragPipelineStageConfig({
|
||||
tenantId,
|
||||
pipelineId: formString(formData, "pipelineId") ?? "",
|
||||
stageId: formString(formData, "stageId") ?? "",
|
||||
requiresAcceptanceProtocol: formBoolean(formData, "requiresAcceptanceProtocol"),
|
||||
acceptanceFormTemplateId: formString(formData, "acceptanceFormTemplateId"),
|
||||
autoArchiveAfterDays: formNumber(formData, "autoArchiveAfterDays") ?? null,
|
||||
});
|
||||
return success("projects.toast.pipelineAcceptanceRuleSaved");
|
||||
}
|
||||
return Response.json({ error: "projects.error.unsupportedAction" }, { status: 400 });
|
||||
} catch (error) {
|
||||
return projectActionErrorResponse(error);
|
||||
}
|
||||
}
|
||||
+255
@@ -0,0 +1,255 @@
|
||||
// WF-P8 S05 (Detail-Schablone Edit-Mode) + M05 (Modal Bestandsfeld) — the
|
||||
// project detail template of a pipeline: which field sits in which section, in
|
||||
// which order, and when it becomes mandatory.
|
||||
//
|
||||
// Two invariants from the screen, enforced here rather than in the UI:
|
||||
// - system fields may be reordered, locked, or moved back into the pool, but
|
||||
// never deleted (`istSystem`);
|
||||
// - projektname, status and prioritaet are always visible and can neither be
|
||||
// hidden nor unfiled (`ALWAYS_VISIBLE_FIELD_KEYS`).
|
||||
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
|
||||
export class PipelineFieldTemplateError extends Error {
|
||||
readonly messageKey: string;
|
||||
constructor(messageKey: string) {
|
||||
super(messageKey);
|
||||
this.name = "PipelineFieldTemplateError";
|
||||
this.messageKey = messageKey;
|
||||
}
|
||||
}
|
||||
|
||||
/** Always-visible fields per S05 ("Projektname, Status und Priorität bleiben immer sichtbar"). */
|
||||
export const ALWAYS_VISIBLE_FIELD_KEYS: readonly string[] = ["projektname", "status", "prioritaet"];
|
||||
|
||||
/**
|
||||
* Fixed system info rendered outside the configurable template ("Projekt-ID,
|
||||
* Erstellt und Board-Spalte sind feste Systeminfos außerhalb dieser
|
||||
* Konfiguration"). Listed so the UI can render them read-only and the service
|
||||
* can reject attempts to file them into a group.
|
||||
*/
|
||||
export const FIXED_SYSTEM_FIELD_KEYS: readonly string[] = ["projektNummer", "createdAt", "boardColumn"];
|
||||
|
||||
export type FieldGroupRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
reihenfolge: number;
|
||||
istSystem: boolean;
|
||||
};
|
||||
|
||||
export type TemplateFieldRow = {
|
||||
id: string;
|
||||
fieldKey: string;
|
||||
groupId: string | null;
|
||||
sichtbar: boolean;
|
||||
pflicht: boolean;
|
||||
pflichtAbStageId: string | null;
|
||||
hinweis: string | null;
|
||||
istSystem: boolean;
|
||||
gesperrt: boolean;
|
||||
reihenfolge: number;
|
||||
};
|
||||
|
||||
export type PipelineFieldTemplate = {
|
||||
pipelineId: string;
|
||||
pipelineName: string;
|
||||
groups: FieldGroupRow[];
|
||||
/** Fields filed into a group, ordered by group then position. */
|
||||
fields: TemplateFieldRow[];
|
||||
/** "Bestandsfelder außerhalb der Schablone" — configured but unfiled. */
|
||||
poolFields: TemplateFieldRow[];
|
||||
/** Stages offered by "Pflicht ab Board-Spalte". */
|
||||
stages: { id: string; name: string; position: number }[];
|
||||
};
|
||||
|
||||
function normalizeText(value?: string | null): string | null {
|
||||
const normalized = value?.trim();
|
||||
return normalized || null;
|
||||
}
|
||||
|
||||
async function assertPipelineWithTx(tx: TenantRlsClient, tenantId: string, pipelineId: string) {
|
||||
const pipeline = await tx.pipeline.findFirst({
|
||||
where: { id: pipelineId, tenantId, archivedAt: null },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
if (!pipeline) throw new CatalogError(foundationErrors.notFound, { pipelineId });
|
||||
return pipeline;
|
||||
}
|
||||
|
||||
export async function loadPipelineFieldTemplate(input: { tenantId: string; pipelineId: string }): Promise<PipelineFieldTemplate> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const pipeline = await assertPipelineWithTx(tx, input.tenantId, input.pipelineId);
|
||||
const [groups, configs, stages] = await Promise.all([
|
||||
tx.pipelineFieldGroup.findMany({
|
||||
where: { tenantId: input.tenantId, pipelineId: input.pipelineId },
|
||||
orderBy: { reihenfolge: "asc" },
|
||||
}),
|
||||
// The template is the pipeline-wide layer (`stageId: null`); per-stage
|
||||
// overrides stay the concern of the pipeline admin screen.
|
||||
tx.pipelineFieldConfig.findMany({
|
||||
where: { tenantId: input.tenantId, pipelineId: input.pipelineId, stageId: null },
|
||||
orderBy: { reihenfolge: "asc" },
|
||||
}),
|
||||
tx.pipelineStage.findMany({
|
||||
where: { tenantId: input.tenantId, pipelineId: input.pipelineId, archivedAt: null },
|
||||
orderBy: { position: "asc" },
|
||||
select: { id: true, name: true, position: true },
|
||||
}),
|
||||
]);
|
||||
const toRow = (config: (typeof configs)[number]): TemplateFieldRow => ({
|
||||
id: config.id,
|
||||
fieldKey: config.fieldKey,
|
||||
groupId: config.groupId,
|
||||
sichtbar: config.sichtbar,
|
||||
pflicht: config.pflicht,
|
||||
pflichtAbStageId: config.pflichtAbStageId,
|
||||
hinweis: config.hinweis,
|
||||
istSystem: config.istSystem,
|
||||
gesperrt: config.gesperrt,
|
||||
reihenfolge: config.reihenfolge,
|
||||
});
|
||||
return {
|
||||
pipelineId: pipeline.id,
|
||||
pipelineName: pipeline.name,
|
||||
groups: groups.map((group) => ({ id: group.id, name: group.name, reihenfolge: group.reihenfolge, istSystem: group.istSystem })),
|
||||
fields: configs.filter((config) => config.groupId).map(toRow),
|
||||
poolFields: configs.filter((config) => !config.groupId).map(toRow),
|
||||
stages,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function createFieldGroup(input: { tenantId: string; pipelineId: string; name: string }): Promise<FieldGroupRow> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const name = normalizeText(input.name);
|
||||
if (!name) throw new PipelineFieldTemplateError("projects.error.fieldGroupNameRequired");
|
||||
await assertPipelineWithTx(tx, input.tenantId, input.pipelineId);
|
||||
const duplicate = await tx.pipelineFieldGroup.findFirst({
|
||||
where: { pipelineId: input.pipelineId, name },
|
||||
select: { id: true },
|
||||
});
|
||||
if (duplicate) throw new PipelineFieldTemplateError("projects.error.fieldGroupNameTaken");
|
||||
const last = await tx.pipelineFieldGroup.findFirst({
|
||||
where: { tenantId: input.tenantId, pipelineId: input.pipelineId },
|
||||
orderBy: { reihenfolge: "desc" },
|
||||
select: { reihenfolge: true },
|
||||
});
|
||||
const group = await tx.pipelineFieldGroup.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
pipelineId: input.pipelineId,
|
||||
name,
|
||||
reihenfolge: (last?.reihenfolge ?? -1) + 1,
|
||||
},
|
||||
});
|
||||
return { id: group.id, name: group.name, reihenfolge: group.reihenfolge, istSystem: group.istSystem };
|
||||
});
|
||||
}
|
||||
|
||||
export async function renameFieldGroup(input: { tenantId: string; pipelineId: string; groupId: string; name: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const name = normalizeText(input.name);
|
||||
if (!name) throw new PipelineFieldTemplateError("projects.error.fieldGroupNameRequired");
|
||||
const group = await tx.pipelineFieldGroup.findFirst({
|
||||
where: { id: input.groupId, tenantId: input.tenantId, pipelineId: input.pipelineId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!group) throw new CatalogError(foundationErrors.notFound, { groupId: input.groupId });
|
||||
const duplicate = await tx.pipelineFieldGroup.findFirst({
|
||||
where: { pipelineId: input.pipelineId, name, NOT: { id: group.id } },
|
||||
select: { id: true },
|
||||
});
|
||||
if (duplicate) throw new PipelineFieldTemplateError("projects.error.fieldGroupNameTaken");
|
||||
await tx.pipelineFieldGroup.update({ where: { id: group.id }, data: { name } });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a group. System groups stay. Its fields are not deleted — they fall
|
||||
* back into the "Bestandsfelder" pool (`groupId: null` via the FK's SET NULL).
|
||||
*/
|
||||
export async function deleteFieldGroup(input: { tenantId: string; pipelineId: string; groupId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const group = await tx.pipelineFieldGroup.findFirst({
|
||||
where: { id: input.groupId, tenantId: input.tenantId, pipelineId: input.pipelineId },
|
||||
select: { id: true, istSystem: true },
|
||||
});
|
||||
if (!group) throw new CatalogError(foundationErrors.notFound, { groupId: input.groupId });
|
||||
if (group.istSystem) throw new PipelineFieldTemplateError("projects.error.fieldGroupSystemUndeletable");
|
||||
await tx.pipelineFieldGroup.delete({ where: { id: group.id } });
|
||||
});
|
||||
}
|
||||
|
||||
export async function reorderFieldGroups(input: { tenantId: string; pipelineId: string; orderedGroupIds: readonly string[] }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const groups = await tx.pipelineFieldGroup.findMany({
|
||||
where: { tenantId: input.tenantId, pipelineId: input.pipelineId },
|
||||
select: { id: true },
|
||||
});
|
||||
const known = new Set(groups.map((group) => group.id));
|
||||
// Reject a partial order outright: silently appending the missing groups
|
||||
// would scramble a layout the user never touched.
|
||||
if (input.orderedGroupIds.length !== known.size || input.orderedGroupIds.some((id) => !known.has(id))) {
|
||||
throw new PipelineFieldTemplateError("projects.error.fieldGroupOrderIncomplete");
|
||||
}
|
||||
for (const [index, groupId] of input.orderedGroupIds.entries()) {
|
||||
await tx.pipelineFieldGroup.update({ where: { id: groupId }, data: { reihenfolge: index } });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a field into a group (or back into the pool with `groupId: null`) and
|
||||
* set its position within that group. This is the drag-and-drop write path of S05.
|
||||
*/
|
||||
export async function moveFieldToGroup(input: {
|
||||
tenantId: string;
|
||||
pipelineId: string;
|
||||
fieldConfigId: string;
|
||||
groupId: string | null;
|
||||
reihenfolge: number;
|
||||
}): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const config = await tx.pipelineFieldConfig.findFirst({
|
||||
where: { id: input.fieldConfigId, tenantId: input.tenantId, pipelineId: input.pipelineId, stageId: null },
|
||||
select: { id: true, fieldKey: true },
|
||||
});
|
||||
if (!config) throw new CatalogError(foundationErrors.notFound, { fieldConfigId: input.fieldConfigId });
|
||||
if (FIXED_SYSTEM_FIELD_KEYS.includes(config.fieldKey)) {
|
||||
throw new PipelineFieldTemplateError("projects.error.fieldFixedSystemInfo");
|
||||
}
|
||||
if (input.groupId === null && ALWAYS_VISIBLE_FIELD_KEYS.includes(config.fieldKey)) {
|
||||
throw new PipelineFieldTemplateError("projects.error.fieldAlwaysVisible");
|
||||
}
|
||||
if (input.groupId) {
|
||||
const group = await tx.pipelineFieldGroup.findFirst({
|
||||
where: { id: input.groupId, tenantId: input.tenantId, pipelineId: input.pipelineId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!group) throw new CatalogError(foundationErrors.notFound, { groupId: input.groupId });
|
||||
}
|
||||
await tx.pipelineFieldConfig.update({
|
||||
where: { id: config.id },
|
||||
data: { groupId: input.groupId, reihenfolge: input.reihenfolge },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Permanently remove a non-system custom field from the template ("Kopieren und
|
||||
* dauerhaftes Löschen mit Datenverlust-Hinweis"). System fields are refused.
|
||||
*/
|
||||
export async function deleteTemplateField(input: { tenantId: string; pipelineId: string; fieldConfigId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const config = await tx.pipelineFieldConfig.findFirst({
|
||||
where: { id: input.fieldConfigId, tenantId: input.tenantId, pipelineId: input.pipelineId, stageId: null },
|
||||
select: { id: true, istSystem: true, fieldKey: true },
|
||||
});
|
||||
if (!config) throw new CatalogError(foundationErrors.notFound, { fieldConfigId: input.fieldConfigId });
|
||||
if (config.istSystem || ALWAYS_VISIBLE_FIELD_KEYS.includes(config.fieldKey)) {
|
||||
throw new PipelineFieldTemplateError("projects.error.fieldSystemUndeletable");
|
||||
}
|
||||
await tx.pipelineFieldConfig.delete({ where: { id: config.id } });
|
||||
});
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
// WF-P8 M04 — route-side assembly of the handover dialog's view-model.
|
||||
//
|
||||
// Two screens reach the same state: the board (S01, right after a card lands in
|
||||
// the final stage) and the detail page (S02, when the project is already
|
||||
// sitting there). Both need the identical answer to "is a handover pending, and
|
||||
// what does it contain", so the permission gate, the preview load and the name
|
||||
// resolution live here once instead of in two route files that could drift.
|
||||
|
||||
import { buildPipelineHandoverVM, type PipelineHandoverVM } from "@hivegrid/view-models";
|
||||
import { resolveUserLabels } from "~/utils/integrations/crm/crmService.server";
|
||||
import { loadPendingHandover } from "./pipelineHandoverService.server";
|
||||
import { toProjektNotizContext } from "./projektNotizService.server";
|
||||
import type { ProjectRouteContext } from "./projectAccess.server";
|
||||
|
||||
/**
|
||||
* The M04 payload for a project, or null when no handover is pending — which is
|
||||
* the normal case and never an error: without the permission, without a
|
||||
* successor board, or anywhere but the final stage there is simply nothing to
|
||||
* offer.
|
||||
*/
|
||||
export async function loadHandoverVM(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
ctx: ProjectRouteContext;
|
||||
}): Promise<PipelineHandoverVM | null> {
|
||||
if (!input.ctx.permissions.includes("projects.handover")) return null;
|
||||
const pending = await loadPendingHandover({
|
||||
tenantId: input.tenantId,
|
||||
projectId: input.projectId,
|
||||
ctx: toProjektNotizContext(input.ctx),
|
||||
});
|
||||
if (!pending) return null;
|
||||
// The preview carries raw author/assignee ids. Resolve exactly those — the
|
||||
// view-model drops what it cannot name rather than print a cuid at a user.
|
||||
const labels = await resolveUserLabels(pending.candidates.map((candidate) => candidate.personId).filter((id): id is string => Boolean(id)));
|
||||
return buildPipelineHandoverVM({ ...pending, userLabels: Object.fromEntries(labels) });
|
||||
}
|
||||
+449
@@ -0,0 +1,449 @@
|
||||
// WF-P8 M04 (Pipeline-Uebergabe) — hand a project into its successor pipeline
|
||||
// together with the companion data the salesperson explicitly picked.
|
||||
//
|
||||
// Trigger (validated with David, see the D-P8 handoff): M04 is NOT a button.
|
||||
// Moving a project into the final stage of its pipeline opens the dialog; only
|
||||
// "Auswahl uebernehmen" runs `executeProjectHandover`.
|
||||
//
|
||||
// AD-20 shape: there is ONE `Projekt` row. The handover re-points
|
||||
// `pipelineId`/`stageId` at the successor pipeline — it never copies the
|
||||
// project. The picked notes/files/tasks/appointments are recorded as the
|
||||
// handover PACKAGE (what the next team is explicitly handed); unpicked
|
||||
// companion data stays on the project untouched. Nothing is deleted here.
|
||||
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
import { projectEditScopeWhere, type ProjectVisibilityContext } from "./projectService.server";
|
||||
import { noteReadScopeWhere, type ProjektNotizContext } from "./projektNotizService.server";
|
||||
|
||||
export class PipelineHandoverServiceError extends Error {
|
||||
readonly messageKey: string;
|
||||
constructor(messageKey: string) {
|
||||
super(messageKey);
|
||||
this.name = "PipelineHandoverServiceError";
|
||||
this.messageKey = messageKey;
|
||||
}
|
||||
}
|
||||
|
||||
export type HandoverItemKind = "notiz" | "datei" | "aufgabe" | "termin";
|
||||
|
||||
export const HANDOVER_ITEM_KINDS: readonly HandoverItemKind[] = ["notiz", "datei", "aufgabe", "termin"];
|
||||
|
||||
export function isHandoverItemKind(value: string): value is HandoverItemKind {
|
||||
return (HANDOVER_ITEM_KINDS as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* M04 posts its selection as a JSON array so one form field carries the whole
|
||||
* pick. Unknown kinds and malformed payloads are dropped rather than failing
|
||||
* the handover: the selection is additive metadata, not the move itself.
|
||||
*
|
||||
* Shared by both callers — the detail page and the board — so a payload that
|
||||
* one accepts can never be one the other silently rejects.
|
||||
*/
|
||||
export function parseHandoverSelection(raw: string | null): { kind: HandoverItemKind; sourceId: string }[] {
|
||||
if (!raw) return [];
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.flatMap((entry) => {
|
||||
if (typeof entry !== "object" || entry === null) return [];
|
||||
const kind = (entry as { kind?: unknown }).kind;
|
||||
const sourceId = (entry as { sourceId?: unknown }).sourceId;
|
||||
if (typeof kind !== "string" || typeof sourceId !== "string" || !sourceId || !isHandoverItemKind(kind)) return [];
|
||||
return [{ kind, sourceId }];
|
||||
});
|
||||
}
|
||||
|
||||
export type HandoverCandidate = {
|
||||
id: string;
|
||||
kind: HandoverItemKind;
|
||||
/** Primary line (note headline, file name, task/appointment title). */
|
||||
title: string;
|
||||
/** Secondary line, where the record has one of its own (note body, description). */
|
||||
body: string | null;
|
||||
/** Raw user id — the view-model resolves it against a name directory. */
|
||||
personId: string | null;
|
||||
/** ISO timestamp used for ordering and for the "12.07. um 10:30 Uhr" style rendering. */
|
||||
atIso: string | null;
|
||||
/** Preselected in the dialog. */
|
||||
defaultSelected: boolean;
|
||||
/** datei */
|
||||
fileExtension?: string | null;
|
||||
fileRole?: string | null;
|
||||
fileSizeBytes?: number | null;
|
||||
/** aufgabe */
|
||||
taskStatus?: string | null;
|
||||
taskPriority?: string | null;
|
||||
deadlineIso?: string | null;
|
||||
/** termin */
|
||||
appointmentType?: string | null;
|
||||
};
|
||||
|
||||
export type HandoverPreview = {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
fromPipelineId: string;
|
||||
fromPipelineName: string;
|
||||
toPipelineId: string;
|
||||
toPipelineName: string;
|
||||
/** Entry stage in the successor pipeline (its lowest-position open stage). */
|
||||
toStageId: string;
|
||||
toStageName: string;
|
||||
candidates: HandoverCandidate[];
|
||||
};
|
||||
|
||||
function excerpt(value: string, max = 120): string {
|
||||
const collapsed = value.replace(/\s+/g, " ").trim();
|
||||
return collapsed.length <= max ? collapsed : `${collapsed.slice(0, max - 1)}…`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A note is one text column, but M04 draws a headline plus a body. Split on the
|
||||
* first line break: what a user typed as the opening line IS the headline. A
|
||||
* one-line note keeps its body empty instead of repeating itself.
|
||||
*/
|
||||
function splitNote(inhalt: string): { title: string; body: string | null } {
|
||||
const [first, ...rest] = inhalt.split(/\r?\n/);
|
||||
const body = rest.join(" ").trim();
|
||||
return { title: excerpt(first ?? "", 80), body: body ? excerpt(body) : null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Badge text of a file row. The extension is what a user recognises ("PDF"),
|
||||
* so it wins over the mime type; a file without one falls back to the mime
|
||||
* subtype rather than showing an empty badge.
|
||||
*/
|
||||
function fileExtensionLabel(displayName: string, mimeType: string): string {
|
||||
const dot = displayName.lastIndexOf(".");
|
||||
const extension = dot > 0 ? displayName.slice(dot + 1) : "";
|
||||
if (extension && extension.length <= 5) return extension.toUpperCase();
|
||||
const subtype = mimeType.split("/")[1] ?? mimeType;
|
||||
return subtype.toUpperCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Entry stage of the successor pipeline: lowest-position stage with
|
||||
* `stageKind: "offen"`. A pipeline without an open stage cannot receive a
|
||||
* handover — `validatePipelineStages` does not guarantee one exists.
|
||||
*/
|
||||
async function resolveEntryStageWithTx(tx: TenantRlsClient, input: { tenantId: string; pipelineId: string }) {
|
||||
const stage = await tx.pipelineStage.findFirst({
|
||||
where: { tenantId: input.tenantId, pipelineId: input.pipelineId, stageKind: "offen", archivedAt: null },
|
||||
orderBy: { position: "asc" },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
if (!stage) throw new PipelineHandoverServiceError("projects.error.handoverTargetHasNoOpenStage");
|
||||
return stage;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when moving `targetStageId` should open M04: the stage is the terminal
|
||||
* one of its pipeline (highest position, or a `gewonnen` stage) AND the
|
||||
* pipeline declares a successor. Callers use this to decide whether to render
|
||||
* the dialog after a stage move.
|
||||
*/
|
||||
export async function shouldOpenHandoverWithTx(
|
||||
tx: TenantRlsClient,
|
||||
input: { tenantId: string; pipelineId: string; targetStageId: string }
|
||||
): Promise<boolean> {
|
||||
const pipeline = await tx.pipeline.findFirst({
|
||||
where: { id: input.pipelineId, tenantId: input.tenantId, archivedAt: null },
|
||||
select: { nachfolgePipelineId: true },
|
||||
});
|
||||
if (!pipeline?.nachfolgePipelineId) return false;
|
||||
const stage = await tx.pipelineStage.findFirst({
|
||||
where: { id: input.targetStageId, tenantId: input.tenantId, pipelineId: input.pipelineId, archivedAt: null },
|
||||
select: { id: true, stageKind: true, position: true },
|
||||
});
|
||||
if (!stage) return false;
|
||||
if (stage.stageKind === "verloren") return false;
|
||||
if (stage.stageKind === "gewonnen") return true;
|
||||
const last = await tx.pipelineStage.findFirst({
|
||||
where: { tenantId: input.tenantId, pipelineId: input.pipelineId, archivedAt: null, stageKind: { not: "verloren" } },
|
||||
orderBy: { position: "desc" },
|
||||
select: { id: true },
|
||||
});
|
||||
return last?.id === stage.id;
|
||||
}
|
||||
|
||||
/** Everything M04 needs to render: the target pipeline plus the pickable companion data. */
|
||||
export async function loadHandoverPreview(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
ctx: ProjektNotizContext;
|
||||
}): Promise<HandoverPreview> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const project = await tx.projekt.findFirst({
|
||||
where: {
|
||||
id: input.projectId,
|
||||
tenantId: input.tenantId,
|
||||
archivedAt: null,
|
||||
...projectEditScopeWhere(input.tenantId, input.ctx),
|
||||
},
|
||||
include: { pipeline: true },
|
||||
});
|
||||
if (!project) throw new CatalogError(foundationErrors.notFound, { projectId: input.projectId });
|
||||
const successorId = project.pipeline.nachfolgePipelineId;
|
||||
if (!successorId) throw new PipelineHandoverServiceError("projects.error.handoverNoSuccessor");
|
||||
const successor = await tx.pipeline.findFirst({
|
||||
where: { id: successorId, tenantId: input.tenantId, archivedAt: null },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
if (!successor) throw new PipelineHandoverServiceError("projects.error.handoverNoSuccessor");
|
||||
const entryStage = await resolveEntryStageWithTx(tx, { tenantId: input.tenantId, pipelineId: successor.id });
|
||||
|
||||
// Notes honour the S02-N reader gate — a "nur ich" note of a different user
|
||||
// must not become pickable here.
|
||||
const [notes, fileLinks, tasks, appointments] = await Promise.all([
|
||||
tx.projektNotiz.findMany({
|
||||
where: { tenantId: input.tenantId, projektId: project.id, archivedAt: null, ...noteReadScopeWhere(input.ctx) },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 50,
|
||||
}),
|
||||
tx.fileEntityLink.findMany({
|
||||
where: { tenantId: input.tenantId, entityType: "project", entityId: project.id },
|
||||
include: { file: { select: { id: true, displayName: true, mimeType: true, sizeBytes: true, createdAt: true, archivedAt: true } } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 50,
|
||||
}),
|
||||
// Tasks attach polymorphically, not through a `projektId` column.
|
||||
tx.task.findMany({
|
||||
where: { tenantId: input.tenantId, linkedEntityType: "project", linkedEntityId: project.id, archivedAt: null },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 50,
|
||||
}),
|
||||
tx.projektTermin.findMany({
|
||||
where: { tenantId: input.tenantId, projektId: project.id, archivedAt: null },
|
||||
orderBy: { startAt: "asc" },
|
||||
take: 50,
|
||||
}),
|
||||
]);
|
||||
|
||||
const candidates: HandoverCandidate[] = [
|
||||
...notes.map((note) => ({
|
||||
id: note.id,
|
||||
kind: "notiz" as const,
|
||||
...splitNote(note.inhalt),
|
||||
personId: note.autorUserId,
|
||||
atIso: note.createdAt.toISOString(),
|
||||
// Everything is preselected: the dialog is a "deselect what must not
|
||||
// travel" step, which matches the counts shown in Davids screens.
|
||||
defaultSelected: true,
|
||||
})),
|
||||
...fileLinks
|
||||
.filter((link) => link.file && !link.file.archivedAt)
|
||||
.map((link) => ({
|
||||
id: link.file.id,
|
||||
kind: "datei" as const,
|
||||
title: link.file.displayName,
|
||||
body: null,
|
||||
personId: null,
|
||||
atIso: link.file.createdAt.toISOString(),
|
||||
defaultSelected: true,
|
||||
fileExtension: fileExtensionLabel(link.file.displayName, link.file.mimeType),
|
||||
fileRole: link.linkRole,
|
||||
fileSizeBytes: link.file.sizeBytes,
|
||||
})),
|
||||
...tasks.map((task) => ({
|
||||
id: task.id,
|
||||
kind: "aufgabe" as const,
|
||||
title: task.title,
|
||||
body: task.description ? excerpt(task.description) : null,
|
||||
personId: task.assignedToUserId,
|
||||
atIso: task.deadline ? task.deadline.toISOString() : task.createdAt.toISOString(),
|
||||
defaultSelected: true,
|
||||
taskStatus: task.status,
|
||||
taskPriority: task.priority,
|
||||
deadlineIso: task.deadline ? task.deadline.toISOString() : null,
|
||||
})),
|
||||
...appointments.map((termin) => ({
|
||||
id: termin.id,
|
||||
kind: "termin" as const,
|
||||
title: termin.titel,
|
||||
body: termin.beschreibung ? excerpt(termin.beschreibung) : null,
|
||||
personId: termin.assignedToUserId,
|
||||
atIso: termin.startAt.toISOString(),
|
||||
defaultSelected: true,
|
||||
appointmentType: termin.typ,
|
||||
})),
|
||||
];
|
||||
|
||||
return {
|
||||
projectId: project.id,
|
||||
projectName: project.projektname,
|
||||
fromPipelineId: project.pipelineId,
|
||||
fromPipelineName: project.pipeline.name,
|
||||
toPipelineId: successor.id,
|
||||
toPipelineName: successor.name,
|
||||
toStageId: entryStage.id,
|
||||
toStageName: entryStage.name,
|
||||
candidates,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Commit the handover: record the package, then re-point the project at the
|
||||
* successor pipeline's entry stage. Both happen in one transaction so a project
|
||||
* can never end up in a pipeline without its handover trail.
|
||||
*/
|
||||
export async function executeProjectHandover(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
userId: string | null;
|
||||
ctx: ProjectVisibilityContext;
|
||||
/** The ticked companion records, as `{kind, sourceId}` pairs. */
|
||||
selection: readonly { kind: HandoverItemKind; sourceId: string }[];
|
||||
}): Promise<{ handoverId: string; toPipelineId: string; toStageId: string }> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const project = await tx.projekt.findFirst({
|
||||
where: {
|
||||
id: input.projectId,
|
||||
tenantId: input.tenantId,
|
||||
archivedAt: null,
|
||||
...projectEditScopeWhere(input.tenantId, input.ctx),
|
||||
},
|
||||
include: { pipeline: true },
|
||||
});
|
||||
if (!project) throw new CatalogError(foundationErrors.notFound, { projectId: input.projectId });
|
||||
const successorId = project.pipeline.nachfolgePipelineId;
|
||||
if (!successorId) throw new PipelineHandoverServiceError("projects.error.handoverNoSuccessor");
|
||||
const successor = await tx.pipeline.findFirst({
|
||||
where: { id: successorId, tenantId: input.tenantId, archivedAt: null },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
if (!successor) throw new PipelineHandoverServiceError("projects.error.handoverNoSuccessor");
|
||||
const entryStage = await resolveEntryStageWithTx(tx, { tenantId: input.tenantId, pipelineId: successor.id });
|
||||
|
||||
const handover = await tx.pipelineHandover.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
projektId: project.id,
|
||||
fromPipelineId: project.pipelineId,
|
||||
toPipelineId: successor.id,
|
||||
fromStageId: project.stageId,
|
||||
toStageId: entryStage.id,
|
||||
performedByUserId: input.userId,
|
||||
},
|
||||
});
|
||||
|
||||
// Dedupe defensively: the dialog can submit the same id twice if a user
|
||||
// double-clicks, and the unique index would otherwise abort the whole move.
|
||||
const seen = new Set<string>();
|
||||
const items = input.selection.filter((item) => {
|
||||
const key = `${item.kind}:${item.sourceId}`;
|
||||
if (seen.has(key) || !item.sourceId) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
if (items.length > 0) {
|
||||
await tx.pipelineHandoverItem.createMany({
|
||||
data: items.map((item) => ({
|
||||
tenantId: input.tenantId,
|
||||
handoverId: handover.id,
|
||||
kind: item.kind,
|
||||
sourceId: item.sourceId,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
await tx.projekt.update({
|
||||
where: { id: project.id, tenantId: input.tenantId },
|
||||
data: {
|
||||
pipelineId: successor.id,
|
||||
stageId: entryStage.id,
|
||||
// Entering a fresh pipeline clears the terminal markers of the old one:
|
||||
// the project is open again in the new view (AD-20, no second row).
|
||||
wonAt: null,
|
||||
lostAt: null,
|
||||
lostReasonId: null,
|
||||
undoStageChangeUntil: null,
|
||||
},
|
||||
});
|
||||
await tx.projektStageChange.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
projektId: project.id,
|
||||
fromStageId: project.stageId,
|
||||
toStageId: entryStage.id,
|
||||
changedByUserId: input.userId,
|
||||
},
|
||||
});
|
||||
|
||||
await logActivity(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.userId,
|
||||
actorKind: input.userId ? "user" : "system",
|
||||
activityType: "project_pipeline_handover",
|
||||
subjectType: "project",
|
||||
subjectId: project.id,
|
||||
summaryText: "activity.runtime.projects.handoverCompleted",
|
||||
metadata: {
|
||||
handoverId: handover.id,
|
||||
fromPipelineId: project.pipelineId,
|
||||
toPipelineId: successor.id,
|
||||
itemCount: items.length,
|
||||
},
|
||||
},
|
||||
{ client: tx }
|
||||
);
|
||||
|
||||
return { handoverId: handover.id, toPipelineId: successor.id, toStageId: entryStage.id };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The M04 payload when the project currently awaits a handover, otherwise null.
|
||||
*
|
||||
* "Awaits a handover" = it sits in the final stage of a pipeline that declares
|
||||
* a successor. Every not-applicable case (no successor, successor without an
|
||||
* open stage, project not editable) resolves to null rather than throwing: the
|
||||
* detail page must render fine when no handover is pending.
|
||||
*/
|
||||
export async function loadPendingHandover(input: {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
ctx: ProjektNotizContext;
|
||||
}): Promise<HandoverPreview | null> {
|
||||
const pending = await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const project = await tx.projekt.findFirst({
|
||||
where: {
|
||||
id: input.projectId,
|
||||
tenantId: input.tenantId,
|
||||
archivedAt: null,
|
||||
...projectEditScopeWhere(input.tenantId, input.ctx),
|
||||
},
|
||||
select: { pipelineId: true, stageId: true },
|
||||
});
|
||||
if (!project) return false;
|
||||
return shouldOpenHandoverWithTx(tx, {
|
||||
tenantId: input.tenantId,
|
||||
pipelineId: project.pipelineId,
|
||||
targetStageId: project.stageId,
|
||||
});
|
||||
});
|
||||
if (!pending) return null;
|
||||
try {
|
||||
return await loadHandoverPreview(input);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Handover trail of a project, newest first (rendered in the S02 "Verlauf" sidebar area). */
|
||||
export async function listProjectHandovers(input: { tenantId: string; projectId: string }) {
|
||||
return withTenantRLS(input.tenantId, async (tx) =>
|
||||
tx.pipelineHandover.findMany({
|
||||
where: { tenantId: input.tenantId, projektId: input.projectId },
|
||||
include: { items: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
})
|
||||
);
|
||||
}
|
||||
+897
@@ -0,0 +1,897 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
withTenantRLS: vi.fn(),
|
||||
listApprovedAbsencesForRange: vi.fn(),
|
||||
putBufferAsFile: vi.fn(),
|
||||
deleteFile: vi.fn(),
|
||||
buildPdfExportArtifact: vi.fn(),
|
||||
withStorageReservation: vi.fn(),
|
||||
publishOutboxEvent: vi.fn(),
|
||||
createAcceptanceFollowUpTask: vi.fn(),
|
||||
tx: {
|
||||
projekt: { findFirst: vi.fn(), findMany: vi.fn(), update: vi.fn() },
|
||||
pipelineStage: { findFirst: vi.fn() },
|
||||
projektStageChange: { create: vi.fn() },
|
||||
scheduleEntry: { findFirst: vi.fn(), findMany: vi.fn(), findUniqueOrThrow: vi.fn(), update: vi.fn(), updateMany: vi.fn(), create: vi.fn() },
|
||||
scheduleConflict: { deleteMany: vi.fn(), createMany: vi.fn() },
|
||||
tenantUser: { findFirst: vi.fn() },
|
||||
projektChecklist: { findFirst: vi.fn() },
|
||||
file: { findMany: vi.fn(), create: vi.fn() },
|
||||
fileEntityLink: { create: vi.fn() },
|
||||
abnahmeProtokoll: { findFirst: vi.fn(), findMany: vi.fn(), findUniqueOrThrow: vi.fn(), create: vi.fn(), update: vi.fn() },
|
||||
abnahmeSignatur: { createMany: vi.fn() },
|
||||
notificationDelivery: { upsert: vi.fn(), create: vi.fn() },
|
||||
offlineSyncMutation: { findUnique: vi.fn(), create: vi.fn(), updateMany: vi.fn() },
|
||||
$executeRaw: vi.fn(),
|
||||
},
|
||||
idempotency: { claim: vi.fn(), complete: vi.fn(), get: vi.fn(), forget: vi.fn() },
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/shared-store", () => ({
|
||||
createIdempotencyStore: () => mocks.idempotency,
|
||||
}));
|
||||
vi.mock("@hivegrid/db/storage-capacity.server", () => ({
|
||||
withTenantStorageWriteReservation: (...args: unknown[]) => mocks.withStorageReservation(...args),
|
||||
}));
|
||||
vi.mock("~/shared-store.server", () => ({ getSharedStore: () => ({}) }));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: mocks.withTenantRLS,
|
||||
}));
|
||||
vi.mock("~/utils/integrations/hrLeaveService.server", () => ({
|
||||
listApprovedAbsencesForRange: mocks.listApprovedAbsencesForRange,
|
||||
listApprovedAbsencesForRangeWithTx: mocks.listApprovedAbsencesForRange,
|
||||
}));
|
||||
vi.mock("~/utils/integrations/storageService", () => ({
|
||||
putBufferAsFile: mocks.putBufferAsFile,
|
||||
deleteFile: mocks.deleteFile,
|
||||
resolveStorageBucket: () => "test-bucket",
|
||||
}));
|
||||
vi.mock("@hivegrid/exports/pdf", () => ({ buildPdfExportArtifact: mocks.buildPdfExportArtifact }));
|
||||
vi.mock("~/locale/i18next.global.server", () => ({ ensureServerGlobalI18n: vi.fn() }));
|
||||
vi.mock("~/locale/request-scoped-t", () => ({ requestScopedT: (key: string) => key }));
|
||||
vi.mock("@hivegrid/activity", () => ({ logActivity: vi.fn(async () => undefined) }));
|
||||
vi.mock("@hivegrid/db/outbox", () => ({ publishOutboxEvent: mocks.publishOutboxEvent }));
|
||||
vi.mock("~/utils/integrations/taskService.server", () => ({
|
||||
createAcceptanceFollowUpTask: mocks.createAcceptanceFollowUpTask,
|
||||
}));
|
||||
|
||||
import {
|
||||
applyOfflineMutation,
|
||||
archiveAcceptanceProtocol,
|
||||
bulkReassignScheduleEntries,
|
||||
listEditablePlantafelProjectOptions,
|
||||
listAcceptanceProtocols,
|
||||
loadPlantafel,
|
||||
ensurePlantafelRange,
|
||||
normalizeBulkScheduleEntryIds,
|
||||
parseOfflineSyncOperation,
|
||||
parsePlantafelDateInput,
|
||||
PLANTAFEL_BULK_REASSIGN_MAX_ENTRIES,
|
||||
PLANTAFEL_MAX_RANGE_DAYS,
|
||||
PLANTAFEL_PROJECT_PICKER_LIMIT,
|
||||
submitAcceptanceProtocol,
|
||||
updateAcceptanceProtocolContent,
|
||||
upsertScheduleEntry,
|
||||
updateScheduleEntryStatus,
|
||||
type PlantafelContext,
|
||||
} from "./plantafelAcceptanceService.server";
|
||||
|
||||
function context(permissions: readonly string[]): PlantafelContext {
|
||||
return {
|
||||
tenantId: "tenant-a",
|
||||
userId: "user-a",
|
||||
permissions,
|
||||
roleIds: ["role-a"],
|
||||
groupIds: ["group-a"],
|
||||
hasModule: true,
|
||||
};
|
||||
}
|
||||
|
||||
function project(id = "project-a") {
|
||||
return {
|
||||
id,
|
||||
tenantId: "tenant-a",
|
||||
projektNummer: "P-001",
|
||||
projektname: "Project",
|
||||
pipelineId: "pipeline-a",
|
||||
stageId: "stage-a",
|
||||
};
|
||||
}
|
||||
|
||||
describe("plantafel and acceptance authorization", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.withTenantRLS.mockImplementation(async (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx));
|
||||
mocks.listApprovedAbsencesForRange.mockResolvedValue([]);
|
||||
mocks.putBufferAsFile.mockResolvedValue({ publicUrl: null });
|
||||
mocks.deleteFile.mockResolvedValue(undefined);
|
||||
mocks.publishOutboxEvent.mockResolvedValue(undefined);
|
||||
mocks.createAcceptanceFollowUpTask.mockResolvedValue(undefined);
|
||||
mocks.buildPdfExportArtifact.mockResolvedValue({
|
||||
bytes: new Uint8Array([1, 2, 3]),
|
||||
contentType: "application/pdf",
|
||||
byteLength: 3,
|
||||
});
|
||||
mocks.withStorageReservation.mockImplementation(async (input) => {
|
||||
const stored = await input.upload();
|
||||
return input.runTransaction((tx) => input.commit(tx, stored));
|
||||
});
|
||||
mocks.tx.scheduleEntry.updateMany.mockResolvedValue({ count: 0 });
|
||||
mocks.tx.offlineSyncMutation.updateMany.mockResolvedValue({ count: 1 });
|
||||
mocks.idempotency.claim.mockResolvedValue(true);
|
||||
mocks.idempotency.complete.mockResolvedValue(undefined);
|
||||
mocks.idempotency.get.mockResolvedValue(null);
|
||||
mocks.idempotency.forget.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("rejects unknown offline operations instead of falling through to acceptance", async () => {
|
||||
expect(parseOfflineSyncOperation("schedule_upsert")).toBe("schedule_upsert");
|
||||
expect(() => parseOfflineSyncOperation("acceptance_delete")).toThrow("projects.error.unsupportedAction");
|
||||
|
||||
await expect(
|
||||
applyOfflineMutation({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["plantafel.write", "projects.read_all"]),
|
||||
clientMutationId: "mutation-a",
|
||||
operation: "acceptance_delete",
|
||||
payload: {},
|
||||
})
|
||||
).rejects.toThrow("projects.error.unsupportedAction");
|
||||
expect(mocks.withTenantRLS).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("requires the exact permission for each offline operation", async () => {
|
||||
await expect(
|
||||
applyOfflineMutation({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["acceptance.write", "projects.read_all"]),
|
||||
clientMutationId: "mutation-schedule",
|
||||
operation: "schedule_status",
|
||||
payload: { entryId: "entry-a", status: "done" },
|
||||
})
|
||||
).rejects.toThrow();
|
||||
|
||||
await expect(
|
||||
applyOfflineMutation({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["plantafel.write", "projects.read_all"]),
|
||||
clientMutationId: "mutation-acceptance",
|
||||
operation: "acceptance_submit",
|
||||
payload: { projectId: "project-a" },
|
||||
})
|
||||
).rejects.toThrow();
|
||||
|
||||
expect(mocks.withTenantRLS).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps an offline mutation payload immutable for a reused client id", async () => {
|
||||
mocks.tx.offlineSyncMutation.findUnique.mockResolvedValue({
|
||||
id: "offline-a",
|
||||
tenantId: "tenant-a",
|
||||
clientMutationId: "mutation-a",
|
||||
createdByUserId: "user-a",
|
||||
operation: "schedule_status",
|
||||
payload: { entryId: "entry-a", status: "done" },
|
||||
status: "pending",
|
||||
resultEntityType: null,
|
||||
resultEntityId: null,
|
||||
});
|
||||
|
||||
await expect(
|
||||
applyOfflineMutation({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["plantafel.write", "projects.read_all"]),
|
||||
clientMutationId: "mutation-a",
|
||||
operation: "schedule_status",
|
||||
payload: { entryId: "entry-a", status: "cancelled" },
|
||||
})
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.idempotency.claim).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.scheduleEntry.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not execute an offline mutation while another replica owns the claim", async () => {
|
||||
const existing = {
|
||||
id: "offline-a",
|
||||
tenantId: "tenant-a",
|
||||
clientMutationId: "mutation-a",
|
||||
createdByUserId: "user-a",
|
||||
operation: "schedule_status",
|
||||
payload: { entryId: "entry-a", status: "done" },
|
||||
status: "pending",
|
||||
resultEntityType: null,
|
||||
resultEntityId: null,
|
||||
};
|
||||
mocks.tx.offlineSyncMutation.findUnique.mockResolvedValue(existing);
|
||||
mocks.idempotency.claim.mockResolvedValue(false);
|
||||
|
||||
await expect(
|
||||
applyOfflineMutation({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["plantafel.write", "projects.read_all"]),
|
||||
clientMutationId: "mutation-a",
|
||||
operation: "schedule_status",
|
||||
payload: { status: "done", entryId: "entry-a" },
|
||||
})
|
||||
).rejects.toThrow("projects.error.offlineMutationPending");
|
||||
|
||||
expect(mocks.tx.scheduleEntry.findFirst).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.offlineSyncMutation.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("limits plantafel entries to centrally readable projects", async () => {
|
||||
mocks.tx.projekt.findMany.mockResolvedValue([{ id: "project-a", projektNummer: "P-001", projektname: "Project" }]);
|
||||
mocks.tx.scheduleEntry.findMany.mockResolvedValue([
|
||||
{
|
||||
id: "entry-a",
|
||||
projektId: "project-a",
|
||||
assignedUserId: "user-a",
|
||||
startAt: new Date("2026-07-02T08:00:00.000Z"),
|
||||
endAt: new Date("2026-07-02T10:00:00.000Z"),
|
||||
conflicts: [],
|
||||
},
|
||||
]);
|
||||
|
||||
await loadPlantafel({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["plantafel.read_own", "projects.read_own_member"]),
|
||||
from: new Date("2026-07-01T00:00:00.000Z"),
|
||||
to: new Date("2026-07-08T00:00:00.000Z"),
|
||||
});
|
||||
|
||||
expect(mocks.tx.scheduleEntry.findMany).toHaveBeenCalledWith({
|
||||
where: expect.objectContaining({
|
||||
tenantId: "tenant-a",
|
||||
archivedAt: null,
|
||||
assignedUserId: "user-a",
|
||||
startAt: { lt: new Date("2026-07-08T00:00:00.000Z") },
|
||||
endAt: { gt: new Date("2026-07-01T00:00:00.000Z") },
|
||||
}),
|
||||
include: { conflicts: { where: { resolvedAt: null }, orderBy: { createdAt: "asc" } } },
|
||||
orderBy: [{ startAt: "asc" }, { assignedUserId: "asc" }],
|
||||
});
|
||||
expect(mocks.tx.projekt.findMany).toHaveBeenCalledWith({
|
||||
where: expect.objectContaining({
|
||||
tenantId: "tenant-a",
|
||||
id: { in: ["project-a"] },
|
||||
archivedAt: null,
|
||||
AND: expect.arrayContaining([
|
||||
{
|
||||
OR: [
|
||||
{
|
||||
mitglieder: {
|
||||
some: {
|
||||
tenantId: "tenant-a",
|
||||
archivedAt: null,
|
||||
OR: [{ userId: "user-a" }, { groupId: { in: ["group-a"] } }],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
expect.objectContaining({ pipeline: expect.any(Object) }),
|
||||
]),
|
||||
}),
|
||||
select: { id: true, projektNummer: true, projektname: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("reports a visible project as non-editable when the central edit scope denies it", async () => {
|
||||
mocks.tx.scheduleEntry.findMany.mockResolvedValue([
|
||||
{
|
||||
id: "entry-visible",
|
||||
projektId: "project-visible",
|
||||
assignedUserId: "user-a",
|
||||
startAt: new Date("2026-07-02T08:00:00.000Z"),
|
||||
endAt: new Date("2026-07-02T10:00:00.000Z"),
|
||||
conflicts: [],
|
||||
},
|
||||
]);
|
||||
mocks.tx.projekt.findMany.mockResolvedValueOnce([{ id: "project-visible", projektNummer: "P-001", projektname: "Visible" }]).mockResolvedValueOnce([]);
|
||||
|
||||
const result = await loadPlantafel({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["plantafel.read_all", "plantafel.write", "projects.read_all"]),
|
||||
from: new Date("2026-07-01T00:00:00.000Z"),
|
||||
to: new Date("2026-07-08T00:00:00.000Z"),
|
||||
});
|
||||
|
||||
expect(result.entries).toHaveLength(1);
|
||||
expect(result.editableProjectIds).toEqual([]);
|
||||
expect(mocks.tx.projekt.findMany).toHaveBeenCalledTimes(2);
|
||||
expect(JSON.stringify(mocks.tx.projekt.findMany.mock.calls[1]?.[0]?.where)).toContain("kannBearbeiten");
|
||||
});
|
||||
|
||||
it("searches only editable projects with an explicit bounded result", async () => {
|
||||
mocks.tx.projekt.findMany.mockResolvedValue(
|
||||
Array.from({ length: PLANTAFEL_PROJECT_PICKER_LIMIT + 1 }, (_, index) => ({
|
||||
id: `project-${index}`,
|
||||
projektNummer: `P-${index}`,
|
||||
projektname: `Wärmepumpe ${index}`,
|
||||
}))
|
||||
);
|
||||
|
||||
const result = await listEditablePlantafelProjectOptions({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["plantafel.write", "projects.read_all"]),
|
||||
query: " Wärme ",
|
||||
});
|
||||
|
||||
expect(result.options).toHaveLength(PLANTAFEL_PROJECT_PICKER_LIMIT);
|
||||
expect(result.hasMore).toBe(true);
|
||||
expect(result.query).toBe("Wärme");
|
||||
expect(mocks.tx.projekt.findMany).toHaveBeenCalledWith({
|
||||
where: expect.objectContaining({
|
||||
tenantId: "tenant-a",
|
||||
archivedAt: null,
|
||||
AND: expect.arrayContaining([
|
||||
expect.objectContaining({ pipeline: expect.any(Object) }),
|
||||
{
|
||||
OR: [{ projektNummer: { contains: "Wärme", mode: "insensitive" } }, { projektname: { contains: "Wärme", mode: "insensitive" } }],
|
||||
},
|
||||
]),
|
||||
}),
|
||||
select: { id: true, projektNummer: true, projektname: true },
|
||||
orderBy: [{ updatedAt: "desc" }, { id: "asc" }],
|
||||
take: PLANTAFEL_PROJECT_PICKER_LIMIT + 1,
|
||||
});
|
||||
expect(JSON.stringify(mocks.tx.projekt.findMany.mock.calls[0]?.[0]?.where)).toContain("kannBearbeiten");
|
||||
});
|
||||
|
||||
it("rejects reversed and remotely oversized plantafel windows before querying", async () => {
|
||||
const from = new Date("2026-07-01T00:00:00.000Z");
|
||||
expect(() => ensurePlantafelRange(from, from)).toThrow("projects.error.scheduleRangeInvalid");
|
||||
expect(() => ensurePlantafelRange(from, new Date(from.getTime() + (PLANTAFEL_MAX_RANGE_DAYS + 1) * 24 * 60 * 60 * 1000))).toThrow(
|
||||
"projects.error.scheduleRangeInvalid"
|
||||
);
|
||||
|
||||
await expect(
|
||||
loadPlantafel({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["plantafel.read_all", "projects.read_all"]),
|
||||
from,
|
||||
to: new Date(from.getTime() + (PLANTAFEL_MAX_RANGE_DAYS + 1) * 24 * 60 * 60 * 1000),
|
||||
})
|
||||
).rejects.toThrow("projects.error.scheduleRangeInvalid");
|
||||
expect(mocks.withTenantRLS).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("parses zoneless Plantafel inputs as Europe/Berlin in a UTC runtime and preserves explicit ISO zones", () => {
|
||||
const previousTimezone = process.env.TZ;
|
||||
process.env.TZ = "UTC";
|
||||
try {
|
||||
expect(parsePlantafelDateInput("2026-07-21T09:00")?.toISOString()).toBe("2026-07-21T07:00:00.000Z");
|
||||
expect(parsePlantafelDateInput("2026-01-21T09:00")?.toISOString()).toBe("2026-01-21T08:00:00.000Z");
|
||||
expect(parsePlantafelDateInput("2026-07-21T09:00:00.000Z")?.toISOString()).toBe("2026-07-21T09:00:00.000Z");
|
||||
expect(parsePlantafelDateInput("2026-07-21T09:00:00+02:00")?.toISOString()).toBe("2026-07-21T07:00:00.000Z");
|
||||
} finally {
|
||||
if (previousTimezone === undefined) delete process.env.TZ;
|
||||
else process.env.TZ = previousTimezone;
|
||||
}
|
||||
});
|
||||
|
||||
it("checks workday bounds in the app time zone instead of the UTC runtime", async () => {
|
||||
const created = {
|
||||
id: "entry-workday-start",
|
||||
tenantId: "tenant-a",
|
||||
projektId: "project-a",
|
||||
assignedUserId: "user-a",
|
||||
startAt: new Date("2026-07-21T04:00:00.000Z"),
|
||||
endAt: new Date("2026-07-21T06:00:00.000Z"),
|
||||
conflicts: [],
|
||||
};
|
||||
mocks.tx.tenantUser.findFirst.mockResolvedValue({ userId: "user-a" });
|
||||
mocks.tx.projekt.findFirst.mockResolvedValue(project());
|
||||
mocks.tx.scheduleEntry.findMany.mockResolvedValue([]);
|
||||
mocks.tx.scheduleEntry.create.mockResolvedValue(created);
|
||||
mocks.tx.scheduleEntry.findUniqueOrThrow.mockResolvedValue(created);
|
||||
mocks.tx.scheduleConflict.deleteMany.mockResolvedValue({ count: 0 });
|
||||
|
||||
const previousTimezone = process.env.TZ;
|
||||
process.env.TZ = "UTC";
|
||||
try {
|
||||
await upsertScheduleEntry({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["plantafel.write", "projects.read_all"]),
|
||||
projektId: "project-a",
|
||||
assignedUserId: "user-a",
|
||||
title: "Frühtermin",
|
||||
startAt: "2026-07-21T06:00",
|
||||
endAt: "2026-07-21T08:00",
|
||||
});
|
||||
} finally {
|
||||
if (previousTimezone === undefined) delete process.env.TZ;
|
||||
else process.env.TZ = previousTimezone;
|
||||
}
|
||||
|
||||
expect(mocks.tx.scheduleEntry.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ startAt: created.startAt, endAt: created.endAt }),
|
||||
});
|
||||
expect(mocks.tx.scheduleConflict.createMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an inactive or foreign assignee on a single schedule upsert", async () => {
|
||||
mocks.tx.tenantUser.findFirst.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
upsertScheduleEntry({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["plantafel.write", "projects.read_all"]),
|
||||
projektId: "project-a",
|
||||
assignedUserId: "user-foreign",
|
||||
title: "Montage",
|
||||
startAt: "2026-07-01T08:00:00.000Z",
|
||||
endAt: "2026-07-01T10:00:00.000Z",
|
||||
})
|
||||
).rejects.toThrow();
|
||||
|
||||
expect(mocks.tx.projekt.findFirst).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.scheduleEntry.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("locks the assignee and persists a schedule entry with its conflicts in one transaction", async () => {
|
||||
const created = {
|
||||
id: "entry-a",
|
||||
tenantId: "tenant-a",
|
||||
projektId: "project-a",
|
||||
assignedUserId: "user-a",
|
||||
startAt: new Date("2026-07-01T08:00:00.000Z"),
|
||||
endAt: new Date("2026-07-01T10:00:00.000Z"),
|
||||
conflicts: [],
|
||||
};
|
||||
mocks.tx.tenantUser.findFirst.mockResolvedValue({ userId: "user-a" });
|
||||
mocks.tx.projekt.findFirst.mockResolvedValue(project());
|
||||
mocks.tx.scheduleEntry.findMany.mockResolvedValue([]);
|
||||
mocks.tx.scheduleEntry.create.mockResolvedValue(created);
|
||||
mocks.tx.scheduleEntry.findUniqueOrThrow.mockResolvedValue(created);
|
||||
mocks.tx.scheduleConflict.deleteMany.mockResolvedValue({ count: 0 });
|
||||
|
||||
await expect(
|
||||
upsertScheduleEntry({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["plantafel.write", "projects.read_all"]),
|
||||
projektId: "project-a",
|
||||
assignedUserId: "user-a",
|
||||
title: "Montage",
|
||||
startAt: created.startAt,
|
||||
endAt: created.endAt,
|
||||
})
|
||||
).resolves.toMatchObject({ entry: { id: "entry-a" }, conflicts: [] });
|
||||
|
||||
expect(mocks.withTenantRLS).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.tx.$executeRaw).toHaveBeenCalledOnce();
|
||||
expect(String(mocks.tx.$executeRaw.mock.calls[0]?.[0])).toContain("pg_advisory_xact_lock");
|
||||
expect(mocks.tx.scheduleConflict.deleteMany).toHaveBeenCalledWith({ where: { tenantId: "tenant-a", entryId: "entry-a" } });
|
||||
});
|
||||
|
||||
it("returns the existing entry for a repeated create mutation instead of creating a duplicate", async () => {
|
||||
const existing = {
|
||||
id: "entry-existing",
|
||||
tenantId: "tenant-a",
|
||||
projektId: "project-a",
|
||||
assignedUserId: "user-a",
|
||||
createdByUserId: "user-a",
|
||||
startAt: new Date("2026-07-21T07:00:00.000Z"),
|
||||
endAt: new Date("2026-07-21T09:00:00.000Z"),
|
||||
conflicts: [],
|
||||
};
|
||||
mocks.tx.tenantUser.findFirst.mockResolvedValue({ userId: "user-a" });
|
||||
mocks.tx.projekt.findFirst.mockResolvedValue(project());
|
||||
mocks.tx.scheduleEntry.findFirst.mockResolvedValue(existing);
|
||||
|
||||
await expect(
|
||||
upsertScheduleEntry({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["plantafel.write", "projects.read_all"]),
|
||||
projektId: "project-a",
|
||||
assignedUserId: "user-a",
|
||||
title: "Montage",
|
||||
startAt: "2026-07-21T09:00",
|
||||
endAt: "2026-07-21T11:00",
|
||||
clientMutationId: "stable-create-id",
|
||||
})
|
||||
).resolves.toMatchObject({ entry: { id: "entry-existing" }, conflicts: [] });
|
||||
|
||||
expect(mocks.tx.scheduleEntry.create).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.$executeRaw).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.tx.$executeRaw.mock.calls[0]?.[1]).toContain("plantafel:mutation");
|
||||
});
|
||||
|
||||
it("rejects hidden signature files before generating an acceptance PDF", async () => {
|
||||
mocks.tx.projekt.findFirst.mockResolvedValue(project());
|
||||
mocks.tx.file.findMany.mockResolvedValue([]);
|
||||
|
||||
await expect(
|
||||
submitAcceptanceProtocol({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["acceptance.write", "projects.read_all", "files.read_all"]),
|
||||
projectId: "project-a",
|
||||
signatures: [
|
||||
{ signerName: "Kunde", signerRole: "kunde", signatureFileId: "file-hidden" },
|
||||
{ signerName: "Monteur", signerRole: "monteur" },
|
||||
],
|
||||
})
|
||||
).rejects.toThrow();
|
||||
|
||||
expect(mocks.tx.file.findMany).toHaveBeenCalledWith({
|
||||
where: expect.objectContaining({ tenantId: "tenant-a", id: { in: ["file-hidden"] }, archivedAt: null }),
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.buildPdfExportArtifact).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("removes the uploaded acceptance PDF when the atomic database write fails", async () => {
|
||||
mocks.tx.projekt.findFirst.mockResolvedValue(project());
|
||||
mocks.tx.file.create.mockResolvedValue({ id: "file-created" });
|
||||
mocks.tx.fileEntityLink.create.mockResolvedValue({ id: "link-created" });
|
||||
mocks.tx.abnahmeProtokoll.create.mockRejectedValue(new Error("database write failed"));
|
||||
mocks.withStorageReservation.mockImplementationOnce(async (input) => {
|
||||
const stored = await input.upload();
|
||||
try {
|
||||
return await input.runTransaction((tx) => input.commit(tx, stored));
|
||||
} catch (error) {
|
||||
await input.rollbackUpload(stored);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
|
||||
await expect(
|
||||
submitAcceptanceProtocol({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["acceptance.write", "projects.read_all", "files.read_all"]),
|
||||
projectId: "project-a",
|
||||
signatures: [
|
||||
{ signerName: "Kunde", signerRole: "kunde" },
|
||||
{ signerName: "Monteur", signerRole: "monteur" },
|
||||
],
|
||||
})
|
||||
).rejects.toThrow("database write failed");
|
||||
|
||||
expect(mocks.putBufferAsFile).toHaveBeenCalledOnce();
|
||||
expect(mocks.withStorageReservation).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ reservation: expect.objectContaining({ tenantId: "tenant-a", actorUserId: "user-a", sizeBytes: 3 }) })
|
||||
);
|
||||
expect(mocks.tx.file.create).toHaveBeenCalledOnce();
|
||||
expect(mocks.deleteFile).toHaveBeenCalledWith({
|
||||
bucket: "test-bucket",
|
||||
key: expect.stringMatching(/^tenants\/tenant-a\/files\/file_.+\/original$/u),
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves an acceptance PDF when a lost commit response already persisted its protocol", async () => {
|
||||
const committed = { id: "protocol-committed", tenantId: "tenant-a", projektId: "project-a", signatures: [] };
|
||||
mocks.tx.projekt.findFirst.mockResolvedValue(project());
|
||||
mocks.tx.file.create.mockResolvedValue({ id: "file-created" });
|
||||
mocks.tx.fileEntityLink.create.mockResolvedValue({ id: "link-created" });
|
||||
mocks.tx.abnahmeProtokoll.create.mockRejectedValue(new Error("connection lost after commit"));
|
||||
mocks.tx.abnahmeProtokoll.findFirst.mockResolvedValue(committed);
|
||||
mocks.tx.abnahmeProtokoll.findUniqueOrThrow.mockResolvedValue(committed);
|
||||
|
||||
await expect(
|
||||
submitAcceptanceProtocol({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["acceptance.write", "projects.read_all", "files.read_all"]),
|
||||
projectId: "project-a",
|
||||
signatures: [
|
||||
{ signerName: "Kunde", signerRole: "kunde" },
|
||||
{ signerName: "Monteur", signerRole: "monteur" },
|
||||
],
|
||||
})
|
||||
).resolves.toMatchObject({ id: "protocol-committed" });
|
||||
|
||||
expect(mocks.tx.abnahmeProtokoll.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: expect.stringMatching(/^abn_/u),
|
||||
tenantId: "tenant-a",
|
||||
pdfFileId: expect.stringMatching(/^file_/u),
|
||||
},
|
||||
include: { signatures: true },
|
||||
});
|
||||
expect(mocks.deleteFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps an acceptance PDF when the post-error commit check is itself unavailable", async () => {
|
||||
mocks.tx.projekt.findFirst.mockResolvedValue(project());
|
||||
mocks.tx.file.create.mockResolvedValue({ id: "file-created" });
|
||||
mocks.tx.fileEntityLink.create.mockResolvedValue({ id: "link-created" });
|
||||
mocks.tx.abnahmeProtokoll.create.mockRejectedValue(new Error("connection lost after commit"));
|
||||
mocks.tx.abnahmeProtokoll.findFirst.mockRejectedValue(new Error("database unavailable"));
|
||||
|
||||
await expect(
|
||||
submitAcceptanceProtocol({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["acceptance.write", "projects.read_all", "files.read_all"]),
|
||||
projectId: "project-a",
|
||||
signatures: [
|
||||
{ signerName: "Kunde", signerRole: "kunde" },
|
||||
{ signerName: "Monteur", signerRole: "monteur" },
|
||||
],
|
||||
})
|
||||
).rejects.toThrow("connection lost after commit");
|
||||
|
||||
expect(mocks.deleteFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("publishes the rejected-acceptance stage transition to workflows and the portal mail debounce", async () => {
|
||||
const rejectedProject = { ...project(), projektleiterId: "lead-user" };
|
||||
const protocol = {
|
||||
id: "protocol-rejected",
|
||||
tenantId: "tenant-a",
|
||||
projektId: "project-a",
|
||||
signatures: [],
|
||||
};
|
||||
mocks.tx.projekt.findFirst.mockResolvedValue(rejectedProject);
|
||||
mocks.tx.projektChecklist.findFirst.mockResolvedValue({ id: "checklist-a" });
|
||||
mocks.tx.file.create.mockResolvedValue({ id: "file-created" });
|
||||
mocks.tx.fileEntityLink.create.mockResolvedValue({ id: "link-created" });
|
||||
mocks.tx.abnahmeProtokoll.create.mockResolvedValue(protocol);
|
||||
mocks.tx.abnahmeProtokoll.findUniqueOrThrow.mockResolvedValue(protocol);
|
||||
mocks.tx.abnahmeSignatur.createMany.mockResolvedValue({ count: 2 });
|
||||
mocks.tx.pipelineStage.findFirst.mockResolvedValue({ id: "stage-execution" });
|
||||
mocks.tx.projekt.update.mockResolvedValue({
|
||||
...rejectedProject,
|
||||
stageId: "stage-execution",
|
||||
});
|
||||
mocks.tx.projektStageChange.create.mockResolvedValue({ id: "stage-change-rejected" });
|
||||
|
||||
await submitAcceptanceProtocol({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["acceptance.write", "projects.read_all", "files.read_all"]),
|
||||
projectId: "project-a",
|
||||
maengelChecklistId: "checklist-a",
|
||||
defects: [{ title: "Kritischer Mangel", classification: "critical" }],
|
||||
signatures: [
|
||||
{ signerName: "Kunde", signerRole: "kunde" },
|
||||
{ signerName: "Monteur", signerRole: "monteur" },
|
||||
],
|
||||
});
|
||||
|
||||
expect(mocks.tx.projekt.update).toHaveBeenCalledWith({
|
||||
where: { id: "project-a", tenantId: "tenant-a" },
|
||||
data: { stageId: "stage-execution", wonAt: null, lostAt: null, lostReasonId: null },
|
||||
});
|
||||
expect(mocks.tx.projektStageChange.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
tenantId: "tenant-a",
|
||||
projektId: "project-a",
|
||||
fromStageId: "stage-a",
|
||||
toStageId: "stage-execution",
|
||||
changedByUserId: "user-a",
|
||||
}),
|
||||
});
|
||||
expect(mocks.publishOutboxEvent).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.publishOutboxEvent.mock.calls.map(([, event]) => event)).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
type: "workflow.trigger.event",
|
||||
payload: expect.objectContaining({ event: "project.stage_changed" }),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
type: "mail.portal-status.stage-changed",
|
||||
payload: expect.objectContaining({
|
||||
tenantId: "tenant-a",
|
||||
projectId: "project-a",
|
||||
previousStageId: "stage-a",
|
||||
expectedStageId: "stage-execution",
|
||||
stageChangeId: "stage-change-rejected",
|
||||
}),
|
||||
}),
|
||||
])
|
||||
);
|
||||
// R-P9b DoD 4 — the lead notification runs through M011 notify() on the
|
||||
// tenant-bound transaction client (RLS policy visible), not a raw insert.
|
||||
expect(mocks.tx.notificationDelivery.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
create: expect.objectContaining({
|
||||
tenantId: "tenant-a",
|
||||
userId: "lead-user",
|
||||
channel: "IN_APP",
|
||||
category: "projects",
|
||||
messageKey: "projects.notify.acceptance.rejected",
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("refuses content updates on saved acceptance protocols", async () => {
|
||||
await expect(updateAcceptanceProtocolContent()).rejects.toThrow("projects.error.acceptanceProtocolImmutable");
|
||||
});
|
||||
|
||||
it("does not read acceptance protocols when the central project scope denies the project", async () => {
|
||||
mocks.tx.projekt.findFirst.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
listAcceptanceProtocols({
|
||||
tenantId: "tenant-a",
|
||||
projectId: "project-denied",
|
||||
ctx: context(["acceptance.read", "projects.read_own"]),
|
||||
})
|
||||
).rejects.toThrow();
|
||||
|
||||
expect(mocks.tx.abnahmeProtokoll.findMany).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.projekt.findFirst).toHaveBeenCalledWith({
|
||||
where: expect.objectContaining({
|
||||
tenantId: "tenant-a",
|
||||
AND: expect.arrayContaining([{ id: "project-denied" }, expect.objectContaining({ AND: expect.any(Array) })]),
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it("edit-gates schedule status changes through the entry project", async () => {
|
||||
mocks.tx.scheduleEntry.findFirst.mockResolvedValue({
|
||||
id: "entry-a",
|
||||
projektId: "project-denied",
|
||||
assignedUserId: "user-a",
|
||||
status: "planned",
|
||||
startAt: new Date("2026-07-01T08:00:00.000Z"),
|
||||
endAt: new Date("2026-07-01T10:00:00.000Z"),
|
||||
});
|
||||
mocks.tx.projekt.findFirst.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
updateScheduleEntryStatus({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["plantafel.write", "projects.read_all"]),
|
||||
entryId: "entry-a",
|
||||
status: "done",
|
||||
})
|
||||
).rejects.toThrow();
|
||||
|
||||
expect(mocks.tx.scheduleEntry.update).not.toHaveBeenCalled();
|
||||
const projectWhere = mocks.tx.projekt.findFirst.mock.calls[0]?.[0]?.where;
|
||||
expect(JSON.stringify(projectWhere)).toContain("kannBearbeiten");
|
||||
});
|
||||
|
||||
it("serializes a cancelled entry reactivation and rejects a new double booking", async () => {
|
||||
const cancelled = {
|
||||
id: "entry-a",
|
||||
tenantId: "tenant-a",
|
||||
projektId: "project-a",
|
||||
assignedUserId: "user-a",
|
||||
status: "cancelled",
|
||||
startAt: new Date("2026-07-01T08:00:00.000Z"),
|
||||
endAt: new Date("2026-07-01T10:00:00.000Z"),
|
||||
};
|
||||
mocks.tx.scheduleEntry.findFirst.mockResolvedValue(cancelled);
|
||||
mocks.tx.projekt.findFirst.mockResolvedValue(project());
|
||||
mocks.tx.scheduleEntry.findMany.mockResolvedValue([
|
||||
{
|
||||
id: "entry-overlap",
|
||||
startAt: new Date("2026-07-01T09:00:00.000Z"),
|
||||
endAt: new Date("2026-07-01T11:00:00.000Z"),
|
||||
},
|
||||
]);
|
||||
|
||||
await expect(
|
||||
updateScheduleEntryStatus({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["plantafel.write", "projects.read_all"]),
|
||||
entryId: "entry-a",
|
||||
status: "planned",
|
||||
})
|
||||
).rejects.toThrow("projects.error.scheduleConflictOverrideRequired");
|
||||
|
||||
expect(mocks.tx.$executeRaw).toHaveBeenCalledTimes(2);
|
||||
expect(String(mocks.tx.$executeRaw.mock.calls[0]?.[0])).toContain("pg_advisory_xact_lock");
|
||||
expect(String(mocks.tx.$executeRaw.mock.calls[1]?.[0])).toContain('FROM "ScheduleEntry"');
|
||||
expect(mocks.tx.scheduleEntry.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("deduplicates bulk entry ids and rejects payloads above the hard cap", () => {
|
||||
expect(normalizeBulkScheduleEntryIds([" entry-a ", "entry-a", "", "entry-b"])).toEqual(["entry-a", "entry-b"]);
|
||||
expect(() => normalizeBulkScheduleEntryIds(Array.from({ length: PLANTAFEL_BULK_REASSIGN_MAX_ENTRIES + 1 }, (_, index) => `entry-${index}`))).toThrow(
|
||||
"foundation.mass_action_exceeds_limit"
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects a bulk assignee who is not an active user in the tenant", async () => {
|
||||
mocks.tx.tenantUser.findFirst.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
bulkReassignScheduleEntries({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["plantafel.bulk_reassign", "projects.read_all"]),
|
||||
entryIds: ["entry-a"],
|
||||
assignedUserId: "user-inactive",
|
||||
})
|
||||
).rejects.toThrow();
|
||||
|
||||
expect(mocks.tx.tenantUser.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
tenantId: "tenant-a",
|
||||
userId: "user-inactive",
|
||||
status: TenantUserStatus.ACTIVE,
|
||||
user: { active: true },
|
||||
},
|
||||
select: { userId: true },
|
||||
});
|
||||
expect(mocks.tx.scheduleEntry.findMany).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.scheduleEntry.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("batch-loads and batch-authorizes deduplicated bulk entries before updating", async () => {
|
||||
const startAt = new Date("2026-07-01T08:00:00.000Z");
|
||||
const endAt = new Date("2026-07-01T10:00:00.000Z");
|
||||
const laterStartAt = new Date("2026-07-01T11:00:00.000Z");
|
||||
const laterEndAt = new Date("2026-07-01T13:00:00.000Z");
|
||||
mocks.tx.tenantUser.findFirst.mockResolvedValue({ userId: "user-b" });
|
||||
mocks.tx.scheduleEntry.findMany
|
||||
.mockResolvedValueOnce([
|
||||
{ id: "entry-a", projektId: "project-a", startAt, endAt, status: "planned" },
|
||||
{ id: "entry-b", projektId: "project-b", startAt: laterStartAt, endAt: laterEndAt, status: "planned" },
|
||||
])
|
||||
.mockResolvedValue([]);
|
||||
mocks.tx.projekt.findMany.mockResolvedValue([{ id: "project-a" }, { id: "project-b" }]);
|
||||
mocks.tx.scheduleEntry.updateMany.mockResolvedValue({ count: 2 });
|
||||
mocks.tx.scheduleConflict.deleteMany.mockResolvedValue({ count: 0 });
|
||||
mocks.tx.scheduleConflict.createMany.mockResolvedValue({ count: 0 });
|
||||
|
||||
await expect(
|
||||
bulkReassignScheduleEntries({
|
||||
tenantId: "tenant-a",
|
||||
ctx: context(["plantafel.bulk_reassign", "projects.read_all"]),
|
||||
entryIds: ["entry-a", "entry-a", "entry-b"],
|
||||
assignedUserId: "user-b",
|
||||
})
|
||||
).resolves.toEqual({ updated: 2 });
|
||||
|
||||
expect(mocks.tx.scheduleEntry.findMany.mock.calls[0]?.[0]).toEqual({
|
||||
where: { id: { in: ["entry-a", "entry-b"] }, tenantId: "tenant-a", archivedAt: null },
|
||||
select: { id: true, projektId: true, startAt: true, endAt: true, status: true },
|
||||
});
|
||||
expect(mocks.tx.projekt.findMany).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.tx.projekt.findMany.mock.calls[0]?.[0]).toMatchObject({
|
||||
where: { tenantId: "tenant-a", id: { in: ["project-a", "project-b"] }, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(JSON.stringify(mocks.tx.projekt.findMany.mock.calls[0]?.[0]?.where)).toContain("kannBearbeiten");
|
||||
expect(mocks.tx.projekt.findFirst).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.scheduleEntry.update).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.scheduleEntry.updateMany).toHaveBeenCalledOnce();
|
||||
expect(mocks.tx.scheduleEntry.updateMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: { in: ["entry-a", "entry-b"] },
|
||||
tenantId: "tenant-a",
|
||||
projektId: { in: ["project-a", "project-b"] },
|
||||
archivedAt: null,
|
||||
},
|
||||
data: { assignedUserId: "user-b", syncStatus: "pending", conflictOverrideReason: null },
|
||||
});
|
||||
expect(mocks.tx.scheduleConflict.deleteMany).toHaveBeenCalledWith({
|
||||
where: { tenantId: "tenant-a", entryId: { in: ["entry-a", "entry-b"] } },
|
||||
});
|
||||
});
|
||||
|
||||
it("scopes protocol archival to the route project and its edit access", async () => {
|
||||
mocks.tx.projekt.findFirst.mockResolvedValue(project());
|
||||
mocks.tx.abnahmeProtokoll.findFirst.mockResolvedValue({ id: "protocol-a" });
|
||||
mocks.tx.abnahmeProtokoll.update.mockResolvedValue({ id: "protocol-a" });
|
||||
|
||||
await archiveAcceptanceProtocol({
|
||||
tenantId: "tenant-a",
|
||||
projectId: "project-a",
|
||||
protocolId: "protocol-a",
|
||||
ctx: context(["acceptance.admin", "projects.read_all"]),
|
||||
});
|
||||
|
||||
expect(mocks.tx.abnahmeProtokoll.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: "protocol-a",
|
||||
tenantId: "tenant-a",
|
||||
projektId: "project-a",
|
||||
archivedAt: null,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.tx.abnahmeProtokoll.update).toHaveBeenCalledWith({
|
||||
where: { id: "protocol-a", tenantId: "tenant-a" },
|
||||
data: { archivedAt: expect.any(Date) },
|
||||
});
|
||||
const projectWhere = mocks.tx.projekt.findFirst.mock.calls[0]?.[0]?.where;
|
||||
expect(JSON.stringify(projectWhere)).toContain("kannBearbeiten");
|
||||
});
|
||||
});
|
||||
+1006
-321
File diff suppressed because it is too large.
Load diff
+26
@@ -0,0 +1,26 @@
|
||||
// @vitest-environment node
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const SOURCES = [
|
||||
"auftragService.server.ts",
|
||||
"pipelineHandoverService.server.ts",
|
||||
"plantafelAcceptanceService.server.ts",
|
||||
"projectService.server.ts",
|
||||
"projektNotizService.server.ts",
|
||||
].map((file) => readFileSync(`apps/web/app/utils/integrations/projects/${file}`, "utf8"));
|
||||
|
||||
describe("project activity i18n contract", () => {
|
||||
it("persists semantic keys for every machine-authored project summary", () => {
|
||||
const summaries = SOURCES.flatMap((source) =>
|
||||
[...source.matchAll(/summaryText:\s*"([^"]+)"/gu)].map((match) => match[1]),
|
||||
);
|
||||
|
||||
expect(summaries).toContain("activity.runtime.projects.created");
|
||||
expect(summaries).toContain("activity.runtime.projects.handoverCompleted");
|
||||
expect(summaries).toContain("activity.runtime.projects.acceptanceSaved");
|
||||
expect(summaries.length).toBeGreaterThan(20);
|
||||
expect(summaries.every((summary) => summary.startsWith("activity.runtime.projects."))).toBe(true);
|
||||
});
|
||||
});
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
// A KWP-bound project refuses writes that HiveGrid does not own. That refusal
|
||||
// used to fall through projectActionErrorResponse and be rethrown, which turned
|
||||
// a board drag onto another column into a full-page 500 instead of a plain
|
||||
// message plus a card that snaps back.
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { KwpProjectDomainError } from "@hivegrid/integrations/kwp-project-domain.server";
|
||||
import { projectActionErrorResponse } from "./projectAccess.server";
|
||||
|
||||
describe("projectActionErrorResponse — KWP refusals", () => {
|
||||
it("answers a binding conflict with 400 and a plain-text key instead of crashing", async () => {
|
||||
const response = projectActionErrorResponse(new KwpProjectDomainError("binding_conflict"));
|
||||
expect(response.status).toBe(400);
|
||||
await expect(response.json()).resolves.toEqual({ error: "projects.error.kwp.binding_conflict" });
|
||||
});
|
||||
|
||||
it("keys every KWP code separately so each refusal can say what to do", async () => {
|
||||
for (const code of ["capability_paused", "stale_write", "routing_required"] as const) {
|
||||
const response = projectActionErrorResponse(new KwpProjectDomainError(code));
|
||||
expect(response.status).toBe(400);
|
||||
await expect(response.json()).resolves.toEqual({ error: `projects.error.kwp.${code}` });
|
||||
}
|
||||
});
|
||||
|
||||
it("still rethrows what it does not know — an unexpected fault must not read as a handled refusal", () => {
|
||||
const boom = new Error("boom");
|
||||
expect(() => projectActionErrorResponse(boom)).toThrow(boom);
|
||||
});
|
||||
});
|
||||
+56
-2
@@ -1,8 +1,10 @@
|
||||
import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
|
||||
import { KwpProjectDomainError } from "@hivegrid/integrations/kwp-project-domain.server";
|
||||
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 { db } from "~/utils/db.server";
|
||||
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { PROJECTS_MODULE_KEY } from "./projectRoutePaths";
|
||||
import { AuftragServiceError } from "./auftragService.server";
|
||||
@@ -13,6 +15,13 @@ export type ProjectRouteContext = ProjectVisibilityContext & {
|
||||
hasModule: boolean;
|
||||
};
|
||||
|
||||
export const PROJECT_READ_PERMISSIONS = [
|
||||
"projects.read_all",
|
||||
"projects.read_own",
|
||||
"projects.read_own_pl",
|
||||
"projects.read_own_member",
|
||||
] as const;
|
||||
|
||||
export async function loadProjectContext({
|
||||
request,
|
||||
params,
|
||||
@@ -27,14 +36,23 @@ export async function loadProjectContext({
|
||||
if (!tenantId || !userInfo.userId) {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
const [hasModule, permissions] = await Promise.all([
|
||||
const [hasModule, permissions, roleAssignments, groupMemberships] = await Promise.all([
|
||||
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: PROJECTS_MODULE_KEY }),
|
||||
getPermissionsByUser(userInfo.userId, tenantId),
|
||||
db.userRole.findMany({ where: { tenantId, userId: userInfo.userId }, select: { roleId: true } }),
|
||||
db.groupUser.findMany({ where: { userId: userInfo.userId, group: { tenantId } }, select: { groupId: true } }),
|
||||
]);
|
||||
if (requireModule && !hasModule) {
|
||||
throw new CatalogError(foundationErrors.notFound, { module: PROJECTS_MODULE_KEY });
|
||||
}
|
||||
return { tenantId, userId: userInfo.userId, permissions, hasModule };
|
||||
return {
|
||||
tenantId,
|
||||
userId: userInfo.userId,
|
||||
permissions,
|
||||
roleIds: roleAssignments.map(({ roleId }) => roleId),
|
||||
groupIds: groupMemberships.map(({ groupId }) => groupId),
|
||||
hasModule,
|
||||
};
|
||||
}
|
||||
|
||||
export function requireProjectPermission(ctx: ProjectRouteContext, permission: string): ProjectRouteContext {
|
||||
@@ -42,6 +60,36 @@ export function requireProjectPermission(ctx: ProjectRouteContext, permission: s
|
||||
return ctx;
|
||||
}
|
||||
|
||||
/** 404 for a route the caller may not see (Bauprinzip A.5.3: Permission-Denied
|
||||
* renders 404, not 403 — and never a 500). */
|
||||
export function projectNotFoundResponse(): Response {
|
||||
return new Response("Not Found", { status: 404 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Loader-side access guard: resolves the project context and renders a graceful
|
||||
* 404 when the projects module is off OR the viewer lacks the required
|
||||
* permission(s) — instead of letting the underlying CatalogError surface as a
|
||||
* 500. Auth redirects from loadProjectContext propagate untouched (module is not
|
||||
* required here, so requireAuth's redirect Response is not swallowed). Use in
|
||||
* LOADERS only; actions keep throwing so projectActionErrorResponse can map them.
|
||||
*/
|
||||
export async function requireProjectView(
|
||||
args: { request: Request; params: Record<string, string | undefined> },
|
||||
permission: string | readonly string[],
|
||||
): Promise<ProjectRouteContext> {
|
||||
const ctx = await loadProjectContext({ request: args.request, params: args.params, requireModule: false });
|
||||
if (!ctx.hasModule) {
|
||||
throw projectNotFoundResponse();
|
||||
}
|
||||
try {
|
||||
return Array.isArray(permission) ? requireAnyProjectPermission(ctx, permission) : requireProjectPermission(ctx, permission as string);
|
||||
} catch (error) {
|
||||
if (error instanceof Response) throw error;
|
||||
throw projectNotFoundResponse();
|
||||
}
|
||||
}
|
||||
|
||||
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");
|
||||
@@ -58,5 +106,11 @@ export function projectActionErrorResponse(error: unknown): Response {
|
||||
if (error instanceof AuftragServiceError) {
|
||||
return Response.json({ error: error.messageKey }, { status: 400 });
|
||||
}
|
||||
// A KWP-bound project refuses writes HiveGrid does not own. That is a normal
|
||||
// "no" for the actor, not a crash: rethrowing turned a drag onto another board
|
||||
// column into a full-page 500 instead of a message plus a card that snaps back.
|
||||
if (error instanceof KwpProjectDomainError) {
|
||||
return Response.json({ error: `projects.error.kwp.${error.code}` }, { status: 400 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
// R-P8b (RA-C2) — real live board pub/sub. Uses the repo's existing in-process
|
||||
// EventEmitter (`~/utils/stream/emitter.server`, the same one that already backs
|
||||
// the workflow-execution SSE stream) so board mutations (stage move, bulk move,
|
||||
// create, update, undo, archive) push real change-events to the connected
|
||||
// pipeline-board SSE clients instead of only a snapshot + heartbeat. No new infra
|
||||
// dependency is introduced.
|
||||
//
|
||||
// Scope caveat: this emitter is per web process. With a single web instance (the
|
||||
// current deployment) every board client shares the process, so events reach all
|
||||
// of them. Horizontal scaling of `hivegrid-web` would need a cross-process
|
||||
// transport (e.g. Redis pub/sub) behind the same publish/subscribe API — tracked
|
||||
// as a follow-up, out of this ticket's scope. This is server-only (.server) and
|
||||
// is never imported by projectService.server (kept out of the pure-service test
|
||||
// import graph) — publishing happens in the route-level orchestration helpers.
|
||||
|
||||
import { publishDashboardChange } from "~/services/dashboard/dashboardEvents.server";
|
||||
import { emitter } from "~/utils/stream/emitter.server";
|
||||
import type { ProjectBoardChange, ProjectBoardChangeType } from "./projectBoardEvents.shared";
|
||||
|
||||
/**
|
||||
* In-process channel name for one pipeline board. Includes the tenantId as
|
||||
* defence-in-depth even though pipeline ids are already globally unique — a
|
||||
* subscriber only ever binds to its own tenant+pipeline channel.
|
||||
*/
|
||||
export function projectBoardChannel(tenantId: string, pipelineId: string): string {
|
||||
return `projectBoard:${tenantId}:${pipelineId}`;
|
||||
}
|
||||
|
||||
let listenerCapRaised = false;
|
||||
|
||||
/** Subscribe an SSE stream to a pipeline board channel. Returns an unsubscribe fn. */
|
||||
export function subscribeToProjectBoard(tenantId: string, pipelineId: string, onChange: (payload: string) => void): () => void {
|
||||
// Many concurrent board viewers can subscribe to the same channel; lift the
|
||||
// default 10-listener cap so Node does not log a MaxListenersExceededWarning.
|
||||
if (!listenerCapRaised) {
|
||||
emitter.setMaxListeners(0);
|
||||
listenerCapRaised = true;
|
||||
}
|
||||
const channel = projectBoardChannel(tenantId, pipelineId);
|
||||
emitter.on(channel, onChange);
|
||||
return () => {
|
||||
emitter.off(channel, onChange);
|
||||
};
|
||||
}
|
||||
|
||||
/** Publish a board change so connected clients of this pipeline board revalidate. */
|
||||
export function publishProjectBoardChange(input: {
|
||||
tenantId: string;
|
||||
pipelineId: string;
|
||||
projectId?: string;
|
||||
type: ProjectBoardChangeType;
|
||||
}): void {
|
||||
const payload: ProjectBoardChange = {
|
||||
type: input.type,
|
||||
pipelineId: input.pipelineId,
|
||||
projectId: input.projectId,
|
||||
at: new Date().toISOString(),
|
||||
};
|
||||
emitter.emit(projectBoardChannel(input.tenantId, input.pipelineId), JSON.stringify(payload));
|
||||
// Project mutations also feed the tenant-wide dashboard stream (R-P11b):
|
||||
// sales/project KPI widgets recompute their snapshot on these changes.
|
||||
publishDashboardChange({ tenantId: input.tenantId, source: "projects" });
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
// R-P8b (RA-C2) — pure shared contract for the live pipeline-board SSE stream.
|
||||
// No server imports (no emitter/config), so it is safe to import from the client
|
||||
// board hook as well as the server publish/subscribe helper. Keeps the SSE event
|
||||
// name and change-payload shape in one place for both sides of the wire.
|
||||
|
||||
/** SSE event name the board stream sends and the client hook listens for. */
|
||||
export const PROJECT_BOARD_SSE_EVENT = "projects.board.changed";
|
||||
|
||||
export type ProjectBoardChangeType = "created" | "stage_changed" | "updated" | "stage_change_undone" | "archived";
|
||||
|
||||
export interface ProjectBoardChange {
|
||||
readonly type: ProjectBoardChangeType;
|
||||
readonly pipelineId: string;
|
||||
readonly projectId?: string;
|
||||
readonly at: string;
|
||||
}
|
||||
+349
@@ -0,0 +1,349 @@
|
||||
// R-P8b (P8 configurable Kanban) Interim-UI (AD-28) — shared server helper for
|
||||
// the board routes (`/projects` and `/projects/pipelines/:id`). Builds the
|
||||
// KanbanBoardVM from projectService.loadProjectBoard + resolved owner labels +
|
||||
// lost reasons, and handles the board actions (stage move, bulk move, undo,
|
||||
// quick-create). Server-only (.server) — never imported by a component.
|
||||
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import { buildBoardFacetsVM, buildKanbanVM, type BoardFacetsVM, type KanbanBoardVM, type PipelineHandoverVM } from "@hivegrid/view-models";
|
||||
import { isDemoDataUiEnabled } from "~/utils/services/.server/demoDataUi.server";
|
||||
import { resolveUserLabels } from "~/utils/integrations/crm/crmService.server";
|
||||
import {
|
||||
archiveProject,
|
||||
bulkMoveProjectStage,
|
||||
createProject,
|
||||
duplicateProject,
|
||||
listLostReasons,
|
||||
loadBoardAssigneeOptions,
|
||||
loadProjectTagOptions,
|
||||
loadProjectBoard,
|
||||
moveProjectStage,
|
||||
moveProjectToPipeline,
|
||||
redoLastProjectStageChange,
|
||||
undoLastProjectStageChange,
|
||||
} from "./projectService.server";
|
||||
import {
|
||||
parseFacetList,
|
||||
parseOwnerList,
|
||||
parsePeriodList,
|
||||
PROJECT_CUSTOMER_TYPES,
|
||||
PROJECT_VALUE_BANDS,
|
||||
type ProjectFacetFilters,
|
||||
} from "./projectFilterFacets";
|
||||
import { executeProjectHandover, parseHandoverSelection } from "./pipelineHandoverService.server";
|
||||
import { loadHandoverVM } from "./pipelineHandoverRoute.server";
|
||||
import { projectNotFoundResponse, type ProjectRouteContext } from "./projectAccess.server";
|
||||
import { projectDetailPath, projectPipelineStreamPath, projectsExportPath, projectsListPath } from "./projectRoutePaths";
|
||||
import { publishProjectBoardChange } from "./projectBoardEvents.server";
|
||||
|
||||
export type KanbanLoaderData = {
|
||||
/** Pipeline name — shell breadcrumb title (Tenant > Boards > <Pipeline>). */
|
||||
title: string;
|
||||
tenantSlug: string;
|
||||
vm: KanbanBoardVM;
|
||||
pipelineId: string;
|
||||
onlyMine: boolean;
|
||||
q: string;
|
||||
includeDemoData: boolean;
|
||||
/** Whether the demo-data toggle may be shown at all (staging/dev only). */
|
||||
demoDataUiEnabled: boolean;
|
||||
/** CSV export of exactly what the board currently shows (same resource the list uses). */
|
||||
exportHref: string;
|
||||
/** List view of the same board and filters — the header view switch target. */
|
||||
listHref: string;
|
||||
/** WF-P8 S01 filter bar: facet dropdowns + active-filter chips. */
|
||||
facets: BoardFacetsVM;
|
||||
/** Raw facet selection, echoed back so the screen can toggle single values. */
|
||||
facetSelection: {
|
||||
owners: string[];
|
||||
customerTypes: string[];
|
||||
periods: string[];
|
||||
periodFrom: string;
|
||||
periodTo: string;
|
||||
valueBands: string[];
|
||||
};
|
||||
};
|
||||
|
||||
export async function loadKanbanData({
|
||||
tenantSlug,
|
||||
tenantId,
|
||||
ctx,
|
||||
pipelineId,
|
||||
onlyMine,
|
||||
includeDemoData,
|
||||
q,
|
||||
facets,
|
||||
locale,
|
||||
}: {
|
||||
tenantSlug: string;
|
||||
tenantId: string;
|
||||
ctx: ProjectRouteContext;
|
||||
pipelineId?: string | null;
|
||||
onlyMine: boolean;
|
||||
includeDemoData: boolean;
|
||||
q?: string | null;
|
||||
facets?: ProjectFacetFilters;
|
||||
locale?: string;
|
||||
}): Promise<KanbanLoaderData> {
|
||||
// Outside staging/dev the `demo=show` query param is ignored server-side —
|
||||
// hiding the checkbox alone would leave demo rows reachable via URL.
|
||||
const demoDataUiEnabled = isDemoDataUiEnabled(undefined, { tenantId, tenantSlug });
|
||||
const withDemoData = demoDataUiEnabled && includeDemoData;
|
||||
const [board, lostReasons] = await Promise.all([
|
||||
// An unknown/unreadable pipelineId (e.g. a stale link that put a project id in
|
||||
// the pipeline slot) must render 404, not surface the CatalogError as a 500.
|
||||
loadProjectBoard({ tenantId, ctx, pipelineId, onlyMine, includeDemoData: withDemoData, q, facets }).catch((error) => {
|
||||
if (error instanceof CatalogError) throw projectNotFoundResponse();
|
||||
throw error;
|
||||
}),
|
||||
listLostReasons({ tenantId }),
|
||||
]);
|
||||
|
||||
const ownerIds = board.columns.flatMap((column) => column.cards.map((card) => card.ownerUserId)).filter((id): id is string => Boolean(id));
|
||||
const [ownerLabels, assignees, tagOptions] = await Promise.all([
|
||||
resolveUserLabels(ownerIds),
|
||||
loadBoardAssigneeOptions({ tenantId, ctx, pipelineId: board.pipeline.id, includeDemoData: withDemoData }),
|
||||
loadProjectTagOptions(tenantId),
|
||||
]);
|
||||
|
||||
const vm = buildKanbanVM({
|
||||
locale,
|
||||
board,
|
||||
lostReasons: lostReasons.map((reason) => ({ id: reason.id, name: reason.name })),
|
||||
ownerLabels,
|
||||
buildDetailHref: (projectId) => projectDetailPath(tenantSlug, projectId),
|
||||
sseHref: projectPipelineStreamPath(tenantSlug, board.pipeline.id),
|
||||
perms: {
|
||||
canWrite: ctx.permissions.includes("projects.write"),
|
||||
canChangeStage: ctx.permissions.includes("projects.change_stage"),
|
||||
canAdmin: ctx.permissions.includes("projects.admin"),
|
||||
canDelete: ctx.permissions.includes("projects.delete"),
|
||||
},
|
||||
});
|
||||
|
||||
// The CSV resource is shared with the list view; the board contributes the
|
||||
// filters it actually has (pipeline, search, only-mine, demo).
|
||||
const exportParams = new URLSearchParams();
|
||||
exportParams.set("pipelineId", board.pipeline.id);
|
||||
if (q) exportParams.set("q", q);
|
||||
if (onlyMine) exportParams.set("onlyMine", "1");
|
||||
if (withDemoData) exportParams.set("demo", "show");
|
||||
|
||||
const facetsVM = buildBoardFacetsVM({
|
||||
assignees: assignees.options,
|
||||
hasUnassigned: assignees.hasUnassigned,
|
||||
tags: tagOptions,
|
||||
selected: {
|
||||
owners: facets?.owners ?? [],
|
||||
customerTypes: facets?.customerTypes ?? [],
|
||||
tagIds: facets?.tagIds ?? [],
|
||||
periods: facets?.periods ?? [],
|
||||
valueBands: facets?.valueBands ?? [],
|
||||
},
|
||||
onlyMine,
|
||||
q: q ?? "",
|
||||
canFilterByValue: ctx.permissions.includes("deals.read_volume_all"),
|
||||
});
|
||||
|
||||
return {
|
||||
title: board.pipeline.name,
|
||||
tenantSlug,
|
||||
vm,
|
||||
pipelineId: board.pipeline.id,
|
||||
onlyMine,
|
||||
q: q ?? "",
|
||||
includeDemoData: withDemoData,
|
||||
demoDataUiEnabled,
|
||||
exportHref: `${projectsExportPath(tenantSlug)}?${exportParams.toString()}`,
|
||||
// Switching to the list keeps the board and its filters — the list names the
|
||||
// board in its headline, so losing the pipeline here would rename the page.
|
||||
listHref: `${projectsListPath(tenantSlug)}?${exportParams.toString()}`,
|
||||
facets: facetsVM,
|
||||
facetSelection: {
|
||||
owners: [...(facets?.owners ?? [])],
|
||||
customerTypes: [...(facets?.customerTypes ?? [])],
|
||||
periods: [...(facets?.periods ?? [])],
|
||||
periodFrom: facets?.periodFrom ?? "",
|
||||
periodTo: facets?.periodTo ?? "",
|
||||
valueBands: [...(facets?.valueBands ?? [])],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* WF-P8 S03: the board a list URL is bound to. The list shows one board (the
|
||||
* flow index dropped the cross-board list), so an absent or stale pipelineId
|
||||
* has to resolve rather than widen the result to every board. Same order the
|
||||
* kanban board falls back in: default board first, then the first visible one.
|
||||
*
|
||||
* Pure, so the list screen and the CSV resource cannot drift apart on which
|
||||
* board they mean.
|
||||
*/
|
||||
export function pickListPipeline<T extends { id: string; isDefault: boolean }>(
|
||||
pipelines: readonly T[],
|
||||
requestedPipelineId: string | null
|
||||
): T | null {
|
||||
return (
|
||||
pipelines.find((pipeline) => pipeline.id === requestedPipelineId) ??
|
||||
pipelines.find((pipeline) => pipeline.isDefault) ??
|
||||
pipelines[0] ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
/** Parse the WF-P8 S01 facet query parameters off a board URL. */
|
||||
export function parseBoardFacetParams(params: URLSearchParams): ProjectFacetFilters {
|
||||
return {
|
||||
owners: parseOwnerList(params.get("owner")),
|
||||
customerTypes: parseFacetList(params.get("kundentyp"), PROJECT_CUSTOMER_TYPES),
|
||||
// Tag ids are tenant data, so they parse like the owner list: unknown ids
|
||||
// simply match nothing instead of rejecting the URL.
|
||||
tagIds: parseOwnerList(params.get("tags")),
|
||||
periods: parsePeriodList(params.get("zeitraum")),
|
||||
periodFrom: params.get("von"),
|
||||
periodTo: params.get("bis"),
|
||||
valueBands: parseFacetList(params.get("wert"), PROJECT_VALUE_BANDS),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Permission required per board intent — used by the route actions so the
|
||||
* pre-check stays in one place (create/duplicate = write, archive = delete,
|
||||
* everything else = stage change).
|
||||
*/
|
||||
export function kanbanIntentPermission(intent: string | null): string {
|
||||
switch (intent) {
|
||||
case "createProject":
|
||||
case "duplicateProject":
|
||||
return "projects.write";
|
||||
case "archiveProject":
|
||||
return "projects.delete";
|
||||
case "handoverProject":
|
||||
return "projects.handover";
|
||||
default:
|
||||
return "projects.change_stage";
|
||||
}
|
||||
}
|
||||
|
||||
/** Handle a board intent. Returns the created project id for "createProject"
|
||||
* (so the route can redirect), else null, plus the M04 payload when the move
|
||||
* just put the project into a stage that offers a pipeline handover. Throws on
|
||||
* failure. */
|
||||
export async function handleKanbanIntent({
|
||||
intent,
|
||||
form,
|
||||
tenantId,
|
||||
ctx,
|
||||
}: {
|
||||
intent: string | null;
|
||||
form: FormData;
|
||||
tenantId: string;
|
||||
ctx: ProjectRouteContext;
|
||||
}): Promise<{ createdProjectId: string | null; handover?: PipelineHandoverVM | null }> {
|
||||
const str = (name: string): string | null => {
|
||||
const value = form.get(name);
|
||||
return typeof value === "string" ? value : null;
|
||||
};
|
||||
switch (intent) {
|
||||
case "moveStage": {
|
||||
const moved = await moveProjectStage({
|
||||
tenantId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
projectId: str("projectId") ?? "",
|
||||
targetStageId: str("targetStageId") ?? "",
|
||||
lostReasonId: str("lostReasonId") || null,
|
||||
notiz: str("notiz") || null,
|
||||
});
|
||||
// Push a real live change-event so every connected board client for this
|
||||
// pipeline revalidates immediately.
|
||||
publishProjectBoardChange({ tenantId, pipelineId: moved.pipelineId, projectId: moved.id, type: "stage_changed" });
|
||||
// M04 is triggered by the move, not by a button (D-P8: "Erreicht eine
|
||||
// Karte die letzte Stage […], oeffnet sich M04 automatisch"). The board
|
||||
// asks right here, so the dialog opens over the board the card was
|
||||
// dropped on instead of waiting for someone to open the project.
|
||||
return { createdProjectId: null, handover: await loadHandoverVM({ tenantId, projectId: moved.id, ctx }) };
|
||||
}
|
||||
case "bulkMoveStage": {
|
||||
const ids = (str("projectIds") ?? "").split(",").map((id) => id.trim()).filter(Boolean);
|
||||
const { pipelineIds } = await bulkMoveProjectStage({
|
||||
tenantId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
projectIds: ids,
|
||||
targetStageId: str("targetStageId") ?? "",
|
||||
lostReasonId: str("lostReasonId") || null,
|
||||
});
|
||||
for (const pipelineId of pipelineIds) {
|
||||
publishProjectBoardChange({ tenantId, pipelineId, type: "stage_changed" });
|
||||
}
|
||||
return { createdProjectId: null };
|
||||
}
|
||||
case "undoStage": {
|
||||
const restored = await undoLastProjectStageChange({ tenantId, userId: ctx.userId, ctx, projectId: str("projectId") ?? "" });
|
||||
publishProjectBoardChange({ tenantId, pipelineId: restored.pipelineId, projectId: restored.id, type: "stage_change_undone" });
|
||||
return { createdProjectId: null };
|
||||
}
|
||||
case "moveToPipeline": {
|
||||
const { project, previousPipelineId } = await moveProjectToPipeline({
|
||||
tenantId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
projectId: str("projectId") ?? "",
|
||||
targetPipelineId: str("targetPipelineId") ?? "",
|
||||
});
|
||||
// The card leaves one board and appears on the other, so both open
|
||||
// boards have to redraw.
|
||||
publishProjectBoardChange({ tenantId, pipelineId: previousPipelineId, projectId: project.id, type: "archived" });
|
||||
publishProjectBoardChange({ tenantId, pipelineId: project.pipelineId, projectId: project.id, type: "created" });
|
||||
return { createdProjectId: null };
|
||||
}
|
||||
case "redoStage": {
|
||||
const reapplied = await redoLastProjectStageChange({ tenantId, userId: ctx.userId, ctx, projectId: str("projectId") ?? "" });
|
||||
publishProjectBoardChange({ tenantId, pipelineId: reapplied.pipelineId, projectId: reapplied.id, type: "stage_changed" });
|
||||
return { createdProjectId: null };
|
||||
}
|
||||
case "createProject": {
|
||||
const project = await createProject({
|
||||
tenantId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
projektname: str("projektname") ?? "",
|
||||
potenziellerAuftragswert: str("potenziellerAuftragswert") || null,
|
||||
// Quick-create lands on the board the user is currently viewing, not the
|
||||
// default sales pipeline. Empty/absent -> service falls back to default.
|
||||
pipelineId: str("pipelineId") || null,
|
||||
zustaendigePersonId: ctx.userId,
|
||||
});
|
||||
publishProjectBoardChange({ tenantId, pipelineId: project.pipelineId, projectId: project.id, type: "created" });
|
||||
return { createdProjectId: project.id };
|
||||
}
|
||||
case "duplicateProject": {
|
||||
const copy = await duplicateProject({ tenantId, userId: ctx.userId, ctx, projectId: str("projectId") ?? "" });
|
||||
publishProjectBoardChange({ tenantId, pipelineId: copy.pipelineId, projectId: copy.id, type: "created" });
|
||||
return { createdProjectId: null };
|
||||
}
|
||||
case "archiveProject": {
|
||||
const archived = await archiveProject({ tenantId, userId: ctx.userId, ctx, projectId: str("projectId") ?? "" });
|
||||
publishProjectBoardChange({ tenantId, pipelineId: archived.pipelineId, projectId: archived.id, type: "archived" });
|
||||
return { createdProjectId: null };
|
||||
}
|
||||
case "handoverProject": {
|
||||
const projectId = str("projectId") ?? "";
|
||||
const result = await executeProjectHandover({
|
||||
tenantId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
projectId,
|
||||
selection: parseHandoverSelection(str("selection")),
|
||||
});
|
||||
// The card leaves this board and appears on the successor's, so both
|
||||
// redraw — same shape as a manual board change.
|
||||
publishProjectBoardChange({ tenantId, pipelineId: str("fromPipelineId") ?? "", projectId, type: "archived" });
|
||||
publishProjectBoardChange({ tenantId, pipelineId: result.toPipelineId, projectId, type: "created" });
|
||||
return { createdProjectId: null, handover: null };
|
||||
}
|
||||
default:
|
||||
return { createdProjectId: null };
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
// WF-P8 S02 "Adressdaten" — payload parsing of the `updateAddresses` intent.
|
||||
// The section posts all three slots in one JSON field, and `null` for a slot is
|
||||
// a real instruction (clear it), so the parser has to keep that apart from
|
||||
// "slot not mentioned" and from a payload it cannot read at all.
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { parseAddressSlots } from "./projectDetailRoute.server";
|
||||
|
||||
describe("parseAddressSlots", () => {
|
||||
it("keeps a null slot as an explicit clear and leaves absent slots untouched", () => {
|
||||
const parsed = parseAddressSlots(JSON.stringify({ projekt: { strasse: "Hauptstr.", ort: "Freiburg" }, rechnung: null }));
|
||||
expect(parsed.projekt).toEqual({ strasse: "Hauptstr.", hausnummer: undefined, plz: undefined, ort: "Freiburg", land: undefined });
|
||||
expect("rechnung" in parsed).toBe(true);
|
||||
expect(parsed.rechnung).toBeNull();
|
||||
expect("bauherr" in parsed).toBe(false);
|
||||
});
|
||||
|
||||
it("writes nothing for a payload it cannot read instead of clearing every slot", () => {
|
||||
for (const raw of [null, "", "not json", "[]", '"projekt"']) {
|
||||
expect(parseAddressSlots(raw)).toEqual({});
|
||||
}
|
||||
});
|
||||
|
||||
it("carries the slot extras, including the ones only one slot shows", () => {
|
||||
const parsed = parseAddressSlots(
|
||||
JSON.stringify({
|
||||
projekt: { ort: "Freiburg", zufahrt: "Hofeinfahrt", notizen: "Anlieferung 7-16 Uhr" },
|
||||
rechnung: { ort: "Freiburg", rechnungsEmail: "rechnung@example.de", zahlungsziel: "30 Tage" },
|
||||
bauherr: { ort: "Freiburg", telefon: "+49 761 1", ansprechpartnerVorOrt: "Frau Schneider", postErwuenscht: true },
|
||||
})
|
||||
);
|
||||
expect(parsed.projekt).toMatchObject({ zufahrt: "Hofeinfahrt", notizen: "Anlieferung 7-16 Uhr" });
|
||||
expect(parsed.rechnung).toMatchObject({ rechnungsEmail: "rechnung@example.de", zahlungsziel: "30 Tage" });
|
||||
expect(parsed.bauherr).toMatchObject({ telefon: "+49 761 1", ansprechpartnerVorOrt: "Frau Schneider", postErwuenscht: true });
|
||||
});
|
||||
|
||||
it("leaves an extra undefined when the slot did not post it, so omission cannot clear it", () => {
|
||||
const parsed = parseAddressSlots(JSON.stringify({ projekt: { ort: "Freiburg" } }));
|
||||
expect(parsed.projekt?.notizen).toBeUndefined();
|
||||
expect(parsed.projekt?.rechnungsEmail).toBeUndefined();
|
||||
expect(parsed.projekt?.postErwuenscht).toBeUndefined();
|
||||
});
|
||||
|
||||
it("drops unknown slots and non-string members", () => {
|
||||
const parsed = parseAddressSlots(JSON.stringify({ lieferung: { ort: "Freiburg" }, projekt: { ort: 42, plz: "79098" } }));
|
||||
expect(Object.keys(parsed)).toEqual(["projekt"]);
|
||||
expect(parsed.projekt).toEqual({ strasse: undefined, hausnummer: undefined, plz: "79098", ort: undefined, land: undefined });
|
||||
});
|
||||
});
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
// WF-P8 S02 contact cards — which master-data rows a card gets. The row set
|
||||
// follows the contact type, and unset fields must not become "—" rows, so this
|
||||
// is worth pinning independently of the screen.
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { contactStammdatenRows } from "./projectDetailRoute.server";
|
||||
import type { ProjektKontaktDetail } from "./projectService.server";
|
||||
|
||||
function kontakt(over: Partial<ProjektKontaktDetail> = {}): ProjektKontaktDetail {
|
||||
return {
|
||||
id: "pk1",
|
||||
kontaktId: "c1",
|
||||
kontaktTyp: "organisation",
|
||||
rolle: "auftraggeber",
|
||||
primaer: true,
|
||||
label: "Weber GmbH",
|
||||
email: null,
|
||||
telefon: null,
|
||||
website: null,
|
||||
ustIdNr: null,
|
||||
handelsregister: null,
|
||||
kundennummer: null,
|
||||
kundeSeit: null,
|
||||
branche: null,
|
||||
mitarbeiterzahl: null,
|
||||
position: null,
|
||||
erreichbarkeit: null,
|
||||
portalInviteEligible: false,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
describe("contactStammdatenRows", () => {
|
||||
it("keeps only the company fields that are set, in export order", () => {
|
||||
const rows = contactStammdatenRows(
|
||||
kontakt({ website: "https://weber.test", branche: "SHK", mitarbeiterzahl: 24, kundeSeit: new Date("2021-03-04T00:00:00.000Z") })
|
||||
);
|
||||
expect(rows).toEqual([
|
||||
{ labelKey: "projects.detail.contacts.website", value: "https://weber.test" },
|
||||
{ labelKey: "projects.detail.contacts.customerSince", value: "2021-03-04" },
|
||||
{ labelKey: "projects.detail.contacts.industry", value: "SHK" },
|
||||
{ labelKey: "projects.detail.contacts.headcount", value: "24" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("gives a person the person fields, never the company ones", () => {
|
||||
const rows = contactStammdatenRows(
|
||||
kontakt({ kontaktTyp: "privatperson", position: "Einkauf", erreichbarkeit: "Mo-Do", branche: "SHK", ustIdNr: "DE1" })
|
||||
);
|
||||
expect(rows).toEqual([
|
||||
{ labelKey: "projects.detail.contacts.position", value: "Einkauf" },
|
||||
{ labelKey: "projects.detail.contacts.availability", value: "Mo-Do" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("drops blank and whitespace-only values instead of rendering empty rows", () => {
|
||||
expect(contactStammdatenRows(kontakt({ website: " ", branche: "" }))).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps a headcount of zero, which is a value and not a missing field", () => {
|
||||
expect(contactStammdatenRows(kontakt({ mitarbeiterzahl: 0 }))).toEqual([
|
||||
{ labelKey: "projects.detail.contacts.headcount", value: "0" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
+633
@@ -0,0 +1,633 @@
|
||||
// R-P8a (P8 Projekt core) Interim-UI (AD-28) — server helper for the project
|
||||
// detail (`/projects/:id`). Builds the P8 ProjektDetailVM + ActivityStreamVM
|
||||
// from projectService + the tenant-scoped Activity timeline and handles the P8
|
||||
// action intents (stammdaten inline-edit, stage move, 24h-undo). Server-only
|
||||
// (.server) — never imported by a component. The P9 (auftrag/signature) parts
|
||||
// of the route stay untouched; this only augments the P8 core section.
|
||||
|
||||
import {
|
||||
buildActivityStreamVM,
|
||||
buildProjektDetailVM,
|
||||
datentypLabelKey,
|
||||
type ActivityStreamVM,
|
||||
type ProjectMemberRole,
|
||||
type ProjektDetailVM,
|
||||
} from "@hivegrid/view-models";
|
||||
import { loadKwpProjectPanel } from "@hivegrid/integrations/kwp-project-domain.server";
|
||||
import { canUsePortalInvitationEntrypoint } from "~/services/customer-portal/portal-invitation-entrypoint.server";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { companyDetailPath, contactDetailPath } from "~/utils/integrations/crm/crmRoutePaths";
|
||||
import { createKontakt, listAssignableUsers, resolveUserLabels } from "~/utils/integrations/crm/crmService.server";
|
||||
import { getCustomFieldValues, listCustomFieldDefinitions } from "~/utils/integrations/crm/customFieldService.server";
|
||||
import type { ProjectRouteContext } from "./projectAccess.server";
|
||||
import { publishProjectBoardChange } from "./projectBoardEvents.server";
|
||||
import { listProjectNotes, toProjektNotizContext } from "./projektNotizService.server";
|
||||
import {
|
||||
linkProjektKontakt,
|
||||
unlinkProjektKontakt,
|
||||
loadProjectDetail,
|
||||
moveProjectStage,
|
||||
PROJECT_ADDRESS_SLOTS,
|
||||
setProjectCustomFieldValue,
|
||||
undoLastProjectStageChange,
|
||||
updateProjectAddresses,
|
||||
updateProjectStammdaten,
|
||||
type ProjectAddressInput,
|
||||
type ProjectAddressSlot,
|
||||
type ProjektKontaktDetail,
|
||||
} from "./projectService.server";
|
||||
|
||||
const ACTIVITY_LIMIT = 50;
|
||||
/** Rows per rail tile: the rail is a glance, the modules below are the full list. */
|
||||
const RAIL_LIMIT = 8;
|
||||
/** Polymorphic CustomFieldValue entity type for the project core (ENTITY-MODEL Domäne 5). */
|
||||
const PROJEKT_CUSTOM_FIELD_ENTITY = "projekt" as const;
|
||||
|
||||
type ActivityDbRow = {
|
||||
id: string;
|
||||
createdAt: Date;
|
||||
actorUserId: string | null;
|
||||
actorKind: string;
|
||||
activityType: string;
|
||||
summaryText: string;
|
||||
};
|
||||
|
||||
function decimalToDisplay(value: unknown): string | null {
|
||||
if (value == null) return null;
|
||||
const num = typeof value === "number" ? value : Number(String(value));
|
||||
if (!Number.isFinite(num)) return null;
|
||||
return num.toFixed(2);
|
||||
}
|
||||
|
||||
type MemberDbRow = { id: string; userId: string; rolle: ProjectMemberRole };
|
||||
|
||||
/**
|
||||
* WF-P8 S02 "Planung und Verantwortliche" needs the member rows with their raw
|
||||
* user ids to drive the two people pickers, which the P9 operations VM drops in
|
||||
* favour of a display label. Group principals stay out: the section offers
|
||||
* pickers over named persons, groups remain editable in the operations panel.
|
||||
*/
|
||||
async function loadProjectUserMembers(tenantId: string, projectId: string): Promise<MemberDbRow[]> {
|
||||
const rows = await withTenantRLS(tenantId, (tx) =>
|
||||
tx.projektMitglied.findMany({
|
||||
where: { tenantId, projektId: projectId, archivedAt: null, userId: { not: null } },
|
||||
orderBy: { createdAt: "asc" },
|
||||
select: { id: true, userId: true, rolle: true },
|
||||
})
|
||||
);
|
||||
return rows.flatMap((row) => (row.userId ? [{ id: row.id, userId: row.userId, rolle: row.rolle as ProjectMemberRole }] : []));
|
||||
}
|
||||
|
||||
/**
|
||||
* WF-P8 S02 "Letzter Kontakt" on the contact cards. Derived, never stored: the
|
||||
* timeline already holds every touch (mail, call, note), and a stored column
|
||||
* would be a second truth that drifts the moment one writer forgets it.
|
||||
*
|
||||
* Contacts and companies use different subject types in the timeline, so both
|
||||
* are queried and the newest entry per contact id wins.
|
||||
*/
|
||||
async function loadLastContactTouch(tenantId: string, kontaktIds: readonly string[]): Promise<Map<string, string>> {
|
||||
if (kontaktIds.length === 0) return new Map();
|
||||
const rows = await withTenantRLS(tenantId, (tx) =>
|
||||
tx.activity.findMany({
|
||||
where: { tenantId, subjectType: { in: ["contact", "company"] }, subjectId: { in: [...kontaktIds] } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: { subjectId: true, createdAt: true },
|
||||
})
|
||||
);
|
||||
const newest = new Map<string, string>();
|
||||
for (const row of rows) {
|
||||
if (!newest.has(row.subjectId)) newest.set(row.subjectId, row.createdAt.toISOString());
|
||||
}
|
||||
return newest;
|
||||
}
|
||||
|
||||
/**
|
||||
* WF-P8 S02 rail: the project's stage history. `ProjektStageChange` already keeps
|
||||
* every move, so the rail reads it instead of a second log — and it reads it
|
||||
* read-only: moving a stage stays the board's and the header's job.
|
||||
*/
|
||||
async function loadStageHistory(
|
||||
tenantId: string,
|
||||
projectId: string,
|
||||
stageNameById: Map<string, string>
|
||||
): Promise<{ id: string; label: string; atIso: string; actorUserId: string | null }[]> {
|
||||
const rows = await withTenantRLS(tenantId, (tx) =>
|
||||
tx.projektStageChange.findMany({
|
||||
where: { tenantId, projektId: projectId, undoneAt: null },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: RAIL_LIMIT,
|
||||
select: { id: true, fromStageId: true, toStageId: true, createdAt: true, changedByUserId: true },
|
||||
})
|
||||
);
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
label: `${stageNameById.get(row.fromStageId) ?? row.fromStageId} → ${stageNameById.get(row.toStageId) ?? row.toStageId}`,
|
||||
atIso: row.createdAt.toISOString(),
|
||||
actorUserId: row.changedByUserId,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* WF-P8 S02 rail: the next appointments and the open tasks of this project.
|
||||
*
|
||||
* Read here rather than reused from the P9 operations view model, because that
|
||||
* one formats an assignee as the bare user id (`principalLabel`) — fine for a
|
||||
* panel that shows it next to a picker, useless in a rail line. These rows carry
|
||||
* the ids so the caller can resolve them with the labels it already fetches.
|
||||
*/
|
||||
async function loadRailAgenda(
|
||||
tenantId: string,
|
||||
projectId: string
|
||||
): Promise<{
|
||||
appointments: { id: string; titel: string; startAt: Date; userId: string | null }[];
|
||||
tasks: { id: string; title: string; deadline: Date | null; userId: string | null }[];
|
||||
}> {
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
const [appointments, tasks] = await Promise.all([
|
||||
tx.projektTermin.findMany({
|
||||
where: { tenantId, projektId: projectId, archivedAt: null },
|
||||
orderBy: { startAt: "asc" },
|
||||
take: RAIL_LIMIT,
|
||||
select: { id: true, titel: true, startAt: true, assignedToUserId: true },
|
||||
}),
|
||||
tx.task.findMany({
|
||||
where: { tenantId, linkedEntityType: "project", linkedEntityId: projectId, archivedAt: null, status: { not: "done" } },
|
||||
orderBy: [{ deadline: "asc" }, { createdAt: "desc" }],
|
||||
take: RAIL_LIMIT,
|
||||
select: { id: true, title: true, deadline: true, assignedToUserId: true },
|
||||
}),
|
||||
]);
|
||||
return {
|
||||
appointments: appointments.map((row) => ({ id: row.id, titel: row.titel, startAt: row.startAt, userId: row.assignedToUserId })),
|
||||
tasks: tasks.map((row) => ({ id: row.id, title: row.title, deadline: row.deadline, userId: row.assignedToUserId })),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** S02 KWP block. The module owns the binding, so it owns the read as well. */
|
||||
async function loadKwpPanel(tenantId: string, projectId: string) {
|
||||
return withTenantRLS(tenantId, (tx) => loadKwpProjectPanel(tx as never, tenantId, projectId));
|
||||
}
|
||||
|
||||
async function loadProjectActivities(tenantId: string, projectId: string): Promise<ActivityDbRow[]> {
|
||||
const rows = await withTenantRLS(tenantId, (tx) =>
|
||||
tx.activity.findMany({
|
||||
where: { tenantId, subjectType: "project", subjectId: projectId },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: ACTIVITY_LIMIT + 1,
|
||||
select: { id: true, createdAt: true, actorUserId: true, actorKind: true, activityType: true, summaryText: true },
|
||||
})
|
||||
);
|
||||
return rows as ActivityDbRow[];
|
||||
}
|
||||
|
||||
export type ProjektCustomFieldDef = { id: string; key: string; label: string; datentyp: string; datentypLabelKey: string };
|
||||
|
||||
/** One rail entry: a line plus its timestamp and, where known, its author. */
|
||||
export type ProjektRailEntry = { id: string; label: string; meta: string | null; atIso: string | null };
|
||||
|
||||
/**
|
||||
* The read-only content of the S02 rail tiles the screen cannot derive from the
|
||||
* detail VM. Read-only on purpose: the editors for appointments, tasks and notes
|
||||
* live in the operations panel further down the same route, and a second editor
|
||||
* over the same rows is how the two drift apart. A second *view* does not have
|
||||
* that problem.
|
||||
*/
|
||||
export type ProjektDetailRailAreas = {
|
||||
history: ProjektRailEntry[];
|
||||
notes: ProjektRailEntry[];
|
||||
appointments: ProjektRailEntry[];
|
||||
tasks: ProjektRailEntry[];
|
||||
};
|
||||
|
||||
export type ProjektDetailP8Data = {
|
||||
detailVM: ProjektDetailVM;
|
||||
activityVM: ActivityStreamVM;
|
||||
ownerOptions: { id: string; label: string }[];
|
||||
customFieldDefs: ProjektCustomFieldDef[];
|
||||
railAreas: ProjektDetailRailAreas;
|
||||
};
|
||||
|
||||
export async function loadProjektDetailP8({
|
||||
tenantId,
|
||||
tenantSlug,
|
||||
projectId,
|
||||
ctx,
|
||||
nowIso,
|
||||
locale,
|
||||
}: {
|
||||
tenantId: string;
|
||||
/** Needed for the S02 contact cards, which link into the CRM detail screens. */
|
||||
tenantSlug: string;
|
||||
projectId: string;
|
||||
ctx: ProjectRouteContext;
|
||||
nowIso: string;
|
||||
locale?: string;
|
||||
}): Promise<ProjektDetailP8Data> {
|
||||
const detail = await loadProjectDetail({ tenantId, projectId, ctx });
|
||||
const canBrowseTenantMembers = ctx.permissions.includes("projects.write") || ctx.permissions.includes("app.settings.members.view");
|
||||
const canReadCrm = ctx.permissions.includes("crm.read_all") || ctx.permissions.includes("crm.read_own");
|
||||
const [activityRows, memberRows, kwpPanel, ownerOptions, customFieldValues, customFieldDefinitions, canInviteToPortal] = await Promise.all([
|
||||
loadProjectActivities(tenantId, projectId),
|
||||
loadProjectUserMembers(tenantId, projectId),
|
||||
loadKwpPanel(tenantId, projectId),
|
||||
canBrowseTenantMembers ? listAssignableUsers(tenantId) : Promise.resolve([]),
|
||||
getCustomFieldValues({ tenantId, entityType: PROJEKT_CUSTOM_FIELD_ENTITY, entityId: projectId }),
|
||||
listCustomFieldDefinitions({ tenantId, entityType: PROJEKT_CUSTOM_FIELD_ENTITY }),
|
||||
canUsePortalInvitationEntrypoint(ctx),
|
||||
]);
|
||||
|
||||
const stageNameById = new Map(detail.stages.map((stage) => [stage.id, stage.name]));
|
||||
const [lastTouchByKontaktId, stageHistory, noteRows, agenda] = await Promise.all([
|
||||
loadLastContactTouch(
|
||||
tenantId,
|
||||
detail.kontakte.map((kontakt) => kontakt.kontaktId)
|
||||
),
|
||||
loadStageHistory(tenantId, projectId, stageNameById),
|
||||
// The note reader owns the visibility scope, so an internal note stays out of
|
||||
// the rail for somebody who may not read it.
|
||||
listProjectNotes({ tenantId, projectId, ctx: toProjektNotizContext(ctx) }).catch(() => []),
|
||||
loadRailAgenda(tenantId, projectId),
|
||||
]);
|
||||
const actorIds = activityRows.map((row) => row.actorUserId).filter((id): id is string => Boolean(id));
|
||||
const userLabels = await resolveUserLabels(
|
||||
[
|
||||
detail.project.zustaendigePersonId,
|
||||
detail.project.projektleiterId,
|
||||
...memberRows.map((row) => row.userId),
|
||||
...actorIds,
|
||||
...stageHistory.map((entry) => entry.actorUserId),
|
||||
...noteRows.map((note) => note.autorUserId),
|
||||
...agenda.appointments.map((appointment) => appointment.userId),
|
||||
...agenda.tasks.map((task) => task.userId),
|
||||
].filter((id): id is string => Boolean(id))
|
||||
);
|
||||
|
||||
const detailVM = buildProjektDetailVM({
|
||||
locale,
|
||||
project: {
|
||||
id: detail.project.id,
|
||||
projektNummer: detail.project.projektNummer,
|
||||
projektname: detail.project.projektname,
|
||||
beschreibung: detail.project.beschreibung,
|
||||
prioritaet: detail.project.prioritaet,
|
||||
stageId: detail.project.stageId,
|
||||
startDatumIso: detail.project.startDatum?.toISOString() ?? null,
|
||||
projekttyp: detail.project.projekttyp,
|
||||
quelle: detail.project.quelle,
|
||||
promotion: detail.project.promotion,
|
||||
email: detail.project.email,
|
||||
telefon: detail.project.telefon,
|
||||
fax: detail.project.fax,
|
||||
deadlineIso: detail.project.deadline?.toISOString() ?? null,
|
||||
zustaendigePersonId: detail.project.zustaendigePersonId,
|
||||
projektleiterId: detail.project.projektleiterId,
|
||||
konvertiertAusLeadId: detail.project.konvertiertAusLeadId,
|
||||
wonAtIso: detail.project.wonAt?.toISOString() ?? null,
|
||||
lostAtIso: detail.project.lostAt?.toISOString() ?? null,
|
||||
undoStageChangeUntilIso: detail.project.undoStageChangeUntil?.toISOString() ?? null,
|
||||
lostReasonId: detail.project.lostReasonId,
|
||||
},
|
||||
pipelineName: detail.pipeline.name,
|
||||
pipelineTypHint: detail.pipeline.typHint,
|
||||
stages: detail.stages.map((stage) => ({
|
||||
id: stage.id,
|
||||
name: stage.name,
|
||||
stageKind: stage.stageKind,
|
||||
winProbability: stage.winProbability,
|
||||
color: stage.color,
|
||||
})),
|
||||
kontakte: detail.kontakte.map((kontakt) => ({
|
||||
id: kontakt.id,
|
||||
kontaktId: kontakt.kontaktId,
|
||||
kontaktTyp: kontakt.kontaktTyp,
|
||||
rolle: kontakt.rolle,
|
||||
primaer: kontakt.primaer,
|
||||
label: kontakt.label,
|
||||
email: kontakt.email,
|
||||
telefon: kontakt.telefon,
|
||||
// Only offered with a CRM read permission. `crm.read_own` can still land
|
||||
// on a 404 for someone else's contact — that is the module's own owner
|
||||
// gate, and hiding the link entirely would cost the common case.
|
||||
stammdaten: contactStammdatenRows(kontakt),
|
||||
notizen: kontakt.notizen,
|
||||
durchwahl: kontakt.durchwahl,
|
||||
mobil: kontakt.mobil,
|
||||
fax: kontakt.fax,
|
||||
adresseLabel: kontakt.adresseLabel,
|
||||
lastContactAtIso: lastTouchByKontaktId.get(kontakt.kontaktId) ?? null,
|
||||
detailHref: canReadCrm
|
||||
? kontakt.kontaktTyp === "organisation"
|
||||
? companyDetailPath(tenantSlug, kontakt.kontaktId)
|
||||
: contactDetailPath(tenantSlug, kontakt.kontaktId)
|
||||
: null,
|
||||
portalInviteEligible: kontakt.portalInviteEligible,
|
||||
})),
|
||||
lostReasons: detail.lostReasons.map((reason) => ({ id: reason.id, name: reason.name })),
|
||||
adressen: detail.adressen,
|
||||
kwp: kwpPanel,
|
||||
customFields: customFieldValues.map((cf) => ({
|
||||
definitionId: cf.definition.id,
|
||||
key: cf.definition.key,
|
||||
label: cf.definition.label,
|
||||
datentyp: cf.definition.datentyp,
|
||||
wert: cf.wert,
|
||||
optionen: cf.definition.optionen,
|
||||
})),
|
||||
value: detail.canViewVolume ? decimalToDisplay(detail.project.potenziellerAuftragswert) : null,
|
||||
orderVolume: detail.canViewVolume ? decimalToDisplay(detail.project.auftragsvolumen) : null,
|
||||
valueVisible: detail.canViewVolume,
|
||||
ownerLabel: detail.project.zustaendigePersonId ? (userLabels.get(detail.project.zustaendigePersonId) ?? null) : null,
|
||||
projektleiterLabel: detail.project.projektleiterId ? (userLabels.get(detail.project.projektleiterId) ?? null) : null,
|
||||
mitglieder: memberRows.map((row) => ({
|
||||
id: row.id,
|
||||
userId: row.userId,
|
||||
rolle: row.rolle,
|
||||
label: userLabels.get(row.userId) ?? row.userId,
|
||||
})),
|
||||
perms: {
|
||||
canWrite: hasPerm(ctx.permissions, "projects.write"),
|
||||
canChangeStage: hasPerm(ctx.permissions, "projects.change_stage"),
|
||||
canInviteToPortal,
|
||||
canManageMembers: hasPerm(ctx.permissions, "projects.manage_members"),
|
||||
},
|
||||
nowIso,
|
||||
});
|
||||
|
||||
const activityVM = buildActivityStreamVM({
|
||||
rows: activityRows.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 customFieldDefs: ProjektCustomFieldDef[] = customFieldDefinitions.map((def) => ({
|
||||
id: def.id,
|
||||
key: def.key,
|
||||
label: def.label,
|
||||
datentyp: def.datentyp,
|
||||
datentypLabelKey: datentypLabelKey(def.datentyp),
|
||||
}));
|
||||
|
||||
const railAreas: ProjektDetailRailAreas = {
|
||||
history: stageHistory.map((entry) => ({
|
||||
id: entry.id,
|
||||
label: entry.label,
|
||||
meta: entry.actorUserId ? (userLabels.get(entry.actorUserId) ?? null) : null,
|
||||
atIso: entry.atIso,
|
||||
})),
|
||||
appointments: agenda.appointments.map((appointment) => ({
|
||||
id: appointment.id,
|
||||
label: appointment.titel,
|
||||
meta: appointment.userId ? (userLabels.get(appointment.userId) ?? null) : null,
|
||||
atIso: appointment.startAt.toISOString(),
|
||||
})),
|
||||
tasks: agenda.tasks.map((task) => ({
|
||||
id: task.id,
|
||||
label: task.title,
|
||||
meta: task.userId ? (userLabels.get(task.userId) ?? null) : null,
|
||||
atIso: task.deadline?.toISOString() ?? null,
|
||||
})),
|
||||
notes: noteRows.slice(0, RAIL_LIMIT).map((note) => ({
|
||||
id: note.id,
|
||||
label: note.inhalt,
|
||||
// The visibility is part of the line: "nur ich" next to a note is what
|
||||
// tells the author that nobody else is reading it.
|
||||
meta: [note.autorUserId ? userLabels.get(note.autorUserId) : null, note.sichtbarkeit].filter(Boolean).join(" · ") || null,
|
||||
atIso: note.createdAt.toISOString(),
|
||||
})),
|
||||
};
|
||||
|
||||
return { detailVM, activityVM, ownerOptions, customFieldDefs, railAreas };
|
||||
}
|
||||
|
||||
function hasPerm(permissions: readonly string[], permission: string): boolean {
|
||||
return permissions.includes(permission);
|
||||
}
|
||||
|
||||
/**
|
||||
* WF-P8 S02 contact cards: the master-data rows below the channels. Only fields
|
||||
* that are actually set become rows — an empty card of "—" labels tells nobody
|
||||
* anything. Company fields go on the organisation card, person fields on the
|
||||
* Ansprechpartner card, so a card never shows the other kind's empty slots.
|
||||
*/
|
||||
export function contactStammdatenRows(kontakt: ProjektKontaktDetail): { labelKey: string; value: string }[] {
|
||||
const candidates: [string, string | null][] =
|
||||
kontakt.kontaktTyp === "organisation"
|
||||
? [
|
||||
["projects.detail.contacts.website", kontakt.website],
|
||||
["projects.detail.contacts.vatId", kontakt.ustIdNr],
|
||||
["projects.detail.contacts.tradeRegister", kontakt.handelsregister],
|
||||
["projects.detail.contacts.customerNumber", kontakt.kundennummer],
|
||||
["projects.detail.contacts.customerSince", kontakt.kundeSeit ? kontakt.kundeSeit.toISOString().slice(0, 10) : null],
|
||||
["projects.detail.contacts.industry", kontakt.branche],
|
||||
["projects.detail.contacts.headcount", kontakt.mitarbeiterzahl === null ? null : String(kontakt.mitarbeiterzahl)],
|
||||
]
|
||||
: [
|
||||
["projects.detail.contacts.position", kontakt.position],
|
||||
["projects.detail.contacts.availability", kontakt.erreichbarkeit],
|
||||
];
|
||||
return candidates.flatMap(([labelKey, value]) => {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed ? [{ labelKey, value: trimmed }] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the S02 address payload. Unknown slots and non-string members are
|
||||
* dropped; `null` for a slot is meaningful (clear it), so it survives. A
|
||||
* malformed payload writes nothing rather than clearing every slot.
|
||||
*/
|
||||
export function parseAddressSlots(raw: string | null): Partial<Record<ProjectAddressSlot, ProjectAddressInput | null>> {
|
||||
if (!raw) return {};
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};
|
||||
const out: Partial<Record<ProjectAddressSlot, ProjectAddressInput | null>> = {};
|
||||
for (const slot of PROJECT_ADDRESS_SLOTS) {
|
||||
if (!(slot in parsed)) continue;
|
||||
const value = (parsed as Record<string, unknown>)[slot];
|
||||
if (value === null) {
|
||||
out[slot] = null;
|
||||
continue;
|
||||
}
|
||||
if (typeof value !== "object" || Array.isArray(value)) continue;
|
||||
const record = value as Record<string, unknown>;
|
||||
const pick = (key: string): string | undefined => (typeof record[key] === "string" ? (record[key] as string) : undefined);
|
||||
out[slot] = {
|
||||
strasse: pick("strasse"),
|
||||
hausnummer: pick("hausnummer"),
|
||||
plz: pick("plz"),
|
||||
ort: pick("ort"),
|
||||
land: pick("land"),
|
||||
// Slot extras (ProjektAdressDetail). Absent members stay undefined so a
|
||||
// slot that never shows a field cannot clear it by omission.
|
||||
bauabschnitt: pick("bauabschnitt"),
|
||||
zufahrt: pick("zufahrt"),
|
||||
koordinaten: pick("koordinaten"),
|
||||
empfaenger: pick("empfaenger"),
|
||||
zahlungsziel: pick("zahlungsziel"),
|
||||
rechnungsEmail: pick("rechnungsEmail"),
|
||||
postErwuenscht: typeof record.postErwuenscht === "boolean" ? record.postErwuenscht : undefined,
|
||||
telefon: pick("telefon"),
|
||||
ansprechpartnerVorOrt: pick("ansprechpartnerVorOrt"),
|
||||
notizen: pick("notizen"),
|
||||
};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Handle a P8 detail intent. Returns true if the intent was a P8 one (handled),
|
||||
* false if it should fall through to the existing P9 action switch. Throws
|
||||
* ProjectServiceError/CatalogError on failure (caller maps to a Response). */
|
||||
export async function handleProjektDetailP8Intent({
|
||||
intent,
|
||||
form,
|
||||
tenantId,
|
||||
projectId,
|
||||
ctx,
|
||||
}: {
|
||||
intent: string | null;
|
||||
form: FormData;
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
ctx: ProjectRouteContext;
|
||||
}): Promise<boolean> {
|
||||
const str = (name: string): string | null => {
|
||||
const value = form.get(name);
|
||||
return typeof value === "string" ? value : null;
|
||||
};
|
||||
switch (intent) {
|
||||
case "updateStammdaten": {
|
||||
const updated = await updateProjectStammdaten({
|
||||
tenantId,
|
||||
projectId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
projektname: str("projektname") ?? undefined,
|
||||
beschreibung: form.has("beschreibung") ? str("beschreibung") : undefined,
|
||||
prioritaet: (str("prioritaet") as never) ?? undefined,
|
||||
potenziellerAuftragswert: form.has("potenziellerAuftragswert") ? str("potenziellerAuftragswert") : undefined,
|
||||
auftragsvolumen: form.has("auftragsvolumen") ? str("auftragsvolumen") : undefined,
|
||||
startDatum: form.has("startDatum") ? str("startDatum") : undefined,
|
||||
deadline: form.has("deadline") ? str("deadline") : undefined,
|
||||
zustaendigePersonId: form.has("zustaendigePersonId") ? str("zustaendigePersonId") : undefined,
|
||||
projektleiterId: form.has("projektleiterId") ? str("projektleiterId") : undefined,
|
||||
projekttyp: form.has("projekttyp") ? str("projekttyp") : undefined,
|
||||
quelle: form.has("quelle") ? str("quelle") : undefined,
|
||||
promotion: form.has("promotion") ? str("promotion") : undefined,
|
||||
email: form.has("email") ? str("email") : undefined,
|
||||
telefon: form.has("telefon") ? str("telefon") : undefined,
|
||||
fax: form.has("fax") ? str("fax") : undefined,
|
||||
});
|
||||
// A detail-edit changes a board card (owner/value/priority) — publish a live
|
||||
// board change so any open pipeline board revalidates.
|
||||
publishProjectBoardChange({ tenantId, pipelineId: updated.pipelineId, projectId: updated.id, type: "updated" });
|
||||
return true;
|
||||
}
|
||||
case "updateAddresses": {
|
||||
// One JSON field carries all three slots: the section saves them together
|
||||
// and a slot is a small record, not a flat list of form fields.
|
||||
const updated = await updateProjectAddresses({
|
||||
tenantId,
|
||||
projectId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
slots: parseAddressSlots(str("slots")),
|
||||
});
|
||||
publishProjectBoardChange({ tenantId, pipelineId: updated.pipelineId, projectId: updated.id, type: "updated" });
|
||||
return true;
|
||||
}
|
||||
case "linkKontakt": {
|
||||
// WF-P8 S02 "Bestehende Firma / Kontakt durchsuchen": the picked contact.
|
||||
await linkProjektKontakt({
|
||||
tenantId,
|
||||
projectId,
|
||||
kontaktId: str("kontaktId") ?? "",
|
||||
rolle: (str("rolle") as never) ?? undefined,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
case "unlinkKontakt": {
|
||||
// WF-P8 S02: the contact leaves this project, not the CRM.
|
||||
await unlinkProjektKontakt({
|
||||
tenantId,
|
||||
projectId,
|
||||
projektKontaktId: str("projektKontaktId") ?? "",
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
case "createKontakt": {
|
||||
// "Neuen Kontakt erstellen" / "Neue Firma erstellen" — one intent, because
|
||||
// the only difference is the contact type and which name field is filled.
|
||||
// The contact itself is created through the CRM service, so a project never
|
||||
// becomes a second place where contacts are born.
|
||||
const kontaktTyp = str("kontaktTyp") === "organisation" ? "organisation" : "privatperson";
|
||||
const email = str("email")?.trim() ?? "";
|
||||
const kontakt = await createKontakt({
|
||||
tenantId,
|
||||
userId: ctx.userId ?? "",
|
||||
kontaktTyp,
|
||||
vorname: kontaktTyp === "privatperson" ? str("vorname") : null,
|
||||
nachname: kontaktTyp === "privatperson" ? str("nachname") : null,
|
||||
orgName: kontaktTyp === "organisation" ? str("orgName") : null,
|
||||
emails: email ? [{ email, primaer: true }] : [],
|
||||
});
|
||||
await linkProjektKontakt({
|
||||
tenantId,
|
||||
projectId,
|
||||
kontaktId: kontakt.id,
|
||||
rolle: (str("rolle") as never) ?? undefined,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
case "moveStage": {
|
||||
const moved = await moveProjectStage({
|
||||
tenantId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
projectId,
|
||||
targetStageId: str("targetStageId") ?? "",
|
||||
lostReasonId: str("lostReasonId") || null,
|
||||
notiz: str("notiz") || null,
|
||||
});
|
||||
publishProjectBoardChange({ tenantId, pipelineId: moved.pipelineId, projectId: moved.id, type: "stage_changed" });
|
||||
return true;
|
||||
}
|
||||
case "undoStage": {
|
||||
const restored = await undoLastProjectStageChange({ tenantId, userId: ctx.userId, ctx, projectId });
|
||||
publishProjectBoardChange({ tenantId, pipelineId: restored.pipelineId, projectId: restored.id, type: "stage_change_undone" });
|
||||
return true;
|
||||
}
|
||||
case "setCustomField": {
|
||||
await setProjectCustomFieldValue({
|
||||
tenantId,
|
||||
userId: ctx.userId,
|
||||
ctx,
|
||||
projectId,
|
||||
definitionId: str("definitionId") ?? "",
|
||||
wert: str("wert"),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
// WF-P8 S01 — the date and money maths behind the board facets. Pure, so it is
|
||||
// tested without a database.
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildOwnerWhere,
|
||||
buildPeriodWhere,
|
||||
buildValueBandWhere,
|
||||
parseFacetList,
|
||||
parseOwnerList,
|
||||
parsePeriodKey,
|
||||
PROJECT_CUSTOMER_TYPES,
|
||||
PROJECT_VALUE_BANDS,
|
||||
resolvePeriodRange,
|
||||
resolvePeriodRanges,
|
||||
UNASSIGNED_OWNER,
|
||||
} from "./projectFilterFacets";
|
||||
|
||||
describe("parseFacetList", () => {
|
||||
it("keeps only known options and drops duplicates", () => {
|
||||
expect(parseFacetList("privatperson,unfug,privatperson,oeffentlich", PROJECT_CUSTOMER_TYPES)).toEqual([
|
||||
"privatperson",
|
||||
"oeffentlich",
|
||||
]);
|
||||
});
|
||||
|
||||
it("treats a missing or empty parameter as no selection", () => {
|
||||
expect(parseFacetList(null, PROJECT_VALUE_BANDS)).toEqual([]);
|
||||
expect(parseFacetList("", PROJECT_VALUE_BANDS)).toEqual([]);
|
||||
});
|
||||
|
||||
it("takes the first period key only", () => {
|
||||
expect(parsePeriodKey("month,week")).toBe("month");
|
||||
expect(parsePeriodKey("quartal")).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps arbitrary owner ids but drops blanks", () => {
|
||||
expect(parseOwnerList("u1, ,u2,u1")).toEqual(["u1", "u2"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolvePeriodRange", () => {
|
||||
// Wednesday, 2026-07-29.
|
||||
const now = new Date(2026, 6, 29, 14, 30);
|
||||
|
||||
it("spans Monday to Sunday for the current week", () => {
|
||||
const range = resolvePeriodRange("week", now)!;
|
||||
expect(range.from.getDate()).toBe(27);
|
||||
expect(range.to.getDate()).toBe(2); // Sunday, already in August
|
||||
expect(range.to.getMonth()).toBe(7);
|
||||
});
|
||||
|
||||
it("spans the first to the last day of the current month", () => {
|
||||
const range = resolvePeriodRange("month", now)!;
|
||||
expect(range.from.getDate()).toBe(1);
|
||||
expect(range.to.getDate()).toBe(31);
|
||||
});
|
||||
|
||||
it("spans today plus 30 days", () => {
|
||||
const range = resolvePeriodRange("next30", now)!;
|
||||
expect(range.from.getDate()).toBe(29);
|
||||
expect(range.to.getMonth()).toBe(7);
|
||||
expect(range.to.getDate()).toBe(28);
|
||||
});
|
||||
|
||||
it("refuses a half-open or inverted custom range instead of inventing an end", () => {
|
||||
expect(resolvePeriodRange("custom", now, { from: "2026-07-01", to: null })).toBeNull();
|
||||
expect(resolvePeriodRange("custom", now, { from: "2026-08-01", to: "2026-07-01" })).toBeNull();
|
||||
expect(resolvePeriodRange("custom", now, { from: "nonsense", to: "2026-07-01" })).toBeNull();
|
||||
});
|
||||
|
||||
it("accepts a well-formed custom range and closes it at end of day", () => {
|
||||
const range = resolvePeriodRange("custom", now, { from: "2026-07-01", to: "2026-07-15" })!;
|
||||
expect(range.from.getDate()).toBe(1);
|
||||
expect(range.to.getDate()).toBe(15);
|
||||
expect(range.to.getHours()).toBe(23);
|
||||
});
|
||||
|
||||
it("is no filter without a period", () => {
|
||||
expect(resolvePeriodRange(null, now)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildPeriodWhere", () => {
|
||||
it("matches projects that start, end or span the range, and no undated ones", () => {
|
||||
const where = buildPeriodWhere({ from: new Date(2026, 6, 1), to: new Date(2026, 6, 31) });
|
||||
const alternatives = where.OR as Record<string, unknown>[];
|
||||
expect(alternatives).toHaveLength(3);
|
||||
expect(alternatives[0]).toHaveProperty("startDatum");
|
||||
expect(alternatives[1]).toHaveProperty("deadline");
|
||||
// No alternative admits a project without both dates.
|
||||
expect(JSON.stringify(alternatives)).not.toContain("null");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildValueBandWhere", () => {
|
||||
it("is no filter without a band", () => {
|
||||
expect(buildValueBandWhere([])).toBeNull();
|
||||
});
|
||||
|
||||
it("uses the confirmed volume and falls back to the estimate, like the card", () => {
|
||||
const where = buildValueBandWhere(["10k_30k"])!;
|
||||
const [band] = where.OR as Record<string, unknown>[];
|
||||
const [confirmed, fallback] = (band!.OR as Record<string, any>[]);
|
||||
expect(confirmed!.auftragsvolumen).toEqual({ gte: 10_000, lt: 30_000 });
|
||||
expect(fallback!.AND[0]).toEqual({ auftragsvolumen: null });
|
||||
expect(fallback!.AND[1]).toEqual({ potenziellerAuftragswert: { gte: 10_000, lt: 30_000 } });
|
||||
});
|
||||
|
||||
it("leaves the top band open-ended", () => {
|
||||
const where = buildValueBandWhere(["ueber60k"])!;
|
||||
const [band] = where.OR as Record<string, unknown>[];
|
||||
const [confirmed] = (band!.OR as Record<string, any>[]);
|
||||
expect(confirmed!.auftragsvolumen).toEqual({ gte: 60_000 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildOwnerWhere", () => {
|
||||
it("is no filter without a selection", () => {
|
||||
expect(buildOwnerWhere([])).toBeNull();
|
||||
});
|
||||
|
||||
it("uses a plain predicate for ids only", () => {
|
||||
expect(buildOwnerWhere(["u1", "u2"])).toEqual({ zustaendigePersonId: { in: ["u1", "u2"] } });
|
||||
});
|
||||
|
||||
it("adds the unassigned bucket as an alternative, not as an id", () => {
|
||||
const where = buildOwnerWhere(["u1", UNASSIGNED_OWNER]) as Record<string, any>;
|
||||
expect(where.OR).toEqual([{ zustaendigePersonId: { in: ["u1"] } }, { zustaendigePersonId: null }]);
|
||||
});
|
||||
|
||||
it("matches only unassigned projects when that is the sole option", () => {
|
||||
expect(buildOwnerWhere([UNASSIGNED_OWNER])).toEqual({ zustaendigePersonId: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolvePeriodRanges", () => {
|
||||
const now = new Date("2026-07-15T12:00:00.000Z");
|
||||
|
||||
it("returns null when nothing is selected", () => {
|
||||
expect(resolvePeriodRanges([], now)).toBeNull();
|
||||
expect(resolvePeriodRanges(undefined, now)).toBeNull();
|
||||
});
|
||||
|
||||
it("matches the single resolver for one period", () => {
|
||||
expect(resolvePeriodRanges(["month"], now)).toEqual(resolvePeriodRange("month", now));
|
||||
});
|
||||
|
||||
it("unions several periods into the widest range", () => {
|
||||
// "this week" sits inside July, "next 30 days" reaches into August: the union
|
||||
// has to start at the earlier bound and end at the later one.
|
||||
const union = resolvePeriodRanges(["week", "next30"], now);
|
||||
const week = resolvePeriodRange("week", now);
|
||||
const next30 = resolvePeriodRange("next30", now);
|
||||
expect(union?.from.getTime()).toBe(Math.min(week!.from.getTime(), next30!.from.getTime()));
|
||||
expect(union?.to.getTime()).toBe(Math.max(week!.to.getTime(), next30!.to.getTime()));
|
||||
});
|
||||
|
||||
it("ignores a half-open custom range instead of widening to infinity", () => {
|
||||
const union = resolvePeriodRanges(["week", "custom"], now, { from: "2026-07-01", to: null });
|
||||
expect(union).toEqual(resolvePeriodRange("week", now));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
// WF-P8 S01 — the pure half of the board filter facets.
|
||||
//
|
||||
// Parses the facet query parameters and turns them into Prisma `where`
|
||||
// fragments. Deliberately free of server imports so the date and money maths
|
||||
// can be unit-tested without a database: the only impure facet (customer type,
|
||||
// which has to resolve contacts first) stays in projectService.server.ts.
|
||||
|
||||
/** Sentinel option of the "Sachbearbeiter" facet: projects with no assignee. */
|
||||
export const UNASSIGNED_OWNER = "none";
|
||||
|
||||
/**
|
||||
* Customer type of a project, read off its primary contact.
|
||||
*
|
||||
* Davids export lists four options and all four are offered, each with its own
|
||||
* meaning in our model (`KontaktTyp` plus `OrgMerkmal`):
|
||||
*
|
||||
* privatperson – kontaktTyp = privatperson
|
||||
* organisation – every organisation, whatever its legal form (the superset)
|
||||
* unternehmen – organisations with a commercial legal form (gmbh, kg)
|
||||
* oeffentlich – organisations marked as a public body
|
||||
*
|
||||
* "Organisation" being the parent of the other two is the point, not a mistake:
|
||||
* it answers "any organisation" without picking a legal form. Selecting several
|
||||
* behaves like every other facet — the union of their rows.
|
||||
*/
|
||||
export const PROJECT_CUSTOMER_TYPES = ["privatperson", "organisation", "unternehmen", "oeffentlich"] as const;
|
||||
export type ProjectCustomerType = (typeof PROJECT_CUSTOMER_TYPES)[number];
|
||||
|
||||
export const PROJECT_PERIOD_KEYS = ["week", "month", "next30", "custom"] as const;
|
||||
export type ProjectPeriodKey = (typeof PROJECT_PERIOD_KEYS)[number];
|
||||
|
||||
export const PROJECT_VALUE_BANDS = ["bis10k", "10k_30k", "30k_60k", "ueber60k"] as const;
|
||||
export type ProjectValueBand = (typeof PROJECT_VALUE_BANDS)[number];
|
||||
|
||||
/** Lower bound (inclusive) and upper bound (exclusive) of a value band, in €. */
|
||||
const VALUE_BAND_RANGE: Record<ProjectValueBand, { min: number; max: number | null }> = {
|
||||
bis10k: { min: 0, max: 10_000 },
|
||||
"10k_30k": { min: 10_000, max: 30_000 },
|
||||
"30k_60k": { min: 30_000, max: 60_000 },
|
||||
ueber60k: { min: 60_000, max: null },
|
||||
};
|
||||
|
||||
export type ProjectFacetFilters = {
|
||||
/** User ids, plus `UNASSIGNED_OWNER` for projects without an assignee. */
|
||||
owners?: readonly string[];
|
||||
customerTypes?: readonly ProjectCustomerType[];
|
||||
/**
|
||||
* Ids from the tenant `Tag` catalogue. Free-form like the owner list, since a
|
||||
* tag catalogue is tenant data and not a closed set of keys.
|
||||
*/
|
||||
tagIds?: readonly string[];
|
||||
/** Selected periods; several are unioned (see resolvePeriodRanges). */
|
||||
periods?: readonly ProjectPeriodKey[];
|
||||
/** Only meaningful when "custom" is among the periods; ISO date (YYYY-MM-DD). */
|
||||
periodFrom?: string | null;
|
||||
periodTo?: string | null;
|
||||
valueBands?: readonly ProjectValueBand[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Split a comma-separated query parameter and keep only the known options.
|
||||
* Unknown values are dropped rather than rejected — a stale bookmark should
|
||||
* narrow the board, never 500 it.
|
||||
*/
|
||||
export function parseFacetList<T extends string>(raw: string | null | undefined, allowed: readonly T[]): T[] {
|
||||
if (!raw) return [];
|
||||
const allowedSet = new Set<string>(allowed);
|
||||
const seen = new Set<T>();
|
||||
for (const part of raw.split(",")) {
|
||||
const value = part.trim();
|
||||
if (allowedSet.has(value)) seen.add(value as T);
|
||||
}
|
||||
return [...seen];
|
||||
}
|
||||
|
||||
/** Same, but for the free-form owner list (ids are not a closed set). */
|
||||
export function parseOwnerList(raw: string | null | undefined): string[] {
|
||||
if (!raw) return [];
|
||||
const seen = new Set<string>();
|
||||
for (const part of raw.split(",")) {
|
||||
const value = part.trim();
|
||||
if (value) seen.add(value);
|
||||
}
|
||||
return [...seen];
|
||||
}
|
||||
|
||||
/** Every selected period; the where-builder unions them. */
|
||||
export function parsePeriodList(raw: string | null | undefined): ProjectPeriodKey[] {
|
||||
return parseFacetList(raw, PROJECT_PERIOD_KEYS);
|
||||
}
|
||||
|
||||
export function parsePeriodKey(raw: string | null | undefined): ProjectPeriodKey | null {
|
||||
const [key] = parseFacetList(raw, PROJECT_PERIOD_KEYS);
|
||||
return key ?? null;
|
||||
}
|
||||
|
||||
/** Midnight-anchored day boundary in the server's timezone. */
|
||||
function startOfDay(date: Date): Date {
|
||||
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
|
||||
}
|
||||
|
||||
function endOfDay(date: Date): Date {
|
||||
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59, 999);
|
||||
}
|
||||
|
||||
function parseIsoDate(value: string | null | undefined): Date | null {
|
||||
if (!value) return null;
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})$/u.exec(value.trim());
|
||||
if (!match) return null;
|
||||
const date = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]));
|
||||
return Number.isNaN(date.getTime()) ? null : date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve several selected periods into the one range that covers them all.
|
||||
*
|
||||
* Davids dropdown offers checkboxes, so several periods can be picked. A project
|
||||
* sits inside a range or it does not, so the union of the selected ranges is the
|
||||
* only reading that makes sense — earliest start to latest end. The chips name
|
||||
* every selected period, so the widening stays visible instead of being implied
|
||||
* by a single collapsed label.
|
||||
*/
|
||||
export function resolvePeriodRanges(
|
||||
periods: readonly ProjectPeriodKey[] | null | undefined,
|
||||
now: Date,
|
||||
custom?: { from?: string | null; to?: string | null }
|
||||
): { from: Date; to: Date } | null {
|
||||
const ranges = (periods ?? []).flatMap((period) => {
|
||||
const range = resolvePeriodRange(period, now, custom);
|
||||
return range ? [range] : [];
|
||||
});
|
||||
if (ranges.length === 0) return null;
|
||||
return ranges.reduce((widest, range) => ({
|
||||
from: range.from < widest.from ? range.from : widest.from,
|
||||
to: range.to > widest.to ? range.to : widest.to,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a period option into a concrete range. Weeks start on Monday (the
|
||||
* calendar convention of every locale this product ships in).
|
||||
*/
|
||||
export function resolvePeriodRange(
|
||||
period: ProjectPeriodKey | null | undefined,
|
||||
now: Date,
|
||||
custom?: { from?: string | null; to?: string | null }
|
||||
): { from: Date; to: Date } | null {
|
||||
switch (period) {
|
||||
case "week": {
|
||||
const weekday = (now.getDay() + 6) % 7; // Monday = 0
|
||||
const monday = startOfDay(new Date(now.getFullYear(), now.getMonth(), now.getDate() - weekday));
|
||||
return { from: monday, to: endOfDay(new Date(monday.getFullYear(), monday.getMonth(), monday.getDate() + 6)) };
|
||||
}
|
||||
case "month": {
|
||||
const first = new Date(now.getFullYear(), now.getMonth(), 1);
|
||||
return { from: first, to: endOfDay(new Date(now.getFullYear(), now.getMonth() + 1, 0)) };
|
||||
}
|
||||
case "next30":
|
||||
return { from: startOfDay(now), to: endOfDay(new Date(now.getFullYear(), now.getMonth(), now.getDate() + 30)) };
|
||||
case "custom": {
|
||||
const from = parseIsoDate(custom?.from);
|
||||
const to = parseIsoDate(custom?.to);
|
||||
// A half-open custom range is not a range — treat it as "no filter"
|
||||
// instead of silently inventing the missing end.
|
||||
if (!from || !to || from > to) return null;
|
||||
return { from, to: endOfDay(to) };
|
||||
}
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Projects whose runtime overlaps the range.
|
||||
*
|
||||
* A project counts as "in the period" when its start or its deadline falls
|
||||
* inside the range, or when it spans the whole range. Projects that carry
|
||||
* neither date are excluded on purpose: a date filter that keeps undated rows
|
||||
* would make the facet look broken.
|
||||
*/
|
||||
export function buildPeriodWhere(range: { from: Date; to: Date }): Record<string, unknown> {
|
||||
return {
|
||||
OR: [
|
||||
{ startDatum: { gte: range.from, lte: range.to } },
|
||||
{ deadline: { gte: range.from, lte: range.to } },
|
||||
{ AND: [{ startDatum: { lte: range.from } }, { deadline: { gte: range.to } }] },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Projects whose value falls into any of the selected bands.
|
||||
*
|
||||
* The board shows `auftragsvolumen` and falls back to
|
||||
* `potenziellerAuftragswert`; the filter has to use the same source, which
|
||||
* Prisma cannot express as a COALESCE in `where` — hence the explicit
|
||||
* "confirmed volume, or no confirmed volume and a matching estimate" pair.
|
||||
*/
|
||||
export function buildValueBandWhere(bands: readonly ProjectValueBand[]): Record<string, unknown> | null {
|
||||
if (bands.length === 0) return null;
|
||||
return {
|
||||
OR: bands.map((band) => {
|
||||
const { min, max } = VALUE_BAND_RANGE[band];
|
||||
const range = max == null ? { gte: min } : { gte: min, lt: max };
|
||||
return {
|
||||
OR: [{ auftragsvolumen: range }, { AND: [{ auftragsvolumen: null }, { potenziellerAuftragswert: range }] }],
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Assignee facet, including the "no assignee" sentinel. */
|
||||
export function buildOwnerWhere(owners: readonly string[]): Record<string, unknown> | null {
|
||||
if (owners.length === 0) return null;
|
||||
const userIds = owners.filter((owner) => owner !== UNASSIGNED_OWNER);
|
||||
const alternatives: Record<string, unknown>[] = [];
|
||||
if (userIds.length > 0) alternatives.push({ zustaendigePersonId: { in: userIds } });
|
||||
if (owners.includes(UNASSIGNED_OWNER)) alternatives.push({ zustaendigePersonId: null });
|
||||
return alternatives.length === 1 ? alternatives[0]! : { OR: alternatives };
|
||||
}
|
||||
+39
-16
@@ -8,10 +8,49 @@ export function projectDetailPath(tenantSlug: string, projectId: string): string
|
||||
return `/${tenantSlug}/projects/${projectId}`;
|
||||
}
|
||||
|
||||
/** WF-P8 S02 contact search (loader-only JSON resource of one project). */
|
||||
export function projectContactSearchPath(tenantSlug: string, projectId: string): string {
|
||||
return `/${tenantSlug}/projects/${projectId}/contact-search`;
|
||||
}
|
||||
|
||||
export function projectsListPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/projects/list`;
|
||||
}
|
||||
|
||||
export function projectsBoardsPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/projects/boards`;
|
||||
}
|
||||
|
||||
export function projectsExportPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/projects/export`;
|
||||
}
|
||||
|
||||
export function projectPipelinesAdminPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/admin/pipelines`;
|
||||
}
|
||||
|
||||
/** WF-P8 S04 — settings of one board (columns, access, successor). */
|
||||
export function projectBoardSettingsPath(tenantSlug: string, pipelineId: string): string {
|
||||
return `${projectPipelinesAdminPath(tenantSlug)}/${pipelineId}`;
|
||||
}
|
||||
|
||||
/** WF-P8 S05 — detail-template config of one board. */
|
||||
export function projectPipelineFieldsAdminPath(tenantSlug: string, pipelineId: string): string {
|
||||
return `${projectPipelinesAdminPath(tenantSlug)}/${pipelineId}/fields`;
|
||||
}
|
||||
|
||||
export function projectLostReasonsAdminPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/admin/pipelines/lost-reasons`;
|
||||
}
|
||||
|
||||
export function projectAcceptanceFormsAdminPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/admin/projects/acceptance-forms`;
|
||||
}
|
||||
|
||||
export function projectTemplatesAdminPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/admin/projects/templates`;
|
||||
}
|
||||
|
||||
export function projectPipelinePath(tenantSlug: string, pipelineId: string): string {
|
||||
return `/${tenantSlug}/projects/pipelines/${pipelineId}`;
|
||||
}
|
||||
@@ -31,19 +70,3 @@ export function projectAcceptancePath(tenantSlug: string, projectId: string): st
|
||||
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`;
|
||||
}
|
||||
+315
@@ -0,0 +1,315 @@
|
||||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
withTenantRLS: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: mocks.withTenantRLS,
|
||||
}));
|
||||
|
||||
import {
|
||||
exportProjectListCsv,
|
||||
filterAggregateReadablePipelineIdsWithTx,
|
||||
normalizeProjectListPage,
|
||||
ownerScopeWhere,
|
||||
projectEditScopeWhere,
|
||||
projectReadScopeWhere,
|
||||
PROJECT_CSV_EXPORT_MAX_ROWS,
|
||||
} from "./projectService.server";
|
||||
|
||||
type ProjectFixture = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
pipelineId: string;
|
||||
stageId: string;
|
||||
projektNummer: string;
|
||||
projektname: string;
|
||||
potenziellerAuftragswert: string | null;
|
||||
auftragsvolumen: string | null;
|
||||
zustaendigePersonId: string | null;
|
||||
projektleiterId: string | null;
|
||||
updatedAt: Date;
|
||||
pipeline: { id: string; name: string };
|
||||
stage: { id: string; name: string };
|
||||
};
|
||||
|
||||
function projectFixture(index: number, overrides: Partial<ProjectFixture> = {}): ProjectFixture {
|
||||
const ordinal = String(index + 1).padStart(4, "0");
|
||||
return {
|
||||
id: `project-${ordinal}`,
|
||||
tenantId: "tenant-1",
|
||||
pipelineId: "pipeline-1",
|
||||
stageId: "stage-1",
|
||||
projektNummer: `HG-${ordinal}`,
|
||||
projektname: `Projekt ${ordinal}`,
|
||||
potenziellerAuftragswert: null,
|
||||
auftragsvolumen: `${index + 1}.00`,
|
||||
zustaendigePersonId: "owner-1",
|
||||
projektleiterId: "manager-1",
|
||||
updatedAt: new Date("2026-07-13T12:00:00.000Z"),
|
||||
pipeline: { id: "pipeline-1", name: "Vertrieb" },
|
||||
stage: { id: "stage-1", name: "Neu" },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function installTenantTransaction(projects: readonly ProjectFixture[]) {
|
||||
const findMany = vi.fn().mockResolvedValue(projects);
|
||||
const pipelineFieldConfigFindMany = vi.fn().mockResolvedValue([]);
|
||||
const tx = {
|
||||
projekt: { findMany },
|
||||
pipelineFieldConfig: { findMany: pipelineFieldConfigFindMany },
|
||||
};
|
||||
mocks.withTenantRLS.mockImplementation(async (_tenantId: string, callback: (client: typeof tx) => Promise<unknown>) => callback(tx));
|
||||
return { findMany, pipelineFieldConfigFindMany };
|
||||
}
|
||||
|
||||
const context = {
|
||||
userId: "user-1",
|
||||
permissions: ["projects.read_all", "deals.read_volume_all"],
|
||||
roleIds: ["role-1"],
|
||||
groupIds: ["group-1"],
|
||||
};
|
||||
|
||||
describe("project CSV export", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test("exports all 537 matching projects without applying the table pagination clamp", async () => {
|
||||
const projects = Array.from({ length: 537 }, (_, index) => projectFixture(index));
|
||||
const { findMany, pipelineFieldConfigFindMany } = installTenantTransaction(projects);
|
||||
|
||||
const csv = await exportProjectListCsv({ tenantId: "tenant-1", ctx: context });
|
||||
|
||||
expect(mocks.withTenantRLS).toHaveBeenCalledWith("tenant-1", expect.any(Function));
|
||||
expect(findMany).toHaveBeenCalledOnce();
|
||||
expect(findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
tenantId: "tenant-1",
|
||||
archivedAt: null,
|
||||
isDemoData: false,
|
||||
pipeline: {
|
||||
accessRules: {
|
||||
none: {
|
||||
tenantId: "tenant-1",
|
||||
kannSehen: false,
|
||||
OR: [
|
||||
{ principalType: "user", principalId: "user-1" },
|
||||
{ principalType: "role", principalId: "role-1" },
|
||||
{ principalType: "group", principalId: "group-1" },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
select: expect.objectContaining({
|
||||
id: true,
|
||||
projektNummer: true,
|
||||
pipeline: { select: { name: true } },
|
||||
stage: { select: { name: true } },
|
||||
}),
|
||||
orderBy: { updatedAt: "desc" },
|
||||
take: PROJECT_CSV_EXPORT_MAX_ROWS + 1,
|
||||
});
|
||||
expect(pipelineFieldConfigFindMany).toHaveBeenCalledOnce();
|
||||
|
||||
const lines = csv.trimEnd().split("\n");
|
||||
expect(lines).toHaveLength(538);
|
||||
expect(lines[1]).toContain('"HG-0001"');
|
||||
expect(lines.at(-1)).toContain('"HG-0537"');
|
||||
});
|
||||
|
||||
test("neutralizes spreadsheet formulas in every user-controlled CSV cell", async () => {
|
||||
installTenantTransaction([
|
||||
projectFixture(0, {
|
||||
projektNummer: "+SUM(1,1)",
|
||||
projektname: '=HYPERLINK("https://evil.example","click")',
|
||||
auftragsvolumen: "-5",
|
||||
zustaendigePersonId: "@OWNER",
|
||||
pipeline: { id: "pipeline-1", name: "\t=CMD()" },
|
||||
stage: { id: "stage-1", name: " -1+2" },
|
||||
}),
|
||||
]);
|
||||
|
||||
const csv = await exportProjectListCsv({ tenantId: "tenant-1", ctx: context });
|
||||
const row = csv.trimEnd().split("\n")[1];
|
||||
|
||||
expect(row).toContain('"\'+SUM(1,1)"');
|
||||
expect(row).toContain('"\'=HYPERLINK(""https://evil.example"",""click"")"');
|
||||
expect(row).toContain('"\'\t=CMD()"');
|
||||
expect(row).toContain('"\' -1+2"');
|
||||
expect(row).toContain('"\'-5.00"');
|
||||
expect(row).toContain('"\'@OWNER"');
|
||||
expect(row).toContain('"2026-07-13T12:00:00.000Z"');
|
||||
});
|
||||
|
||||
test("hides both monetary columns when the potential-value field is denied", async () => {
|
||||
const { pipelineFieldConfigFindMany } = installTenantTransaction([
|
||||
projectFixture(0, { potenziellerAuftragswert: "95000", auftragsvolumen: null }),
|
||||
]);
|
||||
pipelineFieldConfigFindMany.mockResolvedValue([
|
||||
{
|
||||
pipelineId: "pipeline-1",
|
||||
stageId: "stage-1",
|
||||
fieldKey: "potenziellerAuftragswert",
|
||||
sichtbar: false,
|
||||
visibilities: [],
|
||||
},
|
||||
]);
|
||||
|
||||
const csv = await exportProjectListCsv({ tenantId: "tenant-1", ctx: context });
|
||||
|
||||
expect(csv.trimEnd().split("\n")[1]).toContain('"—"');
|
||||
expect(csv).not.toContain("95000.00");
|
||||
});
|
||||
|
||||
test("keeps volume fields hidden when duplicate legacy configs contain an explicit deny", async () => {
|
||||
const { pipelineFieldConfigFindMany } = installTenantTransaction([
|
||||
projectFixture(0, { potenziellerAuftragswert: "95000", auftragsvolumen: null }),
|
||||
]);
|
||||
pipelineFieldConfigFindMany.mockResolvedValue([
|
||||
{
|
||||
pipelineId: "pipeline-1",
|
||||
stageId: "stage-1",
|
||||
fieldKey: "potenziellerAuftragswert",
|
||||
sichtbar: true,
|
||||
visibilities: [{ kannSehen: true, kannBearbeiten: true }],
|
||||
},
|
||||
{
|
||||
pipelineId: "pipeline-1",
|
||||
stageId: "stage-1",
|
||||
fieldKey: "potenziellerAuftragswert",
|
||||
sichtbar: true,
|
||||
visibilities: [{ kannSehen: false, kannBearbeiten: false }],
|
||||
},
|
||||
]);
|
||||
|
||||
const csv = await exportProjectListCsv({ tenantId: "tenant-1", ctx: context });
|
||||
|
||||
expect(csv.trimEnd().split("\n")[1]).toContain('"—"');
|
||||
expect(csv).not.toContain("95000.00");
|
||||
});
|
||||
|
||||
test("rejects an unbounded export before building field-visibility rows", async () => {
|
||||
const projects = Array.from({ length: PROJECT_CSV_EXPORT_MAX_ROWS + 1 }, (_, index) => projectFixture(index));
|
||||
const { pipelineFieldConfigFindMany } = installTenantTransaction(projects);
|
||||
|
||||
await expect(exportProjectListCsv({ tenantId: "tenant-1", ctx: context })).rejects.toMatchObject({
|
||||
messageKey: "projects.error.exportTooLarge",
|
||||
});
|
||||
expect(pipelineFieldConfigFindMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("keeps owner and pipeline scopes when a search query adds another AND clause", async () => {
|
||||
const { findMany } = installTenantTransaction([]);
|
||||
await exportProjectListCsv({
|
||||
tenantId: "tenant-1",
|
||||
ctx: { userId: "user-1", permissions: ["projects.read_own"], roleIds: [], groupIds: [] },
|
||||
filters: { q: "Dach" },
|
||||
});
|
||||
|
||||
const where = findMany.mock.calls[0]![0].where;
|
||||
expect(where.AND).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ OR: [{ zustaendigePersonId: "user-1" }] },
|
||||
expect.objectContaining({ pipeline: expect.any(Object) }),
|
||||
{ OR: [{ projektname: { contains: "Dach", mode: "insensitive" } }, { projektNummer: { contains: "Dach", mode: "insensitive" } }] },
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("project list visibility helpers", () => {
|
||||
test("keeps owner, project-lead, and membership scopes additive without broadening", () => {
|
||||
expect(ownerScopeWhere("tenant-1", { userId: "user-1", permissions: ["projects.read_own"] })).toEqual({
|
||||
OR: [{ zustaendigePersonId: "user-1" }],
|
||||
});
|
||||
expect(ownerScopeWhere("tenant-1", { userId: "user-1", permissions: ["projects.read_own_pl"] })).toEqual({
|
||||
OR: [{ projektleiterId: "user-1" }],
|
||||
});
|
||||
expect(
|
||||
ownerScopeWhere("tenant-1", {
|
||||
userId: "user-1",
|
||||
permissions: ["projects.read_own_member"],
|
||||
groupIds: ["group-1"],
|
||||
}),
|
||||
).toEqual({
|
||||
OR: [
|
||||
{
|
||||
mitglieder: {
|
||||
some: {
|
||||
tenantId: "tenant-1",
|
||||
archivedAt: null,
|
||||
OR: [{ userId: "user-1" }, { groupId: { in: ["group-1"] } }],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(ownerScopeWhere("tenant-1", { userId: "user-1", permissions: [] })).toEqual({ id: { in: [] } });
|
||||
expect(ownerScopeWhere("tenant-1", { userId: "user-1", permissions: ["projects.read_all"] })).toEqual({});
|
||||
});
|
||||
|
||||
test("resolves aggregate field visibility in one query with explicit deny precedence", async () => {
|
||||
const findMany = vi.fn().mockResolvedValue([
|
||||
{
|
||||
pipelineId: "pipeline-1",
|
||||
sichtbar: true,
|
||||
visibilities: [{ kannSehen: true }],
|
||||
},
|
||||
{
|
||||
pipelineId: "pipeline-1",
|
||||
sichtbar: true,
|
||||
visibilities: [{ kannSehen: false }],
|
||||
},
|
||||
{
|
||||
pipelineId: "pipeline-2",
|
||||
sichtbar: true,
|
||||
visibilities: [],
|
||||
},
|
||||
]);
|
||||
|
||||
await expect(
|
||||
filterAggregateReadablePipelineIdsWithTx(
|
||||
{ pipelineFieldConfig: { findMany } } as never,
|
||||
{
|
||||
tenantId: "tenant-1",
|
||||
pipelineIds: ["pipeline-1", "pipeline-2", "pipeline-2"],
|
||||
ctx: context,
|
||||
backstopPermissions: ["deals.read_volume_all"],
|
||||
},
|
||||
),
|
||||
).resolves.toEqual(["pipeline-2"]);
|
||||
expect(findMany).toHaveBeenCalledOnce();
|
||||
expect(findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({
|
||||
tenantId: "tenant-1",
|
||||
pipelineId: { in: ["pipeline-1", "pipeline-2"] },
|
||||
fieldKey: "aggregate:forecast",
|
||||
stageId: null,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test("normalizes invalid and abusive page values", () => {
|
||||
expect(normalizeProjectListPage("foo")).toBe(1);
|
||||
expect(normalizeProjectListPage(Number.POSITIVE_INFINITY)).toBe(1);
|
||||
expect(normalizeProjectListPage(-5)).toBe(1);
|
||||
expect(normalizeProjectListPage("2")).toBe(2);
|
||||
expect(normalizeProjectListPage(999_999)).toBe(10_000);
|
||||
});
|
||||
|
||||
test("keeps project access scopes inside AND so they cannot replace a concrete project id", () => {
|
||||
const ctx = { userId: "user-1", permissions: [] as string[] };
|
||||
expect(projectReadScopeWhere("tenant-1", ctx)).toMatchObject({
|
||||
AND: [{ id: { in: [] } }, { pipeline: expect.any(Object) }],
|
||||
});
|
||||
expect(projectEditScopeWhere("tenant-1", ctx)).toMatchObject({
|
||||
AND: [{ id: { in: [] } }, { pipeline: expect.any(Object) }],
|
||||
});
|
||||
});
|
||||
});
|
||||
+3050
-228
File diff suppressed because it is too large.
Load diff
Loaded 100 of 5955 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user