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
+65
View File
@@ -0,0 +1,65 @@
const { DataTypes } = require('sequelize');
const { sequelize } = require('../db');
const FaultCategory = sequelize.define('FaultCategory', {
categoryId: {
type: DataTypes.STRING,
primaryKey: true,
allowNull: false,
unique: true
},
name: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
comment: '分类名称'
},
description: {
type: DataTypes.TEXT,
comment: '分类说明 - 说明此类故障代表什么问题'
},
priority: {
type: DataTypes.INTEGER,
defaultValue: 0,
comment: '排序优先级'
},
defaultPriority: {
type: DataTypes.STRING,
defaultValue: 'medium',
comment: '默认优先级: critical/high/medium/low'
},
expectedDuration: {
type: DataTypes.INTEGER,
comment: '预计处理时长(小时)'
},
solutions: {
type: DataTypes.JSON,
defaultValue: [],
comment: '常见解决方案'
},
isSystem: {
type: DataTypes.BOOLEAN,
defaultValue: false,
comment: '是否系统内置分类'
},
isActive: {
type: DataTypes.BOOLEAN,
defaultValue: true,
comment: '是否启用'
},
metadata: {
type: DataTypes.JSON,
defaultValue: {},
comment: '扩展字段'
}
}, {
tableName: 'fault_categories',
timestamps: true,
indexes: [
{ fields: ['name'] },
{ fields: ['isActive'] },
{ fields: ['priority'] }
]
});
module.exports = FaultCategory;
+124
View File
@@ -0,0 +1,124 @@
const { DataTypes } = require('sequelize');
const { sequelize } = require('../db');
const User = require('./User');
const Device = require('./Device');
const Ticket = sequelize.define('Ticket', {
ticketId: {
type: DataTypes.STRING,
primaryKey: true,
allowNull: false,
unique: true
},
title: {
type: DataTypes.STRING,
allowNull: false,
comment: '工单标题'
},
deviceId: {
type: DataTypes.STRING,
allowNull: false,
comment: '关联设备ID'
},
deviceName: {
type: DataTypes.STRING,
allowNull: false,
comment: '设备名称'
},
deviceModel: {
type: DataTypes.STRING,
comment: '设备型号'
},
serialNumber: {
type: DataTypes.STRING,
comment: '设备序列号'
},
faultCategory: {
type: DataTypes.STRING,
allowNull: false,
comment: '故障分类'
},
faultSubCategory: {
type: DataTypes.STRING,
comment: '故障子分类'
},
priority: {
type: DataTypes.STRING,
defaultValue: 'medium',
comment: '优先级: critical/high/medium/low'
},
status: {
type: DataTypes.STRING,
defaultValue: 'pending',
comment: '工单状态: pending/in_progress/completed/closed/cancelled'
},
description: {
type: DataTypes.TEXT,
comment: '故障描述'
},
expectedCompletionDate: {
type: DataTypes.DATE,
comment: '期望完成时间'
},
reporterId: {
type: DataTypes.STRING,
allowNull: false,
comment: '报修人ID'
},
reporterName: {
type: DataTypes.STRING,
allowNull: false,
comment: '报修人姓名'
},
location: {
type: DataTypes.STRING,
comment: '设备位置'
},
resolution: {
type: DataTypes.TEXT,
comment: '解决方案'
},
completionDate: {
type: DataTypes.DATE,
comment: '实际完成时间'
},
evaluation: {
type: DataTypes.TEXT,
comment: '用户评价'
},
evaluationRating: {
type: DataTypes.INTEGER,
comment: '评价星级(1-5)'
},
attachments: {
type: DataTypes.JSON,
defaultValue: [],
comment: '附件列表'
},
tags: {
type: DataTypes.JSON,
defaultValue: [],
comment: '标签'
},
metadata: {
type: DataTypes.JSON,
defaultValue: {},
comment: '扩展字段'
}
}, {
tableName: 'tickets',
timestamps: true,
indexes: [
{ fields: ['deviceId'] },
{ fields: ['status'] },
{ fields: ['faultCategory'] },
{ fields: ['priority'] },
{ fields: ['reporterId'] },
{ fields: ['createdAt'] }
]
});
Ticket.belongsTo(User, { foreignKey: 'reporterId', as: 'reporter', constraints: false });
Ticket.belongsTo(Device, { foreignKey: 'deviceId', constraints: false });
module.exports = Ticket;
+90
View File
@@ -0,0 +1,90 @@
const { DataTypes } = require('sequelize');
const { sequelize } = require('../db');
const TicketOperationRecord = sequelize.define('TicketOperationRecord', {
recordId: {
type: DataTypes.STRING,
primaryKey: true,
allowNull: false,
unique: true
},
ticketId: {
type: DataTypes.STRING,
allowNull: false,
comment: '关联工单ID'
},
operationType: {
type: DataTypes.STRING,
allowNull: false,
comment: '操作类型: create/update/status_change/assignment/comment/attachment'
},
operationDescription: {
type: DataTypes.TEXT,
comment: '操作描述'
},
operatorId: {
type: DataTypes.STRING,
allowNull: false,
comment: '操作人ID'
},
operatorName: {
type: DataTypes.STRING,
allowNull: false,
comment: '操作人姓名'
},
operatorRole: {
type: DataTypes.STRING,
comment: '操作人角色'
},
operationSteps: {
type: DataTypes.JSON,
defaultValue: [],
comment: '操作步骤详情'
},
spareParts: {
type: DataTypes.JSON,
defaultValue: [],
comment: '使用的备件列表'
},
beforeState: {
type: DataTypes.JSON,
comment: '操作前状态'
},
afterState: {
type: DataTypes.JSON,
comment: '操作后状态'
},
duration: {
type: DataTypes.INTEGER,
comment: '操作耗时(分钟)'
},
result: {
type: DataTypes.STRING,
comment: '操作结果: success/failed/partial'
},
notes: {
type: DataTypes.TEXT,
comment: '备注信息'
},
attachments: {
type: DataTypes.JSON,
defaultValue: [],
comment: '附件'
},
metadata: {
type: DataTypes.JSON,
defaultValue: {},
comment: '扩展字段'
}
}, {
tableName: 'ticket_operation_records',
timestamps: true,
indexes: [
{ fields: ['ticketId'] },
{ fields: ['operatorId'] },
{ fields: ['operationType'] },
{ fields: ['createdAt'] }
]
});
module.exports = TicketOperationRecord;
+188
View File
@@ -0,0 +1,188 @@
const { sequelize } = require('../db');
const FaultCategory = require('./FaultCategory');
const Ticket = require('./Ticket');
const TicketOperationRecord = require('./TicketOperationRecord');
const User = require('./User');
const Device = require('./Device');
const initDefaultFaultCategories = async () => {
try {
const count = await FaultCategory.count();
if (count > 0) {
console.log('故障分类已存在,跳过初始化');
return;
}
const defaultCategories = [
{
categoryId: 'CAT001',
name: '系统故障',
code: 'system_fault',
description: '操作系统、软件系统相关的故障',
icon: 'DesktopOutlined',
color: '#ff4d4f',
priority: 1,
defaultPriority: 'high',
expectedDuration: 4,
solutions: ['重启服务', '回滚版本', '修复配置', '重装系统'],
isSystem: true
},
{
categoryId: 'CAT002',
name: '硬件故障',
code: 'hardware_fault',
description: '服务器、存储、网络设备等硬件故障',
icon: 'CpuOutlined',
color: '#fa8c16',
priority: 2,
defaultPriority: 'critical',
expectedDuration: 8,
solutions: ['更换部件', '联系厂商', '现场维修'],
isSystem: true
},
{
categoryId: 'CAT003',
name: '网络故障',
code: 'network_fault',
description: '网络连接、交换机、路由器等问题',
icon: 'WifiOutlined',
color: '#1890ff',
priority: 3,
defaultPriority: 'high',
expectedDuration: 2,
solutions: ['检查网线', '重启交换机', '修复配置', '联系运营商'],
isSystem: true
},
{
categoryId: 'CAT004',
name: '软件故障',
code: 'software_fault',
description: '应用程序、Bug、性能问题等',
icon: 'AppstoreOutlined',
color: '#722ed1',
priority: 4,
defaultPriority: 'medium',
expectedDuration: 6,
solutions: ['修复Bug', '优化性能', '更新版本', '配置调整'],
isSystem: true
},
{
categoryId: 'CAT005',
name: '安全事件',
code: 'security_incident',
description: '安全漏洞、入侵检测、权限问题等',
icon: 'SafetyOutlined',
color: '#eb2f96',
priority: 0,
defaultPriority: 'critical',
expectedDuration: 1,
solutions: ['隔离系统', '调查取证', '修复漏洞', '更新安全策略'],
isSystem: true
},
{
categoryId: 'CAT006',
name: '性能问题',
code: 'performance_issue',
description: '响应慢、卡顿、资源耗尽等性能问题',
icon: 'RocketOutlined',
color: '#52c41a',
priority: 5,
defaultPriority: 'medium',
expectedDuration: 4,
solutions: ['资源扩容', '优化SQL', '清理缓存', '负载均衡'],
isSystem: true
},
{
categoryId: 'CAT007',
name: '配置变更',
code: 'config_change',
description: '配置修改、系统调优等需求',
icon: 'SettingOutlined',
color: '#13c2c2',
priority: 6,
defaultPriority: 'low',
expectedDuration: 2,
solutions: ['调整配置', '参数优化', '功能启用'],
isSystem: true
},
{
categoryId: 'CAT008',
name: '例行维护',
code: 'routine_maintenance',
description: '定期维护、巡检、预防性保养',
icon: 'ToolOutlined',
color: '#faad14',
priority: 7,
defaultPriority: 'low',
expectedDuration: 4,
solutions: ['系统更新', '安全检查', '日志清理', '硬件检测'],
isSystem: true
},
{
categoryId: 'CAT009',
name: '数据问题',
code: 'data_issue',
description: '数据丢失、数据错误、数据同步问题',
icon: 'DatabaseOutlined',
color: '#f5222d',
priority: 1,
defaultPriority: 'high',
expectedDuration: 6,
solutions: ['数据恢复', '数据修复', '重新同步', '备份还原'],
isSystem: true
},
{
categoryId: 'CAT010',
name: '电源问题',
code: 'power_issue',
description: '电源故障、UPS、空调等电力系统问题',
icon: 'ThunderboltOutlined',
color: '#fa541c',
priority: 0,
defaultPriority: 'critical',
expectedDuration: 2,
solutions: ['切换电源', '更换UPS', '联系供电', '检查线路'],
isSystem: true
}
];
for (const category of defaultCategories) {
await FaultCategory.create(category);
}
console.log('默认故障分类初始化完成');
} catch (error) {
console.error('初始化故障分类失败:', error);
}
};
const initAssociations = () => {
Ticket.belongsTo(User, { foreignKey: 'assigneeId', as: 'assignee' });
Ticket.hasMany(TicketOperationRecord, { foreignKey: 'ticketId', as: 'operationRecords' });
TicketOperationRecord.belongsTo(Ticket, { foreignKey: 'ticketId' });
};
// 立即初始化关联(在模型导出前)
initAssociations();
const initializeModels = async () => {
try {
await sequelize.sync({ alter: true });
console.log('工单相关数据表同步完成');
initAssociations();
await initDefaultFaultCategories();
console.log('工单系统数据初始化完成');
} catch (error) {
console.error('初始化工单系统数据失败:', error);
}
};
module.exports = {
initializeModels,
Ticket,
TicketOperationRecord,
FaultCategory
};
+4357 -19
View File
File diff suppressed because it is too large Load Diff
+3 -1
View File
@@ -24,6 +24,8 @@
"xlsx": "^0.18.5"
},
"devDependencies": {
"nodemon": "^3.0.1"
"jest": "^30.2.0",
"nodemon": "^3.0.1",
"supertest": "^7.1.4"
}
}
+51
View File
@@ -0,0 +1,51 @@
const { sequelize } = require('./db');
const FaultCategory = require('./models/FaultCategory');
async function recreateFaultCategoryTable() {
try {
console.log('开始重建故障分类表...');
await sequelize.authenticate();
console.log('数据库连接成功');
// 删除旧表并创建新表
await sequelize.query('DROP TABLE IF EXISTS fault_categories');
console.log('旧表已删除');
await FaultCategory.sync();
console.log('新表已创建');
// 初始化默认分类
const defaultCategories = [
{ name: '系统故障', description: '操作系统、应用程序等系统软件的故障问题', priority: 1, defaultPriority: 'high', expectedDuration: 120, isSystem: true, isActive: true },
{ name: '硬件故障', description: '物理设备、服务器、存储等硬件设备的故障问题', priority: 2, defaultPriority: 'high', expectedDuration: 180, isSystem: true, isActive: true },
{ name: '网络故障', description: '网络连接、交换机、路由器等网络相关故障', priority: 3, defaultPriority: 'high', expectedDuration: 120, isSystem: true, isActive: true },
{ name: '软件故障', description: '应用程序错误、软件兼容性等问题', priority: 4, defaultPriority: 'medium', expectedDuration: 90, isSystem: true, isActive: true },
{ name: '安全事件', description: '安全漏洞、入侵检测、权限异常等安全问题', priority: 5, defaultPriority: 'urgent', expectedDuration: 60, isSystem: true, isActive: true },
{ name: '性能问题', description: '系统响应慢、资源利用率高等性能问题', priority: 6, defaultPriority: 'medium', expectedDuration: 120, isSystem: true, isActive: true },
{ name: '配置变更', description: '系统配置、软件配置等变更需求', priority: 7, defaultPriority: 'low', expectedDuration: 60, isSystem: true, isActive: true },
{ name: '例行维护', description: '定期维护、巡检、更新等计划性工作', priority: 8, defaultPriority: 'low', expectedDuration: 120, isSystem: true, isActive: true },
{ name: '数据问题', description: '数据错误、数据丢失、数据同步等数据相关问题', priority: 9, defaultPriority: 'high', expectedDuration: 150, isSystem: true, isActive: true },
{ name: '其他问题', description: '无法归类的其他问题', priority: 99, defaultPriority: 'medium', expectedDuration: 90, isSystem: true, isActive: true }
];
for (const cat of defaultCategories) {
const categoryId = `CAT${Date.now().toString(36).toUpperCase()}${Math.random().toString(36).substr(2, 4).toUpperCase()}`;
await FaultCategory.create({
categoryId,
...cat,
solutions: [],
metadata: {}
});
}
console.log('默认分类已初始化');
console.log('故障分类表重建完成!');
process.exit(0);
} catch (error) {
console.error('操作失败:', error);
process.exit(1);
}
}
recreateFaultCategoryTable();
+194
View File
@@ -0,0 +1,194 @@
const express = require('express');
const router = express.Router();
const { Op } = require('sequelize');
const FaultCategory = require('../models/FaultCategory');
router.get('/', async (req, res) => {
try {
const { isActive } = req.query;
const where = {};
if (isActive !== undefined) {
where.isActive = isActive === 'true';
}
const categories = await FaultCategory.findAll({
where,
order: [['priority', 'ASC'], ['name', 'ASC']]
});
res.json(categories);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
router.get('/stats', async (req, res) => {
try {
const Ticket = require('../models/Ticket');
const { startDate, endDate } = req.query;
const where = {};
if (startDate || endDate) {
where.createdAt = {};
if (startDate) where.createdAt[Op.gte] = new Date(startDate);
if (endDate) where.createdAt[Op.lte] = new Date(endDate + ' 23:59:59');
}
const stats = await Ticket.findAll({
where,
attributes: [
'faultCategory',
[require('sequelize').fn('COUNT', '*'), 'totalCount'],
[require('sequelize').sum(require('sequelize').case({
when: { status: 'completed' },
then: 1
}, 0)), 'completedCount'],
[require('sequelize').sum(require('sequelize').case({
when: { status: { [Op.ne]: 'completed' } },
then: 1
}, 0)), 'pendingCount']
],
group: ['faultCategory']
});
res.json(stats);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
router.get('/:categoryId', async (req, res) => {
try {
const category = await FaultCategory.findByPk(req.params.categoryId);
if (!category) {
return res.status(404).json({ error: '分类不存在' });
}
res.json(category);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
router.post('/', async (req, res) => {
try {
const {
name,
description,
priority,
defaultPriority,
expectedDuration,
solutions,
isActive
} = req.body;
const existing = await FaultCategory.findOne({ where: { name } });
if (existing) {
return res.status(400).json({ error: '分类名称已存在' });
}
const categoryId = `CAT${Date.now().toString(36).toUpperCase()}`;
const category = await FaultCategory.create({
categoryId,
name,
description,
priority: priority || 99,
defaultPriority: defaultPriority || 'medium',
expectedDuration: expectedDuration ? parseInt(expectedDuration) : null,
solutions: solutions || [],
isSystem: false,
isActive: isActive !== false
});
res.status(201).json(category);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
router.post('/init', async (req, res) => {
try {
const defaultCategories = [
{ name: '系统故障', description: '操作系统、应用程序等系统软件的故障问题', priority: 1, defaultPriority: 'high' },
{ name: '硬件故障', description: '物理设备、服务器、存储等硬件设备的故障问题', priority: 2, defaultPriority: 'high' },
{ name: '网络故障', description: '网络连接、交换机、路由器等网络相关故障', priority: 3, defaultPriority: 'high' },
{ name: '软件故障', description: '应用程序错误、软件兼容性等问题', priority: 4, defaultPriority: 'medium' },
{ name: '安全事件', description: '安全漏洞、入侵检测、权限异常等安全问题', priority: 5, defaultPriority: 'urgent' },
{ name: '性能问题', description: '系统响应慢、资源利用率高等性能问题', priority: 6, defaultPriority: 'medium' },
{ name: '配置变更', description: '系统配置、软件配置等变更需求', priority: 7, defaultPriority: 'low' },
{ name: '例行维护', description: '定期维护、巡检、更新等计划性工作', priority: 8, defaultPriority: 'low' },
{ name: '数据问题', description: '数据错误、数据丢失、数据同步等数据相关问题', priority: 9, defaultPriority: 'high' },
{ name: '其他问题', description: '无法归类的其他问题', priority: 99, defaultPriority: 'medium' }
];
for (const cat of defaultCategories) {
const existing = await FaultCategory.findOne({ where: { name: cat.name } });
if (!existing) {
const categoryId = `CAT${Date.now().toString(36).toUpperCase()}${Math.random().toString(36).substr(2, 4).toUpperCase()}`;
await FaultCategory.create({
categoryId,
...cat,
expectedDuration: 120,
solutions: [],
isSystem: true,
isActive: true
});
}
}
res.json({ message: '分类初始化成功' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
router.put('/:categoryId', async (req, res) => {
try {
const category = await FaultCategory.findByPk(req.params.categoryId);
if (!category) {
return res.status(404).json({ error: '分类不存在' });
}
await category.update(req.body);
res.json(category);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
router.delete('/:categoryId', async (req, res) => {
try {
const category = await FaultCategory.findByPk(req.params.categoryId);
if (!category) {
return res.status(404).json({ error: '分类不存在' });
}
const Ticket = require('../models/Ticket');
const ticketCount = await Ticket.count({ where: { faultCategory: category.name } });
if (ticketCount > 0) {
return res.status(400).json({ error: `该分类下有 ${ticketCount} 个工单,无法删除` });
}
await category.destroy();
res.json({ message: '分类已删除' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
router.patch('/:categoryId/toggle', async (req, res) => {
try {
const category = await FaultCategory.findByPk(req.params.categoryId);
if (!category) {
return res.status(404).json({ error: '分类不存在' });
}
await category.update({ isActive: !category.isActive });
res.json(category);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
module.exports = router;
+542
View File
@@ -0,0 +1,542 @@
const express = require('express');
const router = express.Router();
const { Op } = require('sequelize');
const { v4: uuidv4 } = require('uuid');
const { Ticket, TicketOperationRecord } = require('../models/ticketIndex');
const Device = require('../models/Device');
const User = require('../models/User');
// 获取工单统计 (必须定义在 /:ticketId 之前)
router.get('/stats', async (req, res) => {
try {
const { startDate, endDate } = req.query;
const where = {};
if (startDate || endDate) {
where.createdAt = {};
if (startDate) where.createdAt[Op.gte] = new Date(startDate);
if (endDate) where.createdAt[Op.lte] = new Date(endDate + ' 23:59:59');
}
const total = await Ticket.count({ where });
const statusStats = await Ticket.findAll({
where,
attributes: [
'status',
[require('sequelize').fn('COUNT', '*'), 'count']
],
group: ['status']
});
const priorityStats = await Ticket.findAll({
where,
attributes: [
'priority',
[require('sequelize').fn('COUNT', '*'), 'count']
],
group: ['priority']
});
const categoryStats = await Ticket.findAll({
where,
attributes: [
'faultCategory',
[require('sequelize').fn('COUNT', '*'), 'count']
],
group: ['faultCategory']
});
const monthlyStats = await Ticket.findAll({
where,
attributes: [
[require('sequelize').fn('strftime', '%Y-%m', require('sequelize').col('createdAt')), 'month'],
[require('sequelize').fn('COUNT', '*'), 'count']
],
group: ['month'],
order: [['month', 'DESC']],
limit: 12
});
const statusData = statusStats.map(s => s.dataValues);
const pending = statusData.find(s => s.status === 'pending')?.count || 0;
const inProgress = statusData.find(s => s.status === 'in_progress')?.count || 0;
const completed = statusData.find(s => s.status === 'completed')?.count || 0;
const closed = statusData.find(s => s.status === 'closed')?.count || 0;
const byStatus = statusData.map(item => ({
status: item.status,
count: item.count,
percentage: total > 0 ? (item.count / total * 100) : 0
}));
const byPriority = priorityStats.map(p => ({
priority: p.dataValues.priority,
count: p.dataValues.count,
completed: 0,
avgTime: 0
}));
const byCategory = categoryStats.map(c => ({
category: c.dataValues.faultCategory,
count: c.dataValues.count,
completed: 0,
avgTime: 0
}));
const deviceStats = await Ticket.findAll({
where,
attributes: [
'deviceId',
'deviceName',
[require('sequelize').fn('COUNT', '*'), 'count'],
[require('sequelize').fn('MAX', require('sequelize').col('createdAt')), 'lastFaultTime']
],
group: ['deviceId', 'deviceName'],
order: [[require('sequelize').fn('COUNT', '*'), 'DESC']],
limit: 10
});
const byDevice = deviceStats.map(d => ({
deviceId: d.deviceId,
deviceName: d.deviceName,
count: d.dataValues.count,
lastFaultTime: d.dataValues.lastFaultTime,
deviceType: ''
}));
const dailyStats = await Ticket.findAll({
where,
attributes: [
[require('sequelize').fn('DATE', require('sequelize').col('createdAt')), 'date'],
[require('sequelize').fn('COUNT', '*'), 'created']
],
group: ['date'],
order: [['date', 'ASC']]
});
const trend = dailyStats.map(d => ({
date: d.dataValues.date,
created: d.dataValues.created,
completed: 0,
closed: 0,
inProgress: 0,
pending: 0
}));
const avgProcessingTime = 0;
res.json({
total,
pending,
inProgress,
completed,
closed,
avgProcessingTime,
byStatus,
byPriority,
byCategory,
byDevice,
trend,
monthlyStats: monthlyStats.map(m => ({ month: m.dataValues.month, count: m.dataValues.count }))
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// 获取工单统计 (别名)
router.get('/statistics', async (req, res) => {
req.url = '/stats';
router.handle(req, res);
});
// 获取工单列表
router.get('/', async (req, res) => {
try {
const {
keyword,
status,
priority,
faultCategory,
deviceId,
reporterId,
startDate,
endDate,
page = 1,
pageSize = 10
} = req.query;
const offset = (page - 1) * pageSize;
const where = {};
// 关键词搜索
if (keyword) {
where[Op.or] = [
{ ticketId: { [Op.like]: `%${keyword}%` } },
{ title: { [Op.like]: `%${keyword}%` } },
{ deviceName: { [Op.like]: `%${keyword}%` } },
{ serialNumber: { [Op.like]: `%${keyword}%` } },
{ description: { [Op.like]: `%${keyword}%` } }
];
}
// 状态筛选
if (status && status !== 'all') {
where.status = status;
}
// 优先级筛选
if (priority && priority !== 'all') {
where.priority = priority;
}
// 故障分类筛选
if (faultCategory && faultCategory !== 'all') {
where.faultCategory = faultCategory;
}
// 设备筛选
if (deviceId && deviceId !== 'all') {
where.deviceId = deviceId;
}
// 报修人筛选
if (reporterId && reporterId !== 'all') {
where.reporterId = reporterId;
}
// 日期范围筛选
if (startDate || endDate) {
where.createdAt = {};
if (startDate) {
where.createdAt[Op.gte] = new Date(startDate);
}
if (endDate) {
where.createdAt[Op.lte] = new Date(endDate + ' 23:59:59');
}
}
const { count, rows } = await Ticket.findAndCountAll({
where,
include: [
{ model: User, as: 'reporter', attributes: ['userId', 'username'] },
{ model: Device, attributes: ['deviceId', 'name', 'type', 'model'] }
],
order: [['createdAt', 'DESC']],
offset,
limit: parseInt(pageSize)
});
res.json({
total: count,
tickets: rows,
page: parseInt(page),
pageSize: parseInt(pageSize)
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// 获取单个工单详情
router.get('/:ticketId', async (req, res) => {
try {
const ticket = await Ticket.findByPk(req.params.ticketId, {
include: [
{ model: User, as: 'reporter', attributes: ['userId', 'username', 'email'] },
{ model: Device },
{ model: TicketOperationRecord, as: 'operationRecords', order: [['createdAt', 'DESC']] }
]
});
if (!ticket) {
return res.status(404).json({ error: '工单不存在' });
}
res.json(ticket);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// 创建工单
router.post('/', async (req, res) => {
try {
const {
deviceId,
faultCategory,
faultSubCategory,
priority,
description,
expectedCompletionDate,
title,
attachments,
tags
} = req.body;
// 获取设备信息
const device = await Device.findByPk(deviceId, {
include: [{ model: require('../models/Rack') }]
});
if (!device) {
return res.status(404).json({ error: '设备不存在' });
}
const ticketId = `TKT${Date.now().toString(36).toUpperCase()}${Math.random().toString(36).substr(2, 4).toUpperCase()}`;
const ticket = await Ticket.create({
ticketId,
title: title || `${faultCategory} - ${device.name}`,
deviceId,
deviceName: device.name,
deviceModel: device.model,
serialNumber: device.serialNumber,
faultCategory,
faultSubCategory,
priority: priority || 'medium',
description,
expectedCompletionDate: expectedCompletionDate ? new Date(expectedCompletionDate) : null,
reporterId: req.body.reporterId || 'USER001',
reporterName: req.body.reporterName || '系统用户',
location: device.Rack ? `${device.Rack.name}` : '未知位置',
attachments: attachments || [],
tags: tags || [],
status: 'pending'
});
// 创建操作记录
await TicketOperationRecord.create({
recordId: uuidv4(),
ticketId,
operationType: 'create',
operationDescription: '创建工单',
operatorId: ticket.reporterId,
operatorName: ticket.reporterName,
operatorRole: 'user',
afterState: ticket.toJSON()
});
res.status(201).json(ticket);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// 更新工单
router.put('/:ticketId', async (req, res) => {
try {
const ticket = await Ticket.findByPk(req.params.ticketId);
if (!ticket) {
return res.status(404).json({ error: '工单不存在' });
}
const beforeState = ticket.toJSON();
const { operatorId, operatorName, operatorRole } = req.body;
await ticket.update(req.body);
await TicketOperationRecord.create({
recordId: uuidv4(),
ticketId: ticket.ticketId,
operationType: 'update',
operationDescription: '更新工单信息',
operatorId: operatorId || ticket.reporterId,
operatorName: operatorName || ticket.reporterName,
operatorRole: operatorRole || 'user',
beforeState,
afterState: ticket.toJSON()
});
res.json(ticket);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// 更新工单状态
router.put('/:ticketId/status', async (req, res) => {
try {
const { status, operatorId, operatorName, operatorRole, resolution } = req.body;
const ticket = await Ticket.findByPk(req.params.ticketId);
if (!ticket) {
return res.status(404).json({ error: '工单不存在' });
}
const beforeState = ticket.toJSON();
const updateData = { status };
if (status === 'completed') {
updateData.completionDate = new Date();
if (resolution) {
updateData.resolution = resolution;
}
}
await ticket.update(updateData);
await TicketOperationRecord.create({
recordId: uuidv4(),
ticketId: ticket.ticketId,
operationType: 'status_change',
operationDescription: `状态变更为: ${status}`,
operatorId: operatorId || ticket.reporterId,
operatorName: operatorName || ticket.reporterName,
operatorRole: operatorRole || 'user',
beforeState,
afterState: ticket.toJSON()
});
res.json(ticket);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// 处理工单
router.put('/:ticketId/process', async (req, res) => {
try {
const { solution, result, notes, usedParts, operatorId, operatorName, operatorRole } = req.body;
const ticket = await Ticket.findByPk(req.params.ticketId);
if (!ticket) {
return res.status(404).json({ error: '工单不存在' });
}
const beforeState = ticket.toJSON();
const updateData = {
status: 'in_progress',
resolution: solution
};
if (result === 'resolved') {
updateData.status = 'completed';
updateData.completionDate = new Date();
}
await ticket.update(updateData);
await TicketOperationRecord.create({
recordId: uuidv4(),
ticketId: ticket.ticketId,
operationType: 'process',
operationDescription: `处理工单 - 结果: ${result}`,
operationSteps: solution ? [solution] : [],
spareParts: usedParts ? [{ name: usedParts }] : [],
result,
notes,
operatorId: operatorId || ticket.reporterId,
operatorName: operatorName || ticket.reporterName,
operatorRole: operatorRole || 'user',
beforeState,
afterState: ticket.toJSON()
});
res.json(ticket);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// 添加操作记录
router.post('/:ticketId/operations', async (req, res) => {
try {
const {
operationType,
operationDescription,
operationSteps,
spareParts,
duration,
result,
notes,
operatorId,
operatorName,
operatorRole
} = req.body;
const ticket = await Ticket.findByPk(req.params.ticketId);
if (!ticket) {
return res.status(404).json({ error: '工单不存在' });
}
const record = await TicketOperationRecord.create({
recordId: uuidv4(),
ticketId: ticket.ticketId,
operationType,
operationDescription,
operationSteps: operationSteps || [],
spareParts: spareParts || [],
duration,
result,
notes,
operatorId,
operatorName,
operatorRole
});
res.status(201).json(record);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// 获取工单操作记录
router.get('/:ticketId/operations', async (req, res) => {
try {
const records = await TicketOperationRecord.findAll({
where: { ticketId: req.params.ticketId },
order: [['createdAt', 'DESC']]
});
res.json(records);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// 删除工单
router.delete('/:ticketId', async (req, res) => {
try {
const ticket = await Ticket.findByPk(req.params.ticketId);
if (!ticket) {
return res.status(404).json({ error: '工单不存在' });
}
await ticket.destroy();
res.json({ message: '工单已删除' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// 评价工单
router.post('/:ticketId/evaluate', async (req, res) => {
try {
const { evaluation, evaluationRating, operatorId, operatorName } = req.body;
const ticket = await Ticket.findByPk(req.params.ticketId);
if (!ticket) {
return res.status(404).json({ error: '工单不存在' });
}
await ticket.update({ evaluation, evaluationRating });
await TicketOperationRecord.create({
recordId: uuidv4(),
ticketId: ticket.ticketId,
operationType: 'comment',
operationDescription: '用户评价',
operatorId,
operatorName,
operatorRole: 'user',
notes: `评价: ${evaluation}, 星级: ${evaluationRating}`
});
res.json(ticket);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
module.exports = router;
+8
View File
@@ -31,6 +31,10 @@ sequelize.authenticate()
// 同步完成后初始化设备字段
return require('./initDeviceFields')();
})
.then(() => {
// 初始化工单模型关联
return require('./models/ticketIndex').initializeModels();
})
.catch(err => console.error('数据库操作失败:', err));
// 导入路由
@@ -47,6 +51,8 @@ const usersRoutes = require('./routes/users');
const rolesRoutes = require('./routes/roles');
const loginHistoryRoutes = require('./routes/loginHistory');
const operationLogsRoutes = require('./routes/operationLogs');
const ticketRoutes = require('./routes/tickets');
const ticketCategoryRoutes = require('./routes/ticketCategories');
// 使用路由
app.use('/api/devices', deviceRoutes);
@@ -62,6 +68,8 @@ app.use('/api/users', usersRoutes);
app.use('/api/roles', rolesRoutes);
app.use('/api/login-history', loginHistoryRoutes);
app.use('/api/operation-logs', operationLogsRoutes);
app.use('/api/tickets', ticketRoutes);
app.use('/api/ticket-categories', ticketCategoryRoutes);
// 静态文件服务
app.use('/uploads', express.static('uploads'));
+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;