quản lí robot

This commit is contained in:
2026-10-19 15:21:04 +07:00
parent 2be2e075a0
commit 0dc83be4e7
15 changed files with 2095 additions and 184 deletions

View File

@@ -44,5 +44,5 @@ SMTP_FROM=
EMAIL_VERIFY_TOKEN_TTL_MINUTES=30
PASSWORD_RESET_TOKEN_TTL_MINUTES=30
# Maximum size for each uploaded PDF document (1-100 MB).
# Maximum size for each uploaded document (1-100 MB), including robot attachments.
DOCUMENT_MAX_FILE_SIZE_MB=25

116
backend/document-files.js Normal file
View File

@@ -0,0 +1,116 @@
const path = require('node:path');
const { formats, accept, description } = require('../public/js/document-formats');
function documentError(message) {
return Object.assign(new Error(message), { status: 400, code: 'DOCUMENT_VALIDATION' });
}
function getDocumentFormat(fileName) {
return formats[path.extname(String(fileName || '')).toLowerCase()] || null;
}
function isPdfBuffer(value) {
return Buffer.isBuffer(value) && value.length >= 10
&& value.subarray(0, 5).toString('ascii') === '%PDF-'
&& value.subarray(Math.max(0, value.length - 2048)).includes(Buffer.from('%%EOF'));
}
// Inspect the ZIP directory without inflating any entry, including oversized compressed data.
function zipEntryNames(buffer) {
if (buffer.length < 22) return null;
for (let end = buffer.length - 22; end >= Math.max(0, buffer.length - 65557); end--) {
if (buffer.readUInt32LE(end) !== 0x06054b50 || end + 22 + buffer.readUInt16LE(end + 20) !== buffer.length) continue;
if (buffer.readUInt16LE(end + 4) !== 0 || buffer.readUInt16LE(end + 6) !== 0) return null;
const count = buffer.readUInt16LE(end + 10);
if (count !== buffer.readUInt16LE(end + 8)) return null;
const size = buffer.readUInt32LE(end + 12), offset = buffer.readUInt32LE(end + 16);
if (offset + size !== end) return null;
const names = new Set();
let cursor = offset;
for (let index = 0; index < count; index++) {
if (cursor + 46 > end || buffer.readUInt32LE(cursor) !== 0x02014b50) return null;
const nameSize = buffer.readUInt16LE(cursor + 28), extraSize = buffer.readUInt16LE(cursor + 30), commentSize = buffer.readUInt16LE(cursor + 32);
const next = cursor + 46 + nameSize + extraSize + commentSize;
if (next > end) return null;
const localOffset = buffer.readUInt32LE(cursor + 42);
if (localOffset + 30 > offset || buffer.readUInt32LE(localOffset) !== 0x04034b50) return null;
const dataStart = localOffset + 30 + buffer.readUInt16LE(localOffset + 26) + buffer.readUInt16LE(localOffset + 28);
if (dataStart + buffer.readUInt32LE(cursor + 20) > offset) return null;
names.add(buffer.toString('utf8', cursor + 46, cursor + 46 + nameSize));
cursor = next;
}
return cursor === offset + size ? names : null;
}
return null;
}
function isCompoundFile(buffer) {
return buffer.length >= 512 && buffer.subarray(0, 8).equals(Buffer.from('d0cf11e0a1b11ae1', 'hex'));
}
function hasStream(buffer, name) { return buffer.includes(Buffer.from(`${name}\0`, 'utf16le')); }
function documentContentMatches(buffer, extension) {
if (!Buffer.isBuffer(buffer) || !buffer.length) return false;
const starts = hex => buffer.length >= hex.length / 2 && buffer.subarray(0, hex.length / 2).equals(Buffer.from(hex, 'hex'));
const textStart = buffer.subarray(0, 8192).toString('utf8').trimStart();
switch (extension) {
case '.pdf': return isPdfBuffer(buffer);
case '.png': return buffer.length >= 24 && starts('89504e470d0a1a0a');
case '.jpg': case '.jpeg': return buffer.length >= 12 && starts('ffd8ff');
case '.gif': return buffer.length >= 13 && ['GIF87a', 'GIF89a'].includes(buffer.toString('ascii', 0, 6));
case '.webp': return buffer.length >= 12 && buffer.toString('ascii', 0, 4) === 'RIFF' && buffer.toString('ascii', 8, 12) === 'WEBP';
case '.bmp': return buffer.length >= 26 && starts('424d');
case '.tif': case '.tiff': return buffer.length >= 8 && (starts('49492a00') || starts('4d4d002a'));
case '.txt': case '.csv':
if (buffer.length >= 4 && (starts('fffe') || starts('feff'))) return buffer.length % 2 === 0;
return !buffer.some(byte => byte < 32 && ![9, 10, 13].includes(byte));
case '.rtf': return textStart.startsWith('{\\rtf');
case '.doc': return (isCompoundFile(buffer) && hasStream(buffer, 'WordDocument')) || textStart.startsWith('{\\rtf');
case '.xls': return (isCompoundFile(buffer) && (hasStream(buffer, 'Workbook') || hasStream(buffer, 'Book')))
|| (buffer.length >= 8 && [0x0009, 0x0209, 0x0409, 0x0809].includes(buffer.readUInt16LE(0)))
|| (textStart.includes('urn:schemas-microsoft-com:office:spreadsheet') && /<Workbook\b/.test(textStart));
case '.ppt': return isCompoundFile(buffer) && hasStream(buffer, 'PowerPoint Document');
case '.docx': case '.xlsx': case '.pptx': {
if (isCompoundFile(buffer) && hasStream(buffer, 'EncryptedPackage') && hasStream(buffer, 'EncryptionInfo')) return true;
const names = zipEntryNames(buffer);
const mainPart = { '.docx': 'word/document.xml', '.xlsx': 'xl/workbook.xml', '.pptx': 'ppt/presentation.xml' }[extension];
return Boolean(names?.has('[Content_Types].xml') && names.has(mainPart));
}
case '.zip': return zipEntryNames(buffer) !== null;
default: return false;
}
}
function validateDocumentFile(file) {
const extension = path.extname(String(file.originalname || '')).toLowerCase();
const format = formats[extension];
if (!format) throw documentError(`Định dạng chưa được hỗ trợ. Chấp nhận: ${description}.`);
if (!documentContentMatches(file.buffer, extension)) throw documentError(`Nội dung file không đúng định dạng ${extension} hoặc file bị hỏng`);
return format;
}
function normalizeUploadedFileName(value) {
const name = String(value || '');
if ([...name].some(character => character.charCodeAt(0) > 255)) return name;
const bytes = Buffer.from(name, 'latin1'), decoded = bytes.toString('utf8');
return Buffer.from(decoded, 'utf8').equals(bytes) ? decoded : name;
}
function sanitizeDocumentFileName(value) {
const cleaned = String(value || 'document.pdf').replace(/[\u0000-\u001f\u007f]/g, '')
.replace(/[\\/:*?"<>|]/g, '_').trim();
const extension = path.extname(cleaned) || '.pdf';
const base = path.extname(cleaned) ? cleaned.slice(0, -extension.length) : cleaned;
return `${(base || 'document').slice(0, Math.max(1, 255 - extension.length))}${extension.slice(0, 254)}`;
}
function getDocumentContentDisposition(fileName, download = false) {
const safeName = sanitizeDocumentFileName(fileName);
const asciiName = safeName.normalize('NFKD').replace(/[^\x20-\x7e]/g, '').replace(/["\\]/g, '_').trim() || 'document';
const encodedName = encodeURIComponent(safeName).replace(/['()*]/g, character => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
return `${download ? 'attachment' : 'inline'}; filename="${asciiName}"; filename*=UTF-8''${encodedName}`;
}
module.exports = { formats, accept, description, getDocumentFormat, isPdfBuffer, validateDocumentFile,
normalizeUploadedFileName, sanitizeDocumentFileName, getDocumentContentDisposition, zipEntryNames };

166
backend/documents.test.js Normal file
View File

@@ -0,0 +1,166 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const { createRequire } = require('node:module');
const express = require('express');
const XLSX = require('xlsx');
const files = require('./document-files');
function officeZip(mainPart) {
const container = XLSX.CFB.utils.cfb_new();
XLSX.CFB.utils.cfb_add(container, '[Content_Types].xml', Buffer.from('<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"/>'));
XLSX.CFB.utils.cfb_add(container, mainPart, Buffer.from('<document/>'));
return XLSX.CFB.write(container, { type: 'buffer', fileType: 'zip', compression: true });
}
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, XLSX.utils.aoa_to_sheet([['Robot', 'Model'], ['Cộng tác', 'CR10']]), 'Robots');
const examples = {
'manual.pdf': Buffer.from('%PDF-1.4\nmanual\n%%EOF'),
'manual.docx': officeZip('word/document.xml'),
'inventory.xlsx': XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' }),
'inventory.xls': XLSX.write(workbook, { type: 'buffer', bookType: 'xls' }),
'slides.pptx': officeZip('ppt/presentation.xml'),
'photo.png': Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aLl8AAAAASUVORK5CYII=', 'base64'),
'notes.txt': Buffer.from('Tài liệu robot tiếng Việt'),
'rows.csv': Buffer.from('name,model\nRobot,CR10'),
'notes.rtf': Buffer.from('{\\rtf1\\ansi Hello}'),
'bundle.zip': officeZip('manual.txt')
};
function productionWithPool(pool) {
const filename = path.join(__dirname, 'server.js');
const localRequire = createRequire(filename);
const sandbox = { require: name => name === 'dotenv' ? { config() {} } : localRequire(name),
module: { exports: {} }, __dirname, __filename: filename, Buffer, URL, console, testPool: pool,
process: { env: { NODE_ENV: 'test', DOCUMENT_MAX_FILE_SIZE_MB: '1', DATA_ENCRYPTION_SECRET: 'documents-test-only-secret-more-than-32-characters' }, on() {} } };
vm.runInNewContext(`${fs.readFileSync(filename, 'utf8')}\npool = testPool;`, sandbox, { filename });
return sandbox.module.exports.app;
}
async function fixture(t) {
const stored = new Map();
let nextId = 1, writes = 0;
const pool = { request() {
const inputs = {};
return { input(name, _type, value) { inputs[name] = value; return this; }, async query(query) {
if (query.includes('INSERT INTO Documents')) {
const document = { DocumentId: nextId++, Title: inputs.title, OriginalFileName: inputs.originalFileName,
MimeType: inputs.mimeType, FileSize: inputs.fileSize, FileData: inputs.fileData,
UploadedBy: 1, UploadedDate: '2026-10-19T10:00:00', CanDelete: true };
stored.set(document.DocumentId, document); writes++;
return { recordset: [document] };
}
if (inputs.documentId) return { recordset: stored.has(inputs.documentId) ? [stored.get(inputs.documentId)] : [] };
return { recordset: [...stored.values()] };
} };
} };
const production = productionWithPool(pool);
const app = express();
app.use(express.json());
app.use((req, res, next) => { req.user = { UserId: 1, Role: 'admin' }; res.setHeader('Cache-Control', 'no-store'); next(); });
// Exercise the actual multipart middleware, validators, SQL parameters and response headers.
for (const layer of production.router.stack) {
if (!layer.route?.path.startsWith('/api/documents')) continue;
for (const method of Object.keys(layer.route.methods)) {
app[method](layer.route.path, ...layer.route.stack.map(entry => entry.handle));
}
}
app.use(production.router.stack.at(-1).handle);
const server = app.listen(0, '127.0.0.1'); await new Promise(resolve => server.once('listening', resolve));
t.after(() => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); });
const base = `http://127.0.0.1:${server.address().port}/api/documents`;
return { stored, writes: () => writes, request: (suffix = '', options) => fetch(`${base}${suffix}`, options) };
}
function upload(name, buffer, type = 'application/octet-stream') {
const body = new FormData(); body.append('file', new Blob([buffer], { type }), name); return { method: 'POST', body };
}
test('document uploads retain actual extensions, canonical MIME types and exact download bytes', async t => {
const f = await fixture(t);
for (const [name, buffer] of Object.entries(examples)) {
const created = await f.request('', upload(name, buffer));
assert.equal(created.status, 201, `${name}: ${await created.clone().text()}`);
const document = (await created.json()).data;
assert.equal(document.OriginalFileName, name);
assert.equal(document.MimeType, files.getDocumentFormat(name).mimeType);
const response = await f.request(`/${document.DocumentId}/file?download=1`);
assert.equal(response.status, 200);
assert.match(response.headers.get('content-disposition'), /^attachment;/);
assert.ok(response.headers.get('content-disposition').includes(name));
assert.deepEqual(Buffer.from(await response.arrayBuffer()), Buffer.from(buffer));
}
assert.equal(f.writes(), Object.keys(examples).length);
});
test('PDF/image/text previews use their correct types; Office and ZIP always download', async t => {
const f = await fixture(t);
for (const name of ['manual.pdf', 'photo.png', 'notes.txt', 'manual.docx', 'inventory.xlsx', 'bundle.zip']) {
const id = (await (await f.request('', upload(name, examples[name]))).json()).data.DocumentId;
const response = await f.request(`/${id}/file`);
const format = files.getDocumentFormat(name);
assert.equal(response.headers.get('content-type').split(';')[0], format.mimeType);
assert.match(response.headers.get('content-disposition'), format.preview ? /^inline;/ : /^attachment;/);
assert.equal(response.headers.get('x-content-type-options'), 'nosniff');
}
});
test('wrong extensions, fake Office packages, damaged PDFs and oversized uploads never write data', async t => {
const f = await fixture(t);
for (const [name, buffer] of [['malware.exe', Buffer.from('MZ')], ['page.html', Buffer.from('<script/>')],
['image.svg', Buffer.from('<svg/>')], ['fake.pdf', Buffer.from('not PDF')], ['fake.docx', examples['bundle.zip']],
['wrong.xlsx', examples['manual.docx']], ['fake.png', examples['manual.pdf']], ['empty.txt', Buffer.alloc(0)],
['oversized.txt', Buffer.alloc(1024 * 1024 + 1, 65)]]) {
assert.equal((await f.request('', upload(name, buffer))).status, 400, name);
}
assert.equal(f.writes(), 0);
});
test('Vietnamese filenames remain readable and long names retain their actual extension', async t => {
const f = await fixture(t);
const name = 'Hướng dẫn vận hành.docx';
const document = (await (await f.request('', upload(name, examples['manual.docx']))).json()).data;
assert.equal(document.OriginalFileName, name);
assert.equal(document.Title, 'Hướng dẫn vận hành');
const response = await f.request(`/${document.DocumentId}/file`);
assert.ok(response.headers.get('content-disposition').includes(encodeURIComponent(name)));
const longName = files.sanitizeDocumentFileName(`${'a'.repeat(300)}.xlsx`);
assert.equal(longName.length, 255); assert.ok(longName.endsWith('.xlsx'));
assert.doesNotMatch(files.getDocumentContentDisposition('report\r\n.xlsx', true), /[\r\n]/);
});
test('ZIP directory validation is bounded and does not accept mismatched Office files', () => {
const damaged = Buffer.from(examples['bundle.zip']);
damaged.writeUInt32LE(0xffffffff, damaged.length - 22 + 16);
assert.equal(files.zipEntryNames(damaged), null);
assert.throws(() => files.validateDocumentFile({ originalname: 'manual.docx', buffer: examples['slides.pptx'] }));
assert.throws(() => files.validateDocumentFile({ originalname: 'data.csv', buffer: Buffer.from([1, 2, 0, 3]) }));
});
test('legacy Word and PowerPoint require their own OLE streams and retain their file types', () => {
for (const [name, stream] of [['manual.doc', 'WordDocument'], ['slides.ppt', 'PowerPoint Document']]) {
const container = XLSX.CFB.utils.cfb_new();
XLSX.CFB.utils.cfb_add(container, stream, Buffer.from('Legacy Office document stream'));
const buffer = XLSX.CFB.write(container, { type: 'buffer', fileType: 'cfb' });
assert.equal(files.validateDocumentFile({ originalname: name, buffer }).mimeType, files.getDocumentFormat(name).mimeType);
}
assert.throws(() => files.validateDocumentFile({ originalname: 'not-word.doc', buffer: examples['inventory.xls'] }));
});
test('document controls show per-format icons/previews and accept the same supported extensions', () => {
const context = vm.createContext({ document: { addEventListener() {} }, window: { fetch() {}, DocumentFormats: require('../public/js/document-formats') }, console });
vm.runInContext(`${fs.readFileSync(path.join(__dirname, '../public/js/app.js'), 'utf8')}\nglobalThis.manager = Object.create(AccountManager.prototype);`, context);
const manager = context.manager;
Object.assign(manager, { apiBase: '/api', documentSearchTerm: '', documentMaxFileSizeMb: 25,
documents: Object.keys(examples).map((name, index) => ({ DocumentId: index + 1, OriginalFileName: name, Title: name, FileSize: 123 })),
escapeHtml: value => String(value || '').replace(/</g, '&lt;').replace(/>/g, '&gt;') });
const html = manager.getDocumentsContent();
assert.match(html, /Xem PDF/); assert.match(html, /Xem Ảnh/);
assert.doesNotMatch(html, /Xem Word|Xem Excel/);
for (const name of Object.keys(examples)) assert.equal(manager.isSupportedDocumentName(name), true);
assert.equal(manager.isSupportedDocumentName('bad.exe'), false);
assert.match(html, /\.docx/); assert.match(html, /\.xlsx/); assert.match(html, /\.png/);
});

71
backend/robot-schema.sql Normal file
View File

@@ -0,0 +1,71 @@
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
IF OBJECT_ID('dbo.RobotTypes', 'U') IS NULL
BEGIN
CREATE TABLE dbo.RobotTypes (
TypeId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
Name NVARCHAR(100) NOT NULL,
Description NVARCHAR(500) NULL,
CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
UpdatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
CONSTRAINT UQ_RobotTypes_Name UNIQUE (Name)
);
END;
IF OBJECT_ID('dbo.Robots', 'U') IS NULL
BEGIN
CREATE TABLE dbo.Robots (
RobotId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
Name NVARCHAR(255) NOT NULL,
Model NVARCHAR(255) NOT NULL,
Type NVARCHAR(100) NOT NULL,
AvatarData VARBINARY(MAX) NULL,
AvatarMimeType NVARCHAR(100) NULL,
CreatedBy INT NULL,
CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
UpdatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
CONSTRAINT FK_Robots_CreatedBy FOREIGN KEY (CreatedBy) REFERENCES dbo.Users(UserId) ON DELETE SET NULL
);
CREATE INDEX IX_Robots_Name ON dbo.Robots(Name);
END;
IF COL_LENGTH('dbo.Robots', 'TypeId') IS NULL
ALTER TABLE dbo.Robots ADD TypeId INT NULL;
-- A separate compilation scope is required when TypeId was just added.
-- Only unmigrated rows seed the catalog, so renamed types stay renamed.
EXEC(N'
INSERT INTO dbo.RobotTypes (Name)
SELECT DISTINCT COALESCE(NULLIF(LTRIM(RTRIM(r.Type)), N''''), N''Chưa phân loại'')
FROM dbo.Robots r
WHERE r.TypeId IS NULL AND NOT EXISTS (
SELECT 1 FROM dbo.RobotTypes t
WHERE t.Name = COALESCE(NULLIF(LTRIM(RTRIM(r.Type)), N''''), N''Chưa phân loại'')
);
UPDATE r SET TypeId = t.TypeId, Type = t.Name
FROM dbo.Robots r JOIN dbo.RobotTypes t
ON t.Name = COALESCE(NULLIF(LTRIM(RTRIM(r.Type)), N''''), N''Chưa phân loại'')
WHERE r.TypeId IS NULL;
');
IF EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID('dbo.Robots') AND name = 'TypeId' AND is_nullable = 1)
EXEC(N'ALTER TABLE dbo.Robots ALTER COLUMN TypeId INT NOT NULL;');
IF NOT EXISTS (SELECT 1 FROM sys.foreign_keys WHERE name = 'FK_Robots_Type')
EXEC(N'ALTER TABLE dbo.Robots ADD CONSTRAINT FK_Robots_Type FOREIGN KEY (TypeId) REFERENCES dbo.RobotTypes(TypeId);');
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.Robots') AND name = 'IX_Robots_TypeId')
EXEC(N'CREATE INDEX IX_Robots_TypeId ON dbo.Robots(TypeId);');
IF OBJECT_ID('dbo.RobotDocuments', 'U') IS NULL
BEGIN
CREATE TABLE dbo.RobotDocuments (
RobotId INT NOT NULL,
DocumentId INT NOT NULL,
CONSTRAINT PK_RobotDocuments PRIMARY KEY (RobotId, DocumentId),
CONSTRAINT FK_RobotDocuments_Robot FOREIGN KEY (RobotId) REFERENCES dbo.Robots(RobotId) ON DELETE CASCADE,
CONSTRAINT FK_RobotDocuments_Document FOREIGN KEY (DocumentId) REFERENCES dbo.Documents(DocumentId)
);
CREATE INDEX IX_RobotDocuments_DocumentId ON dbo.RobotDocuments(DocumentId);
END;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
THROW;
END CATCH;

171
backend/robots-sql.test.js Normal file
View File

@@ -0,0 +1,171 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { randomBytes } = require('node:crypto');
const express = require('express');
const sql = require('mssql');
const { createRobotRouter, ensureRobotSchema } = require('./robots');
// Explicit opt-in to a disposable loopback SQL Server; never load application credentials.
test('SQL Server preserves shared PDFs, migrates repeatedly, and rolls back an entire failed robot save', {
skip: process.env.ACCMANAGER_ARCHIVE_SQL_TEST === '1' ? false
: 'Set ACCMANAGER_ARCHIVE_SQL_TEST=1 and explicit local SQL test credentials',
timeout: 120000
}, async () => {
const password = process.env.ACCMANAGER_ARCHIVE_TEST_SQL_PASSWORD;
const port = Number(process.env.ACCMANAGER_ARCHIVE_TEST_SQL_PORT || 14339);
assert.ok(password, 'Explicit local test password is required');
assert.ok(Number.isInteger(port) && port > 0 && port < 65536);
const database = `AccManagerRobotsTest_${Date.now()}_${randomBytes(6).toString('hex')}`;
const config = { server: '127.0.0.1', port, user: 'sa', password, database: 'master',
options: { encrypt: false, trustServerCertificate: true, enableArithAbort: true, useUTC: false },
pool: { min: 0, max: 3, idleTimeoutMillis: 1000 }, connectionTimeout: 15000, requestTimeout: 30000 };
const admin = await new sql.ConnectionPool(config).connect();
let pool, server, created = false;
try {
await admin.request().query(`CREATE DATABASE [${database}]`); created = true;
pool = await new sql.ConnectionPool({ ...config, database }).connect();
await pool.request().batch(`
CREATE TABLE dbo.Users (UserId INT IDENTITY PRIMARY KEY, Username NVARCHAR(100));
INSERT dbo.Users (Username) VALUES ('test');
CREATE TABLE dbo.Documents (
DocumentId INT IDENTITY PRIMARY KEY, Title NVARCHAR(255) NOT NULL,
OriginalFileName NVARCHAR(255) NOT NULL, MimeType NVARCHAR(100) NOT NULL DEFAULT 'application/pdf',
FileSize BIGINT NOT NULL, FileData VARBINARY(MAX) NOT NULL, UploadedBy INT NULL,
UploadedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
FOREIGN KEY (UploadedBy) REFERENCES dbo.Users(UserId) ON DELETE SET NULL
);
INSERT dbo.Documents (Title, OriginalFileName, FileSize, FileData, UploadedBy)
VALUES (N'Existing manual', 'existing.pdf', 12, 0x255044462D, 1),
(N'Failure case', 'failure.pdf', 12, 0x255044462D, 1);
CREATE TABLE dbo.Robots (
RobotId INT IDENTITY PRIMARY KEY, Name NVARCHAR(255) NOT NULL, Model NVARCHAR(255) NOT NULL,
Type NVARCHAR(100) NOT NULL, AvatarData VARBINARY(MAX) NULL, AvatarMimeType NVARCHAR(100) NULL,
CreatedBy INT NULL, CreatedDate DATETIME NOT NULL DEFAULT GETDATE(), UpdatedDate DATETIME NOT NULL DEFAULT GETDATE()
);
INSERT dbo.Robots (Name, Model, Type) VALUES (N'Legacy robot', 'LEGACY', N'Robot thử nghiệm');
`);
await ensureRobotSchema(pool); await ensureRobotSchema(pool);
const migrated = (await pool.request().query('SELECT r.TypeId, r.Type, t.Name FROM dbo.Robots r JOIN dbo.RobotTypes t ON t.TypeId = r.TypeId')).recordset;
assert.equal(migrated.length, 1);
assert.equal(migrated[0].Name, 'Robot thử nghiệm');
const typeId = migrated[0].TypeId;
await pool.request().query('DELETE dbo.Robots');
const app = express();
app.use(express.json());
app.use((req, _res, next) => { req.user = { UserId: 1, Role: 'asset' }; next(); });
app.use('/robots', createRobotRouter({ getPool: () => pool, sql, requireManage: (_req, _res, next) => next(),
documentMaxBytes: 1024 * 1024, documentMaxMb: 1,
isPdfBuffer: b => b.subarray(0, 5).toString() === '%PDF-' && b.includes(Buffer.from('%%EOF')),
sanitizeDocumentFileName: name => name,
sendInternalError: (res, _error, message) => res.status(500).json({ success: false, message })
}));
server = app.listen(0, '127.0.0.1'); await new Promise(resolve => server.once('listening', resolve));
const request = (suffix, options) => fetch(`http://127.0.0.1:${server.address().port}/robots${suffix}`, options);
const pdf = Buffer.from('%PDF-1.4\nNew manual\n%%EOF');
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aLl8AAAAASUVORK5CYII=', 'base64');
const form = (name, documentIds = '[1]') => {
const body = new FormData();
for (const [key, value] of Object.entries({ name, model: 'SQL-TEST', typeId: String(typeId), documentIds })) body.append(key, value);
return body;
};
const snapshot = async () => (await pool.request().query(`
SELECT COUNT(*) AS n FROM dbo.Robots;
SELECT COUNT(*) AS n FROM dbo.Documents;
SELECT COUNT(*) AS n FROM dbo.RobotDocuments;
`)).recordsets.map(rows => rows[0].n);
const body = form('Robot thử SQL');
body.append('avatar', new Blob([png], { type: 'image/png' }), 'robot.png');
body.append('documents', new Blob([pdf], { type: 'application/pdf' }), 'new.pdf');
const create = await request('', { method: 'POST', body });
assert.equal(create.status, 201, await create.clone().text());
const firstId = (await create.json()).data.RobotId;
assert.deepEqual(await snapshot(), [1, 3, 2]);
const avatar = await request(`/${firstId}/avatar`);
assert.deepEqual(Buffer.from(await avatar.arrayBuffer()), png);
let details = await (await request(`/${firstId}`)).json();
assert.equal(details.data.Name, 'Robot thử SQL');
assert.equal(details.data.Documents.length, 2);
const uploadedId = details.data.Documents.find(doc => doc.OriginalFileName === 'new.pdf').DocumentId;
const savedBytes = (await pool.request().input('id', sql.Int, uploadedId)
.query('SELECT FileData FROM dbo.Documents WHERE DocumentId = @id')).recordset[0].FileData;
assert.deepEqual(savedBytes, pdf);
// A second robot shares an existing PDF without duplicating its content.
const second = await request('', { method: 'POST', body: form('Robot thứ hai') });
assert.equal(second.status, 201);
const secondId = (await second.json()).data.RobotId;
assert.deepEqual(await snapshot(), [2, 3, 3]);
await assert.rejects(pool.request().query('DELETE dbo.Documents WHERE DocumentId = 1'), error => error.number === 547);
await ensureRobotSchema(pool);
assert.deepEqual(await snapshot(), [2, 3, 3]);
// An actual SQL constraint failure happens after metadata/PDF insertion.
await pool.request().query('ALTER TABLE dbo.RobotDocuments ADD CONSTRAINT CK_RobotLinks_Test CHECK (DocumentId <> 2)');
const failure = form('Must roll back', '[2]');
failure.append('documents', new Blob([pdf], { type: 'application/pdf' }), 'rollback.pdf');
assert.equal((await request('', { method: 'POST', body: failure })).status, 500);
assert.deepEqual(await snapshot(), [2, 3, 3]);
const failedEdit = form('Must not overwrite existing robot', '[2]');
failedEdit.append('documents', new Blob([pdf], { type: 'application/pdf' }), 'rollback-edit.pdf');
assert.equal((await request(`/${firstId}`, { method: 'PUT', body: failedEdit })).status, 500);
assert.deepEqual(await snapshot(), [2, 3, 3]);
details = await (await request(`/${firstId}`)).json();
assert.equal(details.data.Name, 'Robot thử SQL'); assert.equal(details.data.Documents.length, 2);
await pool.request().query('ALTER TABLE dbo.RobotDocuments DROP CONSTRAINT CK_RobotLinks_Test');
const partial = await request(`/${firstId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Đã sửa', model: 'NEW', typeId }) });
assert.equal(partial.status, 200);
details = await (await request(`/${firstId}`)).json();
assert.equal(details.data.Documents.length, 2); assert.equal(details.data.HasAvatar, true);
const clear = form('Đã gỡ liên kết', '[]'); clear.append('removeAvatar', 'true');
assert.equal((await request(`/${firstId}`, { method: 'PUT', body: clear })).status, 200);
assert.deepEqual(await snapshot(), [2, 3, 1]);
assert.equal((await request(`/${firstId}/avatar`)).status, 404);
await assert.rejects(pool.request().query('DELETE dbo.Documents WHERE DocumentId = 1'), error => error.number === 547);
assert.equal((await request(`/${secondId}`, { method: 'DELETE' })).status, 200);
assert.deepEqual(await snapshot(), [1, 3, 0]);
await pool.request().query('DELETE dbo.Documents WHERE DocumentId = 1');
assert.deepEqual(await snapshot(), [1, 2, 0]);
const json = body => ({ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
assert.equal((await request(`/types/${typeId}`, { method: 'DELETE' })).status, 409);
assert.equal((await request('/types', { method: 'POST', ...json({ name: 'Robot thử nghiệm' }) })).status, 409);
const extraType = await request('/types', { method: 'POST', ...json({ name: 'Robot di động', description: 'AMR/AGV' }) });
assert.equal(extraType.status, 201);
const extraId = (await extraType.json()).data.TypeId;
// An in-use type can be renamed without changing its identity or its robots.
assert.equal((await request(`/types/${typeId}`, { method: 'PUT', ...json({ name: 'Thể loại đã đổi tên', description: 'Updated' }) })).status, 200);
await ensureRobotSchema(pool); await ensureRobotSchema(pool);
const catalog = (await (await request('/types')).json()).data;
assert.equal(catalog.length, 2);
assert.equal(catalog.find(type => type.TypeId === typeId).RobotCount, 1);
details = await (await request(`/${firstId}`)).json();
assert.equal(details.data.TypeId, typeId);
assert.equal(details.data.Type, 'Thể loại đã đổi tên');
const duplicateRename = await request(`/types/${typeId}`, { method: 'PUT', ...json({ name: 'Robot di động' }) });
assert.equal(duplicateRename.status, 409);
assert.equal((await (await request(`/${firstId}`)).json()).data.Type, 'Thể loại đã đổi tên');
// Reassignment releases the old type, while the new type becomes protected.
const reassign = form('Chuyển thể loại'); reassign.set('typeId', String(extraId)); reassign.set('documentIds', '[]');
assert.equal((await request(`/${firstId}`, { method: 'PUT', body: reassign })).status, 200);
assert.equal((await request(`/types/${typeId}`, { method: 'DELETE' })).status, 200);
assert.equal((await request(`/types/${extraId}`, { method: 'DELETE' })).status, 409);
assert.equal((await request(`/${firstId}`, { method: 'DELETE' })).status, 200);
assert.equal((await request(`/types/${extraId}`, { method: 'DELETE' })).status, 200);
const stale = form('Must reject stale type'); stale.set('typeId', String(extraId));
assert.equal((await request('', { method: 'POST', body: stale })).status, 400);
assert.deepEqual(await snapshot(), [0, 2, 0]);
} finally {
if (server) { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }
if (pool) await pool.close();
try {
if (created) {
assert.match(database, /^AccManagerRobotsTest_\d+_[a-f0-9]{12}$/);
await admin.request().query(`ALTER DATABASE [${database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE`);
await admin.request().query(`DROP DATABASE [${database}]`);
}
} finally { await admin.close(); }
}
});

317
backend/robots.js Normal file
View File

@@ -0,0 +1,317 @@
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 sử dụng. Hãy chuyển các robot sang thể loại khác trước khi xóa.' });
}
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 };

322
backend/robots.test.js Normal file
View File

@@ -0,0 +1,322 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const express = require('express');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const { createRequire } = require('node:module');
const { createRobotRouter, parseDocumentIds } = require('./robots');
const pdf = Buffer.from('%PDF-1.4\nrobot manual\n%%EOF\n');
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aLl8AAAAASUVORK5CYII=', 'base64');
async function fixture(t, { answer, role = 'asset', maxBytes = 1024 * 1024 } = {}) {
const queries = [], transactions = [];
class Request {
constructor(transaction) { this.transaction = transaction; this.inputs = {}; }
input(name, _type, value) { this.inputs[name] = value; return this; }
async query(query) {
const call = { query, inputs: this.inputs, transaction: this.transaction };
queries.push(call);
const result = answer?.(call);
if (result !== undefined) return result;
if (query.includes('SELECT TypeId, Name FROM dbo.RobotTypes')) return { recordset: [{ TypeId: this.inputs.typeId, Name: 'Cộng tác' }] };
if (query.includes('INSERT INTO dbo.Robots')) return { recordset: [{ RobotId: 17 }] };
if (query.includes('INSERT INTO dbo.Documents')) return { recordset: [{ DocumentId: 51 }] };
if (query.includes('SELECT DocumentId FROM dbo.Documents')) return { recordset: [{ DocumentId: this.inputs.documentId }] };
if (query.includes('SELECT RobotId FROM dbo.Robots')) return { recordset: [{ RobotId: 17 }] };
if (query.includes('COUNT(*) AS DocumentCount')) return { recordset: [{ DocumentCount: 2 }] };
return { recordset: [] };
}
}
class Transaction {
constructor() { transactions.push(this); }
async begin() { this.begun = true; }
async commit() { this.committed = true; }
async rollback() { this.rolledBack = true; }
}
const app = express();
app.use(express.json());
app.use((_req, res, next) => {
res.setHeader('Cache-Control', 'no-store'); next();
});
app.use((req, _res, next) => { req.user = { UserId: 1, Role: role }; next(); });
app.use('/api/robots', createRobotRouter({
getPool: () => ({ request: () => new Request() }),
sql: { ...require('mssql'), Request, Transaction },
requireManage(req, res, next) {
if (!['asset', 'admin'].includes(req.user.Role)) return res.status(403).json({ success: false });
next();
},
documentMaxBytes: maxBytes, documentMaxMb: 1,
isPdfBuffer: buffer => buffer.subarray(0, 5).toString() === '%PDF-' && buffer.includes(Buffer.from('%%EOF')),
sanitizeDocumentFileName: name => name.replace(/[\\/\r\n]/g, '_'),
sendInternalError: (res, _error, message) => res.status(500).json({ success: false, message })
}));
const server = app.listen(0, '127.0.0.1');
await new Promise(resolve => server.once('listening', resolve));
t.after(() => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); });
return { queries, transactions, request: (suffix = '', options) => fetch(`http://127.0.0.1:${server.address().port}/api/robots${suffix}`, options) };
}
function form(extra = {}) {
const body = new FormData();
for (const [key, value] of Object.entries({ name: 'Robot hàn', model: 'CR10', typeId: '1', documentIds: '[3,2,3]', ...extra })) {
if (value !== undefined) body.append(key, value);
}
return body;
}
test('creating a robot saves its avatar, new PDFs and existing links in one transaction', async t => {
const f = await fixture(t);
const body = form();
body.append('avatar', new Blob([png], { type: 'image/png' }), 'robot.png');
body.append('documents', new Blob([pdf], { type: 'application/pdf' }), 'manual.pdf');
const response = await f.request('', { method: 'POST', body });
assert.equal(response.status, 201);
assert.equal((await response.json()).data.RobotId, 17);
assert.equal(f.transactions[0].committed, true);
assert.ok(f.queries.every(query => query.transaction === f.transactions[0]));
const robot = f.queries.find(q => q.query.includes('INSERT INTO dbo.Robots'));
assert.equal(robot.inputs.name, 'Robot hàn');
assert.equal(robot.inputs.typeId, 1);
assert.equal(robot.inputs.type, 'Cộng tác');
assert.deepEqual(robot.inputs.avatarData, png);
const links = f.queries.filter(q => q.query.includes('INSERT INTO dbo.RobotDocuments'));
assert.deepEqual(links.map(q => q.inputs.documentId), [2, 3, 51]);
assert.equal(f.queries.filter(q => q.query.includes('INSERT INTO dbo.Documents')).length, 1);
});
test('a PDF storage failure rolls back robot metadata and every link', async t => {
const f = await fixture(t, { answer({ query }) {
if (query.includes('INSERT INTO dbo.Documents')) throw new Error('Storage failed');
} });
const body = form(); body.append('documents', new Blob([pdf], { type: 'application/pdf' }), 'manual.pdf');
assert.equal((await f.request('', { method: 'POST', body })).status, 500);
assert.equal(f.transactions[0].rolledBack, true);
assert.equal(f.transactions[0].committed, undefined);
assert.equal(f.queries.some(q => q.query.includes('INSERT INTO dbo.RobotDocuments')), false);
});
test('a missing library PDF rejects the whole save before inserting a robot', async t => {
const f = await fixture(t, { answer: ({ query }) => query.includes('SELECT DocumentId FROM dbo.Documents') ? { recordset: [] } : undefined });
assert.equal((await f.request('', { method: 'POST', body: form() })).status, 400);
assert.equal(f.transactions[0].rolledBack, true);
assert.equal(f.queries.some(q => q.query.includes('INSERT')), false);
});
test('editing replaces selected links while retaining the avatar unless requested', async t => {
const f = await fixture(t);
assert.equal((await f.request('/17', { method: 'PUT', body: form({ documentIds: '[8]' }) })).status, 200);
const update = f.queries.find(q => q.query.includes('UPDATE dbo.Robots'));
assert.equal(update.inputs.replaceAvatar, false);
assert.match(update.query, /ELSE AvatarData END/);
assert.ok(f.queries.some(q => q.query.includes('DELETE FROM dbo.RobotDocuments')));
assert.deepEqual(f.queries.filter(q => q.query.includes('INSERT INTO dbo.RobotDocuments')).map(q => q.inputs.documentId), [8]);
assert.equal(f.queries.some(q => q.query.includes('DELETE FROM dbo.Documents')), false);
});
test('partial edits preserve document links and can explicitly remove the avatar', async t => {
const f = await fixture(t);
assert.equal((await f.request('/17', { method: 'PUT', body: form({ documentIds: undefined, removeAvatar: 'true' }) })).status, 200);
const update = f.queries.find(q => q.query.includes('UPDATE dbo.Robots'));
assert.equal(update.inputs.replaceAvatar, true);
assert.equal(update.inputs.avatarData, null);
assert.equal(f.queries.some(q => q.query.includes('DELETE FROM dbo.RobotDocuments')), false);
});
test('forged image/PDF contents and oversized avatars are rejected before database access', async t => {
const f = await fixture(t);
for (const [field, type, name, bytes] of [
['avatar', 'image/png', 'bad.png', Buffer.from('not an image')],
['documents', 'application/pdf', 'bad.pdf', Buffer.from('not a PDF')],
['avatar', 'image/png', 'large.png', Buffer.alloc(5 * 1024 * 1024 + 1)]
]) {
const body = form(); body.append(field, new Blob([bytes], { type }), name);
assert.equal((await f.request('', { method: 'POST', body })).status, 400);
}
assert.equal(f.queries.length, 0);
assert.equal(f.transactions.length, 0);
});
test('PDF size configuration, image extensions and upload counts are enforced', async t => {
const f = await fixture(t, { maxBytes: 20 });
const oversizedPdf = form(); oversizedPdf.append('documents', new Blob([pdf], { type: 'application/pdf' }), 'manual.pdf');
const svg = form(); svg.append('avatar', new Blob(['<svg/>'], { type: 'image/svg+xml' }), 'image.svg');
const many = form();
for (let i = 0; i < 11; i++) many.append('documents', new Blob([pdf], { type: 'application/pdf' }), `${i}.pdf`);
for (const body of [oversizedPdf, svg, many]) assert.equal((await f.request('', { method: 'POST', body })).status, 400);
assert.equal(f.transactions.length, 0);
});
test('invalid metadata and document IDs return useful errors without writes', async t => {
const f = await fixture(t);
for (const extra of [{ name: ' ' }, { model: '' }, { typeId: undefined }, { typeId: '0' }, { typeId: '2147483648' }, { documentIds: 'invalid' },
{ documentIds: '[0]' }, { documentIds: '["3 OR 1=1"]' }, { documentIds: '[2147483648]' }]) {
assert.equal((await f.request('', { method: 'POST', body: form(extra) })).status, 400);
}
assert.equal((await f.request('', { method: 'POST' })).status, 400);
assert.equal((await f.request('/17x', { method: 'PUT', body: form() })).status, 400);
assert.equal(f.transactions.length, 0);
assert.throws(() => parseDocumentIds(Array.from({ length: 101 }, (_, i) => i + 1)));
});
test('missing robots cannot be edited or silently recreated', async t => {
const f = await fixture(t, { answer: ({ query }) => query.includes('SELECT RobotId FROM dbo.Robots') ? { recordset: [] } : undefined });
assert.equal((await f.request('/17', { method: 'PUT', body: form() })).status, 404);
assert.equal(f.transactions[0].rolledBack, true);
assert.equal(f.queries.some(q => q.query.includes('UPDATE') && !q.query.includes('UPDLOCK')), false);
});
test('ordinary users can read robot data but cannot add, update or delete robots', async t => {
const f = await fixture(t, { role: 'user' });
assert.equal((await f.request()).status, 200);
for (const [method, suffix] of [['POST', ''], ['PUT', '/17'], ['DELETE', '/17']]) {
assert.equal((await f.request(suffix, { method, ...(method === 'DELETE' ? {} : { body: form() }) })).status, 403);
}
assert.equal(f.transactions.length, 0);
assert.equal(f.queries.length, 1);
});
test('avatar endpoints return the stored bytes and safe content type', async t => {
const f = await fixture(t, { answer: ({ query }) => query.includes('SELECT AvatarData') ? { recordset: [{ AvatarData: png, AvatarMimeType: 'image/png' }] } : undefined });
const response = await f.request('/17/avatar');
assert.equal(response.status, 200);
assert.equal(response.headers.get('content-type'), 'image/png');
assert.equal(response.headers.get('x-content-type-options'), 'nosniff');
assert.equal(response.headers.get('cache-control'), 'no-store');
assert.deepEqual(Buffer.from(await response.arrayBuffer()), png);
});
test('deleting a robot never deletes shared PDF documents', async t => {
const f = await fixture(t, { answer: ({ query }) => query.startsWith('DELETE FROM dbo.Robots') ? { recordset: [{ RobotId: 17 }] } : undefined });
assert.equal((await f.request('/17', { method: 'DELETE' })).status, 200);
assert.equal(f.queries.length, 1);
assert.match(f.queries[0].query, /^DELETE FROM dbo.Robots/);
assert.doesNotMatch(f.queries[0].query, /DELETE FROM (?:dbo\.)?Documents/);
});
test('robot cards escape user content, search name/model/type, and hide edit actions for viewers', () => {
const source = fs.readFileSync(path.join(__dirname, '../public/js/app.js'), 'utf8');
const context = vm.createContext({ document: { addEventListener() {} }, window: { fetch() {} }, console });
vm.runInContext(`${source}\nglobalThis.manager = Object.create(AccountManager.prototype);`, context);
const manager = context.manager;
Object.assign(manager, { robots: [{ RobotId: 17, Name: '<script>Robot</script>', Model: 'CR10', TypeId: 1, Type: 'Cộng tác', DocumentCount: 2 }],
robotTypes: [{ TypeId: 1, Name: 'Cộng tác', RobotCount: 1 }],
apiBase: '/api', currentUser: { Role: 'user' }, robotPage: 1, robotPageSize: 12, robotSearchTerm: '', robotTypeFilter: '',
robotLoadError: '', escapeHtml: value => String(value ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;') });
let html = manager.getRobotsContent();
assert.match(html, /&lt;script&gt;Robot/);
assert.doesNotMatch(html, /<script>Robot/);
assert.match(html, /2 tài liệu/);
assert.doesNotMatch(html, /data-robot-action="edit"|data-robot-action="delete"|id="addRobotBtn"/);
manager.currentUser.Role = 'admin';
assert.match(manager.getRobotsContent(), /data-robot-action="edit"/);
for (const keyword of ['robot', 'cr10', 'cộng tác']) {
manager.robotSearchTerm = keyword; assert.equal(manager.getFilteredRobots().length, 1);
}
manager.robotTypeFilter = 'AMR'; assert.equal(manager.getFilteredRobots().length, 0);
manager.robotTypeFilter = '1'; assert.equal(manager.getFilteredRobots().length, 1);
manager.robotSearchTerm = ''; manager.robotTypeFilter = ''; manager.robotLoadError = 'Server unavailable';
html = manager.getRobotsContent(); assert.match(html, /role="alert"/); assert.match(html, /Server unavailable/);
});
function serverWithPool(pool) {
const serverPath = path.join(__dirname, 'server.js');
const serverRequire = createRequire(serverPath);
const sandbox = {
require: name => name === 'dotenv' ? { config() {} } : serverRequire(name),
module: { exports: {} }, __dirname, __filename: serverPath, Buffer, URL, console,
process: { env: { NODE_ENV: 'test', DATA_ENCRYPTION_SECRET: 'robot-tests-only-key-with-more-than-32-characters' }, on() {} },
robotTestPool: pool
};
vm.runInNewContext(`${fs.readFileSync(serverPath, 'utf8')}\npool = robotTestPool;`, sandbox, { filename: serverPath });
return sandbox.module.exports.app;
}
test('all robot endpoints require an authenticated session in the production application', async t => {
const app = serverWithPool(null);
const server = app.listen(0, '127.0.0.1'); await new Promise(resolve => server.once('listening', resolve));
t.after(() => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); });
const base = `http://127.0.0.1:${server.address().port}/api/robots`;
for (const [method, suffix] of [['GET', ''], ['GET', '/17'], ['GET', '/17/avatar'], ['POST', ''], ['PUT', '/17'], ['DELETE', '/17'],
['GET', '/types'], ['POST', '/types'], ['PUT', '/types/1'], ['DELETE', '/types/1']]) {
const response = await fetch(`${base}${suffix}`, { method, headers: { 'X-User-Id': '1', 'X-User-Role': 'admin' } });
assert.equal(response.status, 401);
}
});
test('a deleted or unknown robot type rejects the save before inserting robot data', async t => {
const f = await fixture(t, { answer: ({ query }) => query.includes('SELECT TypeId, Name FROM dbo.RobotTypes') ? { recordset: [] } : undefined });
assert.equal((await f.request('', { method: 'POST', body: form() })).status, 400);
assert.equal(f.transactions[0].rolledBack, true);
assert.equal(f.queries.some(q => q.query.includes('INSERT')), false);
});
test('viewers can read the type catalog but cannot create, rename or delete types', async t => {
const f = await fixture(t, { role: 'user' });
assert.equal((await f.request('/types')).status, 200);
for (const [method, suffix] of [['POST', '/types'], ['PUT', '/types/1'], ['DELETE', '/types/1']]) {
assert.equal((await f.request(suffix, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'AMR' }) })).status, 403);
}
assert.equal(f.queries.length, 1);
assert.equal(f.transactions.length, 0);
});
test('type input is validated and duplicate type names return a conflict', async t => {
const f = await fixture(t, { answer({ query }) {
if (query.includes('INSERT INTO dbo.RobotTypes')) throw Object.assign(new Error('duplicate'), { number: 2627 });
} });
for (const body of [{ name: '' }, { name: ' ' }, { name: 'a'.repeat(101) }, { name: [] }, { name: 'AMR', description: 'a'.repeat(501) }]) {
assert.equal((await f.request('/types', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })).status, 400);
}
assert.equal(f.queries.length, 0);
assert.equal((await f.request('/types', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'AMR' }) })).status, 409);
});
test('renaming a type updates the catalog and robot display values atomically', async t => {
const f = await fixture(t, { answer: ({ query }) => query.includes('UPDATE dbo.RobotTypes') ? { recordset: [{ TypeId: 1, Name: 'Cộng tác mới' }] } : undefined });
const response = await f.request('/types/1', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Cộng tác mới', description: 'New description' }) });
assert.equal(response.status, 200);
assert.equal(f.transactions[0].committed, true);
assert.ok(f.queries.every(call => call.transaction === f.transactions[0]));
assert.ok(f.queries.some(call => call.query.includes('UPDATE dbo.Robots SET Type = @name') && call.inputs.name === 'Cộng tác mới'));
});
test('rename failures roll back; used types cannot be deleted, and missing types return 404', async t => {
const failed = await fixture(t, { answer({ query }) {
if (query.includes('UPDATE dbo.RobotTypes')) return { recordset: [{ TypeId: 1 }] };
if (query.includes('UPDATE dbo.Robots')) throw new Error('Storage failure');
} });
assert.equal((await failed.request('/types/1', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Rename' }) })).status, 500);
assert.equal(failed.transactions[0].rolledBack, true);
for (const mode of ['used', 'missing', 'unused']) {
const f = await fixture(t, { answer({ query }) {
if (query.includes('DELETE FROM dbo.RobotTypes')) {
if (mode === 'used') throw Object.assign(new Error('FK conflict'), { number: 547 });
return { recordset: mode === 'unused' ? [{ TypeId: 1 }] : [] };
}
} });
assert.equal((await f.request('/types/1', { method: 'DELETE' })).status, mode === 'used' ? 409 : mode === 'missing' ? 404 : 200);
}
});
test('document deletion blocks robot links and concurrent foreign-key conflicts while retaining owner permissions', async () => {
for (const mode of ['linked', 'unlinked', 'concurrent', 'other-owner']) {
let calls = 0;
const app = serverWithPool({ request() {
return { input() { return this; }, async query(query) {
calls++;
if (query.startsWith('SELECT')) return { recordset: [{ DocumentId: 3, UploadedBy: mode === 'other-owner' ? 2 : 1 }] };
assert.match(query, /NOT EXISTS \(SELECT 1 FROM dbo.RobotDocuments/);
if (mode === 'concurrent') throw Object.assign(new Error('FK conflict'), { number: 547 });
return { recordset: mode === 'unlinked' ? [{ DocumentId: 3 }] : [] };
} };
} });
const route = app.router.stack.find(layer => layer.route?.path === '/api/documents/:id' && layer.route.methods.delete).route;
const response = { statusCode: 200, status(code) { this.statusCode = code; return this; }, json(body) { this.body = body; return this; } };
await route.stack.at(-1).handle({ params: { id: '3' }, user: { UserId: 1, Role: 'user' } }, response);
assert.equal(response.statusCode, mode === 'other-owner' ? 403 : mode === 'unlinked' ? 200 : 409);
assert.equal(calls, mode === 'other-owner' ? 1 : 2);
}
});

View File

@@ -16,6 +16,9 @@ const { ensureAssetArchiveSchema } = require('./asset-archive-schema');
const { parseAllocations, normalizeExportAllocations, addAllocations, releaseAllocations } = require('./asset-project-allocations');
const { buildExportRequestWorkbook } = require('./export-request-workbook');
const { ensureAssetExportDocumentSchema } = require('./asset-export-documents');
const { ensureRobotSchema, createRobotRouter } = require('./robots');
const { getDocumentFormat, isPdfBuffer, validateDocumentFile, normalizeUploadedFileName,
sanitizeDocumentFileName, getDocumentContentDisposition, accept: documentAccept } = require('./document-files');
dotenv.config();
@@ -2291,47 +2294,13 @@ const documentUpload = multer({
parts: 7
},
fileFilter(req, file, callback) {
const extension = require('path').extname(String(file.originalname || '')).toLowerCase();
const mimeType = String(file.mimetype || '').toLowerCase();
if (extension !== '.pdf' || mimeType !== 'application/pdf') {
return callback(new Error('Chỉ chấp nhận file PDF'));
if (!getDocumentFormat(file.originalname)) {
return callback(Object.assign(new Error('Định dạng tài liệu chưa được hỗ trợ'), { code: 'DOCUMENT_VALIDATION' }));
}
callback(null, true);
}
});
function isPdfBuffer(value) {
if (!Buffer.isBuffer(value) || value.length < 10 || value.subarray(0, 5).toString('ascii') !== '%PDF-') {
return false;
}
const trailerStart = Math.max(0, value.length - 2048);
return value.subarray(trailerStart).includes(Buffer.from('%%EOF', 'ascii'));
}
function sanitizeDocumentFileName(value) {
const cleaned = String(value || 'document.pdf')
.replace(/[\u0000-\u001f\u007f]/g, '')
.replace(/[\\/:*?"<>|]/g, '_')
.trim()
.slice(0, 255);
const baseName = cleaned || 'document.pdf';
return baseName.toLowerCase().endsWith('.pdf')
? baseName
: `${baseName.slice(0, 251)}.pdf`;
}
function getDocumentContentDisposition(fileName, download = false) {
const safeFileName = sanitizeDocumentFileName(fileName);
const asciiFileName = safeFileName
.normalize('NFKD')
.replace(/[^\x20-\x7e]/g, '')
.replace(/["\\]/g, '_')
.trim() || 'document.pdf';
const encodedFileName = encodeURIComponent(safeFileName)
.replace(/['()*]/g, character => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
return `${download ? 'attachment' : 'inline'}; filename="${asciiFileName}"; filename*=UTF-8''${encodedFileName}`;
}
// Serve static files from /public
const path = require('path');
const publicDir = path.join(__dirname, '..', 'public');
@@ -3129,6 +3098,7 @@ async function createTables() {
// Fail startup if history preservation cannot be installed.
await ensureAssetArchiveSchema(pool);
await ensureAssetExportDocumentSchema(pool);
await ensureRobotSchema(pool);
await pool.request().query(`
IF COL_LENGTH('dbo.AssetInventory', 'ProjectAllocations') IS NULL
ALTER TABLE dbo.AssetInventory ADD ProjectAllocations NVARCHAR(MAX) NULL;
@@ -9550,9 +9520,15 @@ app.post('/api/assets/import', requireAssetOrAdmin, upload.single('file'), async
});
// ==========================================
// API ROUTES - PDF Documents
// API ROUTES - Shared Documents
// ==========================================
app.use('/api/robots', createRobotRouter({
getPool: () => pool, sql, requireManage: requireAssetOrAdmin,
documentMaxBytes: DOCUMENT_MAX_FILE_SIZE_BYTES, documentMaxMb: DOCUMENT_MAX_FILE_SIZE_MB,
sanitizeDocumentFileName, sendInternalError
}));
app.get('/api/documents', async (req, res) => {
try {
const search = String(req.query.search || '').trim().slice(0, 255);
@@ -9583,7 +9559,8 @@ app.get('/api/documents', async (req, res) => {
res.json({
success: true,
data: result.recordset,
maxFileSizeMb: DOCUMENT_MAX_FILE_SIZE_MB
maxFileSizeMb: DOCUMENT_MAX_FILE_SIZE_MB,
acceptedExtensions: documentAccept
});
} catch (err) {
sendInternalError(res, err, 'Không thể tải danh sách tài liệu');
@@ -9593,20 +9570,18 @@ app.get('/api/documents', async (req, res) => {
app.post('/api/documents', documentUpload.single('file'), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ success: false, message: 'Vui lòng chọn file PDF' });
}
if (!isPdfBuffer(req.file.buffer)) {
return res.status(400).json({ success: false, message: 'Nội dung file không phải là PDF hợp lệ' });
return res.status(400).json({ success: false, message: 'Vui lòng chọn tài liệu' });
}
const format = validateDocumentFile(req.file);
const originalFileName = sanitizeDocumentFileName(req.file.originalname);
const originalFileName = sanitizeDocumentFileName(normalizeUploadedFileName(req.file.originalname));
const requestedTitle = String(req.body.title || '').trim();
const defaultTitle = originalFileName.replace(/\.pdf$/i, '').trim() || 'Tài liệu PDF';
const defaultTitle = originalFileName.replace(/\.[^.]+$/, '').trim() || 'Tài liệu';
const title = (requestedTitle || defaultTitle).slice(0, 255);
const result = await pool.request()
.input('title', sql.NVarChar(255), title)
.input('originalFileName', sql.NVarChar(255), originalFileName)
.input('mimeType', sql.NVarChar(100), 'application/pdf')
.input('mimeType', sql.NVarChar(100), format.mimeType)
.input('fileSize', sql.BigInt, req.file.size)
.input('fileData', sql.VarBinary(sql.MAX), req.file.buffer)
.input('uploadedBy', sql.Int, req.user.UserId)
@@ -9619,10 +9594,11 @@ app.post('/api/documents', documentUpload.single('file'), async (req, res) => {
res.status(201).json({
success: true,
message: 'Đã lưu tài liệu PDF',
message: 'Đã lưu tài liệu',
data: result.recordset[0]
});
} catch (err) {
if (err.code === 'DOCUMENT_VALIDATION') return res.status(400).json({ success: false, message: err.message });
sendInternalError(res, err, 'Không thể lưu tài liệu');
}
});
@@ -9646,8 +9622,10 @@ app.get('/api/documents/:id/file', async (req, res) => {
return res.status(404).json({ success: false, message: 'Không tìm thấy tài liệu' });
}
const shouldDownload = String(req.query.download || '') === '1';
res.setHeader('Content-Type', 'application/pdf');
const format = getDocumentFormat(document.OriginalFileName);
const shouldDownload = String(req.query.download || '') === '1' || !format?.preview;
res.setHeader('Content-Type', format?.mimeType || 'application/octet-stream');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Content-Length', String(document.FileSize));
res.setHeader('Content-Disposition', getDocumentContentDisposition(document.OriginalFileName, shouldDownload));
res.send(document.FileData);
@@ -9677,11 +9655,19 @@ app.delete('/api/documents/:id', async (req, res) => {
return res.status(403).json({ success: false, message: 'Bạn không có quyền xóa tài liệu này' });
}
await pool.request()
const deletedResult = await pool.request()
.input('documentId', sql.Int, documentId)
.query('DELETE FROM Documents WHERE DocumentId = @documentId');
.query(`DELETE FROM Documents OUTPUT DELETED.DocumentId
WHERE DocumentId = @documentId
AND NOT EXISTS (SELECT 1 FROM dbo.RobotDocuments WHERE DocumentId = @documentId)`);
if (!deletedResult.recordset.length) {
return res.status(409).json({ success: false, message: 'Tài liệu đang được gắn với robot. Vui lòng gỡ liên kết trong phần Quản lý robot trước khi xóa.' });
}
res.json({ success: true, message: 'Đã xóa tài liệu' });
} catch (err) {
if (err.number === 547) {
return res.status(409).json({ success: false, message: 'Tài liệu đang được gắn với robot. Vui lòng gỡ liên kết trong phần Quản lý robot trước khi xóa.' });
}
sendInternalError(res, err, 'Không thể xóa tài liệu');
}
});
@@ -9739,7 +9725,7 @@ app.use((err, req, res, next) => {
: err.message;
return res.status(400).json({ success: false, message });
}
if (err.message === 'Only .xls and .xlsx files are allowed' || err.message === 'Chỉ chấp nhận file PDF') {
if (err.message === 'Only .xls and .xlsx files are allowed' || err.code === 'DOCUMENT_VALIDATION') {
return res.status(400).json({ success: false, message: err.message });
}
res.status(500).json({ success: false, message: 'Internal server error' });

View File

@@ -1316,3 +1316,78 @@ BEGIN CATCH
END CATCH;
GO
-- Robot catalog and shared PDF document links. Keep in sync with backend/robot-schema.sql.
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
IF OBJECT_ID('dbo.RobotTypes', 'U') IS NULL
BEGIN
CREATE TABLE dbo.RobotTypes (
TypeId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
Name NVARCHAR(100) NOT NULL,
Description NVARCHAR(500) NULL,
CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
UpdatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
CONSTRAINT UQ_RobotTypes_Name UNIQUE (Name)
);
END;
IF OBJECT_ID('dbo.Robots', 'U') IS NULL
BEGIN
CREATE TABLE dbo.Robots (
RobotId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
Name NVARCHAR(255) NOT NULL,
Model NVARCHAR(255) NOT NULL,
Type NVARCHAR(100) NOT NULL,
AvatarData VARBINARY(MAX) NULL,
AvatarMimeType NVARCHAR(100) NULL,
CreatedBy INT NULL,
CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
UpdatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
CONSTRAINT FK_Robots_CreatedBy FOREIGN KEY (CreatedBy) REFERENCES dbo.Users(UserId) ON DELETE SET NULL
);
CREATE INDEX IX_Robots_Name ON dbo.Robots(Name);
END;
IF COL_LENGTH('dbo.Robots', 'TypeId') IS NULL
ALTER TABLE dbo.Robots ADD TypeId INT NULL;
-- A separate compilation scope is required when TypeId was just added.
-- Only unmigrated rows seed the catalog, so renamed types stay renamed.
EXEC(N'
INSERT INTO dbo.RobotTypes (Name)
SELECT DISTINCT COALESCE(NULLIF(LTRIM(RTRIM(r.Type)), N''''), N''Chưa phân loại'')
FROM dbo.Robots r
WHERE r.TypeId IS NULL AND NOT EXISTS (
SELECT 1 FROM dbo.RobotTypes t
WHERE t.Name = COALESCE(NULLIF(LTRIM(RTRIM(r.Type)), N''''), N''Chưa phân loại'')
);
UPDATE r SET TypeId = t.TypeId, Type = t.Name
FROM dbo.Robots r JOIN dbo.RobotTypes t
ON t.Name = COALESCE(NULLIF(LTRIM(RTRIM(r.Type)), N''''), N''Chưa phân loại'')
WHERE r.TypeId IS NULL;
');
IF EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID('dbo.Robots') AND name = 'TypeId' AND is_nullable = 1)
EXEC(N'ALTER TABLE dbo.Robots ALTER COLUMN TypeId INT NOT NULL;');
IF NOT EXISTS (SELECT 1 FROM sys.foreign_keys WHERE name = 'FK_Robots_Type')
EXEC(N'ALTER TABLE dbo.Robots ADD CONSTRAINT FK_Robots_Type FOREIGN KEY (TypeId) REFERENCES dbo.RobotTypes(TypeId);');
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.Robots') AND name = 'IX_Robots_TypeId')
EXEC(N'CREATE INDEX IX_Robots_TypeId ON dbo.Robots(TypeId);');
IF OBJECT_ID('dbo.RobotDocuments', 'U') IS NULL
BEGIN
CREATE TABLE dbo.RobotDocuments (
RobotId INT NOT NULL,
DocumentId INT NOT NULL,
CONSTRAINT PK_RobotDocuments PRIMARY KEY (RobotId, DocumentId),
CONSTRAINT FK_RobotDocuments_Robot FOREIGN KEY (RobotId) REFERENCES dbo.Robots(RobotId) ON DELETE CASCADE,
CONSTRAINT FK_RobotDocuments_Document FOREIGN KEY (DocumentId) REFERENCES dbo.Documents(DocumentId)
);
CREATE INDEX IX_RobotDocuments_DocumentId ON dbo.RobotDocuments(DocumentId);
END;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
THROW;
END CATCH;
GO

View File

@@ -10,7 +10,8 @@ Thay vì lưu rải rác tài khoản ứng dụng ở nhiều nơi, AccManager
- Quản lý danh sách ứng dụng đang sử dụng trong công ty.
- Gán tài khoản truy cập ứng dụng cho từng người dùng.
- Theo dõi thông tin tài khoản rõ ràng, tránh thất lạc.
- Lưu trữ, tìm kiếm, xem và tải xuống tài liệu PDF dùng chung.
- Lưu trữ, tìm kiếm, xem và tải xuống PDF, Word, Excel, PowerPoint, ảnh và tài liệu dùng chung.
- Quản lý robot với tên, model, loại, ảnh đại diện và tài liệu đi kèm.
## Ai sẽ sử dụng
@@ -23,8 +24,27 @@ Thay vì lưu rải rác tài khoản ứng dụng ở nhiều nơi, AccManager
2. Vào mục Người dùng để tạo mới hoặc cập nhật thông tin nhân sự.
3. Vào mục Ứng dụng để thêm các hệ thống cần quản lý.
4. Vào mục Tài khoản để gán tài khoản ứng dụng cho đúng người.
5. Vào mục Tài liệu PDF để tải lên hoặc xem tài liệu dùng chung.
5. Vào mục Tài liệu để tải lên, xem hoặc tải xuống tài liệu dùng chung.
6. Dùng nút Xem chi tiết trong danh sách người dùng để kiểm tra đầy đủ thông tin trước khi chỉnh sửa.
7. Vào mục Quản lý robot → Danh sách robot để thêm robot, chọn ảnh và gắn tài liệu.
## Kho tài liệu
- Hỗ trợ PDF; Word (`.doc`, `.docx`); Excel (`.xls`, `.xlsx`); PowerPoint (`.ppt`, `.pptx`); ảnh JPG/JPEG/PNG/GIF/WebP/BMP/TIFF; TXT/CSV/RTF và ZIP.
- PDF, ảnh thông dụng và TXT có nút xem trực tiếp. Word, Excel, PowerPoint, TIFF và các định dạng còn lại có nút tải xuống để mở trên máy.
- Mỗi loại file có biểu tượng và nhãn định dạng riêng. Hệ thống giữ nguyên nội dung và đuôi file khi tải xuống; giới hạn dung lượng mặc định 25 MB/file, cấu hình bằng `DOCUMENT_MAX_FILE_SIZE_MB`.
## Quản lý robot
- Admin và Asset được thêm, sửa, xóa robot. Người dùng đã đăng nhập được xem danh sách và chi tiết.
- Vào Quản lý robot → Thể loại robot để thêm, sửa hoặc xóa thể loại với tên và mô tả. Admin/Asset được quản lý danh mục; thể loại đang được sử dụng không thể xóa.
- Tên, model và thể loại robot là bắt buộc. Khi tạo hoặc sửa robot, chọn thể loại từ danh mục. Đổi tên thể loại sẽ cập nhật cho các robot liên quan.
- Ảnh đại diện là tùy chọn, hỗ trợ JPG/PNG/WebP, tối đa 5 MB.
- Khi thêm hoặc sửa robot, có thể tải tối đa 10 file mới mỗi lần và chọn nhiều file từ kho Tài liệu, hỗ trợ cùng các định dạng với kho. Mỗi robot được gắn tối đa 100 tài liệu; dung lượng mỗi file theo cấu hình `DOCUMENT_MAX_FILE_SIZE_MB` (mặc định 25 MB).
- File tải lên cùng robot cũng xuất hiện trong kho Tài liệu. Một tài liệu có thể gắn với nhiều robot.
- Bỏ chọn tài liệu trong form sửa robot để gỡ liên kết. Xóa robot vẫn giữ tài liệu trong kho; cần gỡ hết liên kết robot trước khi xóa file khỏi kho.
- Robot, thể loại, ảnh và tài liệu được lưu trong SQL Server, không cần thư mục upload riêng. Khi khởi động lại backend, hệ thống tự tạo bảng `Robots`, `RobotTypes` và `RobotDocuments` nếu chưa có; các loại robot đã nhập trước đây được tự động chuyển sang danh mục.
- Có thể tìm theo tên/model/loại, lọc theo loại và mở hoặc tải tài liệu trong màn hình Chi tiết robot.
## Quy trình vận hành gợi ý

File diff suppressed because one or more lines are too long

View File

@@ -18,6 +18,122 @@ textarea {
-webkit-tap-highlight-color: transparent;
}
/* Compact navigation: only one branch is open, with native button keyboard support. */
.sidebar-nav {
padding: 0 0.75rem;
overscroll-behavior: contain;
scrollbar-width: thin;
}
.sidebar-menu,
.sidebar-children {
display: flex;
flex-direction: column;
list-style: none;
margin: 0;
padding: 0;
gap: 0.2rem;
}
.sidebar-link {
display: flex;
align-items: center;
gap: 0.625rem;
width: 100%;
min-height: 2.25rem;
padding: 0.4375rem 0.625rem;
border-radius: 0.375rem;
color: #475569;
font-size: 0.9375rem;
line-height: 1.25rem;
text-align: left;
transition: color 0.15s, background-color 0.15s;
}
.sidebar-link:hover {
background: #e2e8f0;
color: #0f172a;
}
.sidebar-link:focus-visible {
outline: 2px solid #3755c3;
outline-offset: 2px;
}
.sidebar-link .material-symbols-outlined {
flex-shrink: 0;
font-size: 1.125rem;
}
.sidebar-text {
flex: 1;
min-width: 0;
white-space: nowrap;
}
.sidebar-link[aria-current="page"] {
background: #e2e8f0;
color: #0f172a;
font-weight: 700;
}
.sidebar-group-toggle[data-active="true"] {
color: #0f172a;
font-weight: 700;
}
.sidebar-link .sidebar-chevron {
margin-left: auto;
font-size: 1rem;
transition: transform 0.15s;
}
.sidebar-group-toggle[aria-expanded="true"] .sidebar-chevron {
transform: rotate(90deg);
}
.sidebar-children {
margin: 0.25rem 0 0.375rem 1.375rem;
padding-left: 0.375rem;
border-left: 1px dashed #cbd5e1;
gap: 0.125rem;
}
.sidebar-children[hidden] {
display: none;
}
.sidebar-children .sidebar-link {
min-height: 2.125rem;
padding-top: 0.4375rem;
padding-bottom: 0.4375rem;
}
.sidebar-admin {
margin-top: 0.5rem;
padding-top: 0.5rem;
border-top: 1px solid #e2e8f0;
}
.dark .sidebar-link {
color: #94a3b8;
}
.dark .sidebar-link:hover,
.dark .sidebar-link[aria-current="page"] {
background: #1e293b;
color: #f8fafc;
}
.dark .sidebar-group-toggle[data-active="true"] {
color: #f8fafc;
}
.dark .sidebar-children,
.dark .sidebar-admin {
border-color: #334155;
}
.table-wrap,
.overflow-x-auto {
overscroll-behavior-x: contain;

View File

@@ -2,6 +2,7 @@
// Main JavaScript functionality
const authenticatedFetch = window.fetch.bind(window);
const DOCUMENT_FORMATS = window.DocumentFormats || { formats: {}, accept: '', description: 'Tài liệu' };
let authRedirectInProgress = false;
window.fetch = async (input, init = {}) => {
const response = await authenticatedFetch(input, {
@@ -69,6 +70,15 @@ class AccountManager {
this.archivingAssets = false;
this.consumables = [];
this.documents = [];
this.robots = [];
this.robotTypes = [];
this.robotTypeSearchTerm = '';
this.robotTypesLoadError = '';
this.robotSearchTerm = '';
this.robotTypeFilter = '';
this.robotPage = 1;
this.robotPageSize = 12;
this.robotLoadError = '';
this.roles = [];
this.notificationPreviewItems = [];
this.notificationItems = [];
@@ -277,6 +287,8 @@ class AccountManager {
await this.fetchAssetDepartments();
await this.fetchAssetProjects();
await this.fetchDocuments();
await this.fetchRobotTypes();
await this.fetchRobots();
await this.fetchNotificationPreview();
if (this.canCurrentUserManageAssets()) {
@@ -363,6 +375,12 @@ class AccountManager {
this.setupAddButtonListeners();
this.setupFilters();
this.setupAccountPagerListeners();
} else if (page === 'robots') {
mainContent.innerHTML = this.getRobotsContent();
this.setupRobotListeners();
} else if (page === 'robot-types') {
mainContent.innerHTML = this.getRobotTypesContent();
this.setupRobotTypeListeners();
} else if (page === 'documents') {
mainContent.innerHTML = this.getDocumentsContent();
this.setupDocumentListeners();
@@ -397,15 +415,43 @@ class AccountManager {
}
setActiveNav(page) {
let activeGroup = null;
document.querySelectorAll('[data-nav]').forEach(link => {
const isActive = link.dataset.nav === page;
link.classList.toggle('border-l-4', isActive);
link.classList.toggle('border-blue-600', isActive);
link.classList.toggle('bg-slate-200/80', isActive);
link.classList.toggle('dark:bg-slate-800', isActive);
link.classList.toggle('text-slate-900', isActive);
link.classList.toggle('dark:text-slate-50', isActive);
link.classList.toggle('font-bold', isActive);
if (isActive) {
link.setAttribute('aria-current', 'page');
activeGroup = link.closest('[data-nav-group]')?.dataset.navGroup || null;
} else {
link.removeAttribute('aria-current');
}
});
document.querySelectorAll('[data-nav-toggle]').forEach(button => {
button.dataset.active = String(button.dataset.navToggle === activeGroup);
});
// Refreshing a view should preserve a group the user opened or collapsed.
if (this.activeSidebarPage !== page) {
this.setOpenSidebarGroup(activeGroup);
this.activeSidebarPage = page;
}
}
setOpenSidebarGroup(groupName = null) {
document.querySelectorAll('[data-nav-toggle]').forEach(button => {
const isOpen = button.dataset.navToggle === groupName;
const panel = document.getElementById(button.getAttribute('aria-controls'));
button.setAttribute('aria-expanded', String(isOpen));
if (panel) panel.hidden = !isOpen;
});
}
setupSidebarNavigation() {
document.querySelectorAll('[data-nav-toggle]').forEach(button => {
if (button.dataset.boundSidebarToggle) return;
button.addEventListener('click', () => {
const nextGroup = button.getAttribute('aria-expanded') === 'true' ? null : button.dataset.navToggle;
this.setOpenSidebarGroup(nextGroup);
});
button.dataset.boundSidebarToggle = 'true';
});
}
@@ -414,6 +460,7 @@ class AccountManager {
}
setupResponsiveShell() {
this.setupSidebarNavigation();
const menuBtn = document.getElementById('mobileMenuBtn');
const backdrop = document.getElementById('sidebarBackdrop');
@@ -3304,6 +3351,476 @@ class AccountManager {
`;
}
async fetchRobotTypes() {
try {
const response = await fetch(`${this.apiBase}/robots/types`, { cache: 'no-store' });
const data = await response.json();
if (!response.ok || !data.success) throw new Error(data.message || 'Không thể tải thể loại robot');
this.robotTypes = Array.isArray(data.data) ? data.data : [];
if (this.robotTypeFilter && !this.robotTypes.some(type => String(type.TypeId) === String(this.robotTypeFilter))) this.robotTypeFilter = '';
this.robotTypesLoadError = '';
} catch (error) { this.robotTypesLoadError = error.message || 'Không thể tải thể loại robot'; }
}
getRobotTypeResultsContent() {
const keyword = String(this.robotTypeSearchTerm || '').trim().toLocaleLowerCase('vi');
const types = this.robotTypes.filter(type => !keyword || [type.Name, type.Description]
.some(value => String(value || '').toLocaleLowerCase('vi').includes(keyword)));
if (this.robotTypesLoadError) return `<p role="alert" class="rounded-xl border border-red-200 bg-red-50 p-5 text-sm text-red-700">${this.escapeHtml(this.robotTypesLoadError)}. Bấm Làm mới để thử lại.</p>`;
if (!types.length) return `<div class="rounded-xl border border-slate-200 bg-white px-6 py-12 text-center">
<span class="material-symbols-outlined text-slate-400" style="font-size:2rem">category</span>
<h2 class="mt-3 font-bold text-slate-700">${keyword ? 'Không tìm thấy thể loại phù hợp' : 'Chưa có thể loại robot'}</h2>
<p class="mt-1 text-sm text-slate-500">${keyword ? 'Hãy thử từ khóa khác.' : 'Thêm thể loại trước, sau đó chọn thể loại khi tạo robot.'}</p></div>`;
const canManage = this.canCurrentUserManageAssets();
return `<div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">${types.map(type => {
const used = Number(type.RobotCount) > 0;
return `<article class="min-w-0 rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
<div class="flex items-start gap-3"><span class="material-symbols-outlined mt-1 text-slate-400">category</span>
<div class="min-w-0 flex-1"><h2 class="break-words font-extrabold text-slate-900">${this.escapeHtml(type.Name)}</h2>
<p class="mt-2 whitespace-pre-line break-words text-sm text-slate-500">${this.escapeHtml(type.Description || 'Chưa có mô tả.')}</p></div></div>
<div class="mt-4 flex items-center gap-2 border-t border-slate-100 pt-3">
<span class="mr-auto text-xs text-slate-500">${Number(type.RobotCount) || 0} robot</span>
${canManage ? `<button type="button" data-robot-type-action="edit" data-type-id="${Number(type.TypeId)}" class="rounded-lg border border-slate-200 px-3 py-2 text-xs font-bold text-primary">Sửa</button>
<button type="button" data-robot-type-action="delete" data-type-id="${Number(type.TypeId)}" ${used ? 'disabled' : ''} title="${used ? 'Chuyển robot sang thể loại khác trước khi xóa' : 'Xóa thể loại'}" class="rounded-lg px-3 py-2 text-xs font-bold text-red-600 disabled:cursor-not-allowed disabled:opacity-40">Xóa</button>` : ''}
</div></article>`;
}).join('')}</div>`;
}
getRobotTypesContent() {
return `<div class="robot-types-page h-full w-full overflow-y-auto p-4 md:p-6">
<div class="page-header mb-5 flex items-center justify-between gap-4">
<div><h1 class="text-2xl font-extrabold text-on-surface">Thể loại robot</h1>
<p class="mt-1 text-sm text-slate-500">Quản lý danh mục thể loại để chọn khi thêm hoặc sửa robot.</p></div>
<div class="flex flex-wrap gap-2">
<button id="refreshRobotTypesBtn" type="button" class="inline-flex items-center justify-center gap-2 rounded-lg border border-slate-300 px-3 py-2 text-xs font-bold text-slate-700"><span class="material-symbols-outlined text-base">refresh</span>Làm mới</button>
${this.canCurrentUserManageAssets() ? '<button id="addRobotTypeBtn" type="button" class="inline-flex items-center justify-center gap-2 rounded-lg bg-primary px-4 py-2 text-xs font-bold text-white"><span class="material-symbols-outlined text-base">add</span>Thêm thể loại</button>' : ''}
</div></div>
<label class="mb-4 block"><span class="sr-only">Tìm thể loại robot</span><input id="robotTypeSearch" type="search" value="${this.escapeHtml(this.robotTypeSearchTerm || '')}" placeholder="Tìm theo tên hoặc mô tả thể loại..." class="w-full rounded-lg border-slate-200 py-2 text-sm focus:ring-primary"></label>
<div id="robotTypeResults">${this.getRobotTypeResultsContent()}</div>
</div>`;
}
setupRobotTypeListeners() {
const results = document.getElementById('robotTypeResults');
document.getElementById('robotTypeSearch')?.addEventListener('input', event => {
this.robotTypeSearchTerm = event.target.value;
results.innerHTML = this.getRobotTypeResultsContent();
});
document.getElementById('addRobotTypeBtn')?.addEventListener('click', () => this.openRobotTypeForm());
document.getElementById('refreshRobotTypesBtn')?.addEventListener('click', async event => {
event.currentTarget.disabled = true;
await this.fetchRobotTypes();
if (this.currentPage === 'robot-types') this.renderView('robot-types');
});
results?.addEventListener('click', async event => {
const button = event.target.closest('[data-robot-type-action]');
if (!button || button.disabled) return;
const type = this.robotTypes.find(item => Number(item.TypeId) === Number(button.dataset.typeId));
if (!type) return;
if (button.dataset.robotTypeAction === 'edit') this.openRobotTypeForm(type);
else {
button.disabled = true;
try { await this.deleteRobotType(type); } finally { button.disabled = false; }
}
});
}
openRobotTypeForm(type = null) {
if (!this.canCurrentUserManageAssets()) return;
const dialog = this.showRobotDialog(`<form id="robotTypeForm">
<div class="flex items-center justify-between gap-4 border-b border-slate-200 px-5 py-4">
<h2 id="robotDialogTitle" class="text-lg font-extrabold">${type ? 'Sửa thể loại robot' : 'Thêm thể loại robot'}</h2>
<button type="button" data-close-robot class="p-1 text-slate-500" aria-label="Đóng"><span class="material-symbols-outlined">close</span></button></div>
<div class="space-y-4 p-5">
<label class="block text-sm font-bold">Tên thể loại <span class="text-red-600">*</span>
<input name="name" required maxlength="100" value="${this.escapeHtml(type?.Name || '')}" placeholder="VD: Robot cộng tác, Robot công nghiệp, AMR..." class="mt-1 w-full rounded-lg border-slate-200 py-2 text-sm focus:ring-primary"></label>
<label class="block text-sm font-bold">Mô tả
<textarea name="description" maxlength="500" rows="3" class="mt-1 w-full rounded-lg border-slate-200 text-sm focus:ring-primary">${this.escapeHtml(type?.Description || '')}</textarea></label>
${Number(type?.RobotCount) > 0 ? `<p class="text-xs text-slate-500">Đổi tên sẽ cập nhật thể loại hiển thị cho ${Number(type.RobotCount)} robot đang sử dụng.</p>` : ''}
</div><div class="flex justify-end gap-2 border-t border-slate-200 bg-slate-50 px-5 py-4">
<button type="button" data-close-robot class="rounded-lg border border-slate-300 px-4 py-2 text-sm font-bold">Hủy</button>
<button type="submit" class="rounded-lg bg-primary px-5 py-2 text-sm font-bold text-white disabled:opacity-50">Lưu thể loại</button></div></form>`);
dialog.querySelector('#robotTypeForm').addEventListener('submit', async event => {
event.preventDefault();
if (dialog.dataset.saving === 'true') return;
const form = event.currentTarget;
const name = form.elements.namedItem('name').value.trim();
if (!name) { this.notifyWarning('Vui lòng nhập tên thể loại.'); return; }
const description = form.elements.namedItem('description').value.trim();
dialog.dataset.saving = 'true';
const controls = [...form.querySelectorAll('input, textarea, button')];
controls.forEach(control => { control.disabled = true; });
const submit = form.querySelector('[type="submit"]'); submit.textContent = 'Đang lưu...';
try {
const response = await fetch(`${this.apiBase}/robots/types${type ? `/${Number(type.TypeId)}` : ''}`, {
method: type ? 'PUT' : 'POST', headers: this.getAuthHeaders(true), body: JSON.stringify({ name, description })
});
const data = await response.json();
if (!response.ok || !data.success) throw new Error(data.message || 'Không thể lưu thể loại robot');
dialog.close();
await Promise.all([this.fetchRobotTypes(), this.fetchRobots()]);
if (['robots', 'robot-types'].includes(this.currentPage)) this.renderView(this.currentPage);
this.notifySuccess(data.message || 'Đã lưu thể loại robot');
} catch (error) { this.notifyFailure(error.message); }
finally { delete dialog.dataset.saving; controls.forEach(control => { control.disabled = false; }); submit.textContent = 'Lưu thể loại'; }
});
}
async deleteRobotType(type) {
if (!this.canCurrentUserManageAssets() || Number(type.RobotCount) > 0) return;
if (!window.confirm(`Xóa thể loại “${type.Name}”?`)) return;
try {
const response = await fetch(`${this.apiBase}/robots/types/${Number(type.TypeId)}`, { method: 'DELETE' });
const data = await response.json();
if (!response.ok || !data.success) throw new Error(data.message || 'Không thể xóa thể loại');
await this.fetchRobotTypes();
if (this.currentPage === 'robot-types') this.renderView('robot-types');
this.notifySuccess(data.message || 'Đã xóa thể loại robot');
} catch (error) { this.notifyFailure(error.message); }
}
async fetchRobots() {
try {
const response = await fetch(`${this.apiBase}/robots`, { cache: 'no-store' });
const data = await response.json();
if (!response.ok || !data.success) throw new Error(data.message || 'Không thể tải danh sách robot');
this.robots = Array.isArray(data.data) ? data.data : [];
this.documentMaxFileSizeMb = Number(data.maxFileSizeMb) || 25;
this.robotLoadError = '';
} catch (error) {
this.robotLoadError = error.message || 'Không thể tải danh sách robot';
}
}
getRobotAvatarHtml(robot, large = false) {
const size = large ? 'h-32 w-32' : 'h-20 w-20';
return `<div class="${size} shrink-0 overflow-hidden rounded-xl bg-slate-100 flex items-center justify-center">
${robot?.HasAvatar ? `<img src="${this.apiBase}/robots/${Number(robot.RobotId)}/avatar?v=${encodeURIComponent(robot.UpdatedDate || '')}"
alt="Ảnh ${this.escapeHtml(robot.Name)}" class="h-full w-full object-contain" loading="lazy">`
: '<span class="material-symbols-outlined text-slate-400" style="font-size:2rem" aria-hidden="true">smart_toy</span>'}
</div>`;
}
getFilteredRobots() {
const keyword = String(this.robotSearchTerm || '').trim().toLocaleLowerCase('vi');
return this.robots.filter(robot => (!this.robotTypeFilter || String(robot.TypeId) === String(this.robotTypeFilter))
&& (!keyword || [robot.Name, robot.Model, robot.Type]
.some(value => String(value || '').toLocaleLowerCase('vi').includes(keyword))));
}
getRobotResultsContent() {
const page = this.getPaged(this.getFilteredRobots(), this.robotPage, this.robotPageSize);
this.robotPage = page.current;
const canManage = this.canCurrentUserManageAssets();
if (this.robotLoadError) return `<div role="alert" class="rounded-xl border border-red-200 bg-red-50 p-6 text-sm text-red-700">${this.escapeHtml(this.robotLoadError)}. Bấm Làm mới để thử lại.</div>`;
if (!page.total) return `<div class="rounded-xl border border-slate-200 bg-white px-6 py-16 text-center">
<span class="material-symbols-outlined text-4xl text-slate-400">smart_toy</span>
<h2 class="mt-3 font-bold text-slate-700">${this.robots.length ? 'Không tìm thấy robot phù hợp' : 'Chưa có robot'}</h2>
<p class="mt-1 text-sm text-slate-500">${this.robots.length ? 'Hãy thử từ khóa hoặc loại robot khác.' : 'Thông tin, ảnh đại diện và tài liệu của robot sẽ được lưu tại đây.'}</p>
</div>`;
return `<div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
${page.data.map(robot => `<article class="min-w-0 rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
<div class="flex items-start gap-4">
${this.getRobotAvatarHtml(robot)}
<div class="min-w-0 flex-1">
<h2 class="break-words font-extrabold text-slate-900">${this.escapeHtml(robot.Name)}</h2>
<p class="mt-1 break-words text-sm text-slate-600"><span class="text-slate-400">Model:</span> ${this.escapeHtml(robot.Model)}</p>
<span class="mt-2 inline-block max-w-full break-words rounded-md bg-primary/10 px-2 py-1 text-xs font-semibold text-primary">${this.escapeHtml(robot.Type)}</span>
</div>
</div>
<div class="mt-4 flex items-center gap-2 border-t border-slate-100 pt-3">
<span class="mr-auto inline-flex items-center gap-1 text-xs text-slate-500"><span class="material-symbols-outlined text-base">attach_file</span>${Number(robot.DocumentCount) || 0} tài liệu</span>
<button type="button" data-robot-action="view" data-robot-id="${Number(robot.RobotId)}" class="rounded-lg border border-slate-200 px-3 py-2 text-xs font-bold text-primary hover:bg-slate-50">Chi tiết</button>
${canManage ? `<button type="button" data-robot-action="edit" data-robot-id="${Number(robot.RobotId)}" class="rounded-lg p-2 text-slate-500 hover:bg-slate-100 hover:text-primary" aria-label="Sửa ${this.escapeHtml(robot.Name)}"><span class="material-symbols-outlined text-lg">edit</span></button>
<button type="button" data-robot-action="delete" data-robot-id="${Number(robot.RobotId)}" class="rounded-lg p-2 text-red-600 hover:bg-red-50" aria-label="Xóa ${this.escapeHtml(robot.Name)}"><span class="material-symbols-outlined text-lg">delete</span></button>` : ''}
</div>
</article>`).join('')}
</div>
<div class="page-pager mt-4 flex items-center justify-between gap-3 text-xs text-slate-500">
<span>Hiển thị ${page.start}–${page.end} / ${page.total} robot</span>
<div class="flex items-center gap-2">
<button type="button" data-robot-page="${page.current - 1}" ${page.current === 1 ? 'disabled' : ''} class="rounded border border-slate-200 px-3 py-2 disabled:opacity-40">Trước</button>
<span>Trang ${page.current} / ${page.totalPages}</span>
<button type="button" data-robot-page="${page.current + 1}" ${page.current === page.totalPages ? 'disabled' : ''} class="rounded border border-slate-200 px-3 py-2 disabled:opacity-40">Sau</button>
</div>
</div>`;
}
getRobotsContent() {
const types = this.robotTypes || [];
return `<div class="robots-page h-full w-full overflow-y-auto p-4 md:p-6">
<div class="page-header mb-5 flex items-center justify-between gap-4">
<div><h1 class="text-2xl font-extrabold text-on-surface">Quản lý robot</h1>
<p class="mt-1 text-sm text-slate-500">Thông tin robot, ảnh đại diện và tài liệu đi kèm.</p></div>
<div class="flex flex-wrap gap-2">
<button id="refreshRobotsBtn" type="button" class="inline-flex items-center justify-center gap-2 rounded-lg border border-slate-300 px-3 py-2 text-xs font-bold text-slate-700 hover:bg-slate-100"><span class="material-symbols-outlined text-base">refresh</span>Làm mới</button>
${this.canCurrentUserManageAssets() ? '<button id="addRobotBtn" type="button" class="inline-flex items-center justify-center gap-2 rounded-lg bg-primary px-4 py-2 text-xs font-bold text-white hover:bg-primary-dim"><span class="material-symbols-outlined text-base">add</span>Thêm robot</button>' : ''}
</div>
</div>
<div class="page-filters mb-4 flex items-center gap-3">
<label class="relative flex-1"><span class="sr-only">Tìm robot</span><span class="material-symbols-outlined absolute left-3 top-1/2 -translate-y-1/2 text-slate-400">search</span>
<input id="robotSearch" type="search" value="${this.escapeHtml(this.robotSearchTerm)}" placeholder="Tìm theo tên, model hoặc thể loại robot..." class="w-full rounded-lg border-slate-200 py-2 pl-10 pr-3 text-sm focus:ring-primary"></label>
<label class="flex items-center gap-2 text-xs text-slate-500">Thể loại
<select id="robotTypeFilter" class="rounded-lg border-slate-200 py-2 text-sm focus:ring-primary"><option value="">Tất cả thể loại</option>
${types.map(type => `<option value="${Number(type.TypeId)}" ${String(this.robotTypeFilter) === String(type.TypeId) ? 'selected' : ''}>${this.escapeHtml(type.Name)}</option>`).join('')}</select></label>
</div>
<div id="robotResults">${this.getRobotResultsContent()}</div>
</div>`;
}
setupRobotListeners() {
const results = document.getElementById('robotResults');
const refreshResults = () => { if (results) results.innerHTML = this.getRobotResultsContent(); };
document.getElementById('robotSearch')?.addEventListener('input', event => {
this.robotSearchTerm = event.target.value; this.robotPage = 1; refreshResults();
});
document.getElementById('robotTypeFilter')?.addEventListener('change', event => {
this.robotTypeFilter = event.target.value; this.robotPage = 1; refreshResults();
});
document.getElementById('addRobotBtn')?.addEventListener('click', () => this.openRobotForm());
document.getElementById('refreshRobotsBtn')?.addEventListener('click', async event => {
const button = event.currentTarget; button.disabled = true;
await Promise.all([this.fetchRobots(), this.fetchRobotTypes()]);
if (this.currentPage === 'robots') this.renderView('robots');
});
results?.addEventListener('click', async event => {
const pager = event.target.closest('[data-robot-page]');
if (pager && !pager.disabled) { this.robotPage = Number(pager.dataset.robotPage); refreshResults(); return; }
const button = event.target.closest('[data-robot-action]');
if (!button || button.disabled) return;
button.disabled = true;
try {
const id = Number(button.dataset.robotId);
if (button.dataset.robotAction === 'view') await this.openRobotDetails(id);
if (button.dataset.robotAction === 'edit') await this.openRobotForm(id);
if (button.dataset.robotAction === 'delete') await this.deleteRobot(id);
} finally { button.disabled = false; }
});
}
async getRobotDetails(robotId) {
const response = await fetch(`${this.apiBase}/robots/${Number(robotId)}`, { cache: 'no-store' });
const data = await response.json();
if (!response.ok || !data.success) throw new Error(data.message || 'Không thể tải thông tin robot');
return data.data;
}
showRobotDialog(content) {
document.getElementById('robotDialog')?.close();
const dialog = document.createElement('dialog');
dialog.id = 'robotDialog';
dialog.setAttribute('aria-labelledby', 'robotDialogTitle');
dialog.className = 'm-auto w-[min(94vw,48rem)] max-w-none max-h-[90dvh] overflow-y-auto rounded-xl border-0 bg-white p-0 text-slate-800 shadow-2xl backdrop:bg-slate-950/50';
dialog.innerHTML = content;
document.body.appendChild(dialog);
dialog.addEventListener('click', event => {
if (dialog.dataset.saving === 'true') return;
if (event.target.closest('[data-close-robot]')) dialog.close();
if (event.target === dialog) {
const rect = dialog.getBoundingClientRect();
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) dialog.close();
}
});
dialog.addEventListener('cancel', event => { if (dialog.dataset.saving === 'true') event.preventDefault(); });
dialog.addEventListener('close', () => {
if (dialog.robotPreviewUrl) URL.revokeObjectURL(dialog.robotPreviewUrl);
dialog.remove();
}, { once: true });
dialog.showModal();
return dialog;
}
async openRobotDetails(robotId) {
try {
const robot = await this.getRobotDetails(robotId);
const dialog = this.showRobotDialog(`<div class="flex items-start justify-between gap-4 border-b border-slate-200 px-5 py-4">
<h2 id="robotDialogTitle" class="break-words text-lg font-extrabold">${this.escapeHtml(robot.Name)}</h2>
<button type="button" data-close-robot class="p-1 text-slate-500" aria-label="Đóng"><span class="material-symbols-outlined">close</span></button>
</div>
<div class="space-y-5 p-5">
<div class="flex flex-wrap items-center gap-5">${this.getRobotAvatarHtml(robot, true)}
<dl class="min-w-0 flex-1 space-y-2 text-sm"><div><dt class="text-xs text-slate-400">Model</dt><dd class="break-words font-semibold">${this.escapeHtml(robot.Model)}</dd></div>
<div><dt class="text-xs text-slate-400">Thể loại robot</dt><dd class="break-words font-semibold">${this.escapeHtml(robot.Type)}</dd></div></dl></div>
<section><h3 class="mb-3 font-bold">Tài liệu đi kèm (${robot.Documents.length})</h3>
<div class="space-y-2">${robot.Documents.length ? robot.Documents.map(doc => `<div class="flex flex-wrap items-center gap-3 rounded-lg border border-slate-200 p-3">
<span class="material-symbols-outlined ${this.getDocumentPresentation(doc).iconClass}">${this.getDocumentPresentation(doc).icon}</span>
<div class="min-w-0 flex-1"><p class="break-words text-sm font-semibold">${this.escapeHtml(doc.Title)}</p><p class="break-words text-xs text-slate-500">${this.escapeHtml(doc.OriginalFileName)} · ${this.formatFileSize(doc.FileSize)}</p></div>
${this.getDocumentPresentation(doc).preview ? `<a href="${this.apiBase}/documents/${Number(doc.DocumentId)}/file" target="_blank" rel="noopener noreferrer" class="rounded border border-slate-200 px-3 py-2 text-xs font-bold text-primary">Xem ${this.getDocumentPresentation(doc).label}</a>` : ''}
<a href="${this.apiBase}/documents/${Number(doc.DocumentId)}/file?download=1" class="rounded border border-slate-200 px-3 py-2 text-xs font-bold text-slate-600">Tải xuống</a>
</div>`).join('') : '<p class="text-sm text-slate-500">Robot chưa có tài liệu đi kèm.</p>'}</div>
</section>
</div>
<div class="flex justify-end gap-2 border-t border-slate-200 bg-slate-50 px-5 py-4">
<button type="button" data-close-robot class="rounded-lg border border-slate-300 px-4 py-2 text-sm font-bold">Đóng</button>
${this.canCurrentUserManageAssets() ? '<button id="editRobotDetailsBtn" type="button" class="rounded-lg bg-primary px-4 py-2 text-sm font-bold text-white">Sửa robot</button>' : ''}
</div>`);
dialog.querySelector('#editRobotDetailsBtn')?.addEventListener('click', async event => {
const button = event.currentTarget; button.disabled = true;
try { await this.openRobotForm(robotId); } finally { button.disabled = false; }
});
} catch (error) { this.notifyFailure(error.message); }
}
async openRobotForm(robotId = null) {
if (!this.canCurrentUserManageAssets()) { this.notifyWarning('Chỉ Admin/Asset được thay đổi thông tin robot.'); return; }
try {
const [robot, libraryResponse, typesResponse] = await Promise.all([
robotId ? this.getRobotDetails(robotId) : Promise.resolve(null),
fetch(`${this.apiBase}/documents`, { cache: 'no-store' }),
fetch(`${this.apiBase}/robots/types`, { cache: 'no-store' })
]);
const library = await libraryResponse.json();
if (!libraryResponse.ok || !library.success) throw new Error(library.message || 'Không thể tải kho tài liệu');
const types = await typesResponse.json();
if (!typesResponse.ok || !types.success) throw new Error(types.message || 'Không thể tải thể loại robot');
this.robotTypes = types.data || [];
this.documents = library.data || [];
this.documentMaxFileSizeMb = Number(library.maxFileSizeMb) || 25;
const selectedIds = new Set((robot?.Documents || []).map(doc => Number(doc.DocumentId)));
const fieldClass = 'w-full rounded-lg border-slate-200 py-2 text-sm focus:ring-primary';
const dialog = this.showRobotDialog(`<form id="robotForm">
<div class="flex items-center justify-between gap-4 border-b border-slate-200 px-5 py-4">
<h2 id="robotDialogTitle" class="text-lg font-extrabold">${robot ? 'Sửa robot' : 'Thêm robot mới'}</h2>
<button type="button" data-close-robot class="p-1 text-slate-500" aria-label="Đóng"><span class="material-symbols-outlined">close</span></button>
</div>
<div class="space-y-5 p-5">
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<label class="block text-sm font-bold sm:col-span-2">Tên robot <span class="text-red-600">*</span><input name="name" required maxlength="255" value="${this.escapeHtml(robot?.Name || '')}" class="${fieldClass} mt-1" placeholder="Nhập tên robot"></label>
<label class="block text-sm font-bold">Model <span class="text-red-600">*</span><input name="model" required maxlength="255" value="${this.escapeHtml(robot?.Model || '')}" class="${fieldClass} mt-1" placeholder="VD: UR10e"></label>
<div><label class="block text-sm font-bold">Thể loại robot <span class="text-red-600">*</span>
<select name="typeId" required class="${fieldClass} mt-1"><option value="">-- Chọn thể loại robot --</option>
${this.robotTypes.map(type => `<option value="${Number(type.TypeId)}" ${Number(robot?.TypeId) === Number(type.TypeId) ? 'selected' : ''}>${this.escapeHtml(type.Name)}</option>`).join('')}</select></label>
<a href="#robot-types" id="robotManageTypesLink" class="mt-2 inline-block text-xs font-semibold text-primary">${this.robotTypes.length ? 'Quản lý thể loại robot' : 'Chưa có thể loại. Bấm để thêm thể loại trước.'}</a></div>
</div>
<section><h3 class="mb-2 text-sm font-bold">Ảnh đại diện</h3>
<div class="flex flex-wrap items-center gap-4"><div id="robotAvatarPreview">${this.getRobotAvatarHtml(robot)}</div>
<div class="min-w-0 flex-1"><label for="robotAvatarFile" class="sr-only">Chọn ảnh đại diện</label><input id="robotAvatarFile" type="file" name="avatar" accept="image/jpeg,image/png,image/webp,.jpg,.jpeg,.png,.webp" class="block w-full text-sm">
<p class="mt-2 text-xs text-slate-500">JPG, PNG hoặc WebP, tối đa 5 MB. Có thể bổ sung ảnh sau.</p>
${robot?.HasAvatar ? '<label class="mt-2 inline-flex items-center gap-2 text-xs text-slate-600"><input id="robotRemoveAvatar" type="checkbox" class="rounded border-slate-300">Xóa ảnh hiện tại</label>' : ''}</div>
</div>
</section>
<section><h3 class="text-sm font-bold">Tài liệu đi kèm</h3><p class="mt-1 text-xs text-slate-500">Tải tài liệu mới lên hoặc chọn file đã có trong kho. Có thể dùng cả hai cách.</p>
<label for="robotDocumentFiles" class="mb-2 mt-3 block text-xs font-bold text-slate-600">Tải tài liệu mới</label>
<input id="robotDocumentFiles" type="file" name="documents" multiple accept="${DOCUMENT_FORMATS.accept}" class="block w-full text-sm">
<p class="mt-2 text-xs text-slate-500">${DOCUMENT_FORMATS.description}. Tối đa 10 file mỗi lần, ${this.documentMaxFileSizeMb} MB/file. File mới cũng được lưu trong mục Tài liệu.</p>
<label for="robotDocumentSearch" class="mb-2 mt-4 block text-xs font-bold text-slate-600">Chọn từ kho tài liệu</label>
<input id="robotDocumentSearch" type="search" class="${fieldClass}" placeholder="Tìm tên tài liệu hoặc tên file...">
<div id="robotLibraryList" class="mt-2 max-h-48 overflow-y-auto rounded-lg border border-slate-200">
${this.documents.length ? this.documents.map(doc => `<label data-robot-library-item data-search="${this.escapeHtml(`${doc.Title} ${doc.OriginalFileName}`.toLocaleLowerCase('vi'))}" class="flex items-start gap-3 border-b border-slate-100 p-3 text-sm last:border-b-0">
<input type="checkbox" name="documentId" value="${Number(doc.DocumentId)}" ${selectedIds.has(Number(doc.DocumentId)) ? 'checked' : ''} class="mt-0.5 rounded border-slate-300">
<span class="min-w-0"><span class="block break-words font-semibold">${this.escapeHtml(doc.Title)}</span><span class="block break-words text-xs text-slate-500">${this.escapeHtml(doc.OriginalFileName)}</span></span>
</label>`).join('') : '<p class="p-3 text-sm text-slate-500">Kho chưa có tài liệu. Bạn có thể tải file mới lên ở trên.</p>'}
</div><p id="robotDocumentSelection" aria-live="polite" class="mt-2 text-xs text-slate-500"></p>
<p class="mt-1 text-xs text-slate-400">Bỏ chọn để gỡ tài liệu khỏi robot. File vẫn được giữ trong kho.</p>
</section>
</div>
<div class="flex justify-end gap-2 border-t border-slate-200 bg-slate-50 px-5 py-4">
<button type="button" data-close-robot class="rounded-lg border border-slate-300 px-4 py-2 text-sm font-bold">Hủy</button>
<button id="robotSaveBtn" type="submit" ${this.robotTypes.length ? '' : 'disabled'} class="rounded-lg bg-primary px-5 py-2 text-sm font-bold text-white disabled:opacity-50">Lưu robot</button>
</div>
</form>`);
const form = dialog.querySelector('#robotForm');
form.querySelector('#robotManageTypesLink').addEventListener('click', event => {
if (dialog.dataset.saving === 'true') { event.preventDefault(); return; }
dialog.close();
});
const avatarInput = form.querySelector('#robotAvatarFile');
const removeAvatar = form.querySelector('#robotRemoveAvatar');
const updatePreview = () => {
if (dialog.robotPreviewUrl) { URL.revokeObjectURL(dialog.robotPreviewUrl); dialog.robotPreviewUrl = null; }
const file = avatarInput.files[0];
if (file && (!['image/jpeg', 'image/png', 'image/webp'].includes(file.type) || file.size > 5 * 1024 * 1024)) {
this.notifyWarning('Chọn ảnh JPG, PNG hoặc WebP, tối đa 5 MB.'); avatarInput.value = '';
}
if (avatarInput.files[0]) {
dialog.robotPreviewUrl = URL.createObjectURL(avatarInput.files[0]);
form.querySelector('#robotAvatarPreview').innerHTML = `<img src="${dialog.robotPreviewUrl}" alt="Xem trước ảnh robot" class="h-20 w-20 rounded-xl bg-slate-100 object-contain">`;
} else form.querySelector('#robotAvatarPreview').innerHTML = this.getRobotAvatarHtml(removeAvatar?.checked ? null : robot);
};
avatarInput.addEventListener('change', () => { if (removeAvatar) removeAvatar.checked = false; updatePreview(); });
removeAvatar?.addEventListener('change', () => { avatarInput.value = ''; updatePreview(); });
form.querySelector('#robotDocumentSearch').addEventListener('input', event => {
const keyword = event.target.value.trim().toLocaleLowerCase('vi');
form.querySelectorAll('[data-robot-library-item]').forEach(item => { item.classList.toggle('hidden', !item.dataset.search.includes(keyword)); });
});
const updateSelection = () => {
form.querySelector('#robotDocumentSelection').textContent = `Đã chọn ${form.querySelectorAll('[name="documentId"]:checked').length} tài liệu từ kho và ${form.querySelector('#robotDocumentFiles').files.length} file mới.`;
};
form.addEventListener('change', updateSelection); updateSelection();
form.addEventListener('submit', event => this.saveRobotForm(event, robotId, dialog));
} catch (error) { this.notifyFailure(error.message || 'Không thể mở form robot'); }
}
async saveRobotForm(event, robotId, dialog) {
event.preventDefault();
if (dialog.dataset.saving === 'true' || !this.canCurrentUserManageAssets()) return;
const form = event.currentTarget;
const documentFiles = [...form.querySelector('#robotDocumentFiles').files];
const documentIds = [...form.querySelectorAll('[name="documentId"]:checked')].map(input => Number(input.value));
if (documentFiles.length > 10 || documentIds.length + documentFiles.length > 100) { this.notifyWarning('Tối đa 10 file mới mỗi lần và 100 tài liệu cho một robot.'); return; }
if (documentFiles.some(file => !this.isSupportedDocumentName(file.name) || file.size > this.documentMaxFileSizeMb * 1024 * 1024)) {
this.notifyWarning(`Chọn định dạng tài liệu được hỗ trợ, tối đa ${this.documentMaxFileSizeMb} MB mỗi file.`); return;
}
const payload = new FormData();
for (const key of ['name', 'model', 'typeId']) {
const value = form.elements.namedItem(key).value.trim();
if (!value) { this.notifyWarning('Vui lòng nhập tên, model và chọn thể loại robot.'); return; }
payload.append(key, value);
}
payload.append('documentIds', JSON.stringify(documentIds));
payload.append('removeAvatar', String(Boolean(form.querySelector('#robotRemoveAvatar')?.checked)));
const avatar = form.querySelector('#robotAvatarFile').files[0];
if (avatar) payload.append('avatar', avatar);
documentFiles.forEach(file => payload.append('documents', file));
dialog.dataset.saving = 'true';
const controls = [...form.querySelectorAll('input, select, button')];
controls.forEach(control => { control.disabled = true; });
const saveButton = form.querySelector('#robotSaveBtn'); saveButton.textContent = 'Đang lưu...';
try {
const response = await fetch(`${this.apiBase}/robots${robotId ? `/${Number(robotId)}` : ''}`, { method: robotId ? 'PUT' : 'POST', body: payload });
const data = await response.json();
if (!response.ok || !data.success) throw new Error(data.message || 'Không thể lưu robot');
dialog.close();
await Promise.all([this.fetchRobots(), this.fetchDocuments(), this.fetchRobotTypes()]);
if (this.currentPage === 'robots') this.renderView('robots');
this.notifySuccess(data.message || 'Đã lưu robot');
} catch (error) { this.notifyFailure(error.message || 'Không thể lưu robot'); }
finally { delete dialog.dataset.saving; controls.forEach(control => { control.disabled = false; }); saveButton.textContent = 'Lưu robot'; }
}
async deleteRobot(robotId) {
if (!this.canCurrentUserManageAssets()) return;
const robot = this.robots.find(item => Number(item.RobotId) === Number(robotId));
if (!robot || !window.confirm(`Xóa robot “${robot.Name}”? Các tài liệu vẫn được giữ trong kho.`)) return;
try {
const response = await fetch(`${this.apiBase}/robots/${Number(robotId)}`, { method: 'DELETE' });
const data = await response.json();
if (!response.ok || !data.success) throw new Error(data.message || 'Không thể xóa robot');
await Promise.all([this.fetchRobots(), this.fetchRobotTypes()]);
if (this.currentPage === 'robots') this.renderView('robots');
this.notifySuccess(data.message || 'Đã xóa robot');
} catch (error) { this.notifyFailure(error.message); }
}
isSupportedDocumentName(fileName) {
const extension = String(fileName || '').match(/\.[^.]+$/)?.[0].toLowerCase();
return Boolean(DOCUMENT_FORMATS.formats[extension]);
}
getDocumentPresentation(document) {
const extension = String(document?.OriginalFileName || '').match(/\.[^.]+$/)?.[0].toLowerCase() || '';
const format = DOCUMENT_FORMATS.formats[extension] || { label: 'File', icon: 'draft', tone: 'slate', preview: false };
const colors = {
red: { badgeClass: 'bg-red-100 text-red-600', iconClass: 'text-red-600' },
blue: { badgeClass: 'bg-blue-100 text-blue-700', iconClass: 'text-blue-700' },
green: { badgeClass: 'bg-emerald-100 text-emerald-700', iconClass: 'text-emerald-700' },
orange: { badgeClass: 'bg-orange-100 text-orange-700', iconClass: 'text-orange-700' },
purple: { badgeClass: 'bg-purple-100 text-purple-700', iconClass: 'text-purple-700' },
slate: { badgeClass: 'bg-slate-100 text-slate-600', iconClass: 'text-slate-600' }
};
return { ...format, ...colors[format.tone], extension: extension.slice(1).toUpperCase() };
}
formatFileSize(value) {
const bytes = Number(value) || 0;
if (bytes < 1024) return `${bytes} B`;
@@ -3329,10 +3846,10 @@ class AccountManager {
<div class="page-header flex items-end justify-between gap-4 mb-5">
<div>
<div class="flex items-center gap-2 text-red-600 mb-1">
<span class="material-symbols-outlined">picture_as_pdf</span>
<span class="material-symbols-outlined">folder_open</span>
<span class="text-xs font-extrabold uppercase tracking-widest">Kho tài liệu</span>
</div>
<h1 class="text-2xl font-extrabold text-slate-900 dark:text-slate-50">Tài liệu PDF</h1>
<h1 class="text-2xl font-extrabold text-slate-900 dark:text-slate-50">Tài liệu</h1>
<p class="text-sm text-slate-500 mt-1">Lưu trữ, xem và tải xuống tài liệu dùng chung.</p>
</div>
<div class="document-header-actions flex flex-wrap items-center justify-end gap-3">
@@ -3364,23 +3881,25 @@ class AccountManager {
${documents.map(document => {
const documentId = Number(document?.DocumentId);
const canDelete = Boolean(document?.CanDelete);
const presentation = this.getDocumentPresentation(document);
return `
<article class="flex min-w-0 gap-4 rounded-xl border border-slate-200 p-4 transition hover:border-red-200 hover:shadow-sm">
<div class="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-red-100 text-red-600">
<span class="material-symbols-outlined text-3xl">picture_as_pdf</span>
<div class="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl ${presentation.badgeClass}" title="${presentation.label}">
<span class="material-symbols-outlined text-3xl">${presentation.icon}</span>
</div>
<div class="min-w-0 flex-1">
<h2 class="truncate font-extrabold text-slate-800" title="${this.escapeHtml(document?.Title || '')}">${this.escapeHtml(document?.Title || 'Tài liệu PDF')}</h2>
<h2 class="truncate font-extrabold text-slate-800" title="${this.escapeHtml(document?.Title || '')}">${this.escapeHtml(document?.Title || 'Tài liệu')}</h2>
<p class="mt-0.5 truncate text-xs text-slate-500" title="${this.escapeHtml(document?.OriginalFileName || '')}">${this.escapeHtml(document?.OriginalFileName || '-')}</p>
<div class="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-[11px] text-slate-500">
<span class="font-bold ${presentation.iconClass}">${this.escapeHtml(presentation.extension || 'FILE')}</span>
<span class="inline-flex items-center gap-1"><span class="material-symbols-outlined text-sm">hard_drive</span>${this.formatFileSize(document?.FileSize)}</span>
<span class="inline-flex items-center gap-1"><span class="material-symbols-outlined text-sm">person</span>${this.escapeHtml(document?.UploadedByName || '-')}</span>
<span class="inline-flex items-center gap-1"><span class="material-symbols-outlined text-sm">schedule</span>${this.formatDateTime(document?.UploadedDate)}</span>
</div>
<div class="mt-3 flex flex-wrap items-center gap-2">
<a href="${this.apiBase}/documents/${documentId}/file" target="_blank" rel="noopener noreferrer" class="inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-bold text-white hover:bg-primary-dim">
<span class="material-symbols-outlined text-base">visibility</span>Xem PDF
</a>
${presentation.preview ? `<a href="${this.apiBase}/documents/${documentId}/file" target="_blank" rel="noopener noreferrer" class="inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-bold text-white hover:bg-primary-dim">
<span class="material-symbols-outlined text-base">visibility</span>Xem ${presentation.label}
</a>` : ''}
<a href="${this.apiBase}/documents/${documentId}/file?download=1" class="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-bold text-slate-700 hover:bg-slate-50">
<span class="material-symbols-outlined text-base">download</span>Tải xuống
</a>
@@ -3400,7 +3919,7 @@ class AccountManager {
<div class="flex h-16 w-16 items-center justify-center rounded-full bg-slate-100 text-slate-400">
<span class="material-symbols-outlined text-4xl">folder_open</span>
</div>
<h2 class="mt-4 font-extrabold text-slate-700">${this.documentSearchTerm ? 'Không tìm thấy tài liệu' : 'Chưa có tài liệu PDF'}</h2>
<h2 class="mt-4 font-extrabold text-slate-700">${this.documentSearchTerm ? 'Không tìm thấy tài liệu' : 'Chưa có tài liệu'}</h2>
<p class="mt-1 max-w-md text-sm text-slate-500">${this.documentSearchTerm ? 'Hãy thử một từ khóa khác.' : 'Bấm “Thêm tài liệu” để lưu tài liệu đầu tiên.'}</p>
</div>
`}
@@ -3415,7 +3934,7 @@ class AccountManager {
<span class="material-symbols-outlined">upload_file</span>
</div>
<div class="min-w-0">
<h2 id="documentUploadDialogTitle" class="text-lg font-extrabold text-slate-900">Thêm tài liệu PDF</h2>
<h2 id="documentUploadDialogTitle" class="text-lg font-extrabold text-slate-900">Thêm tài liệu</h2>
<p class="mt-0.5 text-xs text-slate-500">Tải tài liệu lên kho dùng chung.</p>
</div>
</div>
@@ -3426,10 +3945,10 @@ class AccountManager {
<div class="space-y-4 px-5 py-5">
<div>
<label for="documentFile" class="mb-1.5 block text-sm font-bold text-slate-700">Chọn file PDF <span class="text-red-600">*</span></label>
<input id="documentFile" name="file" type="file" accept="application/pdf,.pdf" required
<label for="documentFile" class="mb-1.5 block text-sm font-bold text-slate-700">Chọn tài liệu <span class="text-red-600">*</span></label>
<input id="documentFile" name="file" type="file" accept="${DOCUMENT_FORMATS.accept}" required
class="block h-11 w-full rounded-lg border border-slate-200 bg-white p-0 pr-3 text-sm file:mr-4 file:h-full file:border-0 file:bg-slate-100 file:px-4 file:font-bold file:text-slate-700 hover:file:bg-slate-200" />
<p class="mt-1.5 text-xs text-slate-500">Chỉ nhận định dạng PDF, tối đa ${this.documentMaxFileSizeMb} MB.</p>
<p class="mt-1.5 text-xs text-slate-500">${DOCUMENT_FORMATS.description}. Tối đa ${this.documentMaxFileSizeMb} MB/file.</p>
</div>
<div>
<label for="documentTitle" class="mb-1.5 block text-sm font-bold text-slate-700">Tên hiển thị <span class="font-normal text-slate-400">(không bắt buộc)</span></label>
@@ -3539,18 +4058,18 @@ class AccountManager {
async handleDocumentUpload(event) {
event.preventDefault();
const form = event.currentTarget;
if (form.dataset.uploading === 'true') return;
const fileInput = form.querySelector('#documentFile');
const titleInput = form.querySelector('#documentTitle');
const submitButton = form.querySelector('#documentUploadSubmit');
const file = fileInput?.files?.[0];
if (!file) {
this.notifyWarning('Vui lòng chọn file PDF');
this.notifyWarning('Vui lòng chọn tài liệu');
return;
}
const extensionIsPdf = String(file.name || '').toLowerCase().endsWith('.pdf');
if (!extensionIsPdf || (file.type && file.type !== 'application/pdf')) {
this.notifyFailure('Chỉ chấp nhận file PDF');
if (!this.isSupportedDocumentName(file.name)) {
this.notifyFailure(`Định dạng chưa được hỗ trợ. Chấp nhận: ${DOCUMENT_FORMATS.description}.`);
return;
}
if (file.size > this.documentMaxFileSizeMb * 1024 * 1024) {
@@ -3583,7 +4102,7 @@ class AccountManager {
this.documentSearchTerm = '';
await this.fetchDocuments();
this.renderView('documents');
this.notifySuccess(data.message || 'Đã lưu tài liệu PDF');
this.notifySuccess(data.message || 'Đã lưu tài liệu');
} catch (err) {
console.error('Upload document error:', err);
this.notifyFailure(err.message || 'Không thể tải tài liệu lên');

View File

@@ -0,0 +1,26 @@
(function () {
const formats = {
'.pdf': { mimeType: 'application/pdf', label: 'PDF', icon: 'picture_as_pdf', tone: 'red', preview: true },
'.doc': { mimeType: 'application/msword', label: 'Word', icon: 'description', tone: 'blue' },
'.docx': { mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', label: 'Word', icon: 'description', tone: 'blue' },
'.xls': { mimeType: 'application/vnd.ms-excel', label: 'Excel', icon: 'table_chart', tone: 'green' },
'.xlsx': { mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', label: 'Excel', icon: 'table_chart', tone: 'green' },
'.ppt': { mimeType: 'application/vnd.ms-powerpoint', label: 'PowerPoint', icon: 'slideshow', tone: 'orange' },
'.pptx': { mimeType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation', label: 'PowerPoint', icon: 'slideshow', tone: 'orange' },
'.jpg': { mimeType: 'image/jpeg', label: 'Ảnh', icon: 'image', tone: 'purple', preview: true },
'.jpeg': { mimeType: 'image/jpeg', label: 'Ảnh', icon: 'image', tone: 'purple', preview: true },
'.png': { mimeType: 'image/png', label: 'Ảnh', icon: 'image', tone: 'purple', preview: true },
'.gif': { mimeType: 'image/gif', label: 'Ảnh', icon: 'image', tone: 'purple', preview: true },
'.webp': { mimeType: 'image/webp', label: 'Ảnh', icon: 'image', tone: 'purple', preview: true },
'.bmp': { mimeType: 'image/bmp', label: 'Ảnh', icon: 'image', tone: 'purple', preview: true },
'.tif': { mimeType: 'image/tiff', label: 'Ảnh TIFF', icon: 'image', tone: 'purple' },
'.tiff': { mimeType: 'image/tiff', label: 'Ảnh TIFF', icon: 'image', tone: 'purple' },
'.txt': { mimeType: 'text/plain', label: 'Văn bản', icon: 'text_snippet', tone: 'slate', preview: true },
'.csv': { mimeType: 'text/csv', label: 'CSV', icon: 'table_chart', tone: 'green' },
'.rtf': { mimeType: 'application/rtf', label: 'RTF', icon: 'description', tone: 'blue' },
'.zip': { mimeType: 'application/zip', label: 'ZIP', icon: 'folder_zip', tone: 'slate' }
};
const config = { formats, accept: Object.keys(formats).join(','), description: 'PDF, Word, Excel, PowerPoint, ảnh, TXT, CSV, RTF, ZIP' };
if (typeof module !== 'undefined' && module.exports) module.exports = config;
if (typeof window !== 'undefined') window.DocumentFormats = config;
}());

View File

@@ -9,7 +9,7 @@
<link href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet"/>
<!-- Material Symbols -->
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200&display=swap" rel="stylesheet"/>
<link rel="stylesheet" href="../css/main.css?v=20260806-4" />
<link rel="stylesheet" href="../css/main.css?v=20261019-4" />
<!-- Notiflix Notify -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-3.2.7.min.css" />
<script src="https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-aio-3.2.7.min.js"></script>
@@ -46,25 +46,6 @@
transform: scale(1);
}
.tree-label {
letter-spacing: 0.08em;
text-transform: uppercase;
font-size: 10px;
font-weight: 800;
color: #64748b;
padding: 0 0.75rem;
margin-bottom: 0.35rem;
}
.tree-branch {
margin-left: 0.75rem;
border-left: 1px dashed rgba(100, 116, 139, 0.5);
padding-left: 0.6rem;
display: flex;
flex-direction: column;
gap: 0.2rem;
}
body.app-shell {
overflow: hidden;
}
@@ -268,102 +249,126 @@
}
</style>
<link rel="stylesheet" href="../css/responsive.css?v=20261013-1" />
<link rel="stylesheet" href="../css/responsive.css?v=20261019-3" />
</head>
<body class="app-shell bg-background text-on-surface antialiased flex h-screen w-screen">
<!-- SideNavBar -->
<aside id="appSidebar" class="h-screen w-56 flex flex-col bg-slate-100 dark:bg-slate-900 font-manrope text-sm font-medium border-r border-outline-variant/10 shrink-0">
<div class="flex flex-col h-full py-6">
<aside id="appSidebar" class="h-screen w-64 flex flex-col bg-slate-100 dark:bg-slate-900 font-manrope text-sm font-medium border-r border-outline-variant/10 shrink-0">
<div class="flex flex-col h-full min-h-0 py-4">
<!-- Header -->
<div class="px-6 mb-8">
<div class="px-5 mb-4 shrink-0">
<a href="#dashboard" class="sidebar-brand-link" aria-label="PNKX - Về trang tổng quan">
<img src="../image/logo_PNKX.png" alt="PNKX" class="sidebar-brand-image"/>
</a>
</div>
<!-- Primary Nav -->
<nav class="flex-1 px-3 space-y-4 overflow-y-auto">
<div>
<div class="tree-label">Tài khoản</div>
<div class="tree-branch">
<a href="#dashboard" data-nav="dashboard" class="flex items-center gap-3 px-3 py-2 border-l-4 border-blue-600 bg-slate-200/80 dark:bg-slate-800 text-slate-900 dark:text-slate-50 font-bold group transition-all cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">dashboard</span>
<span>Tổng quan</span>
<nav id="sidebarNav" class="sidebar-nav flex-1 min-h-0 overflow-y-auto" aria-label="Điều hướng chính">
<ul class="sidebar-menu">
<li>
<a href="#dashboard" data-nav="dashboard" class="sidebar-link" aria-current="page">
<span class="material-symbols-outlined" aria-hidden="true">dashboard</span>
<span class="sidebar-text">Tổng quan</span>
</a>
<a href="#applications" data-nav="applications" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">apps</span>
<span>Ứng dụng</span>
</li>
<li data-nav-group="accounts">
<button id="sidebarAccountsToggle" type="button" class="sidebar-link sidebar-group-toggle" data-nav-toggle="accounts" aria-expanded="false" aria-controls="sidebarAccounts">
<span class="material-symbols-outlined" aria-hidden="true">manage_accounts</span>
<span class="sidebar-text">Tài khoản</span>
<span class="material-symbols-outlined sidebar-chevron" aria-hidden="true">chevron_right</span>
</button>
<ul id="sidebarAccounts" class="sidebar-children" aria-labelledby="sidebarAccountsToggle" hidden>
<li><a href="#applications" data-nav="applications" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">apps</span>
<span class="sidebar-text">Ứng dụng</span>
</a></li>
<li><a href="#accounts" data-nav="accounts" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">manage_accounts</span>
<span class="sidebar-text">Tài khoản</span>
</a></li>
<li><a href="#notifications" data-nav="notifications" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">notifications</span>
<span class="sidebar-text">Thông báo</span>
<span id="notificationNavBadge" class="hidden ml-auto min-w-[20px] h-5 px-1.5 rounded-full bg-red-600 text-white text-[10px] font-extrabold leading-5 text-center">0</span>
</a></li>
</ul>
</li>
<li data-nav-group="assets">
<button id="sidebarAssetsToggle" type="button" class="sidebar-link sidebar-group-toggle" data-nav-toggle="assets" aria-expanded="false" aria-controls="sidebarAssets">
<span class="material-symbols-outlined" aria-hidden="true">inventory_2</span>
<span class="sidebar-text">Quản lý tài sản</span>
<span class="material-symbols-outlined sidebar-chevron" aria-hidden="true">chevron_right</span>
</button>
<ul id="sidebarAssets" class="sidebar-children" aria-labelledby="sidebarAssetsToggle" hidden>
<li><a href="#assets" data-nav="assets" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">inventory_2</span>
<span class="sidebar-text">Tài sản</span>
</a></li>
<li><a href="#asset-borrows" data-nav="asset-borrows" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">assignment_returned</span>
<span class="sidebar-text">Mượn/Trả tài sản</span>
</a></li>
<li><a href="#my-borrowed-assets" data-nav="my-borrowed-assets" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">inventory</span>
<span class="sidebar-text">Tài sản đang mượn</span>
</a></li>
<li><a href="#asset-departments" data-nav="asset-departments" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">apartment</span>
<span class="sidebar-text">Phòng ban</span>
</a></li>
<li><a href="#asset-projects" data-nav="asset-projects" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">workspaces</span>
<span class="sidebar-text">Dự án</span>
</a></li>
</ul>
</li>
<li data-nav-group="consumables">
<button id="sidebarConsumablesToggle" type="button" class="sidebar-link sidebar-group-toggle" data-nav-toggle="consumables" aria-expanded="false" aria-controls="sidebarConsumables">
<span class="material-symbols-outlined" aria-hidden="true">category</span>
<span class="sidebar-text">Vật tư tiêu hao</span>
<span class="material-symbols-outlined sidebar-chevron" aria-hidden="true">chevron_right</span>
</button>
<ul id="sidebarConsumables" class="sidebar-children" aria-labelledby="sidebarConsumablesToggle" hidden>
<li><a href="#consumables" data-nav="consumables" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">category</span>
<span class="sidebar-text">Danh sách VTTH</span>
</a></li>
<li><a href="#consumable-exports" data-nav="consumable-exports" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">outbox</span>
<span class="sidebar-text">Lịch sử xuất</span>
</a></li>
</ul>
</li>
<li data-nav-group="robots">
<button id="sidebarRobotsToggle" type="button" class="sidebar-link sidebar-group-toggle" data-nav-toggle="robots" aria-expanded="false" aria-controls="sidebarRobots">
<span class="material-symbols-outlined" aria-hidden="true">smart_toy</span>
<span class="sidebar-text">Quản lý robot</span>
<span class="material-symbols-outlined sidebar-chevron" aria-hidden="true">chevron_right</span>
</button>
<ul id="sidebarRobots" class="sidebar-children" aria-labelledby="sidebarRobotsToggle" hidden>
<li><a href="#robots" data-nav="robots" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">smart_toy</span>
<span class="sidebar-text">Danh sách robot</span>
</a></li>
<li><a href="#robot-types" data-nav="robot-types" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">category</span>
<span class="sidebar-text">Thể loại robot</span>
</a></li>
</ul>
</li>
<li><a href="#documents" data-nav="documents" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">folder_open</span>
<span class="sidebar-text">Tài liệu</span>
</a></li>
<li id="usersSection" class="sidebar-admin" style="display: none;">
<a id="usersNav" href="#users" data-nav="users" class="sidebar-link" style="display: none;">
<span class="material-symbols-outlined" aria-hidden="true">people</span>
<span class="sidebar-text">Người dùng</span>
</a>
<a href="#accounts" data-nav="accounts" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">manage_accounts</span>
<span>Tài khoản</span>
</a>
<a href="#notifications" data-nav="notifications" class="relative flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">notifications</span>
<span>Thông báo</span>
<span id="notificationNavBadge" class="hidden ml-auto min-w-[20px] h-5 px-1.5 rounded-full bg-red-600 text-white text-[10px] font-extrabold leading-5 text-center">0</span>
</a>
</div>
</div>
<div>
<div class="tree-label">Quản lý tài sản</div>
<div class="tree-branch">
<a href="#assets" data-nav="assets" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">inventory_2</span>
<span>Tài sản</span>
</a>
<a href="#asset-borrows" data-nav="asset-borrows" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">assignment_returned</span>
<span>Mượn/Trả tài sản</span>
</a>
<a href="#my-borrowed-assets" data-nav="my-borrowed-assets" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">inventory</span>
<span>Tài sản đang mượn</span>
</a>
<a href="#asset-departments" data-nav="asset-departments" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">apartment</span>
<span> Phòng Ban</span>
</a>
<a href="#asset-projects" data-nav="asset-projects" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">workspaces</span>
<span>Dự án</span>
</a>
</div>
</div>
<div>
<div class="tree-label">Vật tư tiêu hao</div>
<div class="tree-branch">
<a href="#consumables" data-nav="consumables" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">category</span>
<span>Danh sách VTTH</span>
</a>
<a href="#consumable-exports" data-nav="consumable-exports" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">outbox</span>
<span>Lịch sử xuất</span>
</a>
</div>
</div>
<div>
<div class="tree-label">Tài liệu</div>
<div class="tree-branch">
<a href="#documents" data-nav="documents" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-r-lg">
<span class="material-symbols-outlined">picture_as_pdf</span>
<span>Tài liệu PDF</span>
</a>
</div>
</div>
<div id="usersSection" class="pt-2 border-t border-outline-variant/10" style="display: none;">
<a id="usersNav" href="#users" data-nav="users" class="flex items-center gap-3 px-3 py-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 hover:bg-slate-200/50 transition-all group cursor-pointer rounded-lg" style="display: none;">
<span class="material-symbols-outlined">people</span>
<span>Người dùng (Quản trị)</span>
</a>
</div>
</li>
</ul>
</nav>
<!-- Footer -->
<div class="px-6 pt-4 border-t border-outline-variant/10">
<div class="px-5 pt-3 mt-3 border-t border-outline-variant/10 shrink-0">
<div class="text-[10px] font-bold text-on-surface-variant/40 uppercase tracking-widest">v1.0.0</div>
</div>
</div>
@@ -425,6 +430,7 @@
</div>
</main>
<script src="../js/app.js?v=20261013-3"></script>
<script src="../js/document-formats.js?v=20261019-1"></script>
<script src="../js/app.js?v=20261019-4"></script>
</body>
</html>