feat: show today's successful tasks from dashboard (#3072)

This commit is contained in:
whyour
2026-09-18 02:16:54 +08:00
parent 4eb27427f8
commit a60ec5587a
6 changed files with 127 additions and 56 deletions
+39 -36
View File
@@ -107,42 +107,45 @@ export default (app: Router) => {
}, },
); );
route.get( for (const isSuccess of [false, true]) {
'/failures', route.get(
async (req: Request, res: Response, next: NextFunction) => { isSuccess ? '/successes' : '/failures',
try { async (req: Request, res: Response, next: NextFunction) => {
const rows = (await CrontabStatModel.findAll({ try {
attributes: ['ref_id', [fn('SUM', col('fail_count')), 'fail_count']], const countColumn = isSuccess ? 'success_count' : 'fail_count';
where: { date: dayjs().format('YYYY-MM-DD'), fail_count: { [Op.gt]: 0 } }, const rows = (await CrontabStatModel.findAll({
group: ['ref_id'], attributes: ['ref_id', [fn('SUM', col(countColumn)), 'result_count']],
order: [[fn('SUM', col('fail_count')), 'DESC'], ['ref_id', 'ASC']], where: { date: dayjs().format('YYYY-MM-DD'), [countColumn]: { [Op.gt]: 0 } },
raw: true, group: ['ref_id'],
})) as any[]; order: [[fn('SUM', col(countColumn)), 'DESC'], ['ref_id', 'ASC']],
const crons = rows.length > 0 ? await CrontabModel.findAll({ raw: true,
attributes: ['id', 'name', 'command'], })) as any[];
where: { id: { [Op.in]: rows.map((row) => Number(row.ref_id)) } }, const crons = rows.length > 0 ? await CrontabModel.findAll({
raw: true, attributes: ['id', 'name', 'command'],
}) : []; where: { id: { [Op.in]: rows.map((row) => Number(row.ref_id)) } },
const cronMap = new Map(crons.map((cron) => [cron.id, cron])); raw: true,
res.send({ }) : [];
code: 200, const cronMap = new Map(crons.map((cron) => [cron.id, cron]));
data: rows.map((row) => { res.send({
const id = Number(row.ref_id); code: 200,
const cron = cronMap.get(id); data: rows.map((row) => {
return { const id = Number(row.ref_id);
id, const cron = cronMap.get(id);
name: cron?.name || cron?.command || tf('任务#%s', id), return {
command: cron?.command || '', id,
failCount: Number(row.fail_count), name: cron?.name || cron?.command || tf('任务#%s', id),
deleted: !cron, command: cron?.command || '',
}; [isSuccess ? 'successCount' : 'failCount']: Number(row.result_count),
}), deleted: !cron,
}); };
} catch (e) { }),
next(e); });
} } catch (e) {
}, next(e);
); }
},
);
}
route.get( route.get(
'/trend', '/trend',
+1
View File
@@ -658,6 +658,7 @@
"已停止": "Stopped", "已停止": "Stopped",
"退出码": "Exit Code", "退出码": "Exit Code",
"结束": "End", "结束": "End",
"成功次数": "Success count",
"失败次数": "Failure count", "失败次数": "Failure count",
"最新日志": "Latest log", "最新日志": "Latest log",
"加载失败": "Failed to load", "加载失败": "Failed to load",
+1
View File
@@ -658,6 +658,7 @@
"已停止": "已停止", "已停止": "已停止",
"退出码": "退出码", "退出码": "退出码",
"结束": "结束", "结束": "结束",
"成功次数": "成功次数",
"失败次数": "失败次数", "失败次数": "失败次数",
"最新日志": "最新日志", "最新日志": "最新日志",
"加载失败": "加载失败", "加载失败": "加载失败",
+15 -6
View File
@@ -16,7 +16,7 @@ import { SharedContext } from '@/layouts';
import { request } from '@/utils/http'; import { request } from '@/utils/http';
import config from '@/utils/config'; import config from '@/utils/config';
import CronLogModal from '../crontab/logModal'; import CronLogModal from '../crontab/logModal';
import FailureModal from './failureModal'; import TaskResultModal from './taskResultModal';
interface Overview { interface Overview {
total: number; total: number;
@@ -94,7 +94,7 @@ const Dashboard = () => {
const [labels, setLabels] = useState<any[]>([]); const [labels, setLabels] = useState<any[]>([]);
const [logCron, setLogCron] = useState<any>(null); const [logCron, setLogCron] = useState<any>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [showFailures, setShowFailures] = useState(false); const [result, setResult] = useState<'success' | 'failure' | null>(null);
const fetchData = useCallback(async () => { const fetchData = useCallback(async () => {
try { try {
@@ -192,16 +192,25 @@ const Dashboard = () => {
<Card size="small"><Statistic title={intl.get('成功率')} value={`${overview?.successRate || '0'}%`} valueStyle={{ color: '#52c41a' }} /></Card> <Card size="small"><Statistic title={intl.get('成功率')} value={`${overview?.successRate || '0'}%`} valueStyle={{ color: '#52c41a' }} /></Card>
</Col> </Col>
<Col xs={12} sm={8} md={6} lg={3}> <Col xs={12} sm={8} md={6} lg={3}>
<Card size="small"><Statistic title={intl.get('今日成功')} value={overview?.todaySuccess || 0} valueStyle={{ color: '#52c41a' }} prefix={<CheckCircleOutlined />} /></Card> <Card size="small" hoverable role="button" tabIndex={0}
aria-label={intl.get('今日成功')}
onClick={() => setResult('success')}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
setResult('success');
}
}}
><Statistic title={intl.get('今日成功')} value={overview?.todaySuccess || 0} valueStyle={{ color: '#52c41a' }} prefix={<CheckCircleOutlined />} /></Card>
</Col> </Col>
<Col xs={12} sm={8} md={6} lg={3}> <Col xs={12} sm={8} md={6} lg={3}>
<Card size="small" hoverable role="button" tabIndex={0} <Card size="small" hoverable role="button" tabIndex={0}
aria-label={intl.get('今日失败')} aria-label={intl.get('今日失败')}
onClick={() => setShowFailures(true)} onClick={() => setResult('failure')}
onKeyDown={(event) => { onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === ' ') { if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault(); event.preventDefault();
setShowFailures(true); setResult('failure');
} }
}} }}
><Statistic title={intl.get('今日失败')} value={overview?.todayFail || 0} valueStyle={{ color: '#ff4d4f' }} prefix={<CloseCircleOutlined />} /></Card> ><Statistic title={intl.get('今日失败')} value={overview?.todayFail || 0} valueStyle={{ color: '#ff4d4f' }} prefix={<CloseCircleOutlined />} /></Card>
@@ -361,7 +370,7 @@ const Dashboard = () => {
</Card> </Card>
</Col> </Col>
</Row> </Row>
{showFailures && <FailureModal onCancel={() => setShowFailures(false)} />} {result && <TaskResultModal key={result} result={result} onCancel={() => setResult(null)} />}
{logCron && ( {logCron && (
<CronLogModal <CronLogModal
cron={logCron} cron={logCron}
@@ -5,31 +5,41 @@ import { request } from '@/utils/http';
import config from '@/utils/config'; import config from '@/utils/config';
import CronLogModal from '../crontab/logModal'; import CronLogModal from '../crontab/logModal';
interface FailedTask { interface TaskResult {
id: number; id: number;
name: string; name: string;
command: string; command: string;
failCount: number; failCount?: number;
successCount?: number;
deleted: boolean; deleted: boolean;
} }
export default function FailureModal({ onCancel }: { onCancel: () => void }) { export default function TaskResultModal({
const [tasks, setTasks] = useState<FailedTask[]>([]); result,
onCancel,
}: {
result: 'success' | 'failure';
onCancel: () => void;
}) {
const isSuccess = result === 'success';
const [tasks, setTasks] = useState<TaskResult[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [failed, setFailed] = useState(false); const [failed, setFailed] = useState(false);
const [reload, setReload] = useState(0); const [reload, setReload] = useState(0);
const [logCron, setLogCron] = useState<FailedTask | null>(null); const [logCron, setLogCron] = useState<TaskResult | null>(null);
useEffect(() => { useEffect(() => {
let active = true; let active = true;
setLoading(true); setLoading(true);
setFailed(false); setFailed(false);
request request
.get(`${config.apiPrefix}dashboard/failures`) .get(
`${config.apiPrefix}dashboard/${isSuccess ? 'successes' : 'failures'}`,
)
.then((response) => { .then((response) => {
if (!active) return; if (!active) return;
if (response.code !== 200) if (response.code !== 200)
throw new Error('Failed to load dashboard failures'); throw new Error('Failed to load dashboard task results');
setTasks(response.data); setTasks(response.data);
}) })
.catch(() => { .catch(() => {
@@ -41,12 +51,12 @@ export default function FailureModal({ onCancel }: { onCancel: () => void }) {
return () => { return () => {
active = false; active = false;
}; };
}, [reload]); }, [reload, isSuccess]);
return ( return (
<> <>
<Modal <Modal
title={intl.get('今日失败')} title={intl.get(isSuccess ? '今日成功' : '今日失败')}
open open
onCancel={onCancel} onCancel={onCancel}
footer={null} footer={null}
@@ -64,7 +74,7 @@ export default function FailureModal({ onCancel }: { onCancel: () => void }) {
} }
/> />
) : ( ) : (
<Table<FailedTask> <Table<TaskResult>
loading={loading} loading={loading}
dataSource={tasks} dataSource={tasks}
rowKey="id" rowKey="id"
@@ -84,8 +94,8 @@ export default function FailureModal({ onCancel }: { onCancel: () => void }) {
}, },
{ title: intl.get('命令'), dataIndex: 'command', ellipsis: true }, { title: intl.get('命令'), dataIndex: 'command', ellipsis: true },
{ {
title: intl.get('失败次数'), title: intl.get(isSuccess ? '成功次数' : '失败次数'),
dataIndex: 'failCount', dataIndex: isSuccess ? 'successCount' : 'failCount',
width: 100, width: 100,
}, },
{ {
+49 -2
View File
@@ -5,7 +5,7 @@ const { Sequelize, DataTypes } = require('sequelize');
const dayjs = require('dayjs'); const dayjs = require('dayjs');
const express = require('express'); const express = require('express');
test('today failures includes recovered and deleted tasks, excluding previous days and successes', async (t) => { test('today result lists include mixed and deleted tasks and exclude other dates', async (t) => {
const db = new Sequelize({ const db = new Sequelize({
dialect: 'sqlite', dialect: 'sqlite',
storage: ':memory:', storage: ':memory:',
@@ -53,11 +53,12 @@ test('today failures includes recovered and deleted tasks, excluding previous da
{ ref_id: 1, date: today, fail_count: 2, success_count: 1 }, { ref_id: 1, date: today, fail_count: 2, success_count: 1 },
{ ref_id: 2, date: today, fail_count: 1, success_count: 0 }, { ref_id: 2, date: today, fail_count: 1, success_count: 0 },
{ ref_id: 3, date: today, fail_count: 0, success_count: 4 }, { ref_id: 3, date: today, fail_count: 0, success_count: 4 },
{ ref_id: 4, date: today, fail_count: 3, success_count: 0 }, { ref_id: 4, date: today, fail_count: 3, success_count: 2 },
{ {
ref_id: 3, ref_id: 3,
date: dayjs().subtract(1, 'day').format('YYYY-MM-DD'), date: dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
fail_count: 10, fail_count: 10,
success_count: 20,
}, },
]); ]);
const router = express.Router(); const router = express.Router();
@@ -68,6 +69,9 @@ test('today failures includes recovered and deleted tasks, excluding previous da
const handler = dashboard.stack.find( const handler = dashboard.stack.find(
(layer) => layer.route?.path === '/failures', (layer) => layer.route?.path === '/failures',
).route.stack[0].handle; ).route.stack[0].handle;
const successHandler = dashboard.stack.find(
(layer) => layer.route?.path === '/successes',
).route.stack[0].handle;
let response; let response;
await handler( await handler(
{}, {},
@@ -100,7 +104,50 @@ test('today failures includes recovered and deleted tasks, excluding previous da
}, },
], ],
}); });
await successHandler(
{},
{
send: (value) => {
response = value;
},
},
(error) => {
throw error;
},
);
assert.deepEqual(response, {
code: 200,
data: [
{
id: 3,
name: 'Successful task',
command: 'task success.js',
successCount: 4,
deleted: false,
},
{ id: 4, name: '任务#4', command: '', successCount: 2, deleted: true },
{
id: 1,
name: 'Recovered task',
command: 'task recovered.js',
successCount: 1,
deleted: false,
},
],
});
await stats.destroy({ where: {} }); await stats.destroy({ where: {} });
await successHandler(
{},
{
send: (value) => {
response = value;
},
},
(error) => {
throw error;
},
);
assert.deepEqual(response, { code: 200, data: [] });
await handler( await handler(
{}, {},
{ {