159 lines
5.8 KiB
TypeScript
159 lines
5.8 KiB
TypeScript
import { CatalogError } from "@hivegrid/foundation";
|
|
import type { TelephonyCallDetailVM, TelephonyMatchedEntityType } from "@hivegrid/view-models";
|
|
import { type ActionFunctionArgs, type LoaderFunctionArgs, type MetaFunction, useFetcher, useLoaderData, useNavigate } from "react-router";
|
|
|
|
import { TelephonyCallDetailPage } from "~/components/screens/telephony/TelephonyCallDetailPage";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
import { useSaveToast } from "~/hooks/use-save-toast";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { loadTelephonyContext } from "~/modules/telephony/routes/telephonyAccess.server";
|
|
import { TELEPHONY_MODULE_KEY } from "~/modules/telephony/routes/telephonyRoutePaths";
|
|
import {
|
|
loadTelephonyCallDetail,
|
|
overrideTelephonyCallMatch,
|
|
saveTelephonyCallNote,
|
|
startTelephonyCallBack,
|
|
TelephonyServiceError,
|
|
} from "~/modules/telephony/services/TelephonyService.server";
|
|
import { appendCSRFToken } from "~/utils/csrf";
|
|
import { validateCSRFToken } from "~/utils/session.server";
|
|
|
|
type LoaderData = {
|
|
readonly title: string;
|
|
readonly vm: TelephonyCallDetailVM;
|
|
};
|
|
|
|
type ActionData = {
|
|
readonly intent?: string;
|
|
readonly ok?: true;
|
|
readonly messageKey?: string;
|
|
readonly error?: string;
|
|
};
|
|
|
|
const MATCH_TYPES = new Set<TelephonyMatchedEntityType>(["contact", "lead", "project"]);
|
|
|
|
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
|
const [{ t }, ctx] = await Promise.all([getTranslations(request), loadTelephonyContext({ request, params, requireModule: true })]);
|
|
const vm = await loadTelephonyCallDetail(ctx, params.tenant ?? "", params.id ?? "");
|
|
return Response.json({
|
|
title: `${t("telephony.callDetail.title")} | ${process.env.APP_NAME}`,
|
|
vm,
|
|
} satisfies LoaderData);
|
|
};
|
|
|
|
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
|
|
|
|
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
|
const form = await request.formData();
|
|
await validateCSRFToken(request, { formData: form });
|
|
const ctx = await loadTelephonyContext({ request, params, requireModule: true });
|
|
const callId = params.id ?? "";
|
|
const intent = String(form.get("intent") ?? "");
|
|
|
|
try {
|
|
if (intent === "saveNote") {
|
|
await saveTelephonyCallNote(ctx, {
|
|
callId,
|
|
noteMarkdown: String(form.get("noteMarkdown") ?? ""),
|
|
});
|
|
return Response.json({
|
|
intent,
|
|
ok: true,
|
|
messageKey: "telephony.callDetail.feedback.noteSaved",
|
|
} satisfies ActionData);
|
|
}
|
|
if (intent === "overrideMatch") {
|
|
const type = String(form.get("matchType") ?? "");
|
|
const id = String(form.get("matchId") ?? "").trim();
|
|
const match =
|
|
!type && !id ? null : MATCH_TYPES.has(type as TelephonyMatchedEntityType) && id ? { type: type as TelephonyMatchedEntityType, id } : undefined;
|
|
if (match === undefined) return invalidRequestResponse(intent);
|
|
await overrideTelephonyCallMatch(ctx, { callId, match });
|
|
return Response.json({
|
|
intent,
|
|
ok: true,
|
|
messageKey:
|
|
match === null
|
|
? "telephony.callDetail.feedback.matchRemoved"
|
|
: "telephony.callDetail.feedback.matchSaved",
|
|
} satisfies ActionData);
|
|
}
|
|
if (intent === "callBack") {
|
|
await startTelephonyCallBack(ctx, callId);
|
|
return Response.json({
|
|
intent,
|
|
ok: true,
|
|
messageKey: "telephony.callDetail.feedback.callbackStarted",
|
|
} satisfies ActionData);
|
|
}
|
|
return invalidRequestResponse(intent);
|
|
} catch (error) {
|
|
return telephonyActionErrorResponse(error, intent);
|
|
}
|
|
};
|
|
|
|
export default function TelephonyCallDetailRoute(): React.JSX.Element {
|
|
const { vm } = useLoaderData<LoaderData>();
|
|
const fetcher = useFetcher<ActionData>();
|
|
const navigate = useNavigate();
|
|
const actionVm: TelephonyCallDetailVM = fetcher.data?.error
|
|
? {
|
|
status: "error",
|
|
data: vm.status === "ready" ? vm.data : undefined,
|
|
error: { messageKey: fetcher.data.error },
|
|
}
|
|
: vm;
|
|
// Keep the existing inline error state, and toast only confirmed successes
|
|
// so a failed action is not announced twice.
|
|
useSaveToast(fetcher.data?.ok ? fetcher.data : undefined);
|
|
|
|
const submit = (fields: Record<string, string>) => {
|
|
const form = new FormData();
|
|
for (const [key, value] of Object.entries(fields)) form.set(key, value);
|
|
fetcher.submit(appendCSRFToken(form), { method: "post" });
|
|
};
|
|
|
|
return (
|
|
<TelephonyCallDetailPage
|
|
vm={actionVm}
|
|
busy={fetcher.state !== "idle"}
|
|
actions={{
|
|
onBack: (listHref) => navigate(listHref),
|
|
onOverrideMatch: (_callId, option) =>
|
|
submit({
|
|
intent: "overrideMatch",
|
|
matchType: option?.type ?? "",
|
|
matchId: option?.id ?? "",
|
|
}),
|
|
onSaveNote: (_callId, noteMarkdown) => submit({ intent: "saveNote", noteMarkdown }),
|
|
onCallBack: () => submit({ intent: "callBack" }),
|
|
onRetry: () => window.location.reload(),
|
|
}}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function invalidRequestResponse(intent?: string): Response {
|
|
return Response.json({ intent, error: "telephony.errors.invalidRequest" } satisfies ActionData, { status: 400 });
|
|
}
|
|
|
|
function telephonyActionErrorResponse(error: unknown, intent: string): Response {
|
|
if (error instanceof Response) return error;
|
|
if (error instanceof CatalogError) {
|
|
return Response.json({ intent, error: error.i18nKey } satisfies ActionData, { status: error.status });
|
|
}
|
|
if (error instanceof TelephonyServiceError) {
|
|
return Response.json({ intent, error: error.messageKey } satisfies ActionData, { status: 400 });
|
|
}
|
|
throw error;
|
|
}
|
|
|
|
export function ErrorBoundary(): React.JSX.Element {
|
|
return <ServerError />;
|
|
}
|
|
|
|
export const handle = {
|
|
moduleKey: TELEPHONY_MODULE_KEY,
|
|
breadcrumbKey: "telephony.callDetail.title",
|
|
};
|