接收 全局推送告警 处理告警 优化控制逻辑

This commit is contained in:
mmc
2026-11-16 21:36:53 +08:00
parent d9f4b752dd
commit 2a429722d9
9 changed files with 489 additions and 229 deletions

View File

@@ -0,0 +1,18 @@
## 软著用户手册扩充(2026-11-16)
- 基于源文件 `C:/Users/15563/Desktop/软著/软著-机器人智慧服务系统/软著/用户操作手册-机器人智慧服务系统-完整版.docx` 扩充为 18 页软著格式手册
- 新文件(未改源文件):同目录 `用户操作手册-机器人智慧服务系统-完整版-扩充版V1.1.docx`
- 做法与要点:
- editor_sdk 的 doc 编辑/转图在中文路径下不可用("document is not open"、COS 上传找不到 python),改用 python-docx 生成 + Word COM 统计页数/导 PDF + PyMuPDF 渲染校验
- 格式:A4、页眉"机器人智慧服务系统 V1.0 用户操作手册"(带下框线)、页脚"第 X 页"(PAGE 域)、正文宋体小四 1.5 倍行距首行缩进 2 字符、标题黑体(H1 16pt/H2 14pt)、表格 Table Grid+蓝灰表头、图题表题五号居中
- 章节:原框架基础上重排为连续六章(一概述/二运行环境与登录/三装备总览/四任务规划/五告警中心/六日常建议与常见问题),修复原 3.1-3.7 编号断档、重复 4.7 等问题;不新增功能
- 保留并重排原 6 张截图(登录、装备总览、机器人任务、路径生成、返航点规划、告警中心),统一图号 图2-1~图5-1
- 通过缩小插图至 13.8cm 把 19 页调到精确 18 页
## 软著格式优化(2026-11-16 晚)
- 用户提供了经纬软著申报材料的两个模板:计算机软件著作权登记-源代码.doc、软件著作权产品说明书模版.doc(各1页,仅格式示例)
- 生成两个新文件(原文件未动):
- `软著/机器人智慧服务系统-产品说明书-格式优化版.docx`(15页):按说明书模板——页眉"机器人智慧服务系统 V1.0 + X/Y页码"、封面"软件名 V1.0 / 产品说明书"华文中宋16pt居中、正文华文中宋12pt固定20磅行距首行缩进2字符、结构=软件介绍(名称/版本/类别/著作权人)→软件特色→系统需求→安装和运行方法→软件功能(含6张截图);著作权人为占位符待用户填
- `软著/机器人智慧服务系统V1.0-源代码-格式优化版.docx`(94页):按源代码模板——A4、左右2.0cm上下1.0cm边距、页眉"机器人智慧服务系统V1.0+页码"、正文沿用原7.5pt/12磅行距(5042行,约54行/页≥50行要求)、内容逐行不变
- 踩坑:docx 固定行距(exact 20pt)会把内嵌图片裁剪成细条 → 图片段落必须单独设单倍行距;.doc 转 .docx 用 Word COM(SaveAs 16)
- 模板规则提醒:源代码超60页时申报只需前30页+后30页(第30页断开),已在回复中告知用户

View File

@@ -300,13 +300,13 @@ export default function AlarmCenterPage() {
{t('common.view')} {t('common.view')}
</Button> </Button>
<Button {/*<Button
type="link" type="link"
icon={<EditOutlined />} icon={<EditOutlined />}
onClick={() => openEditModal(record)} onClick={() => openEditModal(record)}
> >
{t('common.modify')} {t('common.modify')}
</Button> </Button>*/}
</Space> </Space>
) )
@@ -850,7 +850,7 @@ export default function AlarmCenterPage() {
{/* 根因分析 */} {/* 根因分析 */}
{/* 推荐处理措施 */} {/* 推荐处理措施 */}
<Card size="small" title={t('alerts.recommendedAction')} style={{ marginBottom: 16 }}> {/*<Card size="small" title={t('alerts.recommendedAction')} style={{ marginBottom: 16 }}>
<div style={{ color: '#333' }}>{currentAlarm.handleSuggestion || '-'}</div> <div style={{ color: '#333' }}>{currentAlarm.handleSuggestion || '-'}</div>
<div className="flex justify-between"> <div className="flex justify-between">
<div> <div>
@@ -864,7 +864,7 @@ export default function AlarmCenterPage() {
</div> </div>
</div> </div>
</Card> </Card>*/}
{/* 处理操作 */} {/* 处理操作 */}
<Card size="small" title={t('alerts.handleOperation')} style={{ marginBottom: 16 }}> <Card size="small" title={t('alerts.handleOperation')} style={{ marginBottom: 16 }}>

View File

@@ -29,7 +29,7 @@ import AgrtcRoomRobot from '../AgrtcRoomRobot';
import CesiumMap from '../Map.jsx'; import CesiumMap from '../Map.jsx';
import DeviceParamModal from './DeviceParamModal'; import DeviceParamModal from './DeviceParamModal';
import { getUAVState, getSiteDevice, getSiteUAVList, getsinglePlan, getRobotTaskList, getDeviceTotalData, updateDeviceAliasApi, hasPermission } from '@/api/device.ts'; import { getUAVState, getSiteDevice, getSiteUAVList, getsinglePlan, getRobotTaskList, getDeviceTotalData, updateDeviceAliasApi, hasPermission } from '@/api/device.ts';
import { getAlarmList } from '@/api/alarmApi.js'; import { getAlarmList, handleAlarm } from '@/api/alarmApi.js';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
@@ -48,6 +48,36 @@ import { backToRestPointCommand } from '@/api/mapEdit';
const { Content } = Layout; const { Content } = Layout;
const { Text, Title } = Typography; const { Text, Title } = Typography;
// 告警时间兼容:Java LocalDateTime 数组 / ISO 字符串 / 时间戳
const formatAlarmTime = (value: any, fmt = 'YYYY-MM-DD HH:mm:ss') => {
if (value === null || value === undefined || value === '') return '';
if (Array.isArray(value)) {
const [y, mo, d, h = 0, mi = 0, se = 0] = value;
if (!y) return '';
const dt = dayjs(new Date(y, mo - 1, d, h, mi, se));
return dt.isValid() ? dt.format(fmt) : '';
}
const dt = dayjs(value);
return dt.isValid() ? dt.format(fmt) : String(value);
};
// 告警标题:alarmTitle 是编码时改用 alarmContent 中文描述
const isAlarmCode = (value: any) => typeof value === 'string' && /^[A-Z][A-Z0-9_]*$/.test(value);
const getAlarmTitleText = (record: any) => {
const title = record?.alarmTitle;
return (isAlarmCode(title) ? record?.alarmContent : (title || record?.alarmContent)) || record?.alarmNo || '';
};
// 告警级别:兼容数字 1-4 / CRITICAL 等别名
const ALARM_LEVEL_ALIAS: Record<string, string> = {
'1': 'ERROR', '2': 'WARNING', '3': 'INFO', '4': 'INFO',
CRITICAL: 'ERROR', MAJOR: 'WARNING', MINOR: 'INFO',
};
const resolveAlarmLevel = (record: any) => {
const raw = String(record?.alertLevel ?? record?.alarmLevel ?? 'INFO').toUpperCase();
return ALARM_LEVEL_ALIAS[raw] || raw;
};
export default function DeviceOverviewPage() { export default function DeviceOverviewPage() {
@@ -312,6 +342,11 @@ export default function DeviceOverviewPage() {
if (!userInfo || !stationId) return; if (!userInfo || !stationId) return;
const controller = new DeviceController(userInfo, messageApi, stationId); const controller = new DeviceController(userInfo, messageApi, stationId);
controller.initMapPush((rtMap: any) => setRealtimeMap(rtMap || {})); controller.initMapPush((rtMap: any) => setRealtimeMap(rtMap || {}));
// 全局推送的新告警:合并到列表顶部(按 id 去重),只显示最近 5 条
controller.onDeviceErrorPush = (payload: any) => {
const incoming: any[] = Array.isArray(payload?.alarms) ? payload.alarms : [];
setAlarmList(incoming);
};
controllerRef.current = controller; controllerRef.current = controller;
return () => { return () => {
if (controllerRef.current) controllerRef.current.closeMapPush(); if (controllerRef.current) controllerRef.current.closeMapPush();
@@ -601,6 +636,24 @@ export default function DeviceOverviewPage() {
}) })
} }
// 手动处理告警:handleStatus=2 表示已关闭
const handleAlarmItem = async (record: any) => {
const alarmId = record?.id;
if (!alarmId) return;
try {
const res = await handleAlarm({ alarmId, handleStatus: 2 });
if (res?.code === 200) {
messageApi.success(t('alerts.handleSuccess'));
setAlarmList((prev) => prev.filter((a) => a.id !== alarmId));
} else {
messageApi.error(res?.msg || t('alerts.handleFail'));
}
} catch (err) {
console.error('处理告警失败', err);
messageApi.error(t('alerts.handleFail'));
}
};
const fetchAlarmList = async () => { const fetchAlarmList = async () => {
try { try {
const res = await getAlarmList({ pageNum: 1, pageSize: 5, siteId: stationId }); const res = await getAlarmList({ pageNum: 1, pageSize: 5, siteId: stationId });
@@ -945,7 +998,7 @@ export default function DeviceOverviewPage() {
> >
<Table <Table
rowKey="time" rowKey={(record) => record?.id ?? record?.alarmNo ?? record?.alarmTime}
size="small" size="small"
pagination={false} pagination={false}
dataSource={taskList} dataSource={taskList}
@@ -1029,33 +1082,57 @@ export default function DeviceOverviewPage() {
</>} </>}
variant="borderless" variant="borderless"
style={{ borderRadius: 8, height: '100%' }} style={{ borderRadius: 8, height: '100%' }}
extra={
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<Button size="small" style={{ borderRadius: 4, border: '1px solid #d9d9d9' }}>
{t('devices.fixed2AllLevels')}
</Button>
</div>
}
> >
<Table <Table
rowKey="time" rowKey={(record) => record?.id ?? record?.alarmNo ?? record?.alarmTitle}
size="small" size="small"
pagination={false} pagination={false}
dataSource={alarmList} dataSource={alarmList}
scroll={{ x: 'max-content' }} scroll={{ x: 'max-content' }}
columns={[ columns={[
{ title: t('common.time'), dataIndex: 'alarmTime', width: 90, render: (v) => <span style={{ fontSize: 13 }}>{v}</span> }, {
{ title: t('devices.device'), dataIndex: 'deviceName', width: 100, render: (v) => <span style={{ fontSize: 13 }}>{v}</span> }, title: t('common.time'),
dataIndex: 'alarmTime',
width: 145,
render: (v) => <span style={{ fontSize: 12, whiteSpace: 'nowrap' }}>{formatAlarmTime(v) || '-'}</span>
},
{
title: t('devices.device'),
dataIndex: 'deviceName',
width: 110,
ellipsis: true,
render: (v, record) => <span style={{ fontSize: 12 }}>{record?.deviceAlias || record?.deviceId || v || '-'}</span>
},
{ {
title: t('alerts.alarmTitle'), title: t('alerts.alarmTitle'),
dataIndex: 'alarmTitle', dataIndex: 'alarmContent',
width: 70, width: 220,
render: (_, record) => {
const text = getAlarmTitleText(record);
return (
<Tooltip title={text}>
<span style={{ fontSize: 12 }}>{text || '-'}</span>
</Tooltip>
);
}
}, },
{ {
title: t('alerts.alertLevel'), dataIndex: 'alertLevel', render: (l) => <AlarmLevelTag level={l} size="small" /> title: t('alerts.alertLevel'),
width: 70,
render: (_, record) => <AlarmLevelTag level={resolveAlarmLevel(record)} size="small" />
},
{
title: t('alerts.handle'),
width: 70,
render: (_, record) => record?.handleStatus === 2
? <Tag style={{ fontSize: 11, margin: 0 }}>{t('alerts.handled')}</Tag>
: (
<Button type="link" size="small" style={{ padding: 0, fontSize: 12 }} onClick={() => handleAlarmItem(record)}>
{t('alerts.handle')}
</Button>
)
}, },
{ title: '', width: 70, render: (_, record) => record.level ? <Tag color="red" style={{ fontSize: 11, margin: 0 }}>{record.level}</Tag> : null }
]} ]}
/> />
<div style={{ textAlign: 'center', marginTop: 8 }}> <div style={{ textAlign: 'center', marginTop: 8 }}>

View File

@@ -734,6 +734,7 @@ export default function DeviceStatusPage() {
const handleGamepadUpdate = useCallback((state) => { const handleGamepadUpdate = useCallback((state) => {
// 无控制权限时:不发送消息,且只发起一次权限申请(避免手柄/方向盘高频更新刷屏) // 无控制权限时:不发送消息,且只发起一次权限申请(避免手柄/方向盘高频更新刷屏)
if (!isControlled) { if (!isControlled) {
messageApi.warning("请获取控制权限");
//if (!hasRequestedControlRef.current && !connecting) { //if (!hasRequestedControlRef.current && !connecting) {
// hasRequestedControlRef.current = true; // hasRequestedControlRef.current = true;
// handleControlModal(); // handleControlModal();
@@ -741,9 +742,12 @@ export default function DeviceStatusPage() {
//return; //return;
} }
console.log(realtimePosition?.controlMode, "现在的控制controlmode") console.log(realtimePosition?.controlMode, "现在的控制controlmode")
if (realtimePosition?.controlMode && (realtimePosition?.controlMode != 3 || realtimePosition?.controlMode != 0)) { if (
realtimePosition?.controlMode != 3 &&
realtimePosition?.controlMode != 0 &&
realtimePosition?.controlMode != null
) {
messageApi.warning(t('devices.noRemoteControl')); messageApi.warning(t('devices.noRemoteControl'));
//return;
} }
console.log('Gamepad state updated:', state); console.log('Gamepad state updated:', state);
// 记录方向盘 xy 坐标,用于倒车影像叠加层 // 记录方向盘 xy 坐标,用于倒车影像叠加层
@@ -756,7 +760,11 @@ export default function DeviceStatusPage() {
const gamepadWarnRef = useRef(0); const gamepadWarnRef = useRef(0);
const blockIfGamepadConnected = useCallback(() => { const blockIfGamepadConnected = useCallback(() => {
// 没连接手柄 或 还没获取控制权限 → 不拦截(没控制权限本来就发不出消息) // 没连接手柄 或 还没获取控制权限 → 不拦截(没控制权限本来就发不出消息)
if (!isGamepadConnected || !isControlled) return false; if (!isGamepadConnected) return false;
if (!isControlled) {
messageApi.warning("请获取控制权限");
return false;
}
const now = Date.now(); const now = Date.now();
if (now - gamepadWarnRef.current > 2000) { if (now - gamepadWarnRef.current > 2000) {
gamepadWarnRef.current = now; gamepadWarnRef.current = now;

View File

@@ -54,8 +54,8 @@ export default function RobotTaskPage() {
const [robotStats, setRobotStats] = useState<ViewStats>({}); const [robotStats, setRobotStats] = useState<ViewStats>({});
setSelectedMachine((prev) => prev || firstRobot.value); const [droneStats, setDroneStats] = useState<ViewStats>({});
setSelectedGroup((prev) => prev || firstRobot.group);
const [robotOnline, setRobotOnline] = useState({ online: 0, total: 0 }); const [robotOnline, setRobotOnline] = useState({ online: 0, total: 0 });

View File

@@ -340,11 +340,49 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
}, []); }, []);
// 切换场站时统一清理旧场站残留:地图画线、机器、实时数据、任务执行状态等
useEffect(() => {
if (!stationId) return;
// 清空地图上所有画的线、打点、规划点、规划区域
setPolyPoints([]);
setPoints([]);
setProPoints({});
setRouteMode('');
setClearNavLine(v => v + 1);
setClearPlanLine(v => v + 1);
setNum(v => v + 1);
setFocusLocation(null);
// 清空上一个场站的设备/实时数据
setDevices([]);
setRealtimeMap({});
// 清空上一个场站的任务执行与机器状态
setExecute(false);
setExecutingRobot(null);
setShowVideo(false);
setRunningPoolTask(null);
setExcuteStatus('stop');
// 清空上一个场站的任务下发选择
setDispatchRouteIds([]);
setDispatchRobotSns([]);
setSelectedRouteForExecute(null);
setSelectedRobotForExecute(null);
setExecuteModalVisible(false);
// 清空地图编辑器区域选中
setEditorType(null);
}, [stationId]);
// 全量设备实时状态 WebSocket(mapPush):实时数据统一从这里获取,退出页面断开连接 // 全量设备实时状态 WebSocket(mapPush):实时数据统一从这里获取,退出页面断开连接
useEffect(() => { useEffect(() => {
if (!userInfo || !stationId || !controllerRef.current) return; if (!userInfo || !stationId || !controllerRef.current) return;
const controller = controllerRef.current; const controller = controllerRef.current;
controller.siteId = stationId; controller.siteId = stationId;
// 切换场站时先清空上一站的实时缓存,避免跨站脏数据残留
setRealtimeMap({});
controller.initMapPush((rtMap: any) => setRealtimeMap(rtMap || {})); controller.initMapPush((rtMap: any) => setRealtimeMap(rtMap || {}));
return () => { return () => {
controller.closeMapPush?.(); controller.closeMapPush?.();

View File

@@ -51,6 +51,7 @@ export default class DeviceController {
this.onIsExecuting = null; this.onIsExecuting = null;
this.handleArrivedPoint = null; this.handleArrivedPoint = null;
this.onDetectionReport = null; this.onDetectionReport = null;
this.onDeviceErrorPush = null;
// 全量设备实时状态(mapPush)连接 // 全量设备实时状态(mapPush)连接
this.mapPushWs = null; this.mapPushWs = null;
@@ -172,6 +173,53 @@ export default class DeviceController {
this.deviceStatusChangedMsg?.(msg); this.deviceStatusChangedMsg?.(msg);
} }
if (msg?.type == 'device_error_push') {
console.log('device_error_push', msg);
const list = Array.isArray(msg?.alarms)
? msg.alarms
: Array.isArray(msg?.data?.alarms)
? msg.data.alarms
: Array.isArray(msg?.data) ? msg.data : [];
const levelMap = { 1: 'ERROR', 2: 'WARNING', 3: 'INFO', 4: 'INFO' };
// 后端 LocalDateTime 以数组 [年,月,日,时,分,秒,纳秒] 下发,需单独转换
const formatAlarmTime = (time) => {
if (time === null || time === undefined || time === '') return '';
if (Array.isArray(time)) {
const [y, mo, d, h = 0, mi = 0, se = 0] = time;
if (!y) return '';
const dt = dayjs(new Date(y, mo - 1, d, h, mi, se));
return dt.isValid() ? dt.format('YYYY-MM-DD HH:mm:ss') : '';
}
const dt = dayjs(time);
return dt.isValid() ? dt.format('YYYY-MM-DD HH:mm:ss') : String(time);
};
// alarmTitle 若为编码(如 SAFETY_FAULT_HEARTBEAT_TIMEOUT),改用 alarmContent 中文描述
const isAlarmCode = (val) => typeof val === 'string' && /^[A-Z][A-Z0-9_]*$/.test(val);
const alarms = list.map((a) => {
if (!a || typeof a !== 'object') return null;
// 统一告警级别:后端 ErrorLevel 1严重/2重要/3一般/4提示 → ERROR/WARNING/INFO
const rawLevel = a.alertLevel ?? a.alarmLevel;
const alertLevel = typeof rawLevel === 'number'
? (levelMap[rawLevel] || 'INFO')
: String(rawLevel || 'INFO').toUpperCase();
const rawTitle = a.alarmTitle;
const alarmTitle = (isAlarmCode(rawTitle) ? (a.alarmContent || rawTitle) : (rawTitle || a.alarmContent)) || a.alarmNo || '';
return {
...a,
alertLevel,
alarmTitle,
handleStatus: a.handleStatus ?? 1,
alarmTime: formatAlarmTime(a.alarmTime),
};
}).filter(Boolean);
if (alarms.length) {
this.onDeviceErrorPush?.({
deviceId: msg?.deviceId || msg?.data?.deviceId,
alarms,
});
}
}
if (msg?.type == 'route_post') { if (msg?.type == 'route_post') {
console.log('route_post'); console.log('route_post');
this.onRoutePost?.(msg); this.onRoutePost?.(msg);

View File

@@ -1878,6 +1878,7 @@ const zh = {
handled: '已处理', handled: '已处理',
restored: '已恢复', restored: '已恢复',
ignored: '已忽略', ignored: '已忽略',
ignore: "忽略",
unableToHandle: '无法处理', unableToHandle: '无法处理',
manufacturerHandling: '厂家处理中', manufacturerHandling: '厂家处理中',
falseAlarm: '误报', falseAlarm: '误报',

View File

@@ -28,7 +28,7 @@ import { RootState } from '../store';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import { getRobotTaskList, getSiteDevice, getDeviceTastPool, getSiteDeviceTaskHistory, getRouteByTask, getSingleRouteList, getTaskPath } from '../api/device'; import { getRobotTaskList, getSiteDevice, getDeviceTastPool, getSiteDeviceTaskHistory, getRouteByTask, getSingleRouteList, getTaskPath } from '../api/device';
import { getAlarmList, getAlarmStatistics } from '../api/alarmApi'; import { getAlarmList, getAlarmStatistics, handleAlarm } from '../api/alarmApi';
import { alarmTypeMap } from '@/constants.js'; import { alarmTypeMap } from '@/constants.js';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import DeviceController from '../components/devices/DeviceController'; import DeviceController from '../components/devices/DeviceController';
@@ -51,6 +51,41 @@ const TASK_STATUS_MAP: Record<string, { text: string; color: string }> = {
const getTaskStatusStyle = (status?: string) => const getTaskStatusStyle = (status?: string) =>
TASK_STATUS_MAP[String(status || '').toUpperCase()] || { text: status || '--', color: 'default' }; TASK_STATUS_MAP[String(status || '').toUpperCase()] || { text: status || '--', color: 'default' };
// 告警时间兼容:Java LocalDateTime 数组 / ISO 字符串 / 时间戳
const formatAlarmTime = (value: any, fmt = 'HH:mm:ss') => {
if (value === null || value === undefined || value === '') return '';
if (Array.isArray(value)) {
const [y, mo, d, h = 0, mi = 0, se = 0] = value;
if (!y) return '';
const dt = dayjs(new Date(y, mo - 1, d, h, mi, se));
return dt.isValid() ? dt.format(fmt) : '';
}
const dt = dayjs(value);
return dt.isValid() ? dt.format(fmt) : String(value);
};
// 告警标题:alarmTitle 是编码(如 SAFETY_FAULT_HEARTBEAT_TIMEOUT)时改用 alarmContent
const isAlarmCode = (value: any) => typeof value === 'string' && /^[A-Z][A-Z0-9_]*$/.test(value);
const getAlarmTitleText = (record: any) => {
const title = record?.alarmTitle;
return (isAlarmCode(title) ? record?.alarmContent : (title || record?.alarmContent)) || record?.alarmNo || '';
};
// 告警级别展示:严重 / 重要 / 提示
const ALARM_LEVEL_ALIAS: Record<string, string> = {
'1': 'ERROR', '2': 'WARNING', '3': 'INFO', '4': 'INFO',
CRITICAL: 'ERROR', MAJOR: 'WARNING', MINOR: 'INFO',
};
const ALARM_LEVEL_META: Record<string, { text: string; color: string; tag: string }> = {
ERROR: { text: '严重', color: '#ff4d4f', tag: 'red' },
WARNING: { text: '重要', color: '#faad14', tag: 'orange' },
INFO: { text: '提示', color: '#1677ff', tag: 'blue' },
};
const resolveAlarmLevel = (record: any) => {
const raw = String(record?.alertLevel ?? record?.alarmLevel ?? 'INFO').toUpperCase();
return ALARM_LEVEL_ALIAS[raw] || raw;
};
// 浅色主题卡片组件 // 浅色主题卡片组件
const MonitorCard: React.FC<{ title: string; icon: React.ReactNode; children: React.ReactNode; extra?: React.ReactNode; height?: number | string; bodyOverflow?: string }> = ({ title, icon, children, extra, height, bodyOverflow = 'auto' }) => ( const MonitorCard: React.FC<{ title: string; icon: React.ReactNode; children: React.ReactNode; extra?: React.ReactNode; height?: number | string; bodyOverflow?: string }> = ({ title, icon, children, extra, height, bodyOverflow = 'auto' }) => (
<Card <Card
@@ -158,12 +193,39 @@ const TaskMonitorPage: React.FC = () => {
controller.deviceStatusChangedMsg = refreshData; controller.deviceStatusChangedMsg = refreshData;
controller.initMapPush((rtMap: any) => setRealtimeMap(rtMap || {})); controller.initMapPush((rtMap: any) => setRealtimeMap(rtMap || {}));
controller.onDetectionReport = handleDetectionReport; controller.onDetectionReport = handleDetectionReport;
// 全局推送的新告警:合并到列表顶部
controller.onDeviceErrorPush = (payload: any) => {
const incoming: any[] = Array.isArray(payload?.alarms) ? payload.alarms : [];
if (!incoming.length) return;
setAlarmList((prev: any[]) => {
const incomingIds = new Set(incoming.map((a) => a.id));
return [...incoming, ...prev.filter((a) => !incomingIds.has(a.id))].slice(0, 5);
});
};
controllerRef.current = controller; controllerRef.current = controller;
return () => { return () => {
controller.closeMapPush(); controller.closeMapPush();
}; };
}, [userInfo, stationId]); }, [userInfo, stationId]);
// 手动处理告警:handleStatus=2 表示已关闭
const handleAlarmItem = async (record: any) => {
const alarmId = record?.id;
if (!alarmId) return;
try {
const res = await handleAlarm({ alarmId, handleStatus: 2 });
if (res?.code === 200) {
utils.message.success('处理成功');
setAlarmList((prev: any[]) => prev.filter((a) => a.id !== alarmId));
} else {
utils.message.error(res?.msg || '处理失败');
}
} catch (err) {
console.error('处理告警失败', err);
utils.message.error('处理失败');
}
};
const fetchRouteDetail = async (id) => { const fetchRouteDetail = async (id) => {
try { try {
const params = { const params = {
@@ -569,28 +631,36 @@ const TaskMonitorPage: React.FC = () => {
</MonitorCard> </MonitorCard>
<MonitorCard title="告警中心" icon={<Bell size={18} color="#ff4d4f" />} extra={<Space size={8}><Badge count={alarmList.filter(a => a.handleStatus === 1).length} overflowCount={99} /><Button type="link" size="small" onClick={() => navigate('/alerts/all')}>查看更多</Button></Space>} height="25%"> <MonitorCard title="告警中心" icon={<Bell size={18} color="#ff4d4f" />} extra={<Space size={8}><Badge count={alarmList.filter((a: any) => a.handleStatus !== 2).length} overflowCount={99} /><Button type="link" size="small" onClick={() => navigate('/alerts/all')}>查看更多</Button></Space>} height="25%">
<List <List
size="small" size="small"
dataSource={alarmList.filter(a => a.handleStatus === 1).slice(0, 3)} dataSource={alarmList.filter((a: any) => a.handleStatus !== 2).slice(0, 3)}
renderItem={(item: any) => ( renderItem={(item: any) => {
<List.Item style={{ padding: '8px 0' }}> const level = resolveAlarmLevel(item);
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, width: '100%' }}> const meta = ALARM_LEVEL_META[level] || ALARM_LEVEL_META.INFO;
<AlertTriangle size={16} color={item.alarmLevel === 'ERROR' ? '#ff4d4f' : '#faad14'} style={{ marginTop: 2 }} /> const title = getAlarmTitleText(item);
<div style={{ flex: 1 }}> return (
<div style={{ fontSize: 13, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}> <List.Item style={{ padding: '8px 0' }}>
<span style={{ fontWeight: 500, color: '#262626' }}>{item.alarmTitle}</span> <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, width: '100%' }}>
<Tag color={item.alarmLevel === 'ERROR' ? 'red' : 'orange'} size="small" style={{ margin: 0, borderRadius: 4 }}> <AlertTriangle size={16} color={meta.color} style={{ marginTop: 2 }} />
{item.alarmLevel === 'ERROR' ? '紧急' : '重要'} <div style={{ flex: 1, minWidth: 0 }}>
</Tag> <div style={{ fontSize: 13, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}>
</div> <Tooltip title={title}>
<div style={{ fontSize: 11, color: '#8c8c8c', marginTop: 4 }}> <span style={{ fontWeight: 500, color: '#262626', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{title || '--'}</span>
{item.deviceName} | {dayjs(item.alarmTime).format('HH:mm:ss')} </Tooltip>
<Space size={4}>
<Tag color={meta.tag} size="small" style={{ margin: 0, borderRadius: 4 }}>{meta.text}</Tag>
<Button type="link" size="small" style={{ padding: 0, fontSize: 12 }} onClick={() => handleAlarmItem(item)}>处理</Button>
</Space>
</div>
<div style={{ fontSize: 11, color: '#8c8c8c', marginTop: 4, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{item.deviceAlias || item.deviceName || item.deviceId || '--'} | {item.alarmTime}
</div>
</div> </div>
</div> </div>
</div> </List.Item>
</List.Item> );
)} }}
locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无未处理告警" /> }} locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无未处理告警" /> }}
/> />
</MonitorCard> </MonitorCard>