Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+14
@@ -0,0 +1,14 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const DETAIL_SOURCE = readFileSync("apps/web/app/utils/integrations/crm/crmDetailRoute.server.ts", "utf8");
|
||||
const LIST_SOURCE = readFileSync("apps/web/app/utils/integrations/crm/crmListRoute.server.ts", "utf8");
|
||||
|
||||
describe("CRM activity i18n contract", () => {
|
||||
it("persists translation keys for machine-authored summaries", () => {
|
||||
const sources = `${DETAIL_SOURCE}\n${LIST_SOURCE}`;
|
||||
expect(sources).toContain('summaryText: "crm.activitySummary.basicsUpdated"');
|
||||
expect(sources).toContain('summaryText: "crm.activitySummary.bulkContactArchived"');
|
||||
expect(sources).not.toMatch(/summaryText: "(?:Stammdaten|Verantwortlicher|E-Mail|Telefonnummer|Verknüpfung|Tag|Kontakt) /);
|
||||
});
|
||||
});
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
// @vitest-environment node
|
||||
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
loadCrmContext: vi.fn(),
|
||||
getVisibleKontaktOrThrow: vi.fn(),
|
||||
validateCsrf: vi.fn(),
|
||||
invitePortalContact: vi.fn(),
|
||||
recordForeignTargetDenial: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("./crmAccess.server", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("./crmAccess.server")>();
|
||||
return { ...original, loadCrmContext: mocks.loadCrmContext };
|
||||
});
|
||||
|
||||
vi.mock("./crmService.server", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("./crmService.server")>();
|
||||
return { ...original, getVisibleKontaktOrThrow: mocks.getVisibleKontaktOrThrow };
|
||||
});
|
||||
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: mocks.validateCsrf }));
|
||||
|
||||
vi.mock("~/services/customer-portal/portal-invitation.server", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("~/services/customer-portal/portal-invitation.server")>();
|
||||
return {
|
||||
...original,
|
||||
invitePortalContact: mocks.invitePortalContact,
|
||||
recordPortalInvitationForeignTargetDenial: mocks.recordForeignTargetDenial,
|
||||
};
|
||||
});
|
||||
|
||||
import { handleKontaktDetailAction } from "./crmDetailRoute.server";
|
||||
|
||||
describe("contact portal invitation object authorization", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.loadCrmContext.mockResolvedValue({
|
||||
tenantId: "tenant-a",
|
||||
userId: "actor-a",
|
||||
permissions: ["crm.read_own", "portal.manage_users"],
|
||||
hasModule: true,
|
||||
});
|
||||
mocks.validateCsrf.mockResolvedValue(undefined);
|
||||
mocks.invitePortalContact.mockResolvedValue("portal-user-a");
|
||||
mocks.recordForeignTargetDenial.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("returns 404 and never invokes the invitation entrypoint for a hidden contact id", async () => {
|
||||
mocks.getVisibleKontaktOrThrow.mockRejectedValue(
|
||||
new CatalogError(foundationErrors.notFound, { kontaktId: "contact-hidden" }),
|
||||
);
|
||||
const request = new Request("https://app.example.test/acme/contacts/contact-hidden", {
|
||||
method: "POST",
|
||||
body: new URLSearchParams({ intent: "invitePortalContact", csrf: "token" }),
|
||||
});
|
||||
|
||||
const response = await handleKontaktDetailAction({
|
||||
request,
|
||||
params: { tenant: "acme", id: "contact-hidden" },
|
||||
variant: "contacts",
|
||||
});
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(mocks.getVisibleKontaktOrThrow).toHaveBeenCalledWith(
|
||||
"tenant-a",
|
||||
"contact-hidden",
|
||||
expect.objectContaining({ userId: "actor-a", permissions: ["crm.read_own", "portal.manage_users"] }),
|
||||
);
|
||||
expect(mocks.validateCsrf).toHaveBeenCalledBefore(mocks.getVisibleKontaktOrThrow);
|
||||
expect(mocks.recordForeignTargetDenial).toHaveBeenCalledWith({
|
||||
tenantId: "tenant-a",
|
||||
actorUserId: "actor-a",
|
||||
operation: "contact_invite",
|
||||
});
|
||||
expect(JSON.stringify(mocks.recordForeignTargetDenial.mock.calls)).not.toContain("contact-hidden");
|
||||
expect(mocks.invitePortalContact).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+146
-36
@@ -14,18 +14,15 @@ import {
|
||||
buildKontaktDetailVM,
|
||||
datentypLabelKey,
|
||||
type ActivityStreamVM,
|
||||
type ClickToCallVM,
|
||||
type KontaktDetailVM,
|
||||
} from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { loadTelephonyContext } from "~/modules/telephony/routes/telephonyAccess.server";
|
||||
import { loadTelephonyClickToCallVM, startTelephonyEntityCall, TelephonyServiceError } from "~/modules/telephony/services/TelephonyService.server";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import {
|
||||
badRequestResponse,
|
||||
crmActionErrorResponse,
|
||||
loadCrmContext,
|
||||
notFoundResponse,
|
||||
requireCrmPermission,
|
||||
type CrmRouteContext,
|
||||
} from "./crmAccess.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { badRequestResponse, crmActionErrorResponse, loadCrmContext, notFoundResponse, requireCrmPermission, type CrmRouteContext } from "./crmAccess.server";
|
||||
import {
|
||||
addKontaktEmail,
|
||||
addKontaktRelation,
|
||||
@@ -52,8 +49,13 @@ import {
|
||||
import { getCustomFieldValues, listCustomFieldDefinitions, setCustomFieldValue } from "./customFieldService.server";
|
||||
import { assignTag, listTags, listTagsForEntity, unassignTag } from "./tagService.server";
|
||||
import { auditCrmEvent, logKontaktActivity } from "./crmAudit.server";
|
||||
import { companiesPath, contactDetailPath, contactsPath, companyDetailPath } from "./crmRoutePaths";
|
||||
import { companiesPath, contactDetailPath, contactsPath, companyDetailPath, tagsAdminPath } from "./crmRoutePaths";
|
||||
import { maskEmailActivitiesForViewer } from "~/modules/emailInbox/services/emailActivityMasking.server";
|
||||
import {
|
||||
canUsePortalInvitationEntrypoint,
|
||||
invitePortalContactFromEntrypoint,
|
||||
portalInvitationActionErrorResponse,
|
||||
} from "~/services/customer-portal/portal-invitation-entrypoint.server";
|
||||
|
||||
const KONTAKT_CUSTOM_FIELD_ENTITY = "kontakt";
|
||||
const KONTAKT_TAG_ENTITY_TYPE = "kontakt";
|
||||
@@ -71,8 +73,11 @@ export type KontaktDetailLoaderData = {
|
||||
detailVM: KontaktDetailVM;
|
||||
activityVM: ActivityStreamVM;
|
||||
allTags: { id: string; name: string; farbe: string }[];
|
||||
/** Set when the viewer may manage tags (crm.admin) — next action for the empty state. */
|
||||
tagsAdminHref: string | null;
|
||||
customFieldDefs: CustomFieldDefOption[];
|
||||
ownerOptions: { id: string; label: string }[];
|
||||
clickToCallVM: ClickToCallVM;
|
||||
};
|
||||
|
||||
type ActivityDbRow = {
|
||||
@@ -96,7 +101,7 @@ async function loadKontaktActivities(tenantId: string, subjectType: "contact" |
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: ACTIVITY_LIMIT + 1,
|
||||
select: { id: true, createdAt: true, actorUserId: true, actorKind: true, activityType: true, summaryText: true, metadata: true },
|
||||
}),
|
||||
})
|
||||
);
|
||||
return rows as ActivityDbRow[];
|
||||
}
|
||||
@@ -128,13 +133,15 @@ export async function loadKontaktDetailData(args: {
|
||||
}
|
||||
const subjectType = detail.kontakt.kontaktTyp === "organisation" ? "company" : "contact";
|
||||
|
||||
const [customFields, tags, definitions, allTags, ownerOptions, activityRows] = await Promise.all([
|
||||
const portalInvitationAffordance = args.variant === "contacts" ? canUsePortalInvitationEntrypoint(ctx) : Promise.resolve(false);
|
||||
const [customFields, tags, definitions, allTags, ownerOptions, activityRows, canInviteToPortal] = await Promise.all([
|
||||
getCustomFieldValues({ tenantId: ctx.tenantId, entityType: KONTAKT_CUSTOM_FIELD_ENTITY, entityId: kontaktId }),
|
||||
listTagsForEntity({ tenantId: ctx.tenantId, entityType: KONTAKT_TAG_ENTITY_TYPE, entityId: kontaktId }),
|
||||
listCustomFieldDefinitions({ tenantId: ctx.tenantId, entityType: KONTAKT_CUSTOM_FIELD_ENTITY }),
|
||||
listTags(ctx.tenantId),
|
||||
listAssignableUsers(ctx.tenantId),
|
||||
loadKontaktActivities(ctx.tenantId, subjectType, kontaktId),
|
||||
portalInvitationAffordance,
|
||||
]);
|
||||
|
||||
const actorIds = activityRows.map((row) => row.actorUserId).filter((id): id is string => Boolean(id));
|
||||
@@ -147,18 +154,44 @@ export async function loadKontaktDetailData(args: {
|
||||
telefone: detail.telefone.map((p) => ({ id: p.id, telefon: p.telefon, primaer: p.primaer })),
|
||||
relationen: detail.relationen.map((r) => ({ id: r.id, vonKontaktId: r.vonKontaktId, zuKontaktId: r.zuKontaktId, rolle: r.rolle, kontext: r.kontext })),
|
||||
adresse: detail.adresse
|
||||
? { strasse: detail.adresse.strasse, hausnummer: detail.adresse.hausnummer, plz: detail.adresse.plz, ort: detail.adresse.ort, land: detail.adresse.land }
|
||||
? {
|
||||
strasse: detail.adresse.strasse,
|
||||
hausnummer: detail.adresse.hausnummer,
|
||||
plz: detail.adresse.plz,
|
||||
ort: detail.adresse.ort,
|
||||
land: detail.adresse.land,
|
||||
}
|
||||
: null,
|
||||
},
|
||||
customFields: customFields.map((cf) => ({
|
||||
definition: { id: cf.definition.id, key: cf.definition.key, label: cf.definition.label, datentyp: cf.definition.datentyp, optionen: cf.definition.optionen },
|
||||
definition: {
|
||||
id: cf.definition.id,
|
||||
key: cf.definition.key,
|
||||
label: cf.definition.label,
|
||||
datentyp: cf.definition.datentyp,
|
||||
optionen: cf.definition.optionen,
|
||||
},
|
||||
wert: cf.wert,
|
||||
})),
|
||||
tags: tags.map((tag) => ({ id: tag.id, name: tag.name, farbe: tag.farbe })),
|
||||
userLabels,
|
||||
perms: { canWrite: ctx.permissions.includes("crm.write"), canDelete: ctx.permissions.includes("crm.delete") },
|
||||
perms: {
|
||||
canWrite: ctx.permissions.includes("crm.write"),
|
||||
canDelete: ctx.permissions.includes("crm.delete"),
|
||||
canInviteToPortal,
|
||||
},
|
||||
tenantSlug,
|
||||
});
|
||||
const telephonyCtx = await loadTelephonyContext({ request: args.request, params: args.params, requireModule: false });
|
||||
const clickToCallVM = await loadTelephonyClickToCallVM(
|
||||
telephonyCtx,
|
||||
detail.telefone.map((phone) => ({
|
||||
id: phone.id,
|
||||
label: detailVM.data?.displayName ?? phone.telefon,
|
||||
e164: phone.telefon,
|
||||
primary: phone.primaer,
|
||||
}))
|
||||
);
|
||||
|
||||
// VA-P23 (M09 Block H): email activities are permission-masked — without
|
||||
// email.read_all only the viewer's OWN mailbox activities show details.
|
||||
@@ -193,6 +226,7 @@ export async function loadKontaktDetailData(args: {
|
||||
detailVM,
|
||||
activityVM,
|
||||
allTags: allTags.map((tag) => ({ id: tag.id, name: tag.name, farbe: tag.farbe })),
|
||||
tagsAdminHref: ctx.permissions.includes("crm.admin") ? tagsAdminPath(tenantSlug) : null,
|
||||
customFieldDefs: definitions.map((def) => ({
|
||||
id: def.id,
|
||||
key: def.key,
|
||||
@@ -201,6 +235,7 @@ export async function loadKontaktDetailData(args: {
|
||||
datentypLabelKey: datentypLabelKey(def.datentyp),
|
||||
})),
|
||||
ownerOptions,
|
||||
clickToCallVM,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -227,15 +262,43 @@ export async function handleKontaktDetailAction(args: {
|
||||
const listHref = args.variant === "companies" ? companiesPath(tenantSlug) : contactsPath(tenantSlug);
|
||||
|
||||
try {
|
||||
// Visibility + type are needed by almost every branch (activity subject).
|
||||
if (intent === "invitePortalContact") {
|
||||
if (args.variant !== "contacts") throw notFoundResponse();
|
||||
await invitePortalContactFromEntrypoint({
|
||||
request: args.request,
|
||||
formData: form,
|
||||
context: ctx,
|
||||
contactId: kontaktId,
|
||||
assertTargetVisible: async () => {
|
||||
await getVisibleKontaktOrThrow(ctx.tenantId, kontaktId, ctx);
|
||||
},
|
||||
});
|
||||
return Response.json({ ok: true, messageKey: "customerPortal.invitation.sent" });
|
||||
}
|
||||
|
||||
// Keep every detail action behind the canonical CRM object-visibility scope.
|
||||
const kontakt: KontaktRow = await getVisibleKontaktOrThrow(ctx.tenantId, kontaktId, ctx);
|
||||
|
||||
// Type is needed by almost every remaining branch (activity subject).
|
||||
const typ = kontakt.kontaktTyp;
|
||||
|
||||
if (intent === "startTelephonyCall") {
|
||||
await validateCSRFToken(args.request, { formData: form });
|
||||
const telephonyCtx = await loadTelephonyContext({ request: args.request, params: args.params, requireModule: true });
|
||||
await startTelephonyEntityCall(telephonyCtx, {
|
||||
entityType: "contact",
|
||||
entityId: kontaktId,
|
||||
numberId: field(form, "numberId"),
|
||||
destination: field(form, "destination"),
|
||||
});
|
||||
return Response.json({ ok: true, messageKey: "crm.toast.callStarted" });
|
||||
}
|
||||
|
||||
if (intent === "delete") {
|
||||
requireCrmPermission(ctx, "crm.delete");
|
||||
await hardDeleteKontakt({ tenantId: ctx.tenantId, kontaktId });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.deleted", targetType: "kontakt", targetId: kontaktId });
|
||||
return redirect(listHref);
|
||||
return redirect(`${listHref}?toast=${encodeURIComponent("crm.toast.contactDeleted")}`);
|
||||
}
|
||||
|
||||
requireCrmPermission(ctx, "crm.write");
|
||||
@@ -252,55 +315,67 @@ export async function handleKontaktDetailAction(args: {
|
||||
orgMerkmal: form.has("orgMerkmal") ? (optionalField(form, "orgMerkmal") as OrgMerkmal | null) : undefined,
|
||||
});
|
||||
await auditCrmEvent({ ctx, action: "kontakt.updated", targetType: "kontakt", targetId: kontaktId });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "Stammdaten aktualisiert" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "crm.activitySummary.basicsUpdated" });
|
||||
// The detail screen's single "Speichern" also carries the owner change,
|
||||
// but only sends `zustaendigerUserId` when it actually differs — so this
|
||||
// reassign runs at most once and never logs a spurious assignee change.
|
||||
if (form.has("zustaendigerUserId")) {
|
||||
const owner = optionalField(form, "zustaendigerUserId");
|
||||
if (owner) {
|
||||
await reassignKontakt({ tenantId: ctx.tenantId, kontaktId, zustaendigerUserId: owner });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.reassigned", targetType: "kontakt", targetId: kontaktId, metadata: { zustaendigerUserId: owner } });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "assignee_changed", summaryText: "crm.activitySummary.assigneeChanged" });
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "addEmail": {
|
||||
await addKontaktEmail({ tenantId: ctx.tenantId, kontaktId, email: field(form, "email"), primaer: form.get("primaer") === "1" });
|
||||
await addKontaktEmail({ tenantId: ctx.tenantId, kontaktId, ctx, email: field(form, "email"), primaer: form.get("primaer") === "1" });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.email_added", targetType: "kontakt", targetId: kontaktId });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "E-Mail hinzugefügt" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "crm.activitySummary.emailAdded" });
|
||||
break;
|
||||
}
|
||||
case "setPrimaryEmail": {
|
||||
await setPrimaryEmail({ tenantId: ctx.tenantId, emailId: field(form, "emailId") });
|
||||
await setPrimaryEmail({ tenantId: ctx.tenantId, kontaktId, ctx, emailId: field(form, "emailId") });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.email_primary_set", targetType: "kontakt", targetId: kontaktId });
|
||||
break;
|
||||
}
|
||||
case "removeEmail": {
|
||||
await removeKontaktEmail({ tenantId: ctx.tenantId, emailId: field(form, "emailId") });
|
||||
await removeKontaktEmail({ tenantId: ctx.tenantId, kontaktId, ctx, emailId: field(form, "emailId") });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.email_removed", targetType: "kontakt", targetId: kontaktId });
|
||||
break;
|
||||
}
|
||||
case "addTelefon": {
|
||||
await addKontaktTelefon({ tenantId: ctx.tenantId, kontaktId, telefon: field(form, "telefon"), primaer: form.get("primaer") === "1" });
|
||||
await addKontaktTelefon({ tenantId: ctx.tenantId, kontaktId, ctx, telefon: field(form, "telefon"), primaer: form.get("primaer") === "1" });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.telefon_added", targetType: "kontakt", targetId: kontaktId });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "Telefonnummer hinzugefügt" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "crm.activitySummary.phoneAdded" });
|
||||
break;
|
||||
}
|
||||
case "setPrimaryTelefon": {
|
||||
await setPrimaryTelefon({ tenantId: ctx.tenantId, telefonId: field(form, "telefonId") });
|
||||
await setPrimaryTelefon({ tenantId: ctx.tenantId, kontaktId, ctx, telefonId: field(form, "telefonId") });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.telefon_primary_set", targetType: "kontakt", targetId: kontaktId });
|
||||
break;
|
||||
}
|
||||
case "removeTelefon": {
|
||||
await removeKontaktTelefon({ tenantId: ctx.tenantId, telefonId: field(form, "telefonId") });
|
||||
await removeKontaktTelefon({ tenantId: ctx.tenantId, kontaktId, ctx, telefonId: field(form, "telefonId") });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.telefon_removed", targetType: "kontakt", targetId: kontaktId });
|
||||
break;
|
||||
}
|
||||
case "addRelation": {
|
||||
await addKontaktRelation({
|
||||
tenantId: ctx.tenantId,
|
||||
vonKontaktId: kontaktId,
|
||||
kontaktId,
|
||||
ctx,
|
||||
zuKontaktId: field(form, "zuKontaktId"),
|
||||
rolle: (field(form, "rolle") || "hauptkontakt") as KontaktArt,
|
||||
kontext: optionalField(form, "kontext"),
|
||||
});
|
||||
await auditCrmEvent({ ctx, action: "kontakt.relation_added", targetType: "kontakt", targetId: kontaktId });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "Verknüpfung hinzugefügt" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "crm.activitySummary.relationAdded" });
|
||||
break;
|
||||
}
|
||||
case "removeRelation": {
|
||||
await removeKontaktRelation({ tenantId: ctx.tenantId, relationId: field(form, "relationId") });
|
||||
await removeKontaktRelation({ tenantId: ctx.tenantId, kontaktId, ctx, relationId: field(form, "relationId") });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.relation_removed", targetType: "kontakt", targetId: kontaktId });
|
||||
break;
|
||||
}
|
||||
@@ -311,27 +386,39 @@ export async function handleKontaktDetailAction(args: {
|
||||
}
|
||||
await reassignKontakt({ tenantId: ctx.tenantId, kontaktId, zustaendigerUserId: owner });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.reassigned", targetType: "kontakt", targetId: kontaktId, metadata: { zustaendigerUserId: owner } });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "assignee_changed", summaryText: "Verantwortlicher geändert" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "assignee_changed", summaryText: "crm.activitySummary.assigneeChanged" });
|
||||
break;
|
||||
}
|
||||
case "addTag": {
|
||||
const tagId = field(form, "tagId");
|
||||
await assignTag({ tenantId: ctx.tenantId, tagId, entityType: KONTAKT_TAG_ENTITY_TYPE, entityId: kontaktId });
|
||||
await auditCrmEvent({ ctx, action: "tag_assignment.assigned", targetType: "tag_assignment", targetId: kontaktId, metadata: { tagId } });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "tag_added", summaryText: "Tag zugewiesen" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "tag_added", summaryText: "crm.activitySummary.tagAssigned" });
|
||||
break;
|
||||
}
|
||||
case "removeTag": {
|
||||
const tagId = field(form, "tagId");
|
||||
await unassignTag({ tenantId: ctx.tenantId, tagId, entityType: KONTAKT_TAG_ENTITY_TYPE, entityId: kontaktId });
|
||||
await auditCrmEvent({ ctx, action: "tag_assignment.unassigned", targetType: "tag_assignment", targetId: kontaktId, metadata: { tagId } });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "tag_removed", summaryText: "Tag entfernt" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "tag_removed", summaryText: "crm.activitySummary.tagRemoved" });
|
||||
break;
|
||||
}
|
||||
case "setCustomField": {
|
||||
const wert: JsonValue = field(form, "wert");
|
||||
await setCustomFieldValue({ tenantId: ctx.tenantId, definitionId: field(form, "definitionId"), entityType: KONTAKT_CUSTOM_FIELD_ENTITY, entityId: kontaktId, wert });
|
||||
await auditCrmEvent({ ctx, action: "custom_field_value.set", targetType: "custom_field_value", targetId: kontaktId, metadata: { definitionId: field(form, "definitionId") } });
|
||||
await setCustomFieldValue({
|
||||
tenantId: ctx.tenantId,
|
||||
definitionId: field(form, "definitionId"),
|
||||
entityType: KONTAKT_CUSTOM_FIELD_ENTITY,
|
||||
entityId: kontaktId,
|
||||
wert,
|
||||
});
|
||||
await auditCrmEvent({
|
||||
ctx,
|
||||
action: "custom_field_value.set",
|
||||
targetType: "custom_field_value",
|
||||
targetId: kontaktId,
|
||||
metadata: { definitionId: field(form, "definitionId") },
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "addNote": {
|
||||
@@ -346,24 +433,47 @@ export async function handleKontaktDetailAction(args: {
|
||||
case "archive": {
|
||||
await archiveKontakt({ tenantId: ctx.tenantId, kontaktId });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.archived", targetType: "kontakt", targetId: kontaktId });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_archived", summaryText: "Kontakt archiviert" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_archived", summaryText: "crm.activitySummary.contactArchived" });
|
||||
break;
|
||||
}
|
||||
case "reactivate": {
|
||||
await reactivateKontakt({ tenantId: ctx.tenantId, kontaktId });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.reactivated", targetType: "kontakt", targetId: kontaktId });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "Kontakt reaktiviert" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "crm.activitySummary.contactReactivated" });
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw badRequestResponse();
|
||||
}
|
||||
|
||||
return redirect(detailHref);
|
||||
const messageKeyByIntent: Record<string, string> = {
|
||||
updateBasics: "crm.toast.contactSaved",
|
||||
addEmail: "crm.toast.emailAdded",
|
||||
setPrimaryEmail: "crm.toast.primaryEmailSet",
|
||||
removeEmail: "crm.toast.emailRemoved",
|
||||
addTelefon: "crm.toast.phoneAdded",
|
||||
setPrimaryTelefon: "crm.toast.primaryPhoneSet",
|
||||
removeTelefon: "crm.toast.phoneRemoved",
|
||||
addRelation: "crm.toast.relationAdded",
|
||||
removeRelation: "crm.toast.relationRemoved",
|
||||
reassign: "crm.toast.contactReassigned",
|
||||
addTag: "crm.toast.tagAssigned",
|
||||
removeTag: "crm.toast.tagRemoved",
|
||||
setCustomField: "crm.toast.customFieldSaved",
|
||||
addNote: "crm.toast.noteAdded",
|
||||
archive: "crm.toast.contactArchived",
|
||||
reactivate: "crm.toast.contactReactivated",
|
||||
};
|
||||
return redirect(`${detailHref}?toast=${encodeURIComponent(messageKeyByIntent[intent ?? ""] ?? "crm.toast.contactSaved")}`);
|
||||
} catch (error) {
|
||||
if (error instanceof Response) {
|
||||
throw error;
|
||||
}
|
||||
if (error instanceof TelephonyServiceError) {
|
||||
return Response.json({ error: error.messageKey }, { status: 400 });
|
||||
}
|
||||
const portalInvitationError = portalInvitationActionErrorResponse(error);
|
||||
if (portalInvitationError) return portalInvitationError;
|
||||
return crmActionErrorResponse(error);
|
||||
}
|
||||
}
|
||||
+104
-33
@@ -21,15 +21,28 @@ import {
|
||||
bulkReassignKontakte,
|
||||
getVisibleKontaktOrThrow,
|
||||
listAssignableUsers,
|
||||
listVisibleKontakteByIds,
|
||||
listKontakteForBrowser,
|
||||
normalizeBulkKontaktIds,
|
||||
reactivateKontakt,
|
||||
resolveUserLabels,
|
||||
type KontaktRow,
|
||||
} from "./crmService.server";
|
||||
import { assignTag, listTags, listTagsForEntity } from "./tagService.server";
|
||||
import { assignTag, listTags, listTagsForEntities, unassignTag } from "./tagService.server";
|
||||
import { auditCrmEvent, logKontaktActivity } from "./crmAudit.server";
|
||||
import { parseKontaktListQuery, kontaktListQueryToParams, type KontaktListQuery } from "./kontaktListQuery";
|
||||
import { companiesPath, companyDetailPath, contactDetailPath, contactNewPath, contactsExportPath, contactsPath } from "./crmRoutePaths";
|
||||
import { isDemoDataUiEnabled } from "~/utils/services/.server/demoDataUi.server";
|
||||
import {
|
||||
companiesPath,
|
||||
companyDetailPath,
|
||||
contactDetailPath,
|
||||
contactNewPath,
|
||||
contactsExportPath,
|
||||
contactsPath,
|
||||
customFieldsAdminPath,
|
||||
duplicatesAdminPath,
|
||||
tagsAdminPath,
|
||||
} from "./crmRoutePaths";
|
||||
|
||||
// The canonical TagAssignment.entityType for a Kontakt (mirrors crmService).
|
||||
const KONTAKT_TAG_ENTITY_TYPE = "kontakt";
|
||||
@@ -49,7 +62,18 @@ export type KontaktListLoaderData = {
|
||||
query: KontaktListQuery;
|
||||
baseHref: string;
|
||||
newHref: string;
|
||||
/** Current user — pre-selected owner in the "Neuer Kontakt" dialog. */
|
||||
defaultOwnerId: string;
|
||||
exportHref: string;
|
||||
/** Top-level perms so the header CTA + admin nav work even on an empty list
|
||||
* (the VM is `empty` for 0 rows, so its data-derived perms are null then). */
|
||||
canWrite: boolean;
|
||||
canAdmin: boolean;
|
||||
contactsHref: string;
|
||||
companiesHref: string;
|
||||
customFieldsHref: string;
|
||||
tagsHref: string;
|
||||
duplicatesHref: string;
|
||||
};
|
||||
|
||||
function variantQuery(variant: KontaktListVariant, query: KontaktListQuery): KontaktListQuery {
|
||||
@@ -71,7 +95,12 @@ export async function loadKontaktListData(args: {
|
||||
const titleKey = args.variant === "companies" ? "crm.companies.title" : "crm.contacts.title";
|
||||
const baseHref = args.variant === "companies" ? companiesPath(tenantSlug) : contactsPath(tenantSlug);
|
||||
const url = new URL(args.request.url);
|
||||
const query = variantQuery(args.variant, parseKontaktListQuery(url.searchParams));
|
||||
const parsed = variantQuery(args.variant, parseKontaktListQuery(url.searchParams));
|
||||
// Outside staging/dev the `demo=show` query param is ignored server-side
|
||||
// (demo data is a staging/dev-only affordance).
|
||||
const query = isDemoDataUiEnabled(undefined, { tenantId: ctx.tenantId, tenantSlug })
|
||||
? parsed
|
||||
: { ...parsed, filter: { ...parsed.filter, includeDemoData: false } };
|
||||
|
||||
const base: Omit<KontaktListLoaderData, "vm" | "tagOptions" | "ownerOptions"> = {
|
||||
title: `${t(titleKey)} | ${process.env.APP_NAME}`,
|
||||
@@ -80,7 +109,15 @@ export async function loadKontaktListData(args: {
|
||||
query,
|
||||
baseHref,
|
||||
newHref: contactNewPath(tenantSlug),
|
||||
defaultOwnerId: ctx.userId,
|
||||
exportHref: `${contactsExportPath(tenantSlug)}?${kontaktListQueryToParams(query).toString()}`,
|
||||
canWrite: ctx.permissions.includes("crm.write"),
|
||||
canAdmin: ctx.permissions.includes("crm.admin"),
|
||||
contactsHref: contactsPath(tenantSlug),
|
||||
companiesHref: companiesPath(tenantSlug),
|
||||
customFieldsHref: customFieldsAdminPath(tenantSlug),
|
||||
tagsHref: tagsAdminPath(tenantSlug),
|
||||
duplicatesHref: duplicatesAdminPath(tenantSlug),
|
||||
};
|
||||
|
||||
if (!ctx.hasModule) {
|
||||
@@ -106,15 +143,16 @@ export async function loadKontaktListData(args: {
|
||||
listAssignableUsers(ctx.tenantId),
|
||||
]);
|
||||
|
||||
const tagsByKontakt = new Map<string, KontaktTagOption[]>();
|
||||
await Promise.all(
|
||||
rows.map(async (row) => {
|
||||
const tags = await listTagsForEntity({ tenantId: ctx.tenantId, entityType: KONTAKT_TAG_ENTITY_TYPE, entityId: row.id });
|
||||
tagsByKontakt.set(
|
||||
row.id,
|
||||
tags.map((tag) => ({ id: tag.id, name: tag.name, farbe: tag.farbe })),
|
||||
);
|
||||
}),
|
||||
const tagRowsByKontakt = await listTagsForEntities({
|
||||
tenantId: ctx.tenantId,
|
||||
entityType: KONTAKT_TAG_ENTITY_TYPE,
|
||||
entityIds: rows.map((row) => row.id),
|
||||
});
|
||||
const tagsByKontakt = new Map<string, KontaktTagOption[]>(
|
||||
[...tagRowsByKontakt].map(([entityId, tags]) => [
|
||||
entityId,
|
||||
tags.map((tag) => ({ id: tag.id, name: tag.name, farbe: tag.farbe })),
|
||||
]),
|
||||
);
|
||||
|
||||
const detailHrefFor = (row: { id: string }) =>
|
||||
@@ -166,21 +204,18 @@ function emptyVmInput(tenantSlug: string) {
|
||||
}
|
||||
|
||||
function parseIds(form: FormData): string[] {
|
||||
return [...new Set(form.getAll("kontaktId").map((v) => v.toString().trim()).filter(Boolean))];
|
||||
return normalizeBulkKontaktIds(form.getAll("kontaktId").map((value) => value.toString()));
|
||||
}
|
||||
|
||||
/** Resolve the visible target contacts for a bulk action (owner-scope enforced
|
||||
* per item). Returns the rows so the activity log can pick the right subject. */
|
||||
async function visibleTargets(tenantId: string, ctx: Parameters<typeof getVisibleKontaktOrThrow>[2], ids: string[]): Promise<KontaktRow[]> {
|
||||
const targets: KontaktRow[] = [];
|
||||
for (const id of ids) {
|
||||
try {
|
||||
targets.push(await getVisibleKontaktOrThrow(tenantId, id, ctx));
|
||||
} catch {
|
||||
// Skip contacts the caller may not touch (read_own); never fail the batch.
|
||||
}
|
||||
}
|
||||
return targets;
|
||||
async function visibleTargets(
|
||||
tenantId: string,
|
||||
ctx: Parameters<typeof getVisibleKontaktOrThrow>[2],
|
||||
ids: string[],
|
||||
options?: { includeArchived?: boolean },
|
||||
): Promise<KontaktRow[]> {
|
||||
return listVisibleKontakteByIds({ tenantId, ctx, kontaktIds: ids, includeArchived: options?.includeArchived });
|
||||
}
|
||||
|
||||
export async function handleKontaktListAction(args: {
|
||||
@@ -192,7 +227,8 @@ export async function handleKontaktListAction(args: {
|
||||
const tenantSlug = args.params.tenant ?? "";
|
||||
const form = await args.request.formData();
|
||||
const intent = form.get("intent")?.toString();
|
||||
const redirectBack = redirect(args.variant === "companies" ? companiesPath(tenantSlug) : contactsPath(tenantSlug));
|
||||
const baseHref = args.variant === "companies" ? companiesPath(tenantSlug) : contactsPath(tenantSlug);
|
||||
const redirectBack = (messageKey: string) => redirect(`${baseHref}?toast=${encodeURIComponent(messageKey)}`);
|
||||
|
||||
try {
|
||||
if (intent === "archive" || intent === "reactivate") {
|
||||
@@ -205,13 +241,13 @@ export async function handleKontaktListAction(args: {
|
||||
if (intent === "archive") {
|
||||
await archiveKontakt({ tenantId: ctx.tenantId, kontaktId });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.archived", targetType: "kontakt", targetId: kontaktId });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: kontakt.kontaktTyp, activityType: "contact_archived", summaryText: "Kontakt archiviert" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: kontakt.kontaktTyp, activityType: "contact_archived", summaryText: "crm.activitySummary.contactArchived" });
|
||||
} else {
|
||||
await reactivateKontakt({ tenantId: ctx.tenantId, kontaktId });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.reactivated", targetType: "kontakt", targetId: kontaktId });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: kontakt.kontaktTyp, activityType: "contact_updated", summaryText: "Kontakt reaktiviert" });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: kontakt.kontaktTyp, activityType: "contact_updated", summaryText: "crm.activitySummary.contactReactivated" });
|
||||
}
|
||||
return redirectBack;
|
||||
return redirectBack(intent === "archive" ? "crm.toast.contactArchived" : "crm.toast.contactReactivated");
|
||||
}
|
||||
|
||||
if (intent === "bulkArchive") {
|
||||
@@ -222,10 +258,24 @@ export async function handleKontaktListAction(args: {
|
||||
await bulkArchiveKontakte({ tenantId: ctx.tenantId, ctx, kontaktIds: ids });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.bulk_archived", targetType: "kontakt", targetId: ids[0], metadata: { kontaktIds: ids } });
|
||||
for (const target of targets) {
|
||||
await logKontaktActivity({ ctx, kontaktId: target.id, kontaktTyp: target.kontaktTyp, activityType: "contact_archived", summaryText: "Kontakt archiviert (Massenaktion)" });
|
||||
await logKontaktActivity({ ctx, kontaktId: target.id, kontaktTyp: target.kontaktTyp, activityType: "contact_archived", summaryText: "crm.activitySummary.bulkContactArchived" });
|
||||
}
|
||||
}
|
||||
return redirectBack;
|
||||
return redirectBack("crm.toast.contactsArchived");
|
||||
}
|
||||
|
||||
if (intent === "bulkReactivate") {
|
||||
requireCrmPermission(ctx, "crm.write");
|
||||
// Archived rows are the whole point here, so opt into them explicitly.
|
||||
const targets = await visibleTargets(ctx.tenantId, ctx, parseIds(form), { includeArchived: true });
|
||||
// No bulk helper exists for reactivation — mirror the single-contact path
|
||||
// per target so audit + activity stay consistent with a manual un-archive.
|
||||
for (const target of targets) {
|
||||
await reactivateKontakt({ tenantId: ctx.tenantId, kontaktId: target.id });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.reactivated", targetType: "kontakt", targetId: target.id, metadata: { bulk: true } });
|
||||
await logKontaktActivity({ ctx, kontaktId: target.id, kontaktTyp: target.kontaktTyp, activityType: "contact_updated", summaryText: "crm.activitySummary.bulkContactReactivated" });
|
||||
}
|
||||
return redirectBack("crm.toast.contactsReactivated");
|
||||
}
|
||||
|
||||
if (intent === "bulkReassign") {
|
||||
@@ -240,10 +290,10 @@ export async function handleKontaktListAction(args: {
|
||||
await bulkReassignKontakte({ tenantId: ctx.tenantId, ctx, kontaktIds: ids, zustaendigerUserId: owner });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.bulk_reassigned", targetType: "kontakt", targetId: ids[0], metadata: { kontaktIds: ids, zustaendigerUserId: owner } });
|
||||
for (const target of targets) {
|
||||
await logKontaktActivity({ ctx, kontaktId: target.id, kontaktTyp: target.kontaktTyp, activityType: "assignee_changed", summaryText: "Verantwortlicher geändert (Massenaktion)" });
|
||||
await logKontaktActivity({ ctx, kontaktId: target.id, kontaktTyp: target.kontaktTyp, activityType: "assignee_changed", summaryText: "crm.activitySummary.bulkAssigneeChanged" });
|
||||
}
|
||||
}
|
||||
return redirectBack;
|
||||
return redirectBack("crm.toast.contactsReassigned");
|
||||
}
|
||||
|
||||
if (intent === "bulkTag") {
|
||||
@@ -256,9 +306,30 @@ export async function handleKontaktListAction(args: {
|
||||
for (const target of targets) {
|
||||
await assignTag({ tenantId: ctx.tenantId, tagId, entityType: KONTAKT_TAG_ENTITY_TYPE, entityId: target.id });
|
||||
await auditCrmEvent({ ctx, action: "tag_assignment.assigned", targetType: "tag_assignment", targetId: target.id, metadata: { tagId } });
|
||||
await logKontaktActivity({ ctx, kontaktId: target.id, kontaktTyp: target.kontaktTyp, activityType: "tag_added", summaryText: "Tag zugewiesen (Massenaktion)" });
|
||||
await logKontaktActivity({ ctx, kontaktId: target.id, kontaktTyp: target.kontaktTyp, activityType: "tag_added", summaryText: "crm.activitySummary.bulkTagAssigned" });
|
||||
}
|
||||
return redirectBack;
|
||||
return redirectBack("crm.toast.contactsTagged");
|
||||
}
|
||||
|
||||
if (intent === "assignTag" || intent === "removeTag") {
|
||||
requireCrmPermission(ctx, "crm.write");
|
||||
const kontaktId = form.get("kontaktId")?.toString().trim();
|
||||
const tagId = form.get("tagId")?.toString().trim();
|
||||
if (!kontaktId || !tagId) {
|
||||
throw badRequestResponse();
|
||||
}
|
||||
// Owner visibility is enforced per contact (404 for a hidden one).
|
||||
const kontakt = await getVisibleKontaktOrThrow(ctx.tenantId, kontaktId, ctx);
|
||||
if (intent === "assignTag") {
|
||||
await assignTag({ tenantId: ctx.tenantId, tagId, entityType: KONTAKT_TAG_ENTITY_TYPE, entityId: kontaktId });
|
||||
await auditCrmEvent({ ctx, action: "tag_assignment.assigned", targetType: "tag_assignment", targetId: kontaktId, metadata: { tagId } });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: kontakt.kontaktTyp, activityType: "tag_added", summaryText: "crm.activitySummary.tagAssigned" });
|
||||
} else {
|
||||
await unassignTag({ tenantId: ctx.tenantId, tagId, entityType: KONTAKT_TAG_ENTITY_TYPE, entityId: kontaktId });
|
||||
await auditCrmEvent({ ctx, action: "tag_assignment.unassigned", targetType: "tag_assignment", targetId: kontaktId, metadata: { tagId } });
|
||||
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: kontakt.kontaktTyp, activityType: "tag_removed", summaryText: "crm.activitySummary.tagRemoved" });
|
||||
}
|
||||
return redirectBack(intent === "assignTag" ? "crm.toast.tagAssigned" : "crm.toast.tagRemoved");
|
||||
}
|
||||
|
||||
throw badRequestResponse();
|
||||
|
||||
+325
@@ -0,0 +1,325 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tx: {
|
||||
tenantUser: { findFirst: vi.fn() },
|
||||
kontakt: { findFirst: vi.fn(), findMany: vi.fn(), update: vi.fn(), updateMany: vi.fn() },
|
||||
kontaktEmail: { findFirst: vi.fn(), findMany: vi.fn(), updateMany: vi.fn(), deleteMany: vi.fn() },
|
||||
kontaktTelefon: { findFirst: vi.fn(), findMany: vi.fn(), updateMany: vi.fn(), deleteMany: vi.fn() },
|
||||
kontaktRelation: { findFirst: vi.fn(), findMany: vi.fn(), create: vi.fn(), deleteMany: vi.fn() },
|
||||
adresse: { findFirst: vi.fn() },
|
||||
},
|
||||
publishKontaktSearchUpsert: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: async (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
|
||||
}));
|
||||
vi.mock("~/utils/db.server", () => ({ db: {} }));
|
||||
vi.mock("~/services/search/searchIndexProjection.server", () => ({
|
||||
publishKontaktSearchUpsert: mocks.publishKontaktSearchUpsert,
|
||||
publishSearchProjectionDelete: vi.fn(),
|
||||
}));
|
||||
|
||||
import {
|
||||
addKontaktRelation,
|
||||
bulkReassignKontakte,
|
||||
CRM_BULK_MAX_CONTACTS,
|
||||
getKontaktDetail,
|
||||
getVisibleKontaktOrThrow,
|
||||
listRelationsForKontakt,
|
||||
listVisibleKontakteByIds,
|
||||
normalizeBulkKontaktIds,
|
||||
reassignKontakt,
|
||||
removeKontaktEmail,
|
||||
removeKontaktRelation,
|
||||
removeKontaktTelefon,
|
||||
setPrimaryEmail,
|
||||
setPrimaryTelefon,
|
||||
} from "./crmService.server";
|
||||
|
||||
describe("CRM assignee tenant boundary", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.tx.kontakt.findFirst.mockResolvedValue({ id: "contact-a" });
|
||||
mocks.tx.kontakt.findMany.mockResolvedValue([]);
|
||||
mocks.tx.kontakt.update.mockResolvedValue({ id: "contact-a" });
|
||||
mocks.tx.kontakt.updateMany.mockResolvedValue({ count: 1 });
|
||||
mocks.tx.kontaktEmail.findMany.mockResolvedValue([]);
|
||||
mocks.tx.kontaktTelefon.findMany.mockResolvedValue([]);
|
||||
mocks.tx.kontaktRelation.findMany.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("deduplicates bulk IDs and rejects payloads above the hard cap", () => {
|
||||
expect(normalizeBulkKontaktIds([" contact-a ", "contact-a", "", "contact-b"])).toEqual(["contact-a", "contact-b"]);
|
||||
expect(() => normalizeBulkKontaktIds(Array.from({ length: CRM_BULK_MAX_CONTACTS + 1 }, (_, index) => `contact-${index}`))).toThrow(
|
||||
"foundation.mass_action_exceeds_limit"
|
||||
);
|
||||
});
|
||||
|
||||
it("batch-loads visible contacts once and preserves the requested order", async () => {
|
||||
mocks.tx.kontakt.findMany.mockResolvedValue([
|
||||
{ id: "contact-b", tenantId: "tenant-a" },
|
||||
{ id: "contact-a", tenantId: "tenant-a" },
|
||||
]);
|
||||
|
||||
await expect(
|
||||
listVisibleKontakteByIds({
|
||||
tenantId: "tenant-a",
|
||||
ctx: { userId: "actor-a", permissions: ["crm.read_all"] },
|
||||
kontaktIds: ["contact-a", "contact-b", "contact-a"],
|
||||
})
|
||||
).resolves.toEqual([
|
||||
{ id: "contact-a", tenantId: "tenant-a" },
|
||||
{ id: "contact-b", tenantId: "tenant-a" },
|
||||
]);
|
||||
|
||||
expect(mocks.tx.kontakt.findMany).toHaveBeenCalledOnce();
|
||||
expect(mocks.tx.kontakt.findMany).toHaveBeenCalledWith({
|
||||
where: { id: { in: ["contact-a", "contact-b"] }, tenantId: "tenant-a", archivedAt: null },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a foreign or inactive assignee before changing a contact", async () => {
|
||||
mocks.tx.tenantUser.findFirst.mockResolvedValue(null);
|
||||
|
||||
await expect(reassignKontakt({ tenantId: "tenant-a", kontaktId: "contact-a", zustaendigerUserId: "foreign-user" })).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.tenantUser.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
tenantId: "tenant-a",
|
||||
userId: "foreign-user",
|
||||
status: TenantUserStatus.ACTIVE,
|
||||
user: { active: true },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.tx.kontakt.findFirst).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.kontakt.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("applies the same active tenant membership check to bulk reassignment", async () => {
|
||||
mocks.tx.tenantUser.findFirst.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
bulkReassignKontakte({
|
||||
tenantId: "tenant-a",
|
||||
ctx: { userId: "actor-a", permissions: ["crm.read_all"] },
|
||||
kontaktIds: ["contact-a"],
|
||||
zustaendigerUserId: "foreign-user",
|
||||
})
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.kontakt.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not let a creator retain crm.read_own visibility after reassignment", async () => {
|
||||
const reassignedContact = {
|
||||
id: "contact-b",
|
||||
tenantId: "tenant-a",
|
||||
createdByUserId: "actor-a",
|
||||
zustaendigerUserId: "actor-b",
|
||||
};
|
||||
mocks.tx.kontakt.findFirst.mockImplementation(async (args: { where?: { id?: string; tenantId?: string; zustaendigerUserId?: string } }) =>
|
||||
args.where?.id === reassignedContact.id &&
|
||||
args.where?.tenantId === reassignedContact.tenantId &&
|
||||
args.where?.zustaendigerUserId === reassignedContact.zustaendigerUserId
|
||||
? reassignedContact
|
||||
: null
|
||||
);
|
||||
|
||||
await expect(
|
||||
getVisibleKontaktOrThrow("tenant-a", "contact-b", {
|
||||
userId: "actor-a",
|
||||
permissions: ["crm.read_own"],
|
||||
})
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.kontakt.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: "contact-b",
|
||||
tenantId: "tenant-a",
|
||||
zustaendigerUserId: "actor-a",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("filters detail relations when the other contact is outside crm.read_own", async () => {
|
||||
mocks.tx.kontakt.findFirst.mockResolvedValue({
|
||||
id: "contact-a",
|
||||
tenantId: "tenant-a",
|
||||
adresseId: null,
|
||||
zustaendigerUserId: "actor-a",
|
||||
});
|
||||
mocks.tx.kontaktRelation.findMany.mockResolvedValue([
|
||||
{ id: "relation-a-b", vonKontaktId: "contact-a", zuKontaktId: "contact-b" },
|
||||
{ id: "relation-c-a", vonKontaktId: "contact-c", zuKontaktId: "contact-a" },
|
||||
]);
|
||||
mocks.tx.kontakt.findMany.mockResolvedValue([{ id: "contact-b" }]);
|
||||
|
||||
const detail = await getKontaktDetail("tenant-a", "contact-a", {
|
||||
userId: "actor-a",
|
||||
permissions: ["crm.read_own"],
|
||||
});
|
||||
|
||||
expect(detail.relationen).toEqual([{ id: "relation-a-b", vonKontaktId: "contact-a", zuKontaktId: "contact-b" }]);
|
||||
expect(mocks.tx.kontakt.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: { in: ["contact-b", "contact-c"] },
|
||||
tenantId: "tenant-a",
|
||||
zustaendigerUserId: "actor-a",
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("requires context and filters both relation directions in the direct relation API", async () => {
|
||||
mocks.tx.kontaktRelation.findMany.mockResolvedValue([
|
||||
{ id: "relation-a-b", vonKontaktId: "contact-a", zuKontaktId: "contact-b" },
|
||||
{ id: "relation-c-a", vonKontaktId: "contact-c", zuKontaktId: "contact-a" },
|
||||
]);
|
||||
mocks.tx.kontakt.findMany.mockResolvedValue([{ id: "contact-c" }]);
|
||||
|
||||
await expect(
|
||||
listRelationsForKontakt("tenant-a", "contact-a", {
|
||||
userId: "actor-a",
|
||||
permissions: ["crm.read_own"],
|
||||
})
|
||||
).resolves.toEqual([{ id: "relation-c-a", vonKontaktId: "contact-c", zuKontaktId: "contact-a" }]);
|
||||
|
||||
expect(mocks.tx.kontakt.findFirst).toHaveBeenCalledWith({
|
||||
where: { id: "contact-a", tenantId: "tenant-a", zustaendigerUserId: "actor-a" },
|
||||
});
|
||||
expect(mocks.tx.kontakt.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: { in: ["contact-b", "contact-c"] },
|
||||
tenantId: "tenant-a",
|
||||
zustaendigerUserId: "actor-a",
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("returns 404 before listing relations when the requested contact is outside the caller scope", async () => {
|
||||
mocks.tx.kontakt.findFirst.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
listRelationsForKontakt("tenant-a", "contact-from-tenant-b", {
|
||||
userId: "actor-a",
|
||||
permissions: ["crm.read_own"],
|
||||
})
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.kontaktRelation.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects email IDs from another contact before changing or deleting them", async () => {
|
||||
mocks.tx.kontaktEmail.findFirst.mockResolvedValue(null);
|
||||
const input = {
|
||||
tenantId: "tenant-a",
|
||||
kontaktId: "contact-a",
|
||||
ctx: { userId: "actor-a", permissions: ["crm.read_own"] },
|
||||
emailId: "email-from-contact-b",
|
||||
};
|
||||
|
||||
await expect(setPrimaryEmail(input)).rejects.toMatchObject({ status: 404 });
|
||||
await expect(removeKontaktEmail(input)).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
const scopedLookup = {
|
||||
where: {
|
||||
id: "email-from-contact-b",
|
||||
tenantId: "tenant-a",
|
||||
kontaktId: "contact-a",
|
||||
},
|
||||
select: { id: true, kontaktId: true },
|
||||
};
|
||||
expect(mocks.tx.kontaktEmail.findFirst).toHaveBeenNthCalledWith(1, scopedLookup);
|
||||
expect(mocks.tx.kontaktEmail.findFirst).toHaveBeenNthCalledWith(2, scopedLookup);
|
||||
expect(mocks.tx.kontaktEmail.updateMany).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.kontaktEmail.deleteMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects telephone IDs from another contact before changing or deleting them", async () => {
|
||||
mocks.tx.kontaktTelefon.findFirst.mockResolvedValue(null);
|
||||
const input = {
|
||||
tenantId: "tenant-a",
|
||||
kontaktId: "contact-a",
|
||||
ctx: { userId: "actor-a", permissions: ["crm.read_own"] },
|
||||
telefonId: "telephone-from-contact-b",
|
||||
};
|
||||
|
||||
await expect(setPrimaryTelefon(input)).rejects.toMatchObject({ status: 404 });
|
||||
await expect(removeKontaktTelefon(input)).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
const scopedLookup = {
|
||||
where: {
|
||||
id: "telephone-from-contact-b",
|
||||
tenantId: "tenant-a",
|
||||
kontaktId: "contact-a",
|
||||
},
|
||||
select: { id: true, kontaktId: true },
|
||||
};
|
||||
expect(mocks.tx.kontaktTelefon.findFirst).toHaveBeenNthCalledWith(1, scopedLookup);
|
||||
expect(mocks.tx.kontaktTelefon.findFirst).toHaveBeenNthCalledWith(2, scopedLookup);
|
||||
expect(mocks.tx.kontaktTelefon.updateMany).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.kontaktTelefon.deleteMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects adding a relation when the target contact is not visible", async () => {
|
||||
mocks.tx.kontakt.findFirst.mockImplementation(async (args: { where?: { id?: string; tenantId?: string; zustaendigerUserId?: string } }) =>
|
||||
args.where?.id === "contact-a" && args.where?.tenantId === "tenant-a" && args.where?.zustaendigerUserId === "actor-a" ? { id: "contact-a" } : null
|
||||
);
|
||||
|
||||
await expect(
|
||||
addKontaktRelation({
|
||||
tenantId: "tenant-a",
|
||||
kontaktId: "contact-a",
|
||||
ctx: { userId: "actor-a", permissions: ["crm.read_own"] },
|
||||
zuKontaktId: "contact-b",
|
||||
rolle: "hauptkontakt",
|
||||
})
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.kontakt.findFirst).toHaveBeenNthCalledWith(1, {
|
||||
where: { id: "contact-a", tenantId: "tenant-a", zustaendigerUserId: "actor-a" },
|
||||
});
|
||||
expect(mocks.tx.kontakt.findFirst).toHaveBeenNthCalledWith(2, {
|
||||
where: { id: "contact-b", tenantId: "tenant-a", zustaendigerUserId: "actor-a" },
|
||||
});
|
||||
expect(mocks.tx.kontaktRelation.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects removing a URL-contact relation when its other endpoint is not visible", async () => {
|
||||
mocks.tx.kontakt.findFirst.mockImplementation(async (args: { where?: { id?: string; tenantId?: string; zustaendigerUserId?: string } }) =>
|
||||
args.where?.id === "contact-a" && args.where?.tenantId === "tenant-a" && args.where?.zustaendigerUserId === "actor-a" ? { id: "contact-a" } : null
|
||||
);
|
||||
mocks.tx.kontaktRelation.findFirst.mockResolvedValue({
|
||||
id: "relation-a-b",
|
||||
vonKontaktId: "contact-a",
|
||||
zuKontaktId: "contact-b",
|
||||
});
|
||||
|
||||
await expect(
|
||||
removeKontaktRelation({
|
||||
tenantId: "tenant-a",
|
||||
kontaktId: "contact-a",
|
||||
ctx: { userId: "actor-a", permissions: ["crm.read_own"] },
|
||||
relationId: "relation-a-b",
|
||||
})
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
|
||||
expect(mocks.tx.kontaktRelation.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: "relation-a-b",
|
||||
tenantId: "tenant-a",
|
||||
OR: [{ vonKontaktId: "contact-a" }, { zuKontaktId: "contact-a" }],
|
||||
},
|
||||
select: { id: true, vonKontaktId: true, zuKontaktId: true },
|
||||
});
|
||||
expect(mocks.tx.kontakt.findFirst).toHaveBeenLastCalledWith({
|
||||
where: { id: "contact-b", tenantId: "tenant-a", zustaendigerUserId: "actor-a" },
|
||||
});
|
||||
expect(mocks.tx.kontaktRelation.deleteMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+257
-76
@@ -14,8 +14,11 @@
|
||||
// cutover). The only access NOT wrapped is the global User lookup
|
||||
// (resolveUserLabels): User is not tenant-scoped, so it stays on the db singleton.
|
||||
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
|
||||
import { CatalogError, foundationErrors, massActionErrors } from "@hivegrid/foundation";
|
||||
import { buildWorkflowTriggerOutboxEvent } from "@hivegrid/queue";
|
||||
import { crmContactsIndex } from "@hivegrid/search";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
import { publishKontaktSearchUpsert, publishSearchProjectionDelete } from "~/services/search/searchIndexProjection.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
@@ -64,6 +67,16 @@ export function ownerScopeWhere(ctx: CrmVisibilityContext): { zustaendigerUserId
|
||||
return canReadAllKontakte(ctx) ? {} : { zustaendigerUserId: ctx.userId };
|
||||
}
|
||||
|
||||
async function requireActiveTenantUserWithTx(tx: TenantRlsClient, tenantId: string, userId: string): Promise<void> {
|
||||
const membership = await tx.tenantUser.findFirst({
|
||||
where: { tenantId, userId, status: TenantUserStatus.ACTIVE, user: { active: true } },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!membership) {
|
||||
throw new CatalogError(foundationErrors.notFound, { userId });
|
||||
}
|
||||
}
|
||||
|
||||
// --- Row types (returned to routes; relation fields excluded) --------------
|
||||
|
||||
export type KontaktRow = {
|
||||
@@ -142,7 +155,9 @@ export type AdresseInput = {
|
||||
* primary; an empty list has no primary. Returns the denormalised primary value
|
||||
* plus the per-item primary flags to persist. Pure (no DB) — used at create time.
|
||||
*/
|
||||
function pickPrimary<T extends { value: string; primaer?: boolean }>(items: readonly T[]): {
|
||||
function pickPrimary<T extends { value: string; primaer?: boolean }>(
|
||||
items: readonly T[]
|
||||
): {
|
||||
primaryValue: string | null;
|
||||
flags: boolean[];
|
||||
} {
|
||||
@@ -243,6 +258,39 @@ function hasAddressData(adresse?: AdresseInput | null): boolean {
|
||||
return Boolean(adresse.strasse?.trim() || adresse.hausnummer?.trim() || adresse.plz?.trim() || adresse.ort?.trim() || adresse.land?.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* R-P12c: kontakt domain events feed the generic automation trigger bus via
|
||||
* the durable workflow-trigger outbox (same delivery as lead/project events).
|
||||
* Published inside the mutation transaction so event and write commit together.
|
||||
*/
|
||||
async function publishKontaktWorkflowEvent(
|
||||
tx: TenantRlsClient,
|
||||
input: {
|
||||
tenantId: string;
|
||||
userId: string | null;
|
||||
event: "kontakt.created" | "kontakt.updated";
|
||||
kontakt: { id: string; kontaktTyp: string; kontaktStatus: string; updatedAt?: Date };
|
||||
changedFields?: readonly string[];
|
||||
}
|
||||
): Promise<void> {
|
||||
const suffix = input.event === "kontakt.updated" ? `:${input.kontakt.updatedAt?.getTime() ?? Date.now()}` : "";
|
||||
await publishOutboxEvent(
|
||||
tx as unknown as OutboxPublisherTransaction,
|
||||
buildWorkflowTriggerOutboxEvent({
|
||||
tenantId: input.tenantId,
|
||||
event: input.event,
|
||||
data: {
|
||||
kontaktId: input.kontakt.id,
|
||||
kontaktTyp: input.kontakt.kontaktTyp,
|
||||
kontaktStatus: input.kontakt.kontaktStatus,
|
||||
...(input.changedFields ? { changedFields: [...input.changedFields] } : {}),
|
||||
},
|
||||
userId: input.userId,
|
||||
sourceId: `kontakt:${input.kontakt.id}:${input.event}${suffix}`,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export async function createKontakt(input: CreateKontaktInput): Promise<KontaktRow> {
|
||||
validateKontaktName(input);
|
||||
const emailItems = (input.emails ?? []).map((entry) => ({ value: entry.email.trim(), primaer: entry.primaer })).filter((entry) => entry.value);
|
||||
@@ -251,6 +299,8 @@ export async function createKontakt(input: CreateKontaktInput): Promise<KontaktR
|
||||
const primaryTelefon = pickPrimary(telefonItems);
|
||||
|
||||
const kontakt = await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const responsibleUserId = input.zustaendigerUserId ?? input.userId;
|
||||
await requireActiveTenantUserWithTx(tx, input.tenantId, responsibleUserId);
|
||||
let adresseId: string | null = null;
|
||||
if (hasAddressData(input.adresse)) {
|
||||
const adresse = await tx.adresse.create({
|
||||
@@ -280,7 +330,7 @@ export async function createKontakt(input: CreateKontaktInput): Promise<KontaktR
|
||||
primaerEmail: primaryEmail.primaryValue,
|
||||
primaerTelefon: primaryTelefon.primaryValue,
|
||||
adresseId,
|
||||
zustaendigerUserId: input.zustaendigerUserId ?? input.userId,
|
||||
zustaendigerUserId: responsibleUserId,
|
||||
isDemoData: input.isDemoData ?? false,
|
||||
},
|
||||
});
|
||||
@@ -289,9 +339,17 @@ export async function createKontakt(input: CreateKontaktInput): Promise<KontaktR
|
||||
await tx.kontaktEmail.create({ data: { tenantId: input.tenantId, kontaktId: created.id, email: emailItems[i].value, primaer: primaryEmail.flags[i] } });
|
||||
}
|
||||
for (let i = 0; i < telefonItems.length; i += 1) {
|
||||
await tx.kontaktTelefon.create({ data: { tenantId: input.tenantId, kontaktId: created.id, telefon: telefonItems[i].value, primaer: primaryTelefon.flags[i] } });
|
||||
await tx.kontaktTelefon.create({
|
||||
data: { tenantId: input.tenantId, kontaktId: created.id, telefon: telefonItems[i].value, primaer: primaryTelefon.flags[i] },
|
||||
});
|
||||
}
|
||||
await publishKontaktSearchUpsert(tx, created);
|
||||
await publishKontaktWorkflowEvent(tx, {
|
||||
tenantId: input.tenantId,
|
||||
userId: input.userId,
|
||||
event: "kontakt.created",
|
||||
kontakt: created,
|
||||
});
|
||||
return created;
|
||||
});
|
||||
return kontakt as KontaktRow;
|
||||
@@ -324,6 +382,16 @@ export async function updateKontakt(input: UpdateKontaktInput): Promise<void> {
|
||||
},
|
||||
});
|
||||
await publishKontaktSearchUpsert(tx, updated);
|
||||
const changedFields = (["kontaktStatus", "vorname", "nachname", "orgName", "orgMerkmal"] as const).filter(
|
||||
(field) => input[field] !== undefined
|
||||
);
|
||||
await publishKontaktWorkflowEvent(tx, {
|
||||
tenantId: input.tenantId,
|
||||
userId: null,
|
||||
event: "kontakt.updated",
|
||||
kontakt: updated,
|
||||
changedFields,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -374,6 +442,7 @@ export async function hardDeleteKontakt(input: { tenantId: string; kontaktId: st
|
||||
|
||||
export async function reassignKontakt(input: { tenantId: string; kontaktId: string; zustaendigerUserId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
await requireActiveTenantUserWithTx(tx, input.tenantId, input.zustaendigerUserId);
|
||||
const existing = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId }, select: { id: true } });
|
||||
if (!existing) {
|
||||
throw new CatalogError(foundationErrors.notFound, { kontaktId: input.kontaktId });
|
||||
@@ -385,108 +454,124 @@ export async function reassignKontakt(input: { tenantId: string; kontaktId: stri
|
||||
|
||||
// --- Email channels --------------------------------------------------------
|
||||
|
||||
export async function addKontaktEmail(input: { tenantId: string; kontaktId: string; email: string; primaer?: boolean }): Promise<KontaktEmailRow> {
|
||||
type KontaktScopedMutationInput = {
|
||||
tenantId: string;
|
||||
kontaktId: string;
|
||||
ctx: CrmVisibilityContext;
|
||||
};
|
||||
|
||||
export async function addKontaktEmail(input: KontaktScopedMutationInput & { email: string; primaer?: boolean }): Promise<KontaktEmailRow> {
|
||||
const email = input.email.trim();
|
||||
if (!email) {
|
||||
throw new CrmServiceError("crm.error.emailRequired");
|
||||
}
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const kontakt = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId }, select: { id: true } });
|
||||
if (!kontakt) {
|
||||
throw new CatalogError(foundationErrors.notFound, { kontaktId: input.kontaktId });
|
||||
}
|
||||
const created = await tx.kontaktEmail.create({ data: { tenantId: input.tenantId, kontaktId: input.kontaktId, email, primaer: false } });
|
||||
await syncPrimaryEmailWithTx(tx, input.tenantId, input.kontaktId, input.primaer ? created.id : undefined);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId } });
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const created = await tx.kontaktEmail.create({ data: { tenantId: input.tenantId, kontaktId: kontakt.id, email, primaer: false } });
|
||||
await syncPrimaryEmailWithTx(tx, input.tenantId, kontakt.id, input.primaer ? created.id : undefined);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: kontakt.id, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
return created as KontaktEmailRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function setPrimaryEmail(input: { tenantId: string; emailId: string }): Promise<void> {
|
||||
export async function setPrimaryEmail(input: KontaktScopedMutationInput & { emailId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const email = await tx.kontaktEmail.findFirst({ where: { id: input.emailId, tenantId: input.tenantId }, select: { id: true, kontaktId: true } });
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const email = await tx.kontaktEmail.findFirst({
|
||||
where: { id: input.emailId, tenantId: input.tenantId, kontaktId: kontakt.id },
|
||||
select: { id: true, kontaktId: true },
|
||||
});
|
||||
if (!email) {
|
||||
throw new CatalogError(foundationErrors.notFound, { emailId: input.emailId });
|
||||
}
|
||||
await syncPrimaryEmailWithTx(tx, input.tenantId, email.kontaktId, email.id);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: email.kontaktId, tenantId: input.tenantId } });
|
||||
await syncPrimaryEmailWithTx(tx, input.tenantId, kontakt.id, email.id);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: kontakt.id, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeKontaktEmail(input: { tenantId: string; emailId: string }): Promise<void> {
|
||||
export async function removeKontaktEmail(input: KontaktScopedMutationInput & { emailId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const email = await tx.kontaktEmail.findFirst({ where: { id: input.emailId, tenantId: input.tenantId }, select: { id: true, kontaktId: true } });
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const email = await tx.kontaktEmail.findFirst({
|
||||
where: { id: input.emailId, tenantId: input.tenantId, kontaktId: kontakt.id },
|
||||
select: { id: true, kontaktId: true },
|
||||
});
|
||||
if (!email) {
|
||||
throw new CatalogError(foundationErrors.notFound, { emailId: input.emailId });
|
||||
}
|
||||
await tx.kontaktEmail.deleteMany({ where: { id: input.emailId, tenantId: input.tenantId } });
|
||||
await syncPrimaryEmailWithTx(tx, input.tenantId, email.kontaktId);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: email.kontaktId, tenantId: input.tenantId } });
|
||||
await tx.kontaktEmail.deleteMany({ where: { id: email.id, tenantId: input.tenantId, kontaktId: kontakt.id } });
|
||||
await syncPrimaryEmailWithTx(tx, input.tenantId, kontakt.id);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: kontakt.id, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
});
|
||||
}
|
||||
|
||||
// --- Telephone channels ----------------------------------------------------
|
||||
|
||||
export async function addKontaktTelefon(input: { tenantId: string; kontaktId: string; telefon: string; primaer?: boolean }): Promise<KontaktTelefonRow> {
|
||||
export async function addKontaktTelefon(input: KontaktScopedMutationInput & { telefon: string; primaer?: boolean }): Promise<KontaktTelefonRow> {
|
||||
const telefon = input.telefon.trim();
|
||||
if (!telefon) {
|
||||
throw new CrmServiceError("crm.error.telefonRequired");
|
||||
}
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const kontakt = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId }, select: { id: true } });
|
||||
if (!kontakt) {
|
||||
throw new CatalogError(foundationErrors.notFound, { kontaktId: input.kontaktId });
|
||||
}
|
||||
const created = await tx.kontaktTelefon.create({ data: { tenantId: input.tenantId, kontaktId: input.kontaktId, telefon, primaer: false } });
|
||||
await syncPrimaryTelefonWithTx(tx, input.tenantId, input.kontaktId, input.primaer ? created.id : undefined);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId } });
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const created = await tx.kontaktTelefon.create({ data: { tenantId: input.tenantId, kontaktId: kontakt.id, telefon, primaer: false } });
|
||||
await syncPrimaryTelefonWithTx(tx, input.tenantId, kontakt.id, input.primaer ? created.id : undefined);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: kontakt.id, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
return created as KontaktTelefonRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function setPrimaryTelefon(input: { tenantId: string; telefonId: string }): Promise<void> {
|
||||
export async function setPrimaryTelefon(input: KontaktScopedMutationInput & { telefonId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const telefon = await tx.kontaktTelefon.findFirst({ where: { id: input.telefonId, tenantId: input.tenantId }, select: { id: true, kontaktId: true } });
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const telefon = await tx.kontaktTelefon.findFirst({
|
||||
where: { id: input.telefonId, tenantId: input.tenantId, kontaktId: kontakt.id },
|
||||
select: { id: true, kontaktId: true },
|
||||
});
|
||||
if (!telefon) {
|
||||
throw new CatalogError(foundationErrors.notFound, { telefonId: input.telefonId });
|
||||
}
|
||||
await syncPrimaryTelefonWithTx(tx, input.tenantId, telefon.kontaktId, telefon.id);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: telefon.kontaktId, tenantId: input.tenantId } });
|
||||
await syncPrimaryTelefonWithTx(tx, input.tenantId, kontakt.id, telefon.id);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: kontakt.id, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeKontaktTelefon(input: { tenantId: string; telefonId: string }): Promise<void> {
|
||||
export async function removeKontaktTelefon(input: KontaktScopedMutationInput & { telefonId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const telefon = await tx.kontaktTelefon.findFirst({ where: { id: input.telefonId, tenantId: input.tenantId }, select: { id: true, kontaktId: true } });
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const telefon = await tx.kontaktTelefon.findFirst({
|
||||
where: { id: input.telefonId, tenantId: input.tenantId, kontaktId: kontakt.id },
|
||||
select: { id: true, kontaktId: true },
|
||||
});
|
||||
if (!telefon) {
|
||||
throw new CatalogError(foundationErrors.notFound, { telefonId: input.telefonId });
|
||||
}
|
||||
await tx.kontaktTelefon.deleteMany({ where: { id: input.telefonId, tenantId: input.tenantId } });
|
||||
await syncPrimaryTelefonWithTx(tx, input.tenantId, telefon.kontaktId);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: telefon.kontaktId, tenantId: input.tenantId } });
|
||||
await tx.kontaktTelefon.deleteMany({ where: { id: telefon.id, tenantId: input.tenantId, kontaktId: kontakt.id } });
|
||||
await syncPrimaryTelefonWithTx(tx, input.tenantId, kontakt.id);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: kontakt.id, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
});
|
||||
}
|
||||
|
||||
// --- Relations -------------------------------------------------------------
|
||||
|
||||
export async function addKontaktRelation(input: { tenantId: string; vonKontaktId: string; zuKontaktId: string; rolle: KontaktArt; kontext?: string | null }): Promise<KontaktRelationRow> {
|
||||
if (input.vonKontaktId === input.zuKontaktId) {
|
||||
export async function addKontaktRelation(
|
||||
input: KontaktScopedMutationInput & { zuKontaktId: string; rolle: KontaktArt; kontext?: string | null }
|
||||
): Promise<KontaktRelationRow> {
|
||||
if (input.kontaktId === input.zuKontaktId) {
|
||||
throw new CrmServiceError("crm.error.selfRelation");
|
||||
}
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const endpoints = await tx.kontakt.findMany({ where: { id: { in: [input.vonKontaktId, input.zuKontaktId] }, tenantId: input.tenantId }, select: { id: true } });
|
||||
if (endpoints.length !== 2) {
|
||||
throw new CatalogError(foundationErrors.notFound, { vonKontaktId: input.vonKontaktId, zuKontaktId: input.zuKontaktId });
|
||||
}
|
||||
const source = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const target = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.zuKontaktId, input.ctx);
|
||||
try {
|
||||
const created = await tx.kontaktRelation.create({
|
||||
data: { tenantId: input.tenantId, vonKontaktId: input.vonKontaktId, zuKontaktId: input.zuKontaktId, rolle: input.rolle, kontext: input.kontext ?? null },
|
||||
data: { tenantId: input.tenantId, vonKontaktId: source.id, zuKontaktId: target.id, rolle: input.rolle, kontext: input.kontext ?? null },
|
||||
});
|
||||
return created as KontaktRelationRow;
|
||||
} catch (error) {
|
||||
@@ -498,30 +583,37 @@ export async function addKontaktRelation(input: { tenantId: string; vonKontaktId
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeKontaktRelation(input: { tenantId: string; relationId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, (tx) => tx.kontaktRelation.deleteMany({ where: { id: input.relationId, tenantId: input.tenantId } }));
|
||||
}
|
||||
|
||||
/** All relations touching a contact, in both directions (von/zu). */
|
||||
export async function listRelationsForKontakt(tenantId: string, kontaktId: string): Promise<KontaktRelationRow[]> {
|
||||
const rows = await withTenantRLS(tenantId, (tx) =>
|
||||
tx.kontaktRelation.findMany({
|
||||
where: { tenantId, OR: [{ vonKontaktId: kontaktId }, { zuKontaktId: kontaktId }] },
|
||||
orderBy: { createdAt: "asc" },
|
||||
}),
|
||||
);
|
||||
return rows as KontaktRelationRow[];
|
||||
export async function removeKontaktRelation(input: KontaktScopedMutationInput & { relationId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const relation = await tx.kontaktRelation.findFirst({
|
||||
where: {
|
||||
id: input.relationId,
|
||||
tenantId: input.tenantId,
|
||||
OR: [{ vonKontaktId: kontakt.id }, { zuKontaktId: kontakt.id }],
|
||||
},
|
||||
select: { id: true, vonKontaktId: true, zuKontaktId: true },
|
||||
});
|
||||
if (!relation) {
|
||||
throw new CatalogError(foundationErrors.notFound, { relationId: input.relationId });
|
||||
}
|
||||
const otherKontaktId = relation.vonKontaktId === kontakt.id ? relation.zuKontaktId : relation.vonKontaktId;
|
||||
await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, otherKontaktId, input.ctx);
|
||||
await tx.kontaktRelation.deleteMany({
|
||||
where: {
|
||||
id: relation.id,
|
||||
tenantId: input.tenantId,
|
||||
OR: [{ vonKontaktId: kontakt.id }, { zuKontaktId: kontakt.id }],
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// --- Visibility / read -----------------------------------------------------
|
||||
|
||||
function isKontaktVisible(kontakt: Pick<KontaktRow, "createdByUserId" | "zustaendigerUserId">, ctx: CrmVisibilityContext): boolean {
|
||||
return canReadAllKontakte(ctx) || kontakt.zustaendigerUserId === ctx.userId || kontakt.createdByUserId === ctx.userId;
|
||||
}
|
||||
|
||||
async function getVisibleKontaktOrThrowWithTx(tx: TenantRlsClient, tenantId: string, kontaktId: string, ctx: CrmVisibilityContext): Promise<KontaktRow> {
|
||||
const kontakt = await tx.kontakt.findFirst({ where: { id: kontaktId, tenantId } });
|
||||
if (!kontakt || !isKontaktVisible(kontakt as KontaktRow, ctx)) {
|
||||
const kontakt = await tx.kontakt.findFirst({ where: { id: kontaktId, tenantId, ...ownerScopeWhere(ctx) } });
|
||||
if (!kontakt) {
|
||||
throw new CatalogError(foundationErrors.notFound, { kontaktId });
|
||||
}
|
||||
return kontakt as KontaktRow;
|
||||
@@ -532,6 +624,35 @@ export async function getVisibleKontaktOrThrow(tenantId: string, kontaktId: stri
|
||||
return withTenantRLS(tenantId, (tx) => getVisibleKontaktOrThrowWithTx(tx, tenantId, kontaktId, ctx));
|
||||
}
|
||||
|
||||
async function listVisibleRelationsForKontaktWithTx(
|
||||
tx: TenantRlsClient,
|
||||
tenantId: string,
|
||||
kontaktId: string,
|
||||
ctx: CrmVisibilityContext
|
||||
): Promise<KontaktRelationRow[]> {
|
||||
const rows = await tx.kontaktRelation.findMany({
|
||||
where: { tenantId, OR: [{ vonKontaktId: kontaktId }, { zuKontaktId: kontaktId }] },
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
if (rows.length === 0) return [];
|
||||
|
||||
const otherKontaktIds = [...new Set(rows.map((row) => (row.vonKontaktId === kontaktId ? row.zuKontaktId : row.vonKontaktId)))];
|
||||
const visibleContacts = await tx.kontakt.findMany({
|
||||
where: { id: { in: otherKontaktIds }, tenantId, ...ownerScopeWhere(ctx) },
|
||||
select: { id: true },
|
||||
});
|
||||
const visibleIds = new Set(visibleContacts.map(({ id }) => id));
|
||||
return rows.filter((row) => visibleIds.has(row.vonKontaktId === kontaktId ? row.zuKontaktId : row.vonKontaktId)) as KontaktRelationRow[];
|
||||
}
|
||||
|
||||
/** All relations whose source and target contacts are visible to the caller. */
|
||||
export async function listRelationsForKontakt(tenantId: string, kontaktId: string, ctx: CrmVisibilityContext): Promise<KontaktRelationRow[]> {
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
await getVisibleKontaktOrThrowWithTx(tx, tenantId, kontaktId, ctx);
|
||||
return listVisibleRelationsForKontaktWithTx(tx, tenantId, kontaktId, ctx);
|
||||
});
|
||||
}
|
||||
|
||||
export type KontaktDetail = {
|
||||
kontakt: KontaktRow;
|
||||
emails: KontaktEmailRow[];
|
||||
@@ -547,7 +668,7 @@ export async function getKontaktDetail(tenantId: string, kontaktId: string, ctx:
|
||||
const [emails, telefone, relationen, adresse] = await Promise.all([
|
||||
tx.kontaktEmail.findMany({ where: { tenantId, kontaktId }, orderBy: { createdAt: "asc" } }),
|
||||
tx.kontaktTelefon.findMany({ where: { tenantId, kontaktId }, orderBy: { createdAt: "asc" } }),
|
||||
tx.kontaktRelation.findMany({ where: { tenantId, OR: [{ vonKontaktId: kontaktId }, { zuKontaktId: kontaktId }] }, orderBy: { createdAt: "asc" } }),
|
||||
listVisibleRelationsForKontaktWithTx(tx, tenantId, kontaktId, ctx),
|
||||
kontakt.adresseId ? tx.adresse.findFirst({ where: { id: kontakt.adresseId, tenantId } }) : Promise.resolve(null),
|
||||
]);
|
||||
return {
|
||||
@@ -604,7 +725,7 @@ async function resolveKontaktBrowserWhereWithTx(
|
||||
tx: TenantRlsClient,
|
||||
tenantId: string,
|
||||
ctx: CrmVisibilityContext,
|
||||
filter: ListKontakteFilter,
|
||||
filter: ListKontakteFilter
|
||||
): Promise<{ where: Record<string, unknown>; empty: boolean }> {
|
||||
const search = filter.search?.trim();
|
||||
let tagScopedIds: string[] | undefined;
|
||||
@@ -681,7 +802,12 @@ export async function listKontakteForBrowser(input: {
|
||||
|
||||
/** All contacts matching the same browser filter, unpaginated, for CSV export
|
||||
* (DoD 2). The CSV string itself is built in the route / a pure util. */
|
||||
export async function listKontakteForCsv(input: { tenantId: string; ctx: CrmVisibilityContext; filter?: ListKontakteFilter; sort?: ListKontakteSort }): Promise<KontaktRow[]> {
|
||||
export async function listKontakteForCsv(input: {
|
||||
tenantId: string;
|
||||
ctx: CrmVisibilityContext;
|
||||
filter?: ListKontakteFilter;
|
||||
sort?: ListKontakteSort;
|
||||
}): Promise<KontaktRow[]> {
|
||||
const filter = input.filter ?? {};
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const { where, empty } = await resolveKontaktBrowserWhereWithTx(tx, input.tenantId, input.ctx, filter);
|
||||
@@ -719,7 +845,10 @@ export async function findDuplicateKontakte(input: DuplicateCheckInput): Promise
|
||||
|
||||
const hardConds: Record<string, unknown>[] = [];
|
||||
if (email) {
|
||||
hardConds.push({ primaerEmail: { equals: email, mode: "insensitive" as const } }, { emails: { some: { email: { equals: email, mode: "insensitive" as const } } } });
|
||||
hardConds.push(
|
||||
{ primaerEmail: { equals: email, mode: "insensitive" as const } },
|
||||
{ emails: { some: { email: { equals: email, mode: "insensitive" as const } } } }
|
||||
);
|
||||
}
|
||||
if (telefon) {
|
||||
hardConds.push({ primaerTelefon: telefon }, { telefone: { some: { telefon } } });
|
||||
@@ -750,26 +879,75 @@ export async function findDuplicateKontakte(input: DuplicateCheckInput): Promise
|
||||
|
||||
// --- Bulk actions (DoD 2) --------------------------------------------------
|
||||
|
||||
export const CRM_BULK_MAX_CONTACTS = 100;
|
||||
|
||||
export function normalizeBulkKontaktIds(kontaktIds: readonly string[]): string[] {
|
||||
if (kontaktIds.length > CRM_BULK_MAX_CONTACTS) {
|
||||
throw new CatalogError(massActionErrors.exceedsLimit, {
|
||||
affected: kontaktIds.length,
|
||||
hardLimit: CRM_BULK_MAX_CONTACTS,
|
||||
});
|
||||
}
|
||||
return [...new Set(kontaktIds.map((id) => id.trim()).filter(Boolean))];
|
||||
}
|
||||
|
||||
export async function listVisibleKontakteByIds(input: {
|
||||
tenantId: string;
|
||||
ctx: CrmVisibilityContext;
|
||||
kontaktIds: readonly string[];
|
||||
/** Archived contacts are excluded by default; set for the un-archive path. */
|
||||
includeArchived?: boolean;
|
||||
}): Promise<KontaktRow[]> {
|
||||
const kontaktIds = normalizeBulkKontaktIds(input.kontaktIds);
|
||||
if (kontaktIds.length === 0) return [];
|
||||
const rows = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.kontakt.findMany({
|
||||
where: {
|
||||
id: { in: kontaktIds },
|
||||
tenantId: input.tenantId,
|
||||
...(input.includeArchived ? {} : { archivedAt: null }),
|
||||
...ownerScopeWhere(input.ctx),
|
||||
},
|
||||
})
|
||||
);
|
||||
const rowById = new Map(rows.map((row) => [row.id, row as KontaktRow]));
|
||||
return kontaktIds.flatMap((id) => {
|
||||
const row = rowById.get(id);
|
||||
return row ? [row] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/** Archive many contacts; only contacts inside the caller's owner-scope are
|
||||
* affected (read_own may not touch others'). Returns the number affected. */
|
||||
export async function bulkArchiveKontakte(input: { tenantId: string; ctx: CrmVisibilityContext; kontaktIds: string[] }): Promise<{ affected: number }> {
|
||||
if (input.kontaktIds.length === 0) {
|
||||
const kontaktIds = normalizeBulkKontaktIds(input.kontaktIds);
|
||||
if (kontaktIds.length === 0) {
|
||||
return { affected: 0 };
|
||||
}
|
||||
const result = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.kontakt.updateMany({ where: { id: { in: input.kontaktIds }, tenantId: input.tenantId, ...ownerScopeWhere(input.ctx) }, data: { archivedAt: new Date() } }),
|
||||
tx.kontakt.updateMany({ where: { id: { in: kontaktIds }, tenantId: input.tenantId, ...ownerScopeWhere(input.ctx) }, data: { archivedAt: new Date() } })
|
||||
);
|
||||
return { affected: result.count };
|
||||
}
|
||||
|
||||
/** Reassign many contacts; owner-scoped like {@link bulkArchiveKontakte}. */
|
||||
export async function bulkReassignKontakte(input: { tenantId: string; ctx: CrmVisibilityContext; kontaktIds: string[]; zustaendigerUserId: string }): Promise<{ affected: number }> {
|
||||
if (input.kontaktIds.length === 0) {
|
||||
export async function bulkReassignKontakte(input: {
|
||||
tenantId: string;
|
||||
ctx: CrmVisibilityContext;
|
||||
kontaktIds: string[];
|
||||
zustaendigerUserId: string;
|
||||
}): Promise<{ affected: number }> {
|
||||
const kontaktIds = normalizeBulkKontaktIds(input.kontaktIds);
|
||||
if (kontaktIds.length === 0) {
|
||||
return { affected: 0 };
|
||||
}
|
||||
const result = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.kontakt.updateMany({ where: { id: { in: input.kontaktIds }, tenantId: input.tenantId, ...ownerScopeWhere(input.ctx) }, data: { zustaendigerUserId: input.zustaendigerUserId } }),
|
||||
);
|
||||
const result = await withTenantRLS(input.tenantId, async (tx) => {
|
||||
await requireActiveTenantUserWithTx(tx, input.tenantId, input.zustaendigerUserId);
|
||||
return tx.kontakt.updateMany({
|
||||
where: { id: { in: kontaktIds }, tenantId: input.tenantId, ...ownerScopeWhere(input.ctx) },
|
||||
data: { zustaendigerUserId: input.zustaendigerUserId },
|
||||
});
|
||||
});
|
||||
return { affected: result.count };
|
||||
}
|
||||
|
||||
@@ -795,7 +973,10 @@ export async function resolveUserLabels(userIds: readonly string[]): Promise<Map
|
||||
/** Tenant members as zustaendigerUser picker options (id + display label). */
|
||||
export async function listAssignableUsers(tenantId: string): Promise<LabeledOption[]> {
|
||||
const members = await withTenantRLS(tenantId, (tx) =>
|
||||
tx.tenantUser.findMany({ where: { tenantId }, select: { user: { select: { id: true, firstName: true, lastName: true, email: true } } } }),
|
||||
tx.tenantUser.findMany({
|
||||
where: { tenantId, status: TenantUserStatus.ACTIVE, user: { active: true } },
|
||||
select: { user: { select: { id: true, firstName: true, lastName: true, email: true } } },
|
||||
})
|
||||
);
|
||||
return members.filter((member) => member.user).map((member) => ({ id: member.user.id, label: userLabel(member.user) }));
|
||||
}
|
||||
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
// WF-P8 S05 field-type picker — the guard that keeps a retype from silently
|
||||
// reinterpreting stored values. Only the decision is under test here, so the
|
||||
// transaction client is a stub; the point is which calls the guard makes and
|
||||
// when it refuses.
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
withTenantRLS: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
count: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({ withTenantRLS: mocks.withTenantRLS }));
|
||||
|
||||
import { updateCustomFieldDefinition } from "./customFieldService.server";
|
||||
import { CrmServiceError } from "./crmService.server";
|
||||
|
||||
const tx = {
|
||||
customFieldDefinition: { findFirst: mocks.findFirst, updateMany: mocks.updateMany },
|
||||
customFieldValue: { count: mocks.count },
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.withTenantRLS.mockImplementation(async (_tenantId: string, callback: (client: unknown) => unknown) => callback(tx));
|
||||
mocks.findFirst.mockResolvedValue({ id: "def_1", datentyp: "datum" });
|
||||
mocks.count.mockResolvedValue(0);
|
||||
});
|
||||
|
||||
describe("updateCustomFieldDefinition retype guard", () => {
|
||||
it("refuses a retype once values are stored, instead of reinterpreting them", async () => {
|
||||
mocks.count.mockResolvedValue(3);
|
||||
|
||||
await expect(updateCustomFieldDefinition({ tenantId: "t1", definitionId: "def_1", datentyp: "zahl" })).rejects.toBeInstanceOf(CrmServiceError);
|
||||
expect(mocks.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("allows the retype while the field holds no values yet", async () => {
|
||||
await expect(updateCustomFieldDefinition({ tenantId: "t1", definitionId: "def_1", datentyp: "zahl" })).resolves.toBeUndefined();
|
||||
expect(mocks.updateMany).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ datentyp: "zahl" }) }));
|
||||
});
|
||||
|
||||
it("lets select and multiselect swap even with values, because both hold option values", async () => {
|
||||
mocks.findFirst.mockResolvedValue({ id: "def_1", datentyp: "select" });
|
||||
mocks.count.mockResolvedValue(7);
|
||||
|
||||
await expect(updateCustomFieldDefinition({ tenantId: "t1", definitionId: "def_1", datentyp: "multiselect" })).resolves.toBeUndefined();
|
||||
// The compatible pair must not even ask for the value count.
|
||||
expect(mocks.count).not.toHaveBeenCalled();
|
||||
expect(mocks.updateMany).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not count values when the submitted type equals the stored one", async () => {
|
||||
mocks.count.mockResolvedValue(9);
|
||||
|
||||
await updateCustomFieldDefinition({ tenantId: "t1", definitionId: "def_1", datentyp: "datum" });
|
||||
|
||||
expect(mocks.count).not.toHaveBeenCalled();
|
||||
expect(mocks.updateMany).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("writes options without touching the type guard", async () => {
|
||||
await updateCustomFieldDefinition({ tenantId: "t1", definitionId: "def_1", optionen: { options: [{ value: "a", label: "A", color: null }] } });
|
||||
|
||||
expect(mocks.count).not.toHaveBeenCalled();
|
||||
expect(mocks.updateMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ data: expect.objectContaining({ optionen: { options: [{ value: "a", label: "A", color: null }] } }) })
|
||||
);
|
||||
});
|
||||
});
|
||||
+60
-23
@@ -8,7 +8,7 @@
|
||||
|
||||
import { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import { CatalogError, foundationErrors, type JsonValue } from "@hivegrid/foundation";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
import { CrmServiceError } from "./crmService.server";
|
||||
|
||||
export type CustomFieldEntityType = "projekt" | "kontakt" | "lead" | "rechnung";
|
||||
@@ -24,7 +24,13 @@ export type CustomFieldDatentyp =
|
||||
| "boolean"
|
||||
| "email"
|
||||
| "telefon"
|
||||
| "datei";
|
||||
| "datei"
|
||||
// WF-P8 S05 additions; see the enum comment in crm.prisma.
|
||||
| "prozent"
|
||||
| "datum_zeit"
|
||||
| "person_team"
|
||||
| "adresse"
|
||||
| "link";
|
||||
|
||||
export type CustomFieldDefinitionRow = {
|
||||
id: string;
|
||||
@@ -100,18 +106,34 @@ export async function updateCustomFieldDefinition(input: {
|
||||
tenantId: string;
|
||||
definitionId: string;
|
||||
label?: string;
|
||||
datentyp?: CustomFieldDatentyp;
|
||||
optionen?: JsonValue | null;
|
||||
archiviert?: boolean;
|
||||
}): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const existing = await tx.customFieldDefinition.findFirst({ where: { id: input.definitionId, tenantId: input.tenantId }, select: { id: true } });
|
||||
const existing = await tx.customFieldDefinition.findFirst({
|
||||
where: { id: input.definitionId, tenantId: input.tenantId },
|
||||
select: { id: true, datentyp: true },
|
||||
});
|
||||
if (!existing) {
|
||||
throw new CatalogError(foundationErrors.notFound, { definitionId: input.definitionId });
|
||||
}
|
||||
// Retyping a field reinterprets every value already stored under it: a date
|
||||
// read as a number, a select value with no matching option. select <-> multiselect
|
||||
// is the exception, both hold option values, so the data keeps its meaning.
|
||||
if (input.datentyp !== undefined && input.datentyp !== existing.datentyp) {
|
||||
const optionTypes = new Set(["select", "multiselect"]);
|
||||
const staysCompatible = optionTypes.has(input.datentyp) && optionTypes.has(existing.datentyp);
|
||||
if (!staysCompatible) {
|
||||
const valueCount = await tx.customFieldValue.count({ where: { tenantId: input.tenantId, definitionId: input.definitionId } });
|
||||
if (valueCount > 0) throw new CrmServiceError("crm.error.customFieldTypeLocked");
|
||||
}
|
||||
}
|
||||
await tx.customFieldDefinition.updateMany({
|
||||
where: { id: input.definitionId, tenantId: input.tenantId },
|
||||
data: {
|
||||
...(input.label !== undefined ? { label: input.label.trim() } : {}),
|
||||
...(input.datentyp !== undefined ? { datentyp: input.datentyp } : {}),
|
||||
...(input.optionen !== undefined ? { optionen: toJsonInput(input.optionen) } : {}),
|
||||
...(input.archiviert !== undefined ? { archiviert: input.archiviert } : {}),
|
||||
},
|
||||
@@ -192,37 +214,52 @@ export type ShkCustomFieldTemplateEntry = {
|
||||
export const SHK_CUSTOM_FIELD_TEMPLATE: ReadonlyArray<ShkCustomFieldTemplateEntry> = [];
|
||||
|
||||
/**
|
||||
* Idempotently create the SHK template fields for a tenant as demo data
|
||||
* (`isDemoData = true`). Existing fields with the same (tenant, entityType, key)
|
||||
* are skipped. With the empty template this is a no-op that returns 0.
|
||||
* Idempotently create the SHK template fields for a tenant. Tenant-created
|
||||
* defaults are normal rows; only an explicit demo seed may opt into demo rows.
|
||||
* Existing fields with the same (tenant, entityType, key) are skipped. With
|
||||
* the empty template this is a no-op that returns 0.
|
||||
*/
|
||||
export async function seedShkCustomFieldTemplate(input: { tenantId: string }): Promise<{ created: number }> {
|
||||
export type SeedShkCustomFieldTemplateInput = { tenantId: string; isDemoData?: boolean };
|
||||
|
||||
export async function seedShkCustomFieldTemplateWithTx(
|
||||
tx: TenantRlsClient,
|
||||
input: SeedShkCustomFieldTemplateInput,
|
||||
): Promise<{ created: number }> {
|
||||
let created = 0;
|
||||
const isDemoData = input.isDemoData ?? false;
|
||||
for (const entry of SHK_CUSTOM_FIELD_TEMPLATE) {
|
||||
const exists = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.customFieldDefinition.findFirst({ where: { tenantId: input.tenantId, entityType: entry.entityType, key: entry.key }, select: { id: true } }),
|
||||
);
|
||||
const exists = await tx.customFieldDefinition.findFirst({
|
||||
where: { tenantId: input.tenantId, entityType: entry.entityType, key: entry.key },
|
||||
select: { id: true },
|
||||
});
|
||||
if (exists) {
|
||||
continue;
|
||||
}
|
||||
await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.customFieldDefinition.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
entityType: entry.entityType,
|
||||
key: entry.key,
|
||||
label: entry.label,
|
||||
datentyp: entry.datentyp,
|
||||
optionen: toJsonInput(entry.optionen ?? null),
|
||||
isDemoData: true,
|
||||
},
|
||||
}),
|
||||
);
|
||||
await tx.customFieldDefinition.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
entityType: entry.entityType,
|
||||
key: entry.key,
|
||||
label: entry.label,
|
||||
datentyp: entry.datentyp,
|
||||
optionen: toJsonInput(entry.optionen ?? null),
|
||||
isDemoData,
|
||||
},
|
||||
});
|
||||
created += 1;
|
||||
}
|
||||
return { created };
|
||||
}
|
||||
|
||||
export async function seedShkCustomFieldTemplate(input: SeedShkCustomFieldTemplateInput): Promise<{ created: number }> {
|
||||
// Avoid opening an RLS transaction while the versioned template is empty.
|
||||
// Once entries exist, the wrapper still binds the tenant before any query.
|
||||
if (SHK_CUSTOM_FIELD_TEMPLATE.length === 0) {
|
||||
return { created: 0 };
|
||||
}
|
||||
return withTenantRLS(input.tenantId, (tx) => seedShkCustomFieldTemplateWithTx(tx, input));
|
||||
}
|
||||
|
||||
/** Bulk-remove demo custom-field definitions on the production switch-over. */
|
||||
export async function clearDemoCustomFields(input: { tenantId: string }): Promise<{ deleted: number }> {
|
||||
const result = await withTenantRLS(input.tenantId, (tx) => tx.customFieldDefinition.deleteMany({ where: { tenantId: input.tenantId, isDemoData: true } }));
|
||||
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
withTenantRLS: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
create: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({ withTenantRLS: mocks.withTenantRLS }));
|
||||
|
||||
import { seedShkCustomFieldTemplate, seedShkCustomFieldTemplateWithTx, SHK_CUSTOM_FIELD_TEMPLATE } from "./customFieldService.server";
|
||||
|
||||
const tx = {
|
||||
customFieldDefinition: {
|
||||
findFirst: mocks.findFirst,
|
||||
create: mocks.create,
|
||||
},
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.withTenantRLS.mockImplementation(async (_tenantId, callback) => callback(tx));
|
||||
});
|
||||
|
||||
describe("SHK custom-field template transaction boundary", () => {
|
||||
it("keeps the intentionally empty template as a no-op in an existing transaction", async () => {
|
||||
const result = await seedShkCustomFieldTemplateWithTx(tx as never, { tenantId: "tenant-atomic-bootstrap" });
|
||||
|
||||
expect(SHK_CUSTOM_FIELD_TEMPLATE).toEqual([]);
|
||||
expect(result).toEqual({ created: 0 });
|
||||
expect(mocks.withTenantRLS).not.toHaveBeenCalled();
|
||||
expect(mocks.findFirst).not.toHaveBeenCalled();
|
||||
expect(mocks.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("avoids an RLS transaction while the versioned template is empty", async () => {
|
||||
await expect(seedShkCustomFieldTemplate({ tenantId: "tenant-wrapper" })).resolves.toEqual({ created: 0 });
|
||||
|
||||
expect(mocks.withTenantRLS).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { countTagUsageByTagIds, listTagsForEntities } from "./tagService.server";
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("tag service batch reads", () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
test("loads assignments for an entity page with one query", async () => {
|
||||
const findMany = vi.fn(async () => [
|
||||
{ entityId: "contact-1", tag: { id: "tag-1", tenantId: "tenant-1", name: "Hot", farbe: "#f00", createdAt: new Date(0) } },
|
||||
{ entityId: "contact-2", tag: { id: "tag-2", tenantId: "tenant-1", name: "Warm", farbe: "#fa0", createdAt: new Date(0) } },
|
||||
]);
|
||||
vi.mocked(withTenantRLS).mockImplementation(async (_tenantId, callback) =>
|
||||
callback({ tagAssignment: { findMany } } as never),
|
||||
);
|
||||
|
||||
const result = await listTagsForEntities({
|
||||
tenantId: "tenant-1",
|
||||
entityType: "kontakt",
|
||||
entityIds: ["contact-1", "contact-2", "contact-1"],
|
||||
});
|
||||
|
||||
expect(findMany).toHaveBeenCalledOnce();
|
||||
expect(findMany).toHaveBeenCalledWith(expect.objectContaining({
|
||||
where: expect.objectContaining({ entityId: { in: ["contact-1", "contact-2"] } }),
|
||||
}));
|
||||
expect(result.get("contact-1")?.map((tag) => tag.id)).toEqual(["tag-1"]);
|
||||
expect(result.get("contact-2")?.map((tag) => tag.id)).toEqual(["tag-2"]);
|
||||
});
|
||||
|
||||
test("loads all per-tag usage counts with one grouped query", async () => {
|
||||
const groupBy = vi.fn(async () => [{ tagId: "tag-1", _count: { _all: 3 } }]);
|
||||
vi.mocked(withTenantRLS).mockImplementation(async (_tenantId, callback) =>
|
||||
callback({ tagAssignment: { groupBy } } as never),
|
||||
);
|
||||
|
||||
const result = await countTagUsageByTagIds("tenant-1", ["tag-1", "tag-2", "tag-1"]);
|
||||
|
||||
expect(groupBy).toHaveBeenCalledOnce();
|
||||
expect(result).toEqual(new Map([["tag-1", 3], ["tag-2", 0]]));
|
||||
});
|
||||
});
|
||||
+40
@@ -104,10 +104,50 @@ export async function listTagsForEntity(input: { tenantId: string; entityType: s
|
||||
return assignments.map((assignment) => assignment.tag as TagRow);
|
||||
}
|
||||
|
||||
export async function listTagsForEntities(input: {
|
||||
tenantId: string;
|
||||
entityType: string;
|
||||
entityIds: readonly string[];
|
||||
}): Promise<Map<string, TagRow[]>> {
|
||||
const entityIds = [...new Set(input.entityIds.filter(Boolean))];
|
||||
const tagsByEntity = new Map(entityIds.map((entityId) => [entityId, [] as TagRow[]]));
|
||||
if (entityIds.length === 0) return tagsByEntity;
|
||||
|
||||
const assignments = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.tagAssignment.findMany({
|
||||
where: { tenantId: input.tenantId, entityType: input.entityType, entityId: { in: entityIds } },
|
||||
include: { tag: true },
|
||||
orderBy: { createdAt: "asc" },
|
||||
}),
|
||||
);
|
||||
for (const assignment of assignments) {
|
||||
tagsByEntity.get(assignment.entityId)?.push(assignment.tag as TagRow);
|
||||
}
|
||||
return tagsByEntity;
|
||||
}
|
||||
|
||||
export async function countTagUsage(tenantId: string, tagId: string): Promise<number> {
|
||||
return withTenantRLS(tenantId, (tx) => tx.tagAssignment.count({ where: { tenantId, tagId } }));
|
||||
}
|
||||
|
||||
export async function countTagUsageByTagIds(tenantId: string, tagIds: readonly string[]): Promise<Map<string, number>> {
|
||||
const ids = [...new Set(tagIds.filter(Boolean))];
|
||||
const usageCounts = new Map(ids.map((tagId) => [tagId, 0]));
|
||||
if (ids.length === 0) return usageCounts;
|
||||
|
||||
const counts = await withTenantRLS(tenantId, (tx) =>
|
||||
tx.tagAssignment.groupBy({
|
||||
by: ["tagId"],
|
||||
where: { tenantId, tagId: { in: ids } },
|
||||
_count: { _all: true },
|
||||
}),
|
||||
);
|
||||
for (const row of counts) {
|
||||
usageCounts.set(row.tagId, row._count._all);
|
||||
}
|
||||
return usageCounts;
|
||||
}
|
||||
|
||||
// --- internal --------------------------------------------------------------
|
||||
|
||||
function isUniqueConstraintError(error: unknown): boolean {
|
||||
|
||||
Reference in new issue
Block a user