Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+350
@@ -0,0 +1,350 @@
|
||||
import {
|
||||
buildWebhookInboxVM,
|
||||
type WebhookInboxData,
|
||||
type WebhookInboxInputRow,
|
||||
type WebhookInboxRow,
|
||||
type WebhookInboxStatus,
|
||||
type WebhookInboxVM,
|
||||
} from "@hivegrid/view-models";
|
||||
import { Activity, AlertTriangle, CheckCircle2, Clock3, ExternalLink, RadioTower, ShieldQuestion } from "lucide-react";
|
||||
import type React from "react";
|
||||
import { Form, Link, LoaderFunctionArgs, MetaFunction, useActionData, useLoaderData, useNavigation, type ActionFunctionArgs } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Badge, type BadgeColor } from "~/components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { redactDiagnosticJsonString } from "~/utils/redaction";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { AdminActionInputError } from "~/services/admin/admin-action-audit.server";
|
||||
import { AdminWebhookInboxError, requestWebhookReplay } from "~/services/admin/webhook-inbox.server";
|
||||
|
||||
const WEBHOOK_FILTERS = ["all", "failed", "pending", "delivered", "unknown"] as const;
|
||||
|
||||
type WebhookFilter = (typeof WEBHOOK_FILTERS)[number];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
vm: WebhookInboxVM;
|
||||
filter: WebhookFilter;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.events.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const filter = parseWebhookFilter(new URL(request.url).searchParams.get("status"));
|
||||
|
||||
const attempts = await db.eventWebhookAttempt.findMany({
|
||||
take: 100,
|
||||
include: {
|
||||
event: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
resource: true,
|
||||
tenantId: true,
|
||||
userId: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
|
||||
const inputRows: WebhookInboxInputRow[] = attempts.map((attempt) => ({
|
||||
id: attempt.id,
|
||||
eventId: attempt.eventId,
|
||||
eventName: attempt.event.name,
|
||||
eventResource: attempt.event.resource,
|
||||
tenantId: attempt.event.tenantId,
|
||||
userId: attempt.event.userId,
|
||||
endpoint: attempt.endpoint,
|
||||
success: attempt.success,
|
||||
status: attempt.status,
|
||||
message: localizeKnownWebhookMessage(attempt.message, t),
|
||||
body: redactDiagnosticJsonString(attempt.body),
|
||||
createdAt: attempt.createdAt.toISOString(),
|
||||
startedAt: attempt.startedAt?.toISOString() ?? null,
|
||||
finishedAt: attempt.finishedAt?.toISOString() ?? null,
|
||||
}));
|
||||
|
||||
const vm = filterWebhookInboxVM(buildWebhookInboxVM({ rows: inputRows }), filter);
|
||||
|
||||
return {
|
||||
title: `${t("admin.webhooks.title")} | ${process.env.APP_NAME}`,
|
||||
vm,
|
||||
filter,
|
||||
} satisfies LoaderData;
|
||||
};
|
||||
|
||||
function localizeKnownWebhookMessage(message: string | null, t: (key: string) => string): string | null {
|
||||
if (message === "admin.webhooks.messages.replayRequested" || message === "Admin replay requested.") {
|
||||
return t("admin.webhooks.messages.replayRequested");
|
||||
}
|
||||
if (message === "admin.webhooks.messages.queueUnavailable" || message === "Webhook delivery queue is unavailable.") {
|
||||
return t("admin.webhooks.messages.queueUnavailable");
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
function badRequest(data: ActionData) {
|
||||
return Response.json(data, { status: 400 });
|
||||
}
|
||||
|
||||
function webhookActionErrorKey(error: unknown): string {
|
||||
if (error instanceof AdminWebhookInboxError || error instanceof AdminActionInputError) return error.i18nKey;
|
||||
return "admin.webhooks.errors.UNKNOWN";
|
||||
}
|
||||
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.events.view");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
if (action !== "request-replay") {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
|
||||
const userInfo = await getUserInfo(request);
|
||||
const actor = await getUser(userInfo.userId);
|
||||
|
||||
try {
|
||||
const result = await requestWebhookReplay({
|
||||
attemptId: form.get("attemptId")?.toString() ?? "",
|
||||
reason: form.get("reason")?.toString() ?? "",
|
||||
actorUserId: userInfo.userId,
|
||||
actorEmail: actor?.email ?? null,
|
||||
request,
|
||||
});
|
||||
return Response.json({ success: t("admin.webhooks.actions.replayRequested", { attemptId: result.replayAttemptId }) } satisfies ActionData);
|
||||
} catch (error) {
|
||||
return badRequest({ error: t(webhookActionErrorKey(error)) });
|
||||
}
|
||||
};
|
||||
|
||||
export default function AdminWebhooksRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigation = useNavigation();
|
||||
const rootData = useRootData();
|
||||
const rows = data.vm.status === "ready" ? data.vm.data.rows : [];
|
||||
const summary = data.vm.status === "ready" ? data.vm.data.summary : null;
|
||||
const loading = navigation.state === "submitting";
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("admin.webhooks.title")}
|
||||
buttons={
|
||||
<Link to={adminPath("events", { mode: "host-aware" })} className="text-primary inline-flex items-center gap-1 text-sm font-medium hover:underline">
|
||||
{t("admin.webhooks.links.events")}
|
||||
<ExternalLink className="size-4" aria-hidden="true" />
|
||||
</Link>
|
||||
}
|
||||
fullWidth
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<div className="border-border bg-surface-neutral-primary rounded-md border p-4">
|
||||
<div className="text-muted-foreground text-sm">{t("admin.webhooks.description")}</div>
|
||||
{actionData?.success && <div className="mt-3 rounded-md bg-green-50 px-3 py-2 text-sm text-green-800">{actionData.success}</div>}
|
||||
{actionData?.error && <div className="mt-3 rounded-md bg-red-50 px-3 py-2 text-sm text-red-800">{actionData.error}</div>}
|
||||
</div>
|
||||
|
||||
{summary ? <WebhookSummaryGrid summary={summary} /> : null}
|
||||
<WebhookFilters active={data.filter} />
|
||||
|
||||
{data.vm.status === "empty" ? (
|
||||
<div className="border-border bg-background rounded-md border p-6">
|
||||
<div className="font-medium">{t("admin.webhooks.empty.headline")}</div>
|
||||
<div className="text-muted-foreground mt-1 text-sm">{t("admin.webhooks.empty.body")}</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{rows.map((row) => (
|
||||
<WebhookAttemptCard key={row.id} row={row} csrf={rootData.csrf} loading={loading} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
function filterWebhookInboxVM(vm: WebhookInboxVM, filter: WebhookFilter): WebhookInboxVM {
|
||||
if (filter === "all" || vm.status !== "ready") return vm;
|
||||
const rows = vm.data.rows.filter((row) => row.deliveryStatus === filter);
|
||||
if (rows.length === 0) return { status: "empty" };
|
||||
return buildWebhookInboxVM({ rows });
|
||||
}
|
||||
|
||||
function parseWebhookFilter(value: string | null): WebhookFilter {
|
||||
return WEBHOOK_FILTERS.includes(value as WebhookFilter) ? (value as WebhookFilter) : "all";
|
||||
}
|
||||
|
||||
function WebhookFilters({ active }: { active: WebhookFilter }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{WEBHOOK_FILTERS.map((filter) => (
|
||||
<Link
|
||||
key={filter}
|
||||
to={adminPath(filter === "all" ? "webhooks" : `webhooks?status=${filter}`, { mode: "host-aware" })}
|
||||
className={`rounded-md border px-3 py-2 text-sm font-medium ${
|
||||
active === filter ? "border-foreground bg-foreground text-background" : "border-border bg-background text-foreground hover:bg-muted"
|
||||
}`}
|
||||
>
|
||||
{t(`admin.webhooks.filters.${filter}`)}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WebhookSummaryGrid({ summary }: { summary: WebhookInboxData["summary"] }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-5">
|
||||
<WebhookSummaryCard title={t("admin.webhooks.summary.total")} value={summary.totalCount} icon={<RadioTower className="size-5" aria-hidden="true" />} tone="neutral" />
|
||||
<WebhookSummaryCard title={t("admin.webhooks.summary.failed")} value={summary.failedCount} icon={<AlertTriangle className="size-5" aria-hidden="true" />} tone={summary.failedCount > 0 ? "danger" : "success"} />
|
||||
<WebhookSummaryCard title={t("admin.webhooks.summary.pending")} value={summary.pendingCount} icon={<Clock3 className="size-5" aria-hidden="true" />} tone={summary.pendingCount > 0 ? "warning" : "success"} />
|
||||
<WebhookSummaryCard title={t("admin.webhooks.summary.delivered")} value={summary.deliveredCount} icon={<CheckCircle2 className="size-5" aria-hidden="true" />} tone="success" />
|
||||
<WebhookSummaryCard title={t("admin.webhooks.summary.unknown")} value={summary.unknownCount} icon={<ShieldQuestion className="size-5" aria-hidden="true" />} tone={summary.unknownCount > 0 ? "warning" : "success"} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WebhookSummaryCard({
|
||||
title,
|
||||
value,
|
||||
icon,
|
||||
tone,
|
||||
}: {
|
||||
title: string;
|
||||
value: number;
|
||||
icon: React.ReactNode;
|
||||
tone: "success" | "warning" | "danger" | "neutral";
|
||||
}) {
|
||||
return (
|
||||
<Card className="gap-4 rounded-lg py-5">
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<CardTitle className="text-sm leading-5">{title}</CardTitle>
|
||||
<div className={`flex size-10 shrink-0 items-center justify-center rounded-md border ${toneIconClasses(tone)}`}>{icon}</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-semibold leading-7">{value}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function WebhookAttemptCard({ row, csrf, loading }: { row: WebhookInboxRow; csrf?: string; loading: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
return (
|
||||
<div className="border-border bg-background rounded-md border p-4">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge color={statusColor(row.deliveryStatus)} withColorDot>
|
||||
{t(row.statusLabelKey)}
|
||||
</Badge>
|
||||
<Badge color="gray">{t(row.providerLabelKey)}</Badge>
|
||||
{row.status ? <Badge color="gray">HTTP {row.status}</Badge> : null}
|
||||
</div>
|
||||
<div className="text-foreground mt-2 font-semibold break-all">{row.eventName}</div>
|
||||
<div className="text-muted-foreground mt-1 text-sm break-all">{row.endpoint}</div>
|
||||
</div>
|
||||
<div className="text-muted-foreground text-right text-xs">
|
||||
<div>{formatters.dateTime(new Date(row.createdAt))}</div>
|
||||
{row.durationMs !== null ? <div>{t("admin.webhooks.fields.durationMs", { duration: row.durationMs })}</div> : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-4 md:grid-cols-[1fr_1fr_2fr]">
|
||||
<WebhookField label={t("admin.webhooks.fields.tenant")} value={row.tenantId} />
|
||||
<WebhookField label={t("admin.webhooks.fields.resource")} value={row.eventResource} />
|
||||
<WebhookField label={t("admin.webhooks.fields.message")} value={row.message} />
|
||||
</div>
|
||||
|
||||
<div className="border-border bg-muted/40 mt-4 rounded-md border p-3">
|
||||
<div className="text-muted-foreground mb-2 flex items-center gap-2 text-xs font-medium uppercase">
|
||||
<Activity className="size-4" aria-hidden="true" />
|
||||
{t("admin.webhooks.fields.payloadPreview")}
|
||||
</div>
|
||||
<pre className="text-foreground max-h-36 overflow-auto whitespace-pre-wrap break-words text-xs leading-5">{row.payloadPreview || t("shared.notSet")}</pre>
|
||||
</div>
|
||||
|
||||
{row.deliveryStatus === "failed" ? <WebhookReplayForm row={row} csrf={csrf} loading={loading} /> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WebhookReplayForm({ row, csrf, loading }: { row: WebhookInboxRow; csrf?: string; loading: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Form method="post" className="border-border mt-4 grid gap-3 border-t pt-4 md:grid-cols-[minmax(180px,1fr)_auto]">
|
||||
<input type="hidden" name="csrf" value={csrf ?? ""} />
|
||||
<input type="hidden" name="action" value="request-replay" />
|
||||
<input type="hidden" name="attemptId" value={row.id} />
|
||||
<label className="text-muted-foreground space-y-1 text-xs font-medium">
|
||||
{t("admin.webhooks.fields.replayReason")}
|
||||
<input
|
||||
className="border-border bg-background text-foreground h-9 w-full rounded-md border px-3 text-sm"
|
||||
name="reason"
|
||||
placeholder={t("admin.webhooks.placeholders.replayReason")}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<div className="flex items-end">
|
||||
<ButtonPrimary type="submit" disabled={loading} className="h-9 px-3 text-xs">
|
||||
{t("admin.webhooks.actions.requestReplay")}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
function WebhookField({ label, value }: { label: string; value: string | null }) {
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<div className="text-muted-foreground text-xs font-medium uppercase">{label}</div>
|
||||
<div className="text-foreground text-sm break-all">{value || "-"}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function statusColor(status: WebhookInboxStatus): BadgeColor {
|
||||
if (status === "delivered") return "green";
|
||||
if (status === "failed") return "red";
|
||||
if (status === "pending") return "yellow";
|
||||
return "gray";
|
||||
}
|
||||
|
||||
function toneIconClasses(tone: "success" | "warning" | "danger" | "neutral") {
|
||||
if (tone === "success") return "border-green-500 bg-green-500/5 text-green-700";
|
||||
if (tone === "warning") return "border-yellow-500 bg-yellow-500/5 text-yellow-700";
|
||||
if (tone === "danger") return "border-red-500 bg-red-500/5 text-red-700";
|
||||
return "border-gray-500 bg-gray-500/5 text-gray-700";
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
Reference in new issue
Block a user