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