187 lines
7.7 KiB
TypeScript
187 lines
7.7 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 { 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 {
|
|
badRequestResponse,
|
|
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 } from "~/utils/integrations/integrationsRoutePaths";
|
|
import { ConnectionDetailPage, type ConnectionDetailActions } from "~/components/screens/integrations/ConnectionDetailPage";
|
|
import type { ConnectWizardSubmit } from "~/components/screens/integrations/ConnectWizardDialog";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
|
|
type LoaderData = { title: string; backHref: string; vm: ConnectionDetailVM; connectionType: string; credentialFields: AppCredentialField[] };
|
|
|
|
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
|
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();
|
|
}
|
|
|
|
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: integrationsSyncsPath(tenantSlug, appKey, connection.id),
|
|
}));
|
|
|
|
const vm = buildConnectionDetailVM({
|
|
appKey,
|
|
appTitleKey: app.titleKey,
|
|
rows,
|
|
canConnect: integrationsHasPermission(ctx, "integrations.connect"),
|
|
canDisconnect: integrationsHasPermission(ctx, "integrations.disconnect"),
|
|
canManualSync: integrationsHasPermission(ctx, "integrations.manual_sync"),
|
|
connectHref: integrationsAppPath(tenantSlug, appKey),
|
|
});
|
|
return Response.json({
|
|
title: `${t("integrations.connections.title")} | ${process.env.APP_NAME}`,
|
|
backHref: integrationsCatalogPath(tenantSlug),
|
|
vm,
|
|
connectionType: app.connectionType,
|
|
credentialFields: [...app.connectionSchema.fields],
|
|
} 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();
|
|
}
|
|
const form = await request.formData();
|
|
const intent = form.get("intent")?.toString();
|
|
|
|
// 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({ ok: true, connectionId: created.id });
|
|
}
|
|
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() ?? "", credentials: readCredentials(), actorUserId: ctx.userId });
|
|
return Response.json({ ok: true });
|
|
}
|
|
if (intent === "disconnect") {
|
|
requireIntegrationsPermission(ctx, "integrations.disconnect");
|
|
await disconnectConnection({ tenantId: ctx.tenantId, connectionId: form.get("connectionId")?.toString() ?? "", actorUserId: ctx.userId });
|
|
return Response.json({ ok: true });
|
|
}
|
|
if (intent === "manual-sync") {
|
|
requireIntegrationsPermission(ctx, "integrations.manual_sync");
|
|
const result = await runSyncForConnection({ tenantId: ctx.tenantId, connectionId: form.get("connectionId")?.toString() ?? "", kind: "manual", createdByUserId: ctx.userId });
|
|
return Response.json({ ok: true, runId: result.runId, status: result.status });
|
|
}
|
|
throw badRequestResponse();
|
|
} catch (error) {
|
|
if (error instanceof Response) {
|
|
throw error;
|
|
}
|
|
return integrationsActionErrorResponse(error);
|
|
}
|
|
};
|
|
|
|
type MutationResponse = { ok?: boolean; error?: string };
|
|
|
|
export default function IntegrationsAppRoute() {
|
|
const { backHref, vm, connectionType, credentialFields } = useLoaderData<LoaderData>();
|
|
const fetcher = useFetcher<MutationResponse>();
|
|
const [closeSignal, setCloseSignal] = useState(0);
|
|
const hadSubmission = useRef(false);
|
|
|
|
const submitting = fetcher.state !== "idle";
|
|
const errorMessage = fetcher.data?.error ?? null;
|
|
|
|
// 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();
|
|
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}
|
|
backHref={backHref}
|
|
actions={actions}
|
|
submitting={submitting}
|
|
errorMessage={errorMessage}
|
|
closeSignal={closeSignal}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|