feat(工单系统): 实现完整的工单管理功能

添加工单系统核心功能,包括:
- 工单模型及相关API接口
- 故障分类管理
- 工单操作记录
- 前端工单管理页面
- 统计报表功能
- 测试框架支持

后端新增工单相关路由和模型,前端添加工单管理界面和统计报表
This commit is contained in:
zhang1106
2025-12-25 16:49:00 +08:00
parent a911d02999
commit bfb789dfd9
17 changed files with 9230 additions and 23 deletions
+2162 -1
View File
File diff suppressed because it is too large Load Diff
+6 -1
View File
@@ -20,7 +20,12 @@
"xlsx": "^0.18.5"
},
"devDependencies": {
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.1",
"@testing-library/user-event": "^14.6.1",
"@vitejs/plugin-react": "^4.0.3",
"vite": "^4.4.9"
"jsdom": "^27.3.0",
"vite": "^4.4.9",
"vitest": "^4.0.16"
}
}
+56 -1
View File
@@ -1,6 +1,6 @@
import React, { useState } from 'react';
import { Layout, Menu, theme, Button, Dropdown, Avatar, message, Space, Divider } from 'antd';
import { BarChartOutlined, DatabaseOutlined, CloudServerOutlined, MenuUnfoldOutlined, MenuFoldOutlined, EyeOutlined, BuildOutlined, HomeOutlined, ShoppingCartOutlined, InboxOutlined, ImportOutlined, FileTextOutlined, UserOutlined, LogoutOutlined, UserOutlined as UserIcon, HistoryOutlined, AuditOutlined } from '@ant-design/icons';
import { BarChartOutlined, DatabaseOutlined, CloudServerOutlined, MenuUnfoldOutlined, MenuFoldOutlined, EyeOutlined, BuildOutlined, HomeOutlined, ShoppingCartOutlined, InboxOutlined, ImportOutlined, FileTextOutlined, UserOutlined, LogoutOutlined, UserOutlined as UserIcon, HistoryOutlined, AuditOutlined, ToolOutlined, ScheduleOutlined } from '@ant-design/icons';
import { BrowserRouter as Router, Routes, Route, Link, Navigate, useLocation, useNavigate } from 'react-router-dom';
import { useAuth } from './context/AuthContext';
import Dashboard from './pages/Dashboard';
@@ -17,6 +17,9 @@ import UserManagement from './pages/UserManagement';
import LoginHistory from './pages/LoginHistory';
import OperationLogs from './pages/OperationLogs';
import Login from './pages/Login';
import TicketManagement from './pages/TicketManagement';
import TicketCategoryManagement from './pages/TicketCategoryManagement';
import TicketStatistics from './pages/TicketStatistics';
import { Spin } from 'antd';
const { Header, Content, Sider } = Layout;
@@ -205,6 +208,28 @@ const AppLayout = ({ children }) => {
},
],
},
{
key: 'ticket-management',
icon: <ToolOutlined />,
label: '工单管理',
children: [
{
key: 'tickets',
icon: <ScheduleOutlined />,
label: <Link to="/tickets">工单列表</Link>,
},
{
key: 'ticket-categories',
icon: <InboxOutlined />,
label: <Link to="/ticket-categories">故障分类</Link>,
},
{
key: 'ticket-statistics',
icon: <BarChartOutlined />,
label: <Link to="/ticket-statistics">统计报表</Link>,
},
],
},
]}
/>
</Sider>
@@ -391,6 +416,36 @@ function App() {
</PrivateRoute>
}
/>
<Route
path="/tickets"
element={
<PrivateRoute>
<AppLayout>
<TicketManagement />
</AppLayout>
</PrivateRoute>
}
/>
<Route
path="/ticket-categories"
element={
<PrivateRoute>
<AppLayout>
<TicketCategoryManagement />
</AppLayout>
</PrivateRoute>
}
/>
<Route
path="/ticket-statistics"
element={
<PrivateRoute>
<AppLayout>
<TicketStatistics />
</AppLayout>
</PrivateRoute>
}
/>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</Router>
+25
View File
@@ -111,4 +111,29 @@ export const operationLogAPI = {
clear: (data) => api.delete('/operation-logs', { data })
};
export const ticketAPI = {
list: (params) => api.get('/tickets', { params }),
get: (ticketId) => api.get(`/tickets/${ticketId}`),
create: (data) => api.post('/tickets', data),
update: (ticketId, data) => api.put(`/tickets/${ticketId}`, data),
delete: (ticketId) => api.delete(`/tickets/${ticketId}`),
assign: (ticketId, data) => api.put(`/tickets/${ticketId}/assign`, data),
transfer: (ticketId, data) => api.put(`/tickets/${ticketId}/transfer`, data),
process: (ticketId, data) => api.put(`/tickets/${ticketId}/process`, data),
close: (ticketId, data) => api.put(`/tickets/${ticketId}/close`, data),
reopen: (ticketId, data) => api.put(`/tickets/${ticketId}/reopen`, data),
getOperations: (ticketId) => api.get(`/tickets/${ticketId}/operations`),
getStatistics: (params) => api.get('/tickets/statistics', { params })
};
export const ticketCategoryAPI = {
list: (params) => api.get('/ticket-categories', { params }),
get: (code) => api.get(`/ticket-categories/${code}`),
create: (data) => api.post('/ticket-categories', data),
update: (code, data) => api.put(`/ticket-categories/${code}`, data),
delete: (code) => api.delete(`/ticket-categories/${code}`),
tree: () => api.get('/ticket-categories/tree'),
init: () => api.post('/ticket-categories/init')
};
export default api;
@@ -0,0 +1,248 @@
import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, Select, message, Card, Space, Popconfirm } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, ReloadOutlined } from '@ant-design/icons';
import axios from 'axios';
const { Option } = Select;
function TicketCategoryManagement() {
const [categories, setCategories] = useState([]);
const [loading, setLoading] = useState(true);
const [modalVisible, setModalVisible] = useState(false);
const [editingCategory, setEditingCategory] = useState(null);
const [form] = Form.useForm();
const fetchCategories = async () => {
try {
setLoading(true);
const response = await axios.get('/api/ticket-categories');
setCategories(response.data || []);
} catch (error) {
message.error('获取故障分类列表失败');
console.error('获取故障分类列表失败:', error);
} finally {
setLoading(false);
}
};
const initCategories = async () => {
try {
await axios.post('/api/ticket-categories/init');
message.success('初始化分类成功');
fetchCategories();
} catch (error) {
message.error('初始化分类失败');
console.error('初始化分类失败:', error);
}
};
useEffect(() => {
fetchCategories();
}, []);
const showModal = (category = null) => {
setEditingCategory(category);
if (category) {
form.setFieldsValue({
name: category.name,
description: category.description,
priority: category.priority,
defaultPriority: category.defaultPriority,
expectedDuration: category.expectedDuration,
isActive: category.isActive
});
} else {
form.resetFields();
}
setModalVisible(true);
};
const handleCancel = () => {
setModalVisible(false);
setEditingCategory(null);
};
const handleSubmit = async (values) => {
try {
if (editingCategory) {
await axios.put(`/api/ticket-categories/${editingCategory.categoryId}`, values);
message.success('分类更新成功');
} else {
await axios.post('/api/ticket-categories', values);
message.success('分类创建成功');
}
setModalVisible(false);
fetchCategories();
setEditingCategory(null);
} catch (error) {
message.error(editingCategory ? '分类更新失败' : '分类创建失败');
console.error(error);
}
};
const handleDelete = async (categoryId) => {
try {
await axios.delete(`/api/ticket-categories/${categoryId}`);
message.success('分类删除成功');
fetchCategories();
} catch (error) {
message.error('分类删除失败');
console.error(error);
}
};
const columns = [
{
title: '分类ID',
dataIndex: 'categoryId',
key: 'categoryId',
width: 150
},
{
title: '分类名称',
dataIndex: 'name',
key: 'name',
width: 180
},
{
title: '分类说明',
dataIndex: 'description',
key: 'description',
width: 300,
ellipsis: true
},
{
title: '优先级',
dataIndex: 'priority',
key: 'priority',
width: 80
},
{
title: '默认优先级',
dataIndex: 'defaultPriority',
key: 'defaultPriority',
width: 100
},
{
title: '预计时长(分钟)',
dataIndex: 'expectedDuration',
key: 'expectedDuration',
width: 120
},
{
title: '启用状态',
dataIndex: 'isActive',
key: 'isActive',
width: 100,
render: (text) => (
<span style={{ color: text ? 'green' : 'red' }}>
{text ? '启用' : '禁用'}
</span>
)
},
{
title: '操作',
key: 'action',
width: 150,
render: (_, record) => (
<Space size="small">
<Button
type="link"
icon={<EditOutlined />}
onClick={() => showModal(record)}
>
编辑
</Button>
<Popconfirm
title="确认删除"
description="确定要删除这个分类吗?"
onConfirm={() => handleDelete(record.categoryId)}
okText="确认"
cancelText="取消"
>
<Button type="link" danger icon={<DeleteOutlined />}>
删除
</Button>
</Popconfirm>
</Space>
)
}
];
return (
<div style={{ padding: 24 }}>
<Card title="故障分类管理" extra={
<Space>
<Button icon={<ReloadOutlined />} onClick={initCategories}>
初始化分类
</Button>
<Button type="primary" icon={<PlusOutlined />} onClick={() => showModal()}>
添加分类
</Button>
</Space>
}>
<Table
columns={columns}
dataSource={categories}
rowKey="categoryId"
loading={loading}
pagination={{ pageSize: 10 }}
/>
</Card>
<Modal
title={editingCategory ? '编辑分类' : '添加分类'}
open={modalVisible}
onCancel={handleCancel}
footer={null}
width={600}
>
<Form form={form} layout="vertical" onFinish={handleSubmit}>
<Form.Item name="name" label="分类名称" rules={[{ required: true }]}>
<Input placeholder="请输入分类名称(如:系统故障、硬件故障等)" />
</Form.Item>
<Form.Item name="description" label="分类说明">
<Input.TextArea rows={3} placeholder="请输入分类说明,说明此类故障代表什么问题" />
</Form.Item>
<Form.Item name="priority" label="排序优先级">
<Input type="number" placeholder="数字越小排序越靠前" />
</Form.Item>
<Form.Item name="defaultPriority" label="默认优先级">
<Select placeholder="选择默认优先级">
<Option value="low"></Option>
<Option value="medium"></Option>
<Option value="high"></Option>
<Option value="urgent">紧急</Option>
</Select>
</Form.Item>
<Form.Item name="expectedDuration" label="预计处理时长(分钟)">
<Input type="number" placeholder="请输入预计处理时长" />
</Form.Item>
<Form.Item name="isActive" label="启用状态" initialValue={true}>
<Select>
<Option value={true}>启用</Option>
<Option value={false}>禁用</Option>
</Select>
</Form.Item>
<Form.Item>
<Space>
<Button type="primary" htmlType="submit">
{editingCategory ? '更新' : '创建'}
</Button>
<Button onClick={handleCancel}>取消</Button>
</Space>
</Form.Item>
</Form>
</Modal>
</div>
);
}
export default TicketCategoryManagement;
+654
View File
@@ -0,0 +1,654 @@
import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, Select, DatePicker, message, Card, Space, Tag, Dropdown, Menu, Tabs, Timeline, Descriptions } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, EyeOutlined, MoreOutlined, UserOutlined, ToolOutlined, CheckCircleOutlined, SyncOutlined, ClockCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import axios from 'axios';
import dayjs from 'dayjs';
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const { TabPane } = Tabs;
function TicketManagement() {
const [tickets, setTickets] = useState([]);
const [devices, setDevices] = useState([]);
const [categories, setCategories] = useState([]);
const [loading, setLoading] = useState(true);
const [modalVisible, setModalVisible] = useState(false);
const [detailModalVisible, setDetailModalVisible] = useState(false);
const [processingModalVisible, setProcessingModalVisible] = useState(false);
const [editingTicket, setEditingTicket] = useState(null);
const [selectedTicket, setSelectedTicket] = useState(null);
const [operationRecords, setOperationRecords] = useState([]);
const [form] = Form.useForm();
const [processForm] = Form.useForm();
const [searchForm] = Form.useForm();
const [pagination, setPagination] = useState({
current: 1,
pageSize: 10,
total: 0,
pageSizeOptions: ['10', '20', '30', '50'],
showSizeChanger: true,
showTotal: (total) => `${total} 条记录`
});
const [searchFilters, setSearchFilters] = useState({});
const fetchTickets = async (page = 1, pageSize = 10, filters = {}) => {
try {
setLoading(true);
const params = {
page,
pageSize,
...searchFilters,
...filters
};
const response = await axios.get('/api/tickets', { params });
const { tickets: ticketList, total } = response.data;
setTickets(ticketList);
setPagination(prev => ({ ...prev, current: page, pageSize, total }));
} catch (error) {
message.error('获取工单列表失败');
console.error('获取工单列表失败:', error);
} finally {
setLoading(false);
}
};
const fetchDevices = async () => {
try {
const response = await axios.get('/api/devices', { params: { pageSize: 1000 } });
setDevices(response.data.devices || []);
} catch (error) {
console.error('获取设备列表失败:', error);
}
};
const fetchCategories = async () => {
try {
const response = await axios.get('/api/ticket-categories');
setCategories(response.data || []);
} catch (error) {
console.error('获取分类列表失败:', error);
}
};
const fetchTicketDetail = async (ticketId) => {
try {
const [ticketRes, operationsRes] = await Promise.all([
axios.get(`/api/tickets/${ticketId}`),
axios.get(`/api/tickets/${ticketId}/operations`)
]);
setSelectedTicket(ticketRes.data);
setOperationRecords(operationsRes.data || []);
setDetailModalVisible(true);
} catch (error) {
message.error('获取工单详情失败');
console.error('获取工单详情失败:', error);
}
};
useEffect(() => {
fetchTickets();
fetchDevices();
fetchCategories();
}, []);
const showModal = (ticket = null) => {
setEditingTicket(ticket);
if (ticket) {
const ticketData = { ...ticket };
if (ticketData.expectedCompletionDate) {
ticketData.expectedCompletionDate = dayjs(ticketData.expectedCompletionDate);
}
if (ticketData.completionDate) {
ticketData.completionDate = dayjs(ticketData.completionDate);
}
form.setFieldsValue(ticketData);
} else {
form.resetFields();
}
setModalVisible(true);
};
const handleCancel = () => {
setModalVisible(false);
setEditingTicket(null);
};
const handleSubmit = async (values) => {
try {
const ticketData = {
...values,
expectedCompletionDate: values.expectedCompletionDate ? values.expectedCompletionDate.format('YYYY-MM-DD HH:mm:ss') : null,
completionDate: values.completionDate ? values.completionDate.format('YYYY-MM-DD HH:mm:ss') : null
};
if (editingTicket) {
await axios.put(`/api/tickets/${editingTicket.ticketId}`, ticketData);
message.success('工单更新成功');
} else {
const user = JSON.parse(localStorage.getItem('user') || '{}');
ticketData.reporterId = user.userId || localStorage.getItem('userId') || 'USER001';
ticketData.reporterName = user.username || '系统用户';
await axios.post('/api/tickets', ticketData);
message.success('工单创建成功');
}
setModalVisible(false);
fetchTickets();
setEditingTicket(null);
} catch (error) {
message.error(editingTicket ? '工单更新失败' : '工单创建失败');
console.error(error);
}
};
const handleDelete = async (ticketId) => {
Modal.confirm({
title: '确认删除',
content: '确定要删除这个工单吗?',
okText: '删除',
okType: 'danger',
cancelText: '取消',
onOk: async () => {
try {
await axios.delete(`/api/tickets/${ticketId}`);
message.success('工单删除成功');
fetchTickets();
} catch (error) {
message.error('工单删除失败');
console.error(error);
}
}
});
};
const handleProcess = (ticket) => {
setSelectedTicket(ticket);
processForm.resetFields();
setProcessingModalVisible(true);
};
const handleProcessSubmit = async (values) => {
try {
await axios.put(`/api/tickets/${selectedTicket.ticketId}/process`, {
...values,
operatorId: localStorage.getItem('userId'),
operatorName: JSON.parse(localStorage.getItem('user') || '{}').username
});
message.success('工单处理完成');
setProcessingModalVisible(false);
fetchTickets();
} catch (error) {
message.error('处理失败');
console.error(error);
}
};
const handleStatusChange = async (ticketId, newStatus) => {
try {
await axios.put(`/api/tickets/${ticketId}/status`, {
status: newStatus,
operatorId: localStorage.getItem('userId'),
operatorName: JSON.parse(localStorage.getItem('user') || '{}').username
});
message.success('状态更新成功');
fetchTickets();
} catch (error) {
message.error('状态更新失败');
console.error(error);
}
};
const handleSearch = (values) => {
setSearchFilters(values);
fetchTickets(1, pagination.pageSize, values);
};
const handleReset = () => {
searchForm.resetFields();
setSearchFilters({});
fetchTickets(1, pagination.pageSize, {});
};
const handleTableChange = (paginationInfo) => {
setPagination(paginationInfo);
fetchTickets(paginationInfo.current, paginationInfo.pageSize, searchFilters);
};
const getStatusColor = (status) => {
const colors = {
pending: 'orange',
in_progress: 'processing',
completed: 'green',
closed: 'default'
};
return colors[status] || 'default';
};
const getStatusText = (status) => {
const texts = {
pending: '待处理',
in_progress: '处理中',
completed: '已完成',
closed: '已关闭'
};
return texts[status] || status;
};
const getPriorityColor = (priority) => {
const colors = {
low: 'green',
medium: 'orange',
high: 'red',
urgent: 'magenta'
};
return colors[priority] || 'default';
};
const getPriorityText = (priority) => {
const texts = {
low: '低',
medium: '中',
high: '高',
urgent: '紧急'
};
return texts[priority] || priority;
};
const columns = [
{
title: '工单编号',
dataIndex: 'ticketId',
key: 'ticketId',
width: 150,
render: (text, record) => (
<Button type="link" onClick={() => fetchTicketDetail(text)}>
{text}
</Button>
)
},
{
title: '标题',
dataIndex: 'title',
key: 'title',
width: 200,
ellipsis: true
},
{
title: '设备信息',
key: 'deviceInfo',
width: 180,
render: (_, record) => (
<div>
<div>{record.deviceName}</div>
<div style={{ fontSize: 12, color: '#888' }}>{record.serialNumber}</div>
</div>
)
},
{
title: '故障分类',
dataIndex: 'faultCategory',
key: 'faultCategory',
width: 120,
render: (text) => text ? <Tag>{text}</Tag> : '-'
},
{
title: '优先级',
dataIndex: 'priority',
key: 'priority',
width: 80,
render: (priority) => (
<Tag color={getPriorityColor(priority)}>
{getPriorityText(priority)}
</Tag>
)
},
{
title: '状态',
dataIndex: 'status',
key: 'status',
width: 100,
render: (status) => (
<Tag color={getStatusColor(status)}>
{getStatusText(status)}
</Tag>
)
},
{
title: '报告人',
dataIndex: ['reporter', 'username'],
key: 'reporter',
width: 100,
render: (text) => text || '-'
},
{
title: '创建时间',
dataIndex: 'createdAt',
key: 'createdAt',
width: 160,
render: (text) => text ? dayjs(text).format('YYYY-MM-DD HH:mm') : '-'
},
{
title: '期望完成时间',
dataIndex: 'expectedCompletionDate',
key: 'expectedCompletionDate',
width: 160,
render: (text) => text ? dayjs(text).format('YYYY-MM-DD HH:mm') : '-'
},
{
title: '操作',
key: 'action',
width: 150,
fixed: 'right',
render: (_, record) => (
<Space size="small">
<Button
type="link"
icon={<EyeOutlined />}
onClick={() => fetchTicketDetail(record.ticketId)}
>
详情
</Button>
{record.status === 'pending' ? (
<Button
type="link"
icon={<ToolOutlined />}
onClick={() => handleProcess(record)}
>
处理
</Button>
) : null}
<Dropdown
overlay={
<Menu>
<Menu.Item key="edit" icon={<EditOutlined />} onClick={() => showModal(record)}>
编辑
</Menu.Item>
{(record.status === 'pending' || record.status === 'in_progress') && (
<Menu.Item
key="complete"
icon={<CheckCircleOutlined />}
onClick={() => handleStatusChange(record.ticketId, 'completed')}
>
完成工单
</Menu.Item>
)}
{record.status === 'completed' && (
<Menu.Item
key="close"
icon={<CloseCircleOutlined />}
onClick={() => handleStatusChange(record.ticketId, 'closed')}
>
关闭工单
</Menu.Item>
)}
<Menu.Item
key="delete"
icon={<DeleteOutlined />}
danger
onClick={() => handleDelete(record.ticketId)}
>
删除
</Menu.Item>
</Menu>
}
>
<Button icon={<MoreOutlined />} />
</Dropdown>
</Space>
)
}
];
return (
<div style={{ padding: 24 }}>
<Card title="工单管理" extra={
<Button type="primary" icon={<PlusOutlined />} onClick={() => showModal()}>
创建工单
</Button>
}>
<Form form={searchForm} layout="inline" onFinish={handleSearch} style={{ marginBottom: 16 }}>
<Form.Item name="keyword" label="关键词">
<Input placeholder="标题/设备/描述" allowClear style={{ width: 200 }} />
</Form.Item>
<Form.Item name="status" label="状态">
<Select placeholder="选择状态" allowClear style={{ width: 120 }}>
<Option value="pending">待处理</Option>
<Option value="in_progress">处理中</Option>
<Option value="completed">已完成</Option>
<Option value="closed">已关闭</Option>
</Select>
</Form.Item>
<Form.Item name="priority" label="优先级">
<Select placeholder="选择优先级" allowClear style={{ width: 100 }}>
<Option value="low"></Option>
<Option value="medium"></Option>
<Option value="high"></Option>
<Option value="urgent">紧急</Option>
</Select>
</Form.Item>
<Form.Item name="faultCategory" label="故障分类">
<Select placeholder="选择分类" allowClear style={{ width: 150 }}>
{categories.map(cat => (
<Option key={cat.categoryId} value={cat.name}>{cat.name}</Option>
))}
</Select>
</Form.Item>
<Form.Item>
<Button type="primary" icon={<SearchOutlined />} htmlType="submit">
搜索
</Button>
<Button style={{ marginLeft: 8 }} onClick={handleReset}>
重置
</Button>
</Form.Item>
</Form>
<Table
columns={columns}
dataSource={tickets}
rowKey="ticketId"
pagination={pagination}
loading={loading}
onChange={handleTableChange}
scroll={{ x: 1400 }}
/>
</Card>
<Modal
title={editingTicket ? '编辑工单' : '创建工单'}
open={modalVisible}
onCancel={handleCancel}
footer={null}
width={700}
>
<Form form={form} layout="vertical" onFinish={handleSubmit}>
<Form.Item name="title" label="工单标题" rules={[{ required: true }]}>
<Input placeholder="请输入工单标题" />
</Form.Item>
<Form.Item name="deviceId" label="关联设备" rules={[{ required: true }]}>
<Select placeholder="选择设备" showSearch optionFilterProp="children">
{devices.map(device => (
<Option key={device.deviceId} value={device.deviceId}>
{device.name} - {device.serialNumber}
</Option>
))}
</Select>
</Form.Item>
<Form.Item name="faultCategory" label="故障分类" rules={[{ required: true }]}>
<Select placeholder="选择故障分类">
{categories.map(cat => (
<Option key={cat.categoryId} value={cat.name}>{cat.name}</Option>
))}
</Select>
</Form.Item>
<Form.Item name="priority" label="优先级" rules={[{ required: true }]}>
<Select placeholder="选择优先级">
<Option value="low"></Option>
<Option value="medium"></Option>
<Option value="high"></Option>
<Option value="urgent">紧急</Option>
</Select>
</Form.Item>
<Form.Item name="description" label="故障描述">
<TextArea rows={4} placeholder="请详细描述故障情况" />
</Form.Item>
<Form.Item name="expectedCompletionDate" label="期望完成时间">
<DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="resolution" label="解决方案">
<TextArea rows={3} placeholder="请输入解决方案" />
</Form.Item>
<Form.Item>
<Space>
<Button type="primary" htmlType="submit">
{editingTicket ? '更新' : '创建'}
</Button>
<Button onClick={handleCancel}>取消</Button>
</Space>
</Form.Item>
</Form>
</Modal>
<Modal
title="处理工单"
open={processingModalVisible}
onCancel={() => setProcessingModalVisible(false)}
footer={null}
width={600}
>
<Form form={processForm} layout="vertical" onFinish={handleProcessSubmit}>
<Descriptions bordered column={1} style={{ marginBottom: 16 }}>
<Descriptions.Item label="工单编号">{selectedTicket?.ticketId}</Descriptions.Item>
<Descriptions.Item label="标题">{selectedTicket?.title}</Descriptions.Item>
<Descriptions.Item label="设备">{selectedTicket?.deviceName}</Descriptions.Item>
<Descriptions.Item label="故障描述">{selectedTicket?.description}</Descriptions.Item>
</Descriptions>
<Form.Item name="solution" label="处理方案" rules={[{ required: true }]}>
<TextArea rows={4} placeholder="请详细描述处理方案和步骤" />
</Form.Item>
<Form.Item name="result" label="处理结果" rules={[{ required: true }]}>
<Select placeholder="选择处理结果">
<Option value="resolved">问题已解决</Option>
<Option value="partially_resolved">部分解决</Option>
<Option value="unresolved">未解决</Option>
<Option value="escalated">需升级处理</Option>
</Select>
</Form.Item>
<Form.Item name="notes" label="备注">
<TextArea rows={2} placeholder="其他补充说明" />
</Form.Item>
<Form.Item name="usedParts" label="使用备件">
<Input placeholder="使用的备件信息(名称、数量)" />
</Form.Item>
<Form.Item>
<Space>
<Button type="primary" htmlType="submit" icon={<CheckCircleOutlined />}>
提交处理结果
</Button>
<Button onClick={() => setProcessingModalVisible(false)}>取消</Button>
</Space>
</Form.Item>
</Form>
</Modal>
<Modal
title={`工单详情 - ${selectedTicket?.ticketId}`}
open={detailModalVisible}
onCancel={() => setDetailModalVisible(false)}
footer={[
<Button key="close" onClick={() => setDetailModalVisible(false)}>
关闭
</Button>,
selectedTicket?.status !== 'closed' && selectedTicket?.status !== 'completed' && (
<Button key="process" type="primary" icon={<ToolOutlined />} onClick={() => {
setDetailModalVisible(false);
handleProcess(selectedTicket);
}}>
处理工单
</Button>
)
]}
width={900}
>
{selectedTicket && (
<Tabs defaultActiveKey="info">
<TabPane tab="基本信息" key="info">
<Descriptions bordered column={2}>
<Descriptions.Item label="工单编号">{selectedTicket.ticketId}</Descriptions.Item>
<Descriptions.Item label="标题">{selectedTicket.title}</Descriptions.Item>
<Descriptions.Item label="设备名称">{selectedTicket.deviceName}</Descriptions.Item>
<Descriptions.Item label="设备序列号">{selectedTicket.serialNumber}</Descriptions.Item>
<Descriptions.Item label="故障分类">{selectedTicket.faultCategory}</Descriptions.Item>
<Descriptions.Item label="优先级">
<Tag color={getPriorityColor(selectedTicket.priority)}>
{getPriorityText(selectedTicket.priority)}
</Tag>
</Descriptions.Item>
<Descriptions.Item label="状态">
<Tag color={getStatusColor(selectedTicket.status)}>
{getStatusText(selectedTicket.status)}
</Tag>
</Descriptions.Item>
<Descriptions.Item label="报告人">{selectedTicket.reporter?.username || '-'}</Descriptions.Item>
<Descriptions.Item label="创建时间">
{selectedTicket.createdAt ? dayjs(selectedTicket.createdAt).format('YYYY-MM-DD HH:mm:ss') : '-'}
</Descriptions.Item>
<Descriptions.Item label="期望完成时间">
{selectedTicket.expectedCompletionDate ? dayjs(selectedTicket.expectedCompletionDate).format('YYYY-MM-DD HH:mm:ss') : '-'}
</Descriptions.Item>
<Descriptions.Item label="完成时间" span={2}>
{selectedTicket.completionDate ? dayjs(selectedTicket.completionDate).format('YYYY-MM-DD HH:mm:ss') : '-'}
</Descriptions.Item>
<Descriptions.Item label="故障描述" span={2}>{selectedTicket.description || '-'}</Descriptions.Item>
<Descriptions.Item label="解决方案" span={2}>{selectedTicket.resolution || '-'}</Descriptions.Item>
<Descriptions.Item label="备注" span={2}>{selectedTicket.notes || '-'}</Descriptions.Item>
</Descriptions>
</TabPane>
<TabPane tab={`操作记录 (${operationRecords.length})`} key="operations">
<Timeline mode="left">
{operationRecords.map((record, index) => (
<Timeline.Item
key={index}
label={dayjs(record.createdAt).format('YYYY-MM-DD HH:mm:ss')}
color={record.operationType === 'create' ? 'green' :
record.operationType === 'complete' ? 'blue' :
record.operationType === 'close' ? 'gray' : 'orange'}
>
<div><strong>{record.operationType}</strong></div>
<div>操作人: {record.operatorName || '-'}</div>
<div>内容: {record.operationDescription || '-'}</div>
</Timeline.Item>
))}
{operationRecords.length === 0 && (
<p style={{ color: '#888' }}>暂无操作记录</p>
)}
</Timeline>
</TabPane>
</Tabs>
)}
</Modal>
</div>
);
}
export default TicketManagement;
+457
View File
@@ -0,0 +1,457 @@
import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, Table, DatePicker, Select, Space, Tag, message } from 'antd';
import { BarChartOutlined, PieChartOutlined, RiseOutlined, FallOutlined, ClockCircleOutlined, CheckCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import axios from 'axios';
import dayjs from 'dayjs';
const { RangePicker } = DatePicker;
const { Option } = Select;
function TicketStatistics() {
const [loading, setLoading] = useState(true);
const [dateRange, setDateRange] = useState([
dayjs().subtract(30, 'days'),
dayjs()
]);
const [statistics, setStatistics] = useState({
total: 0,
pending: 0,
inProgress: 0,
completed: 0,
closed: 0,
avgProcessingTime: 0,
byCategory: [],
byPriority: [],
byStatus: [],
byDevice: [],
trend: []
});
const fetchStatistics = async () => {
try {
setLoading(true);
const params = {
startDate: dateRange[0].format('YYYY-MM-DD'),
endDate: dateRange[1].format('YYYY-MM-DD')
};
const response = await axios.get('/api/tickets/statistics', { params });
setStatistics(response.data);
} catch (error) {
message.error('获取统计数据失败');
console.error('获取统计数据失败:', error);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchStatistics();
}, [dateRange]);
const handleDateChange = (dates) => {
if (dates) {
setDateRange(dates);
}
};
const getStatusColor = (status) => {
const colors = {
pending: 'orange',
assigned: 'blue',
in_progress: 'processing',
completed: 'green',
closed: 'default'
};
return colors[status] || 'default';
};
const getStatusText = (status) => {
const texts = {
pending: '待处理',
assigned: '已分配',
in_progress: '处理中',
completed: '已完成',
closed: '已关闭'
};
return texts[status] || status;
};
const getPriorityColor = (priority) => {
const colors = {
low: 'green',
medium: 'orange',
high: 'red',
urgent: 'magenta'
};
return colors[priority] || 'default';
};
const getPriorityText = (priority) => {
const texts = {
low: '低',
medium: '中',
high: '高',
urgent: '紧急'
};
return texts[priority] || priority;
};
const statusColumns = [
{
title: '状态',
dataIndex: 'status',
key: 'status',
width: 120,
render: (status) => (
<Tag color={getStatusColor(status)}>
{getStatusText(status)}
</Tag>
)
},
{
title: '工单数量',
dataIndex: 'count',
key: 'count',
width: 120,
render: (count) => <Statistic value={count} valueStyle={{ fontSize: 16 }} />
},
{
title: '占比',
dataIndex: 'percentage',
key: 'percentage',
width: 120,
render: (pct) => (
<span style={{ color: pct > 30 ? '#ff4d4f' : '#52c41a' }}>
{pct.toFixed(1)}%
</span>
)
}
];
const categoryColumns = [
{
title: '故障分类',
dataIndex: 'category',
key: 'category',
width: 150
},
{
title: '工单数量',
dataIndex: 'count',
key: 'count',
width: 120,
render: (count) => <Statistic value={count} valueStyle={{ fontSize: 16 }} />
},
{
title: '占比',
dataIndex: 'percentage',
key: 'percentage',
width: 100,
render: (pct) => `${pct.toFixed(1)}%`
},
{
title: '已完成',
dataIndex: 'completed',
key: 'completed',
width: 100,
render: (count) => <Tag color="green">{count}</Tag>
},
{
title: '平均处理时间(小时)',
dataIndex: 'avgTime',
key: 'avgTime',
width: 150,
render: (time) => time !== undefined && time !== null ? time.toFixed(1) : '-'
}
];
const deviceColumns = [
{
title: '设备名称',
dataIndex: 'deviceName',
key: 'deviceName',
width: 180
},
{
title: '故障次数',
dataIndex: 'count',
key: 'count',
width: 100,
render: (count) => <Tag color="red">{count}</Tag>
},
{
title: '最后故障时间',
dataIndex: 'lastFaultTime',
key: 'lastFaultTime',
width: 160,
render: (text) => text ? dayjs(text).format('YYYY-MM-DD HH:mm') : '-'
},
{
title: '设备类型',
dataIndex: 'deviceType',
key: 'deviceType',
width: 100
}
];
const priorityColumns = [
{
title: '优先级',
dataIndex: 'priority',
key: 'priority',
width: 100,
render: (priority) => (
<Tag color={getPriorityColor(priority)}>
{getPriorityText(priority)}
</Tag>
)
},
{
title: '工单数量',
dataIndex: 'count',
key: 'count',
width: 120,
render: (count) => <Statistic value={count} valueStyle={{ fontSize: 16 }} />
},
{
title: '已完成',
dataIndex: 'completed',
key: 'completed',
width: 100,
render: (count) => <Tag color="green">{count}</Tag>
},
{
title: '平均处理时间(小时)',
dataIndex: 'avgTime',
key: 'avgTime',
width: 150,
render: (time) => time !== undefined && time !== null ? time.toFixed(1) : '-'
}
];
const simpleBarData = [
{ name: '待处理', value: statistics.pending },
{ name: '处理中', value: statistics.inProgress },
{ name: '已完成', value: statistics.completed },
{ name: '已关闭', value: statistics.closed }
];
return (
<div style={{ padding: 24 }}>
<Card
title="工单统计报表"
extra={
<Space>
<RangePicker
value={dateRange}
onChange={handleDateChange}
allowClear={false}
/>
</Space>
}
>
<Row gutter={[16, 16]}>
<Col xs={24} sm={12} md={6}>
<Card bordered={false} style={{ background: '#f0f5ff' }}>
<Statistic
title="工单总数"
value={statistics.total}
prefix={<BarChartOutlined style={{ color: '#1890ff' }} />}
valueStyle={{ color: '#1890ff' }}
/>
</Card>
</Col>
<Col xs={24} sm={12} md={6}>
<Card bordered={false} style={{ background: '#fff7e6' }}>
<Statistic
title="待处理工单"
value={statistics.pending}
prefix={<ExclamationCircleOutlined style={{ color: '#fa8c16' }} />}
valueStyle={{ color: '#fa8c16' }}
/>
</Card>
</Col>
<Col xs={24} sm={12} md={6}>
<Card bordered={false} style={{ background: '#e6f7ff' }}>
<Statistic
title="已完成工单"
value={statistics.completed}
prefix={<CheckCircleOutlined style={{ color: '#52c41a' }} />}
valueStyle={{ color: '#52c41a' }}
/>
</Card>
</Col>
<Col xs={24} sm={12} md={6}>
<Card bordered={false} style={{ background: '#f9f0ff' }}>
<Statistic
title="平均处理时长(小时)"
value={statistics.avgProcessingTime || 0}
prefix={<ClockCircleOutlined style={{ color: '#722ed1' }} />}
valueStyle={{ color: '#722ed1' }}
precision={1}
/>
</Card>
</Col>
</Row>
<Row gutter={[16, 16]} style={{ marginTop: 16 }}>
<Col xs={24} sm={12} md={6}>
<Card bordered={false} style={{ background: '#fff0f6' }}>
<Statistic
title="处理中工单"
value={statistics.inProgress}
prefix={<RiseOutlined style={{ color: '#eb2f96' }} />}
valueStyle={{ color: '#eb2f96' }}
/>
</Card>
</Col>
<Col xs={24} sm={12} md={6}>
<Card bordered={false} style={{ background: '#f5f5f5' }}>
<Statistic
title="已关闭工单"
value={statistics.closed}
prefix={<FallOutlined style={{ color: '#8c8c8c' }} />}
valueStyle={{ color: '#8c8c8c' }}
/>
</Card>
</Col>
<Col xs={24} sm={12} md={6}>
<Card bordered={false} style={{ background: '#fff1f0' }}>
<Statistic
title="完成率"
value={statistics.total > 0 ? ((statistics.completed / statistics.total) * 100).toFixed(1) : 0}
suffix="%"
prefix={<PieChartOutlined style={{ color: '#ff4d4f' }} />}
valueStyle={{ color: '#ff4d4f' }}
/>
</Card>
</Col>
<Col xs={24} sm={12} md={6}>
<Card bordered={false} style={{ background: '#f6ffed' }}>
<Statistic
title="处理中占比"
value={statistics.total > 0 ? ((statistics.inProgress / statistics.total) * 100).toFixed(1) : 0}
suffix="%"
prefix={<RiseOutlined style={{ color: '#52c41a' }} />}
valueStyle={{ color: '#52c41a' }}
/>
</Card>
</Col>
</Row>
</Card>
<Row gutter={[16, 16]} style={{ marginTop: 16 }}>
<Col xs={24} lg={12}>
<Card title="按状态分布" loading={loading}>
<Table
columns={statusColumns}
dataSource={statistics.byStatus}
rowKey="status"
pagination={false}
size="small"
/>
</Card>
</Col>
<Col xs={24} lg={12}>
<Card title="按优先级分布" loading={loading}>
<Table
columns={priorityColumns}
dataSource={statistics.byPriority}
rowKey="priority"
pagination={false}
size="small"
/>
</Card>
</Col>
</Row>
<Row gutter={[16, 16]} style={{ marginTop: 16 }}>
<Col xs={24}>
<Card title="按故障分类统计" loading={loading}>
<Table
columns={categoryColumns}
dataSource={statistics.byCategory}
rowKey="category"
pagination={{ pageSize: 10 }}
size="small"
/>
</Card>
</Col>
</Row>
<Row gutter={[16, 16]} style={{ marginTop: 16 }}>
<Col xs={24}>
<Card title="故障频发设备排行" loading={loading}>
<Table
columns={deviceColumns}
dataSource={statistics.byDevice}
rowKey="deviceId"
pagination={{ pageSize: 10 }}
size="small"
/>
</Card>
</Col>
</Row>
<Row gutter={[16, 16]} style={{ marginTop: 16 }}>
<Col xs={24}>
<Card title="工单趋势统计" loading={loading}>
<Table
columns={[
{
title: '日期',
dataIndex: 'date',
key: 'date',
width: 120,
render: (text) => dayjs(text).format('YYYY-MM-DD')
},
{
title: '新建工单',
dataIndex: 'created',
key: 'created',
width: 100,
render: (count) => <Tag color="blue">{count}</Tag>
},
{
title: '已完成',
dataIndex: 'completed',
key: 'completed',
width: 100,
render: (count) => <Tag color="green">{count}</Tag>
},
{
title: '关闭工单',
dataIndex: 'closed',
key: 'closed',
width: 100,
render: (count) => <Tag color="default">{count}</Tag>
},
{
title: '当日处理中',
dataIndex: 'inProgress',
key: 'inProgress',
width: 120,
render: (count) => <Tag color="processing">{count}</Tag>
},
{
title: '新增待处理',
dataIndex: 'pending',
key: 'pending',
width: 120,
render: (count) => <Tag color="orange">{count}</Tag>
}
]}
dataSource={statistics.trend}
rowKey="date"
pagination={{ pageSize: 10 }}
size="small"
/>
</Card>
</Col>
</Row>
</div>
);
}
export default TicketStatistics;