Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+93
@@ -0,0 +1,93 @@
|
||||
// R-P6 (P6 CRM core, Variante A) — shared loader/action guard for CRM routes.
|
||||
//
|
||||
// Resolves the authenticated tenant context and the user's permission set once,
|
||||
// so routes can gate consistently (mirrors taskAccess). Module-not-active handling
|
||||
// differs by intent (§ "404 vs locked"):
|
||||
// - GET loaders pass `requireModule: false` and render a locked/empty VM when
|
||||
// `hasModule` is false.
|
||||
// - Write actions pass `requireModule: true` → 404 (CatalogError.notFound) when
|
||||
// the module is off, and additionally require an explicit crm.* permission.
|
||||
|
||||
import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
|
||||
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { CrmServiceError, type CrmVisibilityContext } from "./crmService.server";
|
||||
|
||||
// The connector/entitlement feature key. The phase is called "crm", but the
|
||||
// seeded/registered feature key is "crm-basic" (packages/entitlements →
|
||||
// featureKeys.crmBasic). A fresh "crm" key would be unseeded, so tenantHasModule
|
||||
// would always return false; "crm-basic" is the key tenants actually carry.
|
||||
export const CRM_MODULE_KEY = "crm-basic";
|
||||
|
||||
// Owner-scope helpers live in crmService (the leaf, used by listKontakteForBrowser)
|
||||
// and are re-exported here so routes can reach them from the access module.
|
||||
export { canReadAllKontakte, ownerScopeWhere } from "./crmService.server";
|
||||
export type { CrmVisibilityContext } from "./crmService.server";
|
||||
|
||||
export type CrmRouteContext = CrmVisibilityContext & {
|
||||
tenantId: string;
|
||||
hasModule: boolean;
|
||||
};
|
||||
|
||||
export async function loadCrmContext({
|
||||
request,
|
||||
params,
|
||||
requireModule = false,
|
||||
}: {
|
||||
request: Request;
|
||||
params: Record<string, string | undefined>;
|
||||
requireModule?: boolean;
|
||||
}): Promise<CrmRouteContext> {
|
||||
await requireAuth({ request, params });
|
||||
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
|
||||
if (!tenantId || !userInfo.userId) {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
const [hasModule, permissions] = await Promise.all([
|
||||
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: CRM_MODULE_KEY }),
|
||||
getPermissionsByUser(userInfo.userId, tenantId),
|
||||
]);
|
||||
if (requireModule && !hasModule) {
|
||||
// Mutations on a disabled module look "not found" (Bauprinzip A.5.3).
|
||||
throw new CatalogError(foundationErrors.notFound, { module: CRM_MODULE_KEY });
|
||||
}
|
||||
return { tenantId, userId: userInfo.userId, permissions, hasModule };
|
||||
}
|
||||
|
||||
/** Require a crm.* permission; throws 404 (CatalogError.notFound) if missing. */
|
||||
export function requireCrmPermission(ctx: CrmRouteContext, permission: string): CrmRouteContext {
|
||||
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, permission);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bare 404 Response for throwing from CRM loaders/actions. The body text is never
|
||||
* shown to users (the route ErrorBoundary renders ServerError); the helper keeps
|
||||
* call sites from inlining a hardcoded user-facing literal.
|
||||
*/
|
||||
export function notFoundResponse(): Response {
|
||||
return new Response("Not Found", { status: 404 });
|
||||
}
|
||||
|
||||
/** Bare 400 Response for invalid action input (same rationale as notFoundResponse). */
|
||||
export function badRequestResponse(): Response {
|
||||
return new Response("Bad Request", { status: 400 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a CRM action error to a JSON Response for resource routes. CatalogError keeps
|
||||
* its status + i18nKey; CrmServiceError is a 400 with its Klartext message key.
|
||||
* Unknown errors are rethrown (→ 500).
|
||||
*/
|
||||
export function crmActionErrorResponse(error: unknown): Response {
|
||||
if (error instanceof CatalogError) {
|
||||
return Response.json({ error: error.i18nKey, code: error.code }, { status: error.status });
|
||||
}
|
||||
if (error instanceof CrmServiceError) {
|
||||
return Response.json({ error: error.messageKey }, { status: 400 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
// R-P6 (P6 CRM core, Variante A) — audit + activity wiring for the CRM module.
|
||||
//
|
||||
// Audit (DoD 13): every write action records a tamper-evident AuditEvent (M001)
|
||||
// via createAuditEvent with the shared db client.
|
||||
//
|
||||
// Activity (DoD 14): user-facing timeline entries are logged against the contact.
|
||||
// A private person maps to the Activity subject "contact", an organisation to
|
||||
// "company". Tag / assignment / note activities reuse the EXISTING activity types
|
||||
// (tag_added, tag_removed, assignee_changed, note_added). All best-effort.
|
||||
|
||||
import type { JsonValue } from "@hivegrid/foundation";
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { logActivity, type ActivityRelatedRef, type ActivitySubjectType, type ActivityType } from "@hivegrid/activity";
|
||||
import type { CrmRouteContext } from "./crmAccess.server";
|
||||
import type { KontaktTyp } from "./crmService.server";
|
||||
|
||||
export type CrmAuditTargetType = "kontakt" | "custom_field" | "custom_field_value" | "tag" | "tag_assignment";
|
||||
|
||||
export type CrmAuditAction =
|
||||
| "kontakt.created"
|
||||
| "kontakt.updated"
|
||||
| "kontakt.archived"
|
||||
| "kontakt.reactivated"
|
||||
| "kontakt.deleted"
|
||||
| "kontakt.reassigned"
|
||||
| "kontakt.email_added"
|
||||
| "kontakt.email_primary_set"
|
||||
| "kontakt.email_removed"
|
||||
| "kontakt.telefon_added"
|
||||
| "kontakt.telefon_primary_set"
|
||||
| "kontakt.telefon_removed"
|
||||
| "kontakt.relation_added"
|
||||
| "kontakt.relation_removed"
|
||||
| "kontakt.bulk_archived"
|
||||
| "kontakt.bulk_reassigned"
|
||||
| "custom_field.created"
|
||||
| "custom_field.updated"
|
||||
| "custom_field.archived"
|
||||
| "custom_field_value.set"
|
||||
| "custom_field.demo_seeded"
|
||||
| "custom_field.demo_cleared"
|
||||
| "tag.created"
|
||||
| "tag.updated"
|
||||
| "tag.deleted"
|
||||
| "tag_assignment.assigned"
|
||||
| "tag_assignment.unassigned";
|
||||
|
||||
export async function auditCrmEvent(input: {
|
||||
ctx: Pick<CrmRouteContext, "tenantId" | "userId">;
|
||||
action: CrmAuditAction;
|
||||
targetType: CrmAuditTargetType;
|
||||
targetId: string;
|
||||
metadata?: Record<string, JsonValue>;
|
||||
}): Promise<void> {
|
||||
try {
|
||||
await createAuditEvent({
|
||||
tenantId: input.ctx.tenantId,
|
||||
actorId: input.ctx.userId,
|
||||
actorType: "user",
|
||||
action: input.action,
|
||||
targetType: input.targetType,
|
||||
targetId: input.targetId,
|
||||
metadata: input.metadata ?? null,
|
||||
});
|
||||
} catch {
|
||||
// Audit must never break the user action; the failure is logged upstream.
|
||||
}
|
||||
}
|
||||
|
||||
/** Map a Kontakt type to its Activity subject (DoD 14). */
|
||||
function kontaktSubjectType(kontaktTyp: KontaktTyp): ActivitySubjectType {
|
||||
return kontaktTyp === "organisation" ? "company" : "contact";
|
||||
}
|
||||
|
||||
export type KontaktActivityType = Extract<
|
||||
ActivityType,
|
||||
"contact_created" | "contact_updated" | "contact_archived" | "assignee_changed" | "tag_added" | "tag_removed" | "note_added"
|
||||
>;
|
||||
|
||||
/**
|
||||
* Log a contact activity. The entry hangs off the contact's own timeline; its
|
||||
* subject type is derived from `kontaktTyp` (private person → contact, organisation
|
||||
* → company). Best-effort.
|
||||
*/
|
||||
export async function logKontaktActivity(input: {
|
||||
ctx: Pick<CrmRouteContext, "tenantId" | "userId">;
|
||||
kontaktId: string;
|
||||
kontaktTyp: KontaktTyp;
|
||||
activityType: KontaktActivityType;
|
||||
summaryText: string;
|
||||
relatedEntityRefs?: ActivityRelatedRef[];
|
||||
}): Promise<void> {
|
||||
try {
|
||||
await logActivity({
|
||||
tenantId: input.ctx.tenantId,
|
||||
actorUserId: input.ctx.userId,
|
||||
actorKind: "user",
|
||||
activityType: input.activityType,
|
||||
subjectType: kontaktSubjectType(input.kontaktTyp),
|
||||
subjectId: input.kontaktId,
|
||||
summaryText: input.summaryText,
|
||||
relatedEntityRefs: input.relatedEntityRefs,
|
||||
});
|
||||
} catch {
|
||||
// Activity logging is best-effort; never break the user action.
|
||||
}
|
||||
}
|
||||
+369
@@ -0,0 +1,369 @@
|
||||
// R-P6 (P6 CRM core, Variante A) — shared loader/action for the contact detail
|
||||
// (`/contacts/:id`) and the organisation detail (`/contacts/companies/:id`).
|
||||
// Both render the SAME server-built KontaktDetailVM + ActivityStreamVM and share
|
||||
// the inline-edit intents (DoD 3); the only per-route difference is the back
|
||||
// link / breadcrumb root. Server-only (.server) — never imported by a component.
|
||||
//
|
||||
// Every write intent is audited (DoD 13, via crmAudit.auditCrmEvent) and, when
|
||||
// contact-relevant, appends an Activity-Stream entry (DoD 14, logKontaktActivity).
|
||||
|
||||
import { redirect } from "react-router";
|
||||
import type { JsonValue } from "@hivegrid/foundation";
|
||||
import {
|
||||
buildActivityStreamVM,
|
||||
buildKontaktDetailVM,
|
||||
datentypLabelKey,
|
||||
type ActivityStreamVM,
|
||||
type KontaktDetailVM,
|
||||
} from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import {
|
||||
badRequestResponse,
|
||||
crmActionErrorResponse,
|
||||
loadCrmContext,
|
||||
notFoundResponse,
|
||||
requireCrmPermission,
|
||||
type CrmRouteContext,
|
||||
} from "./crmAccess.server";
|
||||
import {
|
||||
addKontaktEmail,
|
||||
addKontaktRelation,
|
||||
addKontaktTelefon,
|
||||
archiveKontakt,
|
||||
getKontaktDetail,
|
||||
getVisibleKontaktOrThrow,
|
||||
hardDeleteKontakt,
|
||||
listAssignableUsers,
|
||||
reactivateKontakt,
|
||||
reassignKontakt,
|
||||
removeKontaktEmail,
|
||||
removeKontaktRelation,
|
||||
removeKontaktTelefon,
|
||||
resolveUserLabels,
|
||||
setPrimaryEmail,
|
||||
setPrimaryTelefon,
|
||||
updateKontakt,
|
||||
type KontaktArt,
|
||||
type KontaktRow,
|
||||
type KontaktStatus,
|
||||
type OrgMerkmal,
|
||||
} from "./crmService.server";
|
||||
import { getCustomFieldValues, listCustomFieldDefinitions, setCustomFieldValue } from "./customFieldService.server";
|
||||
import { assignTag, listTags, listTagsForEntity, unassignTag } from "./tagService.server";
|
||||
import { auditCrmEvent, logKontaktActivity } from "./crmAudit.server";
|
||||
import { companiesPath, contactDetailPath, contactsPath, companyDetailPath } from "./crmRoutePaths";
|
||||
import { maskEmailActivitiesForViewer } from "~/modules/emailInbox/services/emailActivityMasking.server";
|
||||
|
||||
const KONTAKT_CUSTOM_FIELD_ENTITY = "kontakt";
|
||||
const KONTAKT_TAG_ENTITY_TYPE = "kontakt";
|
||||
const ACTIVITY_LIMIT = 50;
|
||||
|
||||
export type KontaktDetailVariant = "contacts" | "companies";
|
||||
|
||||
export type CustomFieldDefOption = { id: string; key: string; label: string; datentyp: string; datentypLabelKey: string };
|
||||
|
||||
export type KontaktDetailLoaderData = {
|
||||
title: string;
|
||||
variant: KontaktDetailVariant;
|
||||
backHref: string;
|
||||
listLabelKey: string;
|
||||
detailVM: KontaktDetailVM;
|
||||
activityVM: ActivityStreamVM;
|
||||
allTags: { id: string; name: string; farbe: string }[];
|
||||
customFieldDefs: CustomFieldDefOption[];
|
||||
ownerOptions: { id: string; label: string }[];
|
||||
};
|
||||
|
||||
type ActivityDbRow = {
|
||||
id: string;
|
||||
createdAt: Date;
|
||||
actorUserId: string | null;
|
||||
actorKind: string;
|
||||
activityType: string;
|
||||
summaryText: string;
|
||||
metadata?: unknown;
|
||||
};
|
||||
|
||||
async function loadKontaktActivities(tenantId: string, subjectType: "contact" | "company", subjectId: string): Promise<ActivityDbRow[]> {
|
||||
// No read helper is exported from @hivegrid/activity yet — load the per-entity
|
||||
// timeline tenant-scoped (RLS GUC set by withTenantRLS), newest first.
|
||||
// `metadata` is selected ONLY for the email-visibility masking (VA-P23) and
|
||||
// never reaches the VM.
|
||||
const rows = await withTenantRLS(tenantId, (tx) =>
|
||||
tx.activity.findMany({
|
||||
where: { tenantId, subjectType, subjectId },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: ACTIVITY_LIMIT + 1,
|
||||
select: { id: true, createdAt: true, actorUserId: true, actorKind: true, activityType: true, summaryText: true, metadata: true },
|
||||
}),
|
||||
);
|
||||
return rows as ActivityDbRow[];
|
||||
}
|
||||
|
||||
export async function loadKontaktDetailData(args: {
|
||||
request: Request;
|
||||
params: Record<string, string | undefined>;
|
||||
variant: KontaktDetailVariant;
|
||||
}): Promise<KontaktDetailLoaderData> {
|
||||
const { t } = await getTranslations(args.request);
|
||||
const ctx = await loadCrmContext({ request: args.request, params: args.params });
|
||||
const tenantSlug = args.params.tenant ?? "";
|
||||
const kontaktId = args.params.id ?? "";
|
||||
|
||||
if (!ctx.hasModule) {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
try {
|
||||
requireCrmPermission(ctx, "crm.read_own");
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
|
||||
let detail;
|
||||
try {
|
||||
detail = await getKontaktDetail(ctx.tenantId, kontaktId, ctx);
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
const subjectType = detail.kontakt.kontaktTyp === "organisation" ? "company" : "contact";
|
||||
|
||||
const [customFields, tags, definitions, allTags, ownerOptions, activityRows] = await Promise.all([
|
||||
getCustomFieldValues({ tenantId: ctx.tenantId, entityType: KONTAKT_CUSTOM_FIELD_ENTITY, entityId: kontaktId }),
|
||||
listTagsForEntity({ tenantId: ctx.tenantId, entityType: KONTAKT_TAG_ENTITY_TYPE, entityId: kontaktId }),
|
||||
listCustomFieldDefinitions({ tenantId: ctx.tenantId, entityType: KONTAKT_CUSTOM_FIELD_ENTITY }),
|
||||
listTags(ctx.tenantId),
|
||||
listAssignableUsers(ctx.tenantId),
|
||||
loadKontaktActivities(ctx.tenantId, subjectType, kontaktId),
|
||||
]);
|
||||
|
||||
const actorIds = activityRows.map((row) => row.actorUserId).filter((id): id is string => Boolean(id));
|
||||
const userLabels = await resolveUserLabels([detail.kontakt.zustaendigerUserId, ...actorIds].filter((id): id is string => Boolean(id)));
|
||||
|
||||
const detailVM = buildKontaktDetailVM({
|
||||
detail: {
|
||||
kontakt: detail.kontakt,
|
||||
emails: detail.emails.map((e) => ({ id: e.id, email: e.email, primaer: e.primaer })),
|
||||
telefone: detail.telefone.map((p) => ({ id: p.id, telefon: p.telefon, primaer: p.primaer })),
|
||||
relationen: detail.relationen.map((r) => ({ id: r.id, vonKontaktId: r.vonKontaktId, zuKontaktId: r.zuKontaktId, rolle: r.rolle, kontext: r.kontext })),
|
||||
adresse: detail.adresse
|
||||
? { strasse: detail.adresse.strasse, hausnummer: detail.adresse.hausnummer, plz: detail.adresse.plz, ort: detail.adresse.ort, land: detail.adresse.land }
|
||||
: null,
|
||||
},
|
||||
customFields: customFields.map((cf) => ({
|
||||
definition: { id: cf.definition.id, key: cf.definition.key, label: cf.definition.label, datentyp: cf.definition.datentyp, optionen: cf.definition.optionen },
|
||||
wert: cf.wert,
|
||||
})),
|
||||
tags: tags.map((tag) => ({ id: tag.id, name: tag.name, farbe: tag.farbe })),
|
||||
userLabels,
|
||||
perms: { canWrite: ctx.permissions.includes("crm.write"), canDelete: ctx.permissions.includes("crm.delete") },
|
||||
tenantSlug,
|
||||
});
|
||||
|
||||
// VA-P23 (M09 Block H): email activities are permission-masked — without
|
||||
// email.read_all only the viewer's OWN mailbox activities show details.
|
||||
const maskedActivityRows = await maskEmailActivitiesForViewer({
|
||||
tenantId: ctx.tenantId,
|
||||
userId: ctx.userId,
|
||||
permissions: ctx.permissions,
|
||||
rows: activityRows,
|
||||
maskedText: t("emailInbox.activity.masked"),
|
||||
});
|
||||
|
||||
const activityVM = buildActivityStreamVM({
|
||||
rows: maskedActivityRows.slice(0, ACTIVITY_LIMIT).map((row) => ({
|
||||
id: row.id,
|
||||
createdAt: row.createdAt,
|
||||
actorUserId: row.actorUserId,
|
||||
actorKind: row.actorKind as never,
|
||||
activityType: row.activityType as never,
|
||||
summaryText: row.summaryText,
|
||||
})),
|
||||
userLabels,
|
||||
hasMore: activityRows.length > ACTIVITY_LIMIT,
|
||||
});
|
||||
|
||||
const backHref = args.variant === "companies" ? companiesPath(tenantSlug) : contactsPath(tenantSlug);
|
||||
|
||||
return {
|
||||
title: `${detailVM.data?.displayName ?? t("crm.detail.title")} | ${process.env.APP_NAME}`,
|
||||
variant: args.variant,
|
||||
backHref,
|
||||
listLabelKey: args.variant === "companies" ? "crm.companies.title" : "crm.contacts.title",
|
||||
detailVM,
|
||||
activityVM,
|
||||
allTags: allTags.map((tag) => ({ id: tag.id, name: tag.name, farbe: tag.farbe })),
|
||||
customFieldDefs: definitions.map((def) => ({
|
||||
id: def.id,
|
||||
key: def.key,
|
||||
label: def.label,
|
||||
datentyp: def.datentyp,
|
||||
datentypLabelKey: datentypLabelKey(def.datentyp),
|
||||
})),
|
||||
ownerOptions,
|
||||
};
|
||||
}
|
||||
|
||||
function field(form: FormData, name: string): string {
|
||||
return form.get(name)?.toString().trim() ?? "";
|
||||
}
|
||||
|
||||
function optionalField(form: FormData, name: string): string | null {
|
||||
const value = form.get(name)?.toString().trim();
|
||||
return value ? value : null;
|
||||
}
|
||||
|
||||
export async function handleKontaktDetailAction(args: {
|
||||
request: Request;
|
||||
params: Record<string, string | undefined>;
|
||||
variant: KontaktDetailVariant;
|
||||
}): Promise<Response> {
|
||||
const ctx: CrmRouteContext = await loadCrmContext({ request: args.request, params: args.params, requireModule: true });
|
||||
const tenantSlug = args.params.tenant ?? "";
|
||||
const kontaktId = args.params.id ?? "";
|
||||
const form = await args.request.formData();
|
||||
const intent = form.get("intent")?.toString();
|
||||
const detailHref = args.variant === "companies" ? companyDetailPath(tenantSlug, kontaktId) : contactDetailPath(tenantSlug, kontaktId);
|
||||
const listHref = args.variant === "companies" ? companiesPath(tenantSlug) : contactsPath(tenantSlug);
|
||||
|
||||
try {
|
||||
// Visibility + type are needed by almost every branch (activity subject).
|
||||
const kontakt: KontaktRow = await getVisibleKontaktOrThrow(ctx.tenantId, kontaktId, ctx);
|
||||
const typ = kontakt.kontaktTyp;
|
||||
|
||||
if (intent === "delete") {
|
||||
requireCrmPermission(ctx, "crm.delete");
|
||||
await hardDeleteKontakt({ tenantId: ctx.tenantId, kontaktId });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.deleted", targetType: "kontakt", targetId: kontaktId });
|
||||
return redirect(listHref);
|
||||
}
|
||||
|
||||
requireCrmPermission(ctx, "crm.write");
|
||||
|
||||
switch (intent) {
|
||||
case "updateBasics": {
|
||||
await updateKontakt({
|
||||
tenantId: ctx.tenantId,
|
||||
kontaktId,
|
||||
kontaktStatus: (optionalField(form, "kontaktStatus") as KontaktStatus | null) ?? undefined,
|
||||
vorname: form.has("vorname") ? optionalField(form, "vorname") : undefined,
|
||||
nachname: form.has("nachname") ? optionalField(form, "nachname") : undefined,
|
||||
orgName: form.has("orgName") ? optionalField(form, "orgName") : undefined,
|
||||
orgMerkmal: form.has("orgMerkmal") ? (optionalField(form, "orgMerkmal") as OrgMerkmal | null) : undefined,
|
||||
});
|
||||
await auditCrmEvent({ ctx, action: "kontakt.updated", targetType: "kontakt", targetId: kontaktId });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "Stammdaten aktualisiert" });
|
||||
break;
|
||||
}
|
||||
case "addEmail": {
|
||||
await addKontaktEmail({ tenantId: ctx.tenantId, kontaktId, email: field(form, "email"), primaer: form.get("primaer") === "1" });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.email_added", targetType: "kontakt", targetId: kontaktId });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "E-Mail hinzugefügt" });
|
||||
break;
|
||||
}
|
||||
case "setPrimaryEmail": {
|
||||
await setPrimaryEmail({ tenantId: ctx.tenantId, emailId: field(form, "emailId") });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.email_primary_set", targetType: "kontakt", targetId: kontaktId });
|
||||
break;
|
||||
}
|
||||
case "removeEmail": {
|
||||
await removeKontaktEmail({ tenantId: ctx.tenantId, emailId: field(form, "emailId") });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.email_removed", targetType: "kontakt", targetId: kontaktId });
|
||||
break;
|
||||
}
|
||||
case "addTelefon": {
|
||||
await addKontaktTelefon({ tenantId: ctx.tenantId, kontaktId, telefon: field(form, "telefon"), primaer: form.get("primaer") === "1" });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.telefon_added", targetType: "kontakt", targetId: kontaktId });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "Telefonnummer hinzugefügt" });
|
||||
break;
|
||||
}
|
||||
case "setPrimaryTelefon": {
|
||||
await setPrimaryTelefon({ tenantId: ctx.tenantId, telefonId: field(form, "telefonId") });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.telefon_primary_set", targetType: "kontakt", targetId: kontaktId });
|
||||
break;
|
||||
}
|
||||
case "removeTelefon": {
|
||||
await removeKontaktTelefon({ tenantId: ctx.tenantId, telefonId: field(form, "telefonId") });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.telefon_removed", targetType: "kontakt", targetId: kontaktId });
|
||||
break;
|
||||
}
|
||||
case "addRelation": {
|
||||
await addKontaktRelation({
|
||||
tenantId: ctx.tenantId,
|
||||
vonKontaktId: kontaktId,
|
||||
zuKontaktId: field(form, "zuKontaktId"),
|
||||
rolle: (field(form, "rolle") || "hauptkontakt") as KontaktArt,
|
||||
kontext: optionalField(form, "kontext"),
|
||||
});
|
||||
await auditCrmEvent({ ctx, action: "kontakt.relation_added", targetType: "kontakt", targetId: kontaktId });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "Verknüpfung hinzugefügt" });
|
||||
break;
|
||||
}
|
||||
case "removeRelation": {
|
||||
await removeKontaktRelation({ tenantId: ctx.tenantId, relationId: field(form, "relationId") });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.relation_removed", targetType: "kontakt", targetId: kontaktId });
|
||||
break;
|
||||
}
|
||||
case "reassign": {
|
||||
const owner = field(form, "zustaendigerUserId");
|
||||
if (!owner) {
|
||||
throw badRequestResponse();
|
||||
}
|
||||
await reassignKontakt({ tenantId: ctx.tenantId, kontaktId, zustaendigerUserId: owner });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.reassigned", targetType: "kontakt", targetId: kontaktId, metadata: { zustaendigerUserId: owner } });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "assignee_changed", summaryText: "Verantwortlicher geändert" });
|
||||
break;
|
||||
}
|
||||
case "addTag": {
|
||||
const tagId = field(form, "tagId");
|
||||
await assignTag({ tenantId: ctx.tenantId, tagId, entityType: KONTAKT_TAG_ENTITY_TYPE, entityId: kontaktId });
|
||||
await auditCrmEvent({ ctx, action: "tag_assignment.assigned", targetType: "tag_assignment", targetId: kontaktId, metadata: { tagId } });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "tag_added", summaryText: "Tag zugewiesen" });
|
||||
break;
|
||||
}
|
||||
case "removeTag": {
|
||||
const tagId = field(form, "tagId");
|
||||
await unassignTag({ tenantId: ctx.tenantId, tagId, entityType: KONTAKT_TAG_ENTITY_TYPE, entityId: kontaktId });
|
||||
await auditCrmEvent({ ctx, action: "tag_assignment.unassigned", targetType: "tag_assignment", targetId: kontaktId, metadata: { tagId } });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "tag_removed", summaryText: "Tag entfernt" });
|
||||
break;
|
||||
}
|
||||
case "setCustomField": {
|
||||
const wert: JsonValue = field(form, "wert");
|
||||
await setCustomFieldValue({ tenantId: ctx.tenantId, definitionId: field(form, "definitionId"), entityType: KONTAKT_CUSTOM_FIELD_ENTITY, entityId: kontaktId, wert });
|
||||
await auditCrmEvent({ ctx, action: "custom_field_value.set", targetType: "custom_field_value", targetId: kontaktId, metadata: { definitionId: field(form, "definitionId") } });
|
||||
break;
|
||||
}
|
||||
case "addNote": {
|
||||
const note = field(form, "note");
|
||||
if (!note) {
|
||||
throw badRequestResponse();
|
||||
}
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "note_added", summaryText: note });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.updated", targetType: "kontakt", targetId: kontaktId, metadata: { note: true } });
|
||||
break;
|
||||
}
|
||||
case "archive": {
|
||||
await archiveKontakt({ tenantId: ctx.tenantId, kontaktId });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.archived", targetType: "kontakt", targetId: kontaktId });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_archived", summaryText: "Kontakt archiviert" });
|
||||
break;
|
||||
}
|
||||
case "reactivate": {
|
||||
await reactivateKontakt({ tenantId: ctx.tenantId, kontaktId });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.reactivated", targetType: "kontakt", targetId: kontaktId });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "Kontakt reaktiviert" });
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw badRequestResponse();
|
||||
}
|
||||
|
||||
return redirect(detailHref);
|
||||
} catch (error) {
|
||||
if (error instanceof Response) {
|
||||
throw error;
|
||||
}
|
||||
return crmActionErrorResponse(error);
|
||||
}
|
||||
}
|
||||
+271
@@ -0,0 +1,271 @@
|
||||
// R-P6 (P6 CRM core, Variante A) — shared loader/action for the contact and the
|
||||
// organisation browser. Both `/contacts` and `/contacts/companies` render the
|
||||
// SAME server-built KontaktListVM (DoD 2: filter / sort / paginate / bulk / CSV);
|
||||
// the only difference is the forced `organisation` type filter and the detail
|
||||
// href. Keeping the wiring here keeps the two route files thin and identical in
|
||||
// behaviour. Server-only (.server) — never imported by a component.
|
||||
|
||||
import { redirect } from "react-router";
|
||||
import { buildKontaktListVM, type KontaktListVM } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import {
|
||||
badRequestResponse,
|
||||
crmActionErrorResponse,
|
||||
loadCrmContext,
|
||||
notFoundResponse,
|
||||
requireCrmPermission,
|
||||
} from "./crmAccess.server";
|
||||
import {
|
||||
archiveKontakt,
|
||||
bulkArchiveKontakte,
|
||||
bulkReassignKontakte,
|
||||
getVisibleKontaktOrThrow,
|
||||
listAssignableUsers,
|
||||
listKontakteForBrowser,
|
||||
reactivateKontakt,
|
||||
resolveUserLabels,
|
||||
type KontaktRow,
|
||||
} from "./crmService.server";
|
||||
import { assignTag, listTags, listTagsForEntity } from "./tagService.server";
|
||||
import { auditCrmEvent, logKontaktActivity } from "./crmAudit.server";
|
||||
import { parseKontaktListQuery, kontaktListQueryToParams, type KontaktListQuery } from "./kontaktListQuery";
|
||||
import { companiesPath, companyDetailPath, contactDetailPath, contactNewPath, contactsExportPath, contactsPath } from "./crmRoutePaths";
|
||||
|
||||
// The canonical TagAssignment.entityType for a Kontakt (mirrors crmService).
|
||||
const KONTAKT_TAG_ENTITY_TYPE = "kontakt";
|
||||
|
||||
export type KontaktListVariant = "contacts" | "companies";
|
||||
|
||||
export type KontaktTagOption = { id: string; name: string; farbe: string };
|
||||
export type OwnerOption = { id: string; label: string };
|
||||
|
||||
export type KontaktListLoaderData = {
|
||||
title: string;
|
||||
moduleActive: boolean;
|
||||
variant: KontaktListVariant;
|
||||
vm: KontaktListVM;
|
||||
tagOptions: KontaktTagOption[];
|
||||
ownerOptions: OwnerOption[];
|
||||
query: KontaktListQuery;
|
||||
baseHref: string;
|
||||
newHref: string;
|
||||
exportHref: string;
|
||||
};
|
||||
|
||||
function variantQuery(variant: KontaktListVariant, query: KontaktListQuery): KontaktListQuery {
|
||||
if (variant !== "companies") {
|
||||
return query;
|
||||
}
|
||||
// The organisation browser always pins the type filter, regardless of the URL.
|
||||
return { ...query, filter: { ...query.filter, kontaktTyp: "organisation" } };
|
||||
}
|
||||
|
||||
export async function loadKontaktListData(args: {
|
||||
request: Request;
|
||||
params: Record<string, string | undefined>;
|
||||
variant: KontaktListVariant;
|
||||
}): Promise<KontaktListLoaderData> {
|
||||
const { t } = await getTranslations(args.request);
|
||||
const ctx = await loadCrmContext({ request: args.request, params: args.params });
|
||||
const tenantSlug = args.params.tenant ?? "";
|
||||
const titleKey = args.variant === "companies" ? "crm.companies.title" : "crm.contacts.title";
|
||||
const baseHref = args.variant === "companies" ? companiesPath(tenantSlug) : contactsPath(tenantSlug);
|
||||
const url = new URL(args.request.url);
|
||||
const query = variantQuery(args.variant, parseKontaktListQuery(url.searchParams));
|
||||
|
||||
const base: Omit<KontaktListLoaderData, "vm" | "tagOptions" | "ownerOptions"> = {
|
||||
title: `${t(titleKey)} | ${process.env.APP_NAME}`,
|
||||
moduleActive: ctx.hasModule,
|
||||
variant: args.variant,
|
||||
query,
|
||||
baseHref,
|
||||
newHref: contactNewPath(tenantSlug),
|
||||
exportHref: `${contactsExportPath(tenantSlug)}?${kontaktListQueryToParams(query).toString()}`,
|
||||
};
|
||||
|
||||
if (!ctx.hasModule) {
|
||||
return { ...base, vm: buildKontaktListVM({ ...emptyVmInput(tenantSlug) }), tagOptions: [], ownerOptions: [] };
|
||||
}
|
||||
try {
|
||||
requireCrmPermission(ctx, "crm.read_own");
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
|
||||
const { rows, total, page, pageCount } = await listKontakteForBrowser({
|
||||
tenantId: ctx.tenantId,
|
||||
ctx,
|
||||
filter: query.filter,
|
||||
sort: query.sort,
|
||||
page: query.page,
|
||||
});
|
||||
|
||||
const [userLabels, tagOptions, ownerOptions] = await Promise.all([
|
||||
resolveUserLabels(rows.map((row) => row.zustaendigerUserId).filter((id): id is string => Boolean(id))),
|
||||
listTags(ctx.tenantId),
|
||||
listAssignableUsers(ctx.tenantId),
|
||||
]);
|
||||
|
||||
const tagsByKontakt = new Map<string, KontaktTagOption[]>();
|
||||
await Promise.all(
|
||||
rows.map(async (row) => {
|
||||
const tags = await listTagsForEntity({ tenantId: ctx.tenantId, entityType: KONTAKT_TAG_ENTITY_TYPE, entityId: row.id });
|
||||
tagsByKontakt.set(
|
||||
row.id,
|
||||
tags.map((tag) => ({ id: tag.id, name: tag.name, farbe: tag.farbe })),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const detailHrefFor = (row: { id: string }) =>
|
||||
args.variant === "companies" ? companyDetailPath(tenantSlug, row.id) : contactDetailPath(tenantSlug, row.id);
|
||||
|
||||
const vm = buildKontaktListVM({
|
||||
rows,
|
||||
userLabels,
|
||||
tagsByKontakt,
|
||||
pagination: { page, pageCount, total },
|
||||
sort: query.sort,
|
||||
filter: query.filter,
|
||||
perms: {
|
||||
canWrite: ctx.permissions.includes("crm.write"),
|
||||
canDelete: ctx.permissions.includes("crm.delete"),
|
||||
canReadAll: ctx.permissions.includes("crm.read_all"),
|
||||
},
|
||||
tenantSlug,
|
||||
detailHrefFor,
|
||||
});
|
||||
|
||||
return {
|
||||
...base,
|
||||
vm,
|
||||
tagOptions: tagOptions.map((tag) => ({ id: tag.id, name: tag.name, farbe: tag.farbe })),
|
||||
ownerOptions,
|
||||
};
|
||||
}
|
||||
|
||||
function emptyVmInput(tenantSlug: string) {
|
||||
return {
|
||||
rows: [],
|
||||
userLabels: new Map<string, string>(),
|
||||
tagsByKontakt: new Map<string, never[]>(),
|
||||
pagination: { page: 1, pageCount: 0, total: 0 },
|
||||
sort: { field: "createdAt" as const, dir: "desc" as const },
|
||||
filter: {
|
||||
kontaktTyp: null,
|
||||
kontaktStatus: null,
|
||||
zustaendigerUserId: null,
|
||||
search: null,
|
||||
tagIds: null,
|
||||
tagMatch: "or" as const,
|
||||
includeArchived: false,
|
||||
},
|
||||
perms: { canWrite: false, canDelete: false, canReadAll: false },
|
||||
tenantSlug,
|
||||
};
|
||||
}
|
||||
|
||||
function parseIds(form: FormData): string[] {
|
||||
return [...new Set(form.getAll("kontaktId").map((v) => v.toString().trim()).filter(Boolean))];
|
||||
}
|
||||
|
||||
/** Resolve the visible target contacts for a bulk action (owner-scope enforced
|
||||
* per item). Returns the rows so the activity log can pick the right subject. */
|
||||
async function visibleTargets(tenantId: string, ctx: Parameters<typeof getVisibleKontaktOrThrow>[2], ids: string[]): Promise<KontaktRow[]> {
|
||||
const targets: KontaktRow[] = [];
|
||||
for (const id of ids) {
|
||||
try {
|
||||
targets.push(await getVisibleKontaktOrThrow(tenantId, id, ctx));
|
||||
} catch {
|
||||
// Skip contacts the caller may not touch (read_own); never fail the batch.
|
||||
}
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
export async function handleKontaktListAction(args: {
|
||||
request: Request;
|
||||
params: Record<string, string | undefined>;
|
||||
variant: KontaktListVariant;
|
||||
}): Promise<Response> {
|
||||
const ctx = await loadCrmContext({ request: args.request, params: args.params, requireModule: true });
|
||||
const tenantSlug = args.params.tenant ?? "";
|
||||
const form = await args.request.formData();
|
||||
const intent = form.get("intent")?.toString();
|
||||
const redirectBack = redirect(args.variant === "companies" ? companiesPath(tenantSlug) : contactsPath(tenantSlug));
|
||||
|
||||
try {
|
||||
if (intent === "archive" || intent === "reactivate") {
|
||||
requireCrmPermission(ctx, "crm.write");
|
||||
const kontaktId = form.get("kontaktId")?.toString().trim();
|
||||
if (!kontaktId) {
|
||||
throw badRequestResponse();
|
||||
}
|
||||
const kontakt = await getVisibleKontaktOrThrow(ctx.tenantId, kontaktId, ctx);
|
||||
if (intent === "archive") {
|
||||
await archiveKontakt({ tenantId: ctx.tenantId, kontaktId });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.archived", targetType: "kontakt", targetId: kontaktId });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: kontakt.kontaktTyp, activityType: "contact_archived", summaryText: "Kontakt archiviert" });
|
||||
} else {
|
||||
await reactivateKontakt({ tenantId: ctx.tenantId, kontaktId });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.reactivated", targetType: "kontakt", targetId: kontaktId });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: kontakt.kontaktTyp, activityType: "contact_updated", summaryText: "Kontakt reaktiviert" });
|
||||
}
|
||||
return redirectBack;
|
||||
}
|
||||
|
||||
if (intent === "bulkArchive") {
|
||||
requireCrmPermission(ctx, "crm.write");
|
||||
const targets = await visibleTargets(ctx.tenantId, ctx, parseIds(form));
|
||||
const ids = targets.map((t) => t.id);
|
||||
if (ids.length > 0) {
|
||||
await bulkArchiveKontakte({ tenantId: ctx.tenantId, ctx, kontaktIds: ids });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.bulk_archived", targetType: "kontakt", targetId: ids[0], metadata: { kontaktIds: ids } });
|
||||
for (const target of targets) {
|
||||
await logKontaktActivity({ ctx, kontaktId: target.id, kontaktTyp: target.kontaktTyp, activityType: "contact_archived", summaryText: "Kontakt archiviert (Massenaktion)" });
|
||||
}
|
||||
}
|
||||
return redirectBack;
|
||||
}
|
||||
|
||||
if (intent === "bulkReassign") {
|
||||
requireCrmPermission(ctx, "crm.write");
|
||||
const owner = form.get("zustaendigerUserId")?.toString().trim();
|
||||
if (!owner) {
|
||||
throw badRequestResponse();
|
||||
}
|
||||
const targets = await visibleTargets(ctx.tenantId, ctx, parseIds(form));
|
||||
const ids = targets.map((t) => t.id);
|
||||
if (ids.length > 0) {
|
||||
await bulkReassignKontakte({ tenantId: ctx.tenantId, ctx, kontaktIds: ids, zustaendigerUserId: owner });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.bulk_reassigned", targetType: "kontakt", targetId: ids[0], metadata: { kontaktIds: ids, zustaendigerUserId: owner } });
|
||||
for (const target of targets) {
|
||||
await logKontaktActivity({ ctx, kontaktId: target.id, kontaktTyp: target.kontaktTyp, activityType: "assignee_changed", summaryText: "Verantwortlicher geändert (Massenaktion)" });
|
||||
}
|
||||
}
|
||||
return redirectBack;
|
||||
}
|
||||
|
||||
if (intent === "bulkTag") {
|
||||
requireCrmPermission(ctx, "crm.write");
|
||||
const tagId = form.get("tagId")?.toString().trim();
|
||||
if (!tagId) {
|
||||
throw badRequestResponse();
|
||||
}
|
||||
const targets = await visibleTargets(ctx.tenantId, ctx, parseIds(form));
|
||||
for (const target of targets) {
|
||||
await assignTag({ tenantId: ctx.tenantId, tagId, entityType: KONTAKT_TAG_ENTITY_TYPE, entityId: target.id });
|
||||
await auditCrmEvent({ ctx, action: "tag_assignment.assigned", targetType: "tag_assignment", targetId: target.id, metadata: { tagId } });
|
||||
await logKontaktActivity({ ctx, kontaktId: target.id, kontaktTyp: target.kontaktTyp, activityType: "tag_added", summaryText: "Tag zugewiesen (Massenaktion)" });
|
||||
}
|
||||
return redirectBack;
|
||||
}
|
||||
|
||||
throw badRequestResponse();
|
||||
} catch (error) {
|
||||
if (error instanceof Response) {
|
||||
throw error;
|
||||
}
|
||||
return crmActionErrorResponse(error);
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
// R-P6 (P6 CRM core, Variante A) — pure route-path builders for the typed CRM
|
||||
// URLs. Loaders build these and pass them into the View-Models / route data so
|
||||
// the VMs and components stay routing-agnostic. Client-safe (no server imports)
|
||||
// so a route `handle` export can reference CRM_MODULE_KEY without dragging the
|
||||
// server-only access guard into the client bundle.
|
||||
|
||||
// Tenant connector module key (the seeded entitlement key — see crmAccess.server).
|
||||
export const CRM_MODULE_KEY = "crm-basic";
|
||||
|
||||
export function contactsPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/contacts`;
|
||||
}
|
||||
|
||||
export function contactNewPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/contacts/new`;
|
||||
}
|
||||
|
||||
export function contactDetailPath(tenantSlug: string, kontaktId: string): string {
|
||||
return `/${tenantSlug}/contacts/${kontaktId}`;
|
||||
}
|
||||
|
||||
export function companiesPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/contacts/companies`;
|
||||
}
|
||||
|
||||
export function companyDetailPath(tenantSlug: string, kontaktId: string): string {
|
||||
return `/${tenantSlug}/contacts/companies/${kontaktId}`;
|
||||
}
|
||||
|
||||
export function contactsExportPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/contacts/export`;
|
||||
}
|
||||
|
||||
export function customFieldsAdminPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/contacts/admin/custom-fields`;
|
||||
}
|
||||
|
||||
export function tagsAdminPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/contacts/admin/tags`;
|
||||
}
|
||||
|
||||
export function duplicatesAdminPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/contacts/admin/duplicates`;
|
||||
}
|
||||
+807
@@ -0,0 +1,807 @@
|
||||
// R-P6 (P6 CRM core, Variante A) — domain service for the CRM module.
|
||||
//
|
||||
// Pure-ish server logic for the typed CRM entities (Kontakt + address/email/phone
|
||||
// channels, relations, list/filter/dup-check/bulk). Always tenant-scoped, enforces
|
||||
// owner visibility (crm.read_own → 404, not 403). NO React/UI imports. Routes call
|
||||
// these from their loaders/actions and build the View-Model from the returned rows.
|
||||
// Audit + Activity are NOT written here — the routes wire them via crmAudit.
|
||||
//
|
||||
// RLS-ready (mirrors taskService / fileService): every tenant-scoped access runs
|
||||
// inside withTenantRLS() so the tenant GUC is set before the query. Internal
|
||||
// composition goes through *WithTx(tx, ...) helpers that reuse the active
|
||||
// transaction client — functions never nest withTenantRLS(). This is a functional
|
||||
// no-op until the CRM RLS policies are activated (prisma/rls/crm-isolation.sql, P5
|
||||
// cutover). The only access NOT wrapped is the global User lookup
|
||||
// (resolveUserLabels): User is not tenant-scoped, so it stays on the db singleton.
|
||||
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { crmContactsIndex } from "@hivegrid/search";
|
||||
import { publishKontaktSearchUpsert, publishSearchProjectionDelete } from "~/services/search/searchIndexProjection.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
|
||||
/**
|
||||
* Domain error carrying an i18n message key (M002 Klartext). Routes map
|
||||
* `messageKey` to a catalog error / VM error branch — never a bare HTTP code.
|
||||
*/
|
||||
export class CrmServiceError extends Error {
|
||||
readonly messageKey: string;
|
||||
constructor(messageKey: string) {
|
||||
super(messageKey);
|
||||
this.name = "CrmServiceError";
|
||||
this.messageKey = messageKey;
|
||||
}
|
||||
}
|
||||
|
||||
// --- Domain type aliases (mirror the crm.prisma enums 1:1) -----------------
|
||||
|
||||
export type KontaktTyp = "privatperson" | "organisation";
|
||||
export type KontaktStatus = "kontakt" | "kunde" | "bestandskunde";
|
||||
export type OrgMerkmal = "gmbh" | "kg" | "oeffentliche_einrichtung" | "sonstige";
|
||||
export type KontaktArt = "hauptkontakt" | "sekundaerkontakt" | "mitarbeiter" | "sonstige";
|
||||
|
||||
const MAX_LIST_LIMIT = 200;
|
||||
const DEFAULT_LIST_LIMIT = 50;
|
||||
|
||||
/** Owner-visibility context (the user's permissions for this tenant). */
|
||||
export type CrmVisibilityContext = {
|
||||
userId: string;
|
||||
/** The user's permission names for this tenant (from getPermissionsByUser). */
|
||||
permissions: readonly string[];
|
||||
};
|
||||
|
||||
/** True when the user may see every contact in the tenant (crm.read_all). */
|
||||
export function canReadAllKontakte(ctx: CrmVisibilityContext): boolean {
|
||||
return ctx.permissions.includes("crm.read_all");
|
||||
}
|
||||
|
||||
/**
|
||||
* Owner-scope `where` fragment for the crm.read_own filter (DoD 8). read_all users
|
||||
* get an empty fragment (no restriction); everyone else only ever sees contacts
|
||||
* assigned to them (`zustaendigerUserId`).
|
||||
*/
|
||||
export function ownerScopeWhere(ctx: CrmVisibilityContext): { zustaendigerUserId?: string } {
|
||||
return canReadAllKontakte(ctx) ? {} : { zustaendigerUserId: ctx.userId };
|
||||
}
|
||||
|
||||
// --- Row types (returned to routes; relation fields excluded) --------------
|
||||
|
||||
export type KontaktRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
createdByUserId: string;
|
||||
kontaktTyp: KontaktTyp;
|
||||
kontaktStatus: KontaktStatus;
|
||||
vorname: string | null;
|
||||
nachname: string | null;
|
||||
orgName: string | null;
|
||||
orgMerkmal: OrgMerkmal | null;
|
||||
primaerEmail: string | null;
|
||||
primaerTelefon: string | null;
|
||||
adresseId: string | null;
|
||||
zustaendigerUserId: string | null;
|
||||
isDemoData: boolean;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
archivedAt: Date | null;
|
||||
};
|
||||
|
||||
export type KontaktEmailRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
kontaktId: string;
|
||||
email: string;
|
||||
primaer: boolean;
|
||||
createdAt: Date;
|
||||
};
|
||||
|
||||
export type KontaktTelefonRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
kontaktId: string;
|
||||
telefon: string;
|
||||
primaer: boolean;
|
||||
createdAt: Date;
|
||||
};
|
||||
|
||||
export type KontaktRelationRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
vonKontaktId: string;
|
||||
zuKontaktId: string;
|
||||
rolle: KontaktArt;
|
||||
kontext: string | null;
|
||||
createdAt: Date;
|
||||
};
|
||||
|
||||
export type AdresseRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
strasse: string | null;
|
||||
hausnummer: string | null;
|
||||
plz: string | null;
|
||||
ort: string | null;
|
||||
land: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
export type AdresseInput = {
|
||||
strasse?: string | null;
|
||||
hausnummer?: string | null;
|
||||
plz?: string | null;
|
||||
ort?: string | null;
|
||||
land?: string | null;
|
||||
};
|
||||
|
||||
// --- Primary-channel helper (pure) -----------------------------------------
|
||||
|
||||
/**
|
||||
* Pick the primary channel from an input list (DoD: exactly one primary). The
|
||||
* first item flagged `primaer` wins; if none is flagged the first item is the
|
||||
* primary; an empty list has no primary. Returns the denormalised primary value
|
||||
* plus the per-item primary flags to persist. Pure (no DB) — used at create time.
|
||||
*/
|
||||
function pickPrimary<T extends { value: string; primaer?: boolean }>(items: readonly T[]): {
|
||||
primaryValue: string | null;
|
||||
flags: boolean[];
|
||||
} {
|
||||
if (items.length === 0) {
|
||||
return { primaryValue: null, flags: [] };
|
||||
}
|
||||
let primaryIndex = items.findIndex((item) => item.primaer === true);
|
||||
if (primaryIndex < 0) {
|
||||
primaryIndex = 0;
|
||||
}
|
||||
return {
|
||||
primaryValue: items[primaryIndex].value,
|
||||
flags: items.map((_, index) => index === primaryIndex),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-derive the single primary email for a contact and sync `Kontakt.primaerEmail`.
|
||||
* Runs on the active RLS tx (no own transaction). `preferredEmailId` forces that
|
||||
* row to become primary (e.g. just-added / explicit set); otherwise the existing
|
||||
* primary is kept, falling back to the oldest row.
|
||||
*/
|
||||
async function syncPrimaryEmailWithTx(tx: TenantRlsClient, tenantId: string, kontaktId: string, preferredEmailId?: string): Promise<void> {
|
||||
const emails = await tx.kontaktEmail.findMany({
|
||||
where: { tenantId, kontaktId },
|
||||
select: { id: true, email: true, primaer: true },
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
if (emails.length === 0) {
|
||||
await tx.kontakt.updateMany({ where: { id: kontaktId, tenantId }, data: { primaerEmail: null } });
|
||||
return;
|
||||
}
|
||||
const preferred = preferredEmailId ? emails.find((row) => row.id === preferredEmailId) : undefined;
|
||||
const primary = preferred ?? emails.find((row) => row.primaer) ?? emails[0];
|
||||
for (const row of emails) {
|
||||
const shouldBePrimary = row.id === primary.id;
|
||||
if (row.primaer !== shouldBePrimary) {
|
||||
await tx.kontaktEmail.updateMany({ where: { id: row.id, tenantId }, data: { primaer: shouldBePrimary } });
|
||||
}
|
||||
}
|
||||
await tx.kontakt.updateMany({ where: { id: kontaktId, tenantId }, data: { primaerEmail: primary.email } });
|
||||
}
|
||||
|
||||
/** Telephone counterpart of {@link syncPrimaryEmailWithTx}. */
|
||||
async function syncPrimaryTelefonWithTx(tx: TenantRlsClient, tenantId: string, kontaktId: string, preferredTelefonId?: string): Promise<void> {
|
||||
const telefone = await tx.kontaktTelefon.findMany({
|
||||
where: { tenantId, kontaktId },
|
||||
select: { id: true, telefon: true, primaer: true },
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
if (telefone.length === 0) {
|
||||
await tx.kontakt.updateMany({ where: { id: kontaktId, tenantId }, data: { primaerTelefon: null } });
|
||||
return;
|
||||
}
|
||||
const preferred = preferredTelefonId ? telefone.find((row) => row.id === preferredTelefonId) : undefined;
|
||||
const primary = preferred ?? telefone.find((row) => row.primaer) ?? telefone[0];
|
||||
for (const row of telefone) {
|
||||
const shouldBePrimary = row.id === primary.id;
|
||||
if (row.primaer !== shouldBePrimary) {
|
||||
await tx.kontaktTelefon.updateMany({ where: { id: row.id, tenantId }, data: { primaer: shouldBePrimary } });
|
||||
}
|
||||
}
|
||||
await tx.kontakt.updateMany({ where: { id: kontaktId, tenantId }, data: { primaerTelefon: primary.telefon } });
|
||||
}
|
||||
|
||||
// --- Create / update / lifecycle -------------------------------------------
|
||||
|
||||
export type CreateKontaktInput = {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
kontaktTyp: KontaktTyp;
|
||||
kontaktStatus?: KontaktStatus;
|
||||
vorname?: string | null;
|
||||
nachname?: string | null;
|
||||
orgName?: string | null;
|
||||
orgMerkmal?: OrgMerkmal | null;
|
||||
emails?: { email: string; primaer?: boolean }[];
|
||||
telefone?: { telefon: string; primaer?: boolean }[];
|
||||
adresse?: AdresseInput | null;
|
||||
zustaendigerUserId?: string | null;
|
||||
isDemoData?: boolean;
|
||||
};
|
||||
|
||||
function validateKontaktName(input: { kontaktTyp: KontaktTyp; vorname?: string | null; nachname?: string | null; orgName?: string | null }): void {
|
||||
if (input.kontaktTyp === "privatperson") {
|
||||
if (!input.vorname?.trim() && !input.nachname?.trim()) {
|
||||
throw new CrmServiceError("crm.error.nameRequired");
|
||||
}
|
||||
} else if (!input.orgName?.trim()) {
|
||||
throw new CrmServiceError("crm.error.orgNameRequired");
|
||||
}
|
||||
}
|
||||
|
||||
function hasAddressData(adresse?: AdresseInput | null): boolean {
|
||||
if (!adresse) {
|
||||
return false;
|
||||
}
|
||||
return Boolean(adresse.strasse?.trim() || adresse.hausnummer?.trim() || adresse.plz?.trim() || adresse.ort?.trim() || adresse.land?.trim());
|
||||
}
|
||||
|
||||
export async function createKontakt(input: CreateKontaktInput): Promise<KontaktRow> {
|
||||
validateKontaktName(input);
|
||||
const emailItems = (input.emails ?? []).map((entry) => ({ value: entry.email.trim(), primaer: entry.primaer })).filter((entry) => entry.value);
|
||||
const telefonItems = (input.telefone ?? []).map((entry) => ({ value: entry.telefon.trim(), primaer: entry.primaer })).filter((entry) => entry.value);
|
||||
const primaryEmail = pickPrimary(emailItems);
|
||||
const primaryTelefon = pickPrimary(telefonItems);
|
||||
|
||||
const kontakt = await withTenantRLS(input.tenantId, async (tx) => {
|
||||
let adresseId: string | null = null;
|
||||
if (hasAddressData(input.adresse)) {
|
||||
const adresse = await tx.adresse.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
strasse: input.adresse?.strasse ?? null,
|
||||
hausnummer: input.adresse?.hausnummer ?? null,
|
||||
plz: input.adresse?.plz ?? null,
|
||||
ort: input.adresse?.ort ?? null,
|
||||
land: input.adresse?.land?.trim() || "DE",
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
adresseId = adresse.id;
|
||||
}
|
||||
|
||||
const created = await tx.kontakt.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
createdByUserId: input.userId,
|
||||
kontaktTyp: input.kontaktTyp,
|
||||
kontaktStatus: input.kontaktStatus ?? "kontakt",
|
||||
vorname: input.vorname ?? null,
|
||||
nachname: input.nachname ?? null,
|
||||
orgName: input.orgName ?? null,
|
||||
orgMerkmal: input.orgMerkmal ?? null,
|
||||
primaerEmail: primaryEmail.primaryValue,
|
||||
primaerTelefon: primaryTelefon.primaryValue,
|
||||
adresseId,
|
||||
zustaendigerUserId: input.zustaendigerUserId ?? input.userId,
|
||||
isDemoData: input.isDemoData ?? false,
|
||||
},
|
||||
});
|
||||
|
||||
for (let i = 0; i < emailItems.length; i += 1) {
|
||||
await tx.kontaktEmail.create({ data: { tenantId: input.tenantId, kontaktId: created.id, email: emailItems[i].value, primaer: primaryEmail.flags[i] } });
|
||||
}
|
||||
for (let i = 0; i < telefonItems.length; i += 1) {
|
||||
await tx.kontaktTelefon.create({ data: { tenantId: input.tenantId, kontaktId: created.id, telefon: telefonItems[i].value, primaer: primaryTelefon.flags[i] } });
|
||||
}
|
||||
await publishKontaktSearchUpsert(tx, created);
|
||||
return created;
|
||||
});
|
||||
return kontakt as KontaktRow;
|
||||
}
|
||||
|
||||
export type UpdateKontaktInput = {
|
||||
tenantId: string;
|
||||
kontaktId: string;
|
||||
kontaktStatus?: KontaktStatus;
|
||||
vorname?: string | null;
|
||||
nachname?: string | null;
|
||||
orgName?: string | null;
|
||||
orgMerkmal?: OrgMerkmal | null;
|
||||
};
|
||||
|
||||
export async function updateKontakt(input: UpdateKontaktInput): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const existing = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId }, select: { id: true } });
|
||||
if (!existing) {
|
||||
throw new CatalogError(foundationErrors.notFound, { kontaktId: input.kontaktId });
|
||||
}
|
||||
const updated = await tx.kontakt.update({
|
||||
where: { id: existing.id },
|
||||
data: {
|
||||
...(input.kontaktStatus !== undefined ? { kontaktStatus: input.kontaktStatus } : {}),
|
||||
...(input.vorname !== undefined ? { vorname: input.vorname } : {}),
|
||||
...(input.nachname !== undefined ? { nachname: input.nachname } : {}),
|
||||
...(input.orgName !== undefined ? { orgName: input.orgName } : {}),
|
||||
...(input.orgMerkmal !== undefined ? { orgMerkmal: input.orgMerkmal } : {}),
|
||||
},
|
||||
});
|
||||
await publishKontaktSearchUpsert(tx, updated);
|
||||
});
|
||||
}
|
||||
|
||||
export async function archiveKontakt(input: { tenantId: string; kontaktId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const kontakt = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId }, select: { id: true, kontaktTyp: true } });
|
||||
if (!kontakt) {
|
||||
throw new CatalogError(foundationErrors.notFound, { kontaktId: input.kontaktId });
|
||||
}
|
||||
await tx.kontakt.update({ where: { id: kontakt.id }, data: { archivedAt: new Date() } });
|
||||
await publishSearchProjectionDelete(tx, {
|
||||
schema: crmContactsIndex,
|
||||
tenantId: input.tenantId,
|
||||
entityType: kontakt.kontaktTyp === "organisation" ? "company" : "contact",
|
||||
entityId: kontakt.id,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function reactivateKontakt(input: { tenantId: string; kontaktId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const existing = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId }, select: { id: true } });
|
||||
if (!existing) {
|
||||
throw new CatalogError(foundationErrors.notFound, { kontaktId: input.kontaktId });
|
||||
}
|
||||
const updated = await tx.kontakt.update({ where: { id: existing.id }, data: { archivedAt: null } });
|
||||
await publishKontaktSearchUpsert(tx, updated);
|
||||
});
|
||||
}
|
||||
|
||||
export async function hardDeleteKontakt(input: { tenantId: string; kontaktId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const kontakt = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId }, select: { id: true, kontaktTyp: true } });
|
||||
if (!kontakt) {
|
||||
throw new CatalogError(foundationErrors.notFound, { kontaktId: input.kontaktId });
|
||||
}
|
||||
// KontaktEmail / KontaktTelefon / KontaktRelation cascade on Kontakt delete
|
||||
// (schema onDelete: Cascade). The reusable Adresse stays (it may be shared).
|
||||
await tx.kontakt.delete({ where: { id: kontakt.id } });
|
||||
await publishSearchProjectionDelete(tx, {
|
||||
schema: crmContactsIndex,
|
||||
tenantId: input.tenantId,
|
||||
entityType: kontakt.kontaktTyp === "organisation" ? "company" : "contact",
|
||||
entityId: kontakt.id,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function reassignKontakt(input: { tenantId: string; kontaktId: string; zustaendigerUserId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const existing = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId }, select: { id: true } });
|
||||
if (!existing) {
|
||||
throw new CatalogError(foundationErrors.notFound, { kontaktId: input.kontaktId });
|
||||
}
|
||||
const updated = await tx.kontakt.update({ where: { id: existing.id }, data: { zustaendigerUserId: input.zustaendigerUserId } });
|
||||
await publishKontaktSearchUpsert(tx, updated);
|
||||
});
|
||||
}
|
||||
|
||||
// --- Email channels --------------------------------------------------------
|
||||
|
||||
export async function addKontaktEmail(input: { tenantId: string; kontaktId: string; email: string; primaer?: boolean }): Promise<KontaktEmailRow> {
|
||||
const email = input.email.trim();
|
||||
if (!email) {
|
||||
throw new CrmServiceError("crm.error.emailRequired");
|
||||
}
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const kontakt = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId }, select: { id: true } });
|
||||
if (!kontakt) {
|
||||
throw new CatalogError(foundationErrors.notFound, { kontaktId: input.kontaktId });
|
||||
}
|
||||
const created = await tx.kontaktEmail.create({ data: { tenantId: input.tenantId, kontaktId: input.kontaktId, email, primaer: false } });
|
||||
await syncPrimaryEmailWithTx(tx, input.tenantId, input.kontaktId, input.primaer ? created.id : undefined);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
return created as KontaktEmailRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function setPrimaryEmail(input: { tenantId: string; emailId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const email = await tx.kontaktEmail.findFirst({ where: { id: input.emailId, tenantId: input.tenantId }, select: { id: true, kontaktId: true } });
|
||||
if (!email) {
|
||||
throw new CatalogError(foundationErrors.notFound, { emailId: input.emailId });
|
||||
}
|
||||
await syncPrimaryEmailWithTx(tx, input.tenantId, email.kontaktId, email.id);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: email.kontaktId, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeKontaktEmail(input: { tenantId: string; emailId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const email = await tx.kontaktEmail.findFirst({ where: { id: input.emailId, tenantId: input.tenantId }, select: { id: true, kontaktId: true } });
|
||||
if (!email) {
|
||||
throw new CatalogError(foundationErrors.notFound, { emailId: input.emailId });
|
||||
}
|
||||
await tx.kontaktEmail.deleteMany({ where: { id: input.emailId, tenantId: input.tenantId } });
|
||||
await syncPrimaryEmailWithTx(tx, input.tenantId, email.kontaktId);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: email.kontaktId, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
});
|
||||
}
|
||||
|
||||
// --- Telephone channels ----------------------------------------------------
|
||||
|
||||
export async function addKontaktTelefon(input: { tenantId: string; kontaktId: string; telefon: string; primaer?: boolean }): Promise<KontaktTelefonRow> {
|
||||
const telefon = input.telefon.trim();
|
||||
if (!telefon) {
|
||||
throw new CrmServiceError("crm.error.telefonRequired");
|
||||
}
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const kontakt = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId }, select: { id: true } });
|
||||
if (!kontakt) {
|
||||
throw new CatalogError(foundationErrors.notFound, { kontaktId: input.kontaktId });
|
||||
}
|
||||
const created = await tx.kontaktTelefon.create({ data: { tenantId: input.tenantId, kontaktId: input.kontaktId, telefon, primaer: false } });
|
||||
await syncPrimaryTelefonWithTx(tx, input.tenantId, input.kontaktId, input.primaer ? created.id : undefined);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
return created as KontaktTelefonRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function setPrimaryTelefon(input: { tenantId: string; telefonId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const telefon = await tx.kontaktTelefon.findFirst({ where: { id: input.telefonId, tenantId: input.tenantId }, select: { id: true, kontaktId: true } });
|
||||
if (!telefon) {
|
||||
throw new CatalogError(foundationErrors.notFound, { telefonId: input.telefonId });
|
||||
}
|
||||
await syncPrimaryTelefonWithTx(tx, input.tenantId, telefon.kontaktId, telefon.id);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: telefon.kontaktId, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeKontaktTelefon(input: { tenantId: string; telefonId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const telefon = await tx.kontaktTelefon.findFirst({ where: { id: input.telefonId, tenantId: input.tenantId }, select: { id: true, kontaktId: true } });
|
||||
if (!telefon) {
|
||||
throw new CatalogError(foundationErrors.notFound, { telefonId: input.telefonId });
|
||||
}
|
||||
await tx.kontaktTelefon.deleteMany({ where: { id: input.telefonId, tenantId: input.tenantId } });
|
||||
await syncPrimaryTelefonWithTx(tx, input.tenantId, telefon.kontaktId);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: telefon.kontaktId, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
});
|
||||
}
|
||||
|
||||
// --- Relations -------------------------------------------------------------
|
||||
|
||||
export async function addKontaktRelation(input: { tenantId: string; vonKontaktId: string; zuKontaktId: string; rolle: KontaktArt; kontext?: string | null }): Promise<KontaktRelationRow> {
|
||||
if (input.vonKontaktId === input.zuKontaktId) {
|
||||
throw new CrmServiceError("crm.error.selfRelation");
|
||||
}
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const endpoints = await tx.kontakt.findMany({ where: { id: { in: [input.vonKontaktId, input.zuKontaktId] }, tenantId: input.tenantId }, select: { id: true } });
|
||||
if (endpoints.length !== 2) {
|
||||
throw new CatalogError(foundationErrors.notFound, { vonKontaktId: input.vonKontaktId, zuKontaktId: input.zuKontaktId });
|
||||
}
|
||||
try {
|
||||
const created = await tx.kontaktRelation.create({
|
||||
data: { tenantId: input.tenantId, vonKontaktId: input.vonKontaktId, zuKontaktId: input.zuKontaktId, rolle: input.rolle, kontext: input.kontext ?? null },
|
||||
});
|
||||
return created as KontaktRelationRow;
|
||||
} catch (error) {
|
||||
if (isUniqueConstraintError(error)) {
|
||||
throw new CrmServiceError("crm.error.relationExists");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeKontaktRelation(input: { tenantId: string; relationId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, (tx) => tx.kontaktRelation.deleteMany({ where: { id: input.relationId, tenantId: input.tenantId } }));
|
||||
}
|
||||
|
||||
/** All relations touching a contact, in both directions (von/zu). */
|
||||
export async function listRelationsForKontakt(tenantId: string, kontaktId: string): Promise<KontaktRelationRow[]> {
|
||||
const rows = await withTenantRLS(tenantId, (tx) =>
|
||||
tx.kontaktRelation.findMany({
|
||||
where: { tenantId, OR: [{ vonKontaktId: kontaktId }, { zuKontaktId: kontaktId }] },
|
||||
orderBy: { createdAt: "asc" },
|
||||
}),
|
||||
);
|
||||
return rows as KontaktRelationRow[];
|
||||
}
|
||||
|
||||
// --- Visibility / read -----------------------------------------------------
|
||||
|
||||
function isKontaktVisible(kontakt: Pick<KontaktRow, "createdByUserId" | "zustaendigerUserId">, ctx: CrmVisibilityContext): boolean {
|
||||
return canReadAllKontakte(ctx) || kontakt.zustaendigerUserId === ctx.userId || kontakt.createdByUserId === ctx.userId;
|
||||
}
|
||||
|
||||
async function getVisibleKontaktOrThrowWithTx(tx: TenantRlsClient, tenantId: string, kontaktId: string, ctx: CrmVisibilityContext): Promise<KontaktRow> {
|
||||
const kontakt = await tx.kontakt.findFirst({ where: { id: kontaktId, tenantId } });
|
||||
if (!kontakt || !isKontaktVisible(kontakt as KontaktRow, ctx)) {
|
||||
throw new CatalogError(foundationErrors.notFound, { kontaktId });
|
||||
}
|
||||
return kontakt as KontaktRow;
|
||||
}
|
||||
|
||||
/** Load a single contact (tenant-scoped) and enforce owner visibility, else 404. */
|
||||
export async function getVisibleKontaktOrThrow(tenantId: string, kontaktId: string, ctx: CrmVisibilityContext): Promise<KontaktRow> {
|
||||
return withTenantRLS(tenantId, (tx) => getVisibleKontaktOrThrowWithTx(tx, tenantId, kontaktId, ctx));
|
||||
}
|
||||
|
||||
export type KontaktDetail = {
|
||||
kontakt: KontaktRow;
|
||||
emails: KontaktEmailRow[];
|
||||
telefone: KontaktTelefonRow[];
|
||||
relationen: KontaktRelationRow[];
|
||||
adresse: AdresseRow | null;
|
||||
};
|
||||
|
||||
/** Load a contact with its channels, relations and address (visibility-checked). */
|
||||
export async function getKontaktDetail(tenantId: string, kontaktId: string, ctx: CrmVisibilityContext): Promise<KontaktDetail> {
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, tenantId, kontaktId, ctx);
|
||||
const [emails, telefone, relationen, adresse] = await Promise.all([
|
||||
tx.kontaktEmail.findMany({ where: { tenantId, kontaktId }, orderBy: { createdAt: "asc" } }),
|
||||
tx.kontaktTelefon.findMany({ where: { tenantId, kontaktId }, orderBy: { createdAt: "asc" } }),
|
||||
tx.kontaktRelation.findMany({ where: { tenantId, OR: [{ vonKontaktId: kontaktId }, { zuKontaktId: kontaktId }] }, orderBy: { createdAt: "asc" } }),
|
||||
kontakt.adresseId ? tx.adresse.findFirst({ where: { id: kontakt.adresseId, tenantId } }) : Promise.resolve(null),
|
||||
]);
|
||||
return {
|
||||
kontakt,
|
||||
emails: emails as KontaktEmailRow[],
|
||||
telefone: telefone as KontaktTelefonRow[],
|
||||
relationen: relationen as KontaktRelationRow[],
|
||||
adresse: (adresse as AdresseRow | null) ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// --- List / filter / sort / paginate (server-side, DoD 2) ------------------
|
||||
|
||||
export type KontaktSortField = "name" | "createdAt" | "kontaktStatus";
|
||||
export type SortDir = "asc" | "desc";
|
||||
|
||||
export type ListKontakteFilter = {
|
||||
kontaktTyp?: KontaktTyp | null;
|
||||
kontaktStatus?: KontaktStatus | null;
|
||||
zustaendigerUserId?: string | null;
|
||||
search?: string | null;
|
||||
tagIds?: string[] | null;
|
||||
tagMatch?: "and" | "or";
|
||||
includeArchived?: boolean;
|
||||
includeDemoData?: boolean;
|
||||
};
|
||||
|
||||
export type ListKontakteSort = { field: KontaktSortField; dir: SortDir };
|
||||
|
||||
// Tags on Kontakte are stored with TagAssignment.entityType === "kontakt"
|
||||
// (the canonical string for this entity, mirroring CustomFieldEntityType).
|
||||
const KONTAKT_TAG_ENTITY_TYPE = "kontakt";
|
||||
|
||||
function buildOrderBy(sort?: ListKontakteSort): Record<string, SortDir> | Array<Record<string, SortDir>> {
|
||||
if (!sort) {
|
||||
return { createdAt: "desc" };
|
||||
}
|
||||
if (sort.field === "name") {
|
||||
return [{ nachname: sort.dir }, { vorname: sort.dir }, { orgName: sort.dir }];
|
||||
}
|
||||
if (sort.field === "kontaktStatus") {
|
||||
return { kontaktStatus: sort.dir };
|
||||
}
|
||||
return { createdAt: sort.dir };
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the tenant-scoped, owner-filtered, tag/search-filtered `where` for the
|
||||
* contact browser. Returns `{ where, empty }`; `empty` short-circuits to a 0-row
|
||||
* result when a tag filter matched no contacts (avoids an `id IN ()` query).
|
||||
*/
|
||||
async function resolveKontaktBrowserWhereWithTx(
|
||||
tx: TenantRlsClient,
|
||||
tenantId: string,
|
||||
ctx: CrmVisibilityContext,
|
||||
filter: ListKontakteFilter,
|
||||
): Promise<{ where: Record<string, unknown>; empty: boolean }> {
|
||||
const search = filter.search?.trim();
|
||||
let tagScopedIds: string[] | undefined;
|
||||
|
||||
if (filter.tagIds && filter.tagIds.length > 0) {
|
||||
const assignments = await tx.tagAssignment.findMany({
|
||||
where: { tenantId, entityType: KONTAKT_TAG_ENTITY_TYPE, tagId: { in: filter.tagIds } },
|
||||
select: { entityId: true, tagId: true },
|
||||
});
|
||||
if (filter.tagMatch === "and") {
|
||||
const byEntity = new Map<string, Set<string>>();
|
||||
for (const row of assignments) {
|
||||
const set = byEntity.get(row.entityId) ?? new Set<string>();
|
||||
set.add(row.tagId);
|
||||
byEntity.set(row.entityId, set);
|
||||
}
|
||||
const required = new Set(filter.tagIds);
|
||||
tagScopedIds = [...byEntity.entries()].filter(([, tags]) => [...required].every((tag) => tags.has(tag))).map(([entityId]) => entityId);
|
||||
} else {
|
||||
tagScopedIds = [...new Set(assignments.map((row) => row.entityId))];
|
||||
}
|
||||
if (tagScopedIds.length === 0) {
|
||||
return { where: {}, empty: true };
|
||||
}
|
||||
}
|
||||
|
||||
const where = {
|
||||
tenantId,
|
||||
...ownerScopeWhere(ctx),
|
||||
...(filter.includeArchived ? {} : { archivedAt: null }),
|
||||
...(filter.includeDemoData ? {} : { isDemoData: false }),
|
||||
...(filter.kontaktTyp ? { kontaktTyp: filter.kontaktTyp } : {}),
|
||||
...(filter.kontaktStatus ? { kontaktStatus: filter.kontaktStatus } : {}),
|
||||
...(filter.zustaendigerUserId ? { zustaendigerUserId: filter.zustaendigerUserId } : {}),
|
||||
...(tagScopedIds ? { id: { in: tagScopedIds } } : {}),
|
||||
...(search
|
||||
? {
|
||||
OR: [
|
||||
{ vorname: { contains: search, mode: "insensitive" as const } },
|
||||
{ nachname: { contains: search, mode: "insensitive" as const } },
|
||||
{ orgName: { contains: search, mode: "insensitive" as const } },
|
||||
{ primaerEmail: { contains: search, mode: "insensitive" as const } },
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
return { where, empty: false };
|
||||
}
|
||||
|
||||
export async function listKontakteForBrowser(input: {
|
||||
tenantId: string;
|
||||
ctx: CrmVisibilityContext;
|
||||
filter?: ListKontakteFilter;
|
||||
sort?: ListKontakteSort;
|
||||
page?: number;
|
||||
limit?: number;
|
||||
}): Promise<{ rows: KontaktRow[]; total: number; page: number; pageCount: number }> {
|
||||
const limit = Math.min(Math.max(input.limit ?? DEFAULT_LIST_LIMIT, 1), MAX_LIST_LIMIT);
|
||||
const page = Math.max(input.page ?? 1, 1);
|
||||
const filter = input.filter ?? {};
|
||||
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const { where, empty } = await resolveKontaktBrowserWhereWithTx(tx, input.tenantId, input.ctx, filter);
|
||||
if (empty) {
|
||||
return { rows: [], total: 0, page, pageCount: 0 };
|
||||
}
|
||||
const [rows, total] = await Promise.all([
|
||||
tx.kontakt.findMany({ where, orderBy: buildOrderBy(input.sort), skip: (page - 1) * limit, take: limit }),
|
||||
tx.kontakt.count({ where }),
|
||||
]);
|
||||
return { rows: rows as KontaktRow[], total, page, pageCount: Math.ceil(total / limit) };
|
||||
});
|
||||
}
|
||||
|
||||
/** All contacts matching the same browser filter, unpaginated, for CSV export
|
||||
* (DoD 2). The CSV string itself is built in the route / a pure util. */
|
||||
export async function listKontakteForCsv(input: { tenantId: string; ctx: CrmVisibilityContext; filter?: ListKontakteFilter; sort?: ListKontakteSort }): Promise<KontaktRow[]> {
|
||||
const filter = input.filter ?? {};
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const { where, empty } = await resolveKontaktBrowserWhereWithTx(tx, input.tenantId, input.ctx, filter);
|
||||
if (empty) {
|
||||
return [];
|
||||
}
|
||||
const rows = await tx.kontakt.findMany({ where, orderBy: buildOrderBy(input.sort) });
|
||||
return rows as KontaktRow[];
|
||||
});
|
||||
}
|
||||
|
||||
// --- Duplicate detection (DoD 4) -------------------------------------------
|
||||
|
||||
export type DuplicateCheckInput = {
|
||||
tenantId: string;
|
||||
email?: string | null;
|
||||
telefon?: string | null;
|
||||
vorname?: string | null;
|
||||
nachname?: string | null;
|
||||
orgName?: string | null;
|
||||
excludeKontaktId?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Find potential duplicate contacts (tenant-scoped, non-archived). `hard` = exact
|
||||
* channel match (primary or any email/phone row); `soft` = name match only
|
||||
* (excluding hard hits). The contact identified by `excludeKontaktId` is omitted.
|
||||
*/
|
||||
export async function findDuplicateKontakte(input: DuplicateCheckInput): Promise<{ hard: KontaktRow[]; soft: KontaktRow[] }> {
|
||||
const email = input.email?.trim();
|
||||
const telefon = input.telefon?.trim();
|
||||
const vorname = input.vorname?.trim();
|
||||
const nachname = input.nachname?.trim();
|
||||
const orgName = input.orgName?.trim();
|
||||
|
||||
const hardConds: Record<string, unknown>[] = [];
|
||||
if (email) {
|
||||
hardConds.push({ primaerEmail: { equals: email, mode: "insensitive" as const } }, { emails: { some: { email: { equals: email, mode: "insensitive" as const } } } });
|
||||
}
|
||||
if (telefon) {
|
||||
hardConds.push({ primaerTelefon: telefon }, { telefone: { some: { telefon } } });
|
||||
}
|
||||
|
||||
const softConds: Record<string, unknown>[] = [];
|
||||
if (vorname && nachname) {
|
||||
softConds.push({ AND: [{ vorname: { equals: vorname, mode: "insensitive" as const } }, { nachname: { equals: nachname, mode: "insensitive" as const } }] });
|
||||
}
|
||||
if (orgName) {
|
||||
softConds.push({ orgName: { equals: orgName, mode: "insensitive" as const } });
|
||||
}
|
||||
|
||||
if (hardConds.length === 0 && softConds.length === 0) {
|
||||
return { hard: [], soft: [] };
|
||||
}
|
||||
|
||||
const excludeId = input.excludeKontaktId ?? undefined;
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const base = { tenantId: input.tenantId, archivedAt: null, ...(excludeId ? { id: { not: excludeId } } : {}) };
|
||||
const hard = hardConds.length > 0 ? await tx.kontakt.findMany({ where: { ...base, OR: hardConds }, orderBy: { createdAt: "desc" } }) : [];
|
||||
const hardIds = new Set(hard.map((row) => row.id));
|
||||
const softRaw = softConds.length > 0 ? await tx.kontakt.findMany({ where: { ...base, OR: softConds }, orderBy: { createdAt: "desc" } }) : [];
|
||||
const soft = softRaw.filter((row) => !hardIds.has(row.id));
|
||||
return { hard: hard as KontaktRow[], soft: soft as KontaktRow[] };
|
||||
});
|
||||
}
|
||||
|
||||
// --- Bulk actions (DoD 2) --------------------------------------------------
|
||||
|
||||
/** Archive many contacts; only contacts inside the caller's owner-scope are
|
||||
* affected (read_own may not touch others'). Returns the number affected. */
|
||||
export async function bulkArchiveKontakte(input: { tenantId: string; ctx: CrmVisibilityContext; kontaktIds: string[] }): Promise<{ affected: number }> {
|
||||
if (input.kontaktIds.length === 0) {
|
||||
return { affected: 0 };
|
||||
}
|
||||
const result = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.kontakt.updateMany({ where: { id: { in: input.kontaktIds }, tenantId: input.tenantId, ...ownerScopeWhere(input.ctx) }, data: { archivedAt: new Date() } }),
|
||||
);
|
||||
return { affected: result.count };
|
||||
}
|
||||
|
||||
/** Reassign many contacts; owner-scoped like {@link bulkArchiveKontakte}. */
|
||||
export async function bulkReassignKontakte(input: { tenantId: string; ctx: CrmVisibilityContext; kontaktIds: string[]; zustaendigerUserId: string }): Promise<{ affected: number }> {
|
||||
if (input.kontaktIds.length === 0) {
|
||||
return { affected: 0 };
|
||||
}
|
||||
const result = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.kontakt.updateMany({ where: { id: { in: input.kontaktIds }, tenantId: input.tenantId, ...ownerScopeWhere(input.ctx) }, data: { zustaendigerUserId: input.zustaendigerUserId } }),
|
||||
);
|
||||
return { affected: result.count };
|
||||
}
|
||||
|
||||
// --- Directory helpers (zustaendigerUser display + picker) -----------------
|
||||
|
||||
export type LabeledOption = { id: string; label: string };
|
||||
|
||||
function userLabel(user: { firstName: string; lastName: string; email: string }): string {
|
||||
const name = `${user.firstName} ${user.lastName}`.trim();
|
||||
return name || user.email;
|
||||
}
|
||||
|
||||
/** Resolve display labels for a set of user ids (global user table). */
|
||||
export async function resolveUserLabels(userIds: readonly string[]): Promise<Map<string, string>> {
|
||||
const ids = [...new Set(userIds)].filter(Boolean);
|
||||
if (ids.length === 0) {
|
||||
return new Map();
|
||||
}
|
||||
const users = await db.user.findMany({ where: { id: { in: ids } }, select: { id: true, firstName: true, lastName: true, email: true } });
|
||||
return new Map(users.map((user) => [user.id, userLabel(user)]));
|
||||
}
|
||||
|
||||
/** Tenant members as zustaendigerUser picker options (id + display label). */
|
||||
export async function listAssignableUsers(tenantId: string): Promise<LabeledOption[]> {
|
||||
const members = await withTenantRLS(tenantId, (tx) =>
|
||||
tx.tenantUser.findMany({ where: { tenantId }, select: { user: { select: { id: true, firstName: true, lastName: true, email: true } } } }),
|
||||
);
|
||||
return members.filter((member) => member.user).map((member) => ({ id: member.user.id, label: userLabel(member.user) }));
|
||||
}
|
||||
|
||||
// --- internal --------------------------------------------------------------
|
||||
|
||||
function isUniqueConstraintError(error: unknown): boolean {
|
||||
return Boolean(error && typeof error === "object" && "code" in error && (error as { code?: unknown }).code === "P2002");
|
||||
}
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
// R-P6 (P6 CRM core, Variante A) — tenant custom-field service.
|
||||
//
|
||||
// Definitions (CustomFieldDefinition) describe a polymorphic field per entity
|
||||
// type; values (CustomFieldValue) hold the concrete data for a single entity.
|
||||
// `entityId` carries NO DB foreign key — this service validates the entityType
|
||||
// match. Always tenant-scoped via withTenantRLS. NO React/UI imports. Audit +
|
||||
// Activity are wired by the routes (crmAudit), not here.
|
||||
|
||||
import { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import { CatalogError, foundationErrors, type JsonValue } from "@hivegrid/foundation";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { CrmServiceError } from "./crmService.server";
|
||||
|
||||
export type CustomFieldEntityType = "projekt" | "kontakt" | "lead" | "rechnung";
|
||||
export type CustomFieldDatentyp =
|
||||
| "text"
|
||||
| "textarea"
|
||||
| "zahl"
|
||||
| "waehrung"
|
||||
| "datum"
|
||||
| "datum_range"
|
||||
| "select"
|
||||
| "multiselect"
|
||||
| "boolean"
|
||||
| "email"
|
||||
| "telefon"
|
||||
| "datei";
|
||||
|
||||
export type CustomFieldDefinitionRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
entityType: CustomFieldEntityType;
|
||||
key: string;
|
||||
label: string;
|
||||
datentyp: CustomFieldDatentyp;
|
||||
optionen: JsonValue | null;
|
||||
archiviert: boolean;
|
||||
isDemoData: boolean;
|
||||
createdAt: Date;
|
||||
};
|
||||
|
||||
export type CustomFieldValueRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
definitionId: string;
|
||||
entityType: CustomFieldEntityType;
|
||||
entityId: string;
|
||||
wert: JsonValue | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
function toJsonInput(value: JsonValue | null | undefined): Prisma.InputJsonValue | typeof Prisma.JsonNull {
|
||||
return value === null || value === undefined ? Prisma.JsonNull : (value as Prisma.InputJsonValue);
|
||||
}
|
||||
|
||||
// --- Definitions -----------------------------------------------------------
|
||||
|
||||
export async function createCustomFieldDefinition(input: {
|
||||
tenantId: string;
|
||||
entityType: CustomFieldEntityType;
|
||||
key: string;
|
||||
label: string;
|
||||
datentyp: CustomFieldDatentyp;
|
||||
optionen?: JsonValue | null;
|
||||
isDemoData?: boolean;
|
||||
}): Promise<CustomFieldDefinitionRow> {
|
||||
const key = input.key.trim();
|
||||
const label = input.label.trim();
|
||||
if (!key) {
|
||||
throw new CrmServiceError("crm.error.fieldKeyRequired");
|
||||
}
|
||||
if (!label) {
|
||||
throw new CrmServiceError("crm.error.fieldLabelRequired");
|
||||
}
|
||||
try {
|
||||
const created = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.customFieldDefinition.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
entityType: input.entityType,
|
||||
key,
|
||||
label,
|
||||
datentyp: input.datentyp,
|
||||
optionen: toJsonInput(input.optionen),
|
||||
isDemoData: input.isDemoData ?? false,
|
||||
},
|
||||
}),
|
||||
);
|
||||
return created as CustomFieldDefinitionRow;
|
||||
} catch (error) {
|
||||
if (isUniqueConstraintError(error)) {
|
||||
throw new CrmServiceError("crm.error.fieldKeyExists");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateCustomFieldDefinition(input: {
|
||||
tenantId: string;
|
||||
definitionId: string;
|
||||
label?: string;
|
||||
optionen?: JsonValue | null;
|
||||
archiviert?: boolean;
|
||||
}): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const existing = await tx.customFieldDefinition.findFirst({ where: { id: input.definitionId, tenantId: input.tenantId }, select: { id: true } });
|
||||
if (!existing) {
|
||||
throw new CatalogError(foundationErrors.notFound, { definitionId: input.definitionId });
|
||||
}
|
||||
await tx.customFieldDefinition.updateMany({
|
||||
where: { id: input.definitionId, tenantId: input.tenantId },
|
||||
data: {
|
||||
...(input.label !== undefined ? { label: input.label.trim() } : {}),
|
||||
...(input.optionen !== undefined ? { optionen: toJsonInput(input.optionen) } : {}),
|
||||
...(input.archiviert !== undefined ? { archiviert: input.archiviert } : {}),
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function archiveCustomFieldDefinition(input: { tenantId: string; definitionId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const existing = await tx.customFieldDefinition.findFirst({ where: { id: input.definitionId, tenantId: input.tenantId }, select: { id: true } });
|
||||
if (!existing) {
|
||||
throw new CatalogError(foundationErrors.notFound, { definitionId: input.definitionId });
|
||||
}
|
||||
await tx.customFieldDefinition.updateMany({ where: { id: input.definitionId, tenantId: input.tenantId }, data: { archiviert: true } });
|
||||
});
|
||||
}
|
||||
|
||||
export async function listCustomFieldDefinitions(input: { tenantId: string; entityType: CustomFieldEntityType; includeArchived?: boolean }): Promise<CustomFieldDefinitionRow[]> {
|
||||
const rows = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.customFieldDefinition.findMany({
|
||||
where: { tenantId: input.tenantId, entityType: input.entityType, ...(input.includeArchived ? {} : { archiviert: false }) },
|
||||
orderBy: { createdAt: "asc" },
|
||||
}),
|
||||
);
|
||||
return rows as CustomFieldDefinitionRow[];
|
||||
}
|
||||
|
||||
// --- Values ----------------------------------------------------------------
|
||||
|
||||
export async function setCustomFieldValue(input: {
|
||||
tenantId: string;
|
||||
definitionId: string;
|
||||
entityType: CustomFieldEntityType;
|
||||
entityId: string;
|
||||
wert: JsonValue | null;
|
||||
}): Promise<CustomFieldValueRow> {
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const definition = await tx.customFieldDefinition.findFirst({ where: { id: input.definitionId, tenantId: input.tenantId }, select: { entityType: true } });
|
||||
if (!definition) {
|
||||
throw new CatalogError(foundationErrors.notFound, { definitionId: input.definitionId });
|
||||
}
|
||||
if (definition.entityType !== input.entityType) {
|
||||
throw new CrmServiceError("crm.error.entityTypeMismatch");
|
||||
}
|
||||
const value = await tx.customFieldValue.upsert({
|
||||
where: { definitionId_entityId: { definitionId: input.definitionId, entityId: input.entityId } },
|
||||
update: { wert: toJsonInput(input.wert) },
|
||||
create: { tenantId: input.tenantId, definitionId: input.definitionId, entityType: input.entityType, entityId: input.entityId, wert: toJsonInput(input.wert) },
|
||||
});
|
||||
return value as CustomFieldValueRow;
|
||||
});
|
||||
}
|
||||
|
||||
export type CustomFieldValueWithDefinition = { definition: CustomFieldDefinitionRow; wert: JsonValue | null };
|
||||
|
||||
export async function getCustomFieldValues(input: { tenantId: string; entityType: CustomFieldEntityType; entityId: string }): Promise<CustomFieldValueWithDefinition[]> {
|
||||
const rows = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.customFieldValue.findMany({ where: { tenantId: input.tenantId, entityType: input.entityType, entityId: input.entityId }, include: { definition: true }, orderBy: { createdAt: "asc" } }),
|
||||
);
|
||||
return rows.map((row) => ({ definition: row.definition as CustomFieldDefinitionRow, wert: (row.wert as JsonValue | null) ?? null }));
|
||||
}
|
||||
|
||||
// --- SHK demo-seed mechanism (DoD 6) ---------------------------------------
|
||||
|
||||
export type ShkCustomFieldTemplateEntry = {
|
||||
entityType: CustomFieldEntityType;
|
||||
key: string;
|
||||
label: string;
|
||||
datentyp: CustomFieldDatentyp;
|
||||
optionen?: JsonValue;
|
||||
};
|
||||
|
||||
/**
|
||||
* SHK (Sanitär-Heizung-Klima) custom-field template. Filled with Geerkens later
|
||||
* (E3). The seeding mechanism below is complete; the template is intentionally
|
||||
* empty so no SHK fields are invented before the domain workshop.
|
||||
*/
|
||||
export const SHK_CUSTOM_FIELD_TEMPLATE: ReadonlyArray<ShkCustomFieldTemplateEntry> = [];
|
||||
|
||||
/**
|
||||
* Idempotently create the SHK template fields for a tenant as demo data
|
||||
* (`isDemoData = true`). Existing fields with the same (tenant, entityType, key)
|
||||
* are skipped. With the empty template this is a no-op that returns 0.
|
||||
*/
|
||||
export async function seedShkCustomFieldTemplate(input: { tenantId: string }): Promise<{ created: number }> {
|
||||
let created = 0;
|
||||
for (const entry of SHK_CUSTOM_FIELD_TEMPLATE) {
|
||||
const exists = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.customFieldDefinition.findFirst({ where: { tenantId: input.tenantId, entityType: entry.entityType, key: entry.key }, select: { id: true } }),
|
||||
);
|
||||
if (exists) {
|
||||
continue;
|
||||
}
|
||||
await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.customFieldDefinition.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
entityType: entry.entityType,
|
||||
key: entry.key,
|
||||
label: entry.label,
|
||||
datentyp: entry.datentyp,
|
||||
optionen: toJsonInput(entry.optionen ?? null),
|
||||
isDemoData: true,
|
||||
},
|
||||
}),
|
||||
);
|
||||
created += 1;
|
||||
}
|
||||
return { created };
|
||||
}
|
||||
|
||||
/** Bulk-remove demo custom-field definitions on the production switch-over. */
|
||||
export async function clearDemoCustomFields(input: { tenantId: string }): Promise<{ deleted: number }> {
|
||||
const result = await withTenantRLS(input.tenantId, (tx) => tx.customFieldDefinition.deleteMany({ where: { tenantId: input.tenantId, isDemoData: true } }));
|
||||
return { deleted: result.count };
|
||||
}
|
||||
|
||||
// --- internal --------------------------------------------------------------
|
||||
|
||||
function isUniqueConstraintError(error: unknown): boolean {
|
||||
return Boolean(error && typeof error === "object" && "code" in error && (error as { code?: unknown }).code === "P2002");
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { kontaktListQueryToParams, parseKontaktListQuery } from "./kontaktListQuery";
|
||||
|
||||
describe("parseKontaktListQuery", () => {
|
||||
it("falls back to safe defaults on an empty query", () => {
|
||||
const query = parseKontaktListQuery(new URLSearchParams());
|
||||
expect(query).toEqual({
|
||||
filter: {
|
||||
kontaktTyp: null,
|
||||
kontaktStatus: null,
|
||||
zustaendigerUserId: null,
|
||||
search: null,
|
||||
tagIds: null,
|
||||
tagMatch: "or",
|
||||
includeArchived: false,
|
||||
includeDemoData: false,
|
||||
},
|
||||
sort: { field: "createdAt", dir: "desc" },
|
||||
page: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("parses filter, sort, tag and pagination params", () => {
|
||||
const params = new URLSearchParams("typ=organisation&status=kunde&owner=u1&q=meier&tags=t1,t2&tagMatch=and&archived=1&sort=name&dir=asc&page=3");
|
||||
const query = parseKontaktListQuery(params);
|
||||
expect(query.filter).toEqual({
|
||||
kontaktTyp: "organisation",
|
||||
kontaktStatus: "kunde",
|
||||
zustaendigerUserId: "u1",
|
||||
search: "meier",
|
||||
tagIds: ["t1", "t2"],
|
||||
tagMatch: "and",
|
||||
includeArchived: true,
|
||||
includeDemoData: false,
|
||||
});
|
||||
expect(query.sort).toEqual({ field: "name", dir: "asc" });
|
||||
expect(query.page).toBe(3);
|
||||
});
|
||||
|
||||
it("rejects unknown enum / malformed values", () => {
|
||||
const query = parseKontaktListQuery(new URLSearchParams("typ=bogus&status=nope&sort=weird&dir=sideways&page=-4"));
|
||||
expect(query.filter.kontaktTyp).toBeNull();
|
||||
expect(query.filter.kontaktStatus).toBeNull();
|
||||
expect(query.sort).toEqual({ field: "createdAt", dir: "desc" });
|
||||
expect(query.page).toBe(1);
|
||||
});
|
||||
|
||||
it("merges repeated tag params and the csv tags param", () => {
|
||||
const query = parseKontaktListQuery(new URLSearchParams("tag=a&tag=b&tags=b,c"));
|
||||
expect(query.filter.tagIds).toEqual(["a", "b", "c"]);
|
||||
});
|
||||
|
||||
it("round-trips through kontaktListQueryToParams omitting defaults", () => {
|
||||
const params = kontaktListQueryToParams(parseKontaktListQuery(new URLSearchParams()));
|
||||
expect(params.toString()).toBe("");
|
||||
const round = kontaktListQueryToParams(parseKontaktListQuery(new URLSearchParams("status=kunde&sort=name&dir=asc&page=2")));
|
||||
expect(parseKontaktListQuery(round)).toEqual(parseKontaktListQuery(new URLSearchParams("status=kunde&sort=name&dir=asc&page=2")));
|
||||
});
|
||||
|
||||
it("keeps demo data hidden by default and preserves the explicit show flag", () => {
|
||||
expect(parseKontaktListQuery(new URLSearchParams()).filter.includeDemoData).toBe(false);
|
||||
|
||||
const query = parseKontaktListQuery(new URLSearchParams("demo=show"));
|
||||
expect(query.filter.includeDemoData).toBe(true);
|
||||
expect(kontaktListQueryToParams(query).toString()).toBe("demo=show");
|
||||
});
|
||||
});
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
// R-P6 (P6 CRM core, Variante A) — pure URL <-> contact-browser-query mapping.
|
||||
//
|
||||
// The contact list, the organisation list and the CSV export all read the SAME
|
||||
// filter/sort/page state from the request URL (server-side, DoD 2). Keeping the
|
||||
// parse/serialise here (pure, no server imports) lets the loaders and the
|
||||
// pagination/export links share one source of truth and lets it be unit-tested
|
||||
// without a DB. The literal unions mirror crmService's filter/sort types
|
||||
// structurally so the parsed objects drop straight into listKontakteForBrowser.
|
||||
|
||||
export type KontaktTyp = "privatperson" | "organisation";
|
||||
export type KontaktStatus = "kontakt" | "kunde" | "bestandskunde";
|
||||
export type KontaktSortField = "name" | "createdAt" | "kontaktStatus";
|
||||
export type SortDir = "asc" | "desc";
|
||||
|
||||
export interface KontaktListFilter {
|
||||
kontaktTyp: KontaktTyp | null;
|
||||
kontaktStatus: KontaktStatus | null;
|
||||
zustaendigerUserId: string | null;
|
||||
search: string | null;
|
||||
tagIds: string[] | null;
|
||||
tagMatch: "and" | "or";
|
||||
includeArchived: boolean;
|
||||
includeDemoData: boolean;
|
||||
}
|
||||
|
||||
export interface KontaktListSort {
|
||||
field: KontaktSortField;
|
||||
dir: SortDir;
|
||||
}
|
||||
|
||||
export interface KontaktListQuery {
|
||||
filter: KontaktListFilter;
|
||||
sort: KontaktListSort;
|
||||
page: number;
|
||||
}
|
||||
|
||||
const KONTAKT_TYP = new Set<KontaktTyp>(["privatperson", "organisation"]);
|
||||
const KONTAKT_STATUS = new Set<KontaktStatus>(["kontakt", "kunde", "bestandskunde"]);
|
||||
const SORT_FIELD = new Set<KontaktSortField>(["name", "createdAt", "kontaktStatus"]);
|
||||
|
||||
function oneOf<T>(value: string | null, allowed: Set<T>): T | null {
|
||||
return value && (allowed as Set<string>).has(value) ? (value as T) : null;
|
||||
}
|
||||
|
||||
function parseTagIds(params: URLSearchParams): string[] | null {
|
||||
const repeated = params.getAll("tag").map((v) => v.trim()).filter(Boolean);
|
||||
const csv = (params.get("tags") ?? "").split(",").map((v) => v.trim()).filter(Boolean);
|
||||
const ids = [...new Set([...repeated, ...csv])];
|
||||
return ids.length > 0 ? ids : null;
|
||||
}
|
||||
|
||||
/** Parse the request URL search params into a contact-browser query. Unknown /
|
||||
* malformed values fall back to safe defaults (no filter, createdAt desc, p1). */
|
||||
export function parseKontaktListQuery(params: URLSearchParams): KontaktListQuery {
|
||||
const search = params.get("q")?.trim() || null;
|
||||
const sortField = oneOf<KontaktSortField>(params.get("sort"), SORT_FIELD) ?? "createdAt";
|
||||
const dir: SortDir = params.get("dir") === "asc" ? "asc" : "desc";
|
||||
const pageRaw = Number.parseInt(params.get("page") ?? "1", 10);
|
||||
const page = Number.isFinite(pageRaw) && pageRaw > 0 ? pageRaw : 1;
|
||||
|
||||
return {
|
||||
filter: {
|
||||
kontaktTyp: oneOf<KontaktTyp>(params.get("typ"), KONTAKT_TYP),
|
||||
kontaktStatus: oneOf<KontaktStatus>(params.get("status"), KONTAKT_STATUS),
|
||||
zustaendigerUserId: params.get("owner")?.trim() || null,
|
||||
search,
|
||||
tagIds: parseTagIds(params),
|
||||
tagMatch: params.get("tagMatch") === "and" ? "and" : "or",
|
||||
includeArchived: params.get("archived") === "1",
|
||||
includeDemoData: params.get("demo") === "show",
|
||||
},
|
||||
sort: { field: sortField, dir },
|
||||
page,
|
||||
};
|
||||
}
|
||||
|
||||
/** Serialise a query back to a `URLSearchParams` (stable order) for pagination /
|
||||
* export hrefs. Defaults are omitted to keep the URL clean. */
|
||||
export function kontaktListQueryToParams(query: KontaktListQuery): URLSearchParams {
|
||||
const params = new URLSearchParams();
|
||||
const { filter, sort, page } = query;
|
||||
if (filter.kontaktTyp) params.set("typ", filter.kontaktTyp);
|
||||
if (filter.kontaktStatus) params.set("status", filter.kontaktStatus);
|
||||
if (filter.zustaendigerUserId) params.set("owner", filter.zustaendigerUserId);
|
||||
if (filter.search) params.set("q", filter.search);
|
||||
if (filter.tagIds && filter.tagIds.length > 0) params.set("tags", filter.tagIds.join(","));
|
||||
if (filter.tagMatch === "and") params.set("tagMatch", "and");
|
||||
if (filter.includeArchived) params.set("archived", "1");
|
||||
if (filter.includeDemoData) params.set("demo", "show");
|
||||
if (sort.field !== "createdAt") params.set("sort", sort.field);
|
||||
if (sort.dir !== "desc") params.set("dir", sort.dir);
|
||||
if (page > 1) params.set("page", String(page));
|
||||
return params;
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
// R-P6 (P6 CRM core, Variante A) — tag + polymorphic tag-assignment service.
|
||||
//
|
||||
// Tags are tenant-scoped (unique name per tenant). Assignments link a tag to any
|
||||
// entity via a (entityType, entityId) string pair with NO DB foreign key — this
|
||||
// service validates the tag's existence. Always tenant-scoped via withTenantRLS.
|
||||
// NO React/UI imports. Audit + Activity are wired by the routes (crmAudit).
|
||||
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { CrmServiceError } from "./crmService.server";
|
||||
|
||||
export type TagRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
name: string;
|
||||
farbe: string;
|
||||
createdAt: Date;
|
||||
};
|
||||
|
||||
// --- Tag CRUD --------------------------------------------------------------
|
||||
|
||||
export async function createTag(input: { tenantId: string; name: string; farbe: string }): Promise<TagRow> {
|
||||
const name = input.name.trim();
|
||||
if (!name) {
|
||||
throw new CrmServiceError("crm.error.tagNameRequired");
|
||||
}
|
||||
try {
|
||||
const created = await withTenantRLS(input.tenantId, (tx) => tx.tag.create({ data: { tenantId: input.tenantId, name, farbe: input.farbe } }));
|
||||
return created as TagRow;
|
||||
} catch (error) {
|
||||
if (isUniqueConstraintError(error)) {
|
||||
throw new CrmServiceError("crm.error.tagNameExists");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateTag(input: { tenantId: string; tagId: string; name?: string; farbe?: string }): Promise<void> {
|
||||
if (input.name !== undefined && !input.name.trim()) {
|
||||
throw new CrmServiceError("crm.error.tagNameRequired");
|
||||
}
|
||||
try {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const existing = await tx.tag.findFirst({ where: { id: input.tagId, tenantId: input.tenantId }, select: { id: true } });
|
||||
if (!existing) {
|
||||
throw new CatalogError(foundationErrors.notFound, { tagId: input.tagId });
|
||||
}
|
||||
await tx.tag.updateMany({
|
||||
where: { id: input.tagId, tenantId: input.tenantId },
|
||||
data: { ...(input.name !== undefined ? { name: input.name.trim() } : {}), ...(input.farbe !== undefined ? { farbe: input.farbe } : {}) },
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
if (isUniqueConstraintError(error)) {
|
||||
throw new CrmServiceError("crm.error.tagNameExists");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteTag(input: { tenantId: string; tagId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const existing = await tx.tag.findFirst({ where: { id: input.tagId, tenantId: input.tenantId }, select: { id: true } });
|
||||
if (!existing) {
|
||||
throw new CatalogError(foundationErrors.notFound, { tagId: input.tagId });
|
||||
}
|
||||
// TagAssignment rows cascade on Tag delete (schema onDelete: Cascade).
|
||||
await tx.tag.delete({ where: { id: existing.id } });
|
||||
});
|
||||
}
|
||||
|
||||
export async function listTags(tenantId: string): Promise<TagRow[]> {
|
||||
const rows = await withTenantRLS(tenantId, (tx) => tx.tag.findMany({ where: { tenantId }, orderBy: { name: "asc" } }));
|
||||
return rows as TagRow[];
|
||||
}
|
||||
|
||||
// --- Polymorphic assignments -----------------------------------------------
|
||||
|
||||
export async function assignTag(input: { tenantId: string; tagId: string; entityType: string; entityId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const tag = await tx.tag.findFirst({ where: { id: input.tagId, tenantId: input.tenantId }, select: { id: true } });
|
||||
if (!tag) {
|
||||
throw new CatalogError(foundationErrors.notFound, { tagId: input.tagId });
|
||||
}
|
||||
// Idempotent: the (tagId, entityId, entityType) unique key makes re-assign a no-op.
|
||||
await tx.tagAssignment.upsert({
|
||||
where: { tagId_entityId_entityType: { tagId: input.tagId, entityId: input.entityId, entityType: input.entityType } },
|
||||
update: {},
|
||||
create: { tenantId: input.tenantId, tagId: input.tagId, entityType: input.entityType, entityId: input.entityId },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function unassignTag(input: { tenantId: string; tagId: string; entityType: string; entityId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.tagAssignment.deleteMany({ where: { tenantId: input.tenantId, tagId: input.tagId, entityType: input.entityType, entityId: input.entityId } }),
|
||||
);
|
||||
}
|
||||
|
||||
export async function listTagsForEntity(input: { tenantId: string; entityType: string; entityId: string }): Promise<TagRow[]> {
|
||||
const assignments = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.tagAssignment.findMany({ where: { tenantId: input.tenantId, entityType: input.entityType, entityId: input.entityId }, include: { tag: true }, orderBy: { createdAt: "asc" } }),
|
||||
);
|
||||
return assignments.map((assignment) => assignment.tag as TagRow);
|
||||
}
|
||||
|
||||
export async function countTagUsage(tenantId: string, tagId: string): Promise<number> {
|
||||
return withTenantRLS(tenantId, (tx) => tx.tagAssignment.count({ where: { tenantId, tagId } }));
|
||||
}
|
||||
|
||||
// --- internal --------------------------------------------------------------
|
||||
|
||||
function isUniqueConstraintError(error: unknown): boolean {
|
||||
return Boolean(error && typeof error === "object" && "code" in error && (error as { code?: unknown }).code === "P2002");
|
||||
}
|
||||
Reference in new issue
Block a user