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
+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;