4aae61297f
Analytics parity phases 2–7 (docs/plans/analytics-parity/), built on
138e706 and ported onto v2.3.1:
- Cost by AI tool (?tool= on cost/analytics/stats/workflows, by_tool,
Codex fast/priority and flex tiers, agenthub_cost_usd_total{tool,model})
- Date ranges (from/to) on cost/analytics/workflows; Analytics range select
with Today / This week (Monday) / This month (1st) / 7d / 30d / 90d / All /
Custom; workflow filters carried into workflow-stats.js (read worker)
- Budgets and cost alerts as alert rule types (alert_rules rebuilt without
its rule_type CHECK), GET /api/budgets/status, rule preview, spend pace,
status-bar budget chip; rules stay editable in place
- Query Explorer (/query, allowlisted sort, CSV/JSON export) and scheduled
reports (report_definitions/report_runs, Settings → Reports)
- Session Replay tab and immutable snapshots (session_snapshots, /snapshot/:token)
- Remote Codex sync, push ingest with a hashed token, privacy redaction and
ignored folders (Settings → Data), Cursor sessions (no cost)
- Read-only MCP server, statusline, Grafana/Prometheus files
Also: resizable sidebar, pet run/wave animations, the workspace home keeps a
half-typed prompt, and the pre-commit hook runs only the related tests for a
small commit.
395 lines
14 KiB
TypeScript
395 lines
14 KiB
TypeScript
/**
|
|
* @file ReportSettings.tsx
|
|
* @description Settings → Reports: scheduled report definitions (`/api/reports`)
|
|
* — create/edit (name, window, daily/weekly + weekday, local hour, HTML/JSON),
|
|
* enable switch, Run now, a confirmed Delete, and each report's run history
|
|
* with download links. Every row action is also on a right-click menu. The
|
|
* browser's timezone offset is saved with the definition, so its hour is the
|
|
* user's local hour.
|
|
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
|
*/
|
|
|
|
import { useCallback, useEffect, useState } from "react";
|
|
import { useTranslation } from "react-i18next";
|
|
import { Download, History, Pencil, Play, Plus, Trash2 } from "lucide-react";
|
|
import { api } from "../../lib/api";
|
|
import { formatDateTime } from "../../lib/format";
|
|
import type { ReportDefinition, ReportInput, ReportRun } from "../../lib/types";
|
|
import { Checkbox } from "../Checkbox";
|
|
import { ConfirmModal } from "../ConfirmModal";
|
|
import { ContextMenu, MenuItem, MenuSeparator, useContextMenu } from "../ContextMenu";
|
|
import { Select } from "../Select";
|
|
import { Switch } from "../Switch";
|
|
import { SettingsSection } from "./SettingsRow";
|
|
|
|
const EMPTY: ReportInput = {
|
|
name: "",
|
|
window_days: 7,
|
|
frequency: "weekly",
|
|
hour: 8,
|
|
weekday: 1,
|
|
tz_offset: 0,
|
|
formats: ["html"],
|
|
enabled: true,
|
|
};
|
|
const HOURS = Array.from({ length: 24 }, (_, h) => h);
|
|
const pad = (n: number) => String(n).padStart(2, "0");
|
|
|
|
export function ReportSettings() {
|
|
const { t, i18n } = useTranslation("settings");
|
|
const [items, setItems] = useState<ReportDefinition[] | null>(null);
|
|
const [error, setError] = useState<string | null>(null);
|
|
/** The form: a new report (id null) or the one being edited. */
|
|
const [form, setForm] = useState<{ id: number | null; value: ReportInput } | null>(null);
|
|
const [deleting, setDeleting] = useState<ReportDefinition | null>(null);
|
|
const [busy, setBusy] = useState<number | "form" | null>(null);
|
|
const [history, setHistory] = useState<{ id: number; runs: ReportRun[] } | null>(null);
|
|
const ctx = useContextMenu<ReportDefinition>();
|
|
|
|
const weekday = (d: number) =>
|
|
new Intl.DateTimeFormat(i18n.resolvedLanguage ?? i18n.language, { weekday: "long" }).format(
|
|
new Date(Date.UTC(2026, 0, 4 + d))
|
|
);
|
|
const fail = (err: unknown) => setError(err instanceof Error ? err.message : String(err));
|
|
|
|
const load = useCallback(() => {
|
|
api.reports
|
|
.list()
|
|
.then((r) => setItems(r.reports))
|
|
.catch(fail);
|
|
}, []);
|
|
useEffect(load, [load]);
|
|
|
|
const showHistory = async (id: number) => {
|
|
try {
|
|
const r = await api.reports.runs(id);
|
|
setHistory({ id, runs: r.runs });
|
|
} catch (err) {
|
|
fail(err);
|
|
}
|
|
};
|
|
|
|
const save = async () => {
|
|
if (!form) return;
|
|
setBusy("form");
|
|
const value = { ...form.value, tz_offset: new Date().getTimezoneOffset() };
|
|
try {
|
|
if (form.id === null) await api.reports.create(value);
|
|
else await api.reports.update(form.id, value);
|
|
setForm(null);
|
|
setError(null);
|
|
load();
|
|
} catch (err) {
|
|
fail(err);
|
|
} finally {
|
|
setBusy(null);
|
|
}
|
|
};
|
|
|
|
const toggle = async (r: ReportDefinition, enabled: boolean) => {
|
|
try {
|
|
await api.reports.update(r.id, { enabled });
|
|
load();
|
|
} catch (err) {
|
|
fail(err);
|
|
}
|
|
};
|
|
|
|
const runNow = async (r: ReportDefinition) => {
|
|
setBusy(r.id);
|
|
try {
|
|
const { run } = await api.reports.run(r.id);
|
|
if (run.status === "error") setError(run.error);
|
|
load();
|
|
if (history?.id === r.id) await showHistory(r.id);
|
|
} catch (err) {
|
|
fail(err);
|
|
} finally {
|
|
setBusy(null);
|
|
}
|
|
};
|
|
|
|
const remove = async () => {
|
|
if (!deleting) return;
|
|
try {
|
|
await api.reports.remove(deleting.id);
|
|
if (history?.id === deleting.id) setHistory(null);
|
|
load();
|
|
} catch (err) {
|
|
fail(err);
|
|
} finally {
|
|
setDeleting(null);
|
|
}
|
|
};
|
|
|
|
const edit = (r: ReportDefinition) =>
|
|
setForm({
|
|
id: r.id,
|
|
value: {
|
|
name: r.name,
|
|
window_days: r.window_days,
|
|
frequency: r.frequency,
|
|
hour: r.hour,
|
|
weekday: r.weekday,
|
|
tz_offset: r.tz_offset,
|
|
formats: r.formats,
|
|
enabled: r.enabled,
|
|
},
|
|
});
|
|
const pick = (fn: (r: ReportDefinition) => void) => () => {
|
|
const r = ctx.menu?.item;
|
|
ctx.close();
|
|
if (r) fn(r);
|
|
};
|
|
const schedule = (r: ReportInput) =>
|
|
[
|
|
r.frequency === "daily"
|
|
? t("reports.everyDay", { time: `${pad(r.hour)}:00` })
|
|
: t("reports.everyWeek", { day: weekday(r.weekday), time: `${pad(r.hour)}:00` }),
|
|
t("reports.window", { count: r.window_days }),
|
|
r.formats.map((f) => f.toUpperCase()).join(", "),
|
|
].join(" · ");
|
|
|
|
const set = (patch: Partial<ReportInput>) =>
|
|
setForm((f) => (f ? { ...f, value: { ...f.value, ...patch } } : f));
|
|
const toggleFormat = (f: "html" | "json", on: boolean) =>
|
|
set({
|
|
formats: on
|
|
? [...(form?.value.formats ?? []), f]
|
|
: (form?.value.formats ?? []).filter((x) => x !== f),
|
|
});
|
|
|
|
return (
|
|
<SettingsSection title={t("reports.title")} description={t("reports.description")}>
|
|
{error && (
|
|
<p role="alert" className="py-2 text-xs text-status-danger">
|
|
{error}
|
|
</p>
|
|
)}
|
|
|
|
{form ? (
|
|
<div
|
|
className="my-2 space-y-3 rounded-md border border-border p-3"
|
|
data-testid="report-form"
|
|
>
|
|
<label className="block text-xs text-fg-muted">
|
|
{t("reports.name")}
|
|
<input
|
|
className="input mt-1 w-full text-sm"
|
|
value={form.value.name}
|
|
maxLength={200}
|
|
onChange={(e) => set({ name: e.target.value })}
|
|
/>
|
|
</label>
|
|
<div className="flex flex-wrap items-end gap-3">
|
|
<label className="text-xs text-fg-muted">
|
|
{t("reports.windowDays")}
|
|
<input
|
|
type="number"
|
|
min={1}
|
|
max={366}
|
|
className="input mt-1 block w-24 text-sm"
|
|
value={form.value.window_days}
|
|
onChange={(e) => set({ window_days: Math.trunc(Number(e.target.value)) })}
|
|
/>
|
|
</label>
|
|
<div className="w-36">
|
|
<Select
|
|
value={form.value.frequency}
|
|
onChange={(v) => set({ frequency: v })}
|
|
label={t("reports.frequency")}
|
|
options={[
|
|
{ value: "daily", label: t("reports.daily") },
|
|
{ value: "weekly", label: t("reports.weekly") },
|
|
]}
|
|
/>
|
|
</div>
|
|
{form.value.frequency === "weekly" && (
|
|
<div className="w-40">
|
|
<Select
|
|
value={String(form.value.weekday)}
|
|
onChange={(v) => set({ weekday: Number(v) })}
|
|
label={t("reports.weekday")}
|
|
options={[1, 2, 3, 4, 5, 6, 0].map((d) => ({
|
|
value: String(d),
|
|
label: weekday(d),
|
|
}))}
|
|
/>
|
|
</div>
|
|
)}
|
|
<div className="w-28">
|
|
<Select
|
|
value={String(form.value.hour)}
|
|
onChange={(v) => set({ hour: Number(v) })}
|
|
label={t("reports.hour")}
|
|
options={HOURS.map((h) => ({ value: String(h), label: `${pad(h)}:00` }))}
|
|
/>
|
|
</div>
|
|
</div>
|
|
<div className="flex flex-wrap items-center gap-4">
|
|
<Checkbox
|
|
checked={form.value.formats.includes("html")}
|
|
onChange={(v) => toggleFormat("html", v)}
|
|
label="HTML"
|
|
/>
|
|
<Checkbox
|
|
checked={form.value.formats.includes("json")}
|
|
onChange={(v) => toggleFormat("json", v)}
|
|
label="JSON"
|
|
/>
|
|
</div>
|
|
<p className="text-[11px] text-fg-muted">{t("reports.windowHint")}</p>
|
|
<div className="flex gap-2">
|
|
<button
|
|
type="button"
|
|
className="btn-primary text-xs"
|
|
disabled={
|
|
busy === "form" || !form.value.name.trim() || form.value.formats.length === 0
|
|
}
|
|
onClick={() => void save()}
|
|
>
|
|
{t("reports.save")}
|
|
</button>
|
|
<button type="button" className="btn-ghost text-xs" onClick={() => setForm(null)}>
|
|
{t("reports.cancel")}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
) : (
|
|
<button
|
|
type="button"
|
|
className="btn-ghost my-2 text-xs"
|
|
onClick={() => setForm({ id: null, value: { ...EMPTY, name: t("reports.defaultName") } })}
|
|
>
|
|
<Plus className="h-3.5 w-3.5" />
|
|
{t("reports.add")}
|
|
</button>
|
|
)}
|
|
|
|
{items?.length === 0 && <p className="py-2 text-sm text-fg-muted">{t("reports.empty")}</p>}
|
|
{items && items.length > 0 && (
|
|
<ul className="divide-y divide-border/60" data-testid="report-list">
|
|
{items.map((r) => (
|
|
<li key={r.id} onContextMenu={(e) => ctx.open(e, r)} className="py-2.5">
|
|
<div className="flex items-center gap-3">
|
|
<div className="min-w-0 flex-1">
|
|
<p className="truncate text-sm text-fg-secondary">{r.name}</p>
|
|
<p className="text-[11px] text-fg-muted">{schedule(r)}</p>
|
|
{r.last_run && (
|
|
<p
|
|
className={`text-[11px] ${
|
|
r.last_run.status === "error" ? "text-status-danger" : "text-fg-muted"
|
|
}`}
|
|
>
|
|
{t("reports.lastRun", { at: formatDateTime(r.last_run.created_at) })}
|
|
{r.last_run.status === "error" && ` · ${r.last_run.error ?? ""}`}
|
|
</p>
|
|
)}
|
|
</div>
|
|
<Switch
|
|
checked={r.enabled}
|
|
onChange={(v) => void toggle(r, v)}
|
|
label={t("reports.enabled")}
|
|
title={t("reports.enabled")}
|
|
/>
|
|
<button
|
|
type="button"
|
|
className="btn-ghost text-xs"
|
|
disabled={busy === r.id}
|
|
onClick={() => void runNow(r)}
|
|
title={t("reports.runNow")}
|
|
aria-label={t("reports.runNow")}
|
|
>
|
|
<Play className="h-3.5 w-3.5" />
|
|
</button>
|
|
<button
|
|
type="button"
|
|
className="btn-ghost text-xs"
|
|
onClick={() => (history?.id === r.id ? setHistory(null) : void showHistory(r.id))}
|
|
title={t("reports.history")}
|
|
aria-label={t("reports.history")}
|
|
>
|
|
<History className="h-3.5 w-3.5" />
|
|
</button>
|
|
<button
|
|
type="button"
|
|
className="btn-ghost text-xs"
|
|
onClick={() => edit(r)}
|
|
title={t("reports.edit")}
|
|
aria-label={t("reports.edit")}
|
|
>
|
|
<Pencil className="h-3.5 w-3.5" />
|
|
</button>
|
|
<button
|
|
type="button"
|
|
className="btn-ghost text-xs text-status-danger"
|
|
onClick={() => setDeleting(r)}
|
|
title={t("reports.delete")}
|
|
aria-label={t("reports.delete")}
|
|
>
|
|
<Trash2 className="h-3.5 w-3.5" />
|
|
</button>
|
|
</div>
|
|
{history?.id === r.id && (
|
|
<ul
|
|
className="mt-2 space-y-1 border-l border-border pl-3"
|
|
data-testid="report-runs"
|
|
>
|
|
{history.runs.length === 0 && (
|
|
<li className="text-[11px] text-fg-muted">{t("reports.noRuns")}</li>
|
|
)}
|
|
{history.runs.map((run) => (
|
|
<li key={run.id} className="flex flex-wrap items-center gap-2 text-[11px]">
|
|
<span className="text-fg-secondary">{formatDateTime(run.created_at)}</span>
|
|
<span className="text-fg-muted">
|
|
{t(`reports.trigger.${run.trigger}`)} · {run.window_from} → {run.window_to}
|
|
</span>
|
|
{run.status === "error" ? (
|
|
<span className="text-status-danger">{run.error}</span>
|
|
) : (
|
|
run.files.map((f) => (
|
|
<a
|
|
key={f}
|
|
href={api.reports.fileUrl(r.id, run.id, f)}
|
|
download
|
|
className="inline-flex items-center gap-0.5 text-accent hover:underline"
|
|
title={t("reports.download", { format: f.toUpperCase() })}
|
|
>
|
|
<Download className="h-3 w-3" />
|
|
{f.toUpperCase()}
|
|
</a>
|
|
))
|
|
)}
|
|
</li>
|
|
))}
|
|
</ul>
|
|
)}
|
|
</li>
|
|
))}
|
|
</ul>
|
|
)}
|
|
|
|
{ctx.menu && (
|
|
<ContextMenu x={ctx.menu.x} y={ctx.menu.y} onClose={ctx.close} testId="report-menu">
|
|
<MenuItem onSelect={pick((r) => void runNow(r))}>{t("reports.runNow")}</MenuItem>
|
|
<MenuItem onSelect={pick((r) => void showHistory(r.id))}>{t("reports.history")}</MenuItem>
|
|
<MenuItem onSelect={pick(edit)}>{t("reports.edit")}</MenuItem>
|
|
<MenuSeparator />
|
|
<MenuItem danger onSelect={pick(setDeleting)}>
|
|
{t("reports.delete")}
|
|
</MenuItem>
|
|
</ContextMenu>
|
|
)}
|
|
<ConfirmModal
|
|
open={deleting !== null}
|
|
title={t("reports.deleteTitle")}
|
|
message={t("reports.deleteBody")}
|
|
confirmLabel={t("reports.delete")}
|
|
cancelLabel={t("reports.cancel")}
|
|
onConfirm={() => void remove()}
|
|
onCancel={() => setDeleting(null)}
|
|
/>
|
|
</SettingsSection>
|
|
);
|
|
}
|