Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/services/search/globalSearch.server.ts
T

1218 lines
46 KiB
TypeScript

import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
import { featureKeys, type FeatureKey } from "@hivegrid/entitlements";
import {
createSearchClient,
crmContactsIndex,
filesIndex,
hrDirectoryIndex,
projectsIndex,
searchWithFallback,
tasksIndex,
usersIndex,
type SearchDocument,
type SearchHit,
} from "@hivegrid/search";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
import { getTranslations } from "~/locale/i18next.server";
import { fileReadScopeWhereWithTx } from "~/utils/integrations/fileVisibility.server";
import { ownerScopeWhere as crmOwnerScopeWhere } from "~/utils/integrations/crm/crmService.server";
import { projectReadScopeWhere, type ProjectVisibilityContext } from "~/utils/integrations/projects/projectService.server";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo } from "~/utils/session.server";
export const SEARCH_MODULE_KEY = featureKeys.search;
export const SEARCH_USE_PERMISSION = "search.use";
export type GlobalSearchEntityType = "contact" | "company" | "lead" | "project" | "file" | "task" | "employee" | "user";
export const GLOBAL_SEARCH_ENTITY_TYPES = [
"contact",
"company",
"lead",
"project",
"file",
"task",
"employee",
"user",
] as const satisfies readonly GlobalSearchEntityType[];
export const GLOBAL_SEARCH_QUERY_MIN_LENGTH = 2;
export const GLOBAL_SEARCH_QUERY_MAX_LENGTH = 200;
export const GLOBAL_SEARCH_RESULT_MAX = 50;
export type GlobalSearchResult = {
id: string;
entityType: GlobalSearchEntityType;
title: string;
subtitle: string;
href: string;
permissionSubject: string;
updatedAt: string | null;
};
export type RecentSearchItem = {
id: string;
queryText: string;
entityTypes: GlobalSearchEntityType[];
resultCount: number;
createdAt: string;
};
export type GlobalSearchResponse = {
query: string;
requestedEntityTypes: GlobalSearchEntityType[];
requestId: string | null;
requestKey: string;
results: GlobalSearchResult[];
recentSearches: RecentSearchItem[];
hiddenEntityTypes: GlobalSearchEntityType[];
latencyHint: string;
};
export type SearchContext = ProjectVisibilityContext & {
tenantId: string;
tenantSlug: string;
};
type SearchInput = {
request: Request;
params: Record<string, string | undefined>;
query: string;
limit?: number;
entityTypes?: readonly string[];
requestId?: unknown;
};
export type RecordCommittedSearchInput = {
ctx: SearchContext;
query: unknown;
entityTypes: unknown;
resultCount: unknown;
selectedEntityType: unknown;
selectedEntityId: unknown;
};
export type RecordCommittedSearchResult = {
recorded: boolean;
requestKey: string;
};
export type GlobalSearchInputErrorCode =
| "query_too_short"
| "query_too_long"
| "invalid_entity_types"
| "invalid_result_count"
| "invalid_request_id"
| "invalid_selection";
export class GlobalSearchInputError extends Error {
readonly code: GlobalSearchInputErrorCode;
constructor(code: GlobalSearchInputErrorCode) {
super(code);
this.name = "GlobalSearchInputError";
this.code = code;
}
}
export class GlobalSearchUnavailableError extends Error {
override readonly cause: unknown;
constructor(cause: unknown) {
super("search_unavailable");
this.name = "GlobalSearchUnavailableError";
this.cause = cause;
}
}
type EntityAccess = {
allowed: boolean;
permissionSubject: string;
all?: boolean;
own?: boolean;
};
const DEFAULT_LIMIT = 20;
const RECENT_LIMIT = 6;
const RECENT_HISTORY_LIMIT = 50;
const RECENT_RETENTION_DAYS = 90;
const PROJECT_SCOPE_PERMISSIONS = ["projects.read_all", "projects.read_own", "projects.read_own_member", "projects.read_own_pl"] as const;
const entityTypeOrder = new Map<GlobalSearchEntityType, number>(GLOBAL_SEARCH_ENTITY_TYPES.map((entityType, index) => [entityType, index]));
const entityModuleKeys = {
contact: featureKeys.crmBasic,
company: featureKeys.crmBasic,
lead: featureKeys.leads,
project: featureKeys.projects,
file: featureKeys.files,
task: featureKeys.tasks,
employee: featureKeys.hr,
user: featureKeys.users,
} as const satisfies Record<GlobalSearchEntityType, FeatureKey>;
export async function loadSearchContext({ request, params }: { request: Request; params: Record<string, string | undefined> }): Promise<SearchContext> {
await requireAuth({ request, params });
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
if (!tenantId || !userInfo.userId) {
throw new CatalogError(foundationErrors.notFound);
}
const [hasModule, permissions] = await Promise.all([
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: SEARCH_MODULE_KEY }),
getPermissionsByUser(userInfo.userId, tenantId),
]);
if (!hasModule) {
throw new CatalogError(foundationErrors.notFound, { module: SEARCH_MODULE_KEY });
}
requirePermission({ tenantId, userId: userInfo.userId, permissions }, SEARCH_USE_PERMISSION);
return {
tenantId,
tenantSlug: params.tenant ?? tenantId,
userId: userInfo.userId,
permissions,
};
}
async function hydrateSearchVisibilityContext(ctx: SearchContext, searchableTypes: readonly GlobalSearchEntityType[]): Promise<SearchContext> {
const searchesProject = searchableTypes.includes("project");
const searchesProjectLinkedFiles =
searchableTypes.includes("file") &&
ctx.permissions.includes("files.read_own") &&
!ctx.permissions.includes("files.read_all") &&
PROJECT_SCOPE_PERMISSIONS.some((permission) => ctx.permissions.includes(permission));
const needsProjectScope = searchesProject || searchesProjectLinkedFiles;
const needsTaskGroups = searchableTypes.includes("task") && ctx.permissions.includes("tasks.read_own") && !ctx.permissions.includes("tasks.read_all");
if (!needsProjectScope && !needsTaskGroups) return ctx;
return withTenantRLS(ctx.tenantId, async (database) => {
const [roleAssignments, groupMemberships] = await Promise.all([
needsProjectScope ? database.userRole.findMany({ where: { tenantId: ctx.tenantId, userId: ctx.userId }, select: { roleId: true } }) : Promise.resolve([]),
database.groupUser.findMany({ where: { userId: ctx.userId, group: { tenantId: ctx.tenantId } }, select: { groupId: true } }),
]);
return {
...ctx,
roleIds: needsProjectScope ? roleAssignments.map(({ roleId }) => roleId) : [],
groupIds: groupMemberships.map(({ groupId }) => groupId),
};
});
}
export async function runGlobalSearch(input: SearchInput): Promise<GlobalSearchResponse> {
const [baseCtx, { t }] = await Promise.all([
loadSearchContext({ request: input.request, params: input.params }),
getTranslations(input.request),
]);
const latencyHint = t("search.latencyHint");
const query = parseGlobalSearchQuery(input.query, { allowEmpty: true });
const limit = clampLimit(input.limit);
const requestId = parseGlobalSearchRequestId(input.requestId);
const requestedEntityTypes = parseGlobalSearchEntityTypes(input.entityTypes ?? []);
let enabledEntityTypes: ReadonlySet<GlobalSearchEntityType>;
let recentSearches: RecentSearchItem[];
try {
[enabledEntityTypes, recentSearches] = await Promise.all([loadEnabledEntityTypes(baseCtx), loadRecentSearches(baseCtx)]);
} catch (error) {
throw new GlobalSearchUnavailableError(error);
}
const access = buildAccessMap(baseCtx.permissions, enabledEntityTypes);
const requestedTypes = requestedEntityTypes.length ? new Set(requestedEntityTypes) : null;
const searchableTypes = (Object.keys(access) as GlobalSearchEntityType[]).filter(
(type) => access[type].allowed && (!requestedTypes || requestedTypes.has(type))
);
const hiddenEntityTypes = (Object.keys(access) as GlobalSearchEntityType[]).filter((type) => !access[type].allowed);
const requestKey = buildGlobalSearchRequestKey(query, requestedEntityTypes, limit);
if (!query) {
return { query, requestedEntityTypes, requestId, requestKey, results: [], recentSearches, hiddenEntityTypes, latencyHint };
}
let ctx: SearchContext;
let sqlResults: GlobalSearchResult[];
let validatedMeiliResults: GlobalSearchResult[];
try {
ctx = await hydrateSearchVisibilityContext(baseCtx, searchableTypes);
const [loadedSqlResults, meiliResults] = await Promise.all([
withTenantRLS(ctx.tenantId, (database) => searchSqlFallback({ ctx, access, query, limit, searchableTypes, database })),
searchMeili({ ctx, access, query, limit, searchableTypes }),
]);
sqlResults = loadedSqlResults;
validatedMeiliResults =
meiliResults.length === 0
? []
: await withTenantRLS(ctx.tenantId, (database) => revalidateMeiliResults({ ctx, access, results: meiliResults, database }));
} catch (error) {
// The SQL source is also the current permission authority, so failures must
// fail closed even when Meilisearch itself is reachable.
throw new GlobalSearchUnavailableError(error);
}
const results = mergeResults([...validatedMeiliResults, ...sqlResults], limit);
return { query, requestedEntityTypes, requestId, requestKey, results, recentSearches, hiddenEntityTypes, latencyHint };
}
async function loadEnabledEntityTypes(
ctx: SearchContext,
entityTypes: readonly GlobalSearchEntityType[] = GLOBAL_SEARCH_ENTITY_TYPES
): Promise<ReadonlySet<GlobalSearchEntityType>> {
const moduleKeys = [...new Set(entityTypes.map((entityType) => entityModuleKeys[entityType]))];
const decisions = await Promise.all(
moduleKeys.map(async (moduleKey) => [moduleKey, await tenantHasModule({ tenantId: ctx.tenantId, userId: ctx.userId, moduleKey })] as const)
);
const enabledModuleKeys = new Set(decisions.filter(([, enabled]) => enabled).map(([moduleKey]) => moduleKey));
return new Set(entityTypes.filter((entityType) => enabledModuleKeys.has(entityModuleKeys[entityType])));
}
function buildAccessMap(permissions: readonly string[], enabledEntityTypes: ReadonlySet<GlobalSearchEntityType>): Record<GlobalSearchEntityType, EntityAccess> {
const granted = new Set(permissions);
return {
contact: {
allowed: enabledEntityTypes.has("contact") && (granted.has("crm.read_all") || granted.has("crm.read_own")),
all: granted.has("crm.read_all"),
own: granted.has("crm.read_own"),
permissionSubject: granted.has("crm.read_all") ? "crm.read_all" : "crm.read_own",
},
company: {
allowed: enabledEntityTypes.has("company") && (granted.has("crm.read_all") || granted.has("crm.read_own")),
all: granted.has("crm.read_all"),
own: granted.has("crm.read_own"),
permissionSubject: granted.has("crm.read_all") ? "crm.read_all" : "crm.read_own",
},
lead: {
allowed: enabledEntityTypes.has("lead") && (granted.has("leads.read_all") || granted.has("leads.read_own")),
all: granted.has("leads.read_all"),
own: granted.has("leads.read_own"),
permissionSubject: granted.has("leads.read_all") ? "leads.read_all" : "leads.read_own",
},
project: {
allowed:
enabledEntityTypes.has("project") &&
(granted.has("projects.read_all") ||
granted.has("projects.read_own") ||
granted.has("projects.read_own_member") ||
granted.has("projects.read_own_pl")),
all: granted.has("projects.read_all"),
own: granted.has("projects.read_own") || granted.has("projects.read_own_member") || granted.has("projects.read_own_pl"),
permissionSubject: granted.has("projects.read_all")
? "projects.read_all"
: granted.has("projects.read_own")
? "projects.read_own"
: granted.has("projects.read_own_member")
? "projects.read_own_member"
: "projects.read_own_pl",
},
file: {
allowed: enabledEntityTypes.has("file") && (granted.has("files.read_all") || granted.has("files.read_own")),
all: granted.has("files.read_all"),
own: granted.has("files.read_own"),
permissionSubject: granted.has("files.read_all") ? "files.read_all" : "files.read_own",
},
task: {
allowed: enabledEntityTypes.has("task") && (granted.has("tasks.read_all") || granted.has("tasks.read_own")),
all: granted.has("tasks.read_all"),
own: granted.has("tasks.read_own"),
permissionSubject: granted.has("tasks.read_all") ? "tasks.read_all" : "tasks.read_own",
},
employee: {
allowed: enabledEntityTypes.has("employee") && (granted.has("hr.read_all") || granted.has("hr.read_own")),
all: granted.has("hr.read_all"),
own: granted.has("hr.read_own"),
permissionSubject: granted.has("hr.read_all") ? "hr.read_all" : "hr.read_own",
},
user: {
allowed: enabledEntityTypes.has("user") && granted.has("app.settings.members.view"),
all: granted.has("app.settings.members.view"),
permissionSubject: "app.settings.members.view",
},
};
}
async function searchSqlFallback(input: {
ctx: SearchContext;
access: Record<GlobalSearchEntityType, EntityAccess>;
query: string;
limit: number;
searchableTypes: GlobalSearchEntityType[];
database: TenantRlsClient;
}): Promise<GlobalSearchResult[]> {
const jobs = input.searchableTypes.map((entityType) => {
switch (entityType) {
case "contact":
return searchContacts(input, "contact");
case "company":
return searchContacts(input, "company");
case "lead":
return searchLeads(input);
case "project":
return searchProjects(input);
case "file":
return searchFiles(input);
case "task":
return searchTasks(input);
case "employee":
return searchEmployees(input);
case "user":
return searchUsers(input);
}
});
const chunks = await Promise.all(jobs);
return chunks.flat();
}
async function searchContacts(
{ ctx, access, query, limit, database }: Pick<Parameters<typeof searchSqlFallback>[0], "ctx" | "access" | "query" | "limit" | "database">,
entityType: "contact" | "company"
) {
const entityAccess = access[entityType];
const rows = await database.kontakt.findMany({
where: {
tenantId: ctx.tenantId,
archivedAt: null,
...(entityType === "company" ? { kontaktTyp: "organisation" as const } : { kontaktTyp: "privatperson" as const }),
AND: [
crmOwnerScopeWhere(ctx),
{
OR: [
{ vorname: { contains: query, mode: "insensitive" } },
{ nachname: { contains: query, mode: "insensitive" } },
{ orgName: { contains: query, mode: "insensitive" } },
{ primaerEmail: { contains: query, mode: "insensitive" } },
{ primaerTelefon: { contains: query, mode: "insensitive" } },
],
},
],
},
orderBy: { updatedAt: "desc" },
take: limit,
select: { id: true, vorname: true, nachname: true, orgName: true, primaerEmail: true, updatedAt: true },
});
return rows.map((row) => ({
id: row.id,
entityType,
title:
entityType === "company"
? (row.orgName ?? row.primaerEmail ?? row.id)
: [row.vorname, row.nachname].filter(Boolean).join(" ") || row.primaerEmail || row.id,
subtitle: row.primaerEmail ?? "",
href: appPath({ tenantSlug: ctx.tenantSlug, path: entityType === "company" ? `contacts/companies/${row.id}` : `contacts/${row.id}`, mode: "host-aware" }),
permissionSubject: entityAccess.permissionSubject,
updatedAt: serializeDate(row.updatedAt),
}));
}
async function searchLeads({
ctx,
access,
query,
limit,
database,
}: Pick<Parameters<typeof searchSqlFallback>[0], "ctx" | "access" | "query" | "limit" | "database">) {
const entityAccess = access.lead;
const rows = await database.inboxLead.findMany({
where: {
tenantId: ctx.tenantId,
archivedAt: null,
AND: [
entityAccess.all ? {} : { zustaendigerUserId: ctx.userId },
{
OR: [
{ vorname: { contains: query, mode: "insensitive" } },
{ nachname: { contains: query, mode: "insensitive" } },
{ email: { contains: query, mode: "insensitive" } },
{ telefon: { contains: query, mode: "insensitive" } },
{ message: { contains: query, mode: "insensitive" } },
],
},
],
},
orderBy: { updatedAt: "desc" },
take: limit,
select: { id: true, vorname: true, nachname: true, email: true, message: true, updatedAt: true },
});
return rows.map((row) => ({
id: row.id,
entityType: "lead" as const,
title: [row.vorname, row.nachname].filter(Boolean).join(" ") || row.email || row.id,
subtitle: row.email ?? row.message ?? "",
href: appPath({ tenantSlug: ctx.tenantSlug, path: `leads/${row.id}`, mode: "host-aware" }),
permissionSubject: entityAccess.permissionSubject,
updatedAt: serializeDate(row.updatedAt),
}));
}
async function searchProjects({
ctx,
access,
query,
limit,
database,
}: Pick<Parameters<typeof searchSqlFallback>[0], "ctx" | "access" | "query" | "limit" | "database">) {
const entityAccess = access.project;
const rows = await database.projekt.findMany({
where: {
tenantId: ctx.tenantId,
archivedAt: null,
AND: [
projectReadScopeWhere(ctx.tenantId, ctx),
{
OR: [
{ projektNummer: { contains: query, mode: "insensitive" } },
{ projektname: { contains: query, mode: "insensitive" } },
{ beschreibung: { contains: query, mode: "insensitive" } },
{ projekttyp: { contains: query, mode: "insensitive" } },
{ quelle: { contains: query, mode: "insensitive" } },
],
},
],
},
orderBy: { updatedAt: "desc" },
take: limit,
select: { id: true, projektNummer: true, projektname: true, beschreibung: true, updatedAt: true },
});
return rows.map((row) => ({
id: row.id,
entityType: "project" as const,
title: row.projektname,
subtitle: row.projektNummer || row.beschreibung || "",
href: appPath({ tenantSlug: ctx.tenantSlug, path: `projects/${row.id}`, mode: "host-aware" }),
permissionSubject: entityAccess.permissionSubject,
updatedAt: serializeDate(row.updatedAt),
}));
}
async function searchFiles({
ctx,
access,
query,
limit,
database,
}: Pick<Parameters<typeof searchSqlFallback>[0], "ctx" | "access" | "query" | "limit" | "database">) {
const entityAccess = access.file;
const visibility = await fileReadScopeWhereWithTx(database, ctx.tenantId, ctx);
const rows = await database.file.findMany({
where: {
tenantId: ctx.tenantId,
archivedAt: null,
AND: [
visibility,
{
OR: [{ displayName: { contains: query, mode: "insensitive" } }, { notes: { contains: query, mode: "insensitive" } }, { tags: { has: query } }],
},
],
},
orderBy: { updatedAt: "desc" },
take: limit,
select: { id: true, displayName: true, mimeType: true, updatedAt: true },
});
return rows.map((row) => ({
id: row.id,
entityType: "file" as const,
title: row.displayName,
subtitle: row.mimeType,
href: appPath({ tenantSlug: ctx.tenantSlug, path: `files/${row.id}`, mode: "host-aware" }),
permissionSubject: entityAccess.permissionSubject,
updatedAt: serializeDate(row.updatedAt),
}));
}
type TaskVisibilityCondition =
| { assignedToUserId: string }
| { createdByUserId: string }
| { watchers: { some: { tenantId: string; userId: string } } }
| { assignedToGroupId: { in: string[] } };
function buildTaskVisibilityConditions(ctx: SearchContext): TaskVisibilityCondition[] {
const groupIds = [...new Set(ctx.groupIds ?? [])];
return [
{ assignedToUserId: ctx.userId },
{ createdByUserId: ctx.userId },
{ watchers: { some: { tenantId: ctx.tenantId, userId: ctx.userId } } },
...(groupIds.length > 0 ? [{ assignedToGroupId: { in: groupIds } } as const] : []),
];
}
async function searchTasks({
ctx,
access,
query,
limit,
database,
}: Pick<Parameters<typeof searchSqlFallback>[0], "ctx" | "access" | "query" | "limit" | "database">) {
const entityAccess = access.task;
const visibility = entityAccess.all ? [] : buildTaskVisibilityConditions(ctx);
const rows = await database.task.findMany({
where: {
tenantId: ctx.tenantId,
archivedAt: null,
AND: [
entityAccess.all ? {} : { OR: visibility },
{ OR: [{ title: { contains: query, mode: "insensitive" } }, { description: { contains: query, mode: "insensitive" } }] },
],
},
orderBy: { updatedAt: "desc" },
take: limit,
select: { id: true, title: true, status: true, updatedAt: true },
});
return rows.map((row) => ({
id: row.id,
entityType: "task" as const,
title: row.title,
subtitle: row.status,
href: appPath({ tenantSlug: ctx.tenantSlug, path: `tasks/${row.id}`, mode: "host-aware" }),
permissionSubject: entityAccess.permissionSubject,
updatedAt: serializeDate(row.updatedAt),
}));
}
async function searchUsers({
ctx,
access,
query,
limit,
database,
}: Pick<Parameters<typeof searchSqlFallback>[0], "ctx" | "access" | "query" | "limit" | "database">) {
const entityAccess = access.user;
const rows = await database.tenantUser.findMany({
where: {
tenantId: ctx.tenantId,
status: TenantUserStatus.ACTIVE,
user: {
active: true,
OR: [
{ firstName: { contains: query, mode: "insensitive" } },
{ lastName: { contains: query, mode: "insensitive" } },
{ email: { contains: query, mode: "insensitive" } },
],
},
},
orderBy: { user: { email: "asc" } },
take: limit,
select: { id: true, userId: true, user: { select: { firstName: true, lastName: true, email: true, updatedAt: true } } },
});
return rows.map((row) => ({
id: row.userId,
entityType: "user" as const,
title: [row.user.firstName, row.user.lastName].filter(Boolean).join(" ") || row.user.email,
subtitle: row.user.email,
href: appPath({ tenantSlug: ctx.tenantSlug, path: "settings/team", mode: "host-aware" }),
permissionSubject: entityAccess.permissionSubject,
updatedAt: serializeDate(row.user.updatedAt),
}));
}
async function searchEmployees({
ctx,
access,
query,
limit,
database,
}: Pick<Parameters<typeof searchSqlFallback>[0], "ctx" | "access" | "query" | "limit" | "database">) {
const entityAccess = access.employee;
const matchingMembers = await database.tenantUser.findMany({
where: {
tenantId: ctx.tenantId,
status: TenantUserStatus.ACTIVE,
user: {
active: true,
OR: [
{ firstName: { contains: query, mode: "insensitive" } },
{ lastName: { contains: query, mode: "insensitive" } },
{ email: { contains: query, mode: "insensitive" } },
],
},
},
take: limit,
select: { userId: true },
});
const matchingUserIds = matchingMembers.map(({ userId }) => userId);
const profiles = await database.hrEmployeeProfile.findMany({
where: {
tenantId: ctx.tenantId,
AND: [
entityAccess.all ? {} : { OR: [{ userId: ctx.userId }, { managerUserId: ctx.userId }] },
{
OR: [
{ userId: { in: matchingUserIds } },
{ position: { contains: query, mode: "insensitive" } },
{ team: { contains: query, mode: "insensitive" } },
],
},
],
},
orderBy: { updatedAt: "desc" },
take: limit,
select: { userId: true, position: true, team: true, updatedAt: true },
});
if (profiles.length === 0) return [];
const members = await database.tenantUser.findMany({
where: {
tenantId: ctx.tenantId,
userId: { in: profiles.map(({ userId }) => userId) },
status: TenantUserStatus.ACTIVE,
user: { active: true },
},
select: { userId: true, user: { select: { firstName: true, lastName: true, email: true } } },
});
const memberByUserId = new Map(members.map((member) => [member.userId, member.user]));
return profiles.flatMap((profile) => {
const user = memberByUserId.get(profile.userId);
if (!user) return [];
return [
{
id: profile.userId,
entityType: "employee" as const,
title: [user.firstName, user.lastName].filter(Boolean).join(" ") || user.email,
subtitle: [profile.position, profile.team, user.email].filter(Boolean).join(" · "),
href: appPath({ tenantSlug: ctx.tenantSlug, path: `hr/directory/${profile.userId}`, mode: "host-aware" }),
permissionSubject: entityAccess.permissionSubject,
updatedAt: serializeDate(profile.updatedAt),
},
];
});
}
async function revalidateMeiliResults(input: {
ctx: SearchContext;
access: Record<GlobalSearchEntityType, EntityAccess>;
results: readonly GlobalSearchResult[];
database: TenantRlsClient;
}): Promise<GlobalSearchResult[]> {
const visibleKeys = new Set<string>();
for (const entityType of GLOBAL_SEARCH_ENTITY_TYPES) {
const ids = [...new Set(input.results.filter((result) => result.entityType === entityType).map((result) => result.id))];
if (ids.length === 0) continue;
const visibleIds = await loadVisibleEntityIds({ ...input, entityType, ids });
visibleIds.forEach((id) => visibleKeys.add(`${entityType}:${id}`));
}
return input.results.filter((result) => visibleKeys.has(`${result.entityType}:${result.id}`));
}
async function loadVisibleEntityIds(input: {
ctx: SearchContext;
access: Record<GlobalSearchEntityType, EntityAccess>;
entityType: GlobalSearchEntityType;
ids: readonly string[];
database: TenantRlsClient;
}): Promise<Set<string>> {
const entityAccess = input.access[input.entityType];
if (!entityAccess.allowed || input.ids.length === 0) return new Set();
const ids = [...new Set(input.ids)];
switch (input.entityType) {
case "contact":
case "company": {
const rows = await input.database.kontakt.findMany({
where: {
tenantId: input.ctx.tenantId,
id: { in: ids },
archivedAt: null,
kontaktTyp: input.entityType === "company" ? "organisation" : "privatperson",
...crmOwnerScopeWhere(input.ctx),
},
select: { id: true },
});
return new Set(rows.map((row) => row.id));
}
case "lead": {
const rows = await input.database.inboxLead.findMany({
where: {
tenantId: input.ctx.tenantId,
id: { in: ids },
archivedAt: null,
...(entityAccess.all ? {} : { zustaendigerUserId: input.ctx.userId }),
},
select: { id: true },
});
return new Set(rows.map((row) => row.id));
}
case "project": {
const rows = await input.database.projekt.findMany({
where: {
tenantId: input.ctx.tenantId,
id: { in: ids },
archivedAt: null,
...projectReadScopeWhere(input.ctx.tenantId, input.ctx),
},
select: { id: true },
});
return new Set(rows.map((row) => row.id));
}
case "file": {
const visibility = await fileReadScopeWhereWithTx(input.database, input.ctx.tenantId, input.ctx, ids);
const rows = await input.database.file.findMany({
where: {
tenantId: input.ctx.tenantId,
id: { in: ids },
archivedAt: null,
...visibility,
},
select: { id: true },
});
return new Set(rows.map((row) => row.id));
}
case "task": {
const visibility = entityAccess.all ? [] : buildTaskVisibilityConditions(input.ctx);
const rows = await input.database.task.findMany({
where: {
tenantId: input.ctx.tenantId,
id: { in: ids },
archivedAt: null,
...(entityAccess.all ? {} : { OR: visibility }),
},
select: { id: true },
});
return new Set(rows.map((row) => row.id));
}
case "employee": {
const rows = await input.database.hrEmployeeProfile.findMany({
where: {
tenantId: input.ctx.tenantId,
userId: { in: ids },
...(entityAccess.all ? {} : { OR: [{ userId: input.ctx.userId }, { managerUserId: input.ctx.userId }] }),
},
select: { userId: true },
});
return new Set(rows.map((row) => row.userId));
}
case "user": {
const rows = await input.database.tenantUser.findMany({
where: { tenantId: input.ctx.tenantId, userId: { in: ids }, status: TenantUserStatus.ACTIVE, user: { active: true } },
select: { userId: true },
});
return new Set(rows.map((row) => row.userId));
}
}
}
async function searchMeili(input: {
ctx: SearchContext;
access: Record<GlobalSearchEntityType, EntityAccess>;
query: string;
limit: number;
searchableTypes: GlobalSearchEntityType[];
}): Promise<GlobalSearchResult[]> {
if (!process.env.MEILI_URL || process.env.SEARCH_BACKEND === "sql") return [];
const client = createSearchClient({ url: process.env.MEILI_URL, apiKey: process.env.MEILI_API_KEY });
const jobs: Promise<GlobalSearchResult[]>[] = [];
for (const entityType of ["contact", "company", "lead"] as const) {
if (input.searchableTypes.includes(entityType)) {
jobs.push(
searchWithFallback({
client,
schema: crmContactsIndex,
tenantId: input.ctx.tenantId,
query: input.query,
options: {
limit: input.limit,
extraFilters: [`entityType = "${entityType}"`, ...ownerMeiliFilters(input.access[entityType], input.ctx.userId, ["ownerId"])],
},
fallback: async () => ({ hits: [], estimatedTotalHits: 0, processingTimeMs: 0 }),
}).then((result) => result.hits.map((hit) => meiliCrmHit(input, entityType, hit)))
);
}
}
if (input.searchableTypes.includes("project")) {
jobs.push(
searchWithFallback({
client,
schema: projectsIndex,
tenantId: input.ctx.tenantId,
query: input.query,
options: { limit: input.limit, extraFilters: projectMeiliFilters(input.ctx, input.access.project) },
fallback: async () => ({ hits: [], estimatedTotalHits: 0, processingTimeMs: 0 }),
}).then((result) => result.hits.map((hit) => meiliProjectHit(input, hit)))
);
}
if (input.searchableTypes.includes("file")) {
jobs.push(
searchWithFallback({
client,
schema: filesIndex,
tenantId: input.ctx.tenantId,
query: input.query,
options: { limit: input.limit, extraFilters: ownerMeiliFilters(input.access.file, input.ctx.userId, ["createdByUserId", "assignedToUserId"]) },
fallback: async () => ({ hits: [], estimatedTotalHits: 0, processingTimeMs: 0 }),
}).then((result) => result.hits.map((hit) => meiliFileHit(input, hit)))
);
}
if (input.searchableTypes.includes("task")) {
jobs.push(
searchWithFallback({
client,
schema: tasksIndex,
tenantId: input.ctx.tenantId,
query: input.query,
options: { limit: input.limit, extraFilters: ownerMeiliFilters(input.access.task, input.ctx.userId, ["createdByUserId", "assignedToUserId"]) },
fallback: async () => ({ hits: [], estimatedTotalHits: 0, processingTimeMs: 0 }),
}).then((result) => result.hits.map((hit) => meiliTaskHit(input, hit)))
);
}
if (input.searchableTypes.includes("employee") && input.access.employee.all) {
jobs.push(
searchWithFallback({
client,
schema: hrDirectoryIndex,
tenantId: input.ctx.tenantId,
query: input.query,
options: { limit: input.limit },
fallback: async () => ({ hits: [], estimatedTotalHits: 0, processingTimeMs: 0 }),
}).then((result) => result.hits.map((hit) => meiliEmployeeHit(input, hit)))
);
}
if (input.searchableTypes.includes("user")) {
jobs.push(
searchWithFallback({
client,
schema: usersIndex,
tenantId: input.ctx.tenantId,
query: input.query,
options: { limit: input.limit },
fallback: async () => ({ hits: [], estimatedTotalHits: 0, processingTimeMs: 0 }),
}).then((result) => result.hits.map((hit) => meiliUserHit(input, hit)))
);
}
try {
return (await Promise.all(jobs)).flat();
} catch {
return [];
}
}
function meiliCrmHit(
input: Pick<Parameters<typeof searchMeili>[0], "ctx" | "access">,
entityType: "contact" | "company" | "lead",
hit: SearchHit<SearchDocument>
): GlobalSearchResult {
const doc = hit.document;
const title =
entityType === "company"
? String(doc.company ?? doc.email ?? doc.id)
: [doc.firstName, doc.lastName].filter(Boolean).join(" ") || String(doc.email ?? doc.id);
const path = entityType === "company" ? `contacts/companies/${doc.id}` : entityType === "lead" ? `leads/${doc.id}` : `contacts/${doc.id}`;
return {
id: String(doc.id),
entityType,
title,
subtitle: String(doc.email ?? doc.status ?? ""),
href: appPath({ tenantSlug: input.ctx.tenantSlug, path, mode: "host-aware" }),
permissionSubject: input.access[entityType].permissionSubject,
updatedAt: stringOrNull(doc.updatedAt),
};
}
function meiliProjectHit(input: Pick<Parameters<typeof searchMeili>[0], "ctx" | "access">, hit: SearchHit<SearchDocument>): GlobalSearchResult {
const doc = hit.document;
return {
id: String(doc.id),
entityType: "project",
title: String(doc.name ?? doc.projectNumber ?? doc.id),
subtitle: String(doc.projectNumber ?? doc.type ?? ""),
href: appPath({ tenantSlug: input.ctx.tenantSlug, path: `projects/${doc.id}`, mode: "host-aware" }),
permissionSubject: input.access.project.permissionSubject,
updatedAt: stringOrNull(doc.updatedAt),
};
}
function ownerMeiliFilters(access: EntityAccess, userId: string, fields: readonly string[]): string[] {
if (access.all) return [];
const escaped = escapeMeiliFilterValue(userId);
return [`${fields.map((field) => `${field} = "${escaped}"`).join(" OR ")}`];
}
function projectMeiliFilters(ctx: SearchContext, access: EntityAccess): string[] {
if (access.all) return [];
const fields: string[] = [];
if (ctx.permissions.includes("projects.read_own")) fields.push("ownerId");
if (ctx.permissions.includes("projects.read_own_pl")) fields.push("projectLeadId");
return fields.length > 0 ? ownerMeiliFilters(access, ctx.userId, fields) : [];
}
function meiliFileHit(input: Pick<Parameters<typeof searchMeili>[0], "ctx" | "access">, hit: SearchHit<SearchDocument>): GlobalSearchResult {
const doc = hit.document;
return {
id: String(doc.id),
entityType: "file",
title: String(doc.displayName ?? doc.id),
subtitle: String(doc.mimeType ?? ""),
href: appPath({ tenantSlug: input.ctx.tenantSlug, path: `files/${doc.id}`, mode: "host-aware" }),
permissionSubject: input.access.file.permissionSubject,
updatedAt: stringOrNull(doc.updatedAt),
};
}
function meiliTaskHit(input: Pick<Parameters<typeof searchMeili>[0], "ctx" | "access">, hit: SearchHit<SearchDocument>): GlobalSearchResult {
const doc = hit.document;
return {
id: String(doc.id),
entityType: "task",
title: String(doc.title ?? doc.id),
subtitle: String(doc.status ?? ""),
href: appPath({ tenantSlug: input.ctx.tenantSlug, path: `tasks/${doc.id}`, mode: "host-aware" }),
permissionSubject: input.access.task.permissionSubject,
updatedAt: stringOrNull(doc.updatedAt),
};
}
function meiliEmployeeHit(input: Pick<Parameters<typeof searchMeili>[0], "ctx" | "access">, hit: SearchHit<SearchDocument>): GlobalSearchResult {
const doc = hit.document;
const userId = String(doc.userId ?? doc.id);
return {
id: userId,
entityType: "employee",
title: String(doc.name ?? doc.email ?? userId),
subtitle: [doc.position, doc.team, doc.email].filter(Boolean).join(" · "),
href: appPath({ tenantSlug: input.ctx.tenantSlug, path: `hr/directory/${userId}`, mode: "host-aware" }),
permissionSubject: input.access.employee.permissionSubject,
updatedAt: stringOrNull(doc.updatedAt),
};
}
function meiliUserHit(input: Pick<Parameters<typeof searchMeili>[0], "ctx" | "access">, hit: SearchHit<SearchDocument>): GlobalSearchResult {
const doc = hit.document;
const title = [doc.firstName, doc.lastName].filter(Boolean).join(" ") || String(doc.email ?? doc.id);
return {
id: String(doc.id),
entityType: "user",
title,
subtitle: String(doc.email ?? ""),
href: appPath({ tenantSlug: input.ctx.tenantSlug, path: "settings/team", mode: "host-aware" }),
permissionSubject: input.access.user.permissionSubject,
updatedAt: stringOrNull(doc.lastLoginAt),
};
}
async function loadRecentSearches(ctx: SearchContext): Promise<RecentSearchItem[]> {
const rows = await withTenantRLS(ctx.tenantId, (database) =>
database.recentSearch.findMany({
where: { tenantId: ctx.tenantId, userId: ctx.userId },
orderBy: { createdAt: "desc" },
take: RECENT_LIMIT,
select: { id: true, queryText: true, appliedFilters: true, resultCount: true, createdAt: true },
})
);
return rows.map((row) => ({
id: row.id,
queryText: row.queryText,
entityTypes: readRecentEntityTypes(row.appliedFilters),
resultCount: row.resultCount,
createdAt: serializeDate(row.createdAt) ?? "",
}));
}
export async function recordCommittedSearch(input: RecordCommittedSearchInput): Promise<RecordCommittedSearchResult> {
const query = parseGlobalSearchQuery(input.query);
const entityTypes = parseGlobalSearchEntityTypes(input.entityTypes);
const resultCount = parseGlobalSearchResultCount(input.resultCount);
const selectedEntityType = parseSelectedEntityType(input.selectedEntityType);
const selectedEntityId = parseSelectedEntityId(input.selectedEntityId);
if (!selectedEntityId || (entityTypes.length > 0 && !entityTypes.includes(selectedEntityType))) {
throw new GlobalSearchInputError("invalid_selection");
}
const enabledEntityTypes = await loadEnabledEntityTypes(input.ctx, [selectedEntityType]);
const access = buildAccessMap(input.ctx.permissions, enabledEntityTypes);
if (!access[selectedEntityType].allowed) throw new GlobalSearchInputError("invalid_selection");
const requestKey = buildGlobalSearchRequestKey(query, entityTypes);
const cutoff = new Date(Date.now() - RECENT_RETENTION_DAYS * 24 * 60 * 60 * 1000);
try {
const ctx = await hydrateSearchVisibilityContext(input.ctx, [selectedEntityType]);
await withTenantRLS(ctx.tenantId, async (database) => {
const visibleSelectionIds = await loadVisibleEntityIds({
ctx,
access,
entityType: selectedEntityType,
ids: [selectedEntityId],
database,
});
if (!visibleSelectionIds.has(selectedEntityId)) throw new GlobalSearchInputError("invalid_selection");
const advisoryLockKey = `${ctx.tenantId}:${ctx.userId}`;
await database.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${advisoryLockKey}, 0))`;
const [sameQueryRows, overflowRows] = await Promise.all([
database.recentSearch.findMany({
where: { tenantId: ctx.tenantId, userId: ctx.userId, queryText: query },
select: { id: true, appliedFilters: true },
}),
database.recentSearch.findMany({
where: { tenantId: ctx.tenantId, userId: ctx.userId, createdAt: { gte: cutoff } },
orderBy: { createdAt: "desc" },
skip: RECENT_HISTORY_LIMIT - 1,
select: { id: true },
}),
]);
const duplicateIds = sameQueryRows.filter((row) => haveSameEntityTypes(readRecentEntityTypes(row.appliedFilters), entityTypes)).map((row) => row.id);
const idsToDelete = [...new Set([...duplicateIds, ...overflowRows.map((row) => row.id)])];
await database.recentSearch.deleteMany({
where: {
tenantId: ctx.tenantId,
userId: ctx.userId,
OR: [{ createdAt: { lt: cutoff } }, ...(idsToDelete.length ? [{ id: { in: idsToDelete } }] : [])],
},
});
await database.recentSearch.create({
data: {
tenantId: ctx.tenantId,
userId: ctx.userId,
queryText: query,
resultCount,
appliedFilters: { entityTypes },
},
});
});
return { recorded: true, requestKey };
} catch (error) {
if (error instanceof GlobalSearchInputError) throw error;
// Search history is helpful state and must never block opening a result.
return { recorded: false, requestKey };
}
}
export function parseGlobalSearchQuery(value: unknown, options: { allowEmpty?: boolean } = {}): string {
if (typeof value !== "string") {
throw new GlobalSearchInputError("query_too_short");
}
const query = value.trim();
if (!query && options.allowEmpty) return query;
if (query.length < GLOBAL_SEARCH_QUERY_MIN_LENGTH) {
throw new GlobalSearchInputError("query_too_short");
}
if (query.length > GLOBAL_SEARCH_QUERY_MAX_LENGTH) {
throw new GlobalSearchInputError("query_too_long");
}
return query;
}
export function parseGlobalSearchEntityTypes(value: unknown): GlobalSearchEntityType[] {
if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string" || !entityTypeOrder.has(entry as GlobalSearchEntityType))) {
throw new GlobalSearchInputError("invalid_entity_types");
}
return [...new Set(value as GlobalSearchEntityType[])].sort(
(left, right) => (entityTypeOrder.get(left) ?? Number.MAX_SAFE_INTEGER) - (entityTypeOrder.get(right) ?? Number.MAX_SAFE_INTEGER)
);
}
export function parseGlobalSearchResultCount(value: unknown): number {
const parsed = typeof value === "number" ? value : typeof value === "string" && /^\d+$/u.test(value) ? Number(value) : Number.NaN;
if (!Number.isInteger(parsed) || parsed < 0 || parsed > GLOBAL_SEARCH_RESULT_MAX) {
throw new GlobalSearchInputError("invalid_result_count");
}
return parsed;
}
export function buildGlobalSearchRequestKey(query: string, entityTypes: readonly GlobalSearchEntityType[], limit?: number): string {
return `${encodeURIComponent(query)}|${entityTypes.join(",") || "*"}|${limit ?? "*"}`;
}
function parseGlobalSearchRequestId(value: unknown): string | null {
if (value === undefined || value === null || value === "") return null;
if (typeof value !== "string" || value.length > 128 || /[\u0000-\u001f\u007f]/u.test(value)) {
throw new GlobalSearchInputError("invalid_request_id");
}
return value;
}
function parseSelectedEntityId(value: unknown): string {
if (typeof value !== "string") throw new GlobalSearchInputError("invalid_selection");
const selectedEntityId = value.trim();
if (!selectedEntityId || selectedEntityId.length > 200) throw new GlobalSearchInputError("invalid_selection");
return selectedEntityId;
}
function parseSelectedEntityType(value: unknown): GlobalSearchEntityType {
try {
const [entityType] = parseGlobalSearchEntityTypes([value]);
if (entityType) return entityType;
} catch {
// Invalid selected result payloads use one stable public error code.
}
throw new GlobalSearchInputError("invalid_selection");
}
function readRecentEntityTypes(value: unknown): GlobalSearchEntityType[] {
if (!value || typeof value !== "object" || Array.isArray(value) || !("entityTypes" in value)) return [];
try {
return parseGlobalSearchEntityTypes((value as { entityTypes: unknown }).entityTypes);
} catch {
return [];
}
}
function haveSameEntityTypes(left: readonly GlobalSearchEntityType[], right: readonly GlobalSearchEntityType[]) {
return left.length === right.length && left.every((entityType, index) => entityType === right[index]);
}
function mergeResults(results: GlobalSearchResult[], limit: number) {
const seen = new Set<string>();
const buckets = new Map<GlobalSearchEntityType, Array<{ result: GlobalSearchResult; sourceIndex: number }>>();
results.forEach((result, sourceIndex) => {
const key = `${result.entityType}:${result.id}`;
if (seen.has(key)) return;
seen.add(key);
const bucket = buckets.get(result.entityType) ?? [];
bucket.push({ result, sourceIndex });
buckets.set(result.entityType, bucket);
});
// Preserve the order inside every entity bucket. Meilisearch order carries
// relevance, while SQL rows already arrive ordered by updatedAt.
const merged: GlobalSearchResult[] = [];
while (merged.length < limit) {
const round = GLOBAL_SEARCH_ENTITY_TYPES.flatMap((entityType) => {
const candidate = buckets.get(entityType)?.[0];
return candidate ? [candidate] : [];
}).sort(
(left, right) =>
compareUpdatedDesc(left.result, right.result) ||
(entityTypeOrder.get(left.result.entityType) ?? Number.MAX_SAFE_INTEGER) - (entityTypeOrder.get(right.result.entityType) ?? Number.MAX_SAFE_INTEGER) ||
left.sourceIndex - right.sourceIndex
);
if (round.length === 0) break;
for (const candidate of round) {
buckets.get(candidate.result.entityType)?.shift();
merged.push(candidate.result);
if (merged.length === limit) break;
}
}
return merged;
}
function compareUpdatedDesc(left: GlobalSearchResult, right: GlobalSearchResult) {
const leftUpdatedAt = parseUpdatedAt(left.updatedAt);
const rightUpdatedAt = parseUpdatedAt(right.updatedAt);
if (leftUpdatedAt === rightUpdatedAt) return 0;
return rightUpdatedAt - leftUpdatedAt;
}
function parseUpdatedAt(value: string | null) {
if (!value) return Number.NEGATIVE_INFINITY;
const parsed = Date.parse(value);
return Number.isNaN(parsed) ? Number.NEGATIVE_INFINITY : parsed;
}
function clampLimit(limit: number | undefined) {
if (!limit || Number.isNaN(limit)) return DEFAULT_LIMIT;
return Math.min(Math.max(Math.floor(limit), 1), 50);
}
function serializeDate(value: Date | string | null): string | null {
if (value === null) return null;
return value instanceof Date ? value.toISOString() : value;
}
function stringOrNull(value: unknown): string | null {
return typeof value === "string" ? value : null;
}
function escapeMeiliFilterValue(value: string): string {
return value.replace(/\\/gu, "\\\\").replace(/"/gu, '\\"');
}