const express = require('express'); const multer = require('multer'); const fs = require('node:fs'); const path = require('node:path'); const { getDocumentFormat, validateDocumentFile, normalizeUploadedFileName } = require('./document-files'); const AVATAR_MAX_BYTES = 5 * 1024 * 1024; const MAX_DOCUMENT_UPLOADS = 10; const MAX_LINKED_DOCUMENTS = 100; async function ensureRobotSchema(pool) { await pool.request().batch(fs.readFileSync(path.join(__dirname, 'robot-schema.sql'), 'utf8')); } function invalid(message) { return Object.assign(new Error(message), { status: 400 }); } function positiveId(value) { const id = Number(value); if (!/^\d+$/.test(String(value)) || !Number.isSafeInteger(id) || id < 1 || id > 2147483647) { throw invalid('Mã dữ liệu không hợp lệ'); } return id; } function parseDocumentIds(value) { if (value === undefined) return undefined; let ids = value; if (typeof value === 'string') { try { ids = JSON.parse(value); } catch { throw invalid('Danh sách tài liệu không hợp lệ'); } } if (!Array.isArray(ids) || ids.length > MAX_LINKED_DOCUMENTS) { throw invalid(`Chỉ được liên kết tối đa ${MAX_LINKED_DOCUMENTS} tài liệu`); } return [...new Set(ids.map(positiveId))].sort((a, b) => a - b); } function isAvatarBuffer(buffer, mimeType) { if (!Buffer.isBuffer(buffer) || buffer.length < 12) return false; if (mimeType === 'image/png') return buffer.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex')); if (mimeType === 'image/jpeg') return buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff; if (mimeType === 'image/webp') return buffer.toString('ascii', 0, 4) === 'RIFF' && buffer.toString('ascii', 8, 12) === 'WEBP'; return false; } function createRobotRouter({ getPool, sql, requireManage, documentMaxBytes, documentMaxMb, sanitizeDocumentFileName, sendInternalError }) { const router = express.Router(); const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: Math.max(documentMaxBytes, AVATAR_MAX_BYTES), files: MAX_DOCUMENT_UPLOADS + 1, fields: 6, parts: MAX_DOCUMENT_UPLOADS + 8, fieldSize: 64 * 1024 }, fileFilter(_req, file, callback) { const extension = path.extname(file.originalname).toLowerCase(); const avatarTypes = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp' }; const valid = file.fieldname === 'avatar' ? avatarTypes[extension] === file.mimetype : file.fieldname === 'documents' && Boolean(getDocumentFormat(file.originalname)); callback(valid ? null : invalid('Ảnh đại diện chỉ nhận JPG, PNG, WebP; định dạng tài liệu chưa được hỗ trợ'), valid); } }).fields([{ name: 'avatar', maxCount: 1 }, { name: 'documents', maxCount: MAX_DOCUMENT_UPLOADS }]); const robotColumns = `r.RobotId, r.Name, r.Model, r.TypeId, t.Name AS Type, r.CreatedBy, r.CreatedDate, r.UpdatedDate, CAST(CASE WHEN r.AvatarData IS NULL THEN 0 ELSE 1 END AS BIT) AS HasAvatar, (SELECT COUNT(*) FROM dbo.RobotDocuments rd WHERE rd.RobotId = r.RobotId) AS DocumentCount`; function fail(res, error) { if (error.status === 400) return res.status(400).json({ success: false, message: error.message }); return sendInternalError(res, error, 'Không thể xử lý thông tin robot'); } function failType(res, error) { if ([2601, 2627].includes(error.number)) { return res.status(409).json({ success: false, message: 'Tên thể loại robot đã tồn tại' }); } if (error.number === 547) { return res.status(409).json({ success: false, message: 'Thể loại đang được robot hoặc BOM sử dụng. Không thể xóa để bảo toàn dữ liệu liên quan.' }); } return fail(res, error); } function typeFields(body = {}) { if (typeof body.name !== 'string' || !body.name.trim() || body.name.trim().length > 100) { throw invalid('Vui lòng nhập tên thể loại, tối đa 100 ký tự'); } if (body.description != null && (typeof body.description !== 'string' || body.description.trim().length > 500)) { throw invalid('Mô tả thể loại tối đa 500 ký tự'); } return { name: body.name.trim(), description: body.description?.trim() || null }; } // Declare catalog routes before /:id so "types" cannot be parsed as a robot ID. router.get('/types', async (_req, res) => { try { const result = await getPool().request().query(`SELECT t.TypeId, t.Name, t.Description, t.CreatedDate, t.UpdatedDate, (SELECT COUNT(*) FROM dbo.Robots r WHERE r.TypeId = t.TypeId) AS RobotCount FROM dbo.RobotTypes t ORDER BY t.Name, t.TypeId`); res.json({ success: true, data: result.recordset }); } catch (error) { failType(res, error); } }); router.post('/types', requireManage, async (req, res) => { try { const fields = typeFields(req.body); const result = await getPool().request().input('name', sql.NVarChar(100), fields.name) .input('description', sql.NVarChar(500), fields.description).query(` INSERT INTO dbo.RobotTypes (Name, Description) OUTPUT INSERTED.TypeId, INSERTED.Name, INSERTED.Description VALUES (@name, @description)`); res.status(201).json({ success: true, data: result.recordset[0], message: 'Đã thêm thể loại robot' }); } catch (error) { failType(res, error); } }); router.put('/types/:id', requireManage, async (req, res) => { let transaction, begun = false; try { const typeId = positiveId(req.params.id); const fields = typeFields(req.body); transaction = new sql.Transaction(getPool()); await transaction.begin(); begun = true; const result = await new sql.Request(transaction).input('typeId', sql.Int, typeId) .input('name', sql.NVarChar(100), fields.name).input('description', sql.NVarChar(500), fields.description) .query(`UPDATE dbo.RobotTypes SET Name = @name, Description = @description, UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME()) OUTPUT INSERTED.TypeId, INSERTED.Name, INSERTED.Description WHERE TypeId = @typeId`); if (!result.recordset.length) { await transaction.rollback(); begun = false; return res.status(404).json({ success: false, message: 'Không tìm thấy thể loại robot' }); } await new sql.Request(transaction).input('typeId', sql.Int, typeId).input('name', sql.NVarChar(100), fields.name) .query(`UPDATE dbo.Robots SET Type = @name, UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME()) WHERE TypeId = @typeId`); await transaction.commit(); begun = false; res.json({ success: true, data: result.recordset[0], message: 'Đã cập nhật thể loại robot' }); } catch (error) { if (begun) { try { await transaction.rollback(); } catch { /* The driver may have rolled back. */ } } failType(res, error); } }); router.delete('/types/:id', requireManage, async (req, res) => { try { const result = await getPool().request().input('typeId', sql.Int, positiveId(req.params.id)) .query('DELETE FROM dbo.RobotTypes OUTPUT DELETED.TypeId WHERE TypeId = @typeId'); if (!result.recordset.length) return res.status(404).json({ success: false, message: 'Không tìm thấy thể loại robot' }); res.json({ success: true, message: 'Đã xóa thể loại robot' }); } catch (error) { failType(res, error); } }); router.get('/', async (_req, res) => { try { const result = await getPool().request().query(`SELECT ${robotColumns} FROM dbo.Robots r JOIN dbo.RobotTypes t ON t.TypeId = r.TypeId ORDER BY r.CreatedDate DESC, r.RobotId DESC`); res.json({ success: true, data: result.recordset, maxFileSizeMb: documentMaxMb, avatarMaxFileSizeMb: 5 }); } catch (error) { fail(res, error); } }); router.get('/:id/avatar', async (req, res) => { try { const result = await getPool().request().input('robotId', sql.Int, positiveId(req.params.id)) .query('SELECT AvatarData, AvatarMimeType FROM dbo.Robots WHERE RobotId = @robotId'); const robot = result.recordset[0]; if (!robot?.AvatarData) return res.status(404).json({ success: false, message: 'Robot chưa có ảnh đại diện' }); res.setHeader('Content-Type', robot.AvatarMimeType); res.setHeader('X-Content-Type-Options', 'nosniff'); res.send(robot.AvatarData); } catch (error) { fail(res, error); } }); router.get('/:id', async (req, res) => { try { const robotId = positiveId(req.params.id); const result = await getPool().request().input('robotId', sql.Int, robotId) .query(`SELECT ${robotColumns} FROM dbo.Robots r JOIN dbo.RobotTypes t ON t.TypeId = r.TypeId WHERE r.RobotId = @robotId`); if (!result.recordset[0]) return res.status(404).json({ success: false, message: 'Không tìm thấy robot' }); const documents = await getPool().request().input('robotId', sql.Int, robotId).query(` SELECT d.DocumentId, d.Title, d.OriginalFileName, d.MimeType, d.FileSize, d.UploadedDate FROM dbo.RobotDocuments rd JOIN dbo.Documents d ON d.DocumentId = rd.DocumentId WHERE rd.RobotId = @robotId ORDER BY d.Title, d.DocumentId`); res.json({ success: true, data: { ...result.recordset[0], Documents: documents.recordset } }); } catch (error) { fail(res, error); } }); async function saveRobot(req, res) { let transaction; let begun = false; try { req.body ||= {}; const robotId = req.params.id === undefined ? null : positiveId(req.params.id); const fields = {}; for (const [key, limit] of [['name', 255], ['model', 255]]) { if (typeof req.body[key] !== 'string' || !req.body[key].trim() || req.body[key].trim().length > limit) { throw invalid('Vui lòng nhập tên và model robot, tối đa 255 ký tự'); } fields[key] = req.body[key].trim(); } const typeId = positiveId(req.body.typeId); const documentIds = parseDocumentIds(req.body.documentIds); const avatar = req.files?.avatar?.[0]; const documents = req.files?.documents || []; if (avatar && (avatar.size > AVATAR_MAX_BYTES || !isAvatarBuffer(avatar.buffer, avatar.mimetype))) { throw invalid('Ảnh đại diện phải là JPG, PNG hoặc WebP hợp lệ, tối đa 5 MB'); } for (const file of documents) { if (file.size > documentMaxBytes) throw invalid(`Tài liệu tối đa ${documentMaxMb} MB mỗi file`); file.documentFormat = validateDocumentFile(file); } if ((documentIds?.length || 0) + documents.length > MAX_LINKED_DOCUMENTS) { throw invalid(`Chỉ được liên kết tối đa ${MAX_LINKED_DOCUMENTS} tài liệu`); } if (req.body.removeAvatar !== undefined && !['true', 'false'].includes(String(req.body.removeAvatar))) { throw invalid('Yêu cầu xóa ảnh không hợp lệ'); } transaction = new sql.Transaction(getPool()); await transaction.begin(); begun = true; const request = () => new sql.Request(transaction); // Lock the type before the robot, matching the catalog rename lock order. const selectedType = await request().input('typeId', sql.Int, typeId) .query('SELECT TypeId, Name FROM dbo.RobotTypes WITH (UPDLOCK, HOLDLOCK) WHERE TypeId = @typeId'); if (!selectedType.recordset.length) throw invalid('Thể loại đã bị xóa hoặc không tồn tại. Vui lòng chọn lại.'); fields.type = selectedType.recordset[0].Name; if (robotId !== null) { const existing = await request().input('robotId', sql.Int, robotId) .query('SELECT RobotId FROM dbo.Robots WITH (UPDLOCK, HOLDLOCK) WHERE RobotId = @robotId'); if (!existing.recordset.length) { await transaction.rollback(); begun = false; return res.status(404).json({ success: false, message: 'Không tìm thấy robot' }); } } for (const documentId of documentIds || []) { const existing = await request().input('documentId', sql.Int, documentId).query(` SELECT DocumentId FROM dbo.Documents WITH (UPDLOCK, HOLDLOCK) WHERE DocumentId = @documentId`); if (!existing.recordset.length) throw invalid('Một tài liệu đã bị xóa. Vui lòng chọn lại.'); } // A partial API update preserves existing links; the form always supplies the full selection. if (documentIds === undefined && robotId !== null) { const count = await request().input('robotId', sql.Int, robotId) .query('SELECT COUNT(*) AS DocumentCount FROM dbo.RobotDocuments WHERE RobotId = @robotId'); if (Number(count.recordset[0].DocumentCount) + documents.length > MAX_LINKED_DOCUMENTS) { throw invalid(`Chỉ được liên kết tối đa ${MAX_LINKED_DOCUMENTS} tài liệu`); } } const replaceAvatar = Boolean(avatar) || String(req.body.removeAvatar) === 'true'; const write = request().input('name', sql.NVarChar(255), fields.name) .input('model', sql.NVarChar(255), fields.model).input('type', sql.NVarChar(100), fields.type) .input('typeId', sql.Int, typeId) .input('avatarData', sql.VarBinary(sql.MAX), avatar?.buffer || null) .input('avatarMimeType', sql.NVarChar(100), avatar?.mimetype || null); let savedId; if (robotId === null) { const saved = await write.input('createdBy', sql.Int, req.user.UserId).query(` INSERT INTO dbo.Robots (Name, Model, Type, TypeId, AvatarData, AvatarMimeType, CreatedBy) OUTPUT INSERTED.RobotId VALUES (@name, @model, @type, @typeId, @avatarData, @avatarMimeType, @createdBy)`); savedId = saved.recordset[0].RobotId; } else { await write.input('robotId', sql.Int, robotId).input('replaceAvatar', sql.Bit, replaceAvatar).query(` UPDATE dbo.Robots SET Name = @name, Model = @model, Type = @type, TypeId = @typeId, AvatarData = CASE WHEN @replaceAvatar = 1 THEN @avatarData ELSE AvatarData END, AvatarMimeType = CASE WHEN @replaceAvatar = 1 THEN @avatarMimeType ELSE AvatarMimeType END, UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME()) WHERE RobotId = @robotId`); savedId = robotId; } if (documentIds !== undefined) { await request().input('robotId', sql.Int, savedId) .query('DELETE FROM dbo.RobotDocuments WHERE RobotId = @robotId'); } const allIds = [...(documentIds || [])]; for (const file of documents) { const filename = sanitizeDocumentFileName(normalizeUploadedFileName(file.originalname)); const saved = await request().input('title', sql.NVarChar(255), filename.replace(/\.[^.]+$/, '') || 'Tài liệu') .input('originalFileName', sql.NVarChar(255), filename).input('fileSize', sql.BigInt, file.size) .input('mimeType', sql.NVarChar(100), file.documentFormat.mimeType) .input('fileData', sql.VarBinary(sql.MAX), file.buffer).input('uploadedBy', sql.Int, req.user.UserId) .query(`INSERT INTO dbo.Documents (Title, OriginalFileName, MimeType, FileSize, FileData, UploadedBy) OUTPUT INSERTED.DocumentId VALUES (@title, @originalFileName, @mimeType, @fileSize, @fileData, @uploadedBy)`); allIds.push(saved.recordset[0].DocumentId); } for (const documentId of allIds) { await request().input('robotId', sql.Int, savedId).input('documentId', sql.Int, documentId) .query('INSERT INTO dbo.RobotDocuments (RobotId, DocumentId) VALUES (@robotId, @documentId)'); } await transaction.commit(); begun = false; res.status(robotId === null ? 201 : 200).json({ success: true, data: { RobotId: savedId }, message: 'Đã lưu thông tin robot' }); } catch (error) { if (begun) { try { await transaction.rollback(); } catch { /* Driver may already have rolled back. */ } } fail(res, error); } } router.post('/', requireManage, upload, saveRobot); router.put('/:id', requireManage, upload, saveRobot); router.delete('/:id', requireManage, async (req, res) => { try { const result = await getPool().request().input('robotId', sql.Int, positiveId(req.params.id)) .query('DELETE FROM dbo.Robots OUTPUT DELETED.RobotId WHERE RobotId = @robotId'); if (!result.recordset.length) return res.status(404).json({ success: false, message: 'Không tìm thấy robot' }); res.json({ success: true, message: 'Đã xóa robot. Tài liệu vẫn được giữ trong kho tài liệu.' }); } catch (error) { fail(res, error); } }); router.use((error, _req, res, next) => { if (error instanceof multer.MulterError) { return res.status(400).json({ success: false, message: error.code === 'LIMIT_FILE_SIZE' ? `Ảnh đại diện tối đa 5 MB; tài liệu tối đa ${documentMaxMb} MB mỗi file` : `Tối đa 1 ảnh đại diện và ${MAX_DOCUMENT_UPLOADS} tài liệu; vui lòng kiểm tra tệp tải lên` }); } if (error.status === 400) return fail(res, error); next(error); }); return router; } module.exports = { ensureRobotSchema, createRobotRouter, parseDocumentIds, isAvatarBuffer };