Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/components/screens/automation/AutomationExecutionsPage.tsx
T

338 lines
16 KiB
TypeScript

import { useEffect, useMemo, useState } from "react";
import { Form as RouterForm, Link } from "react-router";
import { useTranslation } from "react-i18next";
import {
FeatherActivity,
FeatherAlertTriangle,
FeatherCalendar,
FeatherCheckCircle,
FeatherChevronLeft,
FeatherChevronRight,
FeatherClock,
FeatherPencilRuler,
FeatherPlay,
FeatherTimer,
FeatherZap,
} from "@subframe/core";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { EmptyState } from "~/ui/components/EmptyState";
import { SearchInput } from "~/ui/components/SearchInput";
import { Select } from "~/ui/components/Select";
import { StatsCard } from "~/ui/components/StatsCard";
import { Switch } from "~/ui/components/Switch";
import { Table } from "~/ui/components/Table";
import { Tag_Label } from "~/ui/components/Tag_Label";
import type { AutomationExecutionListVM, AutomationExecutionsActionData } from "~/services/automation/automation.server";
import { useLocaleFormatters } from "~/locale/format";
import { useRootData } from "~/utils/data/useRootData";
import {
AutomationStatusBadge,
automationStatusLabel,
errorMessage,
formatDurationMs,
localizedValue,
nodeTitle,
statusBadgeTone,
} from "./automationUi";
import { ProbelaufDialog } from "./dialogs/ProbelaufDialog";
const PAGE_SIZE = 10;
const STATUS_OPTIONS = ["success", "failed", "skipped", "running", "queued", "paused"] as const;
type PeriodFilter = "all" | "today" | "7d" | "30d";
/** WF-P12 S02: execution list for one rule with stats, filters and pagination. */
export function AutomationExecutionsPage({
vm,
actionData,
}: {
vm: AutomationExecutionListVM;
actionData?: AutomationExecutionsActionData;
}): React.JSX.Element {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const csrf = useRootData().csrf ?? "";
const [query, setQuery] = useState("");
const [statusFilter, setStatusFilter] = useState<string>("all");
const [periodFilter, setPeriodFilter] = useState<PeriodFilter>("all");
const [onlyDryRuns, setOnlyDryRuns] = useState(false);
const [page, setPage] = useState(0);
const [dryRunOpen, setDryRunOpen] = useState(false);
// A dry-run submit re-renders with fresh actionData; keep the dialog visible
// so the preview result lands where the user started the run.
useEffect(() => {
if (actionData?.dryRunPreview) setDryRunOpen(true);
}, [actionData]);
const filtered = useMemo(() => {
const needle = query.trim().toLowerCase();
const now = Date.now();
const periodStart =
periodFilter === "today"
? new Date(new Date().setHours(0, 0, 0, 0)).getTime()
: periodFilter === "7d"
? now - 7 * 24 * 60 * 60 * 1000
: periodFilter === "30d"
? now - 30 * 24 * 60 * 60 * 1000
: null;
return vm.executions.filter((execution) => {
if (statusFilter !== "all" && execution.status !== statusFilter) return false;
if (onlyDryRuns && !execution.dryRun) return false;
if (periodStart !== null && new Date(execution.createdAt).getTime() < periodStart) return false;
if (needle && !`${execution.summaryText} ${execution.errorText ?? ""}`.toLowerCase().includes(needle)) return false;
return true;
});
}, [vm.executions, query, statusFilter, periodFilter, onlyDryRuns]);
const pageCount = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
const safePage = Math.min(page, pageCount - 1);
const pageRows = filtered.slice(safePage * PAGE_SIZE, safePage * PAGE_SIZE + PAGE_SIZE);
const resetPage = () => setPage(0);
return (
<div className="flex w-full flex-col items-start bg-surface-neutral-primary">
<div className="flex w-full flex-col items-start gap-3 border-b border-solid border-border-default bg-surface-neutral-secondary px-6 py-4 mobile:px-4">
<div className="flex w-full items-center gap-4 mobile:flex-col mobile:items-start">
<div className="flex grow shrink-0 basis-0 items-center gap-3">
<FeatherZap className="text-heading- font-heading- text-icon-neutral-tertiary" />
<span className="text-heading- font-heading- text-text-neutral-primary">{t("automation.executions.title")}</span>
<BadgeFeedback farbe={statusBadgeTone(vm.rule.status)}>
{automationStatusLabel(t, vm.rule.status)}
</BadgeFeedback>
</div>
<div className="flex items-center gap-2 mobile:w-full mobile:flex-none mobile:flex-wrap">
<Link to={vm.rule.editUrl} className="inline-flex">
<Button type="button" variant="tertiary" icon={<FeatherPencilRuler />}>
{t("automation.executions.openEditor")}
</Button>
</Link>
{vm.canRun || vm.canManage ? (
<>
<RouterForm method="post" className="inline-flex">
<input type="hidden" name="csrf" value={csrf} readOnly />
<input type="hidden" name="intent" value="run-now" readOnly />
<Button type="submit" variant="secondary" icon={<FeatherZap />} disabled={vm.rule.status !== "active"}>
{t("automation.executions.runNow.button")}
</Button>
</RouterForm>
<Button type="button" icon={<FeatherPlay />} onClick={() => setDryRunOpen(true)}>
{t("automation.editor.dryRun.start")}
</Button>
</>
) : null}
</div>
</div>
{actionData && !actionData.dryRunPreview ? (
<BadgeFeedback farbe={actionData.ok ? "subtle-positive" : "subtle-negative"}>
{t(actionData.ok ? actionData.messageKey : actionData.errorKey)}
</BadgeFeedback>
) : null}
</div>
<div className="flex w-full flex-col items-start gap-6 px-6 py-6 mobile:px-4">
<div className="flex w-full items-start gap-4 mobile:flex-col">
<StatsCard
trend="neutral"
label={t("automation.detail.lastExecution")}
value={
vm.stats.lastExecutionAt
? formatters.date(vm.stats.lastExecutionAt, { dateStyle: "medium", timeStyle: "short" })
: t("automation.values.never")
}
percentage={
vm.stats.lastExecutionStatus
? automationStatusLabel(t, vm.stats.lastExecutionStatus)
: undefined
}
icon={<FeatherClock />}
/>
<StatsCard
trend={vm.stats.successRate30d !== null && vm.stats.successRate30d >= 90 ? "positive" : "neutral"}
label={t("automation.executions.stats.successRate30d")}
value={vm.stats.successRate30d !== null ? formatters.percent(vm.stats.successRate30d / 100, { maximumFractionDigits: 1 }) : "—"}
icon={<FeatherCheckCircle />}
/>
<StatsCard
trend={vm.stats.failed30d > 0 ? "negative" : "neutral"}
label={t("automation.executions.stats.failed30d")}
value={formatters.number(vm.stats.failed30d)}
icon={<FeatherAlertTriangle />}
/>
<StatsCard
trend="neutral"
label={t("automation.executions.stats.avgDuration")}
value={vm.stats.avgDurationMs !== null ? formatDurationMs(t, formatters, vm.stats.avgDurationMs) : "—"}
icon={<FeatherTimer />}
/>
</div>
<div className="flex w-full flex-wrap items-center gap-3 mobile:flex-col mobile:flex-nowrap mobile:items-stretch">
<SearchInput
className="h-8 w-72 flex-none mobile:w-full"
size="small"
hideShortcut
placeholder={t("automation.executions.filters.searchPlaceholder")}
value={query}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
setQuery(event.target.value);
resetPage();
}}
/>
<Select
className="h-8 w-44 flex-none mobile:w-full"
variant="filled"
size="small"
placeholder={t("automation.executions.filters.statusLabel")}
icon={<FeatherActivity />}
value={statusFilter}
onValueChange={(value: string) => {
setStatusFilter(value);
resetPage();
}}
>
<Select.Item value="all">{t("automation.executions.filters.statusAll")}</Select.Item>
{STATUS_OPTIONS.map((status) => (
<Select.Item key={status} value={status}>
{t(`automation.status.${status}`)}
</Select.Item>
))}
</Select>
<Select
className="h-8 w-44 flex-none mobile:w-full"
variant="filled"
size="small"
placeholder={t("automation.executions.filters.periodLabel")}
icon={<FeatherCalendar />}
value={periodFilter}
onValueChange={(value: string) => {
setPeriodFilter(value as PeriodFilter);
resetPage();
}}
>
<Select.Item value="today">{t("automation.executions.filters.periodToday")}</Select.Item>
<Select.Item value="7d">{t("automation.executions.filters.period7d")}</Select.Item>
<Select.Item value="30d">{t("automation.executions.filters.period30d")}</Select.Item>
<Select.Item value="all">{t("automation.executions.filters.periodAll")}</Select.Item>
</Select>
<div className="flex grow shrink-0 basis-0 items-center justify-end gap-2 mobile:justify-start">
<Switch
checked={onlyDryRuns}
onCheckedChange={(checked: boolean) => {
setOnlyDryRuns(checked);
resetPage();
}}
/>
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-secondary">
{t("automation.executions.filters.onlyDryRuns")}
</span>
</div>
</div>
{vm.executions.length === 0 ? (
<EmptyState outlined title={t("automation.empty.executions")} body={t("automation.executions.subtitle", { trigger: nodeTitle(t, vm.rule.triggerKey) })} />
) : filtered.length === 0 ? (
<EmptyState outlined variant="no-results" title={t("automation.executions.noMatches.title")} body={t("automation.executions.noMatches.body")} />
) : (
<>
<div className="flex w-full flex-col items-start overflow-hidden rounded-lg border border-solid border-border-default shadow-sm overflow-x-auto">
<Table
header={
<Table.HeaderRow className="bg-surface-neutral-tertiary">
<Table.HeaderCell icon={<FeatherClock />}>{t("automation.executions.columns.time")}</Table.HeaderCell>
<Table.HeaderCell icon={<FeatherActivity />}>{t("automation.detail.status")}</Table.HeaderCell>
<Table.HeaderCell>{t("automation.executions.columns.summary")}</Table.HeaderCell>
<Table.HeaderCell>{t("automation.executions.columns.kind")}</Table.HeaderCell>
<Table.HeaderCell icon={<FeatherTimer />}>{t("automation.detail.duration")}</Table.HeaderCell>
<Table.HeaderCell />
</Table.HeaderRow>
}
>
{pageRows.map((execution) => (
<Table.Row key={execution.id} className="cursor-pointer" clickable>
<Table.Cell>
<span className="whitespace-nowrap text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary">
{formatters.date(execution.createdAt, { dateStyle: "medium", timeStyle: "short" })}
</span>
</Table.Cell>
<Table.Cell>
<AutomationStatusBadge status={execution.status} />
</Table.Cell>
<Table.Cell>
<div className="flex max-w-[360px] flex-col items-start">
<span className="line-clamp-1 text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">
{localizedValue(t, execution.summaryText, "automation.values.unknownSummary")}
</span>
{execution.status === "failed" && execution.errorText ? (
<span className="line-clamp-1 text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative">
{errorMessage(t, execution.errorText)}
</span>
) : null}
</div>
</Table.Cell>
<Table.Cell>
<Tag_Label tone={execution.dryRun ? "violet-subtle" : "neutral-subtle"} noAction size="small">
{execution.dryRun ? t("automation.executions.kind.dryRun") : t("automation.executions.kind.live")}
</Tag_Label>
</Table.Cell>
<Table.Cell>
<span className="whitespace-nowrap text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">
{execution.durationMs !== null ? formatDurationMs(t, formatters, execution.durationMs) : "—"}
</span>
</Table.Cell>
<Table.Cell>
<div className="flex w-full items-center justify-end">
<Link to={execution.detailUrl} className="inline-flex">
<Button type="button" variant="tertiary" size="small" iconRight={<FeatherChevronRight />}>
{t("automation.executions.details")}
</Button>
</Link>
</div>
</Table.Cell>
</Table.Row>
))}
</Table>
</div>
<div className="flex w-full items-center gap-3 pb-4 mobile:flex-col mobile:items-start">
<span className="grow shrink-0 basis-0 text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("automation.executions.pagination.range", {
from: formatters.number(safePage * PAGE_SIZE + 1),
to: formatters.number(Math.min((safePage + 1) * PAGE_SIZE, filtered.length)),
total: formatters.number(filtered.length),
})}
</span>
<div className="flex items-center gap-2">
<Button
type="button"
disabled={safePage === 0}
variant="tertiary"
size="small"
icon={<FeatherChevronLeft />}
onClick={() => setPage(Math.max(0, safePage - 1))}
>
{t("automation.executions.pagination.previous")}
</Button>
<Button
type="button"
disabled={safePage >= pageCount - 1}
variant="tertiary"
size="small"
iconRight={<FeatherChevronRight />}
onClick={() => setPage(Math.min(pageCount - 1, safePage + 1))}
>
{t("automation.executions.pagination.next")}
</Button>
</div>
</div>
</>
)}
</div>
<ProbelaufDialog vm={vm} csrf={csrf} actionData={actionData} open={dryRunOpen} onOpenChange={setDryRunOpen} />
</div>
);
}