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'));