Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/routes/app.$tenant/admin.pipelines.$pipelineId.fields.tsx
T

219 lines
9.6 KiB
TypeScript

// WF-P8 S05 (Detail-Schablone Edit-Mode) + M05 (Modal Bestandsfeld).
// Route: /admin/pipelines/:pipelineId/fields — reached from S04 board settings
// via "Zur Detailfelder-Konfiguration".
import { useActionData, useLoaderData, useNavigation, useSubmit, type ActionFunctionArgs, type LoaderFunctionArgs } from "react-router";
import {
buildPipelineFieldTemplateVM,
isTemplateFieldType,
parseCustomFieldOptions,
serializeCustomFieldOptions,
type CustomFieldOption,
type PipelineFieldTemplateData,
} from "@hivegrid/view-models";
import { CatalogError } from "@hivegrid/foundation";
import {
ALWAYS_VISIBLE_FIELD_KEYS,
createFieldGroup,
deleteFieldGroup,
deleteTemplateField,
loadPipelineFieldTemplate,
moveFieldToGroup,
PipelineFieldTemplateError,
renameFieldGroup,
} from "~/utils/integrations/projects/pipelineFieldTemplateService.server";
import { upsertPipelineFieldConfig } from "~/utils/integrations/projects/projectService.server";
import { listCustomFieldDefinitions, updateCustomFieldDefinition } from "~/utils/integrations/crm/customFieldService.server";
import { CrmServiceError } from "~/utils/integrations/crm/crmService.server";
import { loadProjectContext, projectActionErrorResponse, projectNotFoundResponse, requireProjectPermission } from "~/utils/integrations/projects/projectAccess.server";
import { projectPipelinesAdminPath, projectsBoardsPath } from "~/utils/integrations/projects/projectRoutePaths";
import { PipelineFieldTemplatePage } from "~/components/screens/projects/PipelineFieldTemplatePage";
import { getTranslations } from "~/locale/i18next.server";
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
import { useSaveToast } from "~/hooks/use-save-toast";
const FIELD_TEMPLATE_SUCCESS_KEYS: Record<string, string> = {
createFieldGroup: "projects.toast.fieldGroupCreated",
renameFieldGroup: "projects.toast.fieldGroupRenamed",
deleteFieldGroup: "projects.toast.fieldGroupDeleted",
moveTemplateField: "projects.toast.fieldMoved",
updateTemplateField: "projects.toast.fieldSettingsSaved",
updateCustomField: "projects.toast.customFieldDefinitionSaved",
deleteTemplateField: "projects.toast.fieldDeleted",
};
type LoaderData = {
data: PipelineFieldTemplateData;
title: string;
backHref: string;
breadcrumbAncestors: { label: string; href: string }[];
};
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
export async function loader({ request, params }: LoaderFunctionArgs) {
const ctx = requireProjectPermission(await loadProjectContext({ request, params, requireModule: true }), "projects.admin");
const { t } = await getTranslations(request);
try {
const [template, definitions] = await Promise.all([
loadPipelineFieldTemplate({ tenantId: ctx.tenantId, pipelineId: params.pipelineId! }),
listCustomFieldDefinitions({ tenantId: ctx.tenantId, entityType: "projekt" }),
]);
const data = buildPipelineFieldTemplateVM({
...template,
definitions: Object.fromEntries(
definitions.map((definition) => [
definition.key,
{ id: definition.id, label: definition.label, datentyp: definition.datentyp, optionen: definition.optionen },
])
),
alwaysVisibleKeys: ALWAYS_VISIBLE_FIELD_KEYS,
canEdit: true,
});
return Response.json({
data,
title: `${t("projects.fieldTemplate.title")} | ${process.env.APP_NAME}`,
backHref: projectPipelinesAdminPath(params.tenant ?? ""),
breadcrumbAncestors: [
{ label: t("projects.boards.nav"), href: projectsBoardsPath(params.tenant ?? "") },
{ label: t("projects.admin.title"), href: projectPipelinesAdminPath(params.tenant ?? "") },
],
} satisfies LoaderData);
} catch (error) {
if (error instanceof CatalogError) throw projectNotFoundResponse();
throw error;
}
}
function formString(formData: FormData, name: string): string | null {
const value = formData.get(name);
return typeof value === "string" ? value : null;
}
function formNumber(formData: FormData, name: string): number {
const parsed = Number(formString(formData, name));
return Number.isFinite(parsed) ? parsed : 0;
}
/**
* The options payload of the S05 inspector. `undefined` means "field absent or
* unreadable, leave the stored options alone"; an empty list is a real
* instruction and clears them. Anything else would turn a malformed request into
* silent data loss.
*/
function parseOptionsPayload(raw: string | null): CustomFieldOption[] | undefined {
if (raw === null) return undefined;
try {
return parseCustomFieldOptions(JSON.parse(raw));
} catch {
return undefined;
}
}
export async function action({ request, params }: ActionFunctionArgs) {
const ctx = requireProjectPermission(await loadProjectContext({ request, params, requireModule: true }), "projects.admin");
const formData = await request.formData();
const intent = formString(formData, "_action");
const pipelineId = params.pipelineId!;
try {
if (intent === "createFieldGroup") {
const group = await createFieldGroup({ tenantId: ctx.tenantId, pipelineId, name: formString(formData, "name") ?? "" });
return Response.json({ ok: true, intent, messageKey: FIELD_TEMPLATE_SUCCESS_KEYS[intent], group });
}
if (intent === "renameFieldGroup") {
await renameFieldGroup({
tenantId: ctx.tenantId,
pipelineId,
groupId: formString(formData, "groupId") ?? "",
name: formString(formData, "name") ?? "",
});
return Response.json({ ok: true, intent, messageKey: FIELD_TEMPLATE_SUCCESS_KEYS[intent] });
}
if (intent === "deleteFieldGroup") {
await deleteFieldGroup({ tenantId: ctx.tenantId, pipelineId, groupId: formString(formData, "groupId") ?? "" });
return Response.json({ ok: true, intent, messageKey: FIELD_TEMPLATE_SUCCESS_KEYS[intent] });
}
if (intent === "moveTemplateField") {
// An empty groupId means "back into the Bestandsfelder pool".
const rawGroupId = formString(formData, "groupId");
await moveFieldToGroup({
tenantId: ctx.tenantId,
pipelineId,
fieldConfigId: formString(formData, "fieldConfigId") ?? "",
groupId: rawGroupId ? rawGroupId : null,
reihenfolge: formNumber(formData, "reihenfolge"),
});
return Response.json({ ok: true, intent, messageKey: FIELD_TEMPLATE_SUCCESS_KEYS[intent] });
}
if (intent === "updateTemplateField") {
await upsertPipelineFieldConfig({
tenantId: ctx.tenantId,
pipelineId,
fieldKey: formString(formData, "fieldKey") ?? "",
stageId: null,
hinweis: formString(formData, "hinweis"),
pflicht: Boolean(formString(formData, "pflicht")),
pflichtAbStageId: formString(formData, "pflichtAbStageId") || null,
gesperrt: Boolean(formString(formData, "gesperrt")),
});
return Response.json({ ok: true, intent, messageKey: FIELD_TEMPLATE_SUCCESS_KEYS[intent] });
}
if (intent === "updateCustomField") {
// The label, the type and its options live on the tenant-wide
// CustomFieldDefinition, not on this pipeline's field config, so this is a
// separate intent. The options arrive as one JSON field: order matters and
// each entry carries a label and a colour.
const datentyp = formString(formData, "datentyp");
const optionen = parseOptionsPayload(formString(formData, "optionen"));
// An empty label would leave the field nameless in every screen that reads
// the definition, so a blank submission keeps the stored one.
const label = formString(formData, "label")?.trim();
await updateCustomFieldDefinition({
tenantId: ctx.tenantId,
definitionId: formString(formData, "definitionId") ?? "",
...(label ? { label } : {}),
...(datentyp && isTemplateFieldType(datentyp) ? { datentyp } : {}),
...(optionen === undefined ? {} : { optionen: serializeCustomFieldOptions(optionen) }),
});
return Response.json({ ok: true, intent, messageKey: FIELD_TEMPLATE_SUCCESS_KEYS[intent] });
}
if (intent === "deleteTemplateField") {
await deleteTemplateField({ tenantId: ctx.tenantId, pipelineId, fieldConfigId: formString(formData, "fieldConfigId") ?? "" });
return Response.json({ ok: true, intent, messageKey: FIELD_TEMPLATE_SUCCESS_KEYS[intent] });
}
return Response.json({ intent, error: "projects.error.unsupportedAction" }, { status: 400 });
} catch (error) {
if (error instanceof PipelineFieldTemplateError || error instanceof CrmServiceError) {
// The retype guard is a CrmServiceError: it belongs to the CRM definition,
// not to this pipeline's template, and the actor needs its plain text.
return Response.json({ intent, error: error.messageKey }, { status: 400 });
}
return projectActionErrorResponse(error);
}
}
export default function PipelineFieldTemplateRoute() {
const data = useLoaderData<LoaderData>();
const navigation = useNavigation();
const submit = useSubmit();
const actionData = useActionData<{ intent?: string; ok?: boolean; error?: string; messageKey?: string }>();
useSaveToast(actionData);
return (
<PipelineFieldTemplatePage
data={data.data}
backHref={data.backHref}
submitting={navigation.state !== "idle"}
errorKey={actionData?.error ?? null}
actions={{
onSubmit: (intent, fields) => {
const formData = new FormData();
formData.set("_action", intent);
for (const [key, value] of Object.entries(fields ?? {})) formData.set(key, value);
submit(formData, { method: "post" });
},
}}
/>
);
}