Files
2026-07-08 16:15:37 +02:00

94 lines
4.1 KiB
TypeScript

// R-P6 (P6 CRM core, Variante A) — shared loader/action guard for CRM routes.
//
// Resolves the authenticated tenant context and the user's permission set once,
// so routes can gate consistently (mirrors taskAccess). Module-not-active handling
// differs by intent (§ "404 vs locked"):
// - GET loaders pass `requireModule: false` and render a locked/empty VM when
// `hasModule` is false.
// - Write actions pass `requireModule: true` → 404 (CatalogError.notFound) when
// the module is off, and additionally require an explicit crm.* permission.
import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo } from "~/utils/session.server";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
import { CrmServiceError, type CrmVisibilityContext } from "./crmService.server";
// The connector/entitlement feature key. The phase is called "crm", but the
// seeded/registered feature key is "crm-basic" (packages/entitlements →
// featureKeys.crmBasic). A fresh "crm" key would be unseeded, so tenantHasModule
// would always return false; "crm-basic" is the key tenants actually carry.
export const CRM_MODULE_KEY = "crm-basic";
// Owner-scope helpers live in crmService (the leaf, used by listKontakteForBrowser)
// and are re-exported here so routes can reach them from the access module.
export { canReadAllKontakte, ownerScopeWhere } from "./crmService.server";
export type { CrmVisibilityContext } from "./crmService.server";
export type CrmRouteContext = CrmVisibilityContext & {
tenantId: string;
hasModule: boolean;
};
export async function loadCrmContext({
request,
params,
requireModule = false,
}: {
request: Request;
params: Record<string, string | undefined>;
requireModule?: boolean;
}): Promise<CrmRouteContext> {
await requireAuth({ request, params });
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
if (!tenantId || !userInfo.userId) {
throw new CatalogError(foundationErrors.notFound);
}
const [hasModule, permissions] = await Promise.all([
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: CRM_MODULE_KEY }),
getPermissionsByUser(userInfo.userId, tenantId),
]);
if (requireModule && !hasModule) {
// Mutations on a disabled module look "not found" (Bauprinzip A.5.3).
throw new CatalogError(foundationErrors.notFound, { module: CRM_MODULE_KEY });
}
return { tenantId, userId: userInfo.userId, permissions, hasModule };
}
/** Require a crm.* permission; throws 404 (CatalogError.notFound) if missing. */
export function requireCrmPermission(ctx: CrmRouteContext, permission: string): CrmRouteContext {
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, permission);
return ctx;
}
/**
* Bare 404 Response for throwing from CRM loaders/actions. The body text is never
* shown to users (the route ErrorBoundary renders ServerError); the helper keeps
* call sites from inlining a hardcoded user-facing literal.
*/
export function notFoundResponse(): Response {
return new Response("Not Found", { status: 404 });
}
/** Bare 400 Response for invalid action input (same rationale as notFoundResponse). */
export function badRequestResponse(): Response {
return new Response("Bad Request", { status: 400 });
}
/**
* Map a CRM action error to a JSON Response for resource routes. CatalogError keeps
* its status + i18nKey; CrmServiceError is a 400 with its Klartext message key.
* Unknown errors are rethrown (→ 500).
*/
export function crmActionErrorResponse(error: unknown): Response {
if (error instanceof CatalogError) {
return Response.json({ error: error.i18nKey, code: error.code }, { status: error.status });
}
if (error instanceof CrmServiceError) {
return Response.json({ error: error.messageKey }, { status: 400 });
}
throw error;
}