151 lines
6.5 KiB
TypeScript
151 lines
6.5 KiB
TypeScript
// R-P6 (P6 CRM core, Variante A) — create-contact route (`/contacts/new`).
|
|
// `intent=checkDuplicates` (fetcher) surfaces hard/soft duplicate hits live while
|
|
// typing (DoD 4); `intent=create` persists the typed Kontakt (+ audit + activity)
|
|
// and redirects to the detail. Module off -> locked; missing crm.write -> 404.
|
|
|
|
import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useActionData, useFetcher, useLoaderData, useNavigation, useSubmit } from "react-router";
|
|
import { buildKontaktDisplayName } from "@hivegrid/view-models";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import {
|
|
badRequestResponse,
|
|
crmActionErrorResponse,
|
|
loadCrmContext,
|
|
notFoundResponse,
|
|
requireCrmPermission,
|
|
} from "~/utils/integrations/crm/crmAccess.server";
|
|
import { createKontakt, findDuplicateKontakte, listAssignableUsers, type KontaktTyp, type OrgMerkmal, type KontaktStatus } from "~/utils/integrations/crm/crmService.server";
|
|
import { auditCrmEvent, logKontaktActivity } from "~/utils/integrations/crm/crmAudit.server";
|
|
import { companiesPath, companyDetailPath, contactDetailPath, contactsPath, CRM_MODULE_KEY } from "~/utils/integrations/crm/crmRoutePaths";
|
|
import { KontaktNewPage, type KontaktNewFields } from "~/components/screens/crm/KontaktNewPage";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
import { useSaveToast } from "~/hooks/use-save-toast";
|
|
|
|
type DuplicateCard = { id: string; displayName: string; primaerEmail: string | null; primaerTelefon: string | null; detailHref: string };
|
|
type LoaderData = { title: string; moduleActive: boolean; ownerOptions: { id: string; label: string }[]; defaultOwnerId: string; backHref: string };
|
|
|
|
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
|
const { t } = await getTranslations(request);
|
|
const ctx = await loadCrmContext({ request, params });
|
|
const tenantSlug = params.tenant ?? "";
|
|
const base = { title: `${t("crm.new.title")} | ${process.env.APP_NAME}`, backHref: contactsPath(tenantSlug) };
|
|
if (!ctx.hasModule) {
|
|
return Response.json({ ...base, moduleActive: false, ownerOptions: [], defaultOwnerId: ctx.userId } satisfies LoaderData);
|
|
}
|
|
try {
|
|
requireCrmPermission(ctx, "crm.write");
|
|
} catch {
|
|
throw notFoundResponse();
|
|
}
|
|
const ownerOptions = await listAssignableUsers(ctx.tenantId);
|
|
return Response.json({ ...base, moduleActive: true, ownerOptions, defaultOwnerId: ctx.userId } satisfies LoaderData);
|
|
};
|
|
|
|
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
|
const ctx = await loadCrmContext({ request, params, requireModule: true });
|
|
const tenantSlug = params.tenant ?? "";
|
|
const form = await request.formData();
|
|
const intent = form.get("intent")?.toString();
|
|
const str = (name: string) => form.get(name)?.toString().trim() || null;
|
|
|
|
try {
|
|
requireCrmPermission(ctx, "crm.write");
|
|
const kontaktTyp = (str("kontaktTyp") ?? "privatperson") as KontaktTyp;
|
|
|
|
if (intent === "checkDuplicates") {
|
|
const { hard, soft } = await findDuplicateKontakte({
|
|
tenantId: ctx.tenantId,
|
|
email: str("email"),
|
|
telefon: str("telefon"),
|
|
vorname: str("vorname"),
|
|
nachname: str("nachname"),
|
|
orgName: str("orgName"),
|
|
});
|
|
const toCard = (row: (typeof hard)[number]): DuplicateCard => ({
|
|
id: row.id,
|
|
displayName: buildKontaktDisplayName(row),
|
|
primaerEmail: row.primaerEmail,
|
|
primaerTelefon: row.primaerTelefon,
|
|
detailHref: row.kontaktTyp === "organisation" ? companyDetailPath(tenantSlug, row.id) : contactDetailPath(tenantSlug, row.id),
|
|
});
|
|
return Response.json({ hard: hard.map(toCard), soft: soft.map(toCard) });
|
|
}
|
|
|
|
if (intent === "create") {
|
|
const email = str("email");
|
|
const telefon = str("telefon");
|
|
const created = await createKontakt({
|
|
tenantId: ctx.tenantId,
|
|
userId: ctx.userId,
|
|
kontaktTyp,
|
|
kontaktStatus: (str("kontaktStatus") as KontaktStatus | null) ?? undefined,
|
|
vorname: str("vorname"),
|
|
nachname: str("nachname"),
|
|
orgName: str("orgName"),
|
|
orgMerkmal: (str("orgMerkmal") as OrgMerkmal | null) ?? undefined,
|
|
emails: email ? [{ email, primaer: true }] : [],
|
|
telefone: telefon ? [{ telefon, primaer: true }] : [],
|
|
zustaendigerUserId: str("zustaendigerUserId"),
|
|
});
|
|
await auditCrmEvent({ ctx, action: "kontakt.created", targetType: "kontakt", targetId: created.id });
|
|
await logKontaktActivity({
|
|
ctx,
|
|
kontaktId: created.id,
|
|
kontaktTyp,
|
|
activityType: "contact_created",
|
|
summaryText: "crm.activity.contact_created",
|
|
});
|
|
// Back to the list the dialog was opened from, not into the new record.
|
|
// Creating a contact from the list is usually one of several in a row, and
|
|
// landing on a detail page turns the next one into a trip back first.
|
|
const listHref = kontaktTyp === "organisation" ? companiesPath(tenantSlug) : contactsPath(tenantSlug);
|
|
return redirect(`${listHref}?toast=${encodeURIComponent(kontaktTyp === "organisation" ? "crm.toast.companyCreated" : "crm.toast.contactCreated")}`);
|
|
}
|
|
|
|
throw badRequestResponse();
|
|
} catch (error) {
|
|
if (error instanceof Response) {
|
|
throw error;
|
|
}
|
|
return crmActionErrorResponse(error);
|
|
}
|
|
};
|
|
|
|
function fieldsToFormData(fields: KontaktNewFields, intent: string): FormData {
|
|
const form = new FormData();
|
|
form.set("intent", intent);
|
|
for (const [key, value] of Object.entries(fields)) form.set(key, value);
|
|
return form;
|
|
}
|
|
|
|
export default function ContactNewRoute() {
|
|
const { moduleActive, ownerOptions, defaultOwnerId, backHref } = useLoaderData<LoaderData>();
|
|
const actionData = useActionData<{ error?: string }>();
|
|
const dupFetcher = useFetcher<{ hard: DuplicateCard[]; soft: DuplicateCard[] }>();
|
|
const submit = useSubmit();
|
|
useSaveToast(actionData);
|
|
const navigation = useNavigation();
|
|
|
|
return (
|
|
<KontaktNewPage
|
|
moduleActive={moduleActive}
|
|
ownerOptions={ownerOptions}
|
|
defaultOwnerId={defaultOwnerId}
|
|
backHref={backHref}
|
|
listLabelKey="crm.contacts.title"
|
|
duplicates={dupFetcher.data ?? null}
|
|
submitting={navigation.state !== "idle"}
|
|
errorKey={actionData?.error ?? null}
|
|
actions={{
|
|
onCheckDuplicates: (fields) => dupFetcher.submit(fieldsToFormData(fields, "checkDuplicates"), { method: "post" }),
|
|
onCreate: (fields) => submit(fieldsToFormData(fields, "create"), { method: "post" }),
|
|
}}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|
|
|
|
export const handle = { moduleKey: CRM_MODULE_KEY };
|