import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox"; import type { Prisma } from "@hivegrid/db/prisma-browser"; import { crmContactsIndex, filesIndex, projectsIndex, publishSearchDeleteEvent, publishSearchUpsertEvent, tasksIndex, usersIndex, type SearchIndexSchema, } from "@hivegrid/search"; type SearchProjectionTx = Prisma.TransactionClient & { searchIndexEntry: { upsert(args: { where: { tenantId_entityType_entityId: { tenantId: string; entityType: string; entityId: string } }; create: Prisma.SearchIndexEntryUncheckedCreateInput; update: Prisma.SearchIndexEntryUncheckedUpdateInput; }): Promise; updateMany(args: { where: { tenantId: string; entityType: string; entityId: string }; data: Prisma.SearchIndexEntryUncheckedUpdateInput }): Promise; }; }; type SearchEntityType = "contact" | "company" | "lead" | "project" | "file" | "task" | "user"; type SearchProjectionInput = { tx: SearchProjectionTx; schema: SearchIndexSchema; tenantId: string; entityType: SearchEntityType; entityId: string; title: string; subtitle?: string | null; bodyText?: string | null; routePath: string; permissionSubject: string; document: Record & { id: string; tenantId: string }; }; type KontaktSearchRow = { id: string; tenantId: string; kontaktTyp: "privatperson" | "organisation"; kontaktStatus: string; vorname: string | null; nachname: string | null; orgName: string | null; primaerEmail: string | null; zustaendigerUserId: string | null; createdByUserId: string | null; createdAt: Date | string; updatedAt: Date | string; }; type LeadSearchRow = { id: string; tenantId: string; createdByUserId: string | null; zustaendigerUserId: string | null; quelle: string; sourceOrigin: string | null; status: string; vorname: string | null; nachname: string | null; email: string | null; telefon: string | null; message: string | null; createdAt: Date | string; updatedAt: Date | string; }; type ProjectSearchRow = { id: string; tenantId: string; projektNummer: string; projektname: string; beschreibung: string | null; projekttyp: string | null; quelle: string | null; pipelineId: string; stageId: string; zustaendigePersonId: string | null; projektleiterId: string | null; archivedAt: Date | string | null; createdAt: Date | string; updatedAt: Date | string; deadline: Date | string | null; potenziellerAuftragswert: unknown; auftragsvolumen: unknown; }; type FileSearchRow = { id: string; tenantId: string; displayName: string; notes: string | null; tags: string[]; mimeType: string; createdByUserId: string | null; assignedToUserId: string | null; archivedAt: Date | string | null; createdAt: Date | string; updatedAt: Date | string; sizeBytes: number; }; type TaskSearchRow = { id: string; tenantId: string; createdByUserId: string; title: string; description: string | null; status: string; priority: string; deadline: Date | string | null; assignedToUserId: string | null; assignedToGroupId: string | null; linkedEntityType: string | null; linkedEntityId: string | null; archivedAt: Date | string | null; createdAt: Date | string; updatedAt: Date | string; }; type TenantUserSearchRow = { tenantId: string; type: number; status: number; user: { id: string; createdAt: Date | string; email: string; firstName: string; lastName: string; active: boolean; logs?: Array<{ createdAt: Date | string }>; }; }; const TENANT_USER_STATUS_ACTIVE = 2; export async function publishKontaktSearchUpsert(tx: Prisma.TransactionClient, row: KontaktSearchRow): Promise { const entityType = row.kontaktTyp === "organisation" ? "company" : "contact"; const title = entityType === "company" ? (row.orgName ?? row.primaerEmail ?? row.id) : [row.vorname, row.nachname].filter(Boolean).join(" ") || row.primaerEmail || row.id; await publishSearchProjectionUpsert({ tx: tx as SearchProjectionTx, schema: crmContactsIndex, tenantId: row.tenantId, entityType, entityId: row.id, title, subtitle: row.primaerEmail, bodyText: [title, row.primaerEmail].filter(Boolean).join(" "), routePath: `/app/${row.tenantId}/${entityType === "company" ? "contacts/companies" : "contacts"}/${row.id}`, permissionSubject: "crm.read_own", document: { id: row.id, tenantId: row.tenantId, entityType, firstName: row.vorname ?? "", lastName: row.nachname ?? "", email: row.primaerEmail ?? "", company: row.orgName ?? "", jobTitle: "", tags: [], status: row.kontaktStatus, ownerId: row.zustaendigerUserId ?? row.createdByUserId ?? "", createdAt: serializeDate(row.createdAt), updatedAt: serializeDate(row.updatedAt), lastInteractionAt: null, }, }); } export async function publishLeadSearchUpsert(tx: Prisma.TransactionClient, row: LeadSearchRow): Promise { const title = [row.vorname, row.nachname].filter(Boolean).join(" ") || row.email || row.telefon || row.id; await publishSearchProjectionUpsert({ tx: tx as SearchProjectionTx, schema: crmContactsIndex, tenantId: row.tenantId, entityType: "lead", entityId: row.id, title, subtitle: row.email ?? row.telefon ?? row.sourceOrigin ?? row.quelle, bodyText: [title, row.email, row.telefon, row.message].filter(Boolean).join(" "), routePath: `/app/${row.tenantId}/leads/${row.id}`, permissionSubject: "leads.read_own", document: { id: row.id, tenantId: row.tenantId, entityType: "lead", firstName: row.vorname ?? "", lastName: row.nachname ?? "", email: row.email ?? "", company: row.sourceOrigin ?? "", jobTitle: "", tags: [], status: row.status, ownerId: row.zustaendigerUserId ?? row.createdByUserId ?? "", createdAt: serializeDate(row.createdAt), updatedAt: serializeDate(row.updatedAt), lastInteractionAt: null, }, }); } export async function publishProjectSearchUpsert(tx: Prisma.TransactionClient, row: ProjectSearchRow): Promise { await publishSearchProjectionUpsert({ tx: tx as SearchProjectionTx, schema: projectsIndex, tenantId: row.tenantId, entityType: "project", entityId: row.id, title: row.projektname || row.projektNummer || row.id, subtitle: row.projektNummer, bodyText: [row.projektname, row.projektNummer, row.beschreibung, row.projekttyp, row.quelle].filter(Boolean).join(" "), routePath: `/app/${row.tenantId}/projects/${row.id}`, permissionSubject: "projects.read_own", document: { id: row.id, tenantId: row.tenantId, projectNumber: row.projektNummer, name: row.projektname, description: row.beschreibung ?? "", type: row.projekttyp ?? "", source: row.quelle ?? "", pipelineId: row.pipelineId, stageId: row.stageId, ownerId: row.zustaendigePersonId ?? "", projectLeadId: row.projektleiterId ?? "", archived: row.archivedAt !== null, createdAt: serializeDate(row.createdAt), updatedAt: serializeDate(row.updatedAt), deadline: serializeDate(row.deadline), potentialValue: serializeDecimal(row.potenziellerAuftragswert), orderVolume: serializeDecimal(row.auftragsvolumen), }, }); } export async function publishFileSearchUpsert(tx: Prisma.TransactionClient, row: FileSearchRow): Promise { await publishSearchProjectionUpsert({ tx: tx as SearchProjectionTx, schema: filesIndex, tenantId: row.tenantId, entityType: "file", entityId: row.id, title: row.displayName || row.id, subtitle: row.mimeType, bodyText: [row.displayName, row.notes, ...(row.tags ?? [])].filter(Boolean).join(" "), routePath: `/app/${row.tenantId}/files/${row.id}`, permissionSubject: "files.read_own", document: { id: row.id, tenantId: row.tenantId, displayName: row.displayName, notes: row.notes ?? "", tags: row.tags ?? [], mimeType: row.mimeType, createdByUserId: row.createdByUserId ?? "", assignedToUserId: row.assignedToUserId ?? "", archived: row.archivedAt !== null, createdAt: serializeDate(row.createdAt), updatedAt: serializeDate(row.updatedAt), sizeBytes: row.sizeBytes, }, }); } export async function publishTaskSearchUpsert(tx: Prisma.TransactionClient, row: TaskSearchRow): Promise { await publishSearchProjectionUpsert({ tx: tx as SearchProjectionTx, schema: tasksIndex, tenantId: row.tenantId, entityType: "task", entityId: row.id, title: row.title || row.id, subtitle: row.status, bodyText: [row.title, row.description].filter(Boolean).join(" "), routePath: `/app/${row.tenantId}/tasks/${row.id}`, permissionSubject: "tasks.read_own", document: { id: row.id, tenantId: row.tenantId, title: row.title, description: row.description ?? "", status: row.status, priority: row.priority, createdByUserId: row.createdByUserId, assignedToUserId: row.assignedToUserId ?? "", assignedToGroupId: row.assignedToGroupId ?? "", linkedEntityType: row.linkedEntityType ?? "", linkedEntityId: row.linkedEntityId ?? "", archived: row.archivedAt !== null, createdAt: serializeDate(row.createdAt), updatedAt: serializeDate(row.updatedAt), deadline: serializeDate(row.deadline), }, }); } export async function publishTenantUserSearchUpsert(tx: Prisma.TransactionClient, row: TenantUserSearchRow): Promise { const title = [row.user.firstName, row.user.lastName].filter(Boolean).join(" ") || row.user.email || row.user.id; await publishSearchProjectionUpsert({ tx: tx as SearchProjectionTx, schema: usersIndex, tenantId: row.tenantId, entityType: "user", entityId: row.user.id, title, subtitle: row.user.email, bodyText: [title, row.user.email].filter(Boolean).join(" "), routePath: `/app/${row.tenantId}/settings/team`, permissionSubject: "app.settings.members.view", document: { id: row.user.id, tenantId: row.tenantId, firstName: row.user.firstName, lastName: row.user.lastName, email: row.user.email, type: row.type, admin: row.type === 0 || row.type === 1, active: row.user.active && row.status === TENANT_USER_STATUS_ACTIVE, createdAt: serializeDate(row.user.createdAt), lastLoginAt: serializeDate(row.user.logs?.[0]?.createdAt ?? null), }, }); } export async function publishUserSearchDelete(tx: Prisma.TransactionClient, input: { tenantId: string; userId: string }): Promise { await publishSearchProjectionDelete(tx, { schema: usersIndex, tenantId: input.tenantId, entityType: "user", entityId: input.userId, }); } export async function publishSearchProjectionDelete( tx: Prisma.TransactionClient, input: { schema: SearchIndexSchema; tenantId: string; entityType: SearchEntityType; entityId: string }, ): Promise { await (tx as SearchProjectionTx).searchIndexEntry.updateMany({ where: { tenantId: input.tenantId, entityType: input.entityType, entityId: input.entityId }, data: { isArchived: true, lastIndexedAt: new Date() }, }); await publishSearchDeleteEvent({ publish: (event) => publishOutboxEvent(tx as unknown as OutboxPublisherTransaction, { tenantId: event.tenantId, type: event.type, payload: event.payload as Prisma.InputJsonValue, }), schema: input.schema, tenantId: input.tenantId, entityName: input.entityType, documentId: input.entityId, }); } async function publishSearchProjectionUpsert(input: SearchProjectionInput): Promise { const now = new Date(); await input.tx.searchIndexEntry.upsert({ where: { tenantId_entityType_entityId: { tenantId: input.tenantId, entityType: input.entityType, entityId: input.entityId, }, }, create: { tenantId: input.tenantId, entityType: input.entityType, entityId: input.entityId, title: input.title, subtitle: input.subtitle ?? null, bodyText: input.bodyText ?? input.title, routePath: input.routePath, sourceIndex: input.schema.name, permissionSubject: input.permissionSubject, lastIndexedAt: now, }, update: { title: input.title, subtitle: input.subtitle ?? null, bodyText: input.bodyText ?? input.title, routePath: input.routePath, sourceIndex: input.schema.name, permissionSubject: input.permissionSubject, lastIndexedAt: now, isArchived: false, }, }); await publishSearchUpsertEvent({ publish: (event) => publishOutboxEvent(input.tx as unknown as OutboxPublisherTransaction, { tenantId: event.tenantId, type: event.type, payload: event.payload as Prisma.InputJsonValue, }), schema: input.schema, tenantId: input.tenantId, entityName: input.entityType, document: input.document, }); } function serializeDate(value: Date | string | null | undefined): string | null { if (value === null || value === undefined) return null; return value instanceof Date ? value.toISOString() : value; } function serializeDecimal(value: unknown): number | null { if (value === null || value === undefined) return null; if (typeof value === "number") return Number.isFinite(value) ? value : null; if (typeof value === "string") { const parsed = Number(value); return Number.isFinite(parsed) ? parsed : null; } if (typeof value === "object" && "toString" in value && typeof value.toString === "function") { const parsed = Number(value.toString()); return Number.isFinite(parsed) ? parsed : null; } return null; }