357 lines
13 KiB
TypeScript
357 lines
13 KiB
TypeScript
// R-P5 (P5) §P3 — per-app connection management. Loader builds ConnectionDetailVM
|
|
// (status/label/health, NEVER credentials). Action: connect / reconnect (same id,
|
|
// no history loss) / disconnect (revoked) / manual re-sync. Renders the interim
|
|
// ConnectionDetailPage from ~/ui incl. the connect wizard dialog (AD-28); final
|
|
// optic = D-P5 delta.
|
|
|
|
import { useEffect, useRef, useState } from "react";
|
|
import { redirect, type ActionFunctionArgs, type LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
|
|
import { buildConnectionDetailVM, connectionStatusKey, type ConnectionRow, type ConnectionDetailVM } from "@hivegrid/view-models";
|
|
import { getCatalogEntry, type AppCredentialField } from "@hivegrid/integrations";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import {
|
|
integrationsActionErrorResponse,
|
|
integrationsHasPermission,
|
|
loadIntegrationsContext,
|
|
notFoundResponse,
|
|
requireIntegrationsPermission,
|
|
} from "~/utils/integrations/integrationsAccess.server";
|
|
import {
|
|
createConnection,
|
|
disconnectConnection,
|
|
listConnections,
|
|
reconnectConnection,
|
|
runSyncForConnection,
|
|
} from "~/utils/integrations/appsEngineService.server";
|
|
import {
|
|
integrationsAppPath,
|
|
integrationsCatalogPath,
|
|
integrationsSyncsPath,
|
|
kwpSetupPath,
|
|
kwpProjectImportPath,
|
|
legacyIntegrationsRedirectPath,
|
|
} from "~/utils/integrations/integrationsRoutePaths";
|
|
import { telephonySettingsPath } from "~/modules/telephony/routes/telephonyRoutePaths";
|
|
import { calendarConnectionsPath } from "~/modules/calendar/routes/calendarRoutePaths";
|
|
import { requireKwpIntegrationModule } from "~/modules/kwp/routes/kwpAccess.server";
|
|
import { ConnectionDetailPage, type ConnectionDetailActions } from "~/components/screens/integrations/ConnectionDetailPage";
|
|
import type { ConnectWizardSubmit } from "~/components/screens/integrations/ConnectWizardDialog";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
import { useSaveToast } from "~/hooks/use-save-toast";
|
|
import { useRootData } from "~/utils/data/useRootData";
|
|
import { validateCSRFToken } from "~/utils/session.server";
|
|
|
|
type LoaderData = {
|
|
title: string;
|
|
breadcrumbAncestors: { label: string; href: string }[];
|
|
vm: ConnectionDetailVM;
|
|
connectionType: string;
|
|
credentialFields: AppCredentialField[];
|
|
feedback: {
|
|
readonly variant: "success" | "error";
|
|
readonly titleKey: string;
|
|
readonly descriptionKey: string;
|
|
} | null;
|
|
};
|
|
|
|
function kwpFeedback(requestUrl: string, appKey: string, hasActiveConnection: boolean): LoaderData["feedback"] {
|
|
if (appKey !== "kwp") return null;
|
|
const outcomes = new URL(requestUrl).searchParams.getAll("kwp");
|
|
if (outcomes.length !== 1) return null;
|
|
if (outcomes[0] === "connected" && hasActiveConnection) {
|
|
return {
|
|
variant: "success",
|
|
titleKey: "integrations.kwp.oauth.connected",
|
|
descriptionKey: "integrations.kwp.oauth.connectedBody",
|
|
};
|
|
}
|
|
if (outcomes[0] === "error") {
|
|
return {
|
|
variant: "error",
|
|
titleKey: "integrations.kwp.oauth.error",
|
|
descriptionKey: "integrations.kwp.oauth.errorBody",
|
|
};
|
|
}
|
|
return null;
|
|
}
|
|
|
|
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
|
const legacyRedirect = legacyIntegrationsRedirectPath(request.url, params.tenant ?? "");
|
|
if (legacyRedirect) {
|
|
throw redirect(legacyRedirect);
|
|
}
|
|
const { t } = await getTranslations(request);
|
|
const ctx = await loadIntegrationsContext({ request, params });
|
|
const tenantSlug = params.tenant ?? "";
|
|
const appKey = params.app ?? "";
|
|
|
|
if (!ctx.hasModule) {
|
|
throw notFoundResponse();
|
|
}
|
|
try {
|
|
requireIntegrationsPermission(ctx, "integrations.read");
|
|
} catch {
|
|
throw notFoundResponse();
|
|
}
|
|
const app = getCatalogEntry(appKey);
|
|
if (!app) {
|
|
throw notFoundResponse();
|
|
}
|
|
if (appKey === "kwp") {
|
|
await requireKwpIntegrationModule(ctx);
|
|
}
|
|
if (appKey === "aircall" || appKey === "hallopetra") {
|
|
throw redirect(telephonySettingsPath(tenantSlug));
|
|
}
|
|
if (appKey === "google-calendar") {
|
|
// Calendar connections are per-USER CalendarConnection rows managed by the
|
|
// calendar module (OAuth flow, sync status, conflict log) — the generic
|
|
// DataConnection surface would always show zero connections and its
|
|
// connect wizard would bypass the Google OAuth flow.
|
|
throw redirect(calendarConnectionsPath(tenantSlug));
|
|
}
|
|
|
|
const connections = await listConnections(ctx.tenantId, { appId: appKey });
|
|
const rows: ConnectionRow[] = connections.map((connection) => ({
|
|
id: connection.id,
|
|
label: connection.label,
|
|
status: connection.connectionStatus,
|
|
statusKey: connectionStatusKey(connection.connectionStatus),
|
|
healthMessageKey: connection.healthMessageKey,
|
|
lastHealthCheckIso: connection.lastHealthCheck ? connection.lastHealthCheck.toISOString() : null,
|
|
tokenExpiresIso: connection.tokenExpiresAt ? connection.tokenExpiresAt.toISOString() : null,
|
|
syncsHref: appKey === "kwp" ? null : integrationsSyncsPath(tenantSlug, appKey, connection.id),
|
|
}));
|
|
|
|
const vm = buildConnectionDetailVM({
|
|
appKey,
|
|
appTitleKey: app.titleKey,
|
|
rows,
|
|
canConnect: integrationsHasPermission(ctx, "integrations.connect"),
|
|
canDisconnect: appKey !== "kwp" && integrationsHasPermission(ctx, "integrations.disconnect"),
|
|
canManualSync: appKey !== "kwp" && integrationsHasPermission(ctx, "integrations.manual_sync"),
|
|
connectHref: appKey === "kwp" ? kwpSetupPath(tenantSlug) : integrationsAppPath(tenantSlug, appKey),
|
|
projectImportHref: appKey === "kwp" && connections.some((connection) => connection.connectionStatus === "active")
|
|
? kwpProjectImportPath(tenantSlug)
|
|
: null,
|
|
});
|
|
return Response.json({
|
|
// Breadcrumb: … > Erweiterungen > Integrationen > <app title>. The hub
|
|
// layout contributes "Erweiterungen"; the catalog is not a matched route
|
|
// here, so it is injected as a breadcrumb ancestor.
|
|
title: `${t(app.titleKey)} | ${process.env.APP_NAME}`,
|
|
breadcrumbAncestors: [{ label: t("integrations.nav.title"), href: integrationsCatalogPath(tenantSlug) }],
|
|
vm,
|
|
connectionType: app.connectionType,
|
|
credentialFields: [...app.connectionSchema.fields],
|
|
feedback: kwpFeedback(
|
|
request.url,
|
|
appKey,
|
|
connections.some((connection) => connection.connectionStatus === "active"),
|
|
),
|
|
} satisfies LoaderData);
|
|
};
|
|
|
|
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
|
const ctx = await loadIntegrationsContext({ request, params, requireModule: true });
|
|
const appKey = params.app ?? "";
|
|
const app = getCatalogEntry(appKey);
|
|
if (!app) {
|
|
throw notFoundResponse();
|
|
}
|
|
if (appKey === "kwp") {
|
|
await requireKwpIntegrationModule(ctx);
|
|
}
|
|
if (appKey === "aircall" || appKey === "hallopetra") {
|
|
// Never let generic credential mutations bypass provider-aware setup,
|
|
// webhook authentication or disconnect cleanup.
|
|
throw redirect(telephonySettingsPath(params.tenant ?? ""), 303);
|
|
}
|
|
if (appKey === "google-calendar") {
|
|
// Same guard for calendar: connections are per-user CalendarConnection rows
|
|
// created by the Google OAuth flow, never generic DataConnection mutations.
|
|
throw redirect(calendarConnectionsPath(params.tenant ?? ""), 303);
|
|
}
|
|
const form = await request.formData();
|
|
const intent = form.get("intent")?.toString();
|
|
|
|
if (appKey === "kwp") {
|
|
await validateCSRFToken(request, { formData: form });
|
|
}
|
|
|
|
if (appKey === "kwp" && (intent === "connect" || intent === "reconnect")) {
|
|
// KWP is a confidential OAuth2 client. Never let the generic credential
|
|
// form create or replace its encrypted token bundle.
|
|
requireIntegrationsPermission(ctx, "integrations.connect");
|
|
throw redirect(kwpSetupPath(params.tenant ?? ""), 303);
|
|
}
|
|
if (appKey === "kwp" && intent === "manual-sync") {
|
|
// Pull/push is deliberately outside the callback slice. Never create a
|
|
// successful empty SyncRun through the generic Apps Engine action.
|
|
throw notFoundResponse();
|
|
}
|
|
if (appKey === "kwp" && intent === "disconnect") {
|
|
// A local-only clear would leave KWP's one-time refresh token valid at
|
|
// Keycloak. Hide and reject disconnect until provider revocation is part
|
|
// of the verified connector contract.
|
|
throw notFoundResponse();
|
|
}
|
|
|
|
// Collect the credential fields declared by the app's connectionSchema.
|
|
const readCredentials = (): Record<string, unknown> => {
|
|
const credentials: Record<string, unknown> = {};
|
|
for (const field of app.connectionSchema.fields) {
|
|
const value = form.get(field.name);
|
|
if (value != null) {
|
|
credentials[field.name] = value.toString();
|
|
}
|
|
}
|
|
return credentials;
|
|
};
|
|
|
|
try {
|
|
if (intent === "connect") {
|
|
requireIntegrationsPermission(ctx, "integrations.connect");
|
|
const created = await createConnection({
|
|
tenantId: ctx.tenantId,
|
|
appId: appKey,
|
|
label: form.get("label")?.toString() ?? "",
|
|
credentials: readCredentials(),
|
|
createdByUserId: ctx.userId,
|
|
});
|
|
return Response.json({
|
|
intent,
|
|
ok: true,
|
|
connectionId: created.id,
|
|
messageKey: "integrations.connections.feedback.connected",
|
|
});
|
|
}
|
|
if (intent === "reconnect") {
|
|
// Reconnect keeps the connection id (no history loss, DoD #6).
|
|
requireIntegrationsPermission(ctx, "integrations.connect");
|
|
await reconnectConnection({
|
|
tenantId: ctx.tenantId,
|
|
connectionId: form.get("connectionId")?.toString() ?? "",
|
|
expectedAppId: appKey,
|
|
credentials: readCredentials(),
|
|
actorUserId: ctx.userId,
|
|
});
|
|
return Response.json({
|
|
intent,
|
|
ok: true,
|
|
messageKey: "integrations.connections.feedback.reconnected",
|
|
});
|
|
}
|
|
if (intent === "disconnect") {
|
|
requireIntegrationsPermission(ctx, "integrations.disconnect");
|
|
await disconnectConnection({
|
|
tenantId: ctx.tenantId,
|
|
connectionId: form.get("connectionId")?.toString() ?? "",
|
|
expectedAppId: appKey,
|
|
actorUserId: ctx.userId,
|
|
});
|
|
return Response.json({
|
|
intent,
|
|
ok: true,
|
|
messageKey: "integrations.connections.feedback.disconnected",
|
|
});
|
|
}
|
|
if (intent === "manual-sync") {
|
|
requireIntegrationsPermission(ctx, "integrations.manual_sync");
|
|
const result = await runSyncForConnection({
|
|
tenantId: ctx.tenantId,
|
|
connectionId: form.get("connectionId")?.toString() ?? "",
|
|
expectedAppId: appKey,
|
|
kind: "manual",
|
|
createdByUserId: ctx.userId,
|
|
});
|
|
return Response.json({
|
|
intent,
|
|
ok: true,
|
|
runId: result.runId,
|
|
status: result.status,
|
|
messageKey: "integrations.connections.feedback.syncStarted",
|
|
});
|
|
}
|
|
return Response.json({ intent, error: "shared.invalidAction" }, { status: 400 });
|
|
} catch (error) {
|
|
if (error instanceof Response) {
|
|
throw error;
|
|
}
|
|
const response = integrationsActionErrorResponse(error);
|
|
const payload = (await response.json()) as Record<string, unknown>;
|
|
return Response.json({ ...payload, intent }, { status: response.status });
|
|
}
|
|
};
|
|
|
|
type MutationResponse = {
|
|
readonly intent?: string;
|
|
readonly ok?: boolean;
|
|
readonly messageKey?: string;
|
|
readonly error?: string;
|
|
};
|
|
|
|
export default function IntegrationsAppRoute() {
|
|
const { vm, connectionType, credentialFields, feedback } = useLoaderData<LoaderData>();
|
|
const fetcher = useFetcher<MutationResponse>();
|
|
const { csrf } = useRootData();
|
|
const [closeSignal, setCloseSignal] = useState(0);
|
|
const hadSubmission = useRef(false);
|
|
|
|
const submitting = fetcher.state !== "idle";
|
|
const errorMessage = fetcher.data?.error ?? null;
|
|
// Connect/reconnect/disconnect errors remain anchored in their open dialog.
|
|
// Manual sync has no dialog, so its failure must surface through the toast.
|
|
const hasInlineError =
|
|
fetcher.data?.error && ["connect", "reconnect", "disconnect"].includes(fetcher.data.intent ?? "");
|
|
const toastResult = hasInlineError ? undefined : fetcher.data;
|
|
useSaveToast(toastResult);
|
|
|
|
// Close the wizard/confirm dialogs once a mutation went through without error.
|
|
useEffect(() => {
|
|
if (fetcher.state !== "idle") {
|
|
hadSubmission.current = true;
|
|
return;
|
|
}
|
|
if (hadSubmission.current) {
|
|
hadSubmission.current = false;
|
|
if (!fetcher.data?.error) {
|
|
setCloseSignal((value) => value + 1);
|
|
}
|
|
}
|
|
}, [fetcher.state, fetcher.data]);
|
|
|
|
function post(fields: Record<string, string>) {
|
|
const formData = new FormData();
|
|
if (csrf) formData.set("csrf", csrf);
|
|
for (const [name, value] of Object.entries(fields)) {
|
|
formData.set(name, value);
|
|
}
|
|
fetcher.submit(formData, { method: "post" });
|
|
}
|
|
|
|
const actions: ConnectionDetailActions = {
|
|
onConnect: (input: ConnectWizardSubmit) => post({ intent: "connect", label: input.label, ...input.credentials }),
|
|
onReconnect: (connectionId: string, input: ConnectWizardSubmit) => post({ intent: "reconnect", connectionId, ...input.credentials }),
|
|
onDisconnect: (connectionId: string) => post({ intent: "disconnect", connectionId }),
|
|
onManualSync: (connectionId: string) => post({ intent: "manual-sync", connectionId }),
|
|
};
|
|
|
|
return (
|
|
<ConnectionDetailPage
|
|
vm={vm}
|
|
connectionType={connectionType}
|
|
credentialFields={credentialFields}
|
|
actions={actions}
|
|
submitting={submitting}
|
|
errorMessage={errorMessage}
|
|
feedback={feedback}
|
|
closeSignal={closeSignal}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|