Update hivegrid-cloud reference to latest main

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

No files matched your search

@@ -0,0 +1,158 @@
import { empty, ready, type VMState } from "../index.js";
/**
* Activity-stream view-model (R-P6, P6 CRM core — Variante A). Pure function:
* the loader builds it once server-side from the Activity rows + resolved actor
* labels. `summaryText` is ALREADY the German Klartext line persisted on the
* activity (DoD 14) — it is passed through verbatim, never re-translated. Static
* markers are i18n KEYS. No React/Prisma/server imports (DoD A.3).
*
* The actor/type unions mirror `@hivegrid/activity/types` (kept local so the
* view-models package stays dependency-free, matching the task VMs' pattern).
*/
/** Mirrors `ActivityActorKind` from `@hivegrid/activity/types`. */
export type ActivityActorKind = "user" | "system" | "automation" | "ki_agent";
/** Mirrors `ActivityType` from `@hivegrid/activity/types`. */
export type ActivityType =
| "call_inbound"
| "call_outbound"
| "email_sent"
| "email_received"
| "whatsapp_sent"
| "whatsapp_received"
| "chat_message"
| "note_added"
| "tag_added"
| "tag_removed"
| "assignee_changed"
| "deal_stage_changed"
| "project_stage_changed"
| "project_member_added"
| "project_appointment_created"
| "project_invoice_created"
| "project_invoice_status_changed"
| "project_checklist_created"
| "project_schedule_changed"
| "project_acceptance_submitted"
| "file_uploaded"
| "form_submitted"
| "task_created"
| "task_completed"
| "contact_created"
| "contact_updated"
| "contact_archived"
| "appointment_scheduled"
| "appointment_held"
| "lead_promoted"
| "deal_won"
| "deal_lost"
| "automation_triggered"
| "ki_action"
| "audit_event";
export interface ActivityEntryData {
readonly id: string;
readonly activityType: ActivityType;
/** i18n key for the activity-type label (e.g. `crm.activity.note_added`). */
readonly activityLabelKey: string;
readonly actorKind: ActivityActorKind;
/** Resolved actor display name (data) or null for non-user / system actors. */
readonly actorLabel: string | null;
/** Pre-rendered Klartext line from the DB — passed through, NOT translated. */
readonly summaryText: string;
readonly createdAtIso: string;
/** Marker key chosen by activity type, falling back to the actor kind. */
readonly iconKey: string;
}
export interface ActivityStreamData {
readonly entries: readonly ActivityEntryData[];
readonly hasMore: boolean;
}
export type ActivityStreamVM = VMState<ActivityStreamData>;
/** i18n key for an activity type (e.g. `crm.activity.tag_added`). */
export function activityLabelKey(activityType: ActivityType): string {
return `crm.activity.${activityType}`;
}
/** Pick a stable icon marker: a type-specific marker wins, else the actor kind. */
export function activityIconKey(actorKind: ActivityActorKind, activityType: ActivityType): string {
switch (activityType) {
case "email_sent":
case "email_received":
return "mail";
case "call_inbound":
case "call_outbound":
return "phone";
case "whatsapp_sent":
case "whatsapp_received":
case "chat_message":
return "chat";
case "note_added":
return "note";
case "tag_added":
case "tag_removed":
return "tag";
case "file_uploaded":
return "file";
case "assignee_changed":
return "assignee";
case "contact_created":
case "contact_updated":
case "contact_archived":
return "contact";
case "task_created":
case "task_completed":
return "task";
default:
break;
}
switch (actorKind) {
case "automation":
return "automation";
case "ki_agent":
return "ki";
case "system":
return "system";
default:
return "user";
}
}
/** Minimal activity source row (mirrors the persisted Activity columns used). */
export interface ActivityStreamSourceRow {
readonly id: string;
readonly createdAt: Date;
readonly actorUserId: string | null;
readonly actorKind: ActivityActorKind;
readonly activityType: ActivityType;
readonly summaryText: string;
}
export interface BuildActivityStreamVMInput {
readonly rows: readonly ActivityStreamSourceRow[];
/** userId -> display label (crmService.resolveUserLabels). */
readonly userLabels: ReadonlyMap<string, string>;
readonly hasMore: boolean;
}
export function buildActivityStreamVM(input: BuildActivityStreamVMInput): ActivityStreamVM {
if (input.rows.length === 0) {
return empty<ActivityStreamData>();
}
const entries: ActivityEntryData[] = input.rows.map((row) => ({
id: row.id,
activityType: row.activityType,
activityLabelKey: activityLabelKey(row.activityType),
actorKind: row.actorKind,
actorLabel: row.actorUserId ? (input.userLabels.get(row.actorUserId) ?? null) : null,
summaryText: row.summaryText,
createdAtIso: row.createdAt.toISOString(),
iconKey: activityIconKey(row.actorKind, row.activityType),
}));
return ready<ActivityStreamData>({ entries, hasMore: input.hasMore });
}
@@ -0,0 +1,312 @@
import { describe, expect, it } from "vitest";
import {
buildActivityStreamVM,
buildCustomFieldAdminVM,
buildDuplicateVM,
buildKontaktCsv,
buildKontaktDetailVM,
buildKontaktListVM,
buildTagAdminVM,
type BuildActivityStreamVMInput,
type BuildCustomFieldAdminVMInput,
type BuildDuplicateVMInput,
type BuildKontaktDetailVMInput,
type BuildKontaktListVMInput,
type BuildTagAdminVMInput,
type KontaktListAppliedFilter,
} from "../index.js";
const filter: KontaktListAppliedFilter = {
kontaktTyp: null,
kontaktStatus: null,
zustaendigerUserId: null,
search: null,
tagIds: null,
tagMatch: "or",
includeArchived: false,
};
// --- kontakt-list -----------------------------------------------------------
describe("buildKontaktListVM", () => {
const baseInput: BuildKontaktListVMInput = {
rows: [
{
id: "k1",
kontaktTyp: "privatperson",
kontaktStatus: "kunde",
vorname: "Anna",
nachname: "Muster",
orgName: null,
orgMerkmal: null,
primaerEmail: "anna@example.com",
primaerTelefon: null,
zustaendigerUserId: "u1",
createdAt: new Date("2026-06-20T08:00:00.000Z"),
archivedAt: null,
},
{
id: "k2",
kontaktTyp: "organisation",
kontaktStatus: "bestandskunde",
vorname: null,
nachname: null,
orgName: "Acme GmbH",
orgMerkmal: "gmbh",
primaerEmail: null,
primaerTelefon: "+49 30 123",
zustaendigerUserId: null,
createdAt: new Date("2026-06-21T08:00:00.000Z"),
archivedAt: new Date("2026-06-22T08:00:00.000Z"),
},
],
userLabels: new Map([["u1", "Raffael"]]),
tagsByKontakt: new Map([["k1", [{ id: "t1", name: "VIP", farbe: "#f00" }]]]),
pagination: { page: 2, pageCount: 3, total: 120 },
sort: { field: "name", dir: "asc" },
filter,
perms: { canWrite: true, canDelete: false, canReadAll: true },
tenantSlug: "acme",
};
it("returns an empty state when there are no contacts", () => {
const vm = buildKontaktListVM({ ...baseInput, rows: [] });
expect(vm.status).toBe("empty");
});
it("maps rows with display names, i18n keys, tag chips and internal hrefs", () => {
const vm = buildKontaktListVM(baseInput);
if (vm.status !== "ready") throw new Error("expected ready");
const [r1, r2] = vm.data.rows;
expect(r1?.displayName).toBe("Anna Muster");
expect(r1?.typLabelKey).toBe("crm.kontaktTyp.privatperson");
expect(r1?.statusLabelKey).toBe("crm.kontaktStatus.kunde");
expect(r1?.zustaendigerLabel).toBe("Raffael");
expect(r1?.tagChips[0]?.name).toBe("VIP");
expect(r1?.orgMerkmalLabelKey).toBeNull();
expect(r1?.detailHref).toBe("/acme/contacts/k1");
expect(r1?.isArchived).toBe(false);
expect(r1?.createdAtIso).toBe("2026-06-20T08:00:00.000Z");
// organisation row
expect(r2?.displayName).toBe("Acme GmbH");
expect(r2?.orgMerkmalLabelKey).toBe("crm.orgMerkmal.gmbh");
expect(r2?.zustaendigerLabel).toBeNull();
expect(r2?.isArchived).toBe(true);
});
it("derives pagination hasPrev/hasNext and echoes filter/sort/perms", () => {
const vm = buildKontaktListVM(baseInput);
if (vm.status !== "ready") throw new Error("expected ready");
expect(vm.data.pagination).toMatchObject({ page: 2, pageCount: 3, total: 120, hasPrev: true, hasNext: true });
expect(vm.data.sort).toEqual({ field: "name", dir: "asc" });
expect(vm.data.appliedFilter.tagMatch).toBe("or");
expect(vm.data.canReadAll).toBe(true);
});
it("fills the optional org-only fields only when supplied", () => {
const vm = buildKontaktListVM({
...baseInput,
orgKontaktAnzahl: new Map([["k2", 4]]),
orgLastActivityIso: new Map([["k2", "2026-06-23T08:00:00.000Z"]]),
});
if (vm.status !== "ready") throw new Error("expected ready");
expect(vm.data.rows[0]?.kontaktAnzahl).toBeUndefined();
expect(vm.data.rows[1]?.kontaktAnzahl).toBe(4);
expect(vm.data.rows[1]?.letzteActivityIso).toBe("2026-06-23T08:00:00.000Z");
});
});
// --- kontakt-detail ---------------------------------------------------------
describe("buildKontaktDetailVM", () => {
const base: BuildKontaktDetailVMInput = {
detail: {
kontakt: {
id: "k1",
kontaktTyp: "privatperson",
kontaktStatus: "kontakt",
vorname: "Anna",
nachname: "Muster",
orgName: null,
orgMerkmal: null,
primaerEmail: "anna@example.com",
zustaendigerUserId: "u1",
archivedAt: null,
createdAt: new Date("2026-06-20T08:00:00.000Z"),
updatedAt: new Date("2026-06-21T08:00:00.000Z"),
},
emails: [{ id: "e1", email: "anna@example.com", primaer: true }],
telefone: [{ id: "p1", telefon: "+49 30 1", primaer: true }],
relationen: [
{ id: "rel1", vonKontaktId: "k1", zuKontaktId: "k9", rolle: "hauptkontakt", kontext: "Buchhaltung" },
{ id: "rel2", vonKontaktId: "k7", zuKontaktId: "k1", rolle: "mitarbeiter", kontext: null },
],
adresse: { strasse: "Hauptstr", hausnummer: "1", plz: "10115", ort: "Berlin", land: "DE" },
},
customFields: [{ definition: { id: "d1", key: "umsatz", label: "Umsatz", datentyp: "waehrung", optionen: null }, wert: 1000 }],
tags: [{ id: "t1", name: "VIP", farbe: "#f00" }],
userLabels: new Map([["u1", "Raffael"]]),
perms: { canWrite: true, canDelete: false },
tenantSlug: "acme",
};
it("maps channels, relations (von/zu), custom fields and i18n keys", () => {
const vm = buildKontaktDetailVM(base);
if (vm.status !== "ready") throw new Error("expected ready");
expect(vm.data.displayName).toBe("Anna Muster");
expect(vm.data.typLabelKey).toBe("crm.kontaktTyp.privatperson");
expect(vm.data.emails[0]?.primaer).toBe(true);
const von = vm.data.relationen.find((r) => r.id === "rel1");
const zu = vm.data.relationen.find((r) => r.id === "rel2");
expect(von?.richtung).toBe("von");
expect(von?.otherKontaktId).toBe("k9");
expect(von?.rolleLabelKey).toBe("crm.kontaktArt.hauptkontakt");
expect(zu?.richtung).toBe("zu");
expect(zu?.otherKontaktId).toBe("k7");
expect(vm.data.customFields[0]).toMatchObject({ definitionId: "d1", key: "umsatz", datentyp: "waehrung", wert: 1000 });
expect(vm.data.zustaendigerLabel).toBe("Raffael");
expect(vm.data.listHref).toBe("/acme/contacts");
});
it("derives quickActions from perms (archive when active, +delete when deletable)", () => {
const vm = buildKontaktDetailVM(base);
if (vm.status !== "ready") throw new Error("expected ready");
expect(vm.data.quickActions).toEqual(["addNote", "addTag", "reassign", "archive"]);
const archived = buildKontaktDetailVM({
...base,
detail: { ...base.detail, kontakt: { ...base.detail.kontakt, archivedAt: new Date() } },
perms: { canWrite: true, canDelete: true },
});
if (archived.status !== "ready") throw new Error("expected ready");
expect(archived.data.quickActions).toContain("reactivate");
expect(archived.data.quickActions).toContain("delete");
const readOnly = buildKontaktDetailVM({ ...base, perms: { canWrite: false, canDelete: false } });
if (readOnly.status !== "ready") throw new Error("expected ready");
expect(readOnly.data.quickActions).toEqual([]);
});
});
// --- activity-stream --------------------------------------------------------
describe("buildActivityStreamVM", () => {
const input: BuildActivityStreamVMInput = {
rows: [
{ id: "a1", createdAt: new Date("2026-06-20T08:00:00.000Z"), actorUserId: "u1", actorKind: "user", activityType: "note_added", summaryText: "Notiz: Rückruf vereinbart" },
{ id: "a2", createdAt: new Date("2026-06-20T09:00:00.000Z"), actorUserId: null, actorKind: "system", activityType: "contact_created", summaryText: "Kontakt angelegt" },
],
userLabels: new Map([["u1", "Raffael"]]),
hasMore: true,
};
it("returns an empty state when there are no entries", () => {
expect(buildActivityStreamVM({ ...input, rows: [] }).status).toBe("empty");
});
it("passes summaryText through and derives label/icon/actor", () => {
const vm = buildActivityStreamVM(input);
if (vm.status !== "ready") throw new Error("expected ready");
expect(vm.data.hasMore).toBe(true);
const e1 = vm.data.entries[0];
expect(e1?.summaryText).toBe("Notiz: Rückruf vereinbart");
expect(e1?.activityLabelKey).toBe("crm.activity.note_added");
expect(e1?.iconKey).toBe("note");
expect(e1?.actorLabel).toBe("Raffael");
const e2 = vm.data.entries[1];
expect(e2?.actorLabel).toBeNull();
expect(e2?.iconKey).toBe("contact");
});
});
// --- custom-field-admin -----------------------------------------------------
describe("buildCustomFieldAdminVM", () => {
const input: BuildCustomFieldAdminVMInput = {
rows: [{ id: "d1", entityType: "kontakt", key: "umsatz", label: "Umsatz", datentyp: "waehrung", optionen: null, archiviert: false, isDemoData: false }],
entityType: "kontakt",
canWrite: true,
};
it("stays ready (with the CTA context) even when empty", () => {
const vm = buildCustomFieldAdminVM({ ...input, rows: [] });
if (vm.status !== "ready") throw new Error("expected ready");
expect(vm.data.rows).toHaveLength(0);
expect(vm.data.entityType).toBe("kontakt");
expect(vm.data.canWrite).toBe(true);
});
it("maps datentyp label keys", () => {
const vm = buildCustomFieldAdminVM(input);
if (vm.status !== "ready") throw new Error("expected ready");
expect(vm.data.rows[0]?.datentypLabelKey).toBe("crm.datentyp.waehrung");
});
});
// --- tag-admin --------------------------------------------------------------
describe("buildTagAdminVM", () => {
const input: BuildTagAdminVMInput = {
tags: [
{ id: "t1", name: "VIP", farbe: "#f00" },
{ id: "t2", name: "Lead", farbe: "#0f0" },
],
usageCounts: new Map([["t1", 5]]),
canWrite: true,
};
it("defaults usageCount to 0 when no count is supplied", () => {
const vm = buildTagAdminVM(input);
if (vm.status !== "ready") throw new Error("expected ready");
expect(vm.data.rows[0]?.usageCount).toBe(5);
expect(vm.data.rows[1]?.usageCount).toBe(0);
});
});
// --- duplicate --------------------------------------------------------------
describe("buildDuplicateVM", () => {
const input: BuildDuplicateVMInput = {
pairs: [
{
matchType: "hard",
matchReason: "email",
a: { id: "k1", kontaktTyp: "privatperson", kontaktStatus: "kontakt", vorname: "Anna", nachname: "Muster", orgName: null, primaerEmail: "a@x.de", primaerTelefon: null, zustaendigerUserId: "u1", createdAt: new Date("2026-06-20T08:00:00.000Z") },
b: { id: "k2", kontaktTyp: "privatperson", kontaktStatus: "kunde", vorname: "Anna", nachname: "Muster", orgName: null, primaerEmail: "a@x.de", primaerTelefon: null, zustaendigerUserId: null, createdAt: new Date("2026-06-21T08:00:00.000Z") },
},
],
userLabels: new Map([["u1", "Raffael"]]),
canMerge: true,
tenantSlug: "acme",
};
it("returns an empty state when there are no duplicate pairs", () => {
expect(buildDuplicateVM({ ...input, pairs: [] }).status).toBe("empty");
});
it("builds side-by-side cards with reason keys and internal hrefs", () => {
const vm = buildDuplicateVM(input);
if (vm.status !== "ready") throw new Error("expected ready");
const pair = vm.data.pairs[0];
expect(pair?.matchType).toBe("hard");
expect(pair?.matchReasonKey).toBe("crm.duplicate.reason.email");
expect(pair?.a.detailHref).toBe("/acme/contacts/k1");
expect(pair?.a.zustaendigerLabel).toBe("Raffael");
expect(pair?.b.zustaendigerLabel).toBeNull();
expect(vm.data.canMerge).toBe(true);
});
});
// --- kontakt-csv ------------------------------------------------------------
describe("buildKontaktCsv", () => {
it("writes a German header and escapes RFC 4180 special characters", () => {
const csv = buildKontaktCsv([
{ displayName: 'Muster, Anna "die Erste"', kontaktTyp: "privatperson", kontaktStatus: "kunde", primaerEmail: "a@x.de", primaerTelefon: null, zustaendigerLabel: "Raffael", createdAtIso: "2026-06-20T08:00:00.000Z" },
]);
const lines = csv.split("\r\n");
expect(lines[0]).toBe("Name,Typ,Status,E-Mail,Telefon,Zuständig,Erstellt am");
// comma + quote in the name -> field quoted, inner quotes doubled
expect(lines[1]).toContain('"Muster, Anna ""die Erste"""');
// null telefon becomes an empty field
expect(lines[1]).toBe('"Muster, Anna ""die Erste""",privatperson,kunde,a@x.de,,Raffael,2026-06-20T08:00:00.000Z');
});
it("emits a header-only string for an empty row set", () => {
expect(buildKontaktCsv([])).toBe("Name,Typ,Status,E-Mail,Telefon,Zuständig,Erstellt am");
});
});
@@ -0,0 +1,90 @@
import { ready, type VMState } from "../index.js";
/**
* Custom-field admin view-model (R-P6, P6 CRM core — Variante A). Pure function:
* the loader builds it from `customFieldService.listCustomFieldDefinitions`.
* Lists the field definitions for one entity type so an admin can manage them.
* Static texts are i18n KEYS. No React/Prisma/server imports (DoD A.3).
*
* Stays `ready` even with zero rows so the entity-type tabs and the "create
* field" CTA (held in `data`) remain available for the admin.
*/
/** Mirrors `CustomFieldEntityType` from customFieldService. */
export type CustomFieldEntityType = "projekt" | "kontakt" | "lead" | "rechnung";
/** Mirrors `CustomFieldDatentyp` from customFieldService (12 types). */
export type CustomFieldDatentyp =
| "text"
| "textarea"
| "zahl"
| "waehrung"
| "datum"
| "datum_range"
| "select"
| "multiselect"
| "boolean"
| "email"
| "telefon"
| "datei";
export interface CustomFieldAdminRowData {
readonly id: string;
readonly entityType: CustomFieldEntityType;
readonly key: string;
readonly label: string;
readonly datentyp: CustomFieldDatentyp;
/** i18n key for the data type label (e.g. `crm.datentyp.select`). */
readonly datentypLabelKey: string;
/** Opaque JSON options (select/multiselect choices etc.); UI renders them. */
readonly optionen: unknown;
readonly archiviert: boolean;
readonly isDemoData: boolean;
}
export interface CustomFieldAdminData {
readonly rows: readonly CustomFieldAdminRowData[];
/** The entity type currently being managed. */
readonly entityType: CustomFieldEntityType;
readonly canWrite: boolean;
}
export type CustomFieldAdminVM = VMState<CustomFieldAdminData>;
/** i18n key for a custom-field data type (e.g. `crm.datentyp.waehrung`). */
export function datentypLabelKey(datentyp: CustomFieldDatentyp): string {
return `crm.datentyp.${datentyp}`;
}
/** Minimal definition source row (mirrors customFieldService.CustomFieldDefinitionRow). */
export interface CustomFieldAdminSourceRow {
readonly id: string;
readonly entityType: CustomFieldEntityType;
readonly key: string;
readonly label: string;
readonly datentyp: CustomFieldDatentyp;
readonly optionen: unknown;
readonly archiviert: boolean;
readonly isDemoData: boolean;
}
export interface BuildCustomFieldAdminVMInput {
readonly rows: readonly CustomFieldAdminSourceRow[];
readonly entityType: CustomFieldEntityType;
readonly canWrite: boolean;
}
export function buildCustomFieldAdminVM(input: BuildCustomFieldAdminVMInput): CustomFieldAdminVM {
const rows: CustomFieldAdminRowData[] = input.rows.map((row) => ({
id: row.id,
entityType: row.entityType,
key: row.key,
label: row.label,
datentyp: row.datentyp,
datentypLabelKey: datentypLabelKey(row.datentyp),
optionen: row.optionen,
archiviert: row.archiviert,
isDemoData: row.isDemoData,
}));
return ready<CustomFieldAdminData>({ rows, entityType: input.entityType, canWrite: input.canWrite });
}
@@ -0,0 +1,112 @@
import { empty, ready, type VMState } from "../index.js";
import {
buildKontaktDisplayName,
kontaktStatusLabelKey,
kontaktTypLabelKey,
type KontaktStatus,
type KontaktTyp,
} from "./kontakt-list.vm.js";
/**
* Duplicate-contacts view-model (R-P6, P6 CRM core — Variante A) backing the
* `/admin/duplicates` side-by-side merge screen. Pure function: the loader
* builds it from `crmService.findDuplicateKontakte` results, grouped into
* candidate pairs. `hard` = exact channel match, `soft` = name-only match.
* Static texts are i18n KEYS. No React/Prisma/server imports (DoD A.3).
*/
export type DuplicateMatchType = "hard" | "soft";
/** A contact card shown on one side of a merge pair (resolved display data). */
export interface DuplicateKontaktCard {
readonly id: string;
readonly displayName: string;
readonly kontaktTyp: KontaktTyp;
readonly typLabelKey: string;
readonly kontaktStatus: KontaktStatus;
readonly statusLabelKey: string;
readonly primaerEmail: string | null;
readonly primaerTelefon: string | null;
readonly zustaendigerLabel: string | null;
readonly detailHref: string;
readonly createdAtIso: string;
}
export interface DuplicatePairData {
readonly matchType: DuplicateMatchType;
/** i18n key explaining why the pair matched (e.g. `crm.duplicate.reason.email`). */
readonly matchReasonKey: string;
readonly a: DuplicateKontaktCard;
readonly b: DuplicateKontaktCard;
}
export interface DuplicateData {
readonly pairs: readonly DuplicatePairData[];
readonly canMerge: boolean;
}
export type DuplicateVM = VMState<DuplicateData>;
/** i18n key for a duplicate match reason (e.g. `crm.duplicate.reason.name`). */
export function duplicateReasonKey(reason: string): string {
return `crm.duplicate.reason.${reason}`;
}
// --- Builder input ----------------------------------------------------------
export interface DuplicateCardSource {
readonly id: string;
readonly kontaktTyp: KontaktTyp;
readonly kontaktStatus: KontaktStatus;
readonly vorname: string | null;
readonly nachname: string | null;
readonly orgName: string | null;
readonly primaerEmail: string | null;
readonly primaerTelefon: string | null;
readonly zustaendigerUserId: string | null;
readonly createdAt: Date;
}
export interface DuplicatePairSource {
readonly matchType: DuplicateMatchType;
/** Reason token (e.g. "email" | "telefon" | "name" | "orgName"). */
readonly matchReason: string;
readonly a: DuplicateCardSource;
readonly b: DuplicateCardSource;
}
export interface BuildDuplicateVMInput {
readonly pairs: readonly DuplicatePairSource[];
/** userId -> display label (crmService.resolveUserLabels). */
readonly userLabels: ReadonlyMap<string, string>;
readonly canMerge: boolean;
readonly tenantSlug: string;
}
function toCard(source: DuplicateCardSource, userLabels: ReadonlyMap<string, string>, tenantSlug: string): DuplicateKontaktCard {
return {
id: source.id,
displayName: buildKontaktDisplayName(source),
kontaktTyp: source.kontaktTyp,
typLabelKey: kontaktTypLabelKey(source.kontaktTyp),
kontaktStatus: source.kontaktStatus,
statusLabelKey: kontaktStatusLabelKey(source.kontaktStatus),
primaerEmail: source.primaerEmail,
primaerTelefon: source.primaerTelefon,
zustaendigerLabel: source.zustaendigerUserId ? (userLabels.get(source.zustaendigerUserId) ?? null) : null,
detailHref: `/${tenantSlug}/contacts/${source.id}`,
createdAtIso: source.createdAt.toISOString(),
};
}
export function buildDuplicateVM(input: BuildDuplicateVMInput): DuplicateVM {
if (input.pairs.length === 0) {
return empty<DuplicateData>();
}
const pairs: DuplicatePairData[] = input.pairs.map((pair) => ({
matchType: pair.matchType,
matchReasonKey: duplicateReasonKey(pair.matchReason),
a: toCard(pair.a, input.userLabels, input.tenantSlug),
b: toCard(pair.b, input.userLabels, input.tenantSlug),
}));
return ready<DuplicateData>({ pairs, canMerge: input.canMerge });
}
@@ -0,0 +1,56 @@
/**
* Contact CSV export builder (R-P6, P6 CRM core — Variante A). Pure function:
* the route resolves the rows (incl. display labels) and this turns them into an
* RFC 4180 string. No React/Prisma/server imports (DoD A.3).
*
* Decisions:
* - Delimiter `,`, line ending CRLF, fields quoted only when they contain a
* comma, double-quote or newline; embedded quotes are doubled (RFC 4180 §2).
* - Header row uses fixed GERMAN column names: the export is consumed by end
* users (not a machine contract), so human-readable German headers win over
* the raw column keys.
*/
export interface KontaktCsvRow {
readonly displayName: string;
readonly kontaktTyp: string;
readonly kontaktStatus: string;
readonly primaerEmail: string | null;
readonly primaerTelefon: string | null;
readonly zustaendigerLabel: string | null;
readonly createdAtIso: string;
}
const CSV_HEADER: readonly string[] = ["Name", "Typ", "Status", "E-Mail", "Telefon", "Zuständig", "Erstellt am"];
/** Escape a single field per RFC 4180 (quote when needed, double inner quotes). */
function csvField(value: string | null): string {
const raw = value ?? "";
if (/[",\r\n]/.test(raw)) {
return `"${raw.replace(/"/g, '""')}"`;
}
return raw;
}
function csvLine(fields: readonly (string | null)[]): string {
return fields.map(csvField).join(",");
}
/** Build an RFC 4180 CSV (CRLF-separated) with a German header row. */
export function buildKontaktCsv(rows: readonly KontaktCsvRow[]): string {
const lines: string[] = [csvLine(CSV_HEADER)];
for (const row of rows) {
lines.push(
csvLine([
row.displayName,
row.kontaktTyp,
row.kontaktStatus,
row.primaerEmail,
row.primaerTelefon,
row.zustaendigerLabel,
row.createdAtIso,
]),
);
}
return lines.join("\r\n");
}
@@ -0,0 +1,212 @@
import { ready, type VMState } from "../index.js";
import {
kontaktArtLabelKey,
kontaktStatusLabelKey,
kontaktTypLabelKey,
orgMerkmalLabelKey,
buildKontaktDisplayName,
type KontaktArt,
type KontaktStatus,
type KontaktTagChip,
type KontaktTyp,
type OrgMerkmal,
} from "./kontakt-list.vm.js";
/**
* Contact detail view-model (R-P6, P6 CRM core — Variante A). Pure function: the
* loader builds it once server-side from `crmService.getKontaktDetail` plus the
* custom-field values, tags and resolved user labels. All static texts are i18n
* KEYS; resolved names are data. No React/Prisma/server imports (DoD A.3).
*/
export interface KontaktDetailEmail {
readonly id: string;
readonly email: string;
readonly primaer: boolean;
}
export interface KontaktDetailTelefon {
readonly id: string;
readonly telefon: string;
readonly primaer: boolean;
}
export interface KontaktDetailAdresse {
readonly strasse: string | null;
readonly hausnummer: string | null;
readonly plz: string | null;
readonly ort: string | null;
readonly land: string;
}
/** A relation seen from the perspective of the contact being viewed. */
export interface KontaktDetailRelation {
readonly id: string;
/** "von" = this contact is the source, "zu" = this contact is the target. */
readonly richtung: "von" | "zu";
readonly otherKontaktId: string;
readonly rolle: KontaktArt;
readonly rolleLabelKey: string;
readonly kontext: string | null;
}
/** A custom-field value with its definition (display-ready). `wert`/`optionen`
* stay opaque (JSON) — the UI renders per `datentyp`. */
export interface KontaktDetailCustomField {
readonly definitionId: string;
readonly key: string;
readonly label: string;
readonly datentyp: string;
readonly wert: unknown;
readonly optionen: unknown;
}
export interface KontaktDetailData {
readonly id: string;
readonly kontaktTyp: KontaktTyp;
readonly typLabelKey: string;
readonly kontaktStatus: KontaktStatus;
readonly statusLabelKey: string;
readonly displayName: string;
readonly vorname: string | null;
readonly nachname: string | null;
readonly orgName: string | null;
readonly orgMerkmal: OrgMerkmal | null;
readonly orgMerkmalLabelKey: string | null;
readonly emails: readonly KontaktDetailEmail[];
readonly telefone: readonly KontaktDetailTelefon[];
readonly adresse: KontaktDetailAdresse | null;
readonly relationen: readonly KontaktDetailRelation[];
readonly tags: readonly KontaktTagChip[];
readonly customFields: readonly KontaktDetailCustomField[];
readonly zustaendigerLabel: string | null;
readonly zustaendigerUserId: string | null;
readonly isArchived: boolean;
readonly createdAtIso: string;
readonly updatedAtIso: string;
/** Back link to the contact list (breadcrumb / cancel target). */
readonly listHref: string;
readonly canWrite: boolean;
readonly canDelete: boolean;
/** Action keys for the detail toolbar (gated by perms). */
readonly quickActions: readonly string[];
}
export type KontaktDetailVM = VMState<KontaktDetailData>;
// --- Builder input (mirrors crmService row shapes) --------------------------
export interface KontaktDetailSourceKontakt {
readonly id: string;
readonly kontaktTyp: KontaktTyp;
readonly kontaktStatus: KontaktStatus;
readonly vorname: string | null;
readonly nachname: string | null;
readonly orgName: string | null;
readonly orgMerkmal: OrgMerkmal | null;
readonly primaerEmail: string | null;
readonly zustaendigerUserId: string | null;
readonly archivedAt: Date | null;
readonly createdAt: Date;
readonly updatedAt: Date;
}
export interface KontaktDetailSourceRelation {
readonly id: string;
readonly vonKontaktId: string;
readonly zuKontaktId: string;
readonly rolle: KontaktArt;
readonly kontext: string | null;
}
export interface KontaktDetailSource {
readonly kontakt: KontaktDetailSourceKontakt;
readonly emails: readonly KontaktDetailEmail[];
readonly telefone: readonly KontaktDetailTelefon[];
readonly relationen: readonly KontaktDetailSourceRelation[];
readonly adresse: KontaktDetailAdresse | null;
}
/** Custom-field value + definition (mirrors crmService.CustomFieldValueWithDefinition). */
export interface KontaktDetailCustomFieldSource {
readonly definition: {
readonly id: string;
readonly key: string;
readonly label: string;
readonly datentyp: string;
readonly optionen: unknown;
};
readonly wert: unknown;
}
export interface BuildKontaktDetailVMInput {
readonly detail: KontaktDetailSource;
readonly customFields: readonly KontaktDetailCustomFieldSource[];
readonly tags: readonly KontaktTagChip[];
readonly userLabels: ReadonlyMap<string, string>;
readonly perms: { readonly canWrite: boolean; readonly canDelete: boolean };
readonly tenantSlug: string;
}
export function buildKontaktDetailVM(input: BuildKontaktDetailVMInput): KontaktDetailVM {
const { kontakt } = input.detail;
const isOrg = kontakt.kontaktTyp === "organisation";
const relationen: KontaktDetailRelation[] = input.detail.relationen.map((rel) => {
const isVon = rel.vonKontaktId === kontakt.id;
return {
id: rel.id,
richtung: isVon ? "von" : "zu",
otherKontaktId: isVon ? rel.zuKontaktId : rel.vonKontaktId,
rolle: rel.rolle,
rolleLabelKey: kontaktArtLabelKey(rel.rolle),
kontext: rel.kontext,
};
});
const customFields: KontaktDetailCustomField[] = input.customFields.map((cf) => ({
definitionId: cf.definition.id,
key: cf.definition.key,
label: cf.definition.label,
datentyp: cf.definition.datentyp,
wert: cf.wert,
optionen: cf.definition.optionen,
}));
const isArchived = kontakt.archivedAt !== null;
const quickActions: string[] = [];
if (input.perms.canWrite) {
quickActions.push("addNote", "addTag", "reassign", isArchived ? "reactivate" : "archive");
}
if (input.perms.canDelete) {
quickActions.push("delete");
}
return ready<KontaktDetailData>({
id: kontakt.id,
kontaktTyp: kontakt.kontaktTyp,
typLabelKey: kontaktTypLabelKey(kontakt.kontaktTyp),
kontaktStatus: kontakt.kontaktStatus,
statusLabelKey: kontaktStatusLabelKey(kontakt.kontaktStatus),
displayName: buildKontaktDisplayName(kontakt),
vorname: kontakt.vorname,
nachname: kontakt.nachname,
orgName: kontakt.orgName,
orgMerkmal: kontakt.orgMerkmal,
orgMerkmalLabelKey: isOrg && kontakt.orgMerkmal ? orgMerkmalLabelKey(kontakt.orgMerkmal) : null,
emails: input.detail.emails,
telefone: input.detail.telefone,
adresse: input.detail.adresse,
relationen,
tags: input.tags,
customFields,
zustaendigerLabel: kontakt.zustaendigerUserId ? (input.userLabels.get(kontakt.zustaendigerUserId) ?? null) : null,
zustaendigerUserId: kontakt.zustaendigerUserId,
isArchived,
createdAtIso: kontakt.createdAt.toISOString(),
updatedAtIso: kontakt.updatedAt.toISOString(),
listHref: `/${input.tenantSlug}/contacts`,
canWrite: input.perms.canWrite,
canDelete: input.perms.canDelete,
quickActions,
});
}
@@ -0,0 +1,212 @@
import { empty, ready, type VMState } from "../index.js";
/**
* Contact list view-model (R-P6, P6 CRM core — Variante A). Pure function: the
* loader builds it once server-side from the crmService rows, the UI only
* renders. No React, no Prisma, no app/server imports (DoD A.3). All static
* texts are i18n KEYS; resolved values (zustaendigerLabel, tag chips) are data
* passed in by the loader.
*
* This file is the "hub" of the CRM view-models: the shared domain enums and
* their i18n-key helpers live here and are imported by the sibling VMs
* (detail / duplicate) so the barrel re-export stays collision-free.
*
* The organisation list is served by the SAME VM with a `kontaktTyp`
* organisation filter; the org-only fields (`kontaktAnzahl`,
* `letzteActivityIso`) are optional and only filled when the loader supplies
* the corresponding maps.
*/
// --- Shared domain enums (mirror the crm.prisma / crmService enums 1:1) -----
export type KontaktTyp = "privatperson" | "organisation";
export type KontaktStatus = "kontakt" | "kunde" | "bestandskunde";
export type OrgMerkmal = "gmbh" | "kg" | "oeffentliche_einrichtung" | "sonstige";
export type KontaktArt = "hauptkontakt" | "sekundaerkontakt" | "mitarbeiter" | "sonstige";
export type KontaktSortField = "name" | "createdAt" | "kontaktStatus";
export type KontaktSortDir = "asc" | "desc";
/** Tag chip rendered next to a contact (resolved data, no i18n). */
export interface KontaktTagChip {
readonly id: string;
readonly name: string;
readonly farbe: string;
}
// --- Shared i18n-key helpers (reused by detail/duplicate VMs) ---------------
export function kontaktTypLabelKey(typ: KontaktTyp): string {
return `crm.kontaktTyp.${typ}`;
}
export function kontaktStatusLabelKey(status: KontaktStatus): string {
return `crm.kontaktStatus.${status}`;
}
export function orgMerkmalLabelKey(merkmal: OrgMerkmal): string {
return `crm.orgMerkmal.${merkmal}`;
}
export function kontaktArtLabelKey(rolle: KontaktArt): string {
return `crm.kontaktArt.${rolle}`;
}
// --- Row data ---------------------------------------------------------------
export interface KontaktListRowData {
readonly id: string;
/** Built by the loader: name (privatperson) or org name (organisation). */
readonly displayName: string;
readonly kontaktTyp: KontaktTyp;
readonly typLabelKey: string;
readonly kontaktStatus: KontaktStatus;
readonly statusLabelKey: string;
readonly primaerEmail: string | null;
readonly primaerTelefon: string | null;
/** Resolved display label of the responsible user (data) or null. */
readonly zustaendigerLabel: string | null;
/** Organisation merkmal (null for privatperson). */
readonly orgMerkmal: OrgMerkmal | null;
/** i18n key for {@link orgMerkmal} (null unless organisation + merkmal set). */
readonly orgMerkmalLabelKey: string | null;
readonly tagChips: readonly KontaktTagChip[];
readonly isArchived: boolean;
/** Internal detail route (e.g. `/acme/contacts/<id>`). */
readonly detailHref: string;
readonly createdAtIso: string;
/** Org-list only: number of attached contacts (filled when supplied). */
readonly kontaktAnzahl?: number;
/** Org-list only: ISO timestamp of the last activity (filled when supplied). */
readonly letzteActivityIso?: string;
}
/** Echo of the applied browser filter (mirrors crmService.ListKontakteFilter). */
export interface KontaktListAppliedFilter {
readonly kontaktTyp: KontaktTyp | null;
readonly kontaktStatus: KontaktStatus | null;
readonly zustaendigerUserId: string | null;
readonly search: string | null;
readonly tagIds: readonly string[] | null;
readonly tagMatch: "and" | "or";
readonly includeArchived: boolean;
}
export interface KontaktListPagination {
readonly page: number;
readonly pageCount: number;
readonly total: number;
readonly hasPrev: boolean;
readonly hasNext: boolean;
}
export interface KontaktListSort {
readonly field: KontaktSortField;
readonly dir: KontaktSortDir;
}
export interface KontaktListData {
readonly rows: readonly KontaktListRowData[];
readonly pagination: KontaktListPagination;
readonly sort: KontaktListSort;
readonly appliedFilter: KontaktListAppliedFilter;
readonly canWrite: boolean;
readonly canDelete: boolean;
readonly canReadAll: boolean;
}
export type KontaktListVM = VMState<KontaktListData>;
// --- Builder input ----------------------------------------------------------
/** Minimal contact source row (mirrors the crmService `KontaktRow` fields the
* list needs). Timestamps arrive as `Date` and are converted deterministically. */
export interface KontaktListSourceRow {
readonly id: string;
readonly kontaktTyp: KontaktTyp;
readonly kontaktStatus: KontaktStatus;
readonly vorname: string | null;
readonly nachname: string | null;
readonly orgName: string | null;
readonly orgMerkmal: OrgMerkmal | null;
readonly primaerEmail: string | null;
readonly primaerTelefon: string | null;
readonly zustaendigerUserId: string | null;
readonly createdAt: Date;
readonly archivedAt: Date | null;
}
export interface BuildKontaktListVMInput {
readonly rows: readonly KontaktListSourceRow[];
/** userId -> display label (crmService.resolveUserLabels). */
readonly userLabels: ReadonlyMap<string, string>;
/** kontaktId -> tag chips (crmService tag assignments). */
readonly tagsByKontakt: ReadonlyMap<string, readonly KontaktTagChip[]>;
readonly pagination: { readonly page: number; readonly pageCount: number; readonly total: number };
readonly sort: KontaktListSort;
readonly filter: KontaktListAppliedFilter;
readonly perms: { readonly canWrite: boolean; readonly canDelete: boolean; readonly canReadAll: boolean };
/** Tenant slug used to build internal detail hrefs. */
readonly tenantSlug: string;
/** Optional override for the detail href (e.g. an organisation route). */
readonly detailHrefFor?: (row: KontaktListSourceRow) => string;
/** Org-list only: kontaktId -> number of attached contacts. */
readonly orgKontaktAnzahl?: ReadonlyMap<string, number>;
/** Org-list only: kontaktId -> ISO timestamp of the last activity. */
readonly orgLastActivityIso?: ReadonlyMap<string, string>;
}
/** Build the contact display name from raw fields (pure). */
export function buildKontaktDisplayName(row: {
readonly kontaktTyp: KontaktTyp;
readonly vorname: string | null;
readonly nachname: string | null;
readonly orgName: string | null;
readonly primaerEmail: string | null;
}): string {
if (row.kontaktTyp === "organisation") {
return (row.orgName ?? "").trim() || (row.primaerEmail ?? "");
}
const name = `${row.vorname ?? ""} ${row.nachname ?? ""}`.trim();
return name || (row.primaerEmail ?? "");
}
export function buildKontaktListVM(input: BuildKontaktListVMInput): KontaktListVM {
// Empty contact set -> dedicated empty state (DoD 23). The route renders the
// "no contacts yet" prompt; the filter bar/CTA live in the route shell.
if (input.rows.length === 0) {
return empty<KontaktListData>();
}
const rows: KontaktListRowData[] = input.rows.map((row) => {
const isOrg = row.kontaktTyp === "organisation";
const detailHref = input.detailHrefFor ? input.detailHrefFor(row) : `/${input.tenantSlug}/contacts/${row.id}`;
const kontaktAnzahl = input.orgKontaktAnzahl?.get(row.id);
const letzteActivityIso = input.orgLastActivityIso?.get(row.id);
return {
id: row.id,
displayName: buildKontaktDisplayName(row),
kontaktTyp: row.kontaktTyp,
typLabelKey: kontaktTypLabelKey(row.kontaktTyp),
kontaktStatus: row.kontaktStatus,
statusLabelKey: kontaktStatusLabelKey(row.kontaktStatus),
primaerEmail: row.primaerEmail,
primaerTelefon: row.primaerTelefon,
zustaendigerLabel: row.zustaendigerUserId ? (input.userLabels.get(row.zustaendigerUserId) ?? null) : null,
orgMerkmal: row.orgMerkmal,
orgMerkmalLabelKey: isOrg && row.orgMerkmal ? orgMerkmalLabelKey(row.orgMerkmal) : null,
tagChips: input.tagsByKontakt.get(row.id) ?? [],
isArchived: row.archivedAt !== null,
detailHref,
createdAtIso: row.createdAt.toISOString(),
...(kontaktAnzahl !== undefined ? { kontaktAnzahl } : {}),
...(letzteActivityIso !== undefined ? { letzteActivityIso } : {}),
};
});
const { page, pageCount, total } = input.pagination;
return ready<KontaktListData>({
rows,
pagination: { page, pageCount, total, hasPrev: page > 1, hasNext: page < pageCount },
sort: input.sort,
appliedFilter: input.filter,
canWrite: input.perms.canWrite,
canDelete: input.perms.canDelete,
canReadAll: input.perms.canReadAll,
});
}
@@ -0,0 +1,49 @@
import { ready, type VMState } from "../index.js";
/**
* Tag admin view-model (R-P6, P6 CRM core — Variante A). Pure function: the
* loader builds it from `tagService.listTags` plus a per-tag usage count. Lets
* an admin manage tenant tags. No React/Prisma/server imports (DoD A.3).
*
* Stays `ready` even with zero rows so the "create tag" CTA (held in `data`)
* remains available.
*/
export interface TagAdminRowData {
readonly id: string;
readonly name: string;
readonly farbe: string;
/** Number of entities the tag is assigned to (0 when unused). */
readonly usageCount: number;
}
export interface TagAdminData {
readonly rows: readonly TagAdminRowData[];
readonly canWrite: boolean;
}
export type TagAdminVM = VMState<TagAdminData>;
/** Minimal tag source row (mirrors tagService.TagRow). */
export interface TagAdminSourceRow {
readonly id: string;
readonly name: string;
readonly farbe: string;
}
export interface BuildTagAdminVMInput {
readonly tags: readonly TagAdminSourceRow[];
/** tagId -> assignment count. */
readonly usageCounts: ReadonlyMap<string, number>;
readonly canWrite: boolean;
}
export function buildTagAdminVM(input: BuildTagAdminVMInput): TagAdminVM {
const rows: TagAdminRowData[] = input.tags.map((tag) => ({
id: tag.id,
name: tag.name,
farbe: tag.farbe,
usageCount: input.usageCounts.get(tag.id) ?? 0,
}));
return ready<TagAdminData>({ rows, canWrite: input.canWrite });
}