feat(线缆管理): 新增向导式接线创建功能

- 新增四步向导流程,简化接线创建过程
- 添加线缆标签、颜色、安装信息等新字段
- 实现端口可视化面板和冲突检测功能
- 新增耗材日志设备关联字段
- 添加耗材导入后台任务管理
- 更新线缆管理文档和使用指南
This commit is contained in:
zhang1106
2026-03-31 14:34:34 +08:00
parent 5d972799f2
commit 06e3b56469
16 changed files with 3914 additions and 105 deletions
+26
View File
@@ -53,6 +53,31 @@ const Cable = sequelize.define(
type: DataTypes.TEXT,
allowNull: true,
},
cableLabel: {
type: DataTypes.STRING,
allowNull: true,
comment: '线缆标签/编号',
},
cableColor: {
type: DataTypes.STRING,
allowNull: true,
comment: '线缆颜色(便于识别)',
},
installedBy: {
type: DataTypes.STRING,
allowNull: true,
comment: '安装人',
},
installedAt: {
type: DataTypes.DATE,
allowNull: true,
comment: '安装时间',
},
lastTestedAt: {
type: DataTypes.DATE,
allowNull: true,
comment: '上次测试时间',
},
},
{
tableName: 'cables',
@@ -63,6 +88,7 @@ const Cable = sequelize.define(
{ fields: ['status'] },
{ fields: ['cableType'] },
{ fields: ['sourceDeviceId', 'targetDeviceId'] },
{ fields: ['cableLabel'] },
],
}
);
+31
View File
@@ -96,6 +96,36 @@ const ConsumableLog = sequelize.define(
defaultValue: [],
comment: '本次操作的SN序列号列表',
},
deviceId: {
type: DataTypes.STRING,
allowNull: true,
comment: '目标设备ID(出库时关联)',
},
deviceName: {
type: DataTypes.STRING,
allowNull: true,
comment: '目标设备名称',
},
rackId: {
type: DataTypes.STRING,
allowNull: true,
comment: '机柜ID',
},
rackName: {
type: DataTypes.STRING,
allowNull: true,
comment: '机柜名称',
},
roomId: {
type: DataTypes.STRING,
allowNull: true,
comment: '机房ID',
},
roomName: {
type: DataTypes.STRING,
allowNull: true,
comment: '机房名称',
},
},
{
tableName: 'consumable_logs',
@@ -109,6 +139,7 @@ const ConsumableLog = sequelize.define(
{ fields: ['originalLogId'] },
{ fields: ['isEditable'] },
{ fields: ['isConsumableDeleted'] },
{ fields: ['deviceId'] },
],
}
);
+10
View File
@@ -257,6 +257,11 @@ router.post('/', async (req, res) => {
cableLength,
status,
description,
cableLabel,
cableColor,
installedBy,
installedAt,
lastTestedAt,
force,
} = req.body;
@@ -321,6 +326,11 @@ router.post('/', async (req, res) => {
cableLength,
status: status || 'normal',
description,
cableLabel: cableLabel || null,
cableColor: cableColor || null,
installedBy: installedBy || null,
installedAt: installedAt || null,
lastTestedAt: lastTestedAt || null,
});
const createdCable = await Cable.findByPk(cable.cableId, {
+328
View File
@@ -0,0 +1,328 @@
const express = require('express');
const router = express.Router();
const { Op } = require('sequelize');
const { sequelize } = require('../db');
const Consumable = require('../models/Consumable');
const ConsumableLog = require('../models/ConsumableLog');
const { importJobManager } = require('../utils/importJobManager');
const SUPPORTED_FIELDS = [
'consumableId',
'name',
'category',
'unit',
'currentStock',
'minStock',
'maxStock',
'unitPrice',
'supplier',
'location',
'description',
'snList',
'status',
];
const FIELD_ALIASES = {
耗材ID: 'consumableId',
名称: 'name',
分类: 'category',
单位: 'unit',
当前库存: 'currentStock',
最小库存: 'minStock',
最大库存: 'maxStock',
单价: 'unitPrice',
供应商: 'supplier',
存放位置: 'location',
描述: 'description',
SN序列号: 'snList',
状态: 'status',
};
const normalizeFieldName = fieldName => {
if (!fieldName) return null;
const trimmed = String(fieldName).trim();
if (FIELD_ALIASES[trimmed]) {
return FIELD_ALIASES[trimmed];
}
if (SUPPORTED_FIELDS.includes(trimmed)) {
return trimmed;
}
return null;
};
const parseSnList = snStr => {
if (!snStr) return [];
if (Array.isArray(snStr)) return snStr;
if (typeof snStr === 'string') {
return snStr.split(/[,;\n]/).map(s => s.trim()).filter(Boolean);
}
return [];
};
router.post('/consumables/background', async (req, res) => {
const { items, operator = '系统', mode = 'create', fieldMapping = {} } = req.body;
if (!items || !Array.isArray(items) || items.length === 0) {
return res.status(400).json({ error: '没有导入数据' });
}
const jobId = `IMP_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
const job = importJobManager.createJob(jobId, 'consumable_import', items.length);
importJobManager.startJob(jobId);
setImmediate(async () => {
const transaction = await sequelize.transaction();
try {
const results = {
success: 0,
failed: 0,
updated: 0,
skipped: 0,
errors: [],
details: [],
};
for (let i = 0; i < items.length; i++) {
const currentJob = importJobManager.getJob(jobId);
if (currentJob && currentJob.status === 'cancelled') {
await transaction.rollback();
return;
}
const item = items[i];
const rowNumber = i + 1;
try {
const mappedItem = {};
for (const [sourceField, targetField] of Object.entries(fieldMapping)) {
if (sourceField && targetField && item[sourceField] !== undefined) {
mappedItem[targetField] = item[sourceField];
}
}
for (const [key, value] of Object.entries(item)) {
const normalizedField = normalizeFieldName(key);
if (normalizedField && mappedItem[normalizedField] === undefined) {
mappedItem[normalizedField] = value;
}
}
const consumableId =
mappedItem.consumableId || mappedItem.name + `_${Date.now()}`;
const name = mappedItem.name;
const category = mappedItem.category;
if (!name || !category) {
throw new Error('名称和分类为必填项');
}
let snList = [];
if (mappedItem.snList) {
snList = parseSnList(mappedItem.snList);
}
const consumableData = {
consumableId: consumableId || `CON${Date.now()}${i}`,
name,
category,
unit: mappedItem.unit || '个',
currentStock:
snList.length > 0
? snList.length
: parseInt(mappedItem.currentStock) || 0,
minStock: parseInt(mappedItem.minStock) || 10,
maxStock: parseInt(mappedItem.maxStock) || 0,
unitPrice: parseFloat(mappedItem.unitPrice) || 0,
supplier: mappedItem.supplier || '',
location: mappedItem.location || '',
description: mappedItem.description || '',
status: mappedItem.status || 'active',
snList,
};
let existingConsumable = null;
if (consumableData.consumableId) {
existingConsumable = await Consumable.findByPk(consumableData.consumableId, {
transaction,
});
}
let operationType;
let previousStock = 0;
if (existingConsumable) {
if (mode === 'update') {
previousStock = existingConsumable.currentStock;
await existingConsumable.update(consumableData, { transaction });
operationType = 'import_update';
results.updated++;
results.details.push({
row: rowNumber,
status: 'updated',
consumableId: existingConsumable.consumableId,
name: existingConsumable.name,
});
} else {
results.skipped++;
results.details.push({
row: rowNumber,
status: 'skipped',
reason: '耗材已存在',
consumableId: consumableData.consumableId,
});
importJobManager.incrementProgress(jobId, 0, 0, 1, 0);
continue;
}
} else {
await Consumable.create(consumableData, { transaction });
operationType = 'import';
results.success++;
results.details.push({
row: rowNumber,
status: 'created',
consumableId: consumableData.consumableId,
name: consumableData.name,
});
}
await ConsumableLog.create(
{
consumableId: consumableData.consumableId,
consumableName: consumableData.name,
operationType,
quantity: consumableData.currentStock,
previousStock,
currentStock: consumableData.currentStock,
operator,
reason: '后台批量导入',
notes: existingConsumable ? '更新现有耗材' : '',
consumableSnapshot: {
category: consumableData.category,
unit: consumableData.unit,
unitPrice: consumableData.unitPrice,
supplier: consumableData.supplier,
location: consumableData.location,
minStock: consumableData.minStock,
maxStock: consumableData.maxStock,
},
},
{ transaction }
);
importJobManager.incrementProgress(jobId, existingConsumable && mode === 'update' ? 0 : 1, 0, 0, existingConsumable ? 1 : 0);
} catch (error) {
results.failed++;
results.errors.push(`${rowNumber} 行: ${error.message}`);
results.details.push({
row: rowNumber,
status: 'failed',
error: error.message,
});
importJobManager.incrementProgress(jobId, 0, 1, 0, 0);
}
}
await transaction.commit();
importJobManager.completeJob(jobId, results);
} catch (error) {
await transaction.rollback();
importJobManager.failJob(jobId, error.message);
}
});
res.json({
jobId,
message: '导入任务已创建,正在后台执行',
totalItems: items.length,
});
});
router.get('/consumables/progress/:jobId', async (req, res) => {
const { jobId } = req.params;
const progress = importJobManager.getJobProgress(jobId);
if (!progress) {
return res.status(404).json({ error: '任务不存在' });
}
res.json(progress);
});
router.post('/consumables/cancel/:jobId', async (req, res) => {
const { jobId } = req.params;
const job = importJobManager.getJob(jobId);
if (!job) {
return res.status(404).json({ error: '任务不存在' });
}
if (!job.canCancel) {
return res.status(400).json({ error: '该任务无法取消' });
}
importJobManager.cancelJob(jobId);
res.json({ message: '任务已取消' });
});
router.get('/consumables/result/:jobId', async (req, res) => {
const { jobId } = req.params;
const job = importJobManager.getJob(jobId);
if (!job) {
return res.status(404).json({ error: '任务不存在' });
}
if (job.status !== 'completed' && job.status !== 'failed') {
return res.status(400).json({ error: '任务尚未完成' });
}
res.json({
jobId: job.jobId,
status: job.status,
result: job.result,
error: job.error,
completedAt: job.endTime,
});
});
router.get('/consumables/field-mappings', async (req, res) => {
const mappings = [
{ source: '耗材ID', target: 'consumableId', required: false, description: '耗材唯一标识符' },
{ source: '名称', target: 'name', required: true, description: '耗材名称' },
{ source: '分类', target: 'category', required: true, description: '耗材分类' },
{ source: '单位', target: 'unit', required: false, description: '计量单位,默认"个"' },
{ source: '当前库存', target: 'currentStock', required: false, description: '当前库存数量' },
{ source: '最小库存', target: 'minStock', required: false, description: '安全库存预警值' },
{ source: '最大库存', target: 'maxStock', required: false, description: '最大库存限制,0表示无限制' },
{ source: '单价', target: 'unitPrice', required: false, description: '耗材单价' },
{ source: '供应商', target: 'supplier', required: false, description: '供应商名称' },
{ source: '存放位置', target: 'location', required: false, description: '仓库内存放位置' },
{ source: '描述', target: 'description', required: false, description: '耗材详细描述' },
{ source: 'SN序列号', target: 'snList', required: false, description: '序列号列表,用逗号分隔' },
{ source: '状态', target: 'status', required: false, description: '状态:active启用,inactive停用' },
];
const systemFields = [
{ name: 'consumableId', type: 'string', description: '耗材唯一标识符' },
{ name: 'name', type: 'string', description: '耗材名称' },
{ name: 'category', type: 'string', description: '耗材分类' },
{ name: 'unit', type: 'string', description: '计量单位' },
{ name: 'currentStock', type: 'number', description: '当前库存数量' },
{ name: 'minStock', type: 'number', description: '最小库存(预警线)' },
{ name: 'maxStock', type: 'number', description: '最大库存限制' },
{ name: 'unitPrice', type: 'number', description: '单价' },
{ name: 'supplier', type: 'string', description: '供应商' },
{ name: 'location', type: 'string', description: '存放位置' },
{ name: 'description', type: 'text', description: '描述' },
{ name: 'snList', type: 'array', description: 'SN序列号数组' },
{ name: 'status', type: 'string', description: '状态' },
];
res.json({
aliases: mappings,
systemFields,
});
});
module.exports = router;
+195 -2
View File
@@ -459,7 +459,16 @@ router.post('/quick-inout', async (req, res) => {
while (attempt < RETRY.MAX_RETRIES) {
const transaction = await sequelize.transaction();
try {
const { consumableId, type, quantity, operator, reason, notes, snList } = req.body;
const {
consumableId,
type,
quantity,
operator,
reason,
notes,
snList,
deviceId,
} = req.body;
const consumable = await Consumable.findByPk(consumableId, { transaction });
if (!consumable) {
@@ -467,6 +476,39 @@ router.post('/quick-inout', async (req, res) => {
return res.status(404).json({ error: '耗材不存在' });
}
let deviceInfo = {};
if (deviceId && type === 'out') {
const Device = require('../models/Device');
const Rack = require('../models/Rack');
const Room = require('../models/Room');
const device = await Device.findByPk(deviceId, { transaction });
if (device) {
deviceInfo = {
deviceId: device.deviceId,
deviceName: device.name,
rackId: device.rackId,
rackName: null,
roomId: null,
roomName: null,
};
if (device.rackId) {
const rack = await Rack.findByPk(device.rackId, { transaction });
if (rack) {
deviceInfo.rackName = rack.name;
if (rack.roomId) {
const room = await Room.findByPk(rack.roomId, { transaction });
if (room) {
deviceInfo.roomId = room.roomId;
deviceInfo.roomName = room.name;
}
}
}
}
}
}
const previousStock = parseFloat(consumable.currentStock);
let newStock;
const currentSnList = consumable.snList || [];
@@ -554,6 +596,12 @@ router.post('/quick-inout', async (req, res) => {
notes,
isEditable: false,
snList: operationSnList,
deviceId: deviceInfo.deviceId || null,
deviceName: deviceInfo.deviceName || null,
rackId: deviceInfo.rackId || null,
rackName: deviceInfo.rackName || null,
roomId: deviceInfo.roomId || null,
roomName: deviceInfo.roomName || null,
consumableSnapshot: {
category: consumable.category,
unit: consumable.unit,
@@ -571,6 +619,7 @@ router.post('/quick-inout', async (req, res) => {
message: '操作成功',
record,
consumable: await Consumable.findByPk(consumableId),
deviceInfo: Object.keys(deviceInfo).length > 0 ? deviceInfo : null,
});
return;
} catch (error) {
@@ -589,7 +638,18 @@ router.post('/inout', async (req, res) => {
while (attempt < RETRY.MAX_RETRIES) {
const transaction = await sequelize.transaction();
try {
const { consumableId, type, quantity, operator, reason, recipient, notes, snList } = req.body;
const {
consumableId,
type,
quantity,
operator,
reason,
recipient,
notes,
snList,
deviceId,
deviceName,
} = req.body;
const consumable = await Consumable.findByPk(consumableId, { transaction });
if (!consumable) {
@@ -597,6 +657,39 @@ router.post('/inout', async (req, res) => {
return res.status(404).json({ error: '耗材不存在' });
}
let deviceInfo = {};
if (deviceId && type === 'out') {
const Device = require('../models/Device');
const Rack = require('../models/Rack');
const Room = require('../models/Room');
const device = await Device.findByPk(deviceId, { transaction });
if (device) {
deviceInfo = {
deviceId: device.deviceId,
deviceName: device.name,
rackId: device.rackId,
rackName: null,
roomId: null,
roomName: null,
};
if (device.rackId) {
const rack = await Rack.findByPk(device.rackId, { transaction });
if (rack) {
deviceInfo.rackName = rack.name;
if (rack.roomId) {
const room = await Room.findByPk(rack.roomId, { transaction });
if (room) {
deviceInfo.roomId = room.roomId;
deviceInfo.roomName = room.name;
}
}
}
}
}
}
const previousStock = parseFloat(consumable.currentStock);
let newStock;
const currentSnList = consumable.snList || [];
@@ -682,6 +775,12 @@ router.post('/inout', async (req, res) => {
notes,
isEditable: false,
snList: operationSnList,
deviceId: deviceInfo.deviceId || null,
deviceName: deviceInfo.deviceName || null,
rackId: deviceInfo.rackId || null,
rackName: deviceInfo.rackName || null,
roomId: deviceInfo.roomId || null,
roomName: deviceInfo.roomName || null,
consumableSnapshot: {
category: consumable.category,
unit: consumable.unit,
@@ -699,6 +798,7 @@ router.post('/inout', async (req, res) => {
message: '操作成功',
record,
consumable: await Consumable.findByPk(consumableId),
deviceInfo: Object.keys(deviceInfo).length > 0 ? deviceInfo : null,
});
return;
} catch (error) {
@@ -1314,4 +1414,97 @@ router.get('/logs/:id/history', async (req, res) => {
}
});
router.get('/devices/search', async (req, res) => {
try {
const { keyword, limit = 20 } = req.query;
if (!keyword) {
return res.json({ devices: [] });
}
const Device = require('../models/Device');
const Rack = require('../models/Rack');
const Room = require('../models/Room');
const escapedKeyword = keyword.replace(/'/g, "''");
const devices = await Device.findAll({
where: {
[Op.or]: [
{ deviceId: { [Op.like]: `%${escapedKeyword}%` } },
{ name: { [Op.like]: `%${escapedKeyword}%` } },
{ serialNumber: { [Op.like]: `%${escapedKeyword}%` } },
],
},
include: [
{
model: Rack,
as: 'rack',
include: [{ model: Room, as: 'room' }],
},
],
limit: parseInt(limit),
order: [['name', 'ASC']],
});
const result = devices.map(device => ({
deviceId: device.deviceId,
name: device.name,
type: device.type,
model: device.model,
serialNumber: device.serialNumber,
status: device.status,
location: device.rack
? {
rackId: device.rack.rackId,
rackName: device.rack.name,
roomId: device.rack.room ? device.rack.room.roomId : null,
roomName: device.rack.room ? device.rack.room.name : null,
}
: null,
}));
res.json({ devices: result });
} catch (error) {
console.error('搜索设备失败:', error);
res.status(500).json({ error: error.message });
}
});
router.get('/devices/by-sn/:sn', async (req, res) => {
try {
const { sn } = req.params;
const Device = require('../models/Device');
const device = await Device.findOne({
where: {
[Op.or]: [
{ deviceId: { [Op.like]: `%${sn}%` } },
{ serialNumber: { [Op.like]: `%${sn}%` } },
{ name: { [Op.like]: `%${sn}%` } },
],
},
});
if (!device) {
return res.json({ found: false, device: null });
}
res.json({
found: true,
device: {
deviceId: device.deviceId,
name: device.name,
type: device.type,
model: device.model,
serialNumber: device.serialNumber,
status: device.status,
},
});
} catch (error) {
console.error('查询设备失败:', error);
res.status(500).json({ error: error.message });
}
});
module.exports = router;
+63 -27
View File
@@ -100,6 +100,11 @@ const migrations = [
description: '为 devices 表添加复合索引,优化位置冲突检测和悲观锁性能',
migrate: migrateDevicePositionIndexes,
},
{
name: '耗材日志设备关联',
description: '为 consumable_logs 表添加 deviceId、deviceName、rackId、rackName、roomId、roomName 字段',
migrate: migrateConsumableLogDeviceAssociation,
},
];
async function runMigrations() {
@@ -738,37 +743,68 @@ async function migrateDevicePositionIndexes() {
return;
}
console.log(` → 为 ${tableName} 表添加复合索引 rackId_position...`);
try {
if (dialect === 'sqlite') {
await sequelize.query(`CREATE INDEX IF NOT EXISTS devices_rackId_position ON ${tableName}(rackId, position)`);
} else {
await sequelize.query(`CREATE INDEX IF NOT EXISTS \`devices_rackId_position\` ON \`${tableName}\`(\`rackId\`, \`position\`)`);
}
console.log(' ✓ 索引创建成功');
} catch (error) {
if (error.message.includes('already exists') || error.message.includes('Duplicate key name')) {
console.log(' → 索引已存在,跳过');
} else {
throw error;
const indexesToCreate = [
{ name: 'devices_rackId_position', fields: ['rackId', 'position'] },
{ name: 'devices_rackId_position_isIdle', fields: ['rackId', 'position', 'isIdle'] },
];
for (const idx of indexesToCreate) {
console.log(` → 为 ${tableName} 表添加复合索引 ${idx.name}...`);
try {
const existingIndexes = await sequelize.query(`SHOW INDEX FROM ${tableName}`, {
type: sequelize.QueryTypes.SELECT,
});
const indexExists = existingIndexes.some(
existing => existing.Key_name === idx.name
);
if (indexExists) {
console.log(' → 索引已存在,跳过');
} else {
if (dialect === 'sqlite') {
await sequelize.query(
`CREATE INDEX IF NOT EXISTS ${idx.name} ON ${tableName}(${idx.fields.join(', ')})`
);
} else {
await sequelize.query(
`CREATE INDEX \`${idx.name}\` ON \`${tableName}\`(\`${idx.fields.join('`, `')}\`)`
);
}
console.log(' ✓ 索引创建成功');
}
} catch (error) {
if (error.message.includes('already exists') || error.message.includes('Duplicate key name')) {
console.log(' → 索引已存在,跳过');
} else {
throw error;
}
}
}
}
async function migrateConsumableLogDeviceAssociation() {
const tableName = 'consumable_logs';
if (!(await tableExists(tableName))) {
console.log(` ${tableName} 表不存在,跳过`);
return;
}
console.log(` → 为 ${tableName} 表添加复合索引 rackId_position_isIdle...`);
try {
if (dialect === 'sqlite') {
await sequelize.query(`CREATE INDEX IF NOT EXISTS devices_rackId_position_isIdle ON ${tableName}(rackId, position, isIdle)`);
} else {
await sequelize.query(`CREATE INDEX IF NOT EXISTS \`devices_rackId_position_isIdle\` ON \`${tableName}\`(\`rackId\`, \`position\`, \`isIdle\`)`);
}
console.log(' ✓ 索引创建成功');
} catch (error) {
if (error.message.includes('already exists') || error.message.includes('Duplicate key name')) {
console.log(' → 索引已存在,跳过');
} else {
throw error;
}
const columns = await getTableColumns(tableName);
const newColumns = [
{ name: 'deviceId', def: 'VARCHAR(255)' },
{ name: 'deviceName', def: 'VARCHAR(255)' },
{ name: 'rackId', def: 'VARCHAR(255)' },
{ name: 'rackName', def: 'VARCHAR(255)' },
{ name: 'roomId', def: 'VARCHAR(255)' },
{ name: 'roomName', def: 'VARCHAR(255)' },
];
for (const col of newColumns) {
await addColumnIfNotExists(tableName, col.name, col.def);
}
console.log(' 耗材日志设备关联迁移完成');
}
// 执行迁移
+42
View File
@@ -0,0 +1,42 @@
const { sequelize } = require('../db');
const Cable = require('../models/Cable');
async function migrateCableFields() {
try {
console.log('开始迁移 Cable 模型字段...');
// 检查字段是否已存在
const [results] = await sequelize.query('PRAGMA table_info(cables)');
const existingColumns = results.map(row => row.name);
const newColumns = [
{ name: 'cableLabel', type: 'VARCHAR(255)' },
{ name: 'cableColor', type: 'VARCHAR(50)' },
{ name: 'installedBy', type: 'VARCHAR(100)' },
{ name: 'installedAt', type: 'DATETIME' },
{ name: 'lastTestedAt', type: 'DATETIME' },
];
for (const column of newColumns) {
if (!existingColumns.includes(column.name)) {
console.log(`添加字段: ${column.name}`);
await sequelize.query(`ALTER TABLE cables ADD COLUMN ${column.name} ${column.type}`);
} else {
console.log(`字段已存在: ${column.name}`);
}
}
console.log('迁移完成!');
console.log('\n新增字段:');
console.log(' - cableLabel: 线缆标签/编号');
console.log(' - cableColor: 线缆颜色(便于识别)');
console.log(' - installedBy: 安装人');
console.log(' - installedAt: 安装时间');
console.log(' - lastTestedAt: 上次测试时间');
} catch (error) {
console.error('迁移失败:', error);
process.exit(1);
}
}
migrateCableFields();
+3
View File
@@ -251,6 +251,9 @@ const operationLogsRoutes = require('./routes/operationLogs');
const idleDeviceRoutes = require('./routes/idleDevices');
const warehouseRoutes = require('./routes/warehouses');
const dangerousOperationsRoutes = require('./routes/dangerousOperations');
const consumableImportRoutes = require('./routes/consumableImport');
app.use('/api', consumableImportRoutes);
app.use('/api/devices', deviceRoutes);
app.use('/api/racks', rackRoutes);
+174
View File
@@ -0,0 +1,174 @@
const { EventEmitter } = require('events');
const path = require('path');
const fs = require('fs');
class ImportJobManager extends EventEmitter {
constructor() {
super();
this.jobs = new Map();
this.JOB_STATUS = {
PENDING: 'pending',
PROCESSING: 'processing',
COMPLETED: 'completed',
FAILED: 'failed',
CANCELLED: 'cancelled',
};
}
createJob(jobId, type, totalItems) {
const job = {
jobId,
type,
status: this.JOB_STATUS.PENDING,
totalItems,
processedItems: 0,
successCount: 0,
failedCount: 0,
skippedCount: 0,
updatedCount: 0,
startTime: null,
endTime: null,
error: null,
canCancel: true,
result: null,
createdAt: new Date(),
};
this.jobs.set(jobId, job);
return job;
}
getJob(jobId) {
return this.jobs.get(jobId);
}
updateJob(jobId, updates) {
const job = this.jobs.get(jobId);
if (!job) return null;
Object.assign(job, updates);
this.emit('jobUpdate', job);
return job;
}
startJob(jobId) {
const job = this.jobs.get(jobId);
if (!job) return null;
job.status = this.JOB_STATUS.PROCESSING;
job.startTime = new Date();
this.emit('jobStart', job);
return job;
}
incrementProgress(jobId, success = 0, failed = 0, skipped = 0, updated = 0) {
const job = this.jobs.get(jobId);
if (!job) return null;
job.processedItems += success + failed + skipped + updated;
job.successCount += success;
job.failedCount += failed;
job.skippedCount += skipped;
job.updatedCount += updated;
this.emit('jobProgress', job);
return job;
}
completeJob(jobId, result = null) {
const job = this.jobs.get(jobId);
if (!job) return null;
job.status = this.JOB_STATUS.COMPLETED;
job.endTime = new Date();
job.canCancel = false;
job.result = result;
this.emit('jobComplete', job);
return job;
}
failJob(jobId, error) {
const job = this.jobs.get(jobId);
if (!job) return null;
job.status = this.JOB_STATUS.FAILED;
job.endTime = new Date();
job.canCancel = false;
job.error = error;
this.emit('jobFailed', job);
return job;
}
cancelJob(jobId) {
const job = this.jobs.get(jobId);
if (!job || !job.canCancel) return null;
job.status = this.JOB_STATUS.CANCELLED;
job.endTime = new Date();
job.canCancel = false;
this.emit('jobCancelled', job);
return job;
}
getJobProgress(jobId) {
const job = this.jobs.get(jobId);
if (!job) return null;
const progress = {
jobId: job.jobId,
status: job.status,
totalItems: job.totalItems,
processedItems: job.processedItems,
progressPercent:
job.totalItems > 0 ? Math.round((job.processedItems / job.totalItems) * 100) : 0,
successCount: job.successCount,
failedCount: job.failedCount,
skippedCount: job.skippedCount,
updatedCount: job.updatedCount,
canCancel: job.canCancel,
error: job.error,
startTime: job.startTime,
endTime: job.endTime,
elapsedTime: job.startTime
? Date.now() - new Date(job.startTime).getTime()
: null,
};
return progress;
}
listJobs() {
return Array.from(this.jobs.values()).map(job => ({
jobId: job.jobId,
type: job.type,
status: job.status,
totalItems: job.totalItems,
processedItems: job.processedItems,
progressPercent:
job.totalItems > 0 ? Math.round((job.processedItems / job.totalItems) * 100) : 0,
canCancel: job.canCancel,
startTime: job.startTime,
endTime: job.endTime,
createdAt: job.createdAt,
}));
}
cleanupOldJobs(maxAgeMs = 24 * 60 * 60 * 1000) {
const now = Date.now();
for (const [jobId, job] of this.jobs.entries()) {
const jobEndTime = job.endTime || job.createdAt;
if (now - new Date(jobEndTime).getTime() > maxAgeMs) {
this.jobs.delete(jobId);
}
}
}
}
const importJobManager = new ImportJobManager();
setInterval(() => {
importJobManager.cleanupOldJobs();
}, 60 * 60 * 1000);
module.exports = {
importJobManager,
ImportJobManager,
};