136 lines
11 KiB
JavaScript
136 lines
11 KiB
JavaScript
const test = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
const { randomUUID } = require('node:crypto');
|
|
const express = require('express');
|
|
const sql = require('mssql');
|
|
const { ensureRobotBomSchema, createRobotBomRouter } = require('./robot-bom');
|
|
|
|
test('SQL Server migrates legacy BOMs, stores external parts and sources, and keeps quantities independent of inventory', {
|
|
skip: process.env.ACCMANAGER_BOM_SQL_TEST !== '1' ? 'Set ACCMANAGER_BOM_SQL_TEST=1 to use a disposable database on the configured SQL Server' : false,
|
|
timeout: 60000
|
|
}, async () => {
|
|
require('dotenv').config();
|
|
const bool = (key, fallback) => process.env[key] === undefined ? fallback : /^(1|true|yes|on)$/i.test(process.env[key]);
|
|
const database = `AccManagerBomTest_${randomUUID().replace(/-/g, '')}`;
|
|
const config = { server: process.env.DB_SERVER || 'localhost', user: process.env.DB_USER || 'sa', password: process.env.DB_PASSWORD,
|
|
database: 'master', options: { encrypt: bool('DB_ENCRYPT', false), trustServerCertificate: bool('DB_TRUST_CERTIFICATE', true), useUTC: false },
|
|
pool: { min: 0, max: 5, idleTimeoutMillis: 1000 }, connectionTimeout: 15000, requestTimeout: 15000 };
|
|
let admin, pool, server, created = false;
|
|
try {
|
|
admin = await new sql.ConnectionPool(config).connect();
|
|
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 PRIMARY KEY); INSERT dbo.Users VALUES (1);
|
|
CREATE TABLE dbo.RobotTypes (TypeId INT PRIMARY KEY, Name NVARCHAR(100)); INSERT dbo.RobotTypes VALUES (1, N'AMR');
|
|
CREATE TABLE dbo.Robots (RobotId INT PRIMARY KEY, Name NVARCHAR(255), Model NVARCHAR(255), TypeId INT);
|
|
INSERT dbo.Robots VALUES (1, N'Robot thử nghiệm', 'AMR-500', 1);
|
|
CREATE TABLE dbo.AssetInventory (AssetId INT PRIMARY KEY, AssetCode NVARCHAR(100), AssetName NVARCHAR(255),
|
|
Model NVARCHAR(255), Unit NVARCHAR(50), EndingBalance INT, Location NVARCHAR(150), IsArchived BIT);
|
|
INSERT dbo.AssetInventory VALUES (1, 'LK-001', N'Servo', 'SV-400', N'cái', 8, N'Kho A', 0),
|
|
(2, 'OLD', N'Archived', 'SV-400', N'cái', 100, N'Kho A', 1);
|
|
CREATE TABLE dbo.ConsumableInventory (ConsumableId INT PRIMARY KEY, ConsumableCode NVARCHAR(100),
|
|
ConsumableName NVARCHAR(255), Model NVARCHAR(255), Unit NVARCHAR(50), EndingBalance INT);
|
|
INSERT dbo.ConsumableInventory VALUES (1, 'VT-001', N'Cáp', 'CB-2X2.5', 'm', 30);
|
|
-- Simulate the earlier inventory-linked installation, including a released BOM.
|
|
CREATE TABLE dbo.RobotBomRevisions (
|
|
BomId INT IDENTITY PRIMARY KEY, RobotModel NVARCHAR(255) NOT NULL, RobotTypeId INT NOT NULL,
|
|
Revision INT NOT NULL, Status VARCHAR(10) NOT NULL DEFAULT 'draft', LockVersion INT NOT NULL DEFAULT 1,
|
|
CreatedBy INT NULL, CreatedDate DATETIME2 NOT NULL DEFAULT GETDATE(),
|
|
UpdatedDate DATETIME2 NOT NULL DEFAULT GETDATE(), ReleasedDate DATETIME2 NULL,
|
|
CONSTRAINT UQ_RobotBomRevisions_ModelRevision UNIQUE (RobotTypeId, RobotModel, Revision)
|
|
);
|
|
CREATE TABLE dbo.RobotBomLines (
|
|
LineId INT IDENTITY PRIMARY KEY, BomId INT NOT NULL, SourceType VARCHAR(10) NOT NULL,
|
|
SourceId INT NOT NULL, Code NVARCHAR(100) NOT NULL, Name NVARCHAR(255) NOT NULL,
|
|
Model NVARCHAR(255) NOT NULL, Unit NVARCHAR(50) NOT NULL, GroupName NVARCHAR(100) NOT NULL,
|
|
Position NVARCHAR(150) NOT NULL DEFAULT '', Quantity DECIMAL(18,4) NOT NULL,
|
|
Notes NVARCHAR(500) NOT NULL DEFAULT '', SortOrder INT NOT NULL,
|
|
CONSTRAINT CK_RobotBomLines_Source CHECK (SourceType IN ('asset', 'consumable')),
|
|
CONSTRAINT FK_RobotBomLines_Revision FOREIGN KEY (BomId) REFERENCES dbo.RobotBomRevisions(BomId)
|
|
);
|
|
INSERT dbo.RobotBomRevisions (RobotModel, RobotTypeId, Revision, Status) VALUES ('AMR-500', 1, 1, 'released');
|
|
INSERT dbo.RobotBomLines (BomId, SourceType, SourceId, Code, Name, Model, Unit, GroupName, Quantity, Notes, SortOrder)
|
|
VALUES (1, 'asset', 1, 'LK-001', N'Servo cũ', 'SV-400', N'cái', N'Cơ khí', 2, N'Giữ nguyên mô tả', 0);
|
|
`);
|
|
await ensureRobotBomSchema(pool); await ensureRobotBomSchema(pool);
|
|
const legacy = (await pool.request().query('SELECT * FROM dbo.RobotBomLines WHERE BomId = 1')).recordset[0];
|
|
assert.equal(legacy.Name, 'Servo cũ'); assert.equal(legacy.Quantity, 2); assert.equal(legacy.Notes, 'Giữ nguyên mô tả');
|
|
assert.equal(legacy.SourceType, 'manual'); assert.equal(legacy.SourceId, null); assert.equal(legacy.SourceInfo, '');
|
|
assert.equal((await pool.request().query('SELECT Status FROM dbo.RobotBomRevisions WHERE BomId = 1')).recordset[0].Status, 'released');
|
|
const app = express(); app.use(express.json());
|
|
app.use((req, _res, next) => { req.user = { UserId: 1 }; next(); });
|
|
app.use('/boms', createRobotBomRouter({ getPool: () => pool, sql, requireManage: (_req, _res, next) => next(),
|
|
sendInternalError(res, error, message) { console.error('SQL BOM test:', error.message); return 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 = async (suffix = '', method = 'GET', body) => {
|
|
const response = await fetch(`http://127.0.0.1:${server.address().port}/boms${suffix}`, { method,
|
|
...(body === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) });
|
|
return { status: response.status, ...(await response.json()) };
|
|
};
|
|
const catalog = await request('/catalog'); assert.equal(catalog.status, 200); assert.equal(catalog.data.length, 1);
|
|
assert.deepEqual(Object.keys(catalog.data[0]).sort(), ['Code', 'Id', 'Model', 'Name', 'Unit']);
|
|
const id = (await request('', 'POST', { robotId: 1 })).data.BomId;
|
|
const lines = [
|
|
{ name: 'Servo', model: 'SV-400', unit: 'cái', quantity: 30, sourceInfo: 'https://example.com/servo' },
|
|
{ name: 'Khung gia công bên ngoài', model: 'CUSTOM-01', quantity: 2, sourceInfo: 'Nhà sản xuất: Cơ khí ABC' },
|
|
{ name: 'Cáp nguồn bên ngoài', model: 'CB-NEW', unit: 'm', quantity: 1.125, notes: 'Tuyến nguồn' }
|
|
];
|
|
assert.equal((await request(`/${id}`, 'PUT', { lockVersion: 1, lines })).status, 200);
|
|
const saved = (await request(`/${id}`)).data.Lines;
|
|
assert.equal(saved[0].Quantity, 30); assert.equal(saved[0].SourceInfo, 'https://example.com/servo');
|
|
assert.equal(saved[1].Name, 'Khung gia công bên ngoài'); assert.equal(saved[1].SourceInfo, 'Nhà sản xuất: Cơ khí ABC');
|
|
assert.equal(saved[2].Quantity, 1.125);
|
|
// Two clients with the same version cannot both overwrite the revision.
|
|
const saves = await Promise.all([1, 2].map(() => request(`/${id}`, 'PUT', { lockVersion: 2, lines })));
|
|
assert.deepEqual(saves.map(result => result.status).sort(), [200, 409]);
|
|
// Force a real SQL failure after the DELETE, then verify full rollback.
|
|
await pool.request().query('ALTER TABLE dbo.RobotBomLines ADD CONSTRAINT CK_BomTest_Failure CHECK (Quantity < 50)');
|
|
assert.equal((await request(`/${id}`, 'PUT', { lockVersion: 3, lines: [{ ...lines[0], quantity: 99 }] })).status, 500);
|
|
assert.equal((await request(`/${id}`)).data.Lines.length, 3);
|
|
assert.equal((await request(`/${id}`)).data.LockVersion, 3);
|
|
assert.equal((await request(`/${id}/publish`, 'POST', { lockVersion: 3 })).status, 200);
|
|
assert.equal((await request(`/${id}`, 'PUT', { lockVersion: 4, lines: [] })).status, 409);
|
|
const copies = await Promise.all([1, 2].map(() => request('', 'POST', { robotId: 1, copyFromId: id })));
|
|
assert.deepEqual(copies.map(result => result.data.Revision).sort(), [3, 4]);
|
|
await ensureRobotBomSchema(pool);
|
|
assert.equal((await request(`/${copies[0].data.BomId}`)).data.Lines.length, 3);
|
|
assert.equal((await request(`/${copies[0].data.BomId}`)).data.Lines[1].SourceInfo, 'Nhà sản xuất: Cơ khí ABC');
|
|
assert.deepEqual((await pool.request().query('SELECT EndingBalance FROM dbo.AssetInventory ORDER BY AssetId')).recordset.map(item => item.EndingBalance), [8, 100]);
|
|
assert.equal((await pool.request().query('SELECT EndingBalance FROM dbo.ConsumableInventory')).recordset[0].EndingBalance, 30);
|
|
// Once descriptions are entered, no inventory tables are needed to save/publish/copy.
|
|
await pool.request().query('DROP TABLE dbo.AssetInventory; DROP TABLE dbo.ConsumableInventory;');
|
|
await pool.request().query('DELETE FROM dbo.Robots');
|
|
const historical = await request('/models');
|
|
assert.equal(historical.data[0].RobotId, null); assert.equal(historical.data[0].Model, 'AMR-500');
|
|
const detached = await request('', 'POST', { copyFromId: id });
|
|
assert.equal(detached.data.Revision, 5);
|
|
assert.equal((await request(`/${detached.data.BomId}`, 'PUT', { lockVersion: 1, lines })).status, 200);
|
|
assert.equal((await request(`/${detached.data.BomId}/publish`, 'POST', { lockVersion: 2 })).status, 200);
|
|
// Deletions respect concurrent versions and remove only their own lines.
|
|
const draftId = copies[0].data.BomId;
|
|
assert.equal((await request(`/${id}`, 'DELETE', { lockVersion: 3 })).status, 409);
|
|
await pool.request().query(`CREATE TABLE dbo.BomDeleteTestReferences (
|
|
BomId INT NOT NULL REFERENCES dbo.RobotBomRevisions(BomId));
|
|
INSERT dbo.BomDeleteTestReferences VALUES (${draftId})`);
|
|
assert.equal((await request(`/${draftId}`, 'DELETE', { lockVersion: 1 })).status, 500);
|
|
assert.equal((await request(`/${draftId}`)).data.Lines.length, 3);
|
|
await pool.request().query('DROP TABLE dbo.BomDeleteTestReferences');
|
|
const deletions = await Promise.all([1, 2].map(() => request(`/${draftId}`, 'DELETE', { lockVersion: 1 })));
|
|
assert.deepEqual(deletions.map(result => result.status).sort(), [200, 404]);
|
|
assert.equal((await pool.request().input('id', sql.Int, draftId).query('SELECT COUNT(*) AS Total FROM dbo.RobotBomLines WHERE BomId = @id')).recordset[0].Total, 0);
|
|
assert.equal((await request(`/${id}`, 'DELETE', { lockVersion: 4 })).status, 200);
|
|
assert.equal((await request(`/${id}`)).status, 404);
|
|
assert.equal((await request(`/${copies[1].data.BomId}`)).data.Lines.length, 3);
|
|
assert.equal((await request(`/${detached.data.BomId}`)).data.Status, 'released');
|
|
} finally {
|
|
if (server) { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }
|
|
if (pool) await pool.close();
|
|
if (admin) {
|
|
// Only the explicitly created, randomized test database is eligible for cleanup.
|
|
if (created && /^AccManagerBomTest_[a-f0-9]{32}$/.test(database)) await admin.request().query(`ALTER DATABASE [${database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [${database}]`);
|
|
await admin.close();
|
|
}
|
|
}
|
|
});
|