mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-07 05:11:51 +08:00
- Add full-width multi-tab area/line trend chart above Activity & Findings on /dashboard. - Support 7d/14d/30d local day buckets across findings, container creations, and task/finding lifecycle. - Add bilingual i18n keys, mock /sandbox/status route, and migrated-page i18n test coverage.
479 lines
17 KiB
TypeScript
479 lines
17 KiB
TypeScript
"use client";
|
|
|
|
import * as React from "react";
|
|
|
|
import Link from "next/link";
|
|
|
|
import { ArrowUpRightIcon } from "lucide-react";
|
|
import { Area, AreaChart, CartesianGrid, Tooltip as RechartsTooltip, XAxis, YAxis } from "recharts";
|
|
|
|
import { Badge } from "@/components/ui/badge";
|
|
import { Card } from "@/components/ui/card";
|
|
import { type ChartConfig, ChartContainer } from "@/components/ui/chart";
|
|
import { useLiveTranslation } from "@/i18n/use-live-translation";
|
|
import type { ActiveFindingRetest, Finding, FindingStatus, SandboxGlobalStatus, Task } from "@/lib/types";
|
|
import { cn } from "@/lib/utils";
|
|
|
|
type TrendTab = "findings" | "containers" | "lifecycle";
|
|
type WindowDays = 7 | 14 | 30;
|
|
|
|
interface DayBucket {
|
|
dayKey: string;
|
|
label: string;
|
|
findingsTotal: number;
|
|
findingsHighCrit: number;
|
|
findingsMedLow: number;
|
|
findingsClosed: number;
|
|
containersCreated: number;
|
|
containersRunning: number;
|
|
containersTask: number;
|
|
containersSession: number;
|
|
tasksCreated: number;
|
|
tasksCompleted: number;
|
|
}
|
|
|
|
const CLOSED_FINDING_STATUS: Partial<Record<FindingStatus, true>> = {
|
|
resolved: true,
|
|
fixed: true,
|
|
false_positive: true,
|
|
ignored: true,
|
|
duplicate: true,
|
|
risk_accepted: true,
|
|
};
|
|
|
|
const WINDOW_OPTIONS: readonly WindowDays[] = [7, 14, 30];
|
|
|
|
function toLocalDayKey(date: Date): string {
|
|
const y = date.getFullYear();
|
|
const m = String(date.getMonth() + 1).padStart(2, "0");
|
|
const d = String(date.getDate()).padStart(2, "0");
|
|
return `${y}-${m}-${d}`;
|
|
}
|
|
|
|
function parseTimestamp(ts?: string | number): Date | null {
|
|
if (!ts) return null;
|
|
if (typeof ts === "number") {
|
|
if (ts <= 0) return null;
|
|
const d = new Date(ts * 1000);
|
|
return Number.isNaN(d.getTime()) ? null : d;
|
|
}
|
|
const ms = Date.parse(ts);
|
|
if (Number.isNaN(ms)) return null;
|
|
return new Date(ms);
|
|
}
|
|
|
|
export function EnvironmentLifecycleRow({
|
|
sandboxStatus,
|
|
findings,
|
|
tasks,
|
|
activeRetests,
|
|
}: {
|
|
sandboxStatus: SandboxGlobalStatus | null;
|
|
findings: Finding[];
|
|
tasks: Task[];
|
|
activeRetests: ActiveFindingRetest[];
|
|
}) {
|
|
const { t: translate } = useLiveTranslation();
|
|
const [tab, setTab] = React.useState<TrendTab>("findings");
|
|
const [days, setDays] = React.useState<WindowDays>(7);
|
|
|
|
const { buckets, summary } = React.useMemo(() => {
|
|
const today = new Date();
|
|
today.setHours(0, 0, 0, 0);
|
|
|
|
const list: DayBucket[] = [];
|
|
const byKey = new Map<string, DayBucket>();
|
|
for (let i = days - 1; i >= 0; i--) {
|
|
const d = new Date(today);
|
|
d.setDate(today.getDate() - i);
|
|
const dayKey = toLocalDayKey(d);
|
|
const bucket: DayBucket = {
|
|
dayKey,
|
|
label: dayKey.slice(5).replace("-", "/"),
|
|
findingsTotal: 0,
|
|
findingsHighCrit: 0,
|
|
findingsMedLow: 0,
|
|
findingsClosed: 0,
|
|
containersCreated: 0,
|
|
containersRunning: 0,
|
|
containersTask: 0,
|
|
containersSession: 0,
|
|
tasksCreated: 0,
|
|
tasksCompleted: 0,
|
|
};
|
|
list.push(bucket);
|
|
byKey.set(dayKey, bucket);
|
|
}
|
|
|
|
let windowFindings = 0;
|
|
let windowHighCrit = 0;
|
|
let windowClosedFindings = 0;
|
|
let totalClosedFindings = 0;
|
|
|
|
for (const f of findings) {
|
|
const isClosed = Boolean(CLOSED_FINDING_STATUS[f.status]);
|
|
if (isClosed) totalClosedFindings++;
|
|
const dt = parseTimestamp(f.ts);
|
|
if (!dt) continue;
|
|
const bucket = byKey.get(toLocalDayKey(dt));
|
|
if (!bucket) continue;
|
|
bucket.findingsTotal++;
|
|
windowFindings++;
|
|
if (f.severity === "critical" || f.severity === "high") {
|
|
bucket.findingsHighCrit++;
|
|
windowHighCrit++;
|
|
} else {
|
|
bucket.findingsMedLow++;
|
|
}
|
|
if (isClosed) {
|
|
bucket.findingsClosed++;
|
|
windowClosedFindings++;
|
|
}
|
|
}
|
|
|
|
const containers = Array.isArray(sandboxStatus?.containers) ? sandboxStatus.containers : [];
|
|
let windowContainersCreated = 0;
|
|
let currentRunningContainers = 0;
|
|
let currentStoppedContainers = 0;
|
|
|
|
for (const c of containers) {
|
|
if (c.state === "running") currentRunningContainers++;
|
|
else currentStoppedContainers++;
|
|
const dt = parseTimestamp(c.created_at);
|
|
if (!dt) continue;
|
|
const bucket = byKey.get(toLocalDayKey(dt));
|
|
if (!bucket) continue;
|
|
bucket.containersCreated++;
|
|
windowContainersCreated++;
|
|
if (c.state === "running") bucket.containersRunning++;
|
|
if (c.scope === "task") bucket.containersTask++;
|
|
else if (c.scope === "session") bucket.containersSession++;
|
|
}
|
|
|
|
let windowTasksCreated = 0;
|
|
let windowTasksCompleted = 0;
|
|
|
|
for (const t of tasks) {
|
|
const createdDt = parseTimestamp(t.created_unix ?? t.created_at);
|
|
if (createdDt) {
|
|
const b = byKey.get(toLocalDayKey(createdDt));
|
|
if (b) {
|
|
b.tasksCreated++;
|
|
windowTasksCreated++;
|
|
}
|
|
}
|
|
const completedDt = parseTimestamp(t.completed_unix && t.completed_unix > 0 ? t.completed_unix : t.completed_at);
|
|
if (completedDt) {
|
|
const b = byKey.get(toLocalDayKey(completedDt));
|
|
if (b) {
|
|
b.tasksCompleted++;
|
|
windowTasksCompleted++;
|
|
}
|
|
}
|
|
}
|
|
|
|
const closureRate = findings.length > 0 ? Math.round((totalClosedFindings / findings.length) * 100) : 0;
|
|
|
|
return {
|
|
buckets: list,
|
|
summary: {
|
|
windowFindings,
|
|
windowHighCrit,
|
|
windowClosedFindings,
|
|
windowContainersCreated,
|
|
currentRunningContainers,
|
|
currentStoppedContainers,
|
|
windowTasksCreated,
|
|
windowTasksCompleted,
|
|
closureRate,
|
|
},
|
|
};
|
|
}, [days, findings, sandboxStatus, tasks]);
|
|
|
|
const seriesByTab = {
|
|
findings: {
|
|
primaryKey: "findingsTotal" as const,
|
|
primaryLabel: translate("overview.trendSeriesFindings"),
|
|
secondaryKey: "findingsHighCrit" as const,
|
|
secondaryLabel: translate("overview.trendSeriesHighCrit"),
|
|
secondaryColor: "#f43f5e",
|
|
},
|
|
containers: {
|
|
primaryKey: "containersCreated" as const,
|
|
primaryLabel: translate("overview.trendSeriesContainersCreated"),
|
|
secondaryKey: "containersRunning" as const,
|
|
secondaryLabel: translate("overview.trendSeriesContainersRunning"),
|
|
secondaryColor: "#10b981",
|
|
},
|
|
lifecycle: {
|
|
primaryKey: "tasksCreated" as const,
|
|
primaryLabel: translate("overview.trendSeriesTasksCreated"),
|
|
secondaryKey: "tasksCompleted" as const,
|
|
secondaryLabel: translate("overview.trendSeriesTasksCompleted"),
|
|
secondaryColor: "#10b981",
|
|
},
|
|
};
|
|
const activeSeries = seriesByTab[tab];
|
|
|
|
const chartConfig: ChartConfig = {
|
|
primary: { label: activeSeries.primaryLabel, color: "#2563eb" },
|
|
secondary: { label: activeSeries.secondaryLabel, color: activeSeries.secondaryColor },
|
|
};
|
|
|
|
const formatTick = (value: number) => translate("overview.trendYAxisTick", { count: value });
|
|
|
|
let sandboxBadge: React.ReactNode = null;
|
|
if (tab === "containers" && sandboxStatus) {
|
|
if (!sandboxStatus.enabled) {
|
|
sandboxBadge = (
|
|
<Badge variant="outline" className="px-1.5 py-0 text-[10px] text-muted-foreground">
|
|
{translate("overview.sandboxLocal")}
|
|
</Badge>
|
|
);
|
|
} else if (sandboxStatus.available) {
|
|
sandboxBadge = (
|
|
<Badge
|
|
variant="outline"
|
|
className="border-emerald-500/30 bg-emerald-500/10 px-1.5 py-0 text-[10px] text-emerald-600 dark:text-emerald-400"
|
|
>
|
|
{translate("overview.sandboxDocker", { runtime: sandboxStatus.runtime || "runc" })}
|
|
</Badge>
|
|
);
|
|
} else {
|
|
sandboxBadge = (
|
|
<Badge variant="outline" className="border-red-500/30 bg-red-500/10 px-1.5 py-0 text-[10px] text-red-400">
|
|
{translate("overview.sandboxUnavailable")}
|
|
</Badge>
|
|
);
|
|
}
|
|
}
|
|
|
|
let footerSummary: string;
|
|
let footerHref: string;
|
|
let footerLinkLabel: string;
|
|
|
|
if (tab === "findings") {
|
|
footerSummary = translate("overview.trendFooterFindings", {
|
|
total: summary.windowFindings,
|
|
highCrit: summary.windowHighCrit,
|
|
closed: summary.windowClosedFindings,
|
|
});
|
|
footerHref = "/function/findings";
|
|
footerLinkLabel = translate("overview.trendLinkFindings");
|
|
} else if (tab === "containers") {
|
|
footerSummary = translate("overview.trendFooterContainers", {
|
|
created: summary.windowContainersCreated,
|
|
running: summary.currentRunningContainers,
|
|
stopped: summary.currentStoppedContainers,
|
|
});
|
|
footerHref = "/system/sandbox";
|
|
footerLinkLabel = translate("overview.trendLinkContainers");
|
|
} else {
|
|
footerSummary = translate("overview.trendFooterLifecycle", {
|
|
created: summary.windowTasksCreated,
|
|
completed: summary.windowTasksCompleted,
|
|
rate: summary.closureRate,
|
|
});
|
|
footerHref = "/function/tasks";
|
|
footerLinkLabel = translate("overview.trendLinkLifecycle");
|
|
}
|
|
|
|
const tabs: ReadonlyArray<{ id: TrendTab; label: string }> = [
|
|
{ id: "findings", label: translate("overview.trendTabFindings") },
|
|
{ id: "containers", label: translate("overview.trendTabContainers") },
|
|
{ id: "lifecycle", label: translate("overview.trendTabLifecycle") },
|
|
];
|
|
|
|
return (
|
|
<Card className="p-5">
|
|
{/* Header */}
|
|
<div className="mb-4 flex flex-wrap items-start justify-between gap-3">
|
|
<div>
|
|
<h2 className="font-semibold text-sm tracking-tight">{translate("overview.trendTitle")}</h2>
|
|
<p className="mt-0.5 text-muted-foreground text-xs">{translate("overview.trendSubtitle", { days })}</p>
|
|
</div>
|
|
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
{/* Day window switcher */}
|
|
<div className="flex items-center gap-0.5 rounded-md border bg-muted/30 p-0.5">
|
|
{WINDOW_OPTIONS.map((w) => (
|
|
<button
|
|
type="button"
|
|
key={w}
|
|
onClick={() => setDays(w)}
|
|
className={cn(
|
|
"rounded px-2 py-0.5 font-medium text-[11px] transition-colors",
|
|
days === w
|
|
? "bg-background text-foreground shadow-xs"
|
|
: "text-muted-foreground hover:text-foreground",
|
|
)}
|
|
>
|
|
{translate("overview.trendDays", { days: w })}
|
|
</button>
|
|
))}
|
|
</div>
|
|
|
|
{/* Metric tabs */}
|
|
<div className="flex flex-wrap items-center gap-1.5">
|
|
{tabs.map((item) => (
|
|
<button
|
|
type="button"
|
|
key={item.id}
|
|
onClick={() => setTab(item.id)}
|
|
className={cn(
|
|
"rounded-md border px-2.5 py-1 text-xs transition-colors",
|
|
tab === item.id
|
|
? "border-border bg-muted font-medium text-foreground"
|
|
: "border-border/60 bg-background/60 text-muted-foreground hover:text-foreground",
|
|
)}
|
|
>
|
|
{item.label}
|
|
</button>
|
|
))}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Area / Line Trend Chart */}
|
|
<ChartContainer config={chartConfig} className="h-[230px] w-full">
|
|
<AreaChart data={buckets} margin={{ top: 10, right: 12, bottom: 0, left: 0 }}>
|
|
<defs>
|
|
<linearGradient id="dashTrendPrimaryFill" x1="0" y1="0" x2="0" y2="1">
|
|
<stop offset="0%" stopColor="#2563eb" stopOpacity={0.22} />
|
|
<stop offset="100%" stopColor="#2563eb" stopOpacity={0.01} />
|
|
</linearGradient>
|
|
</defs>
|
|
<CartesianGrid vertical={false} strokeDasharray="0" strokeOpacity={0.35} />
|
|
<XAxis
|
|
dataKey="label"
|
|
tickLine={false}
|
|
axisLine={false}
|
|
tickMargin={10}
|
|
interval="preserveStartEnd"
|
|
minTickGap={24}
|
|
tick={{ fontSize: 11 }}
|
|
/>
|
|
<YAxis
|
|
allowDecimals={false}
|
|
tickLine={false}
|
|
axisLine={false}
|
|
width={46}
|
|
domain={[0, (dataMax: number) => Math.max(dataMax, 4)]}
|
|
tick={{ fontSize: 11 }}
|
|
tickFormatter={formatTick}
|
|
/>
|
|
<RechartsTooltip
|
|
cursor={{ stroke: "var(--border)", strokeWidth: 1 }}
|
|
content={({ active, payload }) => {
|
|
if (!active || !payload?.length) return null;
|
|
const b = payload[0]?.payload as DayBucket | undefined;
|
|
if (!b) return null;
|
|
|
|
let rows: Array<{ label: string; value: number; color: string }>;
|
|
if (tab === "findings") {
|
|
rows = [
|
|
{ label: translate("overview.trendSeriesFindings"), value: b.findingsTotal, color: "#2563eb" },
|
|
{ label: translate("overview.trendSeriesHighCrit"), value: b.findingsHighCrit, color: "#f43f5e" },
|
|
{ label: translate("overview.trendSeriesMedLow"), value: b.findingsMedLow, color: "#f59e0b" },
|
|
{ label: translate("overview.trendSeriesClosed"), value: b.findingsClosed, color: "#10b981" },
|
|
];
|
|
} else if (tab === "containers") {
|
|
rows = [
|
|
{
|
|
label: translate("overview.trendSeriesContainersCreated"),
|
|
value: b.containersCreated,
|
|
color: "#2563eb",
|
|
},
|
|
{
|
|
label: translate("overview.trendSeriesContainersRunning"),
|
|
value: b.containersRunning,
|
|
color: "#10b981",
|
|
},
|
|
{
|
|
label: translate("overview.trendSeriesTaskContainers"),
|
|
value: b.containersTask,
|
|
color: "#6366f1",
|
|
},
|
|
{
|
|
label: translate("overview.trendSeriesSessionContainers"),
|
|
value: b.containersSession,
|
|
color: "#0ea5e9",
|
|
},
|
|
];
|
|
} else {
|
|
rows = [
|
|
{ label: translate("overview.trendSeriesTasksCreated"), value: b.tasksCreated, color: "#2563eb" },
|
|
{ label: translate("overview.trendSeriesTasksCompleted"), value: b.tasksCompleted, color: "#10b981" },
|
|
{ label: translate("overview.trendSeriesFindings"), value: b.findingsTotal, color: "#f59e0b" },
|
|
{ label: translate("overview.trendSeriesClosed"), value: b.findingsClosed, color: "#14b8a6" },
|
|
];
|
|
}
|
|
|
|
return (
|
|
<div className="min-w-44 rounded-lg border bg-popover/95 px-3 py-2 text-popover-foreground text-xs shadow-md backdrop-blur-xs">
|
|
<div className="mb-1.5 border-b pb-1 font-medium font-mono text-[11px] text-muted-foreground">
|
|
{b.dayKey}
|
|
</div>
|
|
<div className="space-y-1">
|
|
{rows.map((r) => (
|
|
<div key={r.label} className="flex items-center justify-between gap-4 text-[11px]">
|
|
<span className="inline-flex items-center gap-1.5 text-muted-foreground">
|
|
<span className="size-2 shrink-0 rounded-full" style={{ backgroundColor: r.color }} />
|
|
{r.label}
|
|
</span>
|
|
<span className="font-medium font-mono tabular-nums">{r.value}</span>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
);
|
|
}}
|
|
/>
|
|
<Area
|
|
type="linear"
|
|
dataKey={activeSeries.primaryKey}
|
|
stroke="#2563eb"
|
|
strokeWidth={2}
|
|
fill="url(#dashTrendPrimaryFill)"
|
|
dot={false}
|
|
activeDot={{ r: 4, fill: "#2563eb", stroke: "var(--background)", strokeWidth: 2 }}
|
|
isAnimationActive={false}
|
|
/>
|
|
<Area
|
|
type="linear"
|
|
dataKey={activeSeries.secondaryKey}
|
|
stroke={activeSeries.secondaryColor}
|
|
strokeWidth={1.75}
|
|
strokeDasharray="4 4"
|
|
fill="none"
|
|
dot={false}
|
|
activeDot={{ r: 3.5, fill: activeSeries.secondaryColor, stroke: "var(--background)", strokeWidth: 2 }}
|
|
isAnimationActive={false}
|
|
/>
|
|
</AreaChart>
|
|
</ChartContainer>
|
|
|
|
{/* Footer */}
|
|
<div className="mt-3 flex flex-wrap items-center justify-between gap-2 border-t pt-3 text-muted-foreground text-xs">
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<span className="tabular-nums">{footerSummary}</span>
|
|
{sandboxBadge}
|
|
{tab === "lifecycle" && activeRetests.length > 0 && (
|
|
<span className="inline-flex items-center gap-1 text-blue-500 dark:text-blue-400">
|
|
<span className="inline-block size-1.5 animate-pulse rounded-full bg-blue-500" />
|
|
{translate("overview.activeRetests", { count: activeRetests.length })}
|
|
</span>
|
|
)}
|
|
</div>
|
|
<Link
|
|
href={footerHref}
|
|
className="inline-flex items-center gap-0.5 font-medium text-foreground/80 transition-colors hover:text-foreground"
|
|
>
|
|
{footerLinkLabel}
|
|
<ArrowUpRightIcon className="size-3.5" />
|
|
</Link>
|
|
</div>
|
|
</Card>
|
|
);
|
|
}
|