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

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(); }
}
});