Compare commits

..

9 Commits

Author SHA1 Message Date
6e919fde45 check lần 2 2026-11-30 15:38:49 +07:00
1b1012dbed check tên miền 2026-11-30 15:37:55 +07:00
03a481f20d update export 2026-11-11 10:48:31 +07:00
00122e5b4a update export request 2026-11-10 11:01:24 +07:00
63866b14a1 update dasboard ,noti 2026-11-04 09:54:17 +07:00
ea6768f90d Stop tracking docs directory 2026-11-02 15:14:42 +07:00
a41bd9c193 Ignore docs directory 2026-11-02 15:13:17 +07:00
6a872e8c8b bom 2026-11-02 15:09:59 +07:00
c441c809ca fix domain 2026-11-02 10:19:45 +07:00
44 changed files with 4646 additions and 2304 deletions

View File

@@ -20,8 +20,8 @@ DATA_ENCRYPTION_SECRET=replace-with-at-least-32-random-bytes
BCRYPT_ROUNDS=12
# Public HTTPS origin used by email links, CORS and secure cookies.
APP_BASE_URL=https://accmanager.example.internal
CORS_ALLOWED_ORIGINS=https://accmanager.example.internal
APP_BASE_URL=https://robot.dvex.io.vn
CORS_ALLOWED_ORIGINS=https://robot.dvex.io.vn
COOKIE_SECURE=true
TRUST_PROXY_HOPS=1
SESSION_TTL_HOURS=12

3
.gitignore vendored
View File

@@ -11,4 +11,5 @@ tmp
outputs
test/
tools
output
docs

86
backend/announcements.js Normal file
View File

@@ -0,0 +1,86 @@
const express = require('express');
// Every popup and dismissal is evaluated against the authenticated recipient.
const visibleAnnouncement = `n.Source = 'admin' AND n.IsActive = 1
AND (n.ExpiresAt IS NULL OR n.ExpiresAt > DATEADD(HOUR, 7, SYSUTCDATETIME()))
AND EXISTS (
SELECT 1 FROM NotificationAudiences a WHERE a.NotificationId = n.NotificationId
AND (a.AudienceType = 'all'
OR (a.AudienceType = 'user' AND a.AudienceValue = CONVERT(NVARCHAR(100), @userId))
OR (a.AudienceType = 'role' AND LOWER(a.AudienceValue) = LOWER(@userRole)))
)`;
function createAnnouncementRouter({ getPool, sql, requireManage, getUserId, getRole, sendInternalError }) {
const router = express.Router();
const recipientRequest = req => getPool().request()
.input('userId', sql.Int, getUserId(req))
.input('userRole', sql.NVarChar(100), getRole(req));
router.get('/announcements', async (req, res) => {
try {
const result = await recipientRequest(req).query(`
SELECT n.NotificationId, n.Source, n.Severity, n.Title, n.Message, n.ActionUrl,
n.CreatedDate, n.ExpiresAt, n.CreatedBy,
COALESCE(NULLIF(LTRIM(RTRIM(u.FullName)), ''), u.Username) AS CreatedByName,
CAST(CASE WHEN receipts.ReadAt IS NULL THEN 0 ELSE 1 END AS BIT) AS IsRead
FROM Notifications n
LEFT JOIN Users u ON u.UserId = n.CreatedBy
LEFT JOIN NotificationReceipts receipts ON receipts.NotificationId = n.NotificationId AND receipts.UserId = @userId
WHERE ${visibleAnnouncement}
AND NOT EXISTS (SELECT 1 FROM NotificationPopupDismissals d
WHERE d.NotificationId = n.NotificationId AND d.UserId = @userId)
ORDER BY n.CreatedDate DESC, n.NotificationId DESC;
`);
res.json({ success: true, data: result.recordset });
} catch (error) { sendInternalError(res, error); }
});
router.put('/:id/dismiss', async (req, res) => {
const notificationId = Number(req.params.id);
if (!Number.isSafeInteger(notificationId) || notificationId <= 0) {
return res.status(400).json({ success: false, message: 'Thông báo không hợp lệ' });
}
try {
const result = await recipientRequest(req).input('notificationId', sql.BigInt, notificationId).query(`
IF EXISTS (SELECT 1 FROM Notifications n WHERE n.NotificationId = @notificationId AND ${visibleAnnouncement})
BEGIN
MERGE NotificationPopupDismissals WITH (HOLDLOCK) AS target
USING (SELECT @notificationId AS NotificationId, @userId AS UserId) AS source
ON target.NotificationId = source.NotificationId AND target.UserId = source.UserId
WHEN NOT MATCHED THEN INSERT (NotificationId, UserId)
VALUES (source.NotificationId, source.UserId);
SELECT CAST(1 AS BIT) AS Found;
END
ELSE SELECT CAST(0 AS BIT) AS Found;
`);
if (!result.recordset?.[0]?.Found) return res.status(404).json({ success: false, message: 'Thông báo đã kết thúc hoặc không dành cho bạn' });
res.json({ success: true });
} catch (error) { sendInternalError(res, error); }
});
router.get('/manage', requireManage, async (req, res) => {
const page = Math.max(1, Number.parseInt(req.query.page, 10) || 1);
const pageSize = Math.min(50, Math.max(1, Number.parseInt(req.query.pageSize, 10) || 20));
try {
const result = await getPool().request()
.input('offset', sql.Int, (page - 1) * pageSize)
.input('pageSize', sql.Int, pageSize)
.query(`
SET NOCOUNT ON;
SELECT COUNT_BIG(*) AS Total FROM Notifications WHERE Source = 'admin';
SELECT n.NotificationId, n.Source, n.Severity, n.Title, n.Message, n.ActionUrl,
n.CreatedBy, n.CreatedDate, n.ExpiresAt, n.IsActive,
COALESCE(NULLIF(LTRIM(RTRIM(u.FullName)), ''), u.Username) AS CreatedByName
FROM Notifications n LEFT JOIN Users u ON u.UserId = n.CreatedBy
WHERE n.Source = 'admin'
ORDER BY n.CreatedDate DESC, n.NotificationId DESC
OFFSET @offset ROWS FETCH NEXT @pageSize ROWS ONLY;
`);
const total = Number(result.recordsets?.[0]?.[0]?.Total) || 0;
res.json({ success: true, data: result.recordsets?.[1] || [], pagination: { page, pageSize, total, totalPages: Math.max(1, Math.ceil(total / pageSize)) } });
} catch (error) { sendInternalError(res, error); }
});
return router;
}
module.exports = { createAnnouncementRouter };

View File

@@ -0,0 +1,183 @@
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');
async function fixture(t) {
const notices = [], audiences = [], reads = new Set(), dismissals = new Set(), queries = [];
const users = { 1: 'admin', 2: 'user', 3: 'user', 4: 'asset' };
const visible = (notice, inputs) => notice.IsActive && (!notice.ExpiresAt || +new Date(notice.ExpiresAt) > Date.now())
&& audiences.some(a => a.id === notice.NotificationId && (a.type === 'all' || a.type === 'user' && +a.value === inputs.userId || a.type === 'role' && a.value === inputs.userRole));
class Request {
constructor() { this.inputs = {}; }
input(name, _type, value) { this.inputs[name] = value; return this; }
async query(query) {
const p = this.inputs;
queries.push({ query, inputs: p });
if (query.includes('INSERT INTO Notifications')) {
const notice = { NotificationId: notices.length + 1, Source: p.source, Title: p.title, Message: p.message,
Severity: p.severity, ActionUrl: p.actionUrl, CreatedBy: p.createdBy, CreatedByName: 'Publisher',
ExpiresAt: p.expiresAt, CreatedDate: new Date(), IsActive: true };
notices.push(notice);
return { recordset: [{ NotificationId: notice.NotificationId }] };
}
if (query.includes('INSERT INTO NotificationAudiences')) {
audiences.push({ id: p.notificationId, type: p.audienceType, value: p.audienceValue });
return { recordset: [] };
}
if (query.includes('INTO #VisibleNotifications')) {
assert.match(query, /receipts\.UserId = @userId/);
assert.match(query, /AudienceType = 'user' AND audiences\.AudienceValue = CONVERT\(NVARCHAR\(100\), @userId\)/);
let rows = notices.filter(n => visible(n, p) && (!p.source || n.Source === p.source))
.map(n => ({ ...n, IsRead: reads.has(`${n.NotificationId}:${p.userId}`) }));
const unread = rows.filter(n => !n.IsRead).length;
if (p.unreadOnly) rows = rows.filter(n => !n.IsRead);
return { recordsets: [[{ Total: rows.length }], [{ UnreadCount: unread }], rows.slice(p.offset, p.offset + p.pageSize)] };
}
if (query.includes('MERGE NotificationPopupDismissals')) {
assert.match(query, /WITH \(HOLDLOCK\)/);
assert.match(query, /n\.Source = 'admin' AND n\.IsActive = 1/);
assert.match(query, /a\.AudienceValue = CONVERT\(NVARCHAR\(100\), @userId\)/);
const found = notices.some(n => n.NotificationId === p.notificationId && n.Source === 'admin' && visible(n, p));
if (found) dismissals.add(`${p.notificationId}:${p.userId}`);
return { recordset: [{ Found: found }] };
}
if (query.includes('FROM NotificationPopupDismissals d')) {
assert.match(query, /d\.UserId = @userId/);
assert.match(query, /n\.ExpiresAt > DATEADD/);
return { recordset: notices.filter(n => n.Source === 'admin' && visible(n, p) && !dismissals.has(`${n.NotificationId}:${p.userId}`))
.map(n => ({ ...n, IsRead: reads.has(`${n.NotificationId}:${p.userId}`) })) };
}
if (query.includes('COUNT_BIG(*) AS Total FROM Notifications')) {
const rows = notices.filter(n => n.Source === 'admin');
return { recordsets: [[{ Total: rows.length }], rows.slice(p.offset, p.offset + p.pageSize)] };
}
if (query.includes('MERGE NotificationReceipts')) {
const found = notices.some(n => n.NotificationId === p.notificationId && visible(n, p));
if (found) reads.add(`${p.notificationId}:${p.userId}`);
return { recordset: [{ Found: found }] };
}
if (query.includes('INSERT INTO NotificationReceipts')) {
notices.filter(n => visible(n, p)).forEach(n => reads.add(`${n.NotificationId}:${p.userId}`));
return { recordset: [] };
}
if (query.includes('UPDATE Notifications')) {
assert.match(query, /@isAdmin = 1 OR CreatedBy = @userId/);
const found = notices.find(n => n.NotificationId === p.notificationId && n.Source === 'admin' && n.IsActive && (p.isAdmin || n.CreatedBy === p.userId));
if (found) found.IsActive = false;
return { recordset: [{ Affected: found ? 1 : 0 }] };
}
if (query.includes('FROM AssetBorrowRequests br WITH')) return { recordset: [{ BorrowId: 11, AssetId: 17, RequestType: 'borrow', RequestStatus: 'pending', CreatedBy: 2, BorrowerName: 'User 2', AssetCode: 'TS-17', AssetName: 'PLC' }] };
if (query.includes('UPDATE AssetBorrowRequests')) return { recordset: [] };
throw new Error(`Unexpected SQL in test: ${query.slice(0, 80)}`);
}
}
class Transaction { async begin() {} async commit() {} async rollback() {} }
const filename = path.join(__dirname, 'server.js');
const localRequire = createRequire(filename);
const sql = { ...localRequire('mssql'), Request, Transaction };
const sandbox = {
require: name => name === 'mssql' ? sql : name === 'dotenv' ? { config() {} } : localRequire(name),
module: { exports: {} }, __dirname, __filename: filename, Buffer, URL, console,
testPool: { request: () => new Request() },
process: { env: { NODE_ENV: 'test', DATA_ENCRYPTION_SECRET: 'announcement-tests-only-secret-more-than-32-characters' }, on() {} }
};
vm.runInNewContext(`${fs.readFileSync(filename, 'utf8')}\npool=testPool; getUserDisplayNameById=async()=> 'Manager';`, sandbox, { filename });
const review = express();
review.use(express.json());
review.use((req, _res, next) => { const id = Number(req.headers['x-test-user'] || 2); req.user = { UserId: id, Role: users[id] }; next(); });
for (const layer of sandbox.module.exports.app.router.stack) {
if (layer.handle?.stack?.some(entry => entry.route?.path === '/announcements')) review.use('/api/notifications', layer.handle);
if (!layer.route || !(layer.route.path.startsWith('/api/notifications') || layer.route.path === '/api/asset-borrows/:id/process')) continue;
for (const method of Object.keys(layer.route.methods)) review[method](layer.route.path, ...layer.route.stack.map(entry => entry.handle));
}
const missingApi = sandbox.module.exports.app.router.stack.find(layer => !layer.route && layer.handle.toString().includes('API_NOT_FOUND'));
if (missingApi) review.use('/api', missingApi.handle);
const server = review.listen(0, '127.0.0.1');
await new Promise(resolve => server.once('listening', resolve));
t.after(() => new Promise(resolve => server.close(resolve)));
const call = async (route, user = 2, method = 'GET', body) => {
const response = await fetch(`http://127.0.0.1:${server.address().port}/api/${route}`, {
method, headers: { 'x-test-user': String(user), 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : undefined
});
return { status: response.status, ...(await response.json()) };
};
const publish = (user = 1, extra = {}) => call('notifications', user, 'POST', {
title: 'Lịch bảo trì', message: 'Hệ thống bảo trì vào cuối tuần.', expiresAt: new Date(Date.now() + 86400000).toISOString(), ...extra
});
return { call, publish, notices, audiences, reads, dismissals, queries };
}
test('Admin and Asset can publish; viewers cannot publish or access management; expiry is required', async t => {
const f = await fixture(t);
assert.equal((await f.publish(1)).status, 201);
assert.equal((await f.publish(4)).status, 201);
assert.equal((await f.publish(2)).status, 403);
for (const expiresAt of [null, 'bad-date', '2020-01-01T00:00:00Z']) assert.equal((await f.publish(4, { expiresAt })).status, 400);
assert.equal((await f.call('notifications/manage', 2)).status, 403);
assert.equal((await f.call('notifications/manage', 4)).data.length, 2);
assert.equal(f.notices[1].CreatedBy, 4);
});
test('reading broadcasts does not suppress popups; dismissal persists per user and per announcement', async t => {
const f = await fixture(t);
await f.publish(); await f.publish();
await f.call('notifications/read-all', 2, 'PUT');
assert.equal((await f.call('notifications/announcements', 2)).data.length, 2);
assert.equal((await f.call('notifications/1/dismiss', 2, 'PUT', { userId: 3 })).status, 200);
assert.equal((await f.call('notifications/1/dismiss', 2, 'PUT')).status, 200);
assert.equal(f.dismissals.size, 1);
assert.deepEqual((await f.call('notifications/announcements', 2)).data.map(n => n.NotificationId), [2]);
assert.equal((await f.call('notifications/announcements', 3)).data.length, 2);
assert.equal((await f.call('notifications', 2)).data.length, 2, 'dismissed announcements remain in the personal inbox');
});
test('expired or withdrawn announcements stop appearing and Asset may withdraw only their own posts', async t => {
const f = await fixture(t);
await f.publish(1); await f.publish(4); await f.publish(1);
f.notices[2].ExpiresAt = new Date(Date.now() - 1000);
assert.equal((await f.call('notifications/1', 4, 'DELETE')).status, 404);
assert.equal((await f.call('notifications/2', 4, 'DELETE')).status, 200);
assert.deepEqual((await f.call('notifications/announcements')).data.map(n => n.NotificationId), [1]);
assert.equal((await f.call('notifications/3/dismiss', 2, 'PUT')).status, 404);
assert.equal((await f.call('notifications/manage', 1)).data.length, 3);
assert.equal((await f.call('notifications/1', 1, 'DELETE')).status, 200);
assert.equal((await f.call('notifications/announcements')).data.length, 0);
});
test('real borrow decision handler notifies only the owner; other users cannot read, dismiss or see it in popups', async t => {
const f = await fixture(t);
const result = await f.call('asset-borrows/11/process', 4, 'POST', { action: 'rejected', rejectReason: 'Chưa đủ thiết bị' });
assert.equal(result.status, 200);
assert.deepEqual(f.audiences, [{ id: 1, type: 'user', value: '2' }]);
assert.equal((await f.call('notifications', 2)).data.length, 1);
assert.equal((await f.call('notifications', 3)).data.length, 0);
assert.equal((await f.call('notifications/1/read', 3, 'PUT')).status, 404);
assert.equal((await f.call('notifications/1/read', 2, 'PUT')).status, 200);
assert.equal((await f.call('notifications/1/dismiss', 2, 'PUT')).status, 404);
assert.equal((await f.call('notifications/announcements', 2)).data.length, 0);
assert.equal((await f.call('notifications', 3)).unreadCount, 0);
});
test('new notification APIs are protected by the production session middleware', async t => {
const { app } = require('./server');
const server = app.listen(0, '127.0.0.1');
await new Promise(resolve => server.once('listening', resolve));
t.after(() => new Promise(resolve => server.close(resolve)));
const base = `http://127.0.0.1:${server.address().port}`;
for (const [route, method] of [['announcements', 'GET'], ['manage', 'GET'], ['1/dismiss', 'PUT']]) {
const response = await fetch(`${base}/api/notifications/${route}`, { method, headers: { 'x-user-id': '1', 'x-user-role': 'admin' } });
assert.equal(response.status, 401);
}
});
test('unknown authenticated API paths return JSON instead of an HTML error page', async t => {
const f = await fixture(t);
const result = await f.call('notifications/missing-endpoint', 1);
assert.equal(result.status, 404);
assert.equal(result.code, 'API_NOT_FOUND');
assert.equal(result.success, false);
});

View File

@@ -0,0 +1,185 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawn } = require('node:child_process');
const { createExportSqlFixture } = require('./asset-export-sql-fixture');
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
class Browser {
constructor(url) { this.socket = new WebSocket(url); this.nextId = 0; this.pending = new Map(); this.errors = []; }
async open() {
await new Promise((resolve, reject) => { this.socket.addEventListener('open', resolve, { once: true }); this.socket.addEventListener('error', reject, { once: true }); });
this.socket.addEventListener('message', event => {
const message = JSON.parse(event.data);
if (message.method === 'Runtime.exceptionThrown') this.errors.push(message.params.exceptionDetails);
const pending = this.pending.get(message.id); if (!pending) return;
this.pending.delete(message.id); clearTimeout(pending.timer);
if (message.error) pending.reject(new Error(message.error.message)); else pending.resolve(message.result);
});
}
send(method, params = {}) {
return new Promise((resolve, reject) => {
const id = ++this.nextId;
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`Browser timeout: ${method}`)); }, 15000);
this.pending.set(id, { resolve, reject, timer }); this.socket.send(JSON.stringify({ id, method, params }));
});
}
async evaluate(expression) {
const result = await this.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description || result.exceptionDetails.text);
return result.result?.value;
}
async until(expression) {
for (let i = 0; i < 100; i++) { if (await this.evaluate(expression)) return; await delay(100); }
throw new Error(`Browser state timeout: ${expression}`);
}
}
test('Chrome preserves project export proposals and supports immediate manager exports for others on desktop/mobile', {
skip: process.env.ACCMANAGER_EXPORT_BROWSER_TEST !== '1' ? 'Set ACCMANAGER_EXPORT_BROWSER_TEST=1 for isolated Chrome and SQL checks' : false,
timeout: 120000
}, async () => {
const f = await createExportSqlFixture();
const root = path.resolve(__dirname, '..');
const output = path.join(root, 'output/asset-exports'); fs.mkdirSync(output, { recursive: true });
f.app.get('/api/auth/session', (req, res) => res.json({ success: true, user: { ...req.user,
FullName: { 1: 'Nguyễn An', 2: 'Trần Bình', 3: 'Quản lý kho' }[req.user.UserId] } }));
f.app.get('/api/asset-projects', (_req, res) => res.json({ success: true, data: [
{ ProjectId: 1, ProjectName: 'Dự án A' }, { ProjectId: 2, ProjectName: 'Dự án B' }
] }));
f.app.get('/api/users', (_req, res) => res.json({ success: true, data: [
{ UserId: 1, FullName: 'Nguyễn An' }, { UserId: 2, FullName: 'Trần Bình' }, { UserId: 3, FullName: 'Quản lý kho' }
] }));
f.app.use('/api', (_req, res) => res.json({ success: true, data: [], unreadCount: 0, pagination: { total: 0, totalPages: 1 } }));
f.app.get('/test-xlsx.js', (_req, res) => res.sendFile(require.resolve('xlsx/dist/xlsx.full.min.js')));
f.app.get('/test-notiflix.js', (_req, res) => res.type('js').send('window.Notiflix={Notify:{init(){},success(){},failure(){},warning(){}}};'));
f.app.get('/pages/index.html', (_req, res) => res.type('html').send(fs.readFileSync(path.join(root, 'public/pages/index.html'), 'utf8')
.replace('https://cdn.sheetjs.com/xlsx-0.20.3/package/dist/xlsx.full.min.js', '/test-xlsx.js')
.replace('https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-aio-3.2.7.min.js', '/test-notiflix.js')));
f.app.use(require('express').static(path.join(root, 'public')));
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'accmanager-export-chrome-'));
const chrome = spawn(process.env.ACCMANAGER_TEST_CHROME || 'C:/Program Files/Google/Chrome/Application/chrome.exe', [
'--headless=new', '--remote-debugging-port=0', `--user-data-dir=${profile}`, '--no-first-run', '--no-default-browser-check', '--hide-scrollbars', 'about:blank'
], { stdio: 'ignore', windowsHide: true });
let client;
try {
const portFile = path.join(profile, 'DevToolsActivePort');
for (let i = 0; i < 100 && !fs.existsSync(portFile); i++) await delay(100);
const port = Number(fs.readFileSync(portFile, 'utf8').split('\n')[0]);
const targets = await (await fetch(`http://127.0.0.1:${port}/json`)).json();
client = new Browser(targets.find(target => target.type === 'page').webSocketDebuggerUrl); await client.open();
await client.send('Runtime.enable'); await client.send('Page.enable'); await client.send('Network.enable');
await client.send('Emulation.setDeviceMetricsOverride', { width: 1600, height: 1050, deviceScaleFactor: 1, mobile: false });
await client.send('Page.navigate', { url: `${f.origin}/pages/index.html#assets` });
await client.until('typeof app !== "undefined" && app?.assets?.length === 3 && !!document.getElementById("borrowAssetBtn")');
assert.equal(await client.evaluate('!!document.getElementById("exportAssetForOthersBtn")'), false);
await client.evaluate(`document.querySelector('.asset-row-checkbox[data-asset-id="1"]').click(); document.getElementById('borrowAssetBtn').click()`);
await client.until('document.getElementById("borrowAssetModal").classList.contains("open")');
assert.equal(await client.evaluate('document.getElementById("borrowAssetUserInput").value'), 'Nguyễn An');
await client.evaluate('document.getElementById("borrowAssetProjectInput").value="Dự án A"; document.getElementById("borrowQuantityInput").value="2"; document.getElementById("addBorrowProjectBtn").click(); document.querySelector("#borrowAdditionalProjects select").value="Dự án B"; document.querySelector("#borrowAdditionalProjects input").value="1"; document.getElementById("borrowAssetForm").requestSubmit()');
await client.until('app.currentPage === "asset-exports" && !app.assetExportLoading && app.assetExportRequests.length === 1');
assert.equal(await client.evaluate('document.querySelectorAll(".process-asset-export").length'), 0);
assert.equal((await f.pool.request().query('SELECT EndingBalance FROM AssetInventory WHERE AssetId = 1')).recordset[0].EndingBalance, 10);
// Existing batch form remains available to ordinary users.
await client.evaluate('location.hash="#assets"');
await client.until('!!document.getElementById("borrowAssetBtn")');
await client.evaluate(`document.querySelector('.asset-row-checkbox[data-asset-id="1"]').click(); document.querySelector('.asset-row-checkbox[data-asset-id="2"]').click(); document.getElementById('borrowAssetBtn').click()`);
await client.until('document.getElementById("batchAssetExportModal").classList.contains("open")');
await client.evaluate('const project=document.getElementById("batchAssetExportCommonProject"); project.value="Dự án A"; project.dispatchEvent(new Event("change")); document.getElementById("batchAssetExportForm").requestSubmit()');
await client.until('app.currentPage === "asset-exports" && !app.assetExportLoading && app.assetExportRequests.length === 2');
await client.send('Network.setExtraHTTPHeaders', { headers: { 'x-test-user': '3', 'x-test-role': 'asset' } });
await client.send('Page.reload');
await client.until('typeof app !== "undefined" && app?.currentUser?.Role === "asset" && !app.assetExportLoading && document.querySelectorAll(".process-asset-export").length === 4');
await client.evaluate('document.querySelector(".process-asset-export[data-action=approved]").click()');
await client.until('document.getElementById("assetExportProcessModal").classList.contains("open")');
await client.evaluate('document.getElementById("assetExportProcessForm").requestSubmit()');
await client.until('!app.assetExportProcessing && app.assetExportRequests.some(row=>row.RequestStatus === "approved")');
assert.equal((await f.pool.request().query('SELECT EndingBalance FROM AssetInventory WHERE AssetId = 1')).recordset[0].EndingBalance, 9);
await client.evaluate('document.querySelector(".process-asset-export[data-action=rejected]").click()');
await client.until('document.getElementById("assetExportProcessModal").classList.contains("open")');
await client.evaluate('document.getElementById("assetExportRejectReason").value="Điều chỉnh số lượng theo dự án"; document.getElementById("assetExportProcessForm").requestSubmit()');
await client.until('!app.assetExportProcessing && app.assetExportRequests.some(row=>row.RequestStatus === "rejected")');
await client.send('Network.setExtraHTTPHeaders', { headers: { 'x-test-user': '1', 'x-test-role': 'user' } });
await client.send('Page.reload');
await client.until('typeof app !== "undefined" && app?.currentUser?.Role === "user" && !app.assetExportLoading && app.assetExportRequests.length === 2');
await client.send('Page.captureScreenshot', { format: 'png' }).then(result => fs.writeFileSync(path.join(output, 'requests.png'), Buffer.from(result.data, 'base64')));
await client.evaluate('document.querySelector(".view-asset-export-document").click()');
await client.until('document.getElementById("assetExportPreviewContent").textContent.includes("Dự án A")');
await client.evaluate('document.querySelector("[data-close-modal=assetExportPreviewModal]").click(); app.downloadBlobFile=(blob,name)=>{window.savedDownload={size:blob.size,name}}; document.querySelector(".download-asset-export-document").click()');
await client.until('window.savedDownload?.size > 1000');
// A failed reload clears stale rows and offers a useful retry.
await client.evaluate('window.originalExportFetch=window.fetch; window.fetch=(url,options)=>String(url).includes("asset-export-requests") ? Promise.resolve({ok:false,json:async()=>({success:false,message:"Không tải được danh sách thử nghiệm"})}) : originalExportFetch(url,options); document.getElementById("refreshAssetExportsBtn").click()');
await client.until('!app.assetExportLoading && !!app.assetExportLoadError');
assert.equal(await client.evaluate('app.assetExportRequests.length'), 0);
await client.evaluate('window.fetch=window.originalExportFetch; document.getElementById("refreshAssetExportsBtn").click()');
await client.until('!app.assetExportLoading && app.assetExportRequests.length === 2');
await client.evaluate('document.getElementById("assetExportHistoryTab").click()');
assert.equal(await client.evaluate('!!document.getElementById("assetExportHistoryModal")'), false);
await client.send('Page.captureScreenshot', { format: 'png' }).then(result => fs.writeFileSync(path.join(output, 'desktop.png'), Buffer.from(result.data, 'base64')));
await client.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
await delay(250);
assert.equal(await client.evaluate('document.documentElement.scrollWidth <= innerWidth + 1'), true);
await client.send('Page.captureScreenshot', { format: 'png' }).then(result => fs.writeFileSync(path.join(output, 'mobile.png'), Buffer.from(result.data, 'base64')));
await client.send('Network.setExtraHTTPHeaders', { headers: { 'x-test-user': '2', 'x-test-role': 'user' } });
await client.send('Page.reload');
await client.until('typeof app !== "undefined" && app?.currentUser?.UserId === 2 && !app.assetExportLoading && !!document.getElementById("assetExportsTableBody")');
assert.equal(await client.evaluate('app.assetExportRequests.length'), 0);
assert.equal(await client.evaluate('!!document.getElementById("createAssetExportForOthersBtn")'), false);
// The additional manager action exports immediately; the proposal action remains available.
await client.send('Network.setExtraHTTPHeaders', { headers: { 'x-test-user': '3', 'x-test-role': 'admin' } });
await client.send('Page.reload');
await client.until('typeof app !== "undefined" && app?.currentUser?.Role === "admin" && !!document.getElementById("createAssetExportForOthersBtn")');
await client.evaluate('document.getElementById("createAssetExportForOthersBtn").click()');
await client.until('typeof app !== "undefined" && app?.currentUser?.Role === "admin" && app.assets.length === 3 && !!document.getElementById("exportAssetForOthersBtn")');
await client.evaluate(`app.downloadBlobFile=(blob,name)=>{window.savedDownload={size:blob.size,name}}; document.querySelector('.asset-row-checkbox[data-asset-id="1"]').click(); document.getElementById('exportAssetForOthersBtn').click()`);
await client.until('document.getElementById("borrowAssetModal").classList.contains("open")');
assert.equal(await client.evaluate('document.getElementById("borrowAssetRecipientInput").required'), true);
assert.equal(await client.evaluate('document.getElementById("borrowAssetRequesterField").hidden'), true);
await client.evaluate('document.getElementById("borrowAssetRecipientInput").value="Trần Bình"; document.getElementById("borrowAssetProjectInput").value="Dự án A"; const quantity=document.getElementById("borrowQuantityInput"); quantity.value="2"; quantity.dispatchEvent(new Event("input",{bubbles:true})); document.querySelector("#borrowAssetForm button[type=submit]").scrollIntoView({block:"nearest"})');
await delay(250);
assert.equal(await client.evaluate('document.querySelector("#borrowAssetForm button[type=submit]").getBoundingClientRect().bottom <= innerHeight'), true);
assert.equal(await client.evaluate('document.documentElement.scrollWidth <= innerWidth + 1'), true);
await client.send('Page.captureScreenshot', { format: 'png' }).then(result => fs.writeFileSync(path.join(output, 'export-for-others-mobile.png'), Buffer.from(result.data, 'base64')));
await client.evaluate('document.getElementById("borrowAssetForm").requestSubmit()');
await client.until('!app.assetExportSubmitting && app.assets.find(row=>row.AssetId===1).EndingBalance===7 && window.savedDownload?.size>1000');
assert.equal((await f.pool.request().query('SELECT COUNT(*) AS total FROM AssetExportRequests')).recordset[0].total, 2);
assert.equal(await client.evaluate('location.hash'), '#assets');
await client.evaluate(`app.closeModals(); document.querySelector('.asset-row-checkbox[data-asset-id="1"]').click(); document.getElementById('borrowAssetBtn').click()`);
await client.until('document.getElementById("borrowAssetModal").classList.contains("open")');
assert.equal(await client.evaluate('document.getElementById("borrowAssetForm").dataset.exportForOthers'), 'false');
assert.equal(await client.evaluate('document.getElementById("borrowAssetRecipientInput").disabled'), true);
assert.equal(await client.evaluate('document.querySelector("#borrowAssetForm button[type=submit]").textContent'), 'Gửi đơn chờ duyệt');
// The asset role can export multiple items for a recipient in one saved document.
await client.send('Network.setExtraHTTPHeaders', { headers: { 'x-test-user': '3', 'x-test-role': 'asset' } });
await client.send('Page.reload');
await client.until('typeof app !== "undefined" && app?.currentUser?.Role === "asset" && app.assets.length === 3 && !!document.getElementById("exportAssetForOthersBtn")');
await client.send('Emulation.setDeviceMetricsOverride', { width: 1600, height: 1050, deviceScaleFactor: 1, mobile: false });
await client.evaluate(`app.downloadBlobFile=(blob,name)=>{window.savedDownload={size:blob.size,name}}; document.querySelector('.asset-row-checkbox[data-asset-id="1"]').click(); document.querySelector('.asset-row-checkbox[data-asset-id="2"]').click(); document.getElementById('exportAssetForOthersBtn').click()`);
await client.until('document.getElementById("batchAssetExportModal").classList.contains("open")');
await client.evaluate('document.getElementById("batchAssetExportRecipientInput").value="Nguyễn An"; const common=document.getElementById("batchAssetExportCommonProject"); common.value="Dự án B"; common.dispatchEvent(new Event("change"))');
await client.send('Page.captureScreenshot', { format: 'png' }).then(result => fs.writeFileSync(path.join(output, 'batch-export-for-others.png'), Buffer.from(result.data, 'base64')));
await client.evaluate('document.getElementById("batchAssetExportForm").requestSubmit()');
await client.until('!app.assetExportSubmitting && app.assets.find(row=>row.AssetId===1).EndingBalance===6 && window.savedDownload?.size>1000');
assert.equal((await f.pool.request().query('SELECT EndingBalance FROM AssetInventory WHERE AssetId = 2')).recordset[0].EndingBalance, 3);
assert.equal((await f.pool.request().query('SELECT COUNT(*) AS total FROM AssetExportRequests')).recordset[0].total, 2);
const saved = (await f.pool.request().query('SELECT SnapshotJson FROM AssetExportDocuments ORDER BY ExportedDate DESC')).recordset;
assert.equal(JSON.parse(saved[0].SnapshotJson).requesterName, 'Nguyễn An');
assert.equal(JSON.parse(saved[1].SnapshotJson).requesterName, 'Trần Bình');
await client.evaluate(`app.closeModals(); document.querySelector('.asset-row-checkbox[data-asset-id="1"]').click(); document.querySelector('.asset-row-checkbox[data-asset-id="2"]').click(); document.getElementById('borrowAssetBtn').click()`);
await client.until('document.getElementById("batchAssetExportModal").classList.contains("open")');
assert.equal(await client.evaluate('document.getElementById("batchAssetExportForm").dataset.exportForOthers'), 'false');
assert.equal(await client.evaluate('document.getElementById("batchAssetExportRecipientInput").disabled'), true);
assert.deepEqual(client.errors, []);
} catch (err) {
if (client) console.error('Browser failure state:', await client.evaluate(`({ url: location.href,
role: typeof app !== 'undefined' && app?.currentUser?.Role, page: typeof app !== 'undefined' && app?.currentPage,
assets: typeof app !== 'undefined' && app?.assets?.length, errors: document.body.innerText.slice(-500) })`), client.errors);
throw err;
} finally {
if (client) client.socket.close();
chrome.kill();
await f.cleanup();
}
});

View File

@@ -0,0 +1,135 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const sql = require('mssql');
const XLSX = require('xlsx');
const { createExportSqlFixture } = require('./asset-export-sql-fixture');
test('managers export for another recipient immediately while pending proposals remain separate', {
skip: process.env.ACCMANAGER_EXPORT_SQL_TEST !== '1' ? 'Set ACCMANAGER_EXPORT_SQL_TEST=1 for a disposable database' : false,
timeout: 120000
}, async () => {
const f = await createExportSqlFixture();
try {
const allocations = [{ projectName: 'Dự án A', quantity: 2 }, { projectName: 'Dự án B', quantity: 1 }];
const stock = async id => (await f.pool.request().input('id', sql.Int, id)
.query('SELECT EndingBalance, Borrower FROM AssetInventory WHERE AssetId = @id')).recordset[0];
const payload = { borrowerName: 'Trần Bình', allocations, note: 'Cấp cho người khác' };
for (const endpoint of ['/assets/1/export', '/assets/export']) {
assert.equal((await f.request(endpoint, { method: 'POST', body: payload })).status, 403);
}
const pending = await f.request('/asset-export-requests', { user: 3, role: 'admin', method: 'POST', body: {
borrowerName: 'Trần Bình', items: [{ assetId: 1, allocations }]
} });
assert.equal(pending.data.RequestStatus, 'pending'); assert.equal(pending.data.RequesterName, 'Quản lý kho');
assert.equal((await stock(1)).EndingBalance, 10);
const single = await f.request('/assets/1/export', { user: 3, role: 'admin', method: 'POST', body: payload });
assert.equal(single.status, 200); assert.equal(single.data.length, 2);
assert.equal((await stock(1)).EndingBalance, 7); assert.equal((await stock(1)).Borrower, null);
const document = await f.request(`/asset-export-documents/${single.document.documentId}`, { user: 3, role: 'admin' });
assert.equal(document.data.snapshot.borrowerName, 'Trần Bình');
assert.equal(document.data.snapshot.exportedByName, 'Quản lý kho');
const download = await f.request(`/asset-export-documents/${single.document.documentId}/download`, { user: 3, role: 'admin' });
assert.deepEqual(download.buffer, Buffer.from(single.document.contentBase64, 'base64'));
assert.ok(XLSX.read(download.buffer).Sheets.ycxvt);
const batch = await f.request('/assets/export', { user: 3, role: 'asset', method: 'POST', body: {
borrowerName: 'Nguyễn An', items: [{ assetId: 1, projectName: 'Dự án B', quantity: 1 },
{ assetId: 2, projectName: 'Dự án A', quantity: 2 }]
} });
assert.equal(batch.status, 200); assert.equal(batch.data.length, 2);
assert.equal((await stock(1)).EndingBalance, 6); assert.equal((await stock(2)).EndingBalance, 3);
const requests = await f.request('/asset-export-requests', { user: 3, role: 'asset' });
assert.equal(requests.data.length, 1); assert.equal(requests.data[0].RequestStatus, 'pending');
const failed = await f.request('/assets/export', { user: 3, role: 'asset', method: 'POST', body: {
borrowerName: 'Trần Bình', items: [{ assetId: 1, projectName: 'A', quantity: 1 },
{ assetId: 2, projectName: 'A', quantity: 100 }]
} });
assert.equal(failed.status, 400);
assert.equal((await stock(1)).EndingBalance, 6); assert.equal((await stock(2)).EndingBalance, 3);
assert.equal((await f.pool.request().query('SELECT COUNT(*) AS total FROM AssetExportDocuments')).recordset[0].total, 2);
} finally { await f.cleanup(); }
});
test('SQL project export approvals preserve stock, ownership, documents, return isolation and concurrent decisions', {
skip: process.env.ACCMANAGER_EXPORT_SQL_TEST !== '1' ? 'Set ACCMANAGER_EXPORT_SQL_TEST=1 for a disposable database' : false,
timeout: 120000
}, async () => {
const f = await createExportSqlFixture();
try {
const items = [{ assetId: 1, allocations: [{ projectName: 'Dự án A', quantity: 2 }, { projectName: 'Dự án B', quantity: 3 }] },
{ assetId: 2, allocations: [{ projectName: 'Dự án A', quantity: 2 }] }];
const stock = async id => (await f.pool.request().query(`SELECT * FROM AssetInventory WHERE AssetId = ${id}`)).recordset[0];
const count = async table => (await f.pool.request().query(`SELECT COUNT(*) AS total FROM ${table}`)).recordset[0].total;
const create = (rows = items, user = 1) => f.request('/asset-export-requests', { user, method: 'POST', body: {
items: rows, note: 'Cấp tài sản vào dự án', createdBy: 2, borrowerName: 'Tên giả mạo', requestStatus: 'approved'
} });
const process = (id, action = 'approved', extra = {}) => f.request(`/asset-export-requests/${id}/process`, {
role: 'asset', user: 3, method: 'POST', body: { action, ...extra }
});
const created = await create();
assert.equal(created.status, 201); assert.equal(created.data.RequestStatus, 'pending');
assert.equal(created.data.CreatedBy, 1); assert.equal(created.data.RequesterName, 'Nguyễn An');
assert.equal((await stock(1)).EndingBalance, 10); assert.equal(await count('AssetExportDocuments'), 0);
const id = created.data.ExportRequestId;
assert.equal((await f.request(`/asset-export-requests/${id}/process`, { method: 'POST', body: { action: 'approved' } })).status, 403);
assert.equal((await f.request('/asset-export-requests', { user: 2 })).data.length, 0);
assert.equal((await f.request('/asset-export-requests', { user: 3, role: 'admin' })).data.length, 1);
// Existing privileged export endpoints remain privileged.
assert.equal((await f.request('/assets/1/export', { method: 'POST', body: items[0] })).status, 403);
const approved = await process(id);
assert.equal(approved.status, 200); assert.equal(approved.data.RequestStatus, 'approved');
assert.equal((await stock(1)).EndingBalance, 5); assert.equal((await stock(1)).ExportInPeriod, 5);
assert.equal((await stock(1)).Borrower, null); assert.equal((await stock(2)).EndingBalance, 3);
assert.equal(await count('AssetBorrowRequests'), 0); assert.equal(await count('AssetExportHistory'), 3);
const allocations = JSON.parse((await stock(1)).ProjectAllocations);
assert.deepEqual(allocations.map(row => [row.projectName, row.quantity, row.allocationType]), [['Dự án A', 2, 'export'], ['Dự án B', 3, 'export']]);
assert.equal((await f.request('/asset-export-history', { user: 2 })).data.length, 0);
assert.equal((await f.request('/asset-export-history')).data.length, 3);
const docId = approved.data.ExportDocumentId;
const preview = await f.request(`/asset-export-documents/${docId}`);
assert.equal(preview.status, 200); assert.equal(preview.data.snapshot.requesterName, 'Nguyễn An');
assert.equal(preview.data.snapshot.exportedByName, 'Quản lý kho');
const downloaded = await f.request(`/asset-export-documents/${docId}/download`);
assert.equal(downloaded.status, 200);
assert.deepEqual(downloaded.buffer, Buffer.from(approved.document.contentBase64, 'base64'));
const workbook = XLSX.read(downloaded.buffer); assert.ok(workbook.Sheets.ycxvt);
assert.equal((await f.request(`/asset-export-documents/${docId}`, { user: 2 })).status, 404);
assert.equal((await f.request(`/asset-export-documents/${docId}/download`, { user: 2 })).status, 404);
assert.equal((await process(id)).status, 409); assert.equal((await stock(1)).EndingBalance, 5);
// A user cannot return the permanent allocation through the loan API.
assert.equal((await f.request('/asset-borrows', { method: 'POST', body: { assetId: 1, requestType: 'return', quantity: 1 } })).status, 400);
// Borrow and return two pieces; the five permanent pieces stay issued.
const borrowed = await f.request('/asset-borrows', { method: 'POST', body: { assetId: 1, requestType: 'borrow', quantity: 2 } });
const borrowId = borrowed.data.borrowId;
assert.equal((await f.request(`/asset-borrows/${borrowId}/process`, { user: 3, role: 'asset', method: 'POST', body: { action: 'approved' } })).status, 200);
assert.equal((await stock(1)).EndingBalance, 3);
const returned = await f.request(`/asset-borrows/${borrowId}/return`, { method: 'POST', body: { quantity: 2 } });
assert.equal((await f.request(`/asset-borrows/${returned.data.borrowId}/process`, { user: 3, role: 'asset', method: 'POST', body: { action: 'approved' } })).status, 200);
assert.equal((await stock(1)).EndingBalance, 5); assert.equal((await stock(1)).ExportInPeriod, 5);
assert.deepEqual(JSON.parse((await stock(1)).ProjectAllocations), allocations);
// Rejection never consumes inventory; approval rechecks current stock.
const rejected = await create([{ assetId: 1, projectName: 'Dự án C', quantity: 1 }], 2);
assert.equal((await process(rejected.data.ExportRequestId, 'rejected')).status, 400);
assert.equal((await process(rejected.data.ExportRequestId, 'rejected', { rejectReason: 'Chưa phù hợp' })).status, 200);
assert.equal((await stock(1)).EndingBalance, 5);
const a = await create([{ assetId: 3, projectName: 'Dự án A', quantity: 3 }]);
const b = await create([{ assetId: 3, projectName: 'Dự án B', quantity: 3 }], 2);
const races = await Promise.all([process(a.data.ExportRequestId), process(b.data.ExportRequestId)]);
assert.deepEqual(races.map(row => row.status).sort(), [200, 400]); assert.equal((await stock(3)).EndingBalance, 1);
const same = await create([{ assetId: 3, projectName: 'Dự án C', quantity: 1 }]);
assert.deepEqual((await Promise.all([process(same.data.ExportRequestId), process(same.data.ExportRequestId)])).map(row => row.status).sort(), [200, 409]);
assert.equal((await stock(3)).EndingBalance, 0);
// Failure in history after file/stock writes rolls the entire approval back.
const failing = await create([{ assetId: 1, projectName: 'FAIL', quantity: 1 }]);
const documentsBefore = await count('AssetExportDocuments');
await f.pool.request().query("ALTER TABLE AssetExportHistory ADD CONSTRAINT CK_ExportTest_Failure CHECK (ProjectName <> 'FAIL')");
assert.equal((await process(failing.data.ExportRequestId)).status, 500);
assert.equal((await stock(1)).EndingBalance, 5); assert.equal(await count('AssetExportDocuments'), documentsBefore);
assert.equal((await f.request('/asset-export-requests')).data.find(row => row.ExportRequestId === failing.data.ExportRequestId).RequestStatus, 'pending');
// An archived line prevents all other lines in that approval from being issued.
const archived = await create([{ assetId: 1, projectName: 'A', quantity: 1 }, { assetId: 2, projectName: 'A', quantity: 1 }]);
await f.pool.request().query('UPDATE AssetInventory SET IsArchived = 1 WHERE AssetId = 2');
assert.equal((await process(archived.data.ExportRequestId)).status, 404);
assert.equal((await stock(1)).EndingBalance, 5); assert.equal(await count('AssetExportDocuments'), documentsBefore);
assert.equal((await f.request(`/asset-export-documents/${docId}/download`)).buffer.equals(downloaded.buffer), true);
} finally { await f.cleanup(); }
});

View File

@@ -0,0 +1,176 @@
const fs = require('node:fs');
const path = require('node:path');
const express = require('express');
const { normalizeExportAllocations } = require('./asset-project-allocations');
async function ensureAssetExportRequestSchema(pool) {
await pool.request().batch(fs.readFileSync(path.join(__dirname, 'asset-export-requests.sql'), 'utf8'));
}
function normalizeExportItems(rawItems) {
if (!Array.isArray(rawItems) || !rawItems.length || rawItems.length > 100) {
throw new Error('Vui lòng chọn từ 1 đến 100 tài sản.');
}
const seen = new Set();
const items = rawItems.map(row => {
const assetId = Number(row?.assetId);
if (!Number.isSafeInteger(assetId) || assetId <= 0 || assetId > 2147483647) throw new Error('Mã tài sản không hợp lệ.');
if (seen.has(assetId)) throw new Error('Mỗi tài sản chỉ được xuất hiện một lần trong phiếu.');
seen.add(assetId);
return { assetId, allocations: normalizeExportAllocations(row) };
});
if (items.reduce((sum, item) => sum + item.allocations.length, 0) > 100) {
throw new Error('Một phiếu chỉ hỗ trợ tối đa 100 dòng tài sản / dự án.');
}
return items;
}
function createAssetExportWorkflow({ getPool, sql, requireManage, getRequesterRole, getUserIdFromRequest,
getUserDisplayNameById, prepareAssetExport, performAssetExport, sendInternalError, notifyProcessed, notifyCreated }) {
const router = express.Router();
const canManage = req => ['admin', 'asset'].includes(getRequesterRole(req));
const serialize = row => ({ ...row, Items: JSON.parse(row.ItemsJson), ItemsJson: undefined });
const fail = (statusCode, message) => { throw Object.assign(new Error(message), { statusCode }); };
async function handleError(transaction, res, err) {
if (transaction) {
try { await transaction.rollback(); } catch { /* Preserve the original failure. */ }
}
if (err.statusCode) return res.status(err.statusCode).json({ success: false, message: err.message });
return sendInternalError(res, err);
}
async function loadPlans(transaction, items, note) {
const assets = new Map();
// Use the same order for overlapping requests so approvals cannot overdraw stock.
for (const { assetId } of [...items].sort((a, b) => a.assetId - b.assetId)) {
const result = await new sql.Request(transaction).input('assetId', sql.Int, assetId).query(`
SELECT TOP 1 AssetId, AssetCode, AssetName, Quantity, ImportInPeriod, ExportInPeriod,
EndingBalance, NewQuantity, UsedQuantity, Custodian, Borrower, ProjectAllocations,
Model, SerialNumber, Unit, Department, Notes
FROM AssetInventory WITH (UPDLOCK, HOLDLOCK)
WHERE AssetId = @assetId AND IsArchived = 0
`);
if (!result.recordset?.[0]) fail(404, `Tài sản #${assetId} không còn trong danh mục hiện tại.`);
assets.set(assetId, result.recordset[0]);
}
return items.map(item => prepareAssetExport(assets.get(item.assetId), item.allocations, note));
}
async function createRequest(req, res, singleAssetId) {
let transaction;
try {
let items;
try {
items = normalizeExportItems(singleAssetId === undefined ? req.body?.items : [{ ...req.body, assetId: singleAssetId }]);
} catch (err) { fail(400, err.message); }
const createdBy = getUserIdFromRequest(req);
const requesterName = String(await getUserDisplayNameById(createdBy) || req.user?.FullName || req.user?.Username || '').trim();
if (!createdBy || !requesterName || requesterName.length > 100) fail(400, 'Không xác định được người đề xuất hợp lệ.');
const note = String(req.body?.note || '').trim() || null;
if (note && note.length > 1000) fail(400, 'Ghi chú xuất tối đa 1000 ký tự.');
transaction = new sql.Transaction(getPool());
await transaction.begin();
const plans = await loadPlans(transaction, items, note);
// Preserve the requested descriptions even if the catalog is later edited or archived.
const snapshot = plans.map(plan => ({ assetId: plan.asset.AssetId, assetCode: plan.asset.AssetCode,
assetName: plan.asset.AssetName, model: plan.asset.Model, unit: plan.asset.Unit, allocations: plan.allocations }));
const result = await new sql.Request(transaction)
.input('requesterName', sql.NVarChar(100), requesterName)
.input('itemsJson', sql.NVarChar(sql.MAX), JSON.stringify(snapshot))
.input('requestNote', sql.NVarChar(1000), note)
.input('createdBy', sql.Int, createdBy)
.query(`INSERT INTO AssetExportRequests (RequesterName, ItemsJson, RequestNote, CreatedBy)
OUTPUT INSERTED.* VALUES (@requesterName, @itemsJson, @requestNote, @createdBy)`);
await transaction.commit();
transaction = undefined;
if (notifyCreated) await notifyCreated(result.recordset[0]);
return res.status(201).json({ success: true, message: 'Đã gửi đơn xuất dự án, chờ admin/asset duyệt.', data: serialize(result.recordset[0]) });
} catch (err) { return handleError(transaction, res, err); }
}
// Keep the existing manager-only export API for integrations. The UI submits
// proposals through this router; approval uses the same atomic stock writer.
async function directExport(req, res, singleAssetId) {
let transaction;
try {
let items;
try { items = normalizeExportItems(singleAssetId === undefined ? req.body?.items : [{ ...req.body, assetId: singleAssetId }]); }
catch (err) { fail(400, err.message); }
const requesterName = String(req.body?.borrowerName || req.body?.custodianName || '').trim();
const exportNote = String(req.body?.note || '').trim() || null;
if (!requesterName || requesterName.length > 100) fail(400, 'Vui lòng chọn người đề nghị xuất, tối đa 100 ký tự.');
if (exportNote && exportNote.length > 1000) fail(400, 'Ghi chú xuất tối đa 1000 ký tự.');
const createdBy = getUserIdFromRequest(req);
const exportedByName = await getUserDisplayNameById(createdBy) || req.user?.FullName || req.user?.Username;
transaction = new sql.Transaction(getPool());
await transaction.begin();
const plans = await loadPlans(transaction, items, exportNote);
const exported = await performAssetExport(transaction, plans, { createdBy, requesterName, exportedByName, exportNote });
await transaction.commit();
res.json({ success: true, message: 'Xuất tài sản vào dự án thành công.',
data: singleAssetId !== undefined && req.body.allocations === undefined ? exported.histories[0] : exported.histories,
document: exported.document });
} catch (err) { return handleError(transaction, res, err); }
}
router.get('/', async (req, res) => {
try {
const result = await getPool().request().input('requesterId', sql.Int, getUserIdFromRequest(req) || -1).query(`
SELECT r.*, d.FileName AS DocumentFileName FROM AssetExportRequests r
LEFT JOIN AssetExportDocuments d ON d.ExportDocumentId = r.ExportDocumentId
${canManage(req) ? '' : 'WHERE r.CreatedBy = @requesterId'}
ORDER BY r.CreatedDate DESC, r.ExportRequestId DESC
`);
res.setHeader('Cache-Control', 'private, no-store');
res.json({ success: true, data: result.recordset.map(serialize) });
} catch (err) { sendInternalError(res, err); }
});
router.post('/', (req, res) => createRequest(req, res));
router.post('/:id/process', requireManage, async (req, res) => {
let transaction;
try {
const requestId = Number(req.params.id);
const action = req.body?.action;
const rejectReason = String(req.body?.rejectReason || '').trim() || null;
if (!Number.isSafeInteger(requestId) || requestId <= 0 || requestId > 2147483647) fail(400, 'Mã đơn không hợp lệ.');
if (!['approved', 'rejected'].includes(action)) fail(400, 'Hành động không hợp lệ.');
if (action === 'rejected' && (!rejectReason || rejectReason.length > 1000)) fail(400, 'Vui lòng nhập lý do từ chối, tối đa 1000 ký tự.');
const processedBy = getUserIdFromRequest(req);
const processedByName = await getUserDisplayNameById(processedBy) || req.user?.FullName || req.user?.Username;
transaction = new sql.Transaction(getPool());
await transaction.begin();
const result = await new sql.Request(transaction).input('requestId', sql.Int, requestId).query(`
SELECT * FROM AssetExportRequests WITH (UPDLOCK, HOLDLOCK) WHERE ExportRequestId = @requestId
`);
const target = result.recordset[0];
if (!target) fail(404, 'Không tìm thấy đơn xuất.');
if (target.RequestStatus !== 'pending') fail(409, 'Đơn xuất đã được xử lý trước đó.');
let exported;
if (action === 'approved') {
const items = normalizeExportItems(JSON.parse(target.ItemsJson));
const plans = await loadPlans(transaction, items, target.RequestNote);
exported = await performAssetExport(transaction, plans, { createdBy: target.CreatedBy,
requesterName: target.RequesterName, exportedByName: processedByName, exportNote: target.RequestNote });
}
const saved = await new sql.Request(transaction)
.input('requestId', sql.Int, requestId)
.input('status', sql.NVarChar(20), action)
.input('rejectReason', sql.NVarChar(1000), action === 'rejected' ? rejectReason : null)
.input('processedBy', sql.Int, processedBy)
.input('processedByName', sql.NVarChar(100), processedByName)
.input('documentId', sql.UniqueIdentifier, exported?.document.documentId || null)
.query(`UPDATE AssetExportRequests SET RequestStatus = @status, RejectReason = @rejectReason,
ProcessedBy = @processedBy, ProcessedByName = @processedByName,
ProcessedDate = DATEADD(HOUR, 7, SYSUTCDATETIME()), ExportDocumentId = @documentId
OUTPUT INSERTED.* WHERE ExportRequestId = @requestId`);
await transaction.commit();
transaction = undefined;
if (notifyProcessed) await notifyProcessed(target, action, rejectReason);
res.json({ success: true, message: action === 'approved' ? 'Đã duyệt và xuất tài sản khỏi kho.' : 'Đã từ chối đơn xuất.',
data: serialize(saved.recordset[0]), document: exported?.document });
} catch (err) { return handleError(transaction, res, err); }
});
return { router, createRequest, directExport };
}
module.exports = { ensureAssetExportRequestSchema, normalizeExportItems, createAssetExportWorkflow };

View File

@@ -0,0 +1,31 @@
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
IF OBJECT_ID('dbo.AssetExportRequests', 'U') IS NULL
BEGIN
CREATE TABLE dbo.AssetExportRequests (
ExportRequestId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
RequesterName NVARCHAR(100) NOT NULL,
ItemsJson NVARCHAR(MAX) NOT NULL,
RequestNote NVARCHAR(1000) NULL,
RequestStatus NVARCHAR(20) NOT NULL DEFAULT 'pending',
CreatedBy INT NOT NULL,
CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
ProcessedBy INT NULL,
ProcessedByName NVARCHAR(100) NULL,
ProcessedDate DATETIME NULL,
RejectReason NVARCHAR(1000) NULL,
ExportDocumentId UNIQUEIDENTIFIER NULL,
CONSTRAINT CK_AssetExportRequests_Status CHECK (RequestStatus IN ('pending', 'approved', 'rejected')),
CONSTRAINT FK_AssetExportRequests_User FOREIGN KEY (CreatedBy) REFERENCES dbo.Users(UserId),
CONSTRAINT FK_AssetExportRequests_Document FOREIGN KEY (ExportDocumentId) REFERENCES dbo.AssetExportDocuments(ExportDocumentId)
);
CREATE INDEX IX_AssetExportRequests_Creator ON dbo.AssetExportRequests(CreatedBy, CreatedDate DESC);
CREATE INDEX IX_AssetExportRequests_Status ON dbo.AssetExportRequests(RequestStatus, CreatedDate DESC);
END;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
THROW;
END CATCH;

View File

@@ -0,0 +1,53 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { normalizeExportItems } = require('./asset-export-requests');
const { addProjectExports, releaseAllocations } = require('./asset-project-allocations');
const { createExportTestApp } = require('./asset-export-test-fixture');
test('project export proposals require positive integer quantities, project names and unique inventory IDs', () => {
for (const value of [[], null, [{ assetId: 0, projectName: 'A', quantity: 1 }],
[{ assetId: 1, projectName: '', quantity: 1 }], [{ assetId: 1, projectName: 'A', quantity: 1.5 }],
[{ assetId: 1, projectName: 'A', quantity: -1 }],
[{ assetId: 1, projectName: 'A', quantity: 1 }, { assetId: 1, projectName: 'B', quantity: 1 }],
Array.from({ length: 101 }, (_, i) => ({ assetId: i + 1, projectName: 'A', quantity: 1 }))]) {
assert.throws(() => normalizeExportItems(value));
}
assert.deepEqual(normalizeExportItems([{ assetId: 1, allocations: [
{ projectName: 'Dự án A', quantity: 2 }, { projectName: 'Dự án B', quantity: 3 }
] }])[0].allocations.map(row => row.quantity), [2, 3]);
});
test('permanent project exports consume the existing stock ledger without adding returnable borrowers', () => {
const { prepareAssetExport } = createExportTestApp({});
const asset = { AssetId: 1, AssetCode: 'TS-001', Quantity: 12, ImportInPeriod: 3,
ExportInPeriod: 4, EndingBalance: 11, NewQuantity: 3, UsedQuantity: 8,
Borrower: 'An (2)', ProjectAllocations: JSON.stringify([{ projectName: 'Cũ', borrowerName: '', quantity: 2 }]) };
const plan = prepareAssetExport(asset, [{ projectName: 'Dự án A', quantity: 2 }, { projectName: 'Dự án B', quantity: 3 }], 'Dự án mới');
assert.equal(plan.exportInPeriod, 9);
assert.equal(plan.endingBalance, 6);
assert.equal(plan.newQuantity, 0);
assert.equal(plan.usedQuantity, 6);
assert.equal(plan.borrower, undefined);
assert.equal(asset.Borrower, 'An (2)');
assert.throws(() => prepareAssetExport(asset, [{ projectName: 'A', quantity: 12 }]), /vượt quá/);
assert.throws(() => prepareAssetExport({ ...asset, EndingBalance: 0 }, [{ projectName: 'A', quantity: 1 }]), /hết tồn/);
});
test('returning a loan preserves all quantities permanently issued into projects', () => {
const legacyLoan = [{ projectName: 'Mượn cũ', borrowerName: 'An', quantity: 3 }];
const allocations = addProjectExports(legacyLoan, [{ projectName: 'Dự án A', quantity: 4 }]);
const returned = releaseAllocations(allocations, 'An', 3, 3);
assert.deepEqual(returned, [{ projectName: 'Dự án A', borrowerName: '', quantity: 4, allocationType: 'export' }]);
});
test('production session middleware protects proposal creation, listing and decisions', async t => {
const { productionApp } = createExportTestApp({});
const server = productionApp.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)); });
for (const [path, method] of [['/api/asset-export-requests', 'GET'], ['/api/asset-export-requests', 'POST'],
['/api/asset-export-requests/1/process', 'POST']]) {
const response = await fetch(`http://127.0.0.1:${server.address().port}${path}`, { method });
assert.equal(response.status, 401);
}
});

View File

@@ -0,0 +1,78 @@
const { randomUUID } = require('node:crypto');
const sql = require('mssql');
const { ensureAssetExportDocumentSchema } = require('./asset-export-documents');
const { ensureAssetExportRequestSchema } = require('./asset-export-requests');
const { createExportTestApp } = require('./asset-export-test-fixture');
async function createExportSqlFixture() {
require('dotenv').config();
const database = `AccManagerExportTest_${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: /^(true|1)$/i.test(process.env.DB_ENCRYPT || 'false'),
trustServerCertificate: !/^(false|0)$/i.test(process.env.DB_TRUST_CERTIFICATE || 'true'), useUTC: false },
pool: { min: 0, max: 8, idleTimeoutMillis: 1000 }, connectionTimeout: 15000, requestTimeout: 20000 };
if (process.env.DB_PORT) config.port = Number(process.env.DB_PORT);
let admin, pool, server, created = false;
const cleanup = async () => {
if (server) { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }
if (pool) await pool.close();
if (created) {
if (!/^AccManagerExportTest_[0-9a-f]{32}$/.test(database)) throw new Error('Unsafe test database name');
await admin.request().query(`ALTER DATABASE [${database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [${database}];`);
}
if (admin) await admin.close();
};
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, Username NVARCHAR(100), FullName NVARCHAR(100));
INSERT dbo.Users VALUES (1, 'an', N'Nguyễn An'), (2, 'binh', N'Trần Bình'), (3, 'manager', N'Quản lý kho');
CREATE TABLE dbo.AssetInventory (
AssetId INT PRIMARY KEY, AssetCode NVARCHAR(100), AssetName NVARCHAR(255), Model NVARCHAR(255), SerialNumber NVARCHAR(255),
Quantity INT, ImportInPeriod INT, ExportInPeriod INT, EndingBalance INT, NewQuantity INT, UsedQuantity INT,
Unit NVARCHAR(50), Department NVARCHAR(100), Project NVARCHAR(150), Location NVARCHAR(150), Custodian NVARCHAR(100),
Borrower NVARCHAR(255), ProjectAllocations NVARCHAR(MAX), ExportedBy NVARCHAR(100), Status NVARCHAR(50), Notes NVARCHAR(MAX),
PurchaseDate DATE NULL, PurchasePrice DECIMAL(18,2) NULL, CreatedBy INT NULL,
IsArchived BIT NOT NULL DEFAULT 0, ArchivedDate DATETIME NULL, CreatedDate DATETIME NOT NULL DEFAULT GETDATE(),
UpdatedDate DATETIME NOT NULL DEFAULT GETDATE()
);
INSERT dbo.AssetInventory (AssetId, AssetCode, AssetName, Model, Quantity, ImportInPeriod, ExportInPeriod, EndingBalance, NewQuantity, UsedQuantity, Unit, Custodian, Borrower, ProjectAllocations, Status)
VALUES (1, 'TS-001', N'Máy khoan', 'MK-01', 10, 0, 0, 10, 6, 4, N'cái', N'Quản lý kho', NULL, '[]', 'in_stock'),
(2, 'TS-002', N'Đồng hồ', 'DH-01', 5, 0, 0, 5, 5, 0, N'cái', N'Quản lý kho', NULL, '[]', 'in_stock'),
(3, 'TS-003', N'Động cơ', 'DC-01', 4, 0, 0, 4, 4, 0, N'cái', N'Quản lý kho', NULL, '[]', 'in_stock');
CREATE TABLE dbo.AssetExportHistory (
ExportHistoryId INT IDENTITY PRIMARY KEY, AssetId INT, AssetCode NVARCHAR(100), AssetName NVARCHAR(255),
ExportQuantity INT, ProjectName NVARCHAR(150), CustodianName NVARCHAR(100), ExportedByName NVARCHAR(100),
ExportNote NVARCHAR(1000), CreatedBy INT, ExportedDate DATETIME,
CreatedDate DATETIME NOT NULL DEFAULT GETDATE(), UpdatedDate DATETIME NOT NULL DEFAULT GETDATE()
);
CREATE TABLE dbo.AssetBorrowRequests (
BorrowId INT IDENTITY PRIMARY KEY, AssetId INT, RequestType NVARCHAR(20) DEFAULT 'borrow', RequestStatus NVARCHAR(20) DEFAULT 'pending',
BorrowerName NVARCHAR(100), BorrowQuantity INT, ReturnedQuantity INT DEFAULT 0, Unit NVARCHAR(50), BorrowDate DATE DEFAULT GETDATE(),
RequestNote NVARCHAR(500), RejectReason NVARCHAR(1000), CreatedBy INT, ProcessedBy INT, ProcessedByName NVARCHAR(100),
ProcessedDate DATETIME, CreatedDate DATETIME DEFAULT GETDATE(), UpdatedDate DATETIME DEFAULT GETDATE()
);
CREATE TABLE dbo.AssetBorrowRequestLinks (LinkId INT IDENTITY PRIMARY KEY, BorrowId INT, ReturnId INT, Quantity INT,
CreatedDate DATETIME DEFAULT GETDATE());
`);
await ensureAssetExportDocumentSchema(pool);
await ensureAssetExportRequestSchema(pool);
await ensureAssetExportRequestSchema(pool);
const { app } = createExportTestApp(pool);
server = app.listen(0, '127.0.0.1');
await new Promise(resolve => server.once('listening', resolve));
const origin = `http://127.0.0.1:${server.address().port}`;
const request = async (suffix, { user = 1, role = 'user', method = 'GET', body } = {}) => {
const response = await fetch(`${origin}/api${suffix}`, { method, headers: {
'x-test-user': String(user), 'x-test-role': role, ...(body === undefined ? {} : { 'Content-Type': 'application/json' })
}, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
if (response.headers.get('content-type')?.includes('application/json')) return { status: response.status, ...(await response.json()) };
return { status: response.status, buffer: Buffer.from(await response.arrayBuffer()) };
};
return { pool, app, origin, request, cleanup };
} catch (err) { await cleanup(); throw err; }
}
module.exports = { createExportSqlFixture };

View File

@@ -0,0 +1,48 @@
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const { createRequire } = require('node:module');
const express = require('express');
// Exercise production handlers against isolated SQL/test pools, without sessions
// or notifications touching the application's configured database.
function createExportTestApp(pool, { sql, workbookBuilder } = {}) {
const filename = path.join(__dirname, 'server.js');
const localRequire = createRequire(filename);
const sandbox = {
require(name) {
if (name === 'dotenv') return { config() {} };
if (name === 'mssql' && sql) return sql;
if (name === './export-request-workbook' && workbookBuilder) return { buildExportRequestWorkbook: workbookBuilder };
return localRequire(name);
},
module: { exports: {} }, __dirname, __filename: filename, Buffer, URL, Date, console, testPool: pool,
process: { env: { NODE_ENV: 'test', DATA_ENCRYPTION_SECRET: 'project-export-isolated-test-secret-over-32-characters' }, on() {} }
};
vm.runInNewContext(`${fs.readFileSync(filename, 'utf8')}
pool = testPool;
safeCreateSystemNotification = async () => {};
module.exports.workflow = assetExportWorkflow;
module.exports.prepareAssetExport = prepareAssetExport;
`, sandbox, { filename });
const production = sandbox.module.exports;
const app = express();
app.use(express.json());
app.use((req, res, next) => {
const userId = Number(req.headers['x-test-user'] || 1);
if (!userId) return res.status(401).json({ success: false });
req.user = { UserId: userId, Role: req.headers['x-test-role'] || 'user', FullName: `Người dùng ${userId}` };
next();
});
app.use('/api/asset-export-requests', production.workflow.router);
for (const layer of production.app.router.stack) {
if (!layer.route || !/^\/api\/(asset-export-(history|documents)|asset-borrows|assets)/.test(layer.route.path)) continue;
for (const method of Object.keys(layer.route.methods)) {
// The test server provides identity; retain each route's role guards.
app[method](layer.route.path, ...layer.route.stack.map(entry => entry.handle));
}
}
return { app, productionApp: production.app, prepareAssetExport: production.prepareAssetExport };
}
module.exports = { createExportTestApp };

View File

@@ -0,0 +1,156 @@
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');
function fixture() {
const nodes = { borrowAssetIdInput: { value: '1' }, borrowAssetUserInput: { value: 'An' },
borrowAssetProjectInput: { value: 'Dự án A' }, borrowQuantityInput: { value: '2' }, borrowAssetNoteInput: { value: '' },
borrowAssetForm: { dataset: {} }, borrowAssetRecipientInput: { value: 'Bình' },
batchAssetExportForm: { dataset: {} }, batchAssetExportUserInput: { value: 'An' },
batchAssetExportRecipientInput: { value: 'Bình' }, batchAssetExportNoteInput: { value: '' } };
const requests = [], messages = [], documents = [], refreshes = [];
const button = { disabled: false };
const sandbox = { document: { addEventListener() {}, getElementById: id => nodes[id], querySelector: () => button, querySelectorAll: () => [] },
window: {}, location: { hash: '#assets' }, console,
fetch: async (url, options) => { requests.push({ url, options }); return { ok: true, json: async () => ({
success: true, data: { RequestStatus: 'pending' }, document: { fileName: 'phieu-xuat.xlsx', contentBase64: 'ZmlsZQ==' }
}) }; } };
sandbox.window.fetch = sandbox.fetch;
vm.runInNewContext(`${fs.readFileSync(path.join(__dirname, '../public/js/app.js'), 'utf8')}\napp = Object.create(AccountManager.prototype); globalThis.manager = app;`, sandbox);
const manager = sandbox.manager;
Object.assign(manager, { currentUser: { UserId: 1, Role: 'user', FullName: 'An' }, apiBase: '/api',
selectedAssetIds: new Set([1]), assets: [{ AssetId: 1, AssetCode: 'TS-001', Quantity: 5, ExportInPeriod: 0, EndingBalance: 5 }],
notifySuccess: message => messages.push(message), notifyFailure: message => messages.push(message), notifyWarning: message => messages.push(message),
showExportRequestDocument: file => documents.push(file), refreshAssetsUI: async () => refreshes.push('assets'),
closeModals() {} });
return { manager, sandbox, requests, messages, nodes, button, documents, refreshes };
}
test('ordinary users submit existing project allocations as pending proposals without downloading or changing stock', async () => {
const f = fixture();
await f.manager.handleBorrowAssetSubmit({ preventDefault() {} });
assert.equal(f.requests.length, 1); assert.equal(f.requests[0].url, '/api/asset-export-requests');
assert.deepEqual(JSON.parse(f.requests[0].options.body).items, [{ assetId: 1, allocations: [{ projectName: 'Dự án A', quantity: 2 }] }]);
assert.equal(f.manager.assets[0].EndingBalance, 5); assert.equal(f.manager.lastExportRequestDocument, undefined);
assert.equal(f.sandbox.location.hash, '#asset-exports'); assert.match(f.messages[0], /chờ admin\/asset duyệt/);
assert.equal(f.manager.selectedAssetIds.size, 0); assert.equal(f.button.disabled, false);
});
test('proposal forms block duplicate submissions and retain selection when the server rejects them', async () => {
const f = fixture(); let complete;
f.sandbox.fetch = (url, options) => { f.requests.push({ url, options }); return new Promise(resolve => { complete = resolve; }); };
const first = f.manager.handleBorrowAssetSubmit({ preventDefault() {} });
await f.manager.handleBorrowAssetSubmit({ preventDefault() {} });
assert.equal(f.requests.length, 1); assert.equal(f.button.disabled, true);
complete({ ok: false, json: async () => ({ success: false, message: 'Không đủ tồn' }) });
await first;
assert.equal(f.manager.selectedAssetIds.size, 1); assert.equal(f.button.disabled, false); assert.equal(f.messages[0], 'Không đủ tồn');
});
test('proposal forms reject missing projects, fractional quantities and quantities exceeding stock before submission', async () => {
for (const [field, value] of [['borrowAssetProjectInput', ''], ['borrowQuantityInput', '1.5'], ['borrowQuantityInput', '6']]) {
const f = fixture(); f.nodes[field].value = value;
await f.manager.handleBorrowAssetSubmit({ preventDefault() {} });
assert.equal(f.requests.length, 0); assert.equal(f.messages.length, 1);
}
});
test('export lists filter by creator, status and project, and show processing controls only to managers', () => {
const f = fixture();
const own = { ExportRequestId: 1, CreatedBy: 1, RequesterName: 'An', RequestStatus: 'pending', Items: [
{ assetCode: 'TS-001', assetName: '<Máy khoan>', allocations: [{ projectName: 'Dự án A', quantity: 2 }] }
] };
f.manager.assetExportRequests = [own, { ...own, ExportRequestId: 2, CreatedBy: 2 }];
f.manager.assetExportTab = 'requests';
assert.equal(f.manager.getFilteredAssetExportRows().length, 1);
f.manager.assetExportSearchTerm = 'dự án a'; assert.equal(f.manager.getFilteredAssetExportRows().length, 1);
f.manager.assetExportStatusFilter = 'rejected'; assert.equal(f.manager.getFilteredAssetExportRows().length, 0);
const userRows = f.manager.renderAssetExportRequestsRows([own]);
assert.doesNotMatch(userRows, /process-asset-export|<Máy khoan>/); assert.match(userRows, /&lt;Máy khoan&gt;/);
f.manager.currentUser.Role = 'asset'; assert.match(f.manager.renderAssetExportRequestsRows([own]), /Duyệt xuất/);
});
test('ordinary users cannot invoke the proposal decision UI', async () => {
const f = fixture();
await f.manager.processAssetExportRequest(1, 'approved', '');
assert.equal(f.requests.length, 0);
});
test('admin and asset keep the existing single and batch pending proposal flows', async () => {
for (const role of ['user', 'admin', 'asset']) {
for (const batch of [false, true]) {
const f = fixture(); f.manager.currentUser.Role = role;
f.manager.collectBatchAssetExportItems = () => [{ assetId: 1, allocations: [{ projectName: 'Dự án A', quantity: 2 }] }];
await f.manager[batch ? 'handleBatchAssetExportSubmit' : 'handleBorrowAssetSubmit']({ preventDefault() {} });
assert.equal(f.requests[0].url, '/api/asset-export-requests');
assert.equal(f.documents.length, 0); assert.equal(f.refreshes.length, 0);
assert.match(f.messages[0], /chờ admin\/asset duyệt/);
}
}
});
test('admin and asset can export selected assets to another recipient and download immediately', async () => {
for (const role of ['admin', 'asset']) {
for (const batch of [false, true]) {
const f = fixture(); f.manager.currentUser.Role = role;
f.nodes[batch ? 'batchAssetExportForm' : 'borrowAssetForm'].dataset.exportForOthers = 'true';
f.manager.collectBatchAssetExportItems = () => [{ assetId: 1, allocations: [{ projectName: 'Dự án A', quantity: 2 }] }];
await f.manager[batch ? 'handleBatchAssetExportSubmit' : 'handleBorrowAssetSubmit']({ preventDefault() {} });
assert.equal(f.requests[0].url, batch ? '/api/assets/export' : '/api/assets/1/export');
const body = JSON.parse(f.requests[0].options.body);
assert.equal(body.borrowerName, 'Bình');
assert.deepEqual(batch ? body.items[0].allocations : body.allocations, [{ projectName: 'Dự án A', quantity: 2 }]);
assert.equal(f.documents[0].fileName, 'phieu-xuat.xlsx'); assert.deepEqual(f.refreshes, ['assets']);
assert.equal(f.sandbox.location.hash, '#assets'); assert.equal(f.manager.selectedAssetIds.size, 0);
assert.match(f.messages[0], /Bình/); assert.equal(f.button.disabled, false);
}
}
});
test('exporting for others requires manager permission and a recipient for both forms', async () => {
for (const batch of [false, true]) {
for (const role of ['user', 'admin']) {
const f = fixture(); f.manager.currentUser.Role = role;
f.nodes[batch ? 'batchAssetExportForm' : 'borrowAssetForm'].dataset.exportForOthers = 'true';
f.nodes[batch ? 'batchAssetExportRecipientInput' : 'borrowAssetRecipientInput'].value = '';
f.manager.collectBatchAssetExportItems = () => [{ assetId: 1, allocations: [{ projectName: 'A', quantity: 1 }] }];
await f.manager[batch ? 'handleBatchAssetExportSubmit' : 'handleBorrowAssetSubmit']({ preventDefault() {} });
assert.equal(f.requests.length, 0); assert.equal(f.manager.selectedAssetIds.size, 1);
assert.match(f.messages[0], role === 'user' ? /Asset\/Admin/ : /chọn người nhận/);
}
}
});
test('reopening either form as a proposal clears the direct export mode and recipient validation', () => {
for (const prefix of ['borrowAsset', 'batchAssetExport']) {
const f = fixture();
const form = f.nodes[`${prefix}Form`]; form.querySelector = () => f.button;
for (const suffix of ['RequesterField', 'RecipientField', 'Title', 'Description']) f.nodes[`${prefix}${suffix}`] = {};
f.nodes[`${prefix}RecipientInput`].id = `${prefix}RecipientInput`;
f.manager.populateUserSelectOptions = id => { f.nodes[id].value = ''; };
f.manager.configureAssetExportForm(prefix, true);
assert.equal(form.dataset.exportForOthers, 'true'); assert.equal(f.nodes[`${prefix}RequesterField`].hidden, true);
assert.equal(f.nodes[`${prefix}RecipientInput`].required, true); assert.equal(f.button.textContent, 'Xuất và tải Excel');
f.nodes[`${prefix}RecipientInput`].value = 'Bình';
f.manager.configureAssetExportForm(prefix, false);
assert.equal(form.dataset.exportForOthers, 'false'); assert.equal(f.nodes[`${prefix}RequesterField`].hidden, false);
assert.equal(f.nodes[`${prefix}RecipientField`].hidden, true); assert.equal(f.nodes[`${prefix}RecipientInput`].value, '');
assert.equal(f.nodes[`${prefix}RecipientInput`].disabled, true); assert.equal(f.nodes[`${prefix}RecipientInput`].required, false);
assert.equal(f.button.textContent, 'Gửi đơn chờ duyệt');
}
});
test('direct exports block duplicate submissions and preserve selection on server rejection', async () => {
const f = fixture(); let complete;
f.manager.currentUser.Role = 'asset'; f.nodes.borrowAssetForm.dataset.exportForOthers = 'true';
f.sandbox.fetch = (url, options) => { f.requests.push({ url, options }); return new Promise(resolve => { complete = resolve; }); };
const first = f.manager.handleBorrowAssetSubmit({ preventDefault() {} });
await f.manager.handleBorrowAssetSubmit({ preventDefault() {} });
assert.equal(f.requests.length, 1); assert.equal(f.button.disabled, true);
complete({ ok: false, json: async () => ({ success: false, message: 'Không đủ tồn' }) });
await first;
assert.equal(f.manager.selectedAssetIds.size, 1); assert.equal(f.documents.length, 0);
assert.equal(f.button.disabled, false); assert.equal(f.messages[0], 'Không đủ tồn');
});

View File

@@ -6,7 +6,8 @@ function parseAllocations(value) {
return rows.map(row => ({
projectName: String(row.projectName || '').trim(),
borrowerName: String(row.borrowerName || '').trim(),
quantity: Number(row.quantity)
quantity: Number(row.quantity),
...(row.allocationType === 'export' ? { allocationType: 'export' } : {})
})).filter(row => row.projectName && Number.isSafeInteger(row.quantity) && row.quantity > 0);
}
@@ -38,9 +39,13 @@ function addAllocations(current, rows, borrowerName) {
return [...parseAllocations(current), ...rows.map(row => ({ ...row, borrowerName }))];
}
function addProjectExports(current, rows) {
return [...parseAllocations(current), ...rows.map(row => ({ ...row, borrowerName: '', allocationType: 'export' }))];
}
function releaseAllocations(current, borrowerName, returnedQuantity, borrowerOutstanding) {
const rows = parseAllocations(current);
const matches = row => row.borrowerName.toLowerCase() === borrowerName.toLowerCase();
const matches = row => row.allocationType !== 'export' && row.borrowerName.toLowerCase() === borrowerName.toLowerCase();
const attributed = rows.filter(matches).reduce((sum, row) => sum + row.quantity, 0);
// Older loans without a project (including request-based loans) are consumed first.
let remaining = Math.max(returnedQuantity - Math.max(borrowerOutstanding - attributed, 0), 0);
@@ -53,4 +58,4 @@ function releaseAllocations(current, borrowerName, returnedQuantity, borrowerOut
return rows.filter(row => row.quantity > 0);
}
module.exports = { parseAllocations, normalizeExportAllocations, addAllocations, releaseAllocations };
module.exports = { parseAllocations, normalizeExportAllocations, addAllocations, addProjectExports, releaseAllocations };

131
backend/dashboard.test.js Normal file
View File

@@ -0,0 +1,131 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const source = fs.readFileSync(require.resolve('../public/js/app.js'), 'utf8');
function fixture(fetch = async () => ({ ok: true, json: async () => ({ success: true, data: [] }) })) {
const context = vm.createContext({
window: { fetch }, fetch, console, AbortSignal,
document: { addEventListener() {}, getElementById: () => null, querySelectorAll: () => [] }
});
vm.runInContext(`${source}\nglobalThis.manager = Object.create(AccountManager.prototype);`, context);
const manager = context.manager;
Object.assign(manager, {
assets: [], consumables: [], robots: [], robotTypes: [], accounts: [], applications: [], documents: [],
assetBorrows: [], consumableBorrowRequests: [], assetProjects: [], assetDepartments: [],
currentUser: { Role: 'admin' }, currentPage: 'assets', apiBase: '/api',
dashboardSourceErrors: {}, dashboardLoading: false, dashboardUpdatedAt: null,
selectedAssetIds: new Set(), updatePendingAssetRequestsBadge() {}, updateConsumableBorrowRequestBadges() {}
});
return manager;
}
test('overview counts catalog codes, excludes archived assets and uses available stock calculations', () => {
const manager = fixture();
manager.assets = [
{ AssetId: 1, Quantity: '20', ImportInPeriod: '5', EndingBalance: '25', ExportInPeriod: '0', Unit: 'cái' },
{ AssetId: 2, Quantity: 10, EndingBalance: 7, ExportInPeriod: 3, Unit: 'bộ' },
{ AssetId: 3, Quantity: 2, EndingBalance: 0, ExportInPeriod: 2 },
// An inflated imported balance cannot make a fully allocated asset available.
{ AssetId: 4, Quantity: 3, EndingBalance: 100, ExportInPeriod: 3 },
{ AssetId: 5, Quantity: 1000, IsArchived: 1 }
];
manager.consumables = [{ EndingBalance: '10' }, { EndingBalance: 0 }, { EndingBalance: '0' }];
manager.assetBorrows = [{ RequestStatus: 'pending' }, { RequestStatus: 'approved' }, { RequestStatus: 'rejected' }];
manager.consumableBorrowRequests = [{ RequestStatus: 'pending' }, { RequestStatus: 'approved' }];
const summary = manager.getDashboardSummary();
assert.equal(summary.assets.length, 4);
assert.deepEqual(JSON.parse(JSON.stringify(summary.assetStock)), { inStock: 1, inUse: 1, exported: 2 });
assert.equal(summary.outOfStock.length, 2);
assert.equal(summary.pendingAssets.length + summary.pendingConsumables.length, 2);
const html = manager.renderDashboard();
assert.match(html, /4<span>mã tài sản/);
assert.match(html, /3<span>mã vật tư/);
assert.doesNotMatch(html, /System Overview|Recent Accounts|Add Account/);
});
test('recent updates combine modules, sort by actual timestamps and escape user content', () => {
const manager = fixture();
manager.assets = [{ AssetName: '<img src=x onerror=alert(1)>', Quantity: 1, CreatedDate: '2026-11-01T01:00:00Z' }];
manager.consumables = [{ ConsumableName: 'Vật tư', UpdatedDate: '2026-11-02T01:00:00Z' }];
manager.robots = [{ Name: 'Robot mới', CreatedDate: '2026-11-03T01:00:00Z' }, { Name: 'Robot không có ngày' }];
manager.documents = [{ Title: 'Tài liệu', UploadedDate: '2026-10-31T01:00:00Z' }, { Title: 'Ngày lỗi', UploadedDate: 'invalid' }];
const originalRobots = [...manager.robots];
const summary = manager.getDashboardSummary();
assert.deepEqual(Array.from(summary.recent, row => row.source), ['Robot', 'Vật tư', 'Tài sản', 'Tài liệu']);
assert.equal(manager.robots[0], originalRobots[0]);
const html = manager.renderDashboard();
assert.match(html, /&lt;img src=x onerror=alert\(1\)&gt;/);
assert.doesNotMatch(html, /<img src=x/);
assert.match(html, /03\/11\/2026/);
assert.doesNotMatch(html, /Invalid Date|NaN/);
});
test('empty data and failed modules have distinct states and a failed module does not expose stale counts', () => {
const manager = fixture();
const empty = manager.renderDashboard();
assert.match(empty, /Chưa có tài sản trong danh mục/);
assert.match(empty, /Không có yêu cầu chờ duyệt hoặc vật tư hết tồn/);
manager.assets = [{ Quantity: 10, AssetName: 'Stale asset', CreatedDate: '2026-11-01' }];
manager.dashboardSourceErrors = { assets: 'Tài sản', assetBorrows: 'Yêu cầu tài sản' };
const html = manager.renderDashboard();
assert.match(html, /role="alert"/);
assert.match(html, /—<span>mã tài sản/);
assert.match(html, /Dữ liệu yêu cầu chưa đầy đủ/);
assert.doesNotMatch(html, /Stale asset|Không có yêu cầu chờ duyệt hoặc vật tư hết tồn/);
assert.equal(manager.assets.length, 1);
});
test('refresh uses existing API routes, tolerates one failed module and recovers on retry', async () => {
const requests = [];
let failRobots = true;
const manager = fixture(async (url, options) => {
requests.push({ url, options });
if (url === '/api/robots' && failRobots) throw new Error('Offline');
return { ok: true, json: async () => ({ success: true, data: url === '/api/assets' ? [{ AssetId: 10, Quantity: 5 }] : [] }) };
});
manager.robots = [{ Name: 'Stale robot' }];
await manager.refreshDashboard();
assert.equal(requests.length, 10);
assert.ok(requests.some(request => request.url === '/api/accounts/all'));
assert.ok(requests.some(request => request.url === '/api/robots/types'));
assert.ok(requests.every(request => request.options.cache === 'no-store' && request.options.signal));
assert.equal(manager.assets[0].EndingBalance, 5);
assert.equal(manager.dashboardSourceErrors.robots, 'Robot');
assert.equal(manager.getDashboardSummary().robots.length, 0);
assert.equal(manager.currentPage, 'assets', 'a completed refresh preserves navigation');
assert.equal(manager.dashboardLoading, false);
assert.ok(manager.dashboardUpdatedAt);
failRobots = false;
await manager.refreshDashboard();
assert.equal(Object.keys(manager.dashboardSourceErrors).length, 0);
});
test('refresh rejects unsuccessful HTTP responses and malformed data rather than treating them as empty', async () => {
const manager = fixture(async url => ({
ok: url !== '/api/assets',
json: async () => url === '/api/consumables' ? { success: true, data: null } : { success: true, data: [] }
}));
await manager.refreshDashboard();
assert.equal(manager.dashboardSourceErrors.assets, 'Tài sản');
assert.equal(manager.dashboardSourceErrors.consumables, 'Vật tư tiêu hao');
});
test('overlapping refreshes share the in-progress work instead of issuing a duplicate batch', async () => {
let release;
let requestCount = 0;
const gate = new Promise(resolve => { release = resolve; });
const manager = fixture(async () => {
requestCount++;
await gate;
return { ok: true, json: async () => ({ success: true, data: [] }) };
});
const pending = manager.refreshDashboard();
await manager.refreshDashboard();
assert.equal(requestCount, 10);
release();
await pending;
assert.equal(manager.dashboardLoading, false);
});

View File

@@ -0,0 +1,75 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const source = fs.readFileSync(require.resolve('../public/js/app.js'), 'utf8');
function fixture(fetch) {
const context = vm.createContext({
window: { fetch }, fetch, console, URLSearchParams,
document: { addEventListener() {}, getElementById: () => null }
});
vm.runInContext(`${source}\nglobalThis.manager = Object.create(AccountManager.prototype);`, context);
return Object.assign(context.manager, {
apiBase: '/api', currentPage: 'notification-management', currentUser: { Role: 'admin' },
notificationItems: [], notificationPreviewItems: [], notificationPage: 1, notificationPageSize: 20,
notificationFilter: 'all', notificationSourceFilter: '', notificationUnreadCount: 0,
notificationPagination: { page: 1, total: 0, totalPages: 1 },
renderNotificationsPage() {}, notifyFailure() {}
});
}
test('a missing API or HTML fallback produces an actionable message without a JSON parser error', async () => {
for (const status of [200, 404]) {
const manager = fixture(async () => new Response('<!DOCTYPE html><html>Cannot GET /api/notifications/manage</html>', { status, headers: { 'Content-Type': 'text/html' } }));
await assert.rejects(manager.fetchNotificationJson('/manage'), error => {
assert.match(error.message, /khởi động lại backend/);
assert.doesNotMatch(error.message, /Unexpected token|<!DOCTYPE|Cannot GET/);
return true;
});
}
});
test('proxy errors and invalid JSON have readable errors; JSON business errors keep their original message', async () => {
for (const [response, expected] of [
[new Response('<html>Bad Gateway</html>', { status: 502, headers: { 'Content-Type': 'text/html' } }), /HTTP 502/],
[new Response('{broken', { headers: { 'Content-Type': 'application/json' } }), /không hợp lệ/],
[Response.json({ success: false, message: 'Thông báo đã kết thúc' }, { status: 404 }), /Thông báo đã kết thúc/],
[Response.json({ success: false, code: 'API_NOT_FOUND' }, { status: 404 }), /khởi động lại backend/]
]) {
const manager = fixture(async () => response);
await assert.rejects(manager.fetchNotificationJson('/1/dismiss', { method: 'PUT' }), expected);
}
});
test('notification requests preserve JSON headers and never retry a write automatically', async () => {
const calls = [];
const manager = fixture(async (url, options) => {
calls.push({ url, options });
return Response.json({ success: true });
});
await manager.fetchNotificationJson('', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{"title":"Notice"}' });
assert.equal(calls.length, 1);
assert.equal(calls[0].url, '/api/notifications');
assert.equal(calls[0].options.headers.Accept, 'application/json');
assert.equal(calls[0].options.headers['Content-Type'], 'application/json');
assert.equal(calls[0].options.method, 'POST');
assert.equal(calls[0].options.cache, 'no-store');
});
test('a failed management load shows an error and retry control, then clears both after recovery', async () => {
let offline = true;
const manager = fixture(async () => offline
? new Response('<html>Not found</html>', { status: 404, headers: { 'Content-Type': 'text/html' } })
: Response.json({ success: true, data: [], pagination: { page: 1, total: 0, totalPages: 1 } }));
await manager.refreshNotificationsPage();
assert.equal(manager.notificationLoading, false);
assert.match(manager.getNotificationsContent(), /role="alert"/);
assert.match(manager.getNotificationsContent(), /id="retryNotificationsBtn"/);
assert.doesNotMatch(manager.getNotificationsContent(), /Không có thông báo phù hợp/);
offline = false;
await manager.refreshNotificationsPage();
assert.equal(manager.notificationLoadError, '');
assert.doesNotMatch(manager.getNotificationsContent(), /retryNotificationsBtn/);
assert.match(manager.getNotificationsContent(), /Không có thông báo phù hợp/);
});

View File

@@ -0,0 +1,358 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawn } = require('node:child_process');
const { createBomFixture } = require('./robot-bom-test-fixture');
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
class Browser {
constructor(url) { this.socket = new WebSocket(url); this.nextId = 0; this.pending = new Map(); this.errors = []; }
async open() {
await new Promise((resolve, reject) => { this.socket.addEventListener('open', resolve, { once: true }); this.socket.addEventListener('error', reject, { once: true }); });
this.socket.addEventListener('message', event => {
const message = JSON.parse(event.data);
if (message.method === 'Runtime.exceptionThrown') this.errors.push(message.params.exceptionDetails);
const pending = this.pending.get(message.id);
if (!pending) return;
this.pending.delete(message.id); clearTimeout(pending.timer);
if (message.error) pending.reject(new Error(message.error.message)); else pending.resolve(message.result);
});
}
send(method, params = {}) {
return new Promise((resolve, reject) => {
const id = ++this.nextId;
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`Browser timeout: ${method}`)); }, 15000);
this.pending.set(id, { resolve, reject, timer }); this.socket.send(JSON.stringify({ id, method, params }));
});
}
async evaluate(expression) {
const result = await this.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description || result.exceptionDetails.text);
return result.result?.value;
}
async until(expression) {
for (let i = 0; i < 100; i++) { if (await this.evaluate(expression)) return; await delay(100); }
throw new Error(`Browser state timeout: ${expression}`);
}
}
test('Chrome checks robot confirmations and BOM forms with independent quantities and supplier sources', {
skip: process.env.ACCMANAGER_BOM_BROWSER_TEST !== '1' ? 'Set ACCMANAGER_BOM_BROWSER_TEST=1 for the isolated Chrome UI check' : false,
timeout: 90000
}, async () => {
const root = path.resolve(__dirname, '..');
const output = path.join(root, 'output/bom-robot'); fs.mkdirSync(output, { recursive: true });
let forceSaveFailure = false;
let forceBomDeleteFailure = false;
let failRobotDelete = false;
const robotDeleteRequests = [];
const fixture = createBomFixture({ failQuery: query => (forceSaveFailure && query.includes('INSERT dbo.RobotBomLines'))
|| (forceBomDeleteFailure && query.includes('DELETE FROM dbo.RobotBomRevisions')) });
const review = fixture.app;
const reviewRobots = fixture.state.models.map(robot => ({ ...robot, Name: 'TESTBOM', DocumentCount: 2 }));
review.get('/api/auth/session', (_req, res) => res.json({ success: true, user: { UserId: 1, Username: 'bom-review', FullName: 'Kiểm tra BOM', Role: 'admin' } }));
review.get('/api/robots/types', (_req, res) => res.json({ success: true, data: [{ TypeId: 1, Name: 'AMR' }] }));
review.get('/api/robots', (_req, res) => res.json({ success: true, data: reviewRobots }));
review.delete('/api/robots/:id', (req, res) => {
robotDeleteRequests.push(Number(req.params.id));
if (failRobotDelete) return res.status(500).json({ success: false, message: 'Không thể xóa robot thử nghiệm. Hãy thử lại.' });
const index = reviewRobots.findIndex(robot => robot.RobotId === Number(req.params.id));
if (index < 0) return res.status(404).json({ success: false, message: 'Robot không tồn tại' });
reviewRobots.splice(index, 1); res.json({ success: true, message: 'Đã xóa robot thử nghiệm' });
});
review.use('/api', (_req, res) => res.json({ success: true, data: [], unreadCount: 0, pagination: { total: 0, totalPages: 1 } }));
review.get('/test-xlsx.js', (_req, res) => res.sendFile(require.resolve('xlsx/dist/xlsx.full.min.js')));
review.get('/test-notiflix.js', (_req, res) => res.type('js').send('window.Notiflix={Notify:{init(){},success(){},failure(){},warning(){}}};'));
review.get('/pages/index.html', (_req, res) => {
const source = fs.readFileSync(path.join(root, 'public/pages/index.html'), 'utf8')
.replace('https://cdn.sheetjs.com/xlsx-0.20.3/package/dist/xlsx.full.min.js', '/test-xlsx.js')
.replace('https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-aio-3.2.7.min.js', '/test-notiflix.js');
res.type('html').send(source);
});
review.use(require('express').static(path.join(root, 'public')));
const server = review.listen(0, '127.0.0.1'); await new Promise(resolve => server.once('listening', resolve));
const origin = `http://127.0.0.1:${server.address().port}`;
const chromePath = process.env.ACCMANAGER_TEST_CHROME || 'C:/Program Files/Google/Chrome/Application/chrome.exe';
// Keep browser-managed extension files outside Node's automatic test discovery.
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'accmanager-bom-chrome-'));
const chrome = spawn(chromePath, ['--headless=new', '--remote-debugging-port=0', `--user-data-dir=${profile}`, '--no-first-run', '--no-default-browser-check', '--hide-scrollbars', 'about:blank'], { stdio: 'ignore', windowsHide: true });
let client;
try {
const portFile = path.join(profile, 'DevToolsActivePort');
for (let i = 0; i < 100 && !fs.existsSync(portFile); i++) await delay(100);
const port = Number(fs.readFileSync(portFile, 'utf8').split('\n')[0]);
const targets = await (await fetch(`http://127.0.0.1:${port}/json`)).json();
client = new Browser(targets.find(target => target.type === 'page').webSocketDebuggerUrl); await client.open();
await client.send('Runtime.enable'); await client.send('Page.enable');
await client.send('Page.addScriptToEvaluateOnNewDocument', { source: 'window.confirm=()=>true;window.alert=()=>{};' });
await client.send('Emulation.setDeviceMetricsOverride', { width: 1600, height: 1050, deviceScaleFactor: 1, mobile: false });
await client.send('Page.navigate', { url: `${origin}/pages/index.html#robot-bom` });
await client.until('typeof app !== "undefined" && app?.robotBom?.models.length === 1 && !app.robotBom.busy');
const prepareNotifications = () => client.evaluate('window.bomMessages=[]; app.notifyFailure=app.notifyWarning=app.notifySuccess=(message)=>bomMessages.push(message); true');
await prepareNotifications();
await client.evaluate('document.querySelector("[data-bom-action=new]").click()');
await client.until('app.robotBom.header?.BomId && !app.robotBom.busy');
const entryGeometry = () => client.evaluate(`(() => {
const dialog=document.querySelector('#bomComponentDialog');
const rect=element=>{const value=element.getBoundingClientRect();return [value.x,value.y,value.width,value.height].map(number=>Math.round(number*100)/100)};
return {dialog:rect(dialog),name:rect(dialog.querySelector('[name=name]')),footer:rect(dialog.querySelector('.bom-dialog-footer')),scroll:dialog.querySelector('.bom-material-layout').scrollTop};
})()`);
const add = async ({ id = null, name, model, unit, quantity, sourceInfo = '', screenshot = false }) => {
await client.evaluate('document.querySelector("[data-bom-action=add]").click()');
const opened = await entryGeometry();
if (id !== null) {
await client.until('document.querySelectorAll("#bomComponentDialog [name=assetChoice]").length>0');
await client.evaluate(`document.querySelector('#bomComponentDialog input[name=assetChoice][value="${id}"]').click()`);
assert.equal(await client.evaluate('document.querySelector("#bomMaterialForm").elements.quantity.value'), '1');
assert.equal(await client.evaluate('document.querySelector("#bomMaterialForm").elements.name.value'), 'Động cơ servo 400W');
assert.equal(await client.evaluate('document.querySelector("#bomMaterialForm").elements.model.value'), 'SV-400');
assert.equal(await client.evaluate('/Tồn|Khả dụng/.test(document.querySelector("#bomAssetResults").innerText)'), false);
} else await client.evaluate('document.querySelector("[data-bom-mode=manual]").click()');
await client.evaluate(`(() => { const form = document.querySelector('#bomMaterialForm'); ${name === undefined ? '' : `form.elements.name.value=${JSON.stringify(name)};`} ${model === undefined ? '' : `form.elements.model.value=${JSON.stringify(model)};`} ${unit === undefined ? '' : `form.elements.unit.value=${JSON.stringify(unit)};`} form.elements.quantity.value=${JSON.stringify(String(quantity))}; form.elements.sourceInfo.value=${JSON.stringify(sourceInfo)}; return true; })()`);
const entered = await client.evaluate('Array.from(document.querySelector("#bomMaterialForm").elements).filter(element=>["name","model","quantity","unit","sourceInfo","notes"].includes(element.name)).map(element=>[element.name,element.value])');
for (const mode of ['manual', 'asset', 'manual', 'asset', id === null ? 'manual' : 'asset']) {
await client.evaluate(`(() => { const button=document.querySelector('[data-bom-mode="${mode}"]');button.focus({preventScroll:true});button.click();return true; })()`);
await client.evaluate('new Promise(resolve=>requestAnimationFrame(()=>resolve(true)))');
assert.deepEqual(await entryGeometry(), opened, 'switching modes must not move or resize the dialog/form/footer');
}
assert.deepEqual(await client.evaluate('Array.from(document.querySelector("#bomMaterialForm").elements).filter(element=>["name","model","quantity","unit","sourceInfo","notes"].includes(element.name)).map(element=>[element.name,element.value])'), entered);
if (screenshot) {
const shot = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
fs.writeFileSync(path.join(output, 'bom-component-picker.png'), Buffer.from(shot.data, 'base64'));
}
if (id === null && name === 'Khung gia công bên ngoài') {
const shot = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
fs.writeFileSync(path.join(output, 'bom-external-entry.png'), Buffer.from(shot.data, 'base64'));
}
await client.evaluate('(() => { const form=document.querySelector("#bomMaterialForm"); form.requestSubmit(form.querySelector("button[value=done]")); return true; })()');
await client.until('!document.querySelector("#bomComponentDialog")');
};
await add({ id: 1, quantity: 200, sourceInfo: 'https://example.com/servo', screenshot: true });
await add({ name: 'Khung gia công bên ngoài', model: 'CUSTOM-01', quantity: 12, sourceInfo: 'Nhà sản xuất: Cơ khí ABC' });
await add({ name: 'Cáp nguồn bên ngoài', model: 'CB-NEW', unit: 'm', quantity: 1.25, sourceInfo: 'https://example.com/cable' });
assert.equal(await client.evaluate('app.robotBom.lines.length'), 3);
assert.equal(await client.evaluate('document.querySelector("#bomRobotCount")===null && document.querySelector("[data-bom-stock]")===null'), true);
assert.equal(await client.evaluate('app.robotBom.sourceHtml("javascript:alert(1)").includes("<a")'), false);
assert.equal(await client.evaluate('document.querySelector(".bom-source-link").getAttribute("href")'), 'https://example.com/servo');
await client.evaluate('document.querySelector("[data-bom-action=save]").click()');
await client.until('!app.robotBom.busy && !app.robotBom.dirty');
await client.evaluate('(() => { const input=document.querySelector("[data-bom-quantity]" );input.value="0.5";input.dispatchEvent(new Event("change",{bubbles:true})); })()');
assert.equal(await client.evaluate('app.robotBom.lines[0].Quantity'), 200);
assert.match(await client.evaluate('bomMessages.at(-1)'), /số lượng nguyên/);
await client.evaluate('window.XLSX.writeFile=(book,name)=>{window.bomExport={book,name}};document.querySelector("[data-bom-action=export]").click()');
assert.equal(await client.evaluate('bomExport.name'), 'BOM-AMR-500-v1.xlsx');
assert.equal(await client.evaluate('XLSX.utils.sheet_to_json(bomExport.book.Sheets.BOM).length'), 3);
await client.evaluate('(async()=>{const bytes=XLSX.write(bomExport.book,{bookType:"xlsx",type:"array"});await app.robotBom.importWorkbook(new File([bytes],"roundtrip.xlsx"));return true})()');
assert.equal(await client.evaluate('app.robotBom.lines[2].Quantity'), 1.25);
assert.equal(await client.evaluate('app.robotBom.lines[1].SourceInfo'), 'Nhà sản xuất: Cơ khí ABC');
await client.evaluate('document.querySelector("[data-bom-action=save]").click()');
await client.until('!app.robotBom.busy && !app.robotBom.dirty');
const screenshot = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
fs.writeFileSync(path.join(output, 'bom-desktop.png'), Buffer.from(screenshot.data, 'base64'));
await client.send('Page.reload'); await delay(300);
await client.until('typeof app !== "undefined" && app?.robotBom?.lines.length===3 && !app.robotBom.busy');
await prepareNotifications();
assert.equal(await client.evaluate('app.robotBom.lines[0].SourceInfo'), 'https://example.com/servo');
fixture.state.catalog = [];
await client.evaluate('window.nativeConfirmCalls=0;window.confirm=()=>{nativeConfirmCalls++;return true};document.querySelector("[data-bom-action=publish]").click()');
await client.until('document.querySelector("#bomPublishDialog")?.open');
assert.equal(await client.evaluate('app.robotBom.header.Status'), 'draft');
await client.evaluate('document.querySelector("#bomPublishDialog .bom-dialog-footer [data-bom-publish-cancel]").click()');
await client.until('!document.querySelector("#bomPublishDialog")');
assert.equal(await client.evaluate('app.robotBom.header.Status'), 'draft');
await client.evaluate('document.querySelector("[data-bom-action=publish]").click()');
await client.until('document.querySelector("#bomPublishDialog")?.open');
await client.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
await client.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
await client.until('!document.querySelector("#bomPublishDialog")');
assert.equal(await client.evaluate('app.robotBom.header.Status'), 'draft');
await client.evaluate('document.querySelector("[data-bom-action=publish]").click();document.querySelector("[data-bom-action=publish]").click()');
await client.until('document.querySelector("#bomPublishDialog")?.open');
assert.equal(await client.evaluate('document.querySelectorAll("#bomPublishDialog").length'), 1);
const confirmation = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
fs.writeFileSync(path.join(output, 'bom-publish-confirmation.png'), Buffer.from(confirmation.data, 'base64'));
await client.evaluate('document.querySelector("[data-bom-publish-confirm]").click()');
await client.until('app.robotBom.header?.Status==="released" && !app.robotBom.busy');
assert.equal(await client.evaluate('nativeConfirmCalls'), 0);
assert.equal(fixture.queries.filter(({ query }) => query.includes("Status = 'released'")).length, 1);
assert.equal(await client.evaluate('document.querySelector("[data-bom-action=add]")===null'), true);
await client.evaluate('document.querySelector("[data-bom-action=copy]").click()');
await client.until('app.robotBom.header?.Revision===2 && !app.robotBom.busy');
assert.equal(await client.evaluate('app.robotBom.lines.length'), 3);
await client.evaluate('(() => { const input=document.querySelector("[data-bom-quantity]");input.value="3";input.dispatchEvent(new Event("change",{bubbles:true}));window.confirm=()=>false;location.hash="#robots"; })()');
await client.until('location.hash==="#robot-bom"');
assert.equal(await client.evaluate('app.robotBom.dirty && app.currentPage==="robot-bom"'), true);
forceSaveFailure = true;
await client.evaluate('window.confirm=()=>true;document.querySelector("[data-bom-action=save]").click()');
await client.until('!app.robotBom.busy');
assert.equal(await client.evaluate('app.robotBom.dirty && app.robotBom.lines[0].Quantity===3'), true);
forceSaveFailure = false;
await client.evaluate('document.querySelector("[data-bom-action=save]").click()');
await client.until('!app.robotBom.busy && !app.robotBom.dirty');
assert.equal(fixture.state.lines.find(line => line.BomId === 1).Quantity, 200);
assert.equal(fixture.state.lines.find(line => line.BomId === 1).SourceId, null);
await client.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
await delay(200);
assert.equal(await client.evaluate('document.documentElement.scrollWidth<=390'), true);
const mobile = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
fs.writeFileSync(path.join(output, 'bom-mobile.png'), Buffer.from(mobile.data, 'base64'));
await client.evaluate('document.querySelector("[data-bom-action=add]").click()');
assert.equal(await client.evaluate('document.querySelector("#bomComponentDialog").getBoundingClientRect().width<=390'), true);
const mobileGeometry = await entryGeometry();
for (const mode of ['manual', 'asset', 'manual']) {
await client.evaluate(`document.querySelector('[data-bom-mode="${mode}"]').click()`);
assert.deepEqual(await entryGeometry(), mobileGeometry, 'mobile mode switches must retain geometry and scroll');
}
assert.equal(await client.evaluate('document.querySelector("#bomComponentDialog .bom-dialog-footer").getBoundingClientRect().bottom<=844'), true);
const mobileEntry = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
fs.writeFileSync(path.join(output, 'bom-external-mobile.png'), Buffer.from(mobileEntry.data, 'base64'));
await client.evaluate('document.querySelector("[data-bom-close]").click();app.currentUser.Role="user";app.robotBom.render()');
assert.equal(await client.evaluate('document.querySelector("[data-bom-action=save]")===null && document.querySelector("[data-bom-action=add]")===null && document.querySelector("[data-bom-action=delete]")===null'), true);
fixture.state.models.push({ RobotId: 2, Model: 'AMR-500', TypeId: 2, Type: 'AMR khác cấu hình', Name: 'Robot khác' });
await client.evaluate('app.currentUser.Role="admin";app.robotBom.mount(document.getElementById("mainContent"),{Model:"AMR-500",TypeId:2})');
assert.equal(await client.evaluate('app.robotBom.selectedModel().TypeId'), 2);
assert.equal(await client.evaluate('app.robotBom.header===null'), true);
assert.equal(fixture.state.headers.length, 2);
await client.send('Emulation.setDeviceMetricsOverride', { width: 1600, height: 1050, deviceScaleFactor: 1, mobile: false });
await client.evaluate('window.nativeConfirmCalls=0;window.confirm=()=>{nativeConfirmCalls++;return true};location.hash="#robots"');
await client.until('app.currentPage==="robots" && document.querySelector("[data-robot-action=delete]")');
const openRobotDelete = async () => {
await client.evaluate('document.querySelector("[data-robot-action=delete]").click()');
await client.until('document.querySelector("#robotDeleteDialog")?.open');
assert.equal(await client.evaluate('document.querySelector("#robotDeleteDialog .robot-delete-name").textContent'), 'TESTBOM');
assert.equal(await client.evaluate('document.querySelector("#robotDeleteDialog").innerText.includes("AMR-500")'), true);
};
const waitRobotDeleteClosed = () => client.until('!document.querySelector("#robotDeleteDialog") && !app.robotDeletionPending');
await openRobotDelete();
const robotConfirmation = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
fs.writeFileSync(path.join(output, 'robot-delete-confirmation.png'), Buffer.from(robotConfirmation.data, 'base64'));
await client.evaluate('document.querySelector("#robotDeleteDialog .bom-dialog-footer [data-cancel-robot-delete]").click()');
await waitRobotDeleteClosed(); assert.equal(robotDeleteRequests.length, 0);
await openRobotDelete();
await client.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
await client.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
await waitRobotDeleteClosed(); assert.equal(robotDeleteRequests.length, 0);
await openRobotDelete();
await client.evaluate('document.querySelector("#robotDeleteDialog .bom-dialog-header [data-cancel-robot-delete]").click()');
await waitRobotDeleteClosed(); assert.equal(robotDeleteRequests.length, 0);
await openRobotDelete(); await client.evaluate('location.hash="#robot-types"');
await waitRobotDeleteClosed(); assert.equal(robotDeleteRequests.length, 0);
await client.until('app.currentPage==="robot-types"');
await client.evaluate('document.querySelector("[data-robot-type-action=delete]").click()');
await client.until('document.querySelector("#robotDeleteDialog")?.open');
assert.equal(await client.evaluate('document.querySelector("#robotDeleteTitle").textContent'), 'Xóa thể loại robot?');
await client.evaluate('document.querySelector("#robotDeleteDialog [data-cancel-robot-delete]").click()');
await waitRobotDeleteClosed();
await client.evaluate('location.hash="#robots"');
await client.until('app.currentPage==="robots"');
await client.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
await openRobotDelete();
assert.equal(await client.evaluate('document.querySelector("#robotDeleteDialog").getBoundingClientRect().width<=390 && document.querySelector("#robotDeleteDialog .bom-dialog-footer").getBoundingClientRect().bottom<=844'), true);
const robotMobile = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
fs.writeFileSync(path.join(output, 'robot-delete-mobile.png'), Buffer.from(robotMobile.data, 'base64'));
await client.evaluate('document.querySelector("#robotDeleteDialog [data-cancel-robot-delete]").click()');
await waitRobotDeleteClosed();
await client.send('Emulation.setDeviceMetricsOverride', { width: 1600, height: 1050, deviceScaleFactor: 1, mobile: false });
failRobotDelete = true;
await openRobotDelete(); await client.evaluate('document.querySelector("[data-confirm-robot-delete]").click()');
await waitRobotDeleteClosed();
assert.equal(robotDeleteRequests.length, 1); assert.equal(reviewRobots.length, 1);
assert.match(await client.evaluate('bomMessages.at(-1)'), /Không thể xóa robot thử nghiệm/);
failRobotDelete = false;
await client.evaluate('app.deleteRobot(1);app.deleteRobot(1);true');
await client.until('document.querySelector("#robotDeleteDialog")?.open');
assert.equal(await client.evaluate('document.querySelectorAll("#robotDeleteDialog").length'), 1);
await client.evaluate('document.querySelector("[data-confirm-robot-delete]").click()');
await waitRobotDeleteClosed();
assert.equal(robotDeleteRequests.length, 2); assert.equal(reviewRobots.length, 0);
assert.equal(await client.evaluate('app.robots.length'), 0);
assert.equal(await client.evaluate('nativeConfirmCalls'), 0);
assert.equal(fixture.state.headers.length, 2);
// Delete only the selected revision, with styled confirmation and no implicit save.
await client.evaluate('location.hash="#robot-bom"');
await client.until('app.currentPage==="robot-bom" && !app.robotBom.busy');
await client.evaluate('app.robotBom.mount(document.getElementById("mainContent"),{Model:"AMR-500",TypeId:1})');
await prepareNotifications();
const markBomDirty = () => client.evaluate('(() => { const input=document.querySelector("[data-bom-quantity]");input.value="7";input.dispatchEvent(new Event("change",{bubbles:true}));return true; })()');
const openBomDelete = async () => {
await client.evaluate('document.querySelector("[data-bom-action=delete]").click()');
await client.until('document.querySelector("#bomDeleteDialog")?.open');
};
const bomDeleteCount = () => fixture.queries.filter(({ query }) => query.includes('DELETE FROM dbo.RobotBomRevisions')).length;
await markBomDirty();
await openBomDelete();
assert.equal(await client.evaluate('document.querySelector("#bomDeleteDialog .bom-publish-summary").innerText.includes("AMR-500") && document.querySelector("#bomDeleteTitle").innerText.includes("v2")'), true);
assert.equal(await client.evaluate('document.querySelector("#bomDeleteDialog").innerText.includes("chưa lưu")'), true);
assert.equal(await client.evaluate('document.activeElement.matches(".bom-dialog-footer [data-bom-delete-cancel]")'), true);
await client.evaluate('document.querySelector("#bomDeleteDialog .bom-dialog-footer [data-bom-delete-cancel]").click()');
await client.until('!document.querySelector("#bomDeleteDialog")');
assert.equal(await client.evaluate('app.robotBom.dirty && app.robotBom.lines[0].Quantity===7'), true);
await openBomDelete();
await client.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
await client.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
await client.until('!document.querySelector("#bomDeleteDialog")');
await openBomDelete();
await client.evaluate('document.querySelector("#bomDeleteDialog .bom-dialog-header [data-bom-delete-cancel]").click()');
await client.until('!document.querySelector("#bomDeleteDialog")');
await openBomDelete();
await client.evaluate('app.robotBom.unmount()');
await client.until('!document.querySelector("#bomDeleteDialog")');
assert.equal(bomDeleteCount(), 0); assert.equal(fixture.state.headers.length, 2);
// A stale client cannot delete a newer saved version.
const draft = fixture.state.headers.find(item => item.Revision === 2);
draft.LockVersion++;
await openBomDelete();
await client.evaluate('document.querySelector("[data-bom-delete-confirm]").click()');
await client.until('!app.robotBom.busy && !document.querySelector("#bomDeleteDialog")');
assert.equal(bomDeleteCount(), 0); assert.equal(fixture.state.headers.length, 2);
assert.equal(await client.evaluate('app.robotBom.dirty && app.robotBom.lines[0].Quantity===7'), true);
assert.match(await client.evaluate('bomMessages.at(-1)'), /tải lại trước khi xóa/);
await client.evaluate('app.robotBom.mount(document.getElementById("mainContent"),{Model:"AMR-500",TypeId:1})');
await markBomDirty();
forceBomDeleteFailure = true;
await openBomDelete();
const deleteConfirmation = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
fs.writeFileSync(path.join(output, 'bom-delete-confirmation.png'), Buffer.from(deleteConfirmation.data, 'base64'));
await client.evaluate('document.querySelector("[data-bom-delete-confirm]").click()');
await client.until('!app.robotBom.busy && !document.querySelector("#bomDeleteDialog")');
assert.equal(bomDeleteCount(), 1); assert.equal(fixture.state.headers.length, 2);
assert.equal(fixture.state.lines.filter(line => line.BomId === draft.BomId).length, 3);
assert.equal(await client.evaluate('app.robotBom.dirty && app.robotBom.lines[0].Quantity===7'), true);
forceBomDeleteFailure = false;
await client.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
await openBomDelete();
await client.evaluate('document.querySelector("[data-bom-action=delete]").click()');
assert.equal(await client.evaluate('document.querySelectorAll("#bomDeleteDialog").length'), 1);
assert.equal(await client.evaluate('document.querySelector("#bomDeleteDialog").getBoundingClientRect().width<=390 && document.querySelector("#bomDeleteDialog .bom-dialog-footer").getBoundingClientRect().bottom<=844'), true);
const deleteMobile = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
fs.writeFileSync(path.join(output, 'bom-delete-mobile.png'), Buffer.from(deleteMobile.data, 'base64'));
await client.evaluate('document.querySelector("[data-bom-delete-confirm]").click();document.querySelector("[data-bom-delete-confirm]")?.click()');
await client.until('!app.robotBom.busy && app.robotBom.header?.Revision===1');
assert.equal(bomDeleteCount(), 2); assert.equal(fixture.state.headers.length, 1);
assert.equal(await client.evaluate('!app.robotBom.dirty && app.robotBom.header.Status==="released" && app.robotBom.revisions.length===1'), true);
assert.equal(fixture.state.lines[0].Quantity, 200);
// Deleting the last historical version refreshes the model picker too.
fixture.state.models = fixture.state.models.filter(item => item.TypeId !== 1);
await openBomDelete();
await client.evaluate('document.querySelector("[data-bom-delete-confirm]").click()');
await client.until('!app.robotBom.busy && app.robotBom.header===null');
assert.equal(bomDeleteCount(), 3); assert.equal(fixture.state.headers.length, 0); assert.equal(fixture.state.lines.length, 0);
assert.equal(await client.evaluate('app.robotBom.models.length===1 && app.robotBom.selectedModel().TypeId===2 && app.robotBom.revisions.length===0'), true);
assert.equal(await client.evaluate('document.querySelector("[data-bom-action=delete]")===null && document.querySelector("#bomRevision").disabled'), true);
assert.equal(await client.evaluate('nativeConfirmCalls'), 0);
assert.equal(fixture.queries.some(({ query }) => /(?:UPDATE|INSERT|DELETE).*Inventory/i.test(query)), false);
assert.deepEqual(client.errors, []);
fs.writeFileSync(path.join(output, 'verification.json'), JSON.stringify({ passed: true, checks: ['BOM draft/released deletion', 'BOM delete cancel/Escape/close/unmount', 'stale BOM deletion rejected', 'BOM deletion rollback and retry', 'BOM dirty state preserved on failure and discarded on success', 'double click deletes one BOM', 'remaining revisions and orphaned models refresh', 'styled robot/type deletion confirmations', 'cancel/Escape/close/navigation send no delete', 'failed robot deletion supports retry', 'double click deletes once', 'mobile deletion confirmation', 'stable entry mode geometry and retained fields', 'desktop/mobile mode switching', 'custom publication confirmation', 'cancel and Escape preserve draft', 'double click publishes once', 'asset name/model picker', 'external components', 'BOM quantity independent of stock', 'supplier URL/text', 'safe source links', 'Excel export/import with sources', 'save/reload', 'publish/copy with no inventory', 'mobile overflow', 'viewer controls'], screenshots: ['bom-delete-confirmation.png', 'bom-delete-mobile.png', 'bom-desktop.png', 'bom-component-picker.png', 'bom-external-entry.png', 'bom-publish-confirmation.png', 'bom-mobile.png', 'bom-external-mobile.png', 'robot-delete-confirmation.png', 'robot-delete-mobile.png'] }, null, 2));
} finally {
if (client) { try { await client.send('Browser.close'); } catch {} client.socket.close(); }
chrome.kill();
if (chrome.exitCode === null) await Promise.race([new Promise(resolve => chrome.once('exit', resolve)), delay(2000)]);
const resolved = path.resolve(profile);
if (path.dirname(resolved) === path.resolve(os.tmpdir()) && path.basename(resolved).startsWith('accmanager-bom-chrome-')) {
fs.rmSync(resolved, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}
server.closeAllConnections(); await new Promise(resolve => server.close(resolve));
}
});

View File

@@ -0,0 +1,69 @@
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
IF OBJECT_ID('dbo.RobotBomRevisions', 'U') IS NULL
BEGIN
CREATE TABLE dbo.RobotBomRevisions (
BomId INT IDENTITY(1,1) NOT NULL 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 (DATEADD(HOUR, 7, SYSUTCDATETIME())),
UpdatedDate DATETIME2 NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
ReleasedDate DATETIME2 NULL,
CONSTRAINT UQ_RobotBomRevisions_ModelRevision UNIQUE (RobotTypeId, RobotModel, Revision),
CONSTRAINT CK_RobotBomRevisions_Status CHECK (Status IN ('draft', 'released')),
CONSTRAINT FK_RobotBomRevisions_Type FOREIGN KEY (RobotTypeId) REFERENCES dbo.RobotTypes(TypeId),
CONSTRAINT FK_RobotBomRevisions_User FOREIGN KEY (CreatedBy) REFERENCES dbo.Users(UserId) ON DELETE SET NULL
);
END;
IF OBJECT_ID('dbo.RobotBomLines', 'U') IS NULL
BEGIN
CREATE TABLE dbo.RobotBomLines (
LineId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
BomId INT NOT NULL,
SourceType VARCHAR(10) NOT NULL DEFAULT 'manual',
SourceId INT 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 '',
SourceInfo NVARCHAR(1000) NOT NULL DEFAULT '',
SortOrder INT NOT NULL,
CONSTRAINT FK_RobotBomLines_Revision FOREIGN KEY (BomId) REFERENCES dbo.RobotBomRevisions(BomId),
CONSTRAINT CK_RobotBomLines_Source CHECK (SourceType = 'manual' AND SourceId IS NULL),
CONSTRAINT CK_RobotBomLines_Quantity CHECK (Quantity > 0 AND Quantity <= 100000)
);
CREATE INDEX IX_RobotBomLines_BomId ON dbo.RobotBomLines(BomId, SortOrder);
END;
IF COL_LENGTH('dbo.RobotBomLines', 'SourceInfo') IS NULL
ALTER TABLE dbo.RobotBomLines ADD SourceInfo NVARCHAR(1000) NOT NULL
CONSTRAINT DF_RobotBomLines_SourceInfo DEFAULT '';
-- Retain existing component descriptions and released versions while detaching
-- the obsolete inventory references. Repeated startup leaves content intact.
IF EXISTS (SELECT 1 FROM sys.check_constraints
WHERE parent_object_id = OBJECT_ID('dbo.RobotBomLines')
AND name = 'CK_RobotBomLines_Source' AND definition LIKE '%asset%')
ALTER TABLE dbo.RobotBomLines DROP CONSTRAINT CK_RobotBomLines_Source;
IF EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID('dbo.RobotBomLines')
AND name = 'SourceId' AND is_nullable = 0)
ALTER TABLE dbo.RobotBomLines ALTER COLUMN SourceId INT NULL;
UPDATE dbo.RobotBomLines SET SourceType = 'manual', SourceId = NULL
WHERE SourceType <> 'manual' OR SourceId IS NOT NULL;
IF NOT EXISTS (SELECT 1 FROM sys.check_constraints WHERE parent_object_id = OBJECT_ID('dbo.RobotBomLines')
AND name = 'CK_RobotBomLines_Source')
ALTER TABLE dbo.RobotBomLines ADD CONSTRAINT CK_RobotBomLines_Source
CHECK (SourceType = 'manual' AND SourceId IS NULL);
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
THROW;
END CATCH;

View File

@@ -0,0 +1,135 @@
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();
}
}
});

View File

@@ -0,0 +1,78 @@
const express = require('express');
const { createRobotBomRouter } = require('./robot-bom');
function createBomFixture({ role = 'asset', failQuery } = {}) {
const state = {
models: [{ RobotId: 1, Model: 'AMR-500', TypeId: 1, Type: 'AMR', Name: 'Robot vận chuyển' }],
catalog: [
{ SourceType: 'asset', SourceId: 1, Code: 'LK-001', Name: 'Động cơ servo 400W', Model: 'SV-400', Unit: 'cái', Available: 8, Location: 'Kho A' },
{ SourceType: 'asset', SourceId: 2, Code: 'LK-002', Name: 'Bánh xe chủ động', Model: 'WH-200', Unit: 'cái', Available: 16, Location: 'Kho A' },
{ SourceType: 'asset', SourceId: 3, Code: 'LK-003', Name: 'Bộ pin 48V 40Ah', Model: 'BAT-48-40', Unit: 'bộ', Available: 3, Location: 'Kho A' },
{ SourceType: 'consumable', SourceId: 1, Code: 'VT-001', Name: 'Cáp nguồn', Model: 'CB-2X2.5', Unit: 'm', Available: 30, Location: '' }
],
headers: [], lines: []
};
let nextId = 1;
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 inputs = this.inputs; queries.push({ query, inputs, transaction: this.transaction });
if (failQuery?.(query, inputs)) throw new Error('test database failure');
const rows = recordset => ({ recordset: structuredClone(recordset) });
if (query.includes('FROM dbo.AssetInventory')) return rows(state.catalog.filter(item => item.SourceType === 'asset')
.map(item => ({ Id: item.SourceId, Code: item.Code, Name: item.Name, Model: item.Model, Unit: item.Unit })));
if (query.includes('WITH ModelCatalog')) {
const models = [...state.models];
for (const header of state.headers) {
if (!models.some(model => model.Model === header.RobotModel && model.TypeId === header.RobotTypeId)) models.push({
RobotId: null, Model: header.RobotModel, TypeId: header.RobotTypeId, Type: 'AMR', Name: 'BOM đã lưu theo model'
});
}
return rows(models);
}
if (query.includes('SELECT Model, TypeId FROM dbo.Robots')) return rows(state.models.filter(item => item.RobotId === inputs.robotId));
if (query.includes('MAX(Revision)')) return rows([{ NextRevision: Math.max(0, ...state.headers.filter(item => item.RobotModel === inputs.model && item.RobotTypeId === inputs.typeId).map(item => item.Revision)) + 1 }]);
if (query.includes('INSERT dbo.RobotBomRevisions')) {
const now = new Date().toISOString();
const header = { BomId: nextId++, RobotModel: inputs.model, RobotTypeId: inputs.typeId, Revision: inputs.revision, Status: 'draft', LockVersion: 1, CreatedDate: now, UpdatedDate: now, ReleasedDate: null };
state.headers.push(header); return rows([header]);
}
if (query.includes('DELETE FROM dbo.RobotBomRevisions')) { state.headers = state.headers.filter(item => item.BomId !== inputs.id); return rows([]); }
if (query.includes('FROM dbo.RobotBomRevisions') && query.includes('WHERE BomId = @id')) return rows(state.headers.filter(item => item.BomId === inputs.id));
if (query.includes('FROM dbo.RobotBomRevisions b')) return rows(state.headers.filter(item => item.RobotModel === inputs.model && item.RobotTypeId === inputs.typeId).map(item => ({ ...item, LineCount: state.lines.filter(line => line.BomId === item.BomId).length })).sort((a, b) => b.Revision - a.Revision));
if (query.includes('SELECT * FROM dbo.RobotBomLines')) return rows(state.lines.filter(item => item.BomId === inputs.id).sort((a, b) => a.SortOrder - b.SortOrder));
if (query.includes('DELETE FROM dbo.RobotBomLines')) { state.lines = state.lines.filter(item => item.BomId !== inputs.id); return rows([]); }
if (query.includes('INSERT dbo.RobotBomLines')) {
state.lines.push({ BomId: inputs.bomId, SourceType: inputs.sourceType, SourceId: inputs.sourceId,
Code: inputs.code, Name: inputs.name, Model: inputs.model, Unit: inputs.unit,
GroupName: inputs.groupName, Position: inputs.position, Quantity: inputs.quantity,
Notes: inputs.notes, SourceInfo: inputs.sourceInfo, SortOrder: inputs.sortOrder }); return rows([]);
}
if (query.includes('UPDATE dbo.RobotBomRevisions')) {
const header = state.headers.find(item => item.BomId === inputs.id);
header.LockVersion++; header.UpdatedDate = new Date().toISOString();
if (query.includes("Status = 'released'")) { header.Status = 'released'; header.ReleasedDate = header.UpdatedDate; }
return rows([header]);
}
throw new Error(`Unexpected fixture query: ${query}`);
}
}
class Transaction {
constructor() { transactions.push(this); }
async begin() { this.snapshot = structuredClone(state); }
async commit() { this.committed = true; }
async rollback() { Object.assign(state, this.snapshot); this.rolledBack = true; }
}
const app = express();
app.use(express.json());
app.use((req, _res, next) => { req.user = { UserId: 1, Role: role }; next(); });
app.use('/api/robot-boms', createRobotBomRouter({ 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(); },
sendInternalError(res, _error, message) { return res.status(500).json({ success: false, message }); }
}));
return { app, state, queries, transactions };
}
module.exports = { createBomFixture };

186
backend/robot-bom.js Normal file
View File

@@ -0,0 +1,186 @@
const express = require('express');
const fs = require('node:fs');
const path = require('node:path');
const MAX_LINES = 500;
const fail = (message, status = 400) => Object.assign(new Error(message), { status });
function positiveId(value) {
if (!/^\d+$/.test(String(value)) || !Number.isSafeInteger(Number(value)) || Number(value) < 1 || Number(value) > 2147483647) {
throw fail('Mã dữ liệu không hợp lệ');
}
return Number(value);
}
function textField(value, max, label, required = false) {
if (typeof value !== 'string' || value.trim().length > max || (required && !value.trim())) {
throw fail(`${label} ${required ? 'không được trống và ' : ''}tối đa ${max} ký tự`);
}
return value.trim();
}
function quantity(value, unit) {
if (!/^\d+(\.\d{1,4})?$/.test(String(value)) || !Number.isFinite(Number(value)) || Number(value) <= 0 || Number(value) > 100000) {
throw fail('Số lượng phải lớn hơn 0, tối đa 100.000 và không quá 4 chữ số thập phân');
}
const fractional = /^(m|m2|m²|m3|m³|mét|met|kg|g|gam|l|lít|lit|ml|mm|cm|tấn|tan)$/i.test(String(unit).trim());
if (String(unit).trim() && !fractional && !Number.isInteger(Number(value))) throw fail(`Đơn vị ${unit} yêu cầu số lượng nguyên`);
return Number(value);
}
function normalizeLines(input) {
if (!Array.isArray(input) || input.length > MAX_LINES) throw fail(`BOM tối đa ${MAX_LINES} dòng vật tư`);
return input.map((line, index) => {
if (!line || typeof line !== 'object' || Array.isArray(line)) throw fail(`Vật tư dòng ${index + 1} không hợp lệ`);
const unit = textField(line.unit ?? '', 50, 'Đơn vị');
return { SourceType: 'manual', SourceId: null,
Name: textField(line.name, 255, 'Tên vật tư', true),
Code: textField(line.code ?? '', 100, 'Mã vật tư'), Model: textField(line.model ?? '', 255, 'Model vật tư'),
Unit: unit, GroupName: textField(line.groupName ?? '', 100, 'Cụm lắp ráp'),
Position: textField(line.position ?? '', 150, 'Vị trí lắp'), Quantity: quantity(line.quantity ?? 1, unit),
SourceInfo: textField(line.sourceInfo ?? '', 1000, 'Nguồn'),
Notes: textField(line.notes ?? '', 500, 'Ghi chú'), SortOrder: index };
});
}
async function ensureRobotBomSchema(pool) {
await pool.request().batch(fs.readFileSync(path.join(__dirname, 'robot-bom-schema.sql'), 'utf8'));
}
function createRobotBomRouter({ getPool, sql, requireManage, sendInternalError }) {
const router = express.Router();
const handle = fn => async (req, res) => {
try { req.body ??= {}; await fn(req, res); }
catch (error) {
if (error.status) return res.status(error.status).json({ success: false, message: error.message });
if ([2601, 2627, 1205].includes(error.number)) return res.status(409).json({ success: false, message: 'Dữ liệu vừa được thay đổi. Hãy tải lại BOM rồi thử lại.' });
return sendInternalError(res, error, 'Không thể xử lý BOM robot');
}
};
const inTransaction = async fn => {
const transaction = new sql.Transaction(getPool());
await transaction.begin();
try { const result = await fn(() => new sql.Request(transaction)); await transaction.commit(); return result; }
catch (error) { try { await transaction.rollback(); } catch {} throw error; }
};
const loadHeader = async (request, id, lock = false) => {
const result = await request.input('id', sql.Int, positiveId(id)).query(`
SELECT * FROM dbo.RobotBomRevisions ${lock ? 'WITH (UPDLOCK, HOLDLOCK)' : ''} WHERE BomId = @id`);
if (!result.recordset[0]) throw fail('Không tìm thấy phiên bản BOM', 404);
return result.recordset[0];
};
const checkDraft = (header, version) => {
if (header.Status !== 'draft') throw fail('BOM đã phát hành. Hãy sao chép thành phiên bản nháp mới để chỉnh sửa.', 409);
if (header.LockVersion !== positiveId(version)) throw fail('BOM đã được người khác thay đổi. Hãy tải lại trước khi lưu.', 409);
};
const readLines = async (request, id) => (await request.input('id', sql.Int, id)
.query('SELECT * FROM dbo.RobotBomLines WHERE BomId = @id ORDER BY SortOrder, LineId')).recordset;
async function insertLines(request, id, lines) {
for (const line of lines) {
await request().input('bomId', sql.Int, id)
.input('sourceType', sql.VarChar(10), line.SourceType).input('sourceId', sql.Int, line.SourceId)
.input('code', sql.NVarChar(100), line.Code).input('name', sql.NVarChar(255), line.Name)
.input('model', sql.NVarChar(255), line.Model).input('unit', sql.NVarChar(50), line.Unit)
.input('groupName', sql.NVarChar(100), line.GroupName).input('position', sql.NVarChar(150), line.Position)
.input('quantity', sql.Decimal(18, 4), line.Quantity).input('notes', sql.NVarChar(500), line.Notes)
.input('sourceInfo', sql.NVarChar(1000), line.SourceInfo || '')
.input('sortOrder', sql.Int, line.SortOrder).query(`
INSERT dbo.RobotBomLines (BomId, SourceType, SourceId, Code, Name, Model, Unit, GroupName, Position, Quantity, Notes, SourceInfo, SortOrder)
VALUES (@bomId, @sourceType, @sourceId, @code, @name, @model, @unit, @groupName, @position, @quantity, @notes, @sourceInfo, @sortOrder)`);
}
}
router.get('/models', handle(async (_req, res) => {
const result = await getPool().request().query(`
WITH ModelCatalog AS (
SELECT Model, TypeId FROM dbo.Robots
UNION SELECT RobotModel, RobotTypeId FROM dbo.RobotBomRevisions
)
SELECT MIN(r.RobotId) AS RobotId, m.Model, m.TypeId, t.Name AS Type,
COALESCE(MIN(r.Name), N'BOM đã lưu theo model') AS Name
FROM ModelCatalog m JOIN dbo.RobotTypes t ON t.TypeId = m.TypeId
LEFT JOIN dbo.Robots r ON r.Model = m.Model AND r.TypeId = m.TypeId
GROUP BY m.Model, m.TypeId, t.Name ORDER BY m.Model, t.Name`);
res.json({ success: true, data: result.recordset });
}));
router.get('/catalog', handle(async (_req, res) => {
// This picker copies descriptions only. All quantities belong to the BOM.
const result = await getPool().request().query(`
SELECT AssetId AS Id, AssetCode AS Code, AssetName AS Name,
ISNULL(Model, '') AS Model, ISNULL(Unit, '') AS Unit
FROM dbo.AssetInventory WHERE IsArchived = 0 ORDER BY AssetName, AssetCode`);
res.json({ success: true, data: result.recordset });
}));
router.get('/', handle(async (req, res) => {
const model = textField(req.query.model, 255, 'Model robot', true);
const result = await getPool().request().input('model', sql.NVarChar(255), model)
.input('typeId', sql.Int, positiveId(req.query.typeId)).query(`
SELECT b.*, (SELECT COUNT(*) FROM dbo.RobotBomLines l WHERE l.BomId = b.BomId) AS LineCount
FROM dbo.RobotBomRevisions b WHERE RobotModel = @model AND RobotTypeId = @typeId ORDER BY Revision DESC`);
res.json({ success: true, data: result.recordset });
}));
router.get('/:id', handle(async (req, res) => {
const header = await loadHeader(getPool().request(), req.params.id);
res.json({ success: true, data: { ...header, Lines: await readLines(getPool().request(), header.BomId) } });
}));
router.post('/', requireManage, handle(async (req, res) => {
const copyFrom = req.body.copyFromId == null ? null : positiveId(req.body.copyFromId);
const robotId = req.body.robotId == null && copyFrom ? null : positiveId(req.body.robotId);
const header = await inTransaction(async request => {
const source = copyFrom ? await loadHeader(request(), copyFrom, true) : null;
const robot = robotId == null ? { Model: source.RobotModel, TypeId: source.RobotTypeId }
: (await request().input('robotId', sql.Int, robotId)
.query('SELECT Model, TypeId FROM dbo.Robots WITH (HOLDLOCK) WHERE RobotId = @robotId')).recordset[0];
if (!robot) throw fail('Robot không còn trong danh mục. Hãy tải lại danh sách.', 404);
const revision = (await request().input('model', sql.NVarChar(255), robot.Model).input('typeId', sql.Int, robot.TypeId)
.query(`SELECT ISNULL(MAX(Revision), 0) + 1 AS NextRevision FROM dbo.RobotBomRevisions WITH (UPDLOCK, HOLDLOCK)
WHERE RobotModel = @model AND RobotTypeId = @typeId`)).recordset[0].NextRevision;
const inserted = (await request().input('model', sql.NVarChar(255), robot.Model).input('typeId', sql.Int, robot.TypeId)
.input('revision', sql.Int, revision).input('userId', sql.Int, req.user.UserId)
.query(`INSERT dbo.RobotBomRevisions (RobotModel, RobotTypeId, Revision, CreatedBy)
OUTPUT INSERTED.* VALUES (@model, @typeId, @revision, @userId)`)).recordset[0];
if (copyFrom) {
await insertLines(request, inserted.BomId, await readLines(request(), copyFrom));
}
return inserted;
});
res.status(201).json({ success: true, data: header, message: 'Đã tạo phiên bản BOM nháp' });
}));
router.put('/:id', requireManage, handle(async (req, res) => {
const id = positiveId(req.params.id);
if (!Array.isArray(req.body.lines) || req.body.lines.length > MAX_LINES) throw fail(`BOM tối đa ${MAX_LINES} dòng vật tư`);
const saved = await inTransaction(async request => {
const header = await loadHeader(request(), id, true); checkDraft(header, req.body.lockVersion);
const lines = normalizeLines(req.body.lines);
await request().input('id', sql.Int, id).query('DELETE FROM dbo.RobotBomLines WHERE BomId = @id');
await insertLines(request, id, lines);
const updated = (await request().input('id', sql.Int, id).query(`UPDATE dbo.RobotBomRevisions
SET LockVersion = LockVersion + 1, UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
OUTPUT INSERTED.UpdatedDate WHERE BomId = @id`)).recordset[0];
return { BomId: id, LockVersion: header.LockVersion + 1, UpdatedDate: updated.UpdatedDate, Lines: lines };
});
res.json({ success: true, data: saved, message: 'Đã lưu BOM nháp' });
}));
router.delete('/:id', requireManage, handle(async (req, res) => {
const id = positiveId(req.params.id);
await inTransaction(async request => {
const header = await loadHeader(request(), id, true);
if (header.LockVersion !== positiveId(req.body.lockVersion)) {
throw fail('BOM đã được người khác thay đổi. Hãy tải lại trước khi xóa.', 409);
}
await request().input('id', sql.Int, id).query('DELETE FROM dbo.RobotBomLines WHERE BomId = @id');
await request().input('id', sql.Int, id).query('DELETE FROM dbo.RobotBomRevisions WHERE BomId = @id');
});
res.json({ success: true, message: 'Đã xóa phiên bản BOM' });
}));
router.post('/:id/publish', requireManage, handle(async (req, res) => {
const id = positiveId(req.params.id);
await inTransaction(async request => {
const header = await loadHeader(request(), id, true); checkDraft(header, req.body.lockVersion);
const lines = await readLines(request(), id);
if (!lines.length) throw fail('BOM cần có ít nhất một vật tư trước khi phát hành');
normalizeLines(lines.map(line => ({ name: line.Name, unit: line.Unit, quantity: line.Quantity,
code: line.Code, model: line.Model, groupName: line.GroupName, position: line.Position, notes: line.Notes,
sourceInfo: line.SourceInfo || '' })));
await request().input('id', sql.Int, id).query(`UPDATE dbo.RobotBomRevisions SET Status = 'released',
LockVersion = LockVersion + 1, ReleasedDate = DATEADD(HOUR, 7, SYSUTCDATETIME()),
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME()) WHERE BomId = @id`);
});
res.json({ success: true, message: 'Đã phát hành BOM. Có thể sao chép thành phiên bản mới khi cần chỉnh sửa.' });
}));
return router;
}
module.exports = { ensureRobotBomSchema, createRobotBomRouter, normalizeLines, quantity };

212
backend/robot-bom.test.js Normal file
View File

@@ -0,0 +1,212 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { normalizeLines, quantity } = require('./robot-bom');
const { createBomFixture } = require('./robot-bom-test-fixture');
const line = extra => ({ name: 'Động cơ servo 400W', model: 'SV-400', unit: 'cái', quantity: 2,
sourceInfo: 'https://example.com/servo', notes: '', ...extra });
async function fixture(t, options) {
const f = createBomFixture(options);
const server = f.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)); });
f.request = async (suffix = '', method = 'GET', body) => {
const response = await fetch(`http://127.0.0.1:${server.address().port}/api/robot-boms${suffix}`, { method,
...(body === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) });
return { status: response.status, ...(response.headers.get('content-type')?.includes('application/json')
? await response.json() : { message: await response.text() }) };
};
return f;
}
test('BOM stores editable names/models, quantities and supplier sources without touching inventory', async t => {
const f = await fixture(t);
const created = await f.request('', 'POST', { robotId: 1 });
assert.equal(created.status, 201);
const id = created.data.BomId;
const saved = await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
assert.equal(saved.status, 200); assert.equal(saved.data.LockVersion, 2);
const reopened = await f.request(`/${id}`);
assert.equal(reopened.data.Lines[0].Name, 'Động cơ servo 400W');
assert.equal(reopened.data.Lines[0].Model, 'SV-400');
assert.equal(reopened.data.Lines[0].SourceInfo, 'https://example.com/servo');
assert.equal(reopened.data.Lines[0].SourceId, null);
assert.equal(reopened.data.Lines[0].SourceType, 'manual');
const revisions = await f.request('?model=AMR-500&typeId=1');
assert.equal(revisions.data[0].LineCount, 1);
assert.equal(f.queries.some(({ query }) => /\b(?:AssetInventory|ConsumableInventory)\b/i.test(query)), false);
});
test('asset picker exposes names/models with no stock quantities, including assets with zero stock', async t => {
const f = await fixture(t);
f.state.catalog[0].Available = 0;
const result = await f.request('/catalog');
assert.equal(result.status, 200); assert.equal(result.data.length, 3);
assert.deepEqual(Object.keys(result.data[0]).sort(), ['Code', 'Id', 'Model', 'Name', 'Unit']);
assert.doesNotMatch(f.queries[0].query, /EndingBalance|Quantity|Available/);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line({ quantity: 2000 })] })).status, 200);
assert.equal(f.state.catalog[0].Available, 0);
});
test('publishing freezes the saved snapshot; copying produces an editable independent revision', async t => {
const f = await fixture(t);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] })).status, 200);
assert.equal((await f.request(`/${id}/publish`, 'POST', { lockVersion: 2 })).status, 200);
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 3, lines: [] })).status, 409);
assert.equal((await f.request(`/${id}/publish`, 'POST', { lockVersion: 3 })).status, 409);
f.state.catalog[0].Name = 'New inventory name';
const snapshot = await f.request(`/${id}`);
assert.equal(snapshot.data.Lines[0].Name, 'Động cơ servo 400W');
const copied = await f.request('', 'POST', { robotId: 1, copyFromId: id });
assert.equal(copied.data.Revision, 2); assert.equal(copied.data.Status, 'draft');
await f.request(`/${copied.data.BomId}`, 'PUT', { lockVersion: 1, lines: [line({ quantity: 3 })] });
assert.equal((await f.request(`/${id}`)).data.Lines[0].Quantity, 2);
assert.equal((await f.request(`/${copied.data.BomId}`)).data.Lines[0].Quantity, 3);
assert.equal((await f.request(`/${copied.data.BomId}`)).data.Lines[0].SourceInfo, 'https://example.com/servo');
});
test('concurrent stale saves are rejected without overwriting newer quantities', async t => {
const f = await fixture(t);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line({ quantity: 99 })] })).status, 409);
assert.equal((await f.request(`/${id}/publish`, 'POST', { lockVersion: 1 })).status, 409);
assert.equal((await f.request(`/${id}`)).data.Lines[0].Quantity, 2);
});
test('an insert failure rolls back a complete BOM save including deleted old lines', async t => {
let fail = false;
const f = await fixture(t, { failQuery: query => fail && query.includes('INSERT dbo.RobotBomLines') });
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
fail = true;
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 2, lines: [line({ quantity: 3 })] })).status, 500);
assert.equal((await f.request(`/${id}`)).data.Lines[0].Quantity, 2);
assert.equal((await f.request(`/${id}`)).data.LockVersion, 2);
assert.equal(f.transactions.at(-1).rolledBack, true);
});
test('external parts and supplier descriptions work without any inventory records', async t => {
const f = await fixture(t);
f.state.catalog = [];
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
const lines = [line({ name: 'Khung gia công bên ngoài', model: 'CUSTOM-01', quantity: 12, sourceInfo: 'Nhà sản xuất: Cơ khí ABC, liên hệ bộ phận kỹ thuật' }), { name: 'Bulong M6' }];
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines })).status, 200);
const saved = (await f.request(`/${id}`)).data.Lines;
assert.equal(saved[0].Quantity, 12); assert.equal(saved[1].Quantity, 1);
assert.equal(saved[0].SourceInfo, lines[0].sourceInfo);
assert.equal((await f.request(`/${id}/publish`, 'POST', { lockVersion: 2 })).status, 200);
assert.equal((await f.request('/requirements/check', 'POST', {})).status, 404);
assert.equal(f.queries.some(({ query }) => /Inventory/.test(query)), false);
});
test('viewers can read BOMs and descriptive asset choices but cannot create, edit, publish or delete', async t => {
const f = await fixture(t, { role: 'user' });
for (const suffix of ['/models', '/catalog', '?model=AMR-500&typeId=1']) assert.equal((await f.request(suffix)).status, 200);
for (const [suffix, method] of [['', 'POST'], ['/1', 'PUT'], ['/1/publish', 'POST'], ['/1', 'DELETE']]) assert.equal((await f.request(suffix, method, { robotId: 1 })).status, 403);
assert.equal(f.transactions.length, 0);
});
for (const role of ['admin', 'asset']) {
for (const released of [false, true]) {
test(`${role} can delete a ${released ? 'released' : 'draft'} BOM with its lines while preserving copied revisions and inventory`, async t => {
const f = await fixture(t, { role });
const catalog = structuredClone(f.state.catalog);
const models = structuredClone(f.state.models);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
if (released) await f.request(`/${id}/publish`, 'POST', { lockVersion: 2 });
const copiedId = (await f.request('', 'POST', { copyFromId: id })).data.BomId;
const result = await f.request(`/${id}`, 'DELETE', { lockVersion: released ? 3 : 2 });
assert.equal(result.status, 200); assert.equal(result.success, true);
assert.equal((await f.request(`/${id}`)).status, 404);
assert.equal(f.state.lines.some(item => item.BomId === id), false);
assert.deepEqual((await f.request('?model=AMR-500&typeId=1')).data.map(item => item.BomId), [copiedId]);
assert.equal((await f.request(`/${copiedId}`)).data.Lines[0].Quantity, 2);
assert.deepEqual(f.state.catalog, catalog); assert.deepEqual(f.state.models, models);
const deletes = f.queries.filter(({ query }) => query.startsWith('DELETE'));
assert.equal(deletes.at(-1).transaction, deletes.at(-2).transaction);
assert.equal(f.transactions.at(-1).committed, true);
});
}
}
test('deletion rejects stale or invalid versions and invalid or missing BOM identifiers', async t => {
const f = await fixture(t);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion: 1 })).status, 409);
for (const lockVersion of [undefined, 0, -1, 'invalid']) {
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion })).status, 400);
}
for (const badId of ['abc', '0', '-1', '2147483648']) {
assert.equal((await f.request(`/${badId}`, 'DELETE', { lockVersion: 2 })).status, 400);
}
assert.equal((await f.request('/999', 'DELETE', { lockVersion: 2 })).status, 404);
assert.equal((await f.request(`/${id}`)).data.Lines[0].Quantity, 2);
assert.equal(f.queries.some(({ query }) => query.startsWith('DELETE FROM dbo.RobotBomRevisions')), false);
});
test('a header deletion failure rolls back removed BOM lines and allows retry', async t => {
let fail = true;
const f = await fixture(t, { failQuery: query => fail && query.includes('DELETE FROM dbo.RobotBomRevisions') });
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion: 2 })).status, 500);
assert.equal(f.transactions.at(-1).rolledBack, true);
const retained = (await f.request(`/${id}`)).data;
assert.equal(retained.LockVersion, 2); assert.equal(retained.Lines[0].Quantity, 2);
fail = false;
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion: 2 })).status, 200);
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion: 2 })).status, 404);
});
test('deleting the final historical BOM removes its orphaned model and supports an empty BOM', async t => {
const f = await fixture(t);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
f.state.models = [];
assert.equal((await f.request('/models')).data.length, 1);
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion: 1 })).status, 200);
assert.deepEqual((await f.request('/models')).data, []);
assert.deepEqual((await f.request('?model=AMR-500&typeId=1')).data, []);
});
test('bad identifiers, empty publications, invalid lines and unsafe quantities are rejected', async t => {
const f = await fixture(t);
assert.equal((await f.request('/abc')).status, 400);
assert.equal((await f.request('/999')).status, 404);
assert.equal((await f.request('', 'POST', { robotId: 999 })).status, 404);
assert.equal((await f.request('', 'POST')).status, 400);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
assert.equal((await f.request(`/${id}/publish`, 'POST', { lockVersion: 1 })).status, 400);
for (const bad of [null, [null], [line({ name: '' })], [line({ name: ' '.repeat(2) })], [line({ model: 'x'.repeat(256) })], [line({ sourceInfo: 'x'.repeat(1001) })], [line({ quantity: -1 })], [line({ quantity: 0.5 })], Array(501).fill(line())]) {
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: bad })).status, 400);
}
for (const value of [0, -1, 100001, 'NaN', Infinity, '1e4', 0.00001]) assert.throws(() => quantity(value, 'm'));
assert.equal(quantity(0.125, 'm'), 0.125);
});
test('a name alone is sufficient; inventory identity is discarded while descriptive metadata is retained', () => {
const normalized = normalizeLines([{ name: 'Cảm biến ngoài', sourceType: 'asset', sourceId: 999 }])[0];
assert.equal(normalized.Name, 'Cảm biến ngoài'); assert.equal(normalized.Quantity, 1);
assert.equal(normalized.Model, ''); assert.equal(normalized.Unit, '');
assert.equal(normalized.SourceType, 'manual'); assert.equal(normalized.SourceId, null);
assert.equal(normalizeLines([line(), line()]).length, 2);
assert.equal(normalizeLines([line({ unit: '', quantity: 0.125 })])[0].Quantity, 0.125);
assert.deepEqual(normalizeLines([]), []);
});
test('historical models and revisions remain accessible after their last robot is removed', async t => {
const f = await fixture(t);
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
f.state.models = [];
const models = await f.request('/models');
assert.equal(models.data[0].Model, 'AMR-500'); assert.equal(models.data[0].RobotId, null);
assert.equal((await f.request('?model=AMR-500&typeId=1')).data.length, 1);
const copied = await f.request('', 'POST', { copyFromId: id });
assert.equal(copied.status, 201); assert.equal(copied.data.Revision, 2);
assert.equal((await f.request(`/${copied.data.BomId}`)).data.Lines.length, 1);
});

View File

@@ -75,7 +75,7 @@ function createRobotRouter({ getPool, sql, requireManage, documentMaxBytes, docu
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 res.status(409).json({ success: false, message: 'Thể loại đang được robot hoặc BOM sử dụng. Không thể xóa để bảo toàn dữ liệu liên quan.' });
}
return fail(res, error);
}

18
backend/run-tests.js Normal file
View File

@@ -0,0 +1,18 @@
const fs = require('node:fs');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
// Restrict discovery to source tests. Browser profiles in tmp/ can contain
// third-party extension *.test.js files and must never enter the project suite.
function discover(directory) {
if (!fs.existsSync(directory)) return [];
return fs.readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
const target = path.join(directory, entry.name);
if (entry.isDirectory() && entry.name !== 'node_modules') return discover(target);
return entry.isFile() && /\.test\.[cm]?js$/.test(entry.name) ? [target] : [];
});
}
const files = [__dirname, path.resolve(__dirname, '../test')].flatMap(discover);
const result = spawnSync(process.execPath, ['--test', ...process.argv.slice(2), ...files], { stdio: 'inherit' });
if (result.error) console.error(result.error.message);
process.exitCode = result.status ?? 1;

View File

@@ -13,10 +13,13 @@ const dotenv = require('dotenv');
const helmet = require('helmet');
const { rateLimit } = require('express-rate-limit');
const { ensureAssetArchiveSchema } = require('./asset-archive-schema');
const { parseAllocations, normalizeExportAllocations, addAllocations, releaseAllocations } = require('./asset-project-allocations');
const { parseAllocations, addProjectExports, releaseAllocations } = require('./asset-project-allocations');
const { buildExportRequestWorkbook } = require('./export-request-workbook');
const { ensureAssetExportDocumentSchema } = require('./asset-export-documents');
const { ensureAssetExportRequestSchema, createAssetExportWorkflow } = require('./asset-export-requests');
const { ensureRobotSchema, createRobotRouter } = require('./robots');
const { ensureRobotBomSchema, createRobotBomRouter } = require('./robot-bom');
const { createAnnouncementRouter } = require('./announcements');
const { getDocumentFormat, isPdfBuffer, validateDocumentFile, normalizeUploadedFileName,
sanitizeDocumentFileName, getDocumentContentDisposition, accept: documentAccept } = require('./document-files');
@@ -3070,6 +3073,18 @@ async function createTables() {
)
END`,
`IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'NotificationPopupDismissals')
BEGIN
CREATE TABLE NotificationPopupDismissals (
NotificationId BIGINT NOT NULL,
UserId INT NOT NULL,
DismissedAt DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
PRIMARY KEY (NotificationId, UserId),
FOREIGN KEY (NotificationId) REFERENCES Notifications(NotificationId) ON DELETE CASCADE,
FOREIGN KEY (UserId) REFERENCES Users(UserId) ON DELETE CASCADE
)
END`,
// AuditLog Table
`IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'AuditLog')
BEGIN
@@ -3098,7 +3113,9 @@ async function createTables() {
// Fail startup if history preservation cannot be installed.
await ensureAssetArchiveSchema(pool);
await ensureAssetExportDocumentSchema(pool);
await ensureAssetExportRequestSchema(pool);
await ensureRobotSchema(pool);
await ensureRobotBomSchema(pool);
await pool.request().query(`
IF COL_LENGTH('dbo.AssetInventory', 'ProjectAllocations') IS NULL
ALTER TABLE dbo.AssetInventory ADD ProjectAllocations NVARCHAR(MAX) NULL;
@@ -4271,6 +4288,11 @@ async function safeCreateSystemNotification(payload) {
// API ROUTES - Notifications
// ==========================================
app.use('/api/notifications', createAnnouncementRouter({
getPool: () => pool, sql, requireManage: requireAssetOrAdmin,
getUserId: getUserIdFromRequest, getRole: getRequesterRole, sendInternalError
}));
app.get('/api/notifications', async (req, res) => {
try {
const userId = getUserIdFromRequest(req);
@@ -4358,7 +4380,7 @@ app.get('/api/notifications', async (req, res) => {
}
});
app.post('/api/notifications', requireAdmin, async (req, res) => {
app.post('/api/notifications', requireAssetOrAdmin, async (req, res) => {
try {
const title = String(req.body?.title || '').trim();
const message = String(req.body?.message || '').trim();
@@ -4377,7 +4399,7 @@ app.post('/api/notifications', requireAdmin, async (req, res) => {
if (rawActionUrl && !actionUrl) {
return res.status(400).json({ success: false, message: 'Liên kết chỉ được dùng đường dẫn nội bộ bắt đầu bằng / hoặc #' });
}
if (expiresAt && (Number.isNaN(expiresAt.getTime()) || expiresAt.getTime() <= Date.now())) {
if (!expiresAt || Number.isNaN(expiresAt.getTime()) || expiresAt.getTime() <= Date.now()) {
return res.status(400).json({ success: false, message: 'Thời gian hết hạn phải ở tương lai' });
}
@@ -4488,7 +4510,7 @@ app.put('/api/notifications/:id/read', async (req, res) => {
}
});
app.delete('/api/notifications/:id', requireAdmin, async (req, res) => {
app.delete('/api/notifications/:id', requireAssetOrAdmin, async (req, res) => {
try {
const notificationId = Number(req.params.id);
if (!Number.isInteger(notificationId) || notificationId <= 0) {
@@ -4497,10 +4519,13 @@ app.delete('/api/notifications/:id', requireAdmin, async (req, res) => {
const result = await pool.request()
.input('notificationId', sql.BigInt, notificationId)
.input('userId', sql.Int, getUserIdFromRequest(req))
.input('isAdmin', sql.Bit, getRequesterRole(req) === 'admin')
.query(`
UPDATE Notifications
SET IsActive = 0
WHERE NotificationId = @notificationId AND Source = 'admin' AND IsActive = 1;
WHERE NotificationId = @notificationId AND Source = 'admin' AND IsActive = 1
AND (@isAdmin = 1 OR CreatedBy = @userId);
SELECT @@ROWCOUNT AS Affected;
`);
@@ -8566,11 +8591,12 @@ app.get('/api/assets/:id', async (req, res) => {
}
});
app.get('/api/asset-export-history', requireAssetOrAdmin, async (req, res) => {
app.get('/api/asset-export-history', async (req, res) => {
try {
const limit = Math.min(parsePositiveInteger(req.query.limit, 300), 2000);
const result = await pool.request()
.input('limit', sql.Int, limit)
.input('requesterId', sql.Int, getUserIdFromRequest(req) || -1)
.query(`
SELECT TOP (@limit)
h.ExportHistoryId, h.AssetId, h.AssetCode, h.AssetName,
@@ -8579,6 +8605,7 @@ app.get('/api/asset-export-history', requireAssetOrAdmin, async (req, res) => {
h.ExportDocumentId, d.FileName AS DocumentFileName
FROM AssetExportHistory h
LEFT JOIN AssetExportDocuments d ON d.ExportDocumentId = h.ExportDocumentId
${['admin', 'asset'].includes(getRequesterRole(req)) ? '' : 'WHERE h.CreatedBy = @requesterId'}
ORDER BY h.ExportedDate DESC, h.ExportHistoryId DESC
`);
@@ -8595,11 +8622,13 @@ function isExportDocumentId(value) {
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(String(value || ''));
}
app.get('/api/asset-export-documents/:id', requireAssetOrAdmin, async (req, res) => {
app.get('/api/asset-export-documents/:id', async (req, res) => {
if (!isExportDocumentId(req.params.id)) return res.status(400).json({ success: false, message: 'Mã phiếu không hợp lệ.' });
try {
const result = await pool.request().input('documentId', sql.UniqueIdentifier, req.params.id).query(`
const result = await pool.request().input('documentId', sql.UniqueIdentifier, req.params.id)
.input('requesterId', sql.Int, getUserIdFromRequest(req) || -1).query(`
SELECT ExportDocumentId, FileName, SnapshotJson FROM AssetExportDocuments WHERE ExportDocumentId = @documentId
${['admin', 'asset'].includes(getRequesterRole(req)) ? '' : 'AND CreatedBy = @requesterId'}
`);
const document = result.recordset?.[0];
if (!document) return res.status(404).json({ success: false, message: 'Không tìm thấy phiếu xuất đã lưu.' });
@@ -8609,11 +8638,13 @@ app.get('/api/asset-export-documents/:id', requireAssetOrAdmin, async (req, res)
} catch (err) { sendInternalError(res, err); }
});
app.get('/api/asset-export-documents/:id/download', requireAssetOrAdmin, async (req, res) => {
app.get('/api/asset-export-documents/:id/download', async (req, res) => {
if (!isExportDocumentId(req.params.id)) return res.status(400).json({ success: false, message: 'Mã phiếu không hợp lệ.' });
try {
const result = await pool.request().input('documentId', sql.UniqueIdentifier, req.params.id).query(`
const result = await pool.request().input('documentId', sql.UniqueIdentifier, req.params.id)
.input('requesterId', sql.Int, getUserIdFromRequest(req) || -1).query(`
SELECT FileName, MimeType, FileContent FROM AssetExportDocuments WHERE ExportDocumentId = @documentId
${['admin', 'asset'].includes(getRequesterRole(req)) ? '' : 'AND CreatedBy = @requesterId'}
`);
const document = result.recordset?.[0];
if (!document) return res.status(404).json({ success: false, message: 'Không tìm thấy file Excel đã lưu.' });
@@ -8908,7 +8939,7 @@ app.post('/api/assets/:id/damage-disposal', requireAssetOrAdmin, async (req, res
}
});
function prepareAssetExport(asset, allocations, borrowerName, exportNote) {
function prepareAssetExport(asset, allocations, exportNote) {
const fail = message => { throw Object.assign(new Error(message), { statusCode: 400 }); };
const exportQuantity = allocations.reduce((sum, row) => sum + row.quantity, 0);
const quantity = parseNonNegativeInteger(asset.Quantity, 0);
@@ -8922,144 +8953,107 @@ function prepareAssetExport(asset, allocations, borrowerName, exportNote) {
const label = String(asset.AssetCode || asset.AssetName || asset.AssetId);
if (available <= 0) fail(`${label}: Tài sản đã hết tồn cuối kỳ, không thể xuất thêm.`);
if (exportQuantity > available) fail(`${label}: Số lượng xuất (${exportQuantity}) vượt quá tồn cuối kỳ (${available}).`);
const borrower = mergeBorrowerEntries(asset.Borrower, borrowerName, exportQuantity);
if (borrower && borrower.length > 255) fail('Danh sách người mượn quá dài, vui lòng rút gọn tên.');
const exportDelta = parseBorrowerEntries(borrower)
.reduce((sum, entry) => sum + parseNonNegativeInteger(entry?.quantity, 0), 0) - previousBorrowerExport;
// Permanent project exports never enter the returnable borrower ledger.
const exportDelta = exportQuantity;
const stock = normalizeAssetStockBuckets(available,
parseOptionalNonNegativeInteger(asset.NewQuantity) ?? available,
parseOptionalNonNegativeInteger(asset.UsedQuantity) ?? 0);
const borrowFromNew = Math.min(stock.newQuantity, exportDelta);
const exportFromNew = Math.min(stock.newQuantity, exportDelta);
const endingBalance = Math.max(available - exportDelta, 0);
const exportInPeriod = Math.max(baseExportInPeriod + exportDelta, 0);
const oldNotes = String(asset.Notes || '').trim();
return { asset, allocations, available, borrower, endingBalance, exportInPeriod,
newQuantity: Math.max(stock.newQuantity - borrowFromNew, 0),
usedQuantity: Math.max(stock.usedQuantity - Math.max(exportDelta - borrowFromNew, 0), 0),
return { asset, allocations, available, endingBalance, exportInPeriod,
newQuantity: Math.max(stock.newQuantity - exportFromNew, 0),
usedQuantity: Math.max(stock.usedQuantity - Math.max(exportDelta - exportFromNew, 0), 0),
status: resolveAssetStatusFromStock(endingBalance, exportInPeriod),
notes: exportNote ? (oldNotes ? `${oldNotes}\n${exportNote}` : exportNote) : (oldNotes || null) };
}
async function handleAssetExport(req, res, singleAssetId) {
let transaction;
try {
const rawItems = singleAssetId === undefined ? req.body?.items : [{ ...req.body, assetId: singleAssetId }];
let items;
try {
if (!Array.isArray(rawItems) || !rawItems.length || rawItems.length > 100) throw new Error('Vui lòng chọn từ 1 đến 100 tài sản.');
const seen = new Set();
items = rawItems.map(row => {
const assetId = Number(row?.assetId);
if (!Number.isSafeInteger(assetId) || assetId <= 0 || assetId > 2147483647) throw new Error('Mã tài sản không hợp lệ.');
if (seen.has(assetId)) throw new Error('Mỗi tài sản chỉ được xuất hiện một lần trong phiếu.');
seen.add(assetId);
return { assetId, allocations: normalizeExportAllocations(row) };
});
if (items.reduce((sum, item) => sum + item.allocations.length, 0) > 100) throw new Error('Một phiếu chỉ hỗ trợ tối đa 100 dòng tài sản / dự án.');
} catch (err) {
return res.status(400).json({ success: false, message: err.message });
}
const borrowerName = String(req.body?.borrowerName || req.body?.custodianName || '').trim();
const exportNote = String(req.body?.note || '').trim() || null;
if (!borrowerName || borrowerName.length > 100) return res.status(400).json({ success: false, message: 'Vui lòng chọn người mượn, tối đa 100 ký tự.' });
if (exportNote && exportNote.length > 1000) return res.status(400).json({ success: false, message: 'Ghi chú xuất tối đa 1000 ký tự.' });
const createdBy = getUserIdFromRequest(req);
const exportedByName = await getUserDisplayNameById(createdBy) || req.user?.FullName || req.user?.Username || 'Unknown';
const exportedDate = new Date();
transaction = new sql.Transaction(pool);
await transaction.begin();
const lockedAssets = new Map();
// Consistent lock order avoids deadlocks between overlapping batches.
for (const { assetId } of [...items].sort((a, b) => a.assetId - b.assetId)) {
const result = await new sql.Request(transaction).input('assetId', sql.Int, assetId).query(`
SELECT TOP 1 AssetId, AssetCode, AssetName, Quantity, ImportInPeriod, ExportInPeriod,
EndingBalance, NewQuantity, UsedQuantity, Custodian, Borrower, ProjectAllocations,
Model, SerialNumber, Unit, Department, Notes
FROM AssetInventory WITH (UPDLOCK, ROWLOCK)
WHERE AssetId = @assetId AND IsArchived = 0
`);
if (!result.recordset?.[0]) throw Object.assign(new Error(`Không tìm thấy tài sản ${assetId} trong danh mục hiện tại.`), { statusCode: 404 });
lockedAssets.set(assetId, result.recordset[0]);
}
// Validate every asset before creating the file or writing any inventory.
const plans = items.map(item => prepareAssetExport(lockedAssets.get(item.assetId), item.allocations, borrowerName, exportNote));
const workbookItems = plans.map(plan => ({ item: plan.asset, rows: plan.allocations, availableStock: plan.available }));
const document = await buildExportRequestWorkbook({
...(plans.length === 1 ? workbookItems[0] : { items: workbookItems }),
requesterName: borrowerName, recipientName: borrowerName, exportedByName, note: exportNote, exportedDate
});
const documentId = crypto.randomUUID();
const snapshot = { version: 1, exportedDate: exportedDate.toISOString(), borrowerName, exportedByName, note: exportNote,
items: plans.map(plan => ({ assetId: plan.asset.AssetId, assetCode: plan.asset.AssetCode,
assetName: plan.asset.AssetName, model: plan.asset.Model, serialNumber: plan.asset.SerialNumber,
unit: plan.asset.Unit, department: plan.asset.Department, availableStock: plan.available,
allocations: plan.allocations })) };
async function performAssetExport(transaction, plans, { createdBy, requesterName, exportedByName, exportNote }) {
const exportedDate = new Date();
const workbookItems = plans.map(plan => ({ item: plan.asset, rows: plan.allocations, availableStock: plan.available }));
const document = await buildExportRequestWorkbook({
...(plans.length === 1 ? workbookItems[0] : { items: workbookItems }),
requesterName, recipientName: requesterName, exportedByName, note: exportNote, exportedDate
});
const documentId = crypto.randomUUID();
const snapshot = { version: 1, exportedDate: exportedDate.toISOString(), borrowerName: requesterName, requesterName, exportedByName, note: exportNote,
items: plans.map(plan => ({ assetId: plan.asset.AssetId, assetCode: plan.asset.AssetCode,
assetName: plan.asset.AssetName, model: plan.asset.Model, serialNumber: plan.asset.SerialNumber,
unit: plan.asset.Unit, department: plan.asset.Department, availableStock: plan.available,
allocations: plan.allocations })) };
await new sql.Request(transaction)
.input('documentId', sql.UniqueIdentifier, documentId)
.input('fileName', sql.NVarChar(255), document.fileName)
.input('mimeType', sql.NVarChar(150), document.mimeType)
.input('fileContent', sql.VarBinary(sql.MAX), Buffer.from(document.contentBase64, 'base64'))
.input('snapshotJson', sql.NVarChar(sql.MAX), JSON.stringify(snapshot))
.input('createdBy', sql.Int, createdBy)
.input('exportedDate', sql.DateTime, exportedDate)
.query(`INSERT INTO AssetExportDocuments (ExportDocumentId, FileName, MimeType, FileContent, SnapshotJson, CreatedBy, ExportedDate)
VALUES (@documentId, @fileName, @mimeType, @fileContent, @snapshotJson, @createdBy, @exportedDate)`);
const histories = [];
for (const plan of plans) {
const { asset } = plan;
await new sql.Request(transaction)
.input('documentId', sql.UniqueIdentifier, documentId)
.input('fileName', sql.NVarChar(255), document.fileName)
.input('mimeType', sql.NVarChar(150), document.mimeType)
.input('fileContent', sql.VarBinary(sql.MAX), Buffer.from(document.contentBase64, 'base64'))
.input('snapshotJson', sql.NVarChar(sql.MAX), JSON.stringify(snapshot))
.input('createdBy', sql.Int, createdBy)
.input('exportedDate', sql.DateTime, exportedDate)
.query(`INSERT INTO AssetExportDocuments (ExportDocumentId, FileName, MimeType, FileContent, SnapshotJson, CreatedBy, ExportedDate)
VALUES (@documentId, @fileName, @mimeType, @fileContent, @snapshotJson, @createdBy, @exportedDate)`);
const histories = [];
for (const plan of plans) {
const { asset } = plan;
await new sql.Request(transaction)
.input('assetId', sql.Int, asset.AssetId)
// No borrower: returns can release loans while keeping these project exports.
.input('projectAllocations', sql.NVarChar(sql.MAX), JSON.stringify(addProjectExports(asset.ProjectAllocations, plan.allocations)))
.input('exportInPeriod', sql.Int, plan.exportInPeriod)
.input('endingBalance', sql.Int, plan.endingBalance)
.input('newQuantity', sql.Int, plan.newQuantity)
.input('usedQuantity', sql.Int, plan.usedQuantity)
.input('status', sql.NVarChar, plan.status)
.input('exportedBy', sql.NVarChar, exportedByName)
.input('notes', sql.NVarChar, plan.notes)
.query(`UPDATE AssetInventory SET ProjectAllocations = @projectAllocations,
ExportInPeriod = @exportInPeriod, EndingBalance = @endingBalance, NewQuantity = @newQuantity,
UsedQuantity = @usedQuantity, Status = @status, ExportedBy = @exportedBy, Notes = @notes,
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
WHERE AssetId = @assetId AND IsArchived = 0`);
for (const allocation of plan.allocations) {
const result = await new sql.Request(transaction)
.input('assetId', sql.Int, asset.AssetId)
.input('projectAllocations', sql.NVarChar(sql.MAX), JSON.stringify(addAllocations(asset.ProjectAllocations, plan.allocations, borrowerName)))
.input('borrower', sql.NVarChar, plan.borrower)
.input('exportInPeriod', sql.Int, plan.exportInPeriod)
.input('endingBalance', sql.Int, plan.endingBalance)
.input('newQuantity', sql.Int, plan.newQuantity)
.input('usedQuantity', sql.Int, plan.usedQuantity)
.input('status', sql.NVarChar, plan.status)
.input('exportedBy', sql.NVarChar, exportedByName)
.input('notes', sql.NVarChar, plan.notes)
.query(`UPDATE AssetInventory SET ProjectAllocations = @projectAllocations, Borrower = @borrower,
ExportInPeriod = @exportInPeriod, EndingBalance = @endingBalance, NewQuantity = @newQuantity,
UsedQuantity = @usedQuantity, Status = @status, ExportedBy = @exportedBy, Notes = @notes,
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
WHERE AssetId = @assetId AND IsArchived = 0`);
for (const allocation of plan.allocations) {
const result = await new sql.Request(transaction)
.input('assetId', sql.Int, asset.AssetId)
.input('assetCode', sql.NVarChar, String(asset.AssetCode || '').trim())
.input('assetName', sql.NVarChar, String(asset.AssetName || '').trim())
.input('exportQuantity', sql.Int, allocation.quantity)
.input('projectName', sql.NVarChar, allocation.projectName)
.input('custodianName', sql.NVarChar, String(asset.Custodian || '').trim() || '-')
.input('exportedByName', sql.NVarChar, exportedByName)
.input('exportNote', sql.NVarChar, exportNote)
.input('createdBy', sql.Int, createdBy)
.input('exportedDate', sql.DateTime, exportedDate)
.input('documentId', sql.UniqueIdentifier, documentId)
.query(`INSERT INTO AssetExportHistory (AssetId, AssetCode, AssetName, ExportQuantity, ProjectName,
CustodianName, ExportedByName, ExportNote, CreatedBy, ExportedDate, ExportDocumentId)
OUTPUT INSERTED.*
VALUES (@assetId, @assetCode, @assetName, @exportQuantity, @projectName,
@custodianName, @exportedByName, @exportNote, @createdBy, @exportedDate, @documentId)`);
histories.push(result.recordset?.[0] || null);
}
.input('assetCode', sql.NVarChar, String(asset.AssetCode || '').trim())
.input('assetName', sql.NVarChar, String(asset.AssetName || '').trim())
.input('exportQuantity', sql.Int, allocation.quantity)
.input('projectName', sql.NVarChar, allocation.projectName)
.input('custodianName', sql.NVarChar, String(asset.Custodian || '').trim() || '-')
.input('exportedByName', sql.NVarChar, exportedByName)
.input('exportNote', sql.NVarChar, exportNote)
.input('createdBy', sql.Int, createdBy)
.input('exportedDate', sql.DateTime, exportedDate)
.input('documentId', sql.UniqueIdentifier, documentId)
.query(`INSERT INTO AssetExportHistory (AssetId, AssetCode, AssetName, ExportQuantity, ProjectName,
CustodianName, ExportedByName, ExportNote, CreatedBy, ExportedDate, ExportDocumentId)
OUTPUT INSERTED.*
VALUES (@assetId, @assetCode, @assetName, @exportQuantity, @projectName,
@custodianName, @exportedByName, @exportNote, @createdBy, @exportedDate, @documentId)`);
histories.push(result.recordset?.[0] || null);
}
await transaction.commit();
res.json({ success: true, message: 'Xuất tài sản thành công',
data: singleAssetId !== undefined && req.body.allocations === undefined ? histories[0] : histories,
document: { ...document, documentId } });
} catch (err) {
if (transaction) {
try { await transaction.rollback(); } catch (_rollbackErr) { /* Preserve the original error. */ }
}
if (err.statusCode) res.status(err.statusCode).json({ success: false, message: err.message });
else sendInternalError(res, err);
}
return { document: { ...document, documentId }, histories };
}
app.post('/api/assets/export', requireAssetOrAdmin, (req, res) => handleAssetExport(req, res));
app.post('/api/assets/:id/export', requireAssetOrAdmin, (req, res) => handleAssetExport(req, res, req.params.id));
const assetExportWorkflow = createAssetExportWorkflow({
getPool: () => pool, sql, requireManage: requireAssetOrAdmin, getRequesterRole, getUserIdFromRequest,
getUserDisplayNameById: id => getUserDisplayNameById(id), prepareAssetExport, performAssetExport, sendInternalError,
notifyCreated: target => safeCreateSystemNotification({
severity: 'info', title: 'Đơn xuất vào dự án mới',
message: `${target.RequesterName} đã gửi đơn xuất #${target.ExportRequestId}, chờ duyệt.`,
actionUrl: '#asset-exports', audiences: [{ type: 'role', value: 'admin' }, { type: 'role', value: 'asset' }]
}),
notifyProcessed: (target, action, rejectReason) => safeCreateSystemNotification({
severity: action === 'approved' ? 'success' : 'error',
title: action === 'approved' ? 'Đơn xuất dự án được duyệt' : 'Đơn xuất dự án bị từ chối',
message: `Đơn xuất #${target.ExportRequestId} đã ${action === 'approved' ? 'được duyệt và trừ kho' : `bị từ chối. Lý do: ${rejectReason}`}.`,
actionUrl: '#asset-exports', audiences: [{ type: 'user', value: Number(target.CreatedBy) }]
})
});
app.use('/api/asset-export-requests', assetExportWorkflow.router);
app.post('/api/assets/export', requireAssetOrAdmin, (req, res) => assetExportWorkflow.directExport(req, res));
app.post('/api/assets/:id/export', requireAssetOrAdmin, (req, res) => assetExportWorkflow.directExport(req, res, req.params.id));
app.post('/api/assets', requireAssetOrAdmin, async (req, res) => {
try {
@@ -9529,6 +9523,10 @@ app.use('/api/robots', createRobotRouter({
sanitizeDocumentFileName, sendInternalError
}));
app.use('/api/robot-boms', createRobotBomRouter({
getPool: () => pool, sql, requireManage: requireAssetOrAdmin, sendInternalError
}));
app.get('/api/documents', async (req, res) => {
try {
const search = String(req.query.search || '').trim().slice(0, 255);
@@ -9715,6 +9713,10 @@ app.get('/api/database/info', requireAdmin, async (req, res) => {
// Error Handling
// ==========================================
app.use('/api', (req, res) => {
res.status(404).json({ success: false, code: 'API_NOT_FOUND', message: 'API không tồn tại. Vui lòng cập nhật backend rồi thử lại.' });
});
app.use((err, req, res, next) => {
console.error('Unhandled request error:', err.message);
if (err instanceof multer.MulterError) {

View File

@@ -923,6 +923,19 @@ BEGIN
END
-- ===========================================
-- Popup dismissal is independent of the per-user read receipt.
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'NotificationPopupDismissals')
BEGIN
CREATE TABLE NotificationPopupDismissals (
NotificationId BIGINT NOT NULL,
UserId INT NOT NULL,
DismissedAt DATETIME NOT NULL DEFAULT(DATEADD(HOUR, 7, SYSUTCDATETIME())),
PRIMARY KEY (NotificationId, UserId),
FOREIGN KEY (NotificationId) REFERENCES Notifications(NotificationId) ON DELETE CASCADE,
FOREIGN KEY (UserId) REFERENCES Users(UserId) ON DELETE CASCADE
);
END
-- 12. CREATE AUDIT LOG TABLE
-- ===========================================
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'AuditLog')
@@ -1391,3 +1404,39 @@ BEGIN CATCH
END CATCH;
GO
GO
-- Project export approval workflow. Preserves legacy exports.
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
IF OBJECT_ID('dbo.AssetExportRequests', 'U') IS NULL
BEGIN
CREATE TABLE dbo.AssetExportRequests (
ExportRequestId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
RequesterName NVARCHAR(100) NOT NULL,
ItemsJson NVARCHAR(MAX) NOT NULL,
RequestNote NVARCHAR(1000) NULL,
RequestStatus NVARCHAR(20) NOT NULL DEFAULT 'pending',
CreatedBy INT NOT NULL,
CreatedDate DATETIME NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
ProcessedBy INT NULL,
ProcessedByName NVARCHAR(100) NULL,
ProcessedDate DATETIME NULL,
RejectReason NVARCHAR(1000) NULL,
ExportDocumentId UNIQUEIDENTIFIER NULL,
CONSTRAINT CK_AssetExportRequests_Status CHECK (RequestStatus IN ('pending', 'approved', 'rejected')),
CONSTRAINT FK_AssetExportRequests_User FOREIGN KEY (CreatedBy) REFERENCES dbo.Users(UserId),
CONSTRAINT FK_AssetExportRequests_Document FOREIGN KEY (ExportDocumentId) REFERENCES dbo.AssetExportDocuments(ExportDocumentId)
);
CREATE INDEX IX_AssetExportRequests_Creator ON dbo.AssetExportRequests(CreatedBy, CreatedDate DESC);
CREATE INDEX IX_AssetExportRequests_Status ON dbo.AssetExportRequests(RequestStatus, CreatedDate DESC);
END;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
THROW;
END CATCH;
GO

View File

@@ -1,34 +0,0 @@
# Thay dữ liệu tài sản, giữ lịch sử mượn trả
Chức năng **Xóa danh mục hiện tại** đưa các tài sản hiện tại vào dữ liệu cũ. Phiếu mượn, phiếu trả, các lần trả một phần, danh sách người đang mượn và lịch sử xuất/hư hỏng/thanh lý vẫn được giữ.
## Các bước thực hiện
1. Sao lưu cơ sở dữ liệu SQL Server trước khi thay dữ liệu. Triển khai bản ứng dụng có chức năng lưu trữ tài sản này trước khi thao tác xóa.
2. Đăng nhập bằng tài khoản **Admin** hoặc **Quản lý tài sản**. Mở **Quản lý tài sản** → **Xóa danh mục hiện tại**, đọc nội dung rồi xác nhận. Thao tác áp dụng cho toàn bộ danh mục hiện tại, kể cả tài sản ở trang khác hoặc đang bị bộ lọc ẩn.
3. Upload file tài sản mới bằng chức năng nhập Excel hiện có. Mã tài sản được phép trùng với mã trong dữ liệu cũ. Bản ghi mới có tồn kho riêng; lịch sử cũ tiếp tục gắn với bản ghi cũ.
4. Mở **Mượn/Trả tài sản**, chọn bộ lọc **Đơn → Còn đang mượn**. Chọn thêm **Tài sản → Tài sản cũ** nếu chỉ muốn xem các phiếu của danh mục đã xóa. Số lượng còn mượn bằng số đã mượn trừ số đã được xác nhận trả. Đơn trả đang chờ duyệt chưa được trừ.
5. Mở **Tài sản cũ** để xem toàn bộ tài sản đã xóa khỏi danh mục hiện tại, kể cả tài sản không còn người mượn. Danh sách vẫn hiển thị số lượng còn mượn và người mượn được nhập từ Excel hoặc ghi khi xuất trực tiếp mà chưa có phiếu mượn riêng. Màn hình **Tài sản tôi đang mượn** cũng giữ các tài sản cũ còn đang mượn.
## Xử lý mượn trả sau khi thay dữ liệu
- Phiếu mượn cũ vẫn xem được lịch sử và tạo/duyệt đơn trả theo luồng hiện có. Trả một phần vẫn nằm trong danh sách còn đang mượn.
- Việc trả tài sản cũ cập nhật bản ghi và lịch sử cũ. Muốn đưa số lượng này vào danh mục mới, đối chiếu rồi nhập kho mới riêng; hệ thống không tự ghép chỉ vì trùng mã.
- Tài sản cũ không được sửa hoặc xuất/mượn thêm. Đơn mượn cũ còn chờ xử lý không được duyệt; người quản lý có thể từ chối đơn đó.
- Xóa một tài sản hoặc **Xóa đã chọn** cũng giữ lịch sử theo cùng cơ chế.
Không dùng `DELETE`/`TRUNCATE` bảng tài sản, xóa các bảng mượn trả, hoặc tạo lại database để làm trống danh mục. Chức năng trong giao diện chỉ đánh dấu `IsArchived = 1` trong database; toàn bộ bản ghi cũ vẫn còn và xem được tại **Tài sản cũ**. Dữ liệu đã bị xóa bởi phiên bản trước chỉ có thể lấy lại từ bản sao lưu phù hợp.
## Triển khai
Ứng dụng tự chạy migration khi khởi động: thêm trạng thái lưu trữ, cho phép tái sử dụng mã tài sản trong danh mục mới và bảo vệ các liên kết lịch sử khỏi xóa dây chuyền. Migration không tự xóa hoặc lưu trữ tài sản nào. Nếu migration lỗi, ứng dụng dừng khởi động để người triển khai kiểm tra log.
Build/push image mới, cập nhật `DOCKER_IMAGE` trên máy chủ, rồi chạy:
```bash
docker compose --env-file .env -f docker-compose.image.yml pull accmanager
docker compose --env-file .env -f docker-compose.image.yml up -d accmanager
docker compose --env-file .env -f docker-compose.image.yml logs --tail=100 accmanager
```
Kiểm tra ứng dụng khởi động thành công và có nút **Xóa danh mục hiện tại** trước khi thay dữ liệu.

View File

@@ -1,70 +0,0 @@
# Phiếu đề nghị xuất Excel
Khi xác nhận **Xuất và tải Excel**, hệ thống ghi nhận xuất kho và tự tải phiếu theo mẫu **BM-XUATVT-01**. Áp dụng cho tài sản và vật tư tiêu hao; khi mượn vật tư, nút hiển thị **Mượn và tải Excel**. Hộp thoại sau khi xuất có nút **Tải lại phiếu Excel**, chỉ tải lại file vừa tạo, không xuất kho lần nữa.
## Xuất nhiều tài sản và tải lại từ lịch sử
Chọn một hoặc nhiều dòng trong **Quản lý tài sản**, rồi bấm **Xuất tài sản**. Khi chọn nhiều tài sản, biểu mẫu cho phép nhập số lượng và dự án riêng cho từng tài sản, hoặc áp dụng một dự án chung. Chọn người mượn và bấm **Xuất và tải Excel** để tạo một phiếu chung. Một tài sản vẫn dùng biểu mẫu hiện có, hỗ trợ chia số lượng cho nhiều dự án.
Trong **Lịch sử xuất tài sản**, cột **Phiếu Excel** có **Xem phiếu** để xem nội dung tại thời điểm xuất và **Tải Excel** để lấy lại nguyên file đã lưu. Các dòng tài sản/dự án thuộc cùng một lần xuất trỏ đến cùng một phiếu. Đổi tên, sửa kho, lưu trữ tài sản hoặc khởi động lại ứng dụng không làm thay đổi phiếu đã lưu. Lịch sử cũ chưa từng lưu file hiển thị **Chưa lưu file**; hệ thống không tạo lại file cũ bằng dữ liệu kho hiện tại.
Backend tự cài đặt migration `backend/asset-export-documents.sql` khi khởi động. Cần triển khai mã mới và khởi động lại backend để tạo bảng lưu file trước khi sử dụng tính năng. `database/setup.sql` cũng bao gồm migration này.
## Review bằng dữ liệu test
Chạy từ thư mục dự án:
```powershell
npm run review:export
```
Mở **http://127.0.0.1:4317**. Trang review dùng biểu mẫu và các hàm xử lý xuất hiện tại với dữ liệu giả trong bộ nhớ. Tiến trình này không đọc cấu hình `.env`, không khởi tạo hoặc kết nối SQL Server và không cập nhật dữ liệu thật. Server chỉ lắng nghe trên máy cục bộ. Đổi cổng bằng `EXPORT_REVIEW_PORT` nếu cần.
1. Chọn **Xuất tài sản TEST**.
2. Chọn **Nguyễn Văn Test**, dự án **Dự án Robot TEST A**, số lượng **2**.
3. Chọn **Thêm dự án**, dự án **Dự án Robot TEST B**, số lượng **3**.
4. Điền ghi chú rồi bấm **Xuất và tải Excel**.
5. Kiểm tra kho test giảm từ **17** xuống **12**, hai dòng Excel lần lượt có số lượng **2** và **3**.
6. Bấm **Tải lại phiếu Excel**: tồn kho và lịch sử test không thay đổi.
7. Thử **Xuất vật tư TEST**, chọn dự án và xuất **5** bu lông: tồn kho giảm từ **100** xuống **95**, Excel có thực xuất **5**.
8. Bấm **Đặt lại dữ liệu TEST** để quay về dữ liệu ban đầu. Dừng bằng `Ctrl+C`.
Để thử xuất chung, bấm **Xuất 2 tài sản TEST**, chọn người mượn và số lượng cho máy khoan/đồng hồ đo. Mở **Lịch sử xuất TEST**, chọn **Xem phiếu** hoặc **Tải Excel**. Bản review lưu file trong bộ nhớ giả lập; bản chạy thật lưu file trong SQL Server.
Ngày trên phiếu test cố định là **13/10/2026**. Mã, tên người, dự án, model và serial đều là dữ liệu giả.
## Các trường được điền
| Trường trên phiếu | Giá trị |
| --- | --- |
| Ngày đề nghị | Ngày xuất theo giờ Việt Nam |
| Người đề nghị | Người mượn/nhận đã chọn; nếu xuất vật tư trực tiếp cho dự án thì lấy người xuất |
| Bộ phận sử dụng | Bộ phận đã lưu của tài sản; để trống khi nguồn không có bộ phận |
| Nội dung | Người nhận, người xuất và ghi chú của lần xuất |
| Tên vật tư/linh kiện | Tên, mã, model và serial nếu có |
| ĐVT | Đơn vị đã lưu |
| Số lượng yêu cầu / Thực xuất | Số lượng của từng dòng dự án trong lần xuất này |
| Tồn kho | Số còn có thể xuất trước từng dòng: ví dụ xuất 2 rồi 3 từ kho 17 thì hiển thị 17 rồi 15 |
| Mục đích sử dụng/dự án | Dự án đã chọn; nếu mượn vật tư cho người dùng thì lấy tên người nhận |
| Định mức | Để trống vì hệ thống chưa lưu định mức |
Giữ nguyên nhãn và các chỗ trống ở phần chữ ký, họ tên, ngày ký. Không điền tên hay ngày sẵn ở phần này. Sheet phiếu nhập có trong file gốc được giữ nguyên.
## Cách xử lý
Mẫu chạy thật nằm tại `backend/templates/export-request.xlsx`, là bản sao của file mẫu trong `docs`. Docker đã sao chép toàn bộ thư mục `backend`, nên mẫu được đóng gói cùng ứng dụng.
Backend khóa tài sản theo thứ tự mã nội bộ, kiểm tra toàn bộ tồn kho, tạo Excel rồi lưu nguyên file vào `AssetExportDocuments`, cập nhật kho và ghi lịch sử trong cùng giao dịch. Nếu một tài sản không hợp lệ, thiếu tồn, hoặc tạo/lưu file hay ghi lịch sử thất bại, toàn bộ giao dịch được hủy. Khi xuất thành công, API trả thêm `document` gồm tên file, loại MIME, nội dung base64 và mã phiếu đã lưu. Có thể xuất đến 100 tài sản, tối đa 100 dòng tài sản/dự án trong một phiếu; bảng tự mở rộng trước phần ký tên. Tồn kho trên từng dòng Excel được tính riêng cho từng tài sản.
`POST /api/assets/export` nhận `{ borrowerName, note, items: [{ assetId, allocations: [{ projectName, quantity }] }] }`. API một tài sản `/api/assets/:id/export` vẫn hoạt động và cũng lưu file. API xem phiếu `/api/asset-export-documents/:id` trả nội dung đã ghi nhận; `/api/asset-export-documents/:id/download` trả file Excel đã lưu. Các API này dùng cùng quyền tài sản/admin như lịch sử xuất.
Các phần ZIP không liên quan được giữ nguyên để bảo toàn logo, chú thích, sheet phiếu nhập và thiết lập của mẫu. Nội dung tên/ghi chú được lưu dưới dạng chữ, kể cả khi bắt đầu bằng dấu `=`.
Kiểm tra tự động:
```powershell
npm test
npm run check
```
Bản review không triển khai hoặc khởi động lại hệ thống đang dùng dữ liệu thật. Sau khi review, cần triển khai mã mới theo quy trình hiện tại của dự án.

View File

@@ -1,15 +0,0 @@
# Xuất tài sản cho nhiều dự án
Chọn một tài sản → **Xuất tài sản** → chọn người mượn, dự án và số lượng. Dùng **Thêm dự án** để thêm các dòng trong cùng phiếu xuất. Tên dự án trùng nhau được cộng dồn; tất cả các dòng được lưu trong một giao dịch cùng cập nhật kho và lịch sử xuất.
- Tổng tài sản = tồn đầu kỳ (`Quantity`) + nhập trong kỳ (`ImportInPeriod`).
- Tổng xuất mới không vượt số lượng còn có thể xuất: giá trị nhỏ hơn giữa tồn kho đã lưu và tổng tài sản trừ lượng đang xuất.
- Bảng tài sản, tìm kiếm, chi tiết, giao diện điện thoại và file Excel hiển thị lượng đang xuất theo từng dự án.
- `AssetInventory.Project` vẫn là thông tin dự án mặc định. Phân bổ hiện tại nằm trong `ProjectAllocations`; trường này do máy chủ quản lý.
- Dữ liệu xuất cũ chưa có phân bổ được ghi là **Chưa xác định dự án**. Không dùng dự án cuối cùng hoặc lịch sử xuất cộng dồn để suy đoán lượng hiện tại.
- Luồng trả hiện tại không chọn dự án. Khi duyệt trả, hệ thống giảm phần chưa gắn dự án của người mượn trước, sau đó giảm các lần xuất cho dự án theo thứ tự xuất trước trả trước. Người mượn khác không bị ảnh hưởng.
- Biểu mẫu sửa giữ số lượng đang xuất mới nhất và không cho giảm tổng dưới lượng đó. Import Excel không ghi đè tài sản đang có phân bổ dự án; dùng biểu mẫu sửa cho các tài sản này.
Khởi động lại backend để tự thêm cột `ProjectAllocations` nếu chưa tồn tại. Không cần chỉnh `.env`. Migration giữ nguyên dữ liệu cũ, kể cả tài sản đã lưu trữ.
Kiểm tra: `npm test`, `node --check backend/server.js`, `node --check public/js/app.js`. Các kiểm thử tuyến API dùng SQL pool giả lập, không ghi vào cơ sở dữ liệu thật.

View File

@@ -1,71 +0,0 @@
# Dùng AccManager qua mạng nội bộ khi tên miền hết hạn
Máy chủ hiện tại vẫn chạy tại `172.20.235.176`. Có thể truy cập tạm bằng cách ánh xạ tên `accrobot.pnkr.asia` tới IP này trong file `hosts` của từng máy Windows. Trình duyệt vẫn mở `https://accrobot.pnkr.asia`, nhưng kết nối trực tiếp tới máy chủ trong LAN, không cần DNS công cộng của tên miền.
Ứng dụng, dữ liệu SQL Server, tài khoản và cấu hình Docker hiện tại được giữ nguyên. Máy sử dụng cần kết nối mạng nội bộ hoặc VPN có đường tới `172.20.235.176`.
## Thiết lập trên máy Windows
1. Mở Start, tìm **Notepad**, bấm chuột phải và chọn **Run as administrator**.
2. Trong Notepad chọn **File → Open**, đổi bộ lọc thành **All files**, rồi mở:
```text
C:\Windows\System32\drivers\etc\hosts
```
3. Thêm dòng sau vào cuối file rồi lưu. Nếu đã có dòng đang hoạt động cho đúng tên `accrobot.pnkr.asia`, sửa IP của dòng đó thay vì thêm trùng. Ghi lại IP cũ để hoàn tác; giữ nguyên các dòng của tên khác.
```text
172.20.235.176 accrobot.pnkr.asia # AccManager temporary LAN
```
File phải được lưu đúng tên `hosts`, không thêm đuôi `.txt`.
4. Mở PowerShell hoặc Command Prompt với quyền Administrator và chạy:
```powershell
ipconfig /flushdns
```
5. Đóng rồi mở lại trình duyệt, truy cập **https://accrobot.pnkr.asia** và đăng nhập như bình thường.
Thực hiện trên từng máy cần dùng. Nếu cần áp dụng cho nhiều máy, quản trị mạng có thể tạo bản ghi DNS nội bộ tương đương, với điều kiện các máy sử dụng DNS nội bộ đó.
## Kiểm tra
Sau khi sửa `hosts`, chạy trong PowerShell:
```powershell
curl.exe --noproxy "*" --fail --show-error --connect-timeout 5 --max-time 15 https://accrobot.pnkr.asia/api/health
```
Kết quả mong đợi có `"status":"ok"`. Mở trang đăng nhập và đăng nhập bằng tài khoản hiện có để kiểm tra phiên làm việc.
Nếu chưa truy cập được, kiểm tra máy đang ở đúng LAN/VPN, dòng `hosts` không bị chú thích bằng `#` ở đầu, file không có đuôi `.txt`, rồi xóa cache DNS và mở lại trình duyệt. Nếu máy sử dụng proxy web, cần cho địa chỉ này đi trực tiếp qua LAN.
### Kết quả kiểm tra ngày 10/09/2026
- `https://accrobot.pnkr.asia/api/health` qua IP `172.20.235.176` trả HTTP 200, `status: ok`.
- Trang `/pages/login.html` qua cùng đường kết nối trả HTTP 200.
- Xác minh TLS thành công; chứng chỉ cho `accrobot.pnkr.asia` hết hạn **29/10/2026 lúc 09:56:58 (giờ Việt Nam)**.
- Chưa kiểm tra đăng nhập bằng tài khoản người dùng. Phiên hỗ trợ không có quyền ghi file `hosts`, nên ánh xạ chưa được áp dụng tự động.
Có thể kiểm tra đường kết nối trước khi sửa `hosts` bằng lệnh sau; lệnh chỉ áp dụng ánh xạ cho riêng lần gọi này:
```powershell
curl.exe --noproxy "*" --fail --show-error --connect-timeout 5 --max-time 15 --resolve accrobot.pnkr.asia:443:172.20.235.176 https://accrobot.pnkr.asia/api/health
```
## Vì sao vẫn mở tên web thay vì gõ IP vào trình duyệt?
Ánh xạ `hosts` sử dụng IP nội bộ để kết nối, đồng thời giữ tên HTTPS mà reverse proxy, chứng chỉ và cookie đăng nhập đang dùng. Truy cập bằng `https://172.20.235.176` không khớp tên chứng chỉ. Truy cập `http://172.20.235.176:3000` gặp cấu hình bắt buộc HTTPS và cookie Secure của ứng dụng hiện tại.
Không cần sửa `.env`, chuyển `NODE_ENV` sang development, build image, khởi động lại container hay chuyển cơ sở dữ liệu cho phương án này.
## Hoàn tác sau khi gia hạn tên miền
1. Khi tên miền đã gia hạn và DNS công cộng hoạt động lại, mở file `hosts` với quyền Administrator.
2. Xóa riêng dòng có chú thích `# AccManager temporary LAN`; nếu đã sửa dòng có sẵn, khôi phục nội dung cũ.
3. Chạy `ipconfig /flushdns`, đóng rồi mở lại trình duyệt và truy cập địa chỉ web như trước.
Ánh xạ chỉ giải quyết việc phân giải tên miền. Chứng chỉ HTTPS vẫn cần còn hạn; hoàn tất gia hạn hoặc bố trí chứng chỉ phù hợp trước mốc hết hạn nêu trên.

View File

@@ -1,86 +0,0 @@
# AccManager
AccManager là hệ thống giúp quản lý tập trung tài khoản truy cập cho nhân sự trong tổ chức.
Thay vì lưu rải rác tài khoản ứng dụng ở nhiều nơi, AccManager gom tất cả về một màn hình để dễ tìm, dễ phân quyền và dễ kiểm soát.
## Dự án này dùng để làm gì
- Quản lý danh sách người dùng trong nội bộ.
- 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 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
- Quản trị viên: tạo người dùng, tạo ứng dụng, cấp tài khoản, cập nhật thông tin.
- Người dùng thông thường: xem các tài khoản được cấp cho mình.
## Cách sử dụng nhanh
1. Đăng nhập vào hệ thống.
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 để 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 ý
1. Khi có nhân sự mới:
- Tạo người dùng.
- Gán quyền phù hợp.
- Cấp các tài khoản ứng dụng cần thiết.
2. Khi thay đổi công việc:
- Cập nhật lại danh sách ứng dụng được cấp.
- Thu hồi các tài khoản không còn sử dụng.
3. Khi nhân sự nghỉ việc:
- Khóa hoặc ngừng kích hoạt người dùng.
- Rà soát và thu hồi toàn bộ tài khoản liên quan.
## Lợi ích chính
- Giảm thất lạc thông tin tài khoản.
- Rõ ràng trách nhiệm ai đang dùng tài khoản nào.
- Tiết kiệm thời gian bàn giao và thu hồi quyền truy cập.
- Dễ kiểm tra trước khi cấp quyền mới.
## Tài liệu liên quan
- Hướng dẫn triển khai: [DEPLOYMENT_GUIDE.md](DEPLOYMENT_GUIDE.md)
- Phiếu đề nghị xuất Excel và review với dữ liệu test: [ASSET_EXPORT_EXCEL.md](ASSET_EXPORT_EXCEL.md)
- Dùng tạm trong mạng nội bộ khi tên miền hết hạn: [LOCAL_ACCESS.md](LOCAL_ACCESS.md)
## Cau hinh email xac thuc dang ky
He thong da ho tro xac thuc email cho:
- Dang ky tai khoan moi.
- Doi email trong phan ho so ca nhan.
Phiên bản tài liệu: 4.0.0
Cập nhật: Tháng 4 năm 2026

View File

@@ -1,668 +0,0 @@
# Lộ trình 2 tháng: kho theo model tài sản, BOM robot và cấp vật tư sản xuất
Ngày lập: 08/10/2026. Cập nhật: 09/10/2026 theo yêu cầu chuyển quản lý tài sản từ serial sang model. Đây là kế hoạch đề xuất, cần xác nhận nguồn lực và dữ liệu trước khi cam kết KPI.
## 1. Mục tiêu, giả định và phạm vi
Sau 2 tháng, hệ thống phải thực hiện được chuỗi nghiệp vụ:
**Chuẩn hóa model tài sản → nhập kho theo model và số lượng → lập BOM robot theo model → phát hành phiên bản BOM → tạo lệnh sản xuất → tính nhu cầu/thiếu → giữ số lượng → cấp model và số lượng cho từng robot → xuất Excel → xác nhận số lượng đã lắp → xem BOM thực tế theo model.**
Giả định kế hoạch:
- Hai tháng quy đổi thành 8 tuần, 5 ngày/tuần, khoảng 40 ngày; khi chốt ngày bắt đầu phải gán lịch và trừ ngày nghỉ.
- Một lập trình viên toàn thời gian, Kho/Kỹ thuật/Sản xuất hỗ trợ dữ liệu và xác nhận trong 1–2 ngày làm việc.
- Quỹ Dev khoảng 320 giờ: 240 giờ công việc dự kiến và 80 giờ dự phòng/họp/sửa lỗi/phản hồi; trung bình 6 giờ kế hoạch + 2 giờ dự phòng mỗi ngày. Thời gian phối hợp của bộ phận khác chưa tính vào quỹ này.
- Cuối tuần 1 ước lượng lại theo số model, số dòng dữ liệu cũ, độ sạch dữ liệu, quy trình và nhân lực.
- BOM một cấp, có nhóm/cụm/vị trí lắp; mỗi dòng liên kết model tài sản và định mức. Một lệnh dùng một phiên bản BOM cố định.
- Quản lý lượng theo model, kho/vị trí và tình trạng. Không xây bảng từng chiếc hoặc bước chọn serial cho tài sản trong phạm vi này.
- Serial tài sản cũ, nếu có, được bảo toàn trong dữ liệu nguồn/thông tin tham khảo; không bắt buộc nhập và không dùng làm khóa tồn hoặc điều kiện cấp sản xuất.
- Loại robot có danh mục riêng. Robot cụ thể dùng mã robot nội bộ duy nhất; không nhầm model robot với model tài sản.
- Lệnh nhiều robot phải phân được lượng model cho từng robot. Với MVP, vật tư BOM được gán cho từng robot; vật tư dùng chung cả lệnh cần chốt riêng nếu phát sinh.
- Đơn vị chiếc dùng số nguyên; mét/kg dùng số thập phân với độ chính xác và cách làm tròn đã thống nhất.
- Tải file không thay đổi tồn. Phiếu xác nhận ghi sổ một lần; file chính thức lấy dữ liệu snapshot của phiếu.
- Bộ thử đề xuất: 20 model tài sản, 100 dòng dữ liệu kho nguồn, 2 kho/vị trí, 2 loại robot, 3 phiên bản BOM, 3 lệnh và 5 robot. Đây là dữ liệu thử/UAT; số lượng vật tư từng model được chốt trong bảng kỳ vọng.
Trong phạm vi: danh mục model, kho theo model/số lượng, nhập/xuất/trả/điều chỉnh, BOM/version, lệnh và robot cụ thể, nhu cầu, giữ chỗ theo lượng, cấp một phần, xác nhận lắp/tháo theo lượng, truy vết chứng từ, Excel, phân quyền, migration, kiểm thử, triển khai.
Giai đoạn sau: quản lý từng chiếc bằng serial, truy vết lô nếu cần, BOM nhiều cấp tự bung, thay model tự động, mua hàng, giá thành/kế toán, điều độ sản xuất, ERP, quét QR và in tem. Đưa thêm vào phải ước lượng lại.
## 2. Cơ sở từ dự án hiện tại
| Đã quan sát | Có thể tận dụng | Phần cần bổ sung |
| ---------------------------------------------------------------- | ------------------------------------ | ------------------------------------------------------------------------------- |
| Node.js/Express, SQL Server, frontend JavaScript/Tailwind | Nền tảng đang dùng | Module model/BOM/sản xuất vừa đủ |
| AssetInventory có Model, SerialNumber và các cột số lượng | Kho và dữ liệu cũ | Danh mục model chuẩn, ModelId và tồn theo model/kho/tình trạng |
| ConsumableInventory có Model và số lượng | Vật tư tiêu hao | Liên kết danh mục model, giữ đơn vị và nguồn dữ liệu rõ ràng |
| Xuất dự án, ProjectAllocations, lịch sử | Phân bổ và transaction | Liên kết có khóa tới model/lệnh/robot, phân bổ theo lượng |
| Mượn/trả, lưu trữ | Quy trình cần giữ | Trả đúng phiếu và model, phân biệt mượn với xuất sản xuất |
| Import và exportAssetsToExcel() | Thư viện và định dạng cơ bản | Import model/tồn, BOM, nhu cầu, phiếu và BOM thực tế |
| Schema tại setup.sql và backend/server.js | Tạo/mở rộng database | Đồng bộ database mới/cũ; migration có phiên bản |
| Test phân bổ, lưu trữ, bảo mật | Hồi quy | Test gom model, số lượng, đơn vị, BOM, đồng thời và chuyển dữ liệu |
Chưa kết nối database thật; quy mô dữ liệu và cách dùng Model thực tế cần khảo sát tuần 1. Chưa tìm thấy module BOM/lệnh sản xuất trong mã nguồn đã kiểm tra trước đó. Không cần đọc nội dung .env để cập nhật kế hoạch.
## 3. Quy tắc nghiệp vụ phải chốt
### 3.1. Định danh model tài sản
- Mỗi model có ModelId nội bộ bất biến và mã danh mục nội bộ duy nhất.
- Trường tối thiểu: mã nội bộ, tên tài sản, model nhà sản xuất, hãng, thông số/biến thể nếu ảnh hưởng tương thích, đơn vị cơ sở, nhóm và trạng thái.
- Không giả định chuỗi model duy nhất toàn hệ thống: hai hãng có thể cùng tên model; khác cấu hình có thể không thay thế được. Chốt tổ hợp hãng + model + biến thể cần thiết.
- Chuẩn hóa khoảng trắng/chữ hoa và alias, lưu giá trị gốc. Không tự xóa dấu gạch hoặc ký tự có ý nghĩa trong model.
- Mã linh kiện/PN có thể là thuộc tính hoặc mã tham chiếu; khóa liên kết BOM/kho là ModelId đã chuẩn hóa.
- Một model có thể có nhiều dòng tồn ở nhiều kho/tình trạng. Không gộp khác đơn vị hoặc khác biến thể.
- Chặn xóa model đã có BOM/giao dịch; ngừng sử dụng và giữ lịch sử. Đổi đơn vị hoặc gộp model đã có giao dịch phải có quy trình, không sửa tùy ý.
- Model thiếu/chưa xác minh không được đưa vào BOM phát hành hoặc giao dịch sản xuất mới.
### 3.2. BOM thiết kế, cấp sản xuất và BOM thực tế
1. BOM thiết kế của robot R: động cơ model M-A cần 2 chiếc, bộ điều khiển model C-A cần 1 chiếc.
2. Phiếu cấp cho robot R-001: xuất M-A 2 chiếc, C-A 1 chiếc từ kho K1.
3. BOM thực tế của R-001: xác nhận đã lắp M-A 2 chiếc, C-A 1 chiếc; lượng đã cấp nhưng chưa lắp được hiển thị riêng.
Quản lý theo model cho biết robot dùng model gì, bao nhiêu và theo phiếu nào. Không thể phân biệt hai chiếc cùng model hoặc truy vết vòng đời từng chiếc nếu không có serial/lô. Không đưa khả năng đó vào KPI.
Một model có thể xuất hiện ở nhiều vị trí/cụm BOM; chốt khóa dòng theo vị trí/cụm. Khi tính nhu cầu tổng model phải cộng định mức các dòng tương ứng, vẫn giữ từng vị trí khi cấp/lắp.
### 3.3. Tồn, giữ chỗ và số lượng
- Sổ giao dịch là nguồn biến động; bảng tồn tổng hợp được cập nhật cùng transaction và có đối soát. Chọn rõ một nguồn có thẩm quyền, không cho luồng cũ/mới sửa tổng độc lập.
- Theo từng model/kho/tình trạng: tồn cuối = tồn đầu + nhập + trả đã xác nhận − xuất đã xác nhận ± điều chỉnh được duyệt. Chuyển kho có xuất kho nguồn và nhập kho đích, tổng toàn hệ thống không tăng.
- Tồn đủ điều kiện cấp = lượng tốt đang ở kho, gồm phần đã giữ chỗ. Khả dụng chung = tồn đủ điều kiện − giữ chỗ còn hiệu lực.
- Đang mượn, tại xưởng, đã lắp, chờ kiểm tra, hỏng/thanh lý không cộng vào tồn khả dụng ở kho.
- Model có thể được giữ cho nhiều lệnh nếu tổng lượng giữ không vượt tồn đủ điều kiện.
- Lượng có thể cấp cho lệnh = lượng giữ riêng cho lệnh + lượng chưa giữ cho lệnh khác, trong phạm vi kho cấp được phép.
- Nhu cầu model = tổng định mức các dòng cùng model trong revision BOM × số robot.
- Còn cần cấp = max(nhu cầu − đã cấp ròng, 0); đã cấp ròng = xuất sản xuất − trả được xác nhận. Hàng hỏng tại xưởng cần xử lý thay thế riêng.
- Thiếu cho lần cấp hiện tại = max(còn cần cấp − lượng có thể cấp cho lệnh, 0).
- Giữ chỗ không giảm tồn vật lý. Xác nhận xuất giảm tồn và giải phóng lượng giữ tương ứng.
- Không cho số lượng âm, vượt khả dụng, sai đơn vị hoặc số lẻ với đơn vị chiếc. Dùng kiểu decimal/biểu diễn chính xác cho lượng thập phân; không tự quy đổi nếu chưa có hệ số được xác nhận.
### 3.4. Chứng từ, lắp và trả
- Phiếu nhiều dòng gắn ModelId, kho, lượng, lệnh, robot và dòng BOM; tổng phân bổ robot bằng lượng phiếu tương ứng.
- Phiếu nháp không ghi sổ; ghi sổ chống lặp bằng định danh request/chứng từ. Lỗi một dòng rollback toàn phiếu trong MVP.
- Chặn cấp sai model so với BOM. Cấp model thay thế là thay đổi có duyệt, không tự gộp hai model tương tự.
- Phiên bản BOM phát hành bất biến; lệnh/phiếu lưu tham chiếu bất biến hoặc snapshot.
- Trả một phần gắn phiếu gốc, đúng model/robot; không vượt lượng còn được trả.
- Xác nhận lắp không vượt lượng đã cấp còn tại xưởng. Tháo không vượt lượng đang lắp; lượng đã lắp phải tháo hợp lệ trước khi trả kho.
- Hàng trả chờ kiểm tra/hỏng vào nhóm bị loại khỏi khả dụng.
- Lịch sử lắp/tháo ghi model và lượng, không khẳng định danh tính chiếc đã tháo.
- Chứng từ ghi sổ không xóa/sửa trực tiếp; dùng trả/đảo có lý do và quyền. File tải lại lấy snapshot model/tên/đơn vị/BOM tại thời điểm phiếu.
### 3.5. Chuyển dữ liệu cũ và import
- Lập bảng ánh xạ từng dòng nguồn sang ModelId, kho, tình trạng, đơn vị; Kho/Kỹ thuật xác nhận trước khi gom.
- Gom dòng chỉ khi cùng model đã xác minh, đơn vị, kho và tình trạng; cộng riêng tồn, đang mượn/đã cấp và các bucket cần bảo toàn.
- Không cộng lịch sử xuất lũy kế thành lượng đang cấp hiện tại; không cộng kho và số ngoài kho thành tồn khả dụng.
- Model trống, tên giống nhưng khác hãng/thông số, đơn vị không khớp hoặc lượng mâu thuẫn phải vào báo cáo ngoại lệ.
- Tài sản/vật tư cùng model ở hai nguồn chỉ gộp sau xác nhận; tránh đếm hai lần. Bản lưu trữ giữ quan hệ nguồn và không cộng lại vào tồn hoạt động.
- Giữ AssetId/ConsumableId nguồn và lịch sử; gom báo cáo không xóa quan hệ phiếu cũ. Dữ liệu cũ không rõ robot/lệnh được đánh dấu chưa xác định, không đoán.
- Serial cũ được bảo toàn ở nguồn; thiếu serial không phải lỗi chặn khi model/đơn vị/lượng hợp lệ.
- Import danh mục: cập nhật model theo mã/tổ hợp chuẩn, không tạo trùng danh mục.
- Import phiếu nhập: cùng model có thể nhập nhiều lần hợp lệ. Chống ghi lại cùng phiếu/file đã xác nhận bằng định danh import/chứng từ; không chặn mọi dòng trùng model.
- Import tồn đầu/chuyển dữ liệu là luồng riêng; không cho ghi đè tồn nhóm đang vận hành như cập nhật danh mục.
## 4. Mô hình dữ liệu đề xuất
Tên bảng gợi ý; cân nhắc mở rộng bảng hiện có sau khảo sát, không mặc định tạo lại toàn bộ kho.
| Nhóm | Dữ liệu tối thiểu |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| AssetModels | ModelId, mã nội bộ, model gốc/chuẩn, hãng, biến thể, tên, đơn vị, nhóm, trạng thái |
| ModelAliases, LegacyModelMappings | Alias, bảng/ID nguồn, ModelId, người xác nhận; giữ lịch sử nguồn |
| InventoryBalances | ModelId, kho/vị trí, tình trạng, số lượng, lượng giữ hoặc thông tin tổng hợp |
| InventoryTransactions và dòng | Loại nhập/xuất/trả/chuyển/điều chỉnh, số phiếu, model, lượng, nguồn/đích, người/ngày/lý do |
| RobotModels, Robots | Loại robot riêng, mã robot cụ thể, lệnh, trạng thái |
| BOMHeaders, BOMRevisions, BOMLines | Loại robot, revision, ModelId, định mức, đơn vị, vị trí/cụm, trạng thái |
| ProductionOrders, dòng nhu cầu | Mã lệnh, dự án, revision/snapshot, số robot, lượng cần/đã cấp ròng |
| Reservations | Lệnh, ModelId, kho, lượng, trạng thái; giải phóng đúng phần |
| MaterialIssues và dòng phân bổ | Phiếu, model, lượng, kho, lệnh, robot, dòng BOM, snapshot |
| RobotComponents và lịch sử | Robot, model, vị trí/cụm, lượng đang lắp, lắp/tháo, phiếu nguồn, người/ngày |
| AuditLog | Thực thể, hành động, trước/sau, người/thời gian/lý do |
Ưu tiên index/ràng buộc: mã model, tổ hợp định danh đã chốt, model/kho/tình trạng, số phiếu, revision, lệnh/robot. Khóa hàng tồn theo thứ tự ổn định trong transaction; kiểm tra khả dụng sau khóa. Không cascade xóa lịch sử. Không cần bảng AssetInstances hoặc danh sách serial tài sản để thực hiện phạm vi này.
## 5. Các mốc kiểm soát
| Mốc | Đầu ra | Xác nhận |
| ------- | --------------------------------------------------------------------------- | ----------------------------------- |
| Tuần 1 | Quy tắc model/gom dữ liệu, luồng, mẫu file, ERD, ước lượng lại | Dev + Kho + Kỹ thuật + Sản xuất |
| Tuần 2 | Danh mục model, schema/API tồn và giao dịch số lượng | Dev + Kho |
| Tuần 3 | Giao diện kho/import, dữ liệu mẫu gom đúng, hồi quy | Dev + Kho |
| Tuần 4 | BOM theo model/version, liên kết kho, nghiệm thu tháng 1 | Kho + Kỹ thuật |
| Tuần 5 | Lệnh, nhu cầu/thiếu, giữ lượng và phân bổ robot | Kho + Sản xuất |
| Tuần 6 | Cấp/trả một phần theo model, Excel và chống trừ lặp | Kho + Sản xuất |
| Tuần 7 | BOM thực tế model/lượng, truy vết phiếu, test tích hợp/đồng thời | Kỹ thuật + người nghiệm thu |
| Tuần 8 | UAT, chuyển dữ liệu, triển khai/đào tạo, nghiệm thu tháng 2 | Chủ dự án + các bộ phận |
## 6. Checklist 40 ngày, 240 đầu việc nhỏ
Mỗi ngày 6 mục, tổng khoảng 6 giờ kế hoạch/ngày, không phải 6 giờ/mục. Dev phụ trách chính; mục có Kho/Kỹ thuật/Sản xuất cần giao người phối hợp cụ thể. Các mã D01.1–D40.6 được giữ để theo dõi, nhưng nội dung đã thay theo yêu cầu model.
### Tuần 1 — Chốt model, nghiệp vụ và thiết kế
**D01 — Khảo sát hiện trạng.**
- [ ] D01.1 Liệt kê màn hình/API kho, mượn/trả, dự án và import/export.
- [ ] D01.2 Lập sơ đồ bảng tổng, lịch sử, model và nguồn tài sản/vật tư.
- [ ] D01.3 Kho thống kê số dòng, model trống/trùng/alias, đơn vị và chênh lệch lượng.
- [ ] D01.4 Kỹ thuật cung cấp BOM thật, model/hãng/thông số và vị trí lắp.
- [ ] D01.5 Sản xuất mô tả xuất thiếu, trả dư, cấp bù và lắp thực tế.
- [ ] D01.6 Ghi khoảng cách với bốn yêu cầu; giao người trả lời từng vấn đề.
**D02 — Quy tắc model và ngoại lệ.**
- [ ] D02.1 Chốt ModelId, mã nội bộ, tổ hợp hãng/model/biến thể và alias.
- [ ] D02.2 Chốt đơn vị cơ sở, số nguyên/thập phân và quy đổi được phép.
- [ ] D02.3 Chốt tồn theo kho/vị trí/tình trạng và lượng ngoài kho.
- [ ] D02.4 Chốt BOM, giữ lượng, xuất, lắp/tháo và trả theo lượng.
- [ ] D02.5 Chốt quyền lập/phát hành BOM, xác nhận xuất/trả/lắp.
- [ ] D02.6 Chốt ngoại lệ thiếu model, khác đơn vị, thiếu hàng, đổi BOM và hủy lệnh.
**D03 — Yêu cầu, giao diện và file.**
- [ ] D03.1 Viết user story và tiêu chí nghiệm thu bốn yêu cầu.
- [ ] D03.2 Phác danh mục model, bảng tồn và lịch sử số lượng.
- [ ] D03.3 Phác BOM theo model, revision và tồn khả dụng.
- [ ] D03.4 Phác lệnh, bảng thiếu và phân lượng cho từng robot.
- [ ] D03.5 Kho/Sản xuất xác nhận cột model/hãng/đơn vị/lượng trên bốn loại file.
- [ ] D03.6 Chốt MVP, giai đoạn sau và người nghiệm thu.
**D04 — Thiết kế kỹ thuật và chuyển dữ liệu.**
- [ ] D04.1 Lập ERD, ModelId và ánh xạ bảng nguồn hiện có.
- [ ] D04.2 Thiết kế API/payload/mã lỗi/quyền cho kho, BOM, lệnh và file.
- [ ] D04.3 Chốt khóa dòng tồn theo thứ tự và cơ chế chống ghi sổ lặp.
- [ ] D04.4 Chốt nguồn tồn có thẩm quyền và các cột tổng cũ cần đồng bộ.
- [ ] D04.5 Thiết kế gom dữ liệu model, đối soát và xử lý ngoại lệ.
- [ ] D04.6 Chốt audit/snapshot và quan hệ cấp/lắp model theo robot.
**D05 — Môi trường và ước lượng.**
- [ ] D05.1 Chuẩn bị nhánh và môi trường thử biệt lập, ghi cách khởi động.
- [ ] D05.2 Chuẩn bị bản sao/dataset được phép dùng để thử ghi.
- [ ] D05.3 Chạy test hiện có, lưu baseline và lỗi sẵn có.
- [ ] D05.4 Tạo mẫu 20 model/100 dòng nguồn/2 kho và bảng kỳ vọng tính tay.
- [ ] D05.5 Chia backlog, ước lượng lại và giao đầu vào phối hợp.
- [ ] D05.6 Chốt tuần 1: đặc tả, ERD, mẫu file, quy tắc gom và rủi ro.
### Tuần 2 — Danh mục model và API tồn số lượng
**D06 — Schema và migration.**
- [ ] D06.1 Tạo migration có phiên bản, chạy lại không nhân bản.
- [ ] D06.2 Tạo/mở rộng danh mục model, ánh xạ nguồn và tồn theo kho/tình trạng.
- [ ] D06.3 Tạo sổ giao dịch số lượng và audit tối thiểu.
- [ ] D06.4 Tạo ràng buộc mã model, bucket tồn, đơn vị/lượng và số phiếu.
- [ ] D06.5 Đồng bộ setup.sql và cơ chế khởi tạo/migration backend.
- [ ] D06.6 Thử database rỗng/cũ và chạy lại migration; lưu kết quả.
**D07 — API danh mục model.**
- [ ] D07.1 Làm danh sách/chi tiết/thêm/sửa model và mã nội bộ.
- [ ] D07.2 Kiểm tra model/hãng/biến thể, đơn vị, độ dài và trường bắt buộc.
- [ ] D07.3 Làm alias và ánh xạ dòng tài sản/vật tư nguồn.
- [ ] D07.4 Chặn xóa/đổi đơn vị hoặc gộp tùy ý khi đã có giao dịch.
- [ ] D07.5 Làm tìm kiếm/phân trang/lọc nhóm/hãng và ngừng sử dụng.
- [ ] D07.6 Test quyền, model trùng thật và tên giống nhưng khác cấu hình.
**D08 — API tồn theo model.**
- [ ] D08.1 Làm danh sách tồn theo model/kho/tình trạng và tổng theo model.
- [ ] D08.2 Hiển thị tồn vật lý, đủ điều kiện, giữ chỗ và khả dụng riêng.
- [ ] D08.3 Làm tìm model/mã/alias và lọc kho/tình trạng.
- [ ] D08.4 Làm chi tiết model với từng bucket và nguồn dữ liệu.
- [ ] D08.5 Chặn nhập lượng âm/sai đơn vị/số lẻ cho đơn vị chiếc.
- [ ] D08.6 Test nhiều kho, khác tình trạng, đơn vị thập phân và số 0 đầu trong model.
**D09 — Giao dịch kho nền.**
- [ ] D09.1 Làm nhập kho model/lượng/đơn vị/phiếu/người thao tác.
- [ ] D09.2 Làm xuất/trả và chuyển giữa kho/bucket theo model và lượng.
- [ ] D09.3 Cập nhật tồn, sổ giao dịch và tổng cũ cùng transaction.
- [ ] D09.4 Chặn xuất vượt lượng tốt khả dụng và dùng sai kho/tình trạng.
- [ ] D09.5 Làm điều chỉnh kiểm kê có lý do/quyền, chặn sửa tổng trực tiếp.
- [ ] D09.6 Test lỗi ghi lịch sử rollback và hai yêu cầu tranh lượng cuối cùng.
**D10 — Gom model thử và đối soát.**
- [ ] D10.1 Làm lịch sử model theo chứng từ/kho/người và nguồn cũ.
- [ ] D10.2 Thử gom các dòng cùng model đã xác nhận; giữ các bucket và mapping.
- [ ] D10.3 Xuất ngoại lệ model trống/alias chưa rõ/khác đơn vị/lượng mâu thuẫn.
- [ ] D10.4 Đối soát tồn, mượn, xuất và lưu trữ trước/sau theo model.
- [ ] D10.5 Kho xác nhận nhóm được gom và nhóm phải giữ riêng.
- [ ] D10.6 Demo API kho/model và cập nhật migration/backlog/test.
### Tuần 3 — Giao diện kho, import và hồi quy
**D11 — Danh sách kho model.**
- [ ] D11.1 Thêm menu/tab danh mục model và kho tổng hợp.
- [ ] D11.2 Hiển thị model/hãng/biến thể/đơn vị và tồn theo kho/tình trạng.
- [ ] D11.3 Làm tìm/lọc/phân trang và tổng tồn/khả dụng đúng nghĩa.
- [ ] D11.4 Làm trạng thái tải/rỗng/lỗi/thử lại.
- [ ] D11.5 Hiển thị thao tác theo quyền, đồng thời kiểm tra backend.
- [ ] D11.6 Kiểm tra giao diện máy tính và điện thoại dùng trong kho.
**D12 — Form và lịch sử.**
- [ ] D12.1 Làm form thêm/sửa model, alias và thông số.
- [ ] D12.2 Làm form nhập/xuất/chuyển/điều chỉnh model và số lượng.
- [ ] D12.3 Làm chi tiết tồn và lịch sử theo phiếu.
- [ ] D12.4 Validation lượng/đơn vị và lý do thay đổi.
- [ ] D12.5 Chống submit hai lần, cảnh báo chưa lưu và dữ liệu đã đổi.
- [ ] D12.6 Kiểm tra nhãn/focus/modal/thông báo tiếng Việt.
**D13 — Import danh mục và lượng kho.**
- [ ] D13.1 Tạo mẫu riêng cho danh mục model và phiếu nhập/tồn đầu.
- [ ] D13.2 Kiểm tra cột, dung lượng file, dòng rỗng, đơn vị và số lượng.
- [ ] D13.3 Phân biệt trùng danh mục với nhiều dòng nhập cùng model hợp lệ.
- [ ] D13.4 Làm xem trước, thống kê và file lỗi theo dòng/cột.
- [ ] D13.5 Xác nhận ghi theo transaction/chunk đã quy định; không ghi một phần âm thầm.
- [ ] D13.6 Chống ghi lại cùng lần import/phiếu, vẫn cho nhập model đó ở phiếu khác.
**D14 — Tích hợp luồng cũ.**
- [ ] D14.1 Xuất/mượn cũ liên kết ModelId và lượng, giữ nguồn phiếu.
- [ ] D14.2 Trả một phần đúng phiếu/model/người mượn và lượng còn lại.
- [ ] D14.3 Tách xuất dự án/mượn khỏi xuất sản xuất để không trừ hai lần.
- [ ] D14.4 Lưu trữ danh mục không mất mapping/lịch sử và không cộng lại tồn.
- [ ] D14.5 Hỏng/thanh lý theo lượng chuyển đúng bucket và giảm khả dụng.
- [ ] D14.6 Chạy hồi quy phân bổ dự án/mượn trả/lưu trữ.
**D15 — Nghiệm thu kho.**
- [ ] D15.1 Kho thử nhập → tìm model → xuất/mượn → trả → lịch sử.
- [ ] D15.2 Đối soát 100 dòng nguồn/20 model trên 2 kho mẫu.
- [ ] D15.3 Test người thiếu quyền ở UI và request trực tiếp.
- [ ] D15.4 Đo tìm model/bảng tồn, ghi dữ liệu và cấu hình thử.
- [ ] D15.5 Sửa lỗi chặn và hoàn thiện hướng dẫn kho.
- [ ] D15.6 Lưu demo tuần 3 và tồn đọng có người/hạn xử lý.
### Tuần 4 — BOM theo model và version
**D16 — Loại robot và schema BOM.**
- [ ] D16.1 Tạo danh mục loại robot riêng với model tài sản.
- [ ] D16.2 Tạo BOM/header/revision/dòng liên kết ModelId.
- [ ] D16.3 Ràng buộc revision, lượng dương, đơn vị và vị trí/cụm.
- [ ] D16.4 Triển khai nháp/phát hành/ngừng dùng.
- [ ] D16.5 Chuẩn bị mã robot cụ thể và liên kết lệnh.
- [ ] D16.6 Test migration BOM trên database mới/cũ và tạo mẫu.
**D17 — API BOM/version.**
- [ ] D17.1 Làm danh sách/chi tiết/tạo/sửa BOM nháp.
- [ ] D17.2 Thêm/sửa/xóa dòng model, định mức, vị trí/cụm và ghi chú.
- [ ] D17.3 Chặn model chưa xác minh/ngừng dùng, sai đơn vị và trùng vị trí.
- [ ] D17.4 Làm sao chép/tạo revision mới/phát hành.
- [ ] D17.5 Khóa revision phát hành, giữ revision cũ khi thay đổi.
- [ ] D17.6 Audit và test quyền phát hành/ngừng dùng/xóa nháp.
**D18 — Giao diện BOM.**
- [ ] D18.1 Làm menu/danh sách/lọc loại robot/trạng thái/revision.
- [ ] D18.2 Làm chi tiết BOM/người/ngày phát hành.
- [ ] D18.3 Làm bảng sửa dòng, tìm model theo mã/hãng/thông số.
- [ ] D18.4 Hiển thị định mức/đơn vị/vị trí và cảnh báo sai.
- [ ] D18.5 Làm sao chép/revision/phát hành đúng quyền.
- [ ] D18.6 Test tải/rỗng/lỗi/chưa lưu và BOM nhiều dòng.
**D19 — Liên kết kho và Excel BOM.**
- [ ] D19.1 Hiển thị tồn đủ điều kiện/giữ/khả dụng theo model BOM.
- [ ] D19.2 Mở dòng BOM tới tồn và lịch sử model theo kho.
- [ ] D19.3 Làm import/export Excel BOM theo model/định mức/vị trí.
- [ ] D19.4 Kiểm tra model, đơn vị, lượng và lỗi dòng khi import nháp.
- [ ] D19.5 Tính nhu cầu dự kiến, cộng model ở nhiều vị trí mà không ghi kho.
- [ ] D19.6 Kỹ thuật đối chiếu 2 loại robot/3 revision với mẫu gốc.
**D20 — Nghiệm thu tháng 1.**
- [ ] D20.1 Chạy test kho/model/BOM và hồi quy, lưu kết quả.
- [ ] D20.2 Đối soát dữ liệu mẫu và định mức/tồn từng model.
- [ ] D20.3 Thử sửa revision phát hành, model sai/thiếu và quyền trái phép.
- [ ] D20.4 Kho/Kỹ thuật xác nhận đạt/chưa đạt theo tiêu chí.
- [ ] D20.5 Chấm KPI tháng 1 theo bằng chứng và trọng số.
- [ ] D20.6 Chốt backlog tháng 2, quỹ dự phòng và ngoại lệ dữ liệu.
### Tuần 5 — Lệnh, nhu cầu, giữ số lượng
**D21 — Lệnh và robot cụ thể.**
- [ ] D21.1 Tạo schema lệnh/nhu cầu/robot/phân bổ model.
- [ ] D21.2 Làm lệnh nháp với dự án/loại robot/số lượng/hạn/người nhận.
- [ ] D21.3 Chọn revision phát hành và cố định BOM lúc xác nhận.
- [ ] D21.4 Tạo mã robot cụ thể, chặn trùng; không yêu cầu serial tài sản.
- [ ] D21.5 Chặn đổi loại/số robot tùy ý sau giữ hoặc xuất.
- [ ] D21.6 Làm trạng thái lệnh và điều kiện chuyển/hủy.
**D22 — Tính nhu cầu model.**
- [ ] D22.1 Cộng định mức các vị trí cùng model và nhân số robot.
- [ ] D22.2 Tính cấp ròng/còn cần theo model, dòng BOM và robot.
- [ ] D22.3 Tính tồn/giữ lệnh này/giữ lệnh khác/khả dụng/thiếu.
- [ ] D22.4 Loại lượng mượn/xưởng/hỏng/chờ kiểm tra khỏi kho cấp.
- [ ] D22.5 Chốt độ chính xác đơn vị/làm tròn, không tự quy đổi.
- [ ] D22.6 Test nhiều robot/model lặp vị trí/cấp và trả một phần.
**D23 — Giữ lượng và đồng thời.**
- [ ] D23.1 Làm giữ lượng theo model/kho/lệnh trong transaction.
- [ ] D23.2 Chặn tổng giữ vượt lượng tốt, cho nhiều lệnh giữ nếu còn đủ.
- [ ] D23.3 Làm giải phóng phần/toàn bộ khi đổi kế hoạch/hủy.
- [ ] D23.4 Chốt hiệu lực và quyền giải phóng có lý do.
- [ ] D23.5 Audit và chống request giữ/giải phóng lặp.
- [ ] D23.6 Test hai lệnh tranh lượng cuối trên SQL Server thử.
**D24 — Giao diện nhu cầu.**
- [ ] D24.1 Làm danh sách/tạo/chi tiết lệnh và bộ lọc.
- [ ] D24.2 Hiển thị revision cố định và danh sách robot.
- [ ] D24.3 Hiển thị model/đơn vị/cần/cấp/còn cần/khả dụng/thiếu.
- [ ] D24.4 Làm giữ/giải phóng lượng và cảnh báo giữ cho lệnh khác.
- [ ] D24.5 Xuất file nhu cầu/thiếu, ghi thời điểm và phạm vi kho tính.
- [ ] D24.6 Kho/Sản xuất đối chiếu bảng tính tay.
**D25 — Phân bổ model/lượng để cấp.**
- [ ] D25.1 Chọn kho/model/số lượng theo dòng BOM và robot.
- [ ] D25.2 Dùng phần giữ riêng đúng lệnh, chặn lấy lượng giữ cho lệnh khác.
- [ ] D25.3 Kiểm tra tổng dòng/phân bổ robot không vượt lượng phiếu.
- [ ] D25.4 Chặn sai model/đơn vị, lượng âm/lẻ chiếc/vượt định mức chưa duyệt.
- [ ] D25.5 Server kiểm tra lại khả dụng khi xác nhận do tồn có thể đổi.
- [ ] D25.6 Demo 3 lệnh/5 robot với đủ/thiếu và cạnh tranh lượng.
### Tuần 6 — Cấp/trả model và file chính thức
**D26 — Phiếu xuất nhiều dòng.**
- [ ] D26.1 Tạo số phiếu/header/dòng model/lượng/kho/snapshot.
- [ ] D26.2 Làm tạo/sửa/xóa nháp và danh sách theo lệnh/robot.
- [ ] D26.3 Gắn model/dòng BOM/robot và lượng phân bổ.
- [ ] D26.4 Cho cấp một phần, hiển thị còn thiếu rõ.
- [ ] D26.5 Kiểm tra người nhận/ngày/kho/lý do và cấp vượt được duyệt.
- [ ] D26.6 Phân quyền lập/xác nhận và lịch sử chứng từ.
**D27 — Ghi sổ xuất.**
- [ ] D27.1 Khóa bucket tồn/giữ theo thứ tự, kiểm tra lại toàn bộ lượng.
- [ ] D27.2 Giảm tồn kho, giảm giữ và ghi lượng tại xưởng cùng transaction.
- [ ] D27.3 Ghi cấp ròng theo model/robot/dòng BOM.
- [ ] D27.4 Chống xác nhận hai lần và retry sau lỗi mạng.
- [ ] D27.5 Rollback cả phiếu khi dòng lỗi, trả thông báo cụ thể.
- [ ] D27.6 Test hai phiếu tranh lượng, lỗi lịch sử, lặp và nhiều robot.
**D28 — Trả và đảo chứng từ.**
- [ ] D28.1 Tạo trả theo phiếu gốc/model/robot và lượng.
- [ ] D28.2 Trả một phần, chặn vượt lượng còn trả và trả lặp.
- [ ] D28.3 Chặn trả lượng đã lắp nếu chưa tháo/xác nhận.
- [ ] D28.4 Hàng tốt/chờ kiểm tra/hỏng về đúng bucket.
- [ ] D28.5 Hủy nháp/đảo phiếu ghi sổ có quyền/lý do, giữ lịch sử.
- [ ] D28.6 Test sai model, quá lượng, hủy lệnh và cấp bù.
**D29 — Giao diện xuất/trả.**
- [ ] D29.1 Làm form nhiều dòng model/kho/lượng/robot.
- [ ] D29.2 Xem trước lượng theo robot và xác nhận ghi sổ.
- [ ] D29.3 Xử lý tranh tồn/lỗi mạng mà không ghi lại phiếu.
- [ ] D29.4 Hiển thị đã cấp/đã trả/còn cần theo model và phiếu.
- [ ] D29.5 Làm form trả/đảo có lượng/tình trạng/lý do.
- [ ] D29.6 Kho/Sản xuất thử cấp hai lần và trả một phần.
**D30 — Excel chính thức.**
- [ ] D30.1 Xuất phiếu từ snapshot model/hãng/đơn vị/lượng/BOM.
- [ ] D30.2 Tạo sheet tổng hợp và chi tiết model/lượng theo robot.
- [ ] D30.3 Định dạng model chuỗi, lượng, ngày, cột, xuống dòng và vùng in.
- [ ] D30.4 Phân biệt nháp/chính thức; tải lại không đổi tồn.
- [ ] D30.5 Kiểm tra quyền file và văn bản bị hiểu thành công thức.
- [ ] D30.6 Kho đối chiếu file/phiếu/tồn model và xác nhận tuần 6.
### Tuần 7 — BOM thực tế model/lượng và kiểm thử
**D31 — Xác nhận lắp/tháo.**
- [ ] D31.1 Làm xác nhận model/lượng/vị trí đã lắp cho robot.
- [ ] D31.2 Chặn lắp vượt lượng đã cấp còn tại xưởng hoặc sai model.
- [ ] D31.3 Ghi người/ngày/phiếu nguồn và biến động lượng.
- [ ] D31.4 Làm tháo/cấp thay theo model/lượng/lý do, giữ lịch sử.
- [ ] D31.5 Chặn hoàn thành khi thiếu cấu phần bắt buộc chưa xử lý.
- [ ] D31.6 Kỹ thuật xác nhận cấp/lắp/tháo/trả theo lượng.
**D32 — BOM thực tế và truy vết.**
- [ ] D32.1 Hiển thị thiết kế/đã cấp/đang lắp theo model và vị trí.
- [ ] D32.2 So định mức với lượng thực, hiển thị thiếu/thừa/chờ lắp.
- [ ] D32.3 Robot → model/lượng/phiếu/người và lịch sử lắp/tháo.
- [ ] D32.4 Model → các robot đã cấp/đang lắp và lượng tương ứng.
- [ ] D32.5 Xuất BOM thực tế có robot/revision/model/lượng/thời điểm.
- [ ] D32.6 Test tháo 1 chiếc/cấp bù 1 chiếc, lịch sử khớp; không tuyên bố định danh từng chiếc.
**D33 — Luồng đầy đủ.**
- [ ] D33.1 Test nhập → BOM → lệnh → giữ → cấp → lắp → hoàn thành.
- [ ] D33.2 Test thiếu → cấp một phần → nhập thêm → cấp bổ sung.
- [ ] D33.3 Test trả dư/hàng trả hỏng/tháo/cấp thay theo lượng.
- [ ] D33.4 Đổi revision/tên model không đổi lệnh và snapshot phiếu cũ.
- [ ] D33.5 Test hủy lệnh có giữ/nháp/đã xuất theo chính sách.
- [ ] D33.6 Đối soát từng model/kho/giữ/cấp/trả/xưởng/lắp.
**D34 — Quyền, đồng thời và hiệu năng.**
- [ ] D34.1 Test quyền đọc/lập/xác nhận/trả/lắp/tải file ở API.
- [ ] D34.2 Test hai người giữ/xuất lượng cuối, tồn và khả dụng không âm.
- [ ] D34.3 Test retry/double-click/stale form/rollback và thứ tự khóa.
- [ ] D34.4 Đo tìm model/bảng tồn/BOM/lệnh trên dữ liệu thống nhất.
- [ ] D34.5 Tối ưu index/query; chốt ngưỡng p95 đề xuất dưới 2 giây trên môi trường thử.
- [ ] D34.6 Test import/export lớn, giới hạn request và log tìm lỗi số lượng.
**D35 — Sửa lỗi và chuẩn bị UAT.**
- [ ] D35.1 Tổng hợp bug theo mức/tái hiện/người/hạn.
- [ ] D35.2 Sửa lỗi chặn và chạy lại phần bị ảnh hưởng.
- [ ] D35.3 Hoàn thành ít nhất 30 kịch bản mới tháng 2 đã chốt.
- [ ] D35.4 Chuẩn bị tài khoản/dataset/bảng kỳ vọng UAT.
- [ ] D35.5 Viết hướng dẫn Kho/Kỹ thuật/Sản xuất và quản trị.
- [ ] D35.6 Chốt ứng viên phát hành/lịch UAT/tiêu chí triển khai.
### Tuần 8 — UAT, chuyển dữ liệu và triển khai
**D36 — UAT nghiệp vụ.**
- [ ] D36.1 Kho thử model/nhập/cấp/trả một phần và lịch sử.
- [ ] D36.2 Kỹ thuật thử BOM/version/lắp/tháo và BOM thực tế.
- [ ] D36.3 Sản xuất thử lệnh nhiều robot/thiếu hàng/file bàn giao.
- [ ] D36.4 Xác nhận nhận hàng/ký nhận theo quy trình đã chốt.
- [ ] D36.5 Lưu kết quả từng kịch bản, phiếu/file/bằng chứng.
- [ ] D36.6 Phân loại lỗi chặn và phản hồi có thể để sau.
**D37 — Phản hồi và diễn tập migration.**
- [ ] D37.1 Sửa lỗi chặn UAT và thử lại.
- [ ] D37.2 Migration trên bản sao gần thời điểm triển khai.
- [ ] D37.3 Kho xác nhận model/alias/biến thể/đơn vị ngoại lệ.
- [ ] D37.4 So tồn/mượn/cấp/lưu trữ theo model/kho/tình trạng trước/sau.
- [ ] D37.5 Chạy lại migration, đo thời gian, kiểm tra không cộng lượng lần hai.
- [ ] D37.6 Lưu biên bản, mapping đã xác nhận và nhóm chưa chuyển.
**D38 — Phát hành và khôi phục.**
- [ ] D38.1 Chạy test liên quan/syntax/build CSS nếu đổi và kiểm tra dependency.
- [ ] D38.2 Sao lưu và thử restore riêng, mở/đối soát dữ liệu.
- [ ] D38.3 Chuẩn bị ứng dụng/Docker/migration/cấu hình mẫu không chứa bí mật.
- [ ] D38.4 Chốt thời gian dừng ghi/chuyển dữ liệu/người đối soát.
- [ ] D38.5 Chốt rollback trước/sau giao dịch mới, tránh restore làm mất phiếu mới.
- [ ] D38.6 Chủ dự án xác nhận điều kiện/thời điểm phát hành.
**D39 — Triển khai và đào tạo.**
- [ ] D39.1 Backup tại thời điểm chuyển, kiểm tra và dừng ghi theo lịch.
- [ ] D39.2 Triển khai/chuyển đúng mapping model và nhóm được xác nhận.
- [ ] D39.3 Đối soát lượng/lịch sử, mở ghi khi đạt.
- [ ] D39.4 Smoke test đăng nhập/kho/BOM/lệnh/file/quyền.
- [ ] D39.5 Đào tạo Kho/Kỹ thuật/Sản xuất bằng tình huống cụ thể.
- [ ] D39.6 Theo dõi log và chuỗi giao dịch được người vận hành xác nhận.
**D40 — Theo dõi và nghiệm thu.**
- [ ] D40.1 Đối soát tồn/giữ/cấp/lắp sau giao dịch đầu và sửa lỗi.
- [ ] D40.2 Nghiệm thu bốn yêu cầu, ghi ngoại lệ dữ liệu còn kiểm soát.
- [ ] D40.3 Hoàn thiện hướng dẫn/khôi phục/đầu mối hỗ trợ.
- [ ] D40.4 Báo cáo KPI tháng 2 với test/UAT/migration/triển khai.
- [ ] D40.5 Ghi backlog sau, người và ưu tiên.
- [ ] D40.6 Chốt người/lịch theo dõi sau D40 và bàn giao vận hành.
## 7. KPI tháng 1 — 100 điểm
Mục tiêu: kho theo model/số lượng và BOM robot liên kết model trên môi trường thử.
| Mã | KPI | Trọng số | Tiêu chí | Bằng chứng/xác nhận |
| ---- | ------------------------------------ | ------------: | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
| M1.1 | Nghiệp vụ và thiết kế | 15 | 6 đầu ra: đặc tả, ERD, trạng thái, ma trận quyền, mẫu file, quy tắc gom/chuyển dữ liệu; chốt tuần 1 | Tài liệu/biên bản; Chủ dự án/Kho/Kỹ thuật |
| M1.2 | Kho theo model và lượng | 25 | 20 model/2 kho mẫu; nhập/xuất/trả/chuyển đúng lượng/đơn vị; 0 sai tồn, 0 gom sai hãng/biến thể | Dataset/test/đối soát; Kho |
| M1.3 | Chuẩn hóa/import/chuyển dữ liệu | 20 | 100 dòng nguồn: mỗi dòng có mapping hoặc ngoại lệ rõ; tổng khớp; chạy lại không cộng hai lần; import có xem trước/lỗi theo dòng | Mapping/log/báo cáo; Dev/Kho |
| M1.4 | BOM theo model/version | 20 | 2 loại robot/3 revision; dòng liên kết ModelId/định mức; phát hành bất biến; tồn đúng, model lặp vị trí cộng đúng | BOM/test/demo; Kỹ thuật |
| M1.5 | Chất lượng/hồi quy | 10 | Ít nhất 20 kịch bản mới tháng 1 đạt; test cũ liên quan đạt; 0 lỗi nghiêm trọng tồn đọng | Test/bug; người nghiệm thu |
| M1.6 | Nghiệm thu/tài liệu | 10 | Demo xác nhận Kho/Kỹ thuật, hướng dẫn model/kho/BOM, báo cáo KPI/backlog | Biên bản/tài liệu; Chủ dự án |
| | **Tổng** | **100** | | |
## 8. KPI tháng 2 — 100 điểm
Mục tiêu: cấp model/số lượng cho BOM và robot sản xuất, file, BOM thực tế và vận hành.
| Mã | KPI | Trọng số | Tiêu chí | Bằng chứng/xác nhận |
| ---- | ---------------------------------- | ------------: | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ |
| M2.1 | Lệnh/nhu cầu/giữ lượng | 20 | 3 lệnh/5 robot tính đúng nhu cầu/thiếu/cấp ròng; không giữ vượt tồn; hủy giải phóng đúng; revision cố định | Bảng kỳ vọng/test; Kho/Sản xuất |
| M2.2 | Cấp/trả model và lượng | 30 | Cấp đủ/một phần/nhiều dòng, trả đúng model/phiếu/robot; 0 tồn âm/giữ vượt/trừ lặp; rollback đúng | Phiếu/SQL test/đối soát; Kho |
| M2.3 | File sản xuất | 15 | 4 loại: BOM, nhu cầu/thiếu, phiếu xuất, BOM thực tế; đúng model/đơn vị/lượng/robot; tải lại giữ snapshot | File/đối chiếu; Kho/Sản xuất |
| M2.4 | BOM thực tế/truy vết chứng từ | 10 | 5 robot mẫu có model/lượng đang lắp; truy hai chiều robot–model kèm lượng/phiếu; tháo/cấp bù giữ lịch sử | Demo/file/lịch sử; Kỹ thuật |
| M2.5 | Test/UAT | 15 | Ít nhất 30 kịch bản mới tháng 2 và 100% trọng yếu đạt; hồi quy đạt; 0 lỗi nghiêm trọng tồn đọng | Test/UAT/bug; Chủ dự án |
| M2.6 | Triển khai/bàn giao | 10 | 1 bản vận hành nghiệm thu; đối soát đạt, backup/restore diễn tập; tài liệu/đào tạo/hỗ trợ | Log/biên bản; Chủ dự án |
| | **Tổng** | **100** | | |
### Cách chấm
- Cuối tuần 1 chốt danh sách đầu ra/kịch bản và mẫu số mỗi KPI; không đổi mẫu số để tăng điểm.
- Tỷ lệ KPI = đầu ra/kịch bản được nghiệm thu ÷ tổng đã chốt, tối đa 100%.
- Điểm KPI = trọng số × tỷ lệ; tổng tháng tối đa 100.
- Ví dụ M1.1 đạt 5/6 đầu ra: 15 × 5/6 = 12,5 điểm.
- Có code chưa đủ; cần bằng chứng và người xác nhận.
- Dữ liệu/kiểm kê vật lý do Kho phụ trách; Dev làm ánh xạ/công cụ/đối soát. Phụ thuộc có người/hạn và báo ảnh hưởng mốc.
- Bộ 20 model/100 dòng nguồn/2 kho/2 loại robot/3 revision/3 lệnh/5 robot và 20+30 kịch bản là đề xuất, điều chỉnh tuần 1 theo thực tế.
- Đếm model là danh mục, đếm dòng nguồn là dữ liệu chuyển; không gọi 100 dòng là 100 chiếc.
**Điều kiện bắt buộc:** không nghiệm thu khi sai tồn, gom sai model/đơn vị, giữ vượt lượng, trừ lặp hoặc mất lịch sử. Không triển khai nếu luồng trọng yếu/chuyển dữ liệu chưa đạt. Ghi điểm thực tế nhưng đánh dấu chưa đạt điều kiện nghiệm thu; không dùng điểm trung bình bỏ qua lỗi chặn.
## 9. 50 kịch bản nghiệm thu tối thiểu
Kịch bản nghiệp vụ có thể tự động hóa phần quan trọng. Tranh lượng phải thử SQL Server riêng; test mock không chứng minh khóa/ràng buộc thực.
### Tháng 1 — 20 kịch bản
1. Tạo model hợp lệ có mã/hãng/đơn vị.
2. Alias/khoảng trắng được ánh xạ đúng; ký tự quan trọng giữ nguyên.
3. Tên model giống nhưng khác hãng/biến thể không tự gộp.
4. Trùng danh mục thật theo tổ hợp đã chốt bị chặn.
5. Model thiếu/chưa xác minh bị chặn phát hành BOM/giao dịch sản xuất mới.
6. Sửa thuộc tính có audit; đổi đơn vị/xóa model có lịch sử bị chặn.
7. Tìm/lọc/phân trang và chi tiết model đúng.
8. Nhập nhiều lần cùng model cộng đúng khi khác phiếu hợp lệ.
9. Xuất/mượn và trả một phần đúng lượng/phiếu/người.
10. Hàng hỏng/chờ kiểm tra không cộng khả dụng.
11. Người thiếu quyền không sửa/nhập/điều chỉnh qua API.
12. Lỗi lịch sử rollback cả giao dịch.
13. Import xem trước/lỗi dòng/cột đúng.
14. Retry cùng import không cộng lượng hai lần; phiếu mới cùng model vẫn hợp lệ.
15. Migration chạy lại giữ mapping/lịch sử, không cộng hai lần.
16. Gom đúng model/kho/tình trạng; khác đơn vị hoặc alias chưa rõ vào ngoại lệ.
17. Chuyển kho giữ tổng; lượng âm/số lẻ chiếc bị chặn.
18. BOM model/định mức/đơn vị hợp lệ; hết hàng vẫn giữ dòng.
19. Revision phát hành bất biến; model lặp vị trí tổng nhu cầu đúng.
20. BOM mở đúng tồn model theo kho; tổng/khả dụng khớp mẫu.
### Tháng 2 — 30 kịch bản mới
1. Lệnh một robot tính đúng nhu cầu model.
2. Lệnh nhiều robot và model lặp vị trí tính đúng.
3. Sửa revision không đổi lệnh đã xác nhận.
4. Thiếu hàng hiển thị đúng.
5. Khả dụng cho lệnh tính đúng phần giữ riêng.
6. Không lấy lượng giữ cho lệnh khác.
7. Hai lệnh tranh lượng cuối chỉ giữ trong giới hạn tồn.
8. Nhiều lệnh giữ cùng model được phép khi tổng đủ.
9. Hủy lệnh giải phóng đúng giữ.
10. Giữ không giảm tồn vật lý.
11. Phân lượng cho từng robot, tổng khớp phiếu.
12. Dòng model lặp không gây cấp vượt tổng nhu cầu.
13. Sai model/đơn vị, lượng âm hoặc lẻ chiếc bị chặn.
14. Nháp không đổi tồn.
15. Phiếu nhiều dòng giảm đúng tồn/giữ và tăng lượng tại xưởng.
16. Hai phiếu tranh lượng trên SQL không xuất vượt tồn.
17. Double-click/retry không ghi sổ hai lần.
18. Một dòng lỗi rollback toàn phiếu.
19. Cấp một phần rồi bổ sung không vượt lượng được duyệt.
20. Trả một phần đúng model/phiếu/robot cập nhật cấp ròng.
21. Sai model/trả quá/trả lặp bị chặn.
22. Trả hàng hỏng không thành khả dụng.
23. Lượng đã lắp phải tháo hợp lệ trước trả.
24. Lắp không vượt lượng đã cấp còn tại xưởng.
25. Tháo không vượt đang lắp; cấp bù giữ lịch sử model/lượng.
26. Hoàn thành robot thiếu cấu phần bắt buộc bị chặn.
27. Bốn loại file khớp model/hãng/đơn vị/lượng/robot.
28. Tải lại lấy snapshot; đổi tên model/BOM không đổi phiếu cũ hoặc tồn.
29. Quyền lập/xác nhận/trả/lắp/tải kiểm tra ở API.
30. Chuyển/restore giữ tổng theo model/kho/tình trạng và lịch sử nguồn.
## 10. Theo dõi công việc và báo cáo tuần
| Mã | Đầu việc | Người làm | Người nghiệm thu | Phụ thuộc | Hạn | Trạng thái | Bằng chứng | KPI |
| ----- | --------------------------------------------- | ------------ | ------------------- | ------------- | ---- | ------------ | ------------------- | ---- |
| D10.2 | Gom dòng cùng model, giữ bucket/mapping | Dev + Kho | Kho | D02.1, D06 | D10 | Chưa làm | Mapping/đối soát | M1.3 |
| D30.6 | Đối chiếu Excel với phiếu và tồn model | Kho + Dev | Kho/Sản xuất | D27, D30.1–5 | D30 | Chưa làm | File/biên bản | M2.3 |
Thêm cột tháng/tuần và giờ ước lượng khi chia việc. Trạng thái: Chưa làm → Đang làm → Chờ kiểm tra → Hoàn thành; Chờ đầu vào phải có người/hạn.
Báo cáo tuần: đầu ra đã nghiệm thu, KPI từng nhóm, lỗi chặn, model/đơn vị chưa rõ, phụ thuộc quá hạn, dự phòng đã dùng và mục tiêu tuần sau. Không đo tiến độ chỉ bằng số checklist vì kích thước việc khác nhau.
## 11. Rủi ro và xử lý
| Rủi ro | Xử lý | Chủ trì |
| -------------------------------------------------- | ------------------------------------------------------------------------------------------- | ---------------- |
| Model gõ nhiều kiểu, thiếu hãng/thông số | Mapping/alias có xác nhận, nhóm ngoại lệ giữ riêng | Kho + Kỹ thuật |
| Gộp tên giống nhưng khác cấu hình/đơn vị | Định danh hãng/model/biến thể, đơn vị cơ sở; không gộp theo chuỗi đơn thuần | Kỹ thuật + Dev |
| Tài sản/vật tư hai nguồn bị đếm đôi | Xác nhận nguồn/mapping, đối soát trước/sau | Kho |
| Kho cũ/mới cùng sửa tổng | Một nguồn có thẩm quyền, cập nhật transaction, chặn sửa trực tiếp | Dev |
| Nhiều lệnh tranh lượng | Khóa bucket, kiểm tra sau khóa, test SQL thật | Dev |
| Import trùng model bị coi là phiếu trùng | Tách danh mục/phiếu nhập/tồn đầu; chống lặp theo chứng từ | Dev |
| Mượn/xuất/lắp bị cộng vào khả dụng | Tách bucket/vị trí/loại giao dịch, đối soát luồng cũ | Dev + Kho |
| Mong đợi truy vết chiếc dù chỉ quản model | Ghi rõ giới hạn model/lượng/phiếu; bổ sung serial/lô là phạm vi riêng | Chủ dự án |
| Phạm vi tăng hoặc phản hồi muộn | Demo hằng tuần, mẫu file tuần 1, quỹ dự phòng, điều chỉnh nguồn lực/lịch | Chủ dự án |
| Rollback mất phiếu mới | Dừng ghi/đối soát trước restore; phương án sau phát sinh giao dịch rõ | Dev + vận hành |
## 12. Nội dung đăng ký KPI tháng
**Tháng 1:** Chuẩn hóa danh mục model tài sản và ánh xạ dữ liệu cũ; hoàn thiện kho theo model/số lượng/kho/tình trạng, nhập/xuất/trả/import có đối soát; xây dựng BOM robot theo model có phiên bản và liên kết kho; kiểm thử/hồi quy và nghiệm thu theo sáu KPI tháng 1.
**Tháng 2:** Xây dựng lệnh sản xuất theo revision BOM, tính nhu cầu/thiếu và giữ số lượng theo model; cấp/trả và phân bổ cho từng robot; xuất bốn loại file; xác nhận lắp/tháo theo model/lượng và truy vết chứng từ; hoàn thành UAT, chuyển dữ liệu, triển khai/bàn giao theo sáu KPI tháng 2.
Tình huống nghiệm thu cuối kỳ: robot R-001 có BOM cần M-A 2 chiếc và C-A 1 chiếc → giữ/cấp đúng lượng → xác nhận đã lắp → xem phiếu/đơn vị/lượng/model → tải file khớp → tra model M-A thấy các robot và lượng đã cấp/đang lắp, không tuyên bố nhận diện từng chiếc.
## 13. Thay đổi so với kế hoạch serial trước đây
| Trước | Kế hoạch hiện tại |
| --------------------------------------- | ---------------------------------------------------------------------- |
| Danh mục + từng chiếc/AssetInstances | Danh mục AssetModels + tồn model/kho/tình trạng |
| Chuẩn hóa/duy nhất serial | Chuẩn hóa model/hãng/biến thể/alias/đơn vị |
| Chọn serial để cấp/giữ | Chọn model/kho/lượng; giữ số lượng |
| Trả/lắp từng chiếc | Trả/lắp đúng model/phiếu/robot và lượng |
| Đối soát danh sách serial | Đối soát mapping và tổng lượng theo model/kho/tình trạng |
| Robot ↔ serial | Robot ↔ model kèm lượng/chứng từ |
| KPI 100 thiết bị có serial | KPI 20 model và 100 dòng nguồn có mapping/ngoại lệ |
| Chặn thiếu serial | Chặn thiếu/chưa xác minh model/đơn vị; serial không bắt buộc |
Giữ lộ trình 8 tuần/40 ngày/240 đầu việc, các mốc nghiệm thu và tổng trọng số KPI tháng. Nội dung checklist, dữ liệu mẫu, mô hình và 50 kịch bản đã đổi theo model; không chỉ thay từ ngữ.

View File

@@ -1,765 +0,0 @@
# Portable UI Style Guide - AccManager Inspired
Tài liệu này dùng để mang phong cách UI hiện tại của AccManager sang một dự án khác. Nội dung tập trung vào ngôn ngữ thiết kế, token, layout, component pattern và checklist triển khai, không phụ thuộc chặt vào nghiệp vụ tài khoản/tài sản của AccManager.
## 1. Design DNA
Phong cách UI gốc là một **admin console nội bộ**: gọn, sáng, nhiều dữ liệu, dễ quét bảng, thao tác nhanh và ít trang trí thừa.
Tinh thần chính:
- Ưu tiên hiệu quả vận hành hơn cảm giác marketing.
- Nền sáng, bề mặt trắng/xám nhạt, màu nhấn xanh primary.
- Layout chắc, dày thông tin nhưng vẫn thoáng.
- Component nhỏ gọn: table, filter, modal, form, badge, icon action.
- Button và icon rõ chức năng, phản hồi hover/active nhẹ.
- Typography dùng heading đậm, label nhỏ uppercase, nội dung bảng vừa đủ đọc.
- Phù hợp cho dashboard, CRM, ERP mini, tool nội bộ, quản lý dữ liệu, asset/account/user management.
Không nên biến phong cách này thành landing page, hero lớn, nhiều gradient trang trí, card marketing hoặc layout quá thoáng kiểu portfolio.
## 2. Stack Khuyến Nghị
Để tái tạo đúng style, dự án mới nên dùng:
- Tailwind CSS.
- Font heading: `Manrope`.
- Font body: `Inter`.
- Icon: Google Material Symbols Outlined.
- Toast/notification: Notiflix hoặc thư viện tương đương.
- Table data với sticky header, horizontal scroll trên mobile.
Google Fonts:
```html
<link href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<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">
```
Material Symbols base CSS:
```css
.material-symbols-outlined {
font-family: 'Material Symbols Outlined';
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
font-size: 1.25rem;
line-height: 1;
letter-spacing: normal;
text-transform: none;
display: inline-flex;
white-space: nowrap;
direction: ltr;
}
```
## 3. Tailwind Design Tokens
Có thể copy phần `theme.extend` này sang `tailwind.config.js` của dự án mới.
```js
theme: {
extend: {
colors: {
"primary": "#3755c3",
"primary-dim": "#2848b7",
"primary-container": "#dde1ff",
"on-primary": "#f8f7ff",
"background": "#f7f9fb",
"surface": "#f7f9fb",
"surface-container-lowest": "#ffffff",
"surface-container-low": "#f0f4f7",
"surface-container": "#e8eff3",
"surface-container-high": "#e1e9ee",
"surface-container-highest": "#d9e4ea",
"on-surface": "#2a3439",
"on-surface-variant": "#566166",
"outline": "#717c82",
"outline-variant": "#a9b4b9",
"error": "#9f403d",
"error-container": "#fe8983"
},
fontFamily: {
headline: ["Manrope", "sans-serif"],
body: ["Inter", "sans-serif"],
label: ["Inter", "sans-serif"]
},
borderRadius: {
DEFAULT: "0.125rem",
lg: "0.25rem",
xl: "0.5rem",
full: "0.75rem"
}
}
}
```
Base body:
```html
<body class="bg-background text-on-surface antialiased">
```
Font rule:
```css
body { font-family: 'Inter', sans-serif; }
h1, h2, h3, .brand-logo { font-family: 'Manrope', sans-serif; }
```
## 4. Color Usage
Màu nền:
- App background: `bg-background`.
- Main card/table: `bg-white` hoặc `bg-surface-container-lowest`.
- Filter bar/input subtle: `bg-surface-container-low`.
- Header/table head: `bg-slate-50`.
Màu chữ:
- Text chính: `text-on-surface`, `text-slate-900`.
- Text phụ: `text-on-surface-variant`, `text-slate-500`, `text-slate-600`.
- Link/action chính: `text-primary`.
Màu hành động:
- Primary: `bg-primary hover:bg-primary-dim text-on-primary`.
- Secondary: border slate, text slate.
- Danger: `bg-red-600 hover:bg-red-700 text-white` hoặc `text-error`.
- Success: emerald/green.
- Pending/warning: amber/yellow.
- Info: blue.
Tránh:
- Dùng quá nhiều gradient.
- Dùng một palette đơn sắc toàn xanh.
- Nền tối toàn trang nếu chưa thiết kế dark mode đầy đủ.
- Màu quá rực trên bảng dữ liệu.
## 5. Typography Scale
Page title:
```html
<h1 class="text-2xl font-extrabold text-on-surface tracking-tight">Page Title</h1>
```
Subtitle:
```html
<p class="text-sm text-on-surface-variant">Short page description.</p>
```
Table header / form label:
```html
<span class="text-[10px] font-bold uppercase tracking-wider text-on-surface-variant">Label</span>
```
Table body:
```html
<td class="px-4 py-3 text-sm text-slate-600">Value</td>
```
Badge text:
```html
<span class="px-2 py-1 rounded text-xs font-semibold">Status</span>
```
Nguyên tắc:
- Heading đậm, ngắn, dễ scan.
- Label nhỏ, uppercase, tracking rộng.
- Nội dung bảng không quá lớn để giữ mật độ dữ liệu.
- Không dùng hero-scale type trong dashboard/tool view.
## 6. App Shell Pattern
Dùng shell này cho các app quản trị/dữ liệu.
```html
<body class="app-shell bg-background text-on-surface antialiased flex h-screen w-screen overflow-hidden">
<aside id="appSidebar" class="h-screen w-56 flex flex-col bg-slate-100 border-r border-outline-variant/10 shrink-0">
<!-- Sidebar content -->
</aside>
<button id="sidebarBackdrop" type="button" aria-label="Close navigation"></button>
<main id="appMain" class="flex-1 flex flex-col h-screen min-w-0">
<header class="h-14 flex items-center justify-between px-6 bg-slate-50/80 backdrop-blur-xl border-b border-outline-variant/10 shrink-0">
<!-- Topbar actions -->
</header>
<div id="mainContent" class="flex-1 overflow-hidden">
<!-- Current page -->
</div>
</main>
</body>
```
Sidebar style:
- Width desktop: `w-56`.
- Background: `bg-slate-100`.
- Border right: `border-outline-variant/10`.
- Group label: uppercase, `text-[10px]`, tracking rộng.
- Active nav: left border xanh, nền slate nhạt, text đậm.
- Nav item: icon + label, height vừa phải, hover nền slate.
Active nav example:
```html
<a class="flex items-center gap-3 px-3 py-2 border-l-4 border-blue-600 bg-slate-200/80 text-slate-900 font-bold rounded-r-lg">
<span class="material-symbols-outlined">dashboard</span>
<span>Tổng quan</span>
</a>
```
Inactive nav:
```html
<a class="flex items-center gap-3 px-3 py-2 text-slate-600 hover:text-slate-900 hover:bg-slate-200/50 transition-all rounded-r-lg">
<span class="material-symbols-outlined">apps</span>
<span>Ứng dụng</span>
</a>
```
## 7. Page Layout Pattern
Mỗi page nên theo cấu trúc:
```html
<div class="page-name flex flex-col p-4 md:p-6 overflow-hidden h-full">
<div class="page-header flex items-center justify-between gap-4 mb-5 shrink-0">
<div>
<h1 class="text-2xl font-extrabold text-on-surface tracking-tight">Page Title</h1>
<p class="text-sm text-on-surface-variant">Short explanation.</p>
</div>
<div class="flex flex-wrap items-center gap-2">
<!-- Action buttons -->
</div>
</div>
<div class="page-filters flex items-center gap-3 mb-4 shrink-0">
<!-- Search/filter controls -->
</div>
<div class="flex-1 bg-white rounded-xl border border-slate-200 shadow-sm flex flex-col overflow-hidden min-h-0">
<!-- Table/list/content -->
</div>
</div>
```
Nguyên tắc:
- Page padding luôn `p-4 md:p-6`.
- Header không quá cao.
- Action chính nằm bên phải.
- Filter nằm ngay trên bảng.
- Content panel chiếm hết phần còn lại.
- Không bọc section bằng quá nhiều card lồng nhau.
## 8. Dashboard Pattern
Dashboard nên có:
- Header ngắn.
- CTA chính.
- Metric grid.
- Recent activity hoặc bảng tóm tắt.
Metric card:
```html
<div class="bg-surface-container-lowest p-4 rounded-xl border border-outline-variant/15 flex flex-col">
<span class="text-[10px] font-bold text-on-surface-variant uppercase tracking-wider mb-2">Applications</span>
<div class="flex items-baseline justify-between">
<span class="text-2xl font-black text-on-surface">24</span>
<span class="text-[10px] font-bold text-on-surface-variant">18 Active</span>
</div>
</div>
```
Grid:
```html
<div class="dashboard-stats grid grid-cols-4 gap-4 shrink-0">
```
Responsive:
- Desktop: 4 cột.
- Tablet/mobile: 2 cột.
- Mobile nhỏ: 1 cột.
## 9. Table Pattern
Đây là component quan trọng nhất của style này.
```html
<div class="flex-1 bg-white rounded-xl border border-slate-200 shadow-sm flex flex-col overflow-hidden min-h-0">
<div class="table-wrap overflow-y-auto overflow-x-auto flex-1">
<table class="w-full text-left border-collapse" style="min-width: 900px;">
<thead class="sticky top-0 z-10 bg-slate-50 border-b border-slate-200">
<tr>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Name</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500 text-right">Actions</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100">
<tr class="hover:bg-slate-50/80 transition-colors">
<td class="px-4 py-3 text-sm text-slate-700">Example</td>
<td class="px-4 py-3 text-right">...</td>
</tr>
</tbody>
</table>
</div>
<div class="page-pager flex items-center justify-between px-4 py-2 border-t border-slate-200 bg-slate-50 text-xs text-slate-600">
<span>Showing 1-10 of 50</span>
<div class="flex items-center gap-2">
<button class="px-2 py-1 border border-slate-200 rounded text-xs">Prev</button>
<span class="text-[11px]">Page 1 / 5</span>
<button class="px-2 py-1 border border-slate-200 rounded text-xs">Next</button>
</div>
</div>
</div>
```
Quy ước table:
- Header sticky.
- Row hover nhẹ.
- Cell padding đều.
- Text trong bảng ưu tiên `text-sm`.
- Header dùng `text-[10px] uppercase`.
- Nếu nhiều cột, đặt `min-width` và cho horizontal scroll.
- Nếu có action column quan trọng, có thể sticky bên phải.
Sticky action column:
```html
<td class="sticky right-0 z-10 bg-white group-hover:bg-slate-50/80 px-4 py-3 text-right shadow-[-10px_0_12px_-12px_rgba(15,23,42,0.45)]">
```
## 10. Filter/Search Pattern
Filter bar:
```html
<div class="page-filters flex items-center gap-3 mb-4">
<div class="flex items-center gap-1.5">
<span class="text-[10px] font-bold uppercase text-on-surface-variant">Status</span>
<select class="bg-surface-container-low border-slate-200 rounded-md text-[11px] py-1 px-2 pr-6 focus:ring-1 focus:ring-primary shadow-sm">
<option>All</option>
</select>
</div>
<div class="flex items-center gap-1.5 flex-1">
<span class="text-[10px] font-bold uppercase text-on-surface-variant">Search</span>
<input class="flex-1 bg-surface-container-low border-slate-200 rounded-md text-[11px] py-1 px-2 focus:ring-1 focus:ring-primary shadow-sm" placeholder="Search...">
</div>
</div>
```
Nguyên tắc:
- Filter ngắn, đặt sát bảng.
- Search chiếm phần còn lại.
- Label filter nhỏ và uppercase.
- Trên mobile, filter chuyển thành column/full width.
## 11. Button Pattern
Primary:
```html
<button class="bg-primary hover:bg-primary-dim text-on-primary px-4 py-2 rounded-lg text-xs font-bold flex items-center gap-1.5 transition-all active:scale-95">
<span class="material-symbols-outlined text-base">add</span>
Add New
</button>
```
Secondary:
```html
<button class="border border-slate-300 hover:bg-slate-100 text-slate-700 px-3 py-2 rounded-lg text-xs font-bold flex items-center gap-1.5 transition-all active:scale-95">
<span class="material-symbols-outlined text-base">download</span>
Export
</button>
```
Danger:
```html
<button class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg text-xs font-bold">
Delete
</button>
```
Icon action:
```html
<button class="p-1.5 text-slate-400 transition-colors hover:text-primary" title="Edit">
<span class="material-symbols-outlined text-lg">edit</span>
</button>
```
Disabled:
```html
<button class="opacity-50 cursor-not-allowed" disabled>Disabled</button>
```
## 12. Form Pattern
Form field:
```html
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Name</label>
<input class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="Enter name">
</div>
```
Readonly:
```html
<input readonly class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 bg-slate-50 text-slate-600">
```
Textarea:
```html
<textarea class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 h-20 resize-none"></textarea>
```
Field with icon:
```html
<div class="relative">
<span class="absolute left-3 top-1/2 -translate-y-1/2 text-on-surface-variant/60">
<span class="material-symbols-outlined text-base">person</span>
</span>
<input class="w-full pl-10 pr-4 py-2.5 bg-surface-container-low border border-outline-variant/30 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent text-sm font-medium">
</div>
```
## 13. Badge/Status Pattern
Online/offline:
```html
<div class="flex items-center gap-1.5">
<div class="w-1.5 h-1.5 rounded-full bg-primary ring-2 ring-primary/20"></div>
<span class="text-xs font-medium text-on-primary-fixed-variant">Online</span>
</div>
```
Status badges:
```html
<span class="inline-block px-2 py-1 rounded text-xs font-semibold bg-emerald-100 text-emerald-700">Trong kho</span>
<span class="inline-block px-2 py-1 rounded text-xs font-semibold bg-blue-100 text-blue-700">Đang sử dụng</span>
<span class="inline-block px-2 py-1 rounded text-xs font-semibold bg-yellow-100 text-yellow-700">Đang chờ</span>
<span class="inline-block px-2 py-1 rounded text-xs font-semibold bg-red-100 text-red-700">Từ chối</span>
```
Role chip:
```html
<span class="px-3 py-1 rounded-full text-xs font-semibold bg-blue-100 text-blue-700">Admin</span>
```
## 14. Modal Pattern
Backdrop + content:
```html
<div class="modal-backdrop fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="exampleModal">
<div class="modal-content w-full max-w-lg bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden m-4">
<div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50">
<h3 class="text-base font-extrabold text-slate-900">Modal Title</h3>
<button class="p-1.5 rounded-lg hover:bg-slate-200 text-slate-400 transition-colors">
<span class="material-symbols-outlined">close</span>
</button>
</div>
<form class="p-6 space-y-4">
<!-- Fields -->
<div class="flex gap-3 pt-4">
<button type="button" class="flex-1 px-4 py-2 text-xs font-bold text-slate-600 border border-slate-200 rounded-lg">Cancel</button>
<button type="submit" class="flex-1 px-4 py-2 bg-primary hover:bg-primary-dim text-on-primary rounded-lg text-xs font-bold">Save</button>
</div>
</form>
</div>
</div>
```
Modal CSS:
```css
.modal-backdrop {
opacity: 0;
transition: opacity 0.2s ease-in-out;
pointer-events: none;
}
.modal-backdrop.open {
opacity: 1;
pointer-events: auto;
}
.modal-content {
transform: scale(0.95);
transition: transform 0.2s ease-in-out;
}
.modal-backdrop.open .modal-content {
transform: scale(1);
}
```
Danger confirm modal:
```html
<div class="px-6 py-4 border-b border-slate-100 bg-red-50 flex items-center gap-3">
<span class="material-symbols-outlined text-red-600 text-2xl">warning</span>
<h3 class="text-base font-extrabold text-red-700">Xác nhận xóa</h3>
</div>
```
## 15. Login/Auth Screen Pattern
Auth screen dùng centered card:
```html
<body class="bg-gradient-to-br from-blue-50 via-background to-purple-50 antialiased">
<div class="min-h-screen flex items-center justify-center px-4">
<div class="w-full max-w-md">
<div class="bg-white rounded-2xl shadow-lg border border-outline-variant/10 p-8">
<div class="text-center mb-8">
<div class="flex justify-center mb-4">
<div class="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center">
<span class="material-symbols-outlined text-primary text-4xl">security</span>
</div>
</div>
<h1 class="text-2xl font-black text-slate-900 tracking-tight">Product Name</h1>
<p class="text-xs uppercase tracking-widest text-on-surface-variant font-bold mt-2">Admin Console</p>
</div>
<!-- Form -->
</div>
</div>
</div>
</body>
```
Auth tabs:
```html
<div class="flex gap-2 mb-6" role="tablist">
<button class="flex-1 py-2.5 rounded-lg text-xs font-bold uppercase tracking-wider border border-outline-variant/30 bg-primary text-on-primary shadow-sm">Đăng nhập</button>
<button class="flex-1 py-2.5 rounded-lg text-xs font-bold uppercase tracking-wider border border-outline-variant/30 bg-surface-container-low text-on-surface-variant">Đăng ký</button>
</div>
```
Alert states:
```html
<div class="bg-error-container/20 text-error/80 border border-error/30 rounded-lg px-4 py-3 text-xs font-medium">Error message</div>
<div class="bg-green-50 text-green-800 border border-green-200 rounded-lg px-4 py-3 text-xs font-medium">Success message</div>
<div class="bg-amber-50 text-amber-800 border border-amber-200 rounded-lg px-4 py-3 text-xs font-medium">Warning message</div>
```
## 16. Responsive Rules
Recommended CSS:
```css
#mobileMenuBtn,
#sidebarBackdrop {
display: none;
}
@media (max-width: 900px) {
body.app-shell {
width: 100%;
min-height: 100dvh;
height: 100dvh;
overflow: hidden;
position: relative;
}
#mobileMenuBtn {
display: inline-flex;
align-items: center;
justify-content: center;
}
#sidebarBackdrop {
display: block;
position: fixed;
inset: 0;
z-index: 70;
background: rgba(15, 23, 42, 0.45);
opacity: 0;
pointer-events: none;
transition: opacity 0.2s ease-in-out;
}
#appSidebar {
position: fixed;
inset: 0 auto 0 0;
height: 100dvh;
width: min(82vw, 16rem);
z-index: 80;
transform: translateX(-100%);
transition: transform 0.2s ease-in-out;
box-shadow: 0 20px 45px rgba(15, 23, 42, 0.35);
}
body.mobile-nav-open #sidebarBackdrop {
opacity: 1;
pointer-events: auto;
}
body.mobile-nav-open #appSidebar {
transform: translateX(0);
}
.page-header,
.page-filters,
.users-controls {
flex-direction: column;
align-items: stretch;
gap: 0.75rem;
}
.table-wrap {
overflow-x: auto;
}
.table-wrap table {
min-width: 700px;
}
.page-pager {
gap: 0.5rem;
flex-direction: column;
align-items: flex-start;
}
.modal-backdrop {
align-items: flex-end;
}
.modal-backdrop .modal-content {
width: calc(100% - 1rem);
max-height: min(88dvh, 700px);
margin: 0.5rem;
overflow-y: auto;
border-radius: 0.9rem;
}
}
@media (max-width: 560px) {
.dashboard-stats {
grid-template-columns: 1fr;
}
}
```
Mobile behavior:
- Sidebar thành off-canvas.
- Topbar gọn lại.
- Profile metadata nên ẩn.
- Header/filter chuyển column.
- Table luôn scroll ngang nếu nhiều cột.
- Modal gần bottom và giới hạn chiều cao.
## 17. UX Rules
Giữ những nguyên tắc này khi áp dụng sang dự án khác:
1. Mỗi màn dữ liệu cần có search hoặc filter nếu danh sách có thể dài.
2. Action chính luôn rõ ràng, nằm ở page header.
3. Action nguy hiểm luôn cần confirm.
4. Action theo quyền nên disabled trực quan, không chỉ báo lỗi sau khi bấm.
5. Table phải có empty state.
6. Table dài cần pagination.
7. Form dài nên chia grid 2 cột trên desktop, 1 cột mobile.
8. Modal dài phải scroll trong content, không làm tràn viewport.
9. Badge trạng thái phải thống nhất màu theo ý nghĩa.
10. Icon-only button phải có `title` hoặc accessible name.
11. Không dùng nhiều card trang trí trong dashboard vận hành.
12. Text không được overlap hoặc tràn button/card.
## 18. Accessibility Checklist
Khi port sang dự án mới, nên bổ sung:
- `aria-label` cho icon-only buttons.
- `role="dialog"` và `aria-modal="true"` cho modal.
- Focus trap trong modal.
- Đóng modal bằng phím `Escape`.
- `aria-expanded` cho mobile menu.
- `aria-selected` cho tabs.
- Label đầy đủ cho form input.
- Không chỉ dùng màu để truyền đạt trạng thái; nên có text status.
- Contrast đủ tốt cho text nhỏ.
## 19. Implementation Checklist
Khi bắt đầu dự án mới:
1. Cài Tailwind và plugin forms nếu cần.
2. Copy design tokens vào `tailwind.config.js`.
3. Thêm Google Fonts và Material Symbols.
4. Tạo app shell: sidebar, topbar, content area.
5. Tạo component base cho button, table, filter, modal, badge.
6. Tạo responsive sidebar theo breakpoint `900px`.
7. Áp dụng page layout pattern cho từng màn hình.
8. Kiểm tra table trên mobile với horizontal scroll.
9. Chuẩn hóa status color map.
10. Thêm empty/loading/error states.
## 20. Mapping Sang Dự Án Khác
Nếu dự án mới không phải quản lý tài khoản/tài sản, vẫn có thể dùng style này bằng cách đổi tên module:
| AccManager concept | Dự án mới có thể thay bằng |
| --- | --- |
| Applications | Products, Services, Modules, Integrations |
| Accounts | Records, Credentials, Customers, Contracts |
| Assets | Inventory, Devices, Documents, Items |
| Users | Members, Staff, Operators |
| Departments | Teams, Groups, Categories |
| Projects | Campaigns, Workspaces, Sites |
| Borrow/Return | Requests, Tickets, Approvals, Workflows |
Điều quan trọng là giữ cùng cấu trúc:
- Sidebar nhóm chức năng.
- Page header + actions.
- Filter/search.
- Table/list.
- Modal CRUD.
- Badge trạng thái.
- Toast feedback.
## 21. Những Gì Nên Tránh Khi Port
- Copy nguyên text nghiệp vụ AccManager nếu dự án mới khác domain.
- Copy table quá nhiều cột khi domain không cần.
- Lạm dụng modal cho mọi thứ nếu workflow mới cần full page editor.
- Dùng gradient nền cho app shell chính.
- Tăng border radius quá lớn làm mất chất admin console.
- Dùng font khác quá mềm hoặc decorative.
- Thêm quá nhiều shadow, glassmorphism, decorative blobs.
- Trộn nhiều style icon khác nhau.

View File

@@ -7,7 +7,7 @@
"start": "node backend/server.js",
"dev": "nodemon backend/server.js",
"review:export": "node tools/export-review-server.js",
"test": "node --test",
"test": "node backend/run-tests.js",
"check": "node --check backend/server.js && node --check public/js/app.js && npm audit",
"build:css": "tailwindcss -c tailwind.config.js -i ./public/css/tailwind.css -o ./public/css/main.css --minify",
"watch:css": "tailwindcss -c tailwind.config.js -i ./public/css/tailwind.css -o ./public/css/main.css --watch"

View File

@@ -0,0 +1,48 @@
.announcement-dialog {
width: min(560px, calc(100vw - 32px));
max-height: calc(100dvh - 40px);
margin: auto;
padding: 0;
overflow-y: auto;
border: 1px solid #e2e8f0;
border-radius: 16px;
background: white;
color: #243248;
box-shadow: 0 24px 80px #0f172a40;
}
.announcement-dialog::backdrop { background: rgb(15 23 42 / 55%); backdrop-filter: blur(3px); }
.announcement-heading { display: flex; align-items: flex-start; gap: 14px; padding: 24px 24px 20px; border-bottom: 1px solid #edf1f7; }
.announcement-symbol { display: flex; align-items: center; justify-content: center; flex-shrink: 0; width: 44px; height: 44px; border-radius: 12px; background: #edf1ff; color: #3755c3; font-size: 25px; }
.announcement-heading > div { flex: 1; min-width: 0; }
.announcement-heading p { margin: 2px 0 6px; color: #64748b; font-size: 10px; font-weight: 700; letter-spacing: 0.09em; }
.announcement-heading h2 { font-size: 19px; font-weight: 800; line-height: 1.5; overflow-wrap: anywhere; }
.announcement-heading button { display: flex; padding: 5px; border-radius: 7px; color: #64748b; }
.announcement-heading button:hover { background: #f1f5f9; }
.announcement-body { padding: 20px 24px 24px; }
.announcement-author { margin-bottom: 16px; color: #64748b; font-size: 11px; line-height: 1.8; }
#announcementMessage { white-space: pre-wrap; overflow-wrap: anywhere; font-size: 14px; line-height: 1.85; }
.announcement-error { margin-top: 16px; border-radius: 8px; padding: 10px 12px; background: #fff1f2; color: #be123c; font-size: 12px; line-height: 1.6; }
.announcement-footer { padding: 18px 24px 22px; border-top: 1px solid #edf1f7; background: #f8fafc; }
.announcement-footer label { display: flex; align-items: center; gap: 9px; width: fit-content; min-height: 32px; font-size: 13px; font-weight: 600; cursor: pointer; }
.announcement-footer input { width: 16px; height: 16px; border: 1px solid #94a3b8; border-radius: 4px; color: #3755c3; }
.announcement-footer > p { margin: 3px 0 18px; color: #64748b; font-size: 11px; line-height: 1.6; }
.announcement-footer > div { display: flex; justify-content: flex-end; flex-wrap: wrap; gap: 10px; }
.announcement-footer button { min-height: 42px; padding: 10px 18px; border: 1px solid #dbe2ef; border-radius: 8px; font-size: 12px; font-weight: 700; }
.announcement-footer .announcement-primary { border-color: #3755c3; background: #3755c3; color: white; }
.announcement-footer .announcement-secondary { background: white; color: #3755c3; }
.announcement-dialog button:disabled { opacity: 0.6; cursor: wait; }
.announcement-dialog :is(button, input):focus-visible { outline: 2px solid #3755c3; outline-offset: 3px; }
.announcement-management-note { margin-top: 20px; border: 1px solid #dce4f6; border-radius: 10px; padding: 14px 16px; background: #f0f4ff; color: #435577; font-size: 12px; line-height: 1.8; }
.announcement-post-status { margin-top: 8px; color: #64748b; font-size: 11px; font-weight: 600; }
.notification-withdraw-dialog .bom-confirm-icon { color: #dc2626; background: #fef2f2; }
.notification-withdraw-dialog .bom-dialog-footer { justify-content: flex-end; }
.notification-withdraw-summary { margin-bottom: 18px; padding: 16px; border: 1px solid #e2e8f0; border-radius: 8px; background: #f8fafc; overflow-wrap: anywhere; }
.notification-withdraw-summary strong { font-size: 14px; font-weight: 700; }
.notification-withdraw-summary p { margin-top: 6px; color: #64748b; font-size: 11px; line-height: 1.6; }
#notificationComposerModal > div { max-height: calc(100dvh - 32px); overflow-y: auto; }
@media (max-width: 480px) {
.announcement-heading { padding: 18px 16px 16px; gap: 10px; }
.announcement-heading h2 { font-size: 17px; }
.announcement-body, .announcement-footer { padding: 16px; }
.announcement-symbol { width: 36px; height: 36px; font-size: 22px; }
}

View File

@@ -0,0 +1,364 @@
/* Asset catalog actions: page utilities and actions on the current selection. */
.assets-page {
--asset-action-surface: #fff;
--asset-action-text: #334155;
--asset-action-muted: #64748b;
--asset-action-border: #e2e8f0;
--asset-action-tint: #f5f7ff;
}
.assets-page .asset-page-heading {
position: relative;
z-index: 120;
}
.asset-page-actions,
.asset-selection-actions {
display: flex;
align-items: center;
gap: 0.5rem;
flex-shrink: 0;
}
.assets-page .asset-action-button {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
min-height: 2.5rem;
padding: 0.5625rem 0.875rem;
border: 1px solid var(--asset-action-border);
border-radius: 0.625rem;
background: var(--asset-action-surface);
color: var(--asset-action-text);
font-size: 0.8125rem;
font-weight: 600;
line-height: 1.25;
white-space: nowrap;
cursor: pointer;
touch-action: manipulation;
transition: border-color 0.15s, background-color 0.15s, color 0.15s;
}
.asset-action-button .material-symbols-outlined,
.asset-menu-item .material-symbols-outlined {
flex-shrink: 0;
font-size: 1.125rem;
}
.assets-page .asset-action-button:hover:not(:disabled) {
border-color: #b8c4e8;
background: var(--asset-action-tint);
color: #3755c3;
}
.assets-page .asset-action-primary {
border-color: #3755c3;
background: #3755c3;
color: #fff;
box-shadow: 0 2px 4px rgb(55 85 195 / 0.12);
}
.assets-page .asset-action-primary:hover:not(:disabled) {
border-color: #2848b7;
background: #2848b7;
color: #fff;
}
.asset-action-button:focus-visible,
.asset-menu-item:focus-visible,
.asset-selection-clear:focus-visible {
outline: 2px solid #3755c3;
outline-offset: 3px;
}
.assets-page .asset-action-button:disabled,
.assets-page .asset-menu-item:disabled {
color: #94a3b8;
cursor: not-allowed;
}
.asset-action-menu {
position: relative;
}
.asset-action-menu > summary {
list-style: none;
}
.asset-action-menu > summary::-webkit-details-marker {
display: none;
}
.asset-action-menu[open] > summary {
border-color: #b8c4e8;
color: #3755c3;
background: var(--asset-action-tint);
}
.asset-menu-chevron {
transition: transform 0.15s;
}
.asset-action-menu[open] .asset-menu-chevron {
transform: rotate(180deg);
}
.asset-menu-panel {
position: absolute;
top: calc(100% + 0.5rem);
right: 0;
z-index: 150;
width: 19rem;
max-width: calc(100vw - 2rem);
max-height: min(28rem, calc(100dvh - 12rem));
overflow-y: auto;
padding: 0.375rem;
border: 1px solid var(--asset-action-border);
border-radius: 0.875rem;
background: var(--asset-action-surface);
box-shadow: 0 12px 36px rgb(15 23 42 / 0.12), 0 2px 6px rgb(15 23 42 / 0.04);
text-align: left;
}
.assets-page .asset-menu-label {
margin: 0;
padding: 0.625rem 0.75rem 0.375rem;
color: var(--asset-action-muted);
font-size: 0.6875rem;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.assets-page .asset-menu-item {
display: flex;
align-items: center;
gap: 0.75rem;
width: 100%;
min-height: 2.75rem;
padding: 0.625rem 0.75rem;
border: 0;
border-radius: 0.5rem;
background: transparent;
color: var(--asset-action-text);
font-size: 0.8125rem;
font-weight: 600;
line-height: 1.4;
text-align: left;
cursor: pointer;
}
.asset-menu-item small,
.asset-export-action small {
display: block;
margin-top: 0.1875rem;
color: var(--asset-action-muted);
font-size: 0.6875rem;
font-weight: 400;
line-height: 1.35;
}
.asset-menu-item:hover:not(:disabled) {
background: var(--asset-action-tint);
}
.asset-menu-item:disabled small {
color: inherit;
}
.assets-page .asset-menu-danger {
color: #c2413b;
}
.asset-menu-danger:hover:not(:disabled) {
background: #fff5f4;
}
.asset-menu-divider {
margin-top: 0.375rem !important;
padding-top: 0.375rem;
border-top: 1px solid var(--asset-action-border);
}
.asset-selection-toolbar {
position: relative;
z-index: 110;
display: flex;
align-items: center;
justify-content: space-between;
flex-shrink: 0;
gap: 1rem;
margin-bottom: 0.75rem;
padding: 0.75rem 0.875rem;
border: 1px solid var(--asset-action-border);
border-radius: 0.75rem;
background: var(--asset-action-surface);
transition: background-color 0.15s, border-color 0.15s;
}
.asset-selection-toolbar[data-has-selection="true"] {
border-color: #cdd6f6;
background: var(--asset-action-tint);
}
.asset-selection-info {
display: grid;
grid-template-columns: auto auto;
align-items: center;
justify-content: start;
gap: 0.3125rem 0.75rem;
min-width: 0;
}
.asset-selection-status {
display: flex;
align-items: center;
gap: 0.5rem;
color: var(--asset-action-text);
font-size: 0.8125rem;
font-weight: 600;
}
.asset-selection-count {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 1.625rem;
height: 1.625rem;
padding: 0 0.3125rem;
border-radius: 0.4375rem;
background: #f1f5f9;
color: #64748b;
font-variant-numeric: tabular-nums;
}
[data-has-selection="true"] .asset-selection-count {
background: #3755c3;
color: #fff;
}
.asset-selection-hint {
grid-column: 1 / -1;
grid-row: 2;
color: var(--asset-action-muted);
font-size: 0.6875rem;
line-height: 1.4;
}
.asset-selection-clear {
color: #3755c3;
font-size: 0.75rem;
text-underline-offset: 3px;
}
.asset-selection-clear:hover {
text-decoration: underline;
}
.assets-page .asset-export-action {
justify-content: flex-start;
min-height: 3rem;
text-align: left;
}
.assets-page .asset-action-proposal:not(:disabled) {
border-color: #c2cdf1;
color: #3755c3;
}
.assets-page .asset-export-action:disabled small {
color: #94a3b8;
}
@media (max-width: 1200px) {
.asset-selection-toolbar {
flex-wrap: wrap;
}
}
@media (max-width: 900px) {
.assets-page .asset-page-actions {
flex-wrap: wrap;
width: 100%;
gap: 0.5rem;
}
.assets-page .asset-page-actions > button,
.assets-page .asset-page-actions > details {
flex: 1 1 auto;
width: auto;
}
.assets-page .asset-page-actions > details > summary {
width: 100%;
}
.assets-page .asset-page-actions > .asset-action-primary {
flex: 1 0 100%;
order: -1;
}
.assets-page .asset-action-button {
min-height: 2.75rem;
}
.assets-page .asset-page-actions .asset-menu-panel {
right: 0;
}
.assets-page .asset-filter-bar {
grid-template-columns: minmax(7rem, 0.35fr) minmax(0, 1fr);
}
.assets-page .asset-filter-bar .compact-filter-search {
grid-column: auto;
grid-row: auto;
}
.asset-selection-toolbar {
align-items: stretch;
gap: 0.625rem;
padding: 0.75rem;
}
.asset-selection-info {
padding-right: 3rem;
}
.asset-selection-actions {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
width: 100%;
}
.assets-page .asset-export-action {
gap: 0.375rem;
padding: 0.625rem;
font-size: 0.75rem;
white-space: normal;
}
.asset-selection-menu {
position: absolute;
top: 0.75rem;
right: 0.75rem;
}
.assets-page .asset-selection-menu > summary {
min-width: 2.75rem;
padding: 0.5rem;
}
.asset-selection-menu > summary > span:last-child {
display: none;
}
}
.dark .assets-page {
--asset-action-surface: #172033;
--asset-action-text: #e2e8f0;
--asset-action-muted: #94a3b8;
--asset-action-border: #334155;
--asset-action-tint: #1e293b;
}

139
public/css/dashboard.css Normal file
View File

@@ -0,0 +1,139 @@
/* Overview of the existing management modules; all stock totals count catalog codes. */
.dashboard-page {
color: #263449;
background: #f7f9fc;
scrollbar-gutter: stable;
}
.dashboard-shell {
max-width: 1680px;
margin: 0 auto;
padding-bottom: 12px;
}
.dashboard-shell .dashboard-header {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 16px;
margin-bottom: 24px;
}
.dashboard-eyebrow { margin-bottom: 7px; font-size: 10px; font-weight: 800; letter-spacing: 0.12em; color: #62708a; }
.dashboard-header h1 { font-size: 25px; line-height: 1.3; font-weight: 800; letter-spacing: -0.035em; }
.dashboard-header p { margin-top: 6px; font-size: 12px; line-height: 1.6; color: #64748b; }
.dashboard-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; }
.dashboard-updated { font-size: 11px; color: #64748b; }
.dashboard-refresh { display: inline-flex; align-items: center; justify-content: center; gap: 6px; padding: 9px 13px; border: 1px solid #dce3ee; border-radius: 8px; background: white; font-size: 12px; font-weight: 700; box-shadow: 0 1px 2px #172a4610; }
.dashboard-refresh:hover { background: #eef2ff; border-color: #b9c7f4; }
.dashboard-refresh:disabled { opacity: 0.6; cursor: wait; }
.dashboard-refresh .material-symbols-outlined { font-size: 18px; }
.dashboard-warning { display: flex; align-items: flex-start; gap: 10px; margin-bottom: 18px; border: 1px solid #f4d59c; border-radius: 10px; padding: 12px 16px; background: #fffbeb; color: #92400e; font-size: 12px; line-height: 1.6; }
.dashboard-metrics { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; margin-bottom: 20px; }
.dashboard-metric { display: block; min-width: 0; padding: 19px 20px 16px; background: white; border: 1px solid #e3e9f1; border-radius: 12px; box-shadow: 0 2px 4px #172a4603; transition: border-color 0.15s, box-shadow 0.15s; }
.dashboard-metric:hover { border-color: #b8c6e8; box-shadow: 0 4px 14px #263f7110; }
.dashboard-metric-top { display: flex; align-items: center; gap: 10px; font-size: 12px; font-weight: 700; color: #536176; }
.dashboard-metric-top > .material-symbols-outlined { margin-left: auto; font-size: 16px; color: #94a3b8; }
.dashboard-icon { width: 36px; height: 36px; display: inline-flex; align-items: center; justify-content: center; flex: 0 0 auto; border-radius: 10px; color: var(--dashboard-accent, #3755c3); background: var(--dashboard-soft, #edf1ff); }
.dashboard-icon .material-symbols-outlined { font-size: 20px; }
.dashboard-tone-blue { --dashboard-accent: #3755c3; --dashboard-soft: #edf1ff; }
.dashboard-tone-green { --dashboard-accent: #087f69; --dashboard-soft: #e8f7f0; }
.dashboard-tone-purple { --dashboard-accent: #7c51c5; --dashboard-soft: #f2edfb; }
.dashboard-tone-amber { --dashboard-accent: #a66313; --dashboard-soft: #fff5e2; }
.dashboard-tone-rose { --dashboard-accent: #be4658; --dashboard-soft: #fff0f2; }
.dashboard-metric-value { display: flex; align-items: baseline; flex-wrap: wrap; column-gap: 8px; margin-top: 16px; font-size: 32px; font-weight: 800; line-height: 1.2; letter-spacing: -0.04em; }
.dashboard-metric-value > span { color: #718096; font-size: 11px; font-weight: 500; letter-spacing: 0; }
.dashboard-metric > p { margin-top: 10px; padding-top: 12px; border-top: 1px solid #f0f3f8; color: #64748b; font-size: 11px; line-height: 1.6; }
.dashboard-layout { display: grid; grid-template-columns: minmax(0, 1.85fr) minmax(300px, 1fr); align-items: start; gap: 20px; }
.dashboard-main-column, .dashboard-side-column { display: grid; min-width: 0; gap: 20px; }
.dashboard-stock-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; }
.dashboard-panel { min-width: 0; padding: 20px; background: white; border: 1px solid #e3e9f1; border-radius: 12px; }
.dashboard-panel-heading { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; }
.dashboard-panel-heading h2 { display: inline-flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 800; }
.dashboard-panel-heading h2 .material-symbols-outlined { font-size: 18px; color: #6a7eaa; }
.dashboard-panel-heading > a { display: inline-flex; align-items: center; gap: 4px; color: #3755c3; font-size: 11px; font-weight: 700; }
.dashboard-panel-heading > a .material-symbols-outlined { font-size: 15px; }
.dashboard-panel-note { color: #7a8799; font-size: 10px; line-height: 1.6; }
p.dashboard-panel-note { margin-top: 6px; }
.dashboard-stock-row { margin-top: 20px; }
.dashboard-stock-row > div:first-child { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 9px; font-size: 11px; }
.dashboard-stock-row > div:first-child > span { display: inline-flex; align-items: center; gap: 7px; color: #5f6e82; }
.dashboard-stock-row strong { font-size: 13px; white-space: nowrap; }
.dashboard-stock-row small { font-size: 10px; font-weight: 400; color: #7a8799; }
.dashboard-dot { display: inline-block; flex-shrink: 0; width: 7px; height: 7px; border-radius: 50%; }
.dashboard-track { height: 6px; overflow: hidden; background: #f0f3f8; border-radius: 4px; }
.dashboard-track > span { display: block; height: 100%; border-radius: inherit; }
.dashboard-fill-blue { background: #5a79d5; }
.dashboard-fill-purple { background: #a285d5; }
.dashboard-fill-green { background: #43a78d; }
.dashboard-fill-amber { background: #e4b05f; }
.dashboard-fill-rose { background: #dd8190; }
.dashboard-inline-link { display: flex; align-items: center; gap: 6px; margin-top: 19px; color: #3755c3; font-size: 11px; font-weight: 600; }
.dashboard-inline-link .material-symbols-outlined { font-size: 17px; }
.dashboard-inline-link > .material-symbols-outlined:last-child { margin-left: auto; }
.dashboard-empty { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; min-height: 140px; padding: 20px 8px; text-align: center; color: #7a8799; font-size: 12px; line-height: 1.7; }
.dashboard-empty > .material-symbols-outlined { font-size: 28px; color: #c3cddd; }
.dashboard-recent-list { margin-top: 12px; }
.dashboard-recent-row { display: grid; grid-template-columns: 36px minmax(0, 1fr) auto auto 14px; align-items: center; gap: 12px; padding: 12px 0; border-bottom: 1px solid #f0f3f8; }
.dashboard-recent-row:last-child { border-bottom: 0; padding-bottom: 0; }
.dashboard-recent-name { min-width: 0; }
.dashboard-recent-name strong, .dashboard-robot-row strong { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; font-weight: 600; }
.dashboard-recent-name small, .dashboard-robot-row small { display: block; margin-top: 4px; color: #7a8799; font-size: 10px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.dashboard-recent-row time { color: #7a8799; font-size: 10px; white-space: nowrap; }
.dashboard-recent-row > .material-symbols-outlined, .dashboard-robot-row > .material-symbols-outlined { color: #a5b0c1; font-size: 16px; }
.dashboard-tag { display: inline-flex; align-items: center; justify-content: center; padding: 4px 7px; border-radius: 5px; font-size: 10px; font-weight: 600; color: var(--dashboard-accent); background: var(--dashboard-soft); white-space: nowrap; }
.dashboard-attention-row { display: flex; align-items: center; gap: 10px; width: 100%; margin-top: 14px; text-align: left; }
.dashboard-attention-row > span:nth-child(2) { min-width: 0; flex: 1; }
.dashboard-attention-row strong { display: block; font-size: 11px; font-weight: 600; line-height: 1.5; }
.dashboard-attention-row small { display: block; margin-top: 3px; color: #7a8799; font-size: 10px; line-height: 1.5; }
.dashboard-attention-row > b { font-size: 16px; color: #a66313; }
.dashboard-attention-row > .material-symbols-outlined { font-size: 15px; color: #a5b0c1; }
.dashboard-shortage-list { display: grid; gap: 10px; margin: 14px 0 0 46px; padding-left: 12px; border-left: 2px solid #f0f3f8; }
.dashboard-shortage-list a { display: flex; justify-content: space-between; gap: 12px; min-width: 0; font-size: 11px; }
.dashboard-shortage-list a > span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #64748b; }
.dashboard-shortage-list small { flex-shrink: 0; font-size: 10px; color: #be4658; }
.dashboard-shortage-list .dashboard-inline-link { margin-top: 0; }
.dashboard-robot-row { display: flex; align-items: center; gap: 12px; margin-top: 16px; }
.dashboard-robot-row > div:first-child { height: 54px; width: 54px; border-radius: 9px; }
.dashboard-robot-row > span:nth-child(2) { flex: 1; min-width: 0; }
.dashboard-resources { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
.dashboard-resource { display: flex; align-items: center; gap: 10px; min-width: 0; padding: 14px 16px; background: white; border: 1px solid #e3e9f1; border-radius: 10px; font-size: 12px; color: #64748b; }
.dashboard-resource > .material-symbols-outlined { font-size: 19px; color: #8997b2; }
.dashboard-resource strong { margin-left: auto; font-size: 16px; color: #334155; }
.dashboard-resource > .material-symbols-outlined:last-child { font-size: 14px; }
.dashboard-shell a:hover strong, .dashboard-attention-row:hover strong { color: #3755c3; }
.dashboard-shell :is(a, button):focus-visible { outline: 2px solid #3755c3; outline-offset: 4px; border-radius: 6px; }
@media (max-width: 1200px) {
.dashboard-layout { grid-template-columns: minmax(0, 1fr); }
.dashboard-side-column { grid-template-columns: repeat(2, minmax(0, 1fr)); align-items: start; }
.dashboard-metric { padding: 16px; }
.dashboard-metric-top { gap: 7px; font-size: 11px; }
}
@media (max-width: 600px) {
.dashboard-shell .dashboard-header { align-items: flex-start; gap: 12px; margin-bottom: 18px; }
.dashboard-actions { width: 100%; justify-content: space-between; gap: 8px; }
.dashboard-updated { font-size: 10px; }
.dashboard-refresh { min-height: 40px; }
.dashboard-metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; margin-bottom: 14px; }
.dashboard-metric { padding: 12px; }
.dashboard-metric-top { flex-wrap: wrap; gap: 7px; font-size: 11px; }
.dashboard-metric-top > .material-symbols-outlined { display: none; }
.dashboard-metric .dashboard-icon { height: 28px; width: 28px; border-radius: 8px; }
.dashboard-metric .dashboard-icon .material-symbols-outlined { font-size: 17px; }
.dashboard-metric-value { font-size: 28px; margin-top: 12px; gap: 5px; }
.dashboard-metric-value > span { font-size: 10px; }
.dashboard-metric > p { min-height: 39px; margin-top: 9px; padding-top: 9px; font-size: 10px; }
.dashboard-stock-grid, .dashboard-side-column { grid-template-columns: minmax(0, 1fr); gap: 14px; }
.dashboard-layout, .dashboard-main-column { gap: 14px; }
.dashboard-panel { padding: 16px; }
.dashboard-recent-row { grid-template-columns: 32px minmax(0, 1fr) auto; gap: 8px; }
.dashboard-recent-row > .dashboard-icon { width: 32px; height: 32px; grid-row: span 2; }
.dashboard-recent-row time { grid-column: 2 / 4; }
.dashboard-recent-row > .material-symbols-outlined { display: none; }
.dashboard-resource { padding: 12px; gap: 7px; font-size: 11px; }
.dashboard-resource > .material-symbols-outlined:last-child { display: none; }
.dashboard-resources { gap: 10px; }
}

File diff suppressed because one or more lines are too long

View File

@@ -153,57 +153,39 @@ textarea {
z-index: 0;
}
/* Keep saved export files and both actions visible beside wide history rows. */
#assetExportHistoryModal .asset-export-history-dialog {
width: min(1600px, calc(100vw - 2rem));
max-width: none;
max-height: calc(100dvh - 2rem);
}
.asset-export-history-scroll {
max-height: calc(100dvh - 10rem);
overflow: auto;
overscroll-behavior: contain;
scrollbar-width: thin;
}
.asset-export-history-table {
min-width: 1280px;
table-layout: fixed;
/* Keep project export decisions and saved files accessible in wide tables. */
.asset-exports-page table {
border-collapse: separate;
border-spacing: 0;
}
.asset-export-history-table th,
.asset-export-history-table td {
border-bottom: 1px solid #f1f5f9;
.asset-exports-page th,
.asset-exports-page td {
overflow-wrap: anywhere;
}
.asset-export-history-table thead th {
position: sticky;
top: 0;
z-index: 2;
background: #f8fafc;
overflow-wrap: normal;
}
@media (min-width: 901px) {
.asset-exports-page thead th {
position: sticky;
top: 0;
z-index: 2;
background: #f8fafc;
}
.asset-export-history-table .asset-export-history-document {
position: sticky;
right: 0;
z-index: 1;
background: #fff;
border-left: 1px solid #e2e8f0;
box-shadow: -6px 0 12px -10px rgb(15 23 42 / 0.3);
}
.asset-exports-page tbody td:last-child {
position: sticky;
right: 0;
z-index: 1;
min-width: 190px;
background: #fff;
border-left: 1px solid #e2e8f0;
box-shadow: -6px 0 12px -10px rgb(15 23 42 / 0.3);
}
.asset-export-history-table thead .asset-export-history-document {
z-index: 3;
background: #f8fafc;
}
.asset-export-history-table tr:hover .asset-export-history-document {
background: #f8fafc;
.asset-exports-page thead th:last-child {
right: 0;
z-index: 3;
}
}
.asset-export-history-file-actions {

229
public/css/robot-bom.css Normal file
View File

@@ -0,0 +1,229 @@
.bom-page { height:100%; overflow-y:auto; padding:24px; color:#2a3439; background:#f7f9fb; font-size:14px; }
.bom-page h1,.bom-page h2,.bom-page h3,.bom-dialog h2,.bom-dialog h3 { font-family:Manrope,Inter,sans-serif; margin:0; font-weight:800; }
.bom-page h1 { font-size:28px; line-height:1.25; margin-bottom:6px; }
.bom-page h2,.bom-dialog h3 { font-size:17px; }
.bom-page-header { display:flex; align-items:center; justify-content:space-between; gap:20px; margin-bottom:22px; flex-wrap:wrap; }
.bom-eyebrow { font-size:10px; letter-spacing:.1em; font-weight:700; color:#64748b; margin:0 0 5px; }
.bom-muted { color:#64748b; font-size:13px; }
.bom-toolbar,.bom-identity-actions { display:flex; flex-wrap:wrap; gap:8px; }
.bom-btn { display:inline-flex; align-items:center; justify-content:center; gap:6px; border:1px solid #d5deea; border-radius:7px; background:white; color:#334155; padding:9px 12px; font-size:12px; font-weight:700; line-height:1.4; white-space:nowrap; cursor:pointer; }
.bom-btn:hover:not(:disabled) { background:#edf2ff; border-color:#a9b8e9; color:#3755c3; }
.bom-btn:disabled { opacity:.45; cursor:default; }
.bom-btn-primary { color:white; background:#3755c3; border-color:#3755c3; }
.bom-btn-primary:hover:not(:disabled) { color:white; background:#2848b7; }
.bom-btn .material-symbols-outlined { font-size:18px; }
.bom-identity { display:flex; align-items:center; gap:18px; flex-wrap:wrap; padding:18px; background:white; border:1px solid #e2e8f0; border-radius:10px; }
.bom-robot-icon { display:flex; align-items:center; justify-content:center; width:64px; height:64px; border-radius:12px; background:#edf2ff; color:#3755c3; font-size:36px; flex-shrink:0; }
.bom-model-field { flex:1; min-width:180px; }
.bom-model-field label,.bom-version-field label { display:block; color:#64748b; font-size:11px; font-weight:600; margin-bottom:5px; }
.bom-model-field select { width:100%; max-width:360px; font-weight:700; }
.bom-model-field small { display:block; margin-top:5px; color:#64748b; font-size:11px; }
.bom-version-field { min-width:170px; }
.bom-page select,.bom-page input:not([type=file]),.bom-dialog select,.bom-dialog input:not([type=radio]),.bom-dialog textarea { border:1px solid #d7e0eb; border-radius:6px; background:white; font-size:13px; color:#334155; padding:9px 11px; min-height:38px; }
.bom-page input:focus,.bom-page select:focus,.bom-dialog input:focus,.bom-dialog textarea:focus { outline:2px solid #b9c7ff; outline-offset:1px; border-color:#3755c3; }
.bom-badge { display:inline-flex; align-items:center; white-space:nowrap; color:#b45309; background:#fffbeb; border:1px solid #fde68a; border-radius:5px; padding:5px 8px; font-size:11px; font-weight:700; }
.bom-badge-green { color:#15803d; background:#f0fdf4; border-color:#bbf7d0; }
.bom-tabs { display:flex; gap:16px; margin:15px 0 18px; border-bottom:1px solid #e2e8f0; overflow-x:auto; }
.bom-tabs button { padding:13px 8px; color:#64748b; font-size:13px; font-weight:600; white-space:nowrap; border-bottom:2px solid transparent; }
.bom-tabs button[aria-current=page] { color:#3755c3; border-bottom-color:#3755c3; }
.bom-workspace { display:grid; grid-template-columns:minmax(0,1fr) 335px; gap:16px; align-items:start; }
.bom-card { background:white; border:1px solid #e2e8f0; border-radius:9px; min-width:0; overflow:hidden; }
.bom-main-card { padding:18px; }
.bom-card-heading { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:18px; }
.bom-main-card>.bom-card-heading { padding:0 0 14px; }
.bom-count { display:inline-block; font-size:11px; font-weight:500; color:#64748b; background:#f1f5f9; padding:3px 6px; border-radius:5px; vertical-align:middle; }
.bom-filters { display:flex; gap:10px; margin-bottom:14px; }
.bom-search { display:flex; align-items:center; position:relative; flex:1; min-width:100px; }
.bom-search>.material-symbols-outlined { position:absolute; left:11px; color:#94a3b8; font-size:19px; pointer-events:none; }
.bom-search input { width:100%; padding-left:36px!important; }
.bom-filters select { max-width:190px; }
.bom-table-scroll { overflow-x:auto; width:100%; }
.bom-lines-table,.bom-stock-table,.bom-picker-table { width:100%; border-collapse:collapse; font-size:12px; text-align:left; }
.bom-lines-table th,.bom-stock-table th,.bom-picker-table th { font-weight:600; background:#f1f5f9; color:#475569; padding:11px 10px; white-space:nowrap; border:1px solid #e2e8f0; }
.bom-lines-table td,.bom-stock-table td,.bom-picker-table td { padding:12px 10px; border:1px solid #e2e8f0; vertical-align:middle; }
.bom-lines-table strong,.bom-stock-table strong,.bom-picker-table strong { display:block; font-weight:600; }
.bom-lines-table small,.bom-stock-table small,.bom-picker-table small,.bom-selected-summary small { display:block; color:#64748b; font-size:10px; margin-top:3px; line-height:1.45; }
.bom-lines-table td:first-child { min-width:155px; }
.bom-lines-table td:nth-child(2) { min-width:95px; }
.bom-lines-table td:nth-child(5) { min-width:140px; max-width:230px; overflow-wrap:anywhere; }
.bom-group th { background:#eef3f8; font-size:11px; text-transform:uppercase; color:#334155; padding:10px; }
.bom-group .material-symbols-outlined { font-size:17px; margin-right:7px; vertical-align:middle; }
.bom-group small { display:inline; margin-left:10px; font-weight:400; font-size:10px; text-transform:none; color:#64748b; }
.bom-page input.bom-quantity { width:76px; min-height:32px; padding:5px 6px; }
.bom-row-actions { white-space:nowrap; }
.bom-row-actions button { padding:4px; color:#64748b; }
.bom-row-actions button:hover { color:#3755c3; background:#eff6ff; border-radius:4px; }
.bom-row-actions button[data-bom-delete]:hover { color:#dc2626; background:#fef2f2; }
.bom-row-actions .material-symbols-outlined { font-size:17px; }
.bom-stock-card { padding:18px; }
.bom-stock-card>.bom-card-heading { padding:0 0 18px; }
.bom-count-field { display:flex; align-items:center; justify-content:space-between; gap:12px; font-size:12px; }
.bom-count-field input { width:100px; }
.bom-footnote { color:#64748b; font-size:11px; margin:14px 0; line-height:1.6; }
.bom-stock-card>.bom-btn { margin-bottom:14px; }
.bom-stock-table { font-size:11px; }
.bom-stock-table th,.bom-stock-table td { padding:9px 7px; }
.bom-stock-table td:not(:first-child),.bom-stock-table th:not(:first-child) { text-align:right; }
.bom-stock-table td:first-child { max-width:180px; overflow-wrap:anywhere; }
.bom-shortage td { background:#fff7ed; }
.bom-danger { color:#c2410c!important; }
.bom-success { color:#15803d; font-weight:600; }
.bom-stock-result { display:flex; align-items:center; gap:9px; padding:12px; border-radius:7px; margin-top:16px; font-size:12px; }
.bom-stock-result small { display:block; margin-top:3px; font-size:11px; }
.bom-stock-warning { background:#fff7ed; border:1px solid #fed7aa; color:#c2410c; }
.bom-stock-ok { background:#f0fdf4; border:1px solid #bbf7d0; color:#15803d; }
.bom-stock-message { padding:20px 0; }
.bom-empty { display:flex; flex-direction:column; align-items:center; justify-content:center; text-align:center; padding:52px 20px; gap:12px; color:#64748b; }
.bom-empty>.material-symbols-outlined { font-size:36px; color:#94a3b8; }
.bom-empty>strong { color:#334155; font-size:16px; }
.bom-empty p { font-size:13px; margin:0; }
.bom-empty a { color:#3755c3; }
.bom-identity+.bom-empty { margin-top:18px; }
.bom-alert { border:1px solid #fecaca; color:#b91c1c; background:#fef2f2; border-radius:7px; padding:12px; font-size:13px; margin-bottom:16px; }
.bom-sr { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip:rect(0,0,0,0); white-space:nowrap; border:0; }
.bom-dialog { margin:auto; width:min(1120px,95vw); max-width:none; max-height:92dvh; overflow-y:auto; border:0; border-radius:10px; padding:0; background:white; color:#2a3439; box-shadow:0 24px 80px #0f172a33; }
.bom-dialog::backdrop { background:#0f172a66; }
.bom-dialog-header { display:flex; justify-content:space-between; align-items:flex-start; gap:16px; padding:20px; border-bottom:1px solid #e2e8f0; }
.bom-dialog-header h2 { font-size:20px; }
.bom-dialog-header p { font-size:12px; color:#64748b; margin:5px 0 0; }
.bom-dialog-header>button { padding:3px; color:#64748b; }
.bom-picker-layout { display:grid; grid-template-columns:minmax(0,1.8fr) minmax(280px,1fr); }
.bom-picker-catalog { padding:20px; min-width:0; }
.bom-picker-tools { display:flex; gap:14px; flex-wrap:wrap; }
.bom-source-tabs { display:flex; gap:5px; }
.bom-source-tabs button { padding:9px 12px; border:1px solid #e2e8f0; border-radius:6px; background:white; font-size:12px; font-weight:600; }
.bom-source-tabs button[aria-pressed=true] { background:#3755c3; border-color:#3755c3; color:white; }
.bom-picker-table-wrap { max-height:410px; overflow:auto; }
.bom-picker-table th { position:sticky; top:0; z-index:1; }
.bom-picker-table td { padding:12px 8px; }
.bom-picker-table td:first-child { width:35px; }
.bom-picker-table td:nth-child(2) { min-width:130px; }
.bom-picker-table label { cursor:pointer; }
.bom-picked-row td { background:#edf3ff; }
.bom-picker-pagination { display:flex; align-items:center; justify-content:space-between; gap:10px; color:#64748b; font-size:11px; margin-top:16px; }
.bom-picker-pagination>div { display:flex; gap:5px; }
.bom-picker-settings { border-left:1px solid #e2e8f0; padding:20px; }
.bom-picker-settings>label { display:block; font-size:12px; font-weight:600; margin-top:15px; }
.bom-picker-settings label>input,.bom-picker-settings label>textarea { display:block; width:100%; margin-top:6px; font-weight:400; }
.bom-selected-summary { padding:12px; background:#f1f5f9; border-radius:7px; font-size:13px; margin-top:12px; }
.bom-quantity-unit { display:flex; margin-top:6px; }
.bom-quantity-unit input { width:100%; min-width:0; border-radius:6px 0 0 6px!important; font-weight:400; }
.bom-quantity-unit>span { display:flex; align-items:center; padding:0 12px; background:#f1f5f9; border:1px solid #d7e0eb; border-left:0; border-radius:0 6px 6px 0; font-size:12px; }
.bom-info { display:flex; gap:9px; background:#eff6ff; border-radius:7px; padding:12px; margin-top:20px; font-size:11px; color:#3755c3; }
.bom-info p { color:#64748b; margin:4px 0 0; font-size:11px; }
.bom-dialog-footer { display:flex; align-items:center; justify-content:space-between; gap:14px; padding:18px 20px; border-top:1px solid #e2e8f0; background:#fdfefe; }
.bom-dialog-footer>div { display:flex; flex-wrap:wrap; gap:8px; }
@media(min-width:1700px) { .bom-workspace { grid-template-columns:minmax(0,1fr) 390px; } }
@media(max-width:1250px) { .bom-workspace { grid-template-columns:minmax(0,1fr); } .bom-stock-card { max-width:none; } .bom-identity-actions { width:100%; } }
@media(max-width:760px) { .bom-page { padding:16px; } .bom-page h1 { font-size:24px; } .bom-identity { gap:12px; padding:14px; } .bom-robot-icon { width:45px; height:45px; font-size:28px; } .bom-version-field { min-width:150px; flex:1; } .bom-filters { flex-wrap:wrap; } .bom-filters select { width:100%; max-width:none; } .bom-main-card,.bom-stock-card { padding:14px; } .bom-card-heading h2 { font-size:15px; } .bom-picker-layout { grid-template-columns:minmax(0,1fr); } .bom-picker-settings { border-left:0; border-top:1px solid #e2e8f0; } .bom-picker-table-wrap { max-height:260px; } .bom-picker-pagination { flex-wrap:wrap; } .bom-dialog-footer { flex-wrap:wrap; } .bom-dialog-footer>div { width:100%; justify-content:flex-end; } .bom-tabs { gap:8px; } .bom-tabs button { font-size:12px; } .bom-picker-tools>.bom-search { min-width:100%; } }
.bom-lines-table td:first-child { min-width:0; width:48px; color:#64748b; }
.bom-lines-table td:nth-child(2) { min-width:180px; }
.bom-lines-table td:nth-child(3) { min-width:110px; }
.bom-lines-table td:nth-child(5) { min-width:180px; max-width:300px; }
.bom-lines-table .bom-quantity-unit { margin:0; align-items:center; gap:7px; }
.bom-lines-table .bom-quantity-unit input { width:76px; border-radius:6px!important; }
.bom-lines-table .bom-quantity-unit small { margin:0; white-space:nowrap; }
.bom-notes,.bom-source-cell { overflow-wrap:anywhere; white-space:pre-wrap; }
.bom-source-link { color:#3755c3; text-decoration:underline; text-underline-offset:3px; }
.bom-source-link:hover { color:#2848b7; }
.bom-history-table { width:100%; border-collapse:collapse; font-size:12px; text-align:left; }
.bom-history-table th,.bom-history-table td { border:1px solid #e2e8f0; padding:12px 10px; white-space:nowrap; }
.bom-history-table th { background:#f1f5f9; color:#475569; font-weight:600; }
.bom-dialog { width:min(620px,95vw); }
.bom-entry-tabs { display:flex; flex-wrap:wrap; gap:8px; padding:16px 20px; border-bottom:1px solid #e2e8f0; }
.bom-entry-tabs button { border:1px solid #e2e8f0; padding:9px 12px; border-radius:6px; font-size:12px; font-weight:600; }
.bom-entry-tabs button[aria-pressed=true] { background:#3755c3; color:white; border-color:#3755c3; }
.bom-material-layout { display:grid; grid-template-columns:minmax(0,1fr); }
.bom-asset-picker { padding:20px; border-right:1px solid #e2e8f0; min-width:0; }
.bom-asset-picker[hidden] { display:none; }
.bom-asset-table-wrap { max-height:410px; overflow:auto; }
.bom-asset-table { width:100%; border-collapse:collapse; font-size:12px; text-align:left; }
.bom-asset-table th,.bom-asset-table td { border:1px solid #e2e8f0; padding:11px 9px; }
.bom-asset-table th { background:#f1f5f9; position:sticky; top:0; color:#475569; font-weight:600; }
.bom-asset-table tbody tr { cursor:pointer; }
.bom-asset-table tbody tr:hover { background:#f7f9fb; }
.bom-asset-table strong,.bom-asset-table small { display:block; }
.bom-asset-table small { font-size:10px; color:#64748b; margin-top:4px; }
.bom-material-fields { padding:20px; min-width:0; }
.bom-material-fields label { display:block; font-size:12px; font-weight:600; margin-bottom:16px; }
.bom-material-fields label:last-child { margin-bottom:0; }
.bom-material-fields label>input,.bom-material-fields label>textarea { display:block; width:100%; margin-top:6px; font-weight:400; }
.bom-form-grid { display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1fr); gap:16px; }
.bom-optional { font-size:11px; color:#94a3b8; font-weight:400; }
.bom-dialog-footer { justify-content:flex-end; }
/* Both entry modes share one fixed frame and the same form column. */
.bom-entry-dialog { width:min(1100px,95vw); height:min(790px,calc(100dvh - 48px)); max-height:calc(100dvh - 48px); overflow:hidden; }
.bom-entry-dialog[open] { display:flex; }
.bom-entry-dialog>form { display:flex; flex-direction:column; width:100%; height:100%; min-height:0; }
.bom-entry-dialog .bom-dialog-header,.bom-entry-dialog .bom-entry-tabs,.bom-entry-dialog .bom-dialog-footer { flex-shrink:0; }
.bom-entry-dialog .bom-material-layout { flex:1; min-height:0; grid-template-columns:minmax(0,1fr) minmax(360px,1.1fr); overflow:hidden; }
.bom-entry-context { min-width:0; min-height:0; display:grid; grid-template-columns:minmax(0,1fr); border-right:1px solid #e2e8f0; background:#f8fafc; }
.bom-entry-dialog .bom-asset-picker { display:flex; flex-direction:column; min-height:0; border:0; }
.bom-entry-dialog .bom-asset-picker[hidden],.bom-external-guide[hidden] { display:none; }
.bom-entry-dialog .bom-asset-picker>.bom-search { flex:0 0 auto; }
.bom-entry-dialog #bomAssetResults { display:flex; flex:1; flex-direction:column; min-height:0; }
.bom-entry-dialog #bomAssetResults>.bom-footnote { flex-shrink:0; margin-bottom:0; }
.bom-entry-dialog .bom-asset-table-wrap { flex:1; min-height:0; max-height:none; scrollbar-gutter:stable; }
.bom-entry-dialog .bom-material-fields { min-height:0; overflow-y:auto; overscroll-behavior:contain; scrollbar-gutter:stable; padding:22px 24px; }
.bom-entry-dialog .bom-material-fields textarea { min-height:66px; max-height:150px; }
.bom-entry-dialog .bom-dialog-footer { justify-content:space-between; }
.bom-entry-save-hint { max-width:360px; font-size:11px; line-height:1.6; color:#64748b; margin:0; }
.bom-external-guide { padding:28px; overflow-y:auto; scrollbar-gutter:stable; }
.bom-external-icon { display:flex; align-items:center; justify-content:center; width:52px; height:52px; border-radius:12px; color:#3755c3; background:#e8edff; font-size:28px; margin-bottom:18px; }
.bom-external-guide h3 { font-size:19px; margin-bottom:9px; }
.bom-external-guide>p { font-size:13px; line-height:1.7; color:#64748b; margin:0; }
.bom-external-guide ul { display:flex; flex-direction:column; gap:22px; list-style:none; padding:0; margin:28px 0; }
.bom-external-guide li { display:flex; gap:12px; font-size:13px; }
.bom-external-guide li>.material-symbols-outlined { color:#3755c3; font-size:20px; margin-top:1px; }
.bom-external-guide li strong { font-weight:600; }
.bom-external-guide li small { display:block; color:#64748b; margin-top:5px; font-size:12px; line-height:1.6; }
.bom-external-guide p.bom-external-note { border-top:1px solid #e2e8f0; padding-top:18px; font-size:11px; }
.bom-confirm-dialog { width:min(520px,95vw); }
.bom-confirm-heading { display:flex; align-items:center; gap:13px; }
.bom-confirm-heading .bom-eyebrow { margin-bottom:4px; }
.bom-confirm-icon { display:flex; align-items:center; justify-content:center; flex-shrink:0; width:44px; height:44px; border-radius:12px; background:#e8edff; color:#3755c3; font-size:25px; }
.bom-confirm-body { padding:20px 24px 24px; }
.bom-confirm-body>p { font-size:13px; line-height:1.7; color:#64748b; margin:0 0 18px; }
.bom-publish-summary { display:grid; grid-template-columns:2fr 1fr 1.3fr; gap:16px; background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; padding:16px; margin:0 0 18px; }
.bom-publish-summary div { min-width:0; }
.bom-publish-summary dt { color:#64748b; font-size:11px; margin-bottom:6px; }
.bom-publish-summary dd { margin:0; font-size:13px; font-weight:700; overflow-wrap:anywhere; }
.bom-publish-note { display:flex; gap:9px; color:#3755c3; border-radius:7px; background:#eff3ff; padding:12px; }
.bom-publish-note>.material-symbols-outlined { font-size:18px; flex-shrink:0; margin-top:1px; }
.bom-publish-note p { font-size:12px; line-height:1.7; margin:0; }
.bom-confirm-body>p.bom-footnote { margin:14px 0 0; font-size:11px; }
.bom-btn:focus-visible { outline:2px solid #3755c3; outline-offset:3px; }
.robot-delete-dialog .bom-confirm-icon,.bom-delete-dialog .bom-confirm-icon { color:#dc2626; background:#fef2f2; }
.bom-btn.bom-btn-delete { color:#dc2626; border-color:#fecaca; }
.bom-btn.bom-btn-delete:hover:not(:disabled) { color:#b91c1c; background:#fef2f2; border-color:#fca5a5; }
.robot-delete-card { background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; padding:16px; margin:0 0 18px; }
.robot-delete-name { display:block; font-size:16px; font-weight:700; overflow-wrap:anywhere; }
.robot-delete-details { display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1fr); gap:16px; margin:16px 0 0; }
.robot-delete-details dt { color:#64748b; font-size:11px; margin-bottom:5px; }
.robot-delete-details dd { margin:0; font-size:13px; font-weight:600; overflow-wrap:anywhere; }
.bom-btn.bom-btn-danger { color:white; background:#dc2626; border-color:#dc2626; }
.bom-btn.bom-btn-danger:hover:not(:disabled) { color:white; background:#b91c1c; border-color:#b91c1c; }
.bom-btn.bom-btn-danger:focus-visible { outline-color:#dc2626; }
@media(max-width:760px) {
.bom-entry-dialog { width:calc(100vw - 24px); height:calc(100dvh - 32px); max-height:calc(100dvh - 32px); }
.bom-entry-dialog .bom-material-layout { display:flex; flex-direction:column; overflow-y:auto; overscroll-behavior:contain; }
.bom-entry-context { flex:0 0 200px; height:200px; border-right:0; border-bottom:1px solid #e2e8f0; }
.bom-entry-dialog .bom-material-fields { flex-shrink:0; overflow:visible; padding:16px; }
.bom-entry-dialog .bom-asset-picker { padding:14px 16px; overflow:hidden; }
.bom-entry-dialog .bom-asset-picker>.bom-footnote { margin:8px 0; font-size:10px; }
.bom-entry-tabs { padding:12px 16px; }
.bom-entry-tabs button { padding:9px 10px; font-size:11px; }
.bom-external-guide { padding:18px; }
.bom-external-icon { width:36px; height:36px; font-size:22px; margin-bottom:12px; }
.bom-external-guide h3 { font-size:17px; }
.bom-external-guide>p { font-size:12px; }
.bom-external-guide ul,.bom-external-guide .bom-external-note { display:none; }
.bom-entry-save-hint { max-width:none; font-size:10px; }
.bom-entry-dialog .bom-dialog-footer { gap:10px; padding:12px 16px; }
.bom-entry-dialog .bom-dialog-footer>div { width:100%; justify-content:flex-end; gap:6px; }
.bom-entry-dialog .bom-dialog-footer .bom-btn { padding:8px 10px; font-size:11px; }
.bom-confirm-body { padding:18px; }
.bom-publish-summary { gap:10px; padding:12px; }
.bom-confirm-dialog .bom-dialog-header { padding:18px; }
.bom-confirm-dialog .bom-dialog-header h2 { font-size:17px; }
}

File diff suppressed because it is too large Load Diff

288
public/js/robot-bom.js Normal file
View File

@@ -0,0 +1,288 @@
/* Descriptive robot BOM: asset names/models may be copied; BOM quantities are entered independently. */
(() => {
'use strict';
const modelKey = item => JSON.stringify([Number(item.TypeId), item.Model]);
const number = value => Number(value || 0).toLocaleString('vi-VN', { maximumFractionDigits: 4 });
const fractionalUnit = unit => !String(unit).trim() || /^(m|m2|m²|m3|m³|mét|met|kg|g|gam|l|lít|lit|ml|mm|cm|tấn|tan)$/i.test(String(unit).trim());
class RobotBomController {
constructor(app) {
this.app = app; this.models = []; this.revisions = []; this.lines = [];
this.header = null; this.modelId = ''; this.dirty = false; this.busy = false;
this.query = ''; this.tab = 'bom';
this.beforeUnload = event => { if (this.dirty) { event.preventDefault(); event.returnValue = ''; } };
}
escape(value) { return this.app.escapeHtml(String(value ?? '')); }
canManage() { return this.app.canCurrentUserManageAssets(); }
editable() { return this.canManage() && this.header?.Status === 'draft'; }
active() { return this.app.currentPage === 'robot-bom'; }
async api(suffix, options = {}) {
const response = await fetch(`${this.app.apiBase}/robot-boms${suffix}`, { cache: 'no-store', ...options,
headers: { ...(options.body ? { 'Content-Type': 'application/json' } : {}), ...options.headers } });
const result = await response.json();
if (!response.ok || !result.success) throw new Error(result.message || 'Không thể tải dữ liệu BOM');
return result.data;
}
async mount(root, preferredModel) {
this.root = root; this.busy = true; this.error = ''; this.dirty = false;
window.addEventListener('beforeunload', this.beforeUnload); this.render();
try {
this.models = await this.api('/models');
const selected = this.models.find(item => preferredModel && typeof preferredModel === 'object'
? item.Model === preferredModel.Model && item.TypeId === preferredModel.TypeId : item.Model === preferredModel)
|| this.models.find(item => modelKey(item) === this.modelId) || this.models[0];
this.modelId = selected ? modelKey(selected) : ''; await this.loadModel();
} catch (error) { this.error = error.message; }
finally { this.busy = false; this.render(); }
}
unmount() {
window.removeEventListener('beforeunload', this.beforeUnload);
document.getElementById('bomComponentDialog')?.close();
document.getElementById('bomPublishDialog')?.close();
document.getElementById('bomDeleteDialog')?.close();
}
selectedModel() { return this.models.find(item => modelKey(item) === this.modelId); }
async loadModel(preferredId) {
const model = this.selectedModel();
this.header = null; this.lines = []; this.revisions = []; this.dirty = false; this.query = ''; this.error = '';
if (!model) return;
this.revisions = await this.api(`?model=${encodeURIComponent(model.Model)}&typeId=${model.TypeId}`);
const revision = this.revisions.find(item => Number(item.BomId) === Number(preferredId)) || this.revisions[0];
if (revision) await this.loadRevision(revision.BomId);
}
async loadRevision(id) { const data = await this.api(`/${Number(id)}`); this.header = data; this.lines = data.Lines || []; this.dirty = false; }
async run(action) {
if (this.busy) return; this.busy = true; this.render();
try { await action(); } catch (error) { this.app.notifyFailure(error.message); }
finally { this.busy = false; this.render(); }
}
discardChanges() { return !this.dirty || window.confirm('BOM có thay đổi chưa lưu. Bỏ các thay đổi này?'); }
payload() {
return this.lines.map(line => ({ name: line.Name, model: line.Model || '', quantity: line.Quantity ?? 1, unit: line.Unit || '',
sourceInfo: line.SourceInfo || '', notes: line.Notes || '', code: line.Code || '', groupName: line.GroupName || '', position: line.Position || '' }));
}
validateLine(line) {
if (typeof line.Name !== 'string' || !line.Name.trim() || line.Name.trim().length > 255) throw new Error('Nhập tên tài sản / vật tư, tối đa 255 ký tự.');
const value = line.Quantity ?? 1;
if (!/^\d+(\.\d{1,4})?$/.test(String(value)) || Number(value) <= 0 || Number(value) > 100000) throw new Error('Số lượng phải lớn hơn 0, tối đa 100.000 và không quá 4 chữ số thập phân.');
if (!fractionalUnit(line.Unit || '') && !Number.isInteger(Number(value))) throw new Error(`Đơn vị ${line.Unit} yêu cầu số lượng nguyên.`);
if ((line.Model || '').length > 255 || (line.Unit || '').length > 50 || (line.Notes || '').length > 500 || (line.SourceInfo || '').length > 1000) throw new Error('Model tối đa 255, đơn vị 50, ghi chú 500 và nguồn 1.000 ký tự.');
}
validateLines(lines) { if (lines.length > 500) throw new Error('BOM tối đa 500 dòng vật tư.'); lines.forEach(line => this.validateLine(line)); }
async persistDraft() {
this.validateLines(this.lines);
const saved = await this.api(`/${this.header.BomId}`, { method: 'PUT', body: JSON.stringify({ lockVersion: this.header.LockVersion, lines: this.payload() }) });
this.header.LockVersion = saved.LockVersion; this.lines = saved.Lines; this.dirty = false;
this.header.UpdatedDate = saved.UpdatedDate || this.header.UpdatedDate;
const revision = this.revisions.find(item => item.BomId === this.header.BomId);
if (revision) { revision.LineCount = this.lines.length; revision.LockVersion = saved.LockVersion; revision.UpdatedDate = this.header.UpdatedDate; }
}
changed() { this.dirty = true; this.render(); }
button(action, label, icon, primary = false, disabled = false) {
return `<button type="button" data-bom-action="${action}" class="bom-btn ${primary ? 'bom-btn-primary' : ''} ${action === 'delete' ? 'bom-btn-delete' : ''}" ${disabled || this.busy ? 'disabled' : ''}>${icon ? `<span class="material-symbols-outlined" aria-hidden="true">${icon}</span>` : ''}${label}</button>`;
}
sourceHtml(value) {
if (!value) return '<span class="bom-muted">—</span>';
try {
const url = new URL(value);
if (['https:', 'http:'].includes(url.protocol)) return `<a class="bom-source-link" href="${this.escape(url.href)}" target="_blank" rel="noopener noreferrer">${this.escape(value)}</a>`;
} catch {}
return `<span class="bom-source-text">${this.escape(value)}</span>`;
}
tableHtml() {
const keyword = this.query.trim().toLocaleLowerCase('vi');
const rows = this.lines.map((line, index) => ({ line, index })).filter(({ line }) => !keyword || [line.Name, line.Code, line.Model, line.SourceInfo, line.Notes].some(value => String(value || '').toLocaleLowerCase('vi').includes(keyword)));
if (!rows.length) return `<div class="bom-empty"><span class="material-symbols-outlined">view_list</span><strong>${this.lines.length ? 'Không tìm thấy vật tư phù hợp' : 'Chưa có thành phần trong BOM'}</strong><p>${this.lines.length ? 'Thử từ khóa khác.' : 'Thêm tài sản sẵn có hoặc nhập vật tư từ bên ngoài.'}</p></div>`;
const edit = this.editable() && !this.busy;
return `<div class="bom-table-scroll"><table class="bom-lines-table"><thead><tr><th>STT</th><th>Tên tài sản / Vật tư</th><th>Model</th><th>Số lượng</th><th>Nguồn</th><th>Ghi chú</th>${this.canManage() ? '<th><span class="bom-sr">Thao tác</span></th>' : ''}</tr></thead><tbody>${rows.map(({ line, index }) => `<tr><td>${index + 1}</td><td><strong>${this.escape(line.Name)}</strong>${line.Code ? `<small>${this.escape(line.Code)}</small>` : ''}</td><td>${this.escape(line.Model || '—')}</td><td><div class="bom-quantity-unit">${edit ? `<input class="bom-quantity" type="number" data-bom-quantity="${index}" min="${fractionalUnit(line.Unit || '') ? '0.0001' : '1'}" max="100000" step="${fractionalUnit(line.Unit || '') ? '0.0001' : '1'}" value="${Number(line.Quantity ?? 1)}" aria-label="Số lượng ${this.escape(line.Name)}">` : number(line.Quantity ?? 1)}${line.Unit ? `<small>${this.escape(line.Unit)}</small>` : ''}</div></td><td class="bom-source-cell">${this.sourceHtml(line.SourceInfo)}</td><td class="bom-notes">${this.escape(line.Notes || '—')}</td>${this.canManage() ? `<td class="bom-row-actions">${edit ? `<button type="button" data-bom-edit="${index}" aria-label="Sửa ${this.escape(line.Name)}"><span class="material-symbols-outlined">edit</span></button><button type="button" data-bom-delete="${index}" aria-label="Xóa ${this.escape(line.Name)}"><span class="material-symbols-outlined">delete</span></button>` : '—'}</td>` : ''}</tr>`).join('')}</tbody></table></div>`;
}
historyHtml() {
return `<div class="bom-table-scroll"><table class="bom-history-table"><thead><tr><th>Phiên bản</th><th>Trạng thái</th><th>Số dòng</th><th>Cập nhật</th><th>Phát hành</th><th></th></tr></thead><tbody>${this.revisions.map(revision => `<tr><td><strong>v${Number(revision.Revision)}</strong></td><td><span class="bom-badge ${revision.Status === 'released' ? 'bom-badge-green' : ''}">${revision.Status === 'released' ? 'Đã phát hành' : 'Bản nháp'}</span></td><td>${number(revision.LineCount)}</td><td>${this.escape(this.app.formatDateTime(revision.UpdatedDate))}</td><td>${revision.ReleasedDate ? this.escape(this.app.formatDateTime(revision.ReleasedDate)) : '—'}</td><td><button class="bom-btn" data-bom-open="${Number(revision.BomId)}" ${this.busy ? 'disabled' : ''}>Xem BOM</button></td></tr>`).join('')}</tbody></table></div>`;
}
render() {
if (!this.active()) return;
const model = this.selectedModel(); const disabled = this.busy ? 'disabled' : ''; const edit = this.editable();
this.root.innerHTML = `<section class="bom-page" data-bom-page><header class="bom-page-header"><div><p class="bom-eyebrow">THÀNH PHẦN ROBOT</p><h1>BOM robot</h1><p class="bom-muted">Danh sách tài sản và vật tư cấu tạo của robot.</p></div><div class="bom-toolbar">${this.button('refresh', 'Làm mới', 'refresh')}${this.canManage() ? this.button('import', 'Nhập Excel', 'upload', false, !edit) : ''}${this.button('export', 'Xuất Excel', 'download', false, !this.header)}${this.canManage() ? this.button('save', this.dirty ? 'Lưu thay đổi' : 'Lưu BOM', 'save', true, !edit) : ''}</div></header>${this.error ? `<div class="bom-alert" role="alert">${this.escape(this.error)}. Bấm Làm mới để thử lại.</div>` : ''}
<section class="bom-identity"><span class="bom-robot-icon material-symbols-outlined" aria-hidden="true">smart_toy</span><div class="bom-model-field"><label for="bomModel">Model robot</label><select id="bomModel" ${disabled}><option value="" ${this.models.length ? 'hidden' : ''}>${this.busy ? 'Đang tải…' : 'Chưa có robot'}</option>${this.models.map(item => `<option value="${this.escape(modelKey(item))}" ${this.modelId === modelKey(item) ? 'selected' : ''}>${this.escape(item.Model)} · ${this.escape(item.Type)}</option>`).join('')}</select><small>${this.escape(model?.Name || 'Thêm robot trong Danh sách robot để bắt đầu.')}</small></div><div class="bom-version-field"><label for="bomRevision">Phiên bản BOM</label><select id="bomRevision" ${disabled || !this.header ? 'disabled' : ''}>${this.revisions.length ? this.revisions.map(item => `<option value="${Number(item.BomId)}" ${this.header?.BomId === item.BomId ? 'selected' : ''}>v${Number(item.Revision)} · ${item.Status === 'released' ? 'Đã phát hành' : 'Bản nháp'}</option>`).join('') : '<option>Chưa có BOM</option>'}</select></div>${this.header ? `<span class="bom-badge ${this.header.Status === 'released' ? 'bom-badge-green' : ''}">${this.header.Status === 'released' ? 'Đã phát hành' : this.dirty ? 'Chưa lưu thay đổi' : 'Bản nháp'}</span>` : ''}${this.canManage() ? `<div class="bom-identity-actions">${this.button('new', 'BOM mới', 'add', false, !model?.RobotId)}${this.header ? this.button('copy', 'Sao chép BOM', 'content_copy') + this.button('publish', 'Phát hành', 'send', false, !edit || !this.lines.length) + this.button('delete', 'Xóa BOM', 'delete') : ''}</div>` : ''}</section>
${!this.header ? `<div class="bom-card bom-empty"><span class="material-symbols-outlined">inventory_2</span><strong>${this.busy ? 'Đang tải BOM…' : this.models.length ? 'Model robot này chưa có BOM' : 'Chưa có model robot'}</strong><p>${this.models.length ? 'Tạo BOM và thêm các vật tư cấu thành robot.' : '<a href="#robots">Đến Danh sách robot để thêm robot.</a>'}</p>${this.canManage() && model ? this.button('new', 'Tạo BOM đầu tiên', 'add', true) : ''}</div>` : `<nav class="bom-tabs" aria-label="Nội dung BOM">${[['bom', 'Thành phần robot'], ['history', 'Lịch sử phiên bản']].map(([tab, label]) => `<button type="button" data-bom-tab="${tab}" aria-current="${this.tab === tab ? 'page' : 'false'}">${label}</button>`).join('')}</nav><section class="bom-card bom-main-card"><div class="bom-card-heading"><h2>${this.tab === 'history' ? 'Lịch sử phiên bản' : 'Danh sách thành phần'} <span class="bom-count">${this.tab === 'history' ? this.revisions.length + ' phiên bản' : this.lines.length + ' vật tư'}</span></h2>${edit && this.tab === 'bom' ? this.button('add', 'Thêm vật tư', 'add', true) : ''}</div>${this.tab === 'history' ? this.historyHtml() : `<div class="bom-filters"><label class="bom-search"><span class="material-symbols-outlined" aria-hidden="true">search</span><input id="bomSearch" type="search" value="${this.escape(this.query)}" placeholder="Tìm tên, model, nguồn hoặc ghi chú…" aria-label="Tìm vật tư trong BOM"></label></div><div id="bomLineRows">${this.tableHtml()}</div>`}</section>`}<input id="bomImportFile" class="bom-sr" type="file" accept=".xls,.xlsx" aria-label="Chọn file BOM Excel"></section>`;
const page = this.root.querySelector('[data-bom-page]'); page.addEventListener('click', event => this.click(event)); page.addEventListener('change', event => this.change(event));
page.addEventListener('input', event => { if (event.target.id === 'bomSearch') { this.query = event.target.value; this.root.querySelector('#bomLineRows').innerHTML = this.tableHtml(); } });
}
confirmPublication() {
if (this.publishConfirmation) return this.publishConfirmation;
const dialog = document.createElement('dialog');
dialog.id = 'bomPublishDialog'; dialog.className = 'bom-dialog bom-confirm-dialog';
dialog.setAttribute('aria-labelledby', 'bomPublishTitle');
dialog.setAttribute('aria-describedby', 'bomPublishDescription');
dialog.innerHTML = `<header class="bom-dialog-header"><div class="bom-confirm-heading"><span class="bom-confirm-icon material-symbols-outlined" aria-hidden="true">task_alt</span><div><p class="bom-eyebrow">CHỐT PHIÊN BẢN</p><h2 id="bomPublishTitle">Phát hành BOM v${Number(this.header.Revision)}?</h2></div></div><button type="button" data-bom-publish-cancel aria-label="Đóng"><span class="material-symbols-outlined">close</span></button></header>
<div class="bom-confirm-body"><p id="bomPublishDescription">Phiên bản này sẽ được khóa chỉnh sửa sau khi phát hành.</p><dl class="bom-publish-summary"><div><dt>Model robot</dt><dd>${this.escape(this.header.RobotModel)}</dd></div><div><dt>Phiên bản</dt><dd>v${Number(this.header.Revision)}</dd></div><div><dt>Thành phần</dt><dd>${this.lines.length} dòng vật tư</dd></div></dl>
<div class="bom-publish-note"><span class="material-symbols-outlined" aria-hidden="true">info</span><p>Khi cần thay đổi, dùng <strong>Sao chép BOM</strong> để tạo phiên bản nháp mới.</p></div>${this.dirty ? '<p class="bom-footnote">Các thay đổi chưa lưu sẽ được lưu trước khi phát hành.</p>' : ''}</div>
<footer class="bom-dialog-footer"><div><button type="button" data-bom-publish-cancel class="bom-btn">Quay lại</button><button type="button" data-bom-publish-confirm class="bom-btn bom-btn-primary"><span class="material-symbols-outlined" aria-hidden="true">lock</span>Phát hành BOM</button></div></footer>`;
this.publishConfirmation = new Promise(resolve => {
dialog.addEventListener('click', event => {
if (event.target.closest('[data-bom-publish-confirm]')) dialog.close('confirm');
else if (event.target.closest('[data-bom-publish-cancel]')) dialog.close();
else 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('close', () => {
const confirmed = dialog.returnValue === 'confirm';
dialog.remove(); this.publishConfirmation = null; resolve(confirmed);
}, { once: true });
document.body.appendChild(dialog); dialog.showModal();
dialog.querySelector('.bom-dialog-footer [data-bom-publish-cancel]').focus({ preventScroll: true });
});
return this.publishConfirmation;
}
confirmDeletion() {
if (this.deleteConfirmation) return this.deleteConfirmation;
const dialog = document.createElement('dialog');
dialog.id = 'bomDeleteDialog'; dialog.className = 'bom-dialog bom-confirm-dialog bom-delete-dialog';
dialog.setAttribute('aria-labelledby', 'bomDeleteTitle');
dialog.setAttribute('aria-describedby', 'bomDeleteDescription');
const revision = this.revisions.find(item => item.BomId === this.header.BomId);
dialog.innerHTML = `<header class="bom-dialog-header"><div class="bom-confirm-heading"><span class="bom-confirm-icon material-symbols-outlined" aria-hidden="true">delete</span><div><p class="bom-eyebrow">XÓA PHIÊN BẢN</p><h2 id="bomDeleteTitle">Xóa BOM v${Number(this.header.Revision)}?</h2></div></div><button type="button" data-bom-delete-cancel aria-label="Đóng"><span class="material-symbols-outlined">close</span></button></header>
<div class="bom-confirm-body"><p id="bomDeleteDescription">BOM này và toàn bộ vật tư trong phiên bản sẽ bị xóa vĩnh viễn. Thao tác này không thể hoàn tác.</p><dl class="bom-publish-summary"><div><dt>Model robot</dt><dd>${this.escape(this.header.RobotModel)}</dd></div><div><dt>Phiên bản</dt><dd>v${Number(this.header.Revision)}</dd></div><div><dt>Thành phần đã lưu</dt><dd>${number(revision?.LineCount ?? this.lines.length)} dòng vật tư</dd></div></dl><p class="bom-footnote">Chỉ xóa phiên bản đang chọn. Các phiên bản BOM khác, robot và tài sản trong kho vẫn được giữ nguyên.</p>${this.dirty ? '<p class="bom-footnote">Các thay đổi chưa lưu của phiên bản này cũng sẽ bị bỏ.</p>' : ''}</div>
<footer class="bom-dialog-footer"><div><button type="button" data-bom-delete-cancel class="bom-btn">Hủy</button><button type="button" data-bom-delete-confirm class="bom-btn bom-btn-danger"><span class="material-symbols-outlined" aria-hidden="true">delete</span>Xóa BOM</button></div></footer>`;
this.deleteConfirmation = new Promise(resolve => {
dialog.addEventListener('click', event => {
if (event.target.closest('[data-bom-delete-confirm]')) dialog.close('confirm');
else if (event.target.closest('[data-bom-delete-cancel]')) dialog.close();
else 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('close', () => {
const confirmed = dialog.returnValue === 'confirm';
dialog.remove(); this.deleteConfirmation = null; resolve(confirmed);
}, { once: true });
document.body.appendChild(dialog); dialog.showModal();
dialog.querySelector('.bom-dialog-footer [data-bom-delete-cancel]').focus({ preventScroll: true });
});
return this.deleteConfirmation;
}
async click(event) {
const tab = event.target.closest('[data-bom-tab]'); if (tab && !this.busy) { this.tab = tab.dataset.bomTab; this.render(); return; }
const open = event.target.closest('[data-bom-open]'); if (open && !this.busy && this.discardChanges()) { await this.run(async () => { await this.loadRevision(open.dataset.bomOpen); this.tab = 'bom'; }); return; }
const edit = event.target.closest('[data-bom-edit]'); const remove = event.target.closest('[data-bom-delete]');
if ((edit || remove) && this.editable() && !this.busy) { const index = Number((edit || remove).dataset[edit ? 'bomEdit' : 'bomDelete']); if (!this.lines[index]) return; if (edit) this.openMaterialForm(index); else { this.lines.splice(index, 1); this.changed(); } return; }
const button = event.target.closest('[data-bom-action]'); if (!button || button.disabled || this.busy) return;
const action = button.dataset.bomAction;
if (action === 'add' && this.editable()) return this.openMaterialForm();
if (action === 'export') return this.exportWorkbook();
if (action === 'import' && this.editable()) return this.root.querySelector('#bomImportFile').click();
if (action === 'refresh' && this.discardChanges()) return this.mount(this.root, this.selectedModel());
if (!this.canManage()) return;
if (action === 'delete' && this.header) {
const { BomId: bomId, LockVersion: lockVersion, Revision: revision } = this.header;
const selectedModelId = this.modelId;
if (!await this.confirmDeletion() || this.busy || !this.active() || !this.canManage()
|| this.header?.BomId !== bomId || this.header.LockVersion !== lockVersion || this.modelId !== selectedModelId) return;
return this.run(async () => {
await this.api(`/${bomId}`, { method: 'DELETE', body: JSON.stringify({ lockVersion }) });
this.header = null; this.lines = []; this.revisions = []; this.dirty = false;
this.app.notifySuccess(`Đã xóa BOM v${revision}.`);
this.models = await this.api('/models');
this.modelId = this.models.find(item => modelKey(item) === selectedModelId) ? selectedModelId : this.models[0] ? modelKey(this.models[0]) : '';
await this.loadModel(); this.tab = 'bom';
});
}
if (action === 'save' && this.editable()) return this.run(async () => { await this.persistDraft(); this.app.notifySuccess('Đã lưu BOM.'); });
if (['new', 'copy'].includes(action) && this.selectedModel()) {
if (action === 'new' && (!this.selectedModel().RobotId || !this.discardChanges())) return;
return this.run(async () => { if (action === 'copy' && this.dirty) await this.persistDraft(); const created = await this.api('', { method: 'POST', body: JSON.stringify({ robotId: this.selectedModel().RobotId ?? undefined, ...(action === 'copy' ? { copyFromId: this.header.BomId } : {}) }) }); await this.loadModel(created.BomId); this.tab = 'bom'; this.app.notifySuccess('Đã tạo BOM nháp.'); });
}
if (action === 'publish' && this.editable()) {
const bomId = this.header.BomId;
if (!await this.confirmPublication() || this.busy || !this.editable() || this.header.BomId !== bomId) return;
return this.run(async () => {
if (this.dirty) await this.persistDraft();
await this.api(`/${bomId}/publish`, { method: 'POST', body: JSON.stringify({ lockVersion: this.header.LockVersion }) });
this.header.Status = 'released'; this.dirty = false;
this.app.notifySuccess('Đã phát hành BOM.'); await this.loadModel(bomId);
});
}
}
async change(event) {
const target = event.target; if (target.id === 'bomImportFile' && target.files[0]) { await this.importWorkbook(target.files[0]); return; } if (this.busy) return;
if (target.id === 'bomModel') { if (!this.discardChanges()) { target.value = this.modelId; return; } this.modelId = target.value; await this.run(() => this.loadModel()); }
else if (target.id === 'bomRevision') { if (!this.discardChanges()) { target.value = String(this.header.BomId); return; } await this.run(() => this.loadRevision(target.value)); }
else if (target.hasAttribute('data-bom-quantity') && this.editable()) { const line = this.lines[Number(target.dataset.bomQuantity)]; try { this.validateLine({ ...line, Quantity: target.value }); line.Quantity = Number(target.value); this.changed(); } catch (error) { target.value = line.Quantity; this.app.notifyWarning(error.message); } }
}
openMaterialForm(index = null) {
if (!this.editable()) return; if (this.lines.length >= 500 && index === null) { this.app.notifyWarning('BOM tối đa 500 dòng vật tư.'); return; }
const previous = index === null ? null : this.lines[index]; const state = { mode: previous ? 'manual' : 'asset', catalog: null, loading: false, error: '', selected: null, query: '' };
const dialog = document.createElement('dialog'); dialog.id = 'bomComponentDialog'; dialog.className = 'bom-dialog bom-entry-dialog'; dialog.setAttribute('aria-labelledby', 'bomMaterialTitle');
dialog.innerHTML = `<form id="bomMaterialForm"><header class="bom-dialog-header"><div><h2 id="bomMaterialTitle">${previous ? 'Sửa vật tư' : 'Thêm vật tư vào BOM'}</h2><p>Chọn tên/model từ tài sản hoặc nhập vật tư bên ngoài.</p></div><button type="button" data-bom-close aria-label="Đóng"><span class="material-symbols-outlined">close</span></button></header><div class="bom-entry-tabs"><button type="button" data-bom-mode="asset">Chọn tài sản có sẵn</button><button type="button" data-bom-mode="manual">Nhập vật tư bên ngoài</button></div>
<div class="bom-material-layout">
<section class="bom-entry-context"><div class="bom-asset-picker"><label class="bom-search"><span class="material-symbols-outlined">search</span><input id="bomAssetSearch" type="search" placeholder="Tìm tên, mã hoặc model tài sản…" aria-label="Tìm tài sản"></label><p class="bom-footnote">Lấy tên và model từ tài sản. Số lượng BOM tự nhập.</p><div id="bomAssetResults"></div></div>
<div class="bom-external-guide" hidden><span class="bom-external-icon material-symbols-outlined" aria-hidden="true">edit_note</span><h3>Vật tư bên ngoài</h3><p>Thêm trực tiếp thành phần chưa có trong danh sách tài sản.</p><ul><li><span class="material-symbols-outlined" aria-hidden="true">check_circle</span><span><strong>Nhập tên vật tư</strong><small>Bổ sung model hoặc quy cách nếu có.</small></span></li><li><span class="material-symbols-outlined" aria-hidden="true">format_list_numbered</span><span><strong>Tự điền số lượng</strong><small>Theo cấu hình của robot đang lập BOM.</small></span></li><li><span class="material-symbols-outlined" aria-hidden="true">link</span><span><strong>Ghi lại nguồn cung cấp</strong><small>Link mua hàng hoặc thông tin nhà sản xuất.</small></span></li></ul><p class="bom-external-note">Có thể chuyển lại danh sách tài sản; thông tin đang nhập vẫn được giữ.</p></div>
</section>
<section class="bom-material-fields"><label>Tên tài sản / Vật tư <span class="bom-danger">*</span><input name="name" required maxlength="255" value="${this.escape(previous?.Name || '')}" placeholder="VD: Động cơ servo, cảm biến…" autocomplete="off"></label><label>Model <span class="bom-optional">(tùy chọn)</span><input name="model" maxlength="255" value="${this.escape(previous?.Model || '')}" placeholder="Model / quy cách vật tư"></label><div class="bom-form-grid"><label>Số lượng<input name="quantity" type="number" min="0.0001" max="100000" step="0.0001" value="${Number(previous?.Quantity ?? 1)}"></label><label>Đơn vị <span class="bom-optional">(tùy chọn)</span><input name="unit" maxlength="50" value="${this.escape(previous?.Unit || '')}" placeholder="VD: cái, bộ, m"></label></div><label>Nguồn <span class="bom-optional">(tùy chọn)</span><textarea name="sourceInfo" maxlength="1000" rows="2" placeholder="Link mua hàng hoặc thông tin nhà sản xuất / nhà cung cấp…">${this.escape(previous?.SourceInfo || '')}</textarea></label><label>Ghi chú <span class="bom-optional">(tùy chọn)</span><textarea name="notes" maxlength="500" rows="2" placeholder="Thông tin thêm về vật tư…">${this.escape(previous?.Notes || '')}</textarea></label></section>
</div><footer class="bom-dialog-footer"><p class="bom-entry-save-hint">Thêm vật tư, sau đó bấm <strong>Lưu BOM</strong> để lưu danh sách.</p><div><button type="button" data-bom-close class="bom-btn">Hủy</button>${!previous ? '<button type="submit" name="action" value="continue" class="bom-btn">Thêm và tiếp tục</button>' : ''}<button type="submit" name="action" value="done" class="bom-btn bom-btn-primary">${previous ? 'Cập nhật' : 'Thêm vào BOM'}</button></div></footer></form>`;
const form = dialog.querySelector('form');
const renderCatalog = () => {
const host = dialog.querySelector('#bomAssetResults');
if (state.loading) { host.innerHTML = '<p class="bom-muted bom-footnote" role="status">Đang tải danh sách tài sản…</p>'; return; }
if (state.error) { host.innerHTML = `<p class="bom-alert">${this.escape(state.error)}. Có thể chuyển sang Nhập vật tư bên ngoài.</p>`; return; }
const query = state.query.trim().toLocaleLowerCase('vi'); const rows = (state.catalog || []).filter(item => !query || [item.Name, item.Code, item.Model].some(value => String(value || '').toLocaleLowerCase('vi').includes(query)));
host.innerHTML = rows.length ? `<div class="bom-asset-table-wrap"><table class="bom-asset-table"><thead><tr><th></th><th>Tên tài sản</th><th>Model</th></tr></thead><tbody>${rows.slice(0, 50).map(item => `<tr class="${state.selected?.Id === item.Id ? 'bom-picked-row' : ''}"><td><input type="radio" name="assetChoice" value="${Number(item.Id)}" ${state.selected?.Id === item.Id ? 'checked' : ''} aria-label="Chọn ${this.escape(item.Name)}"></td><td><strong>${this.escape(item.Name)}</strong><small>${this.escape(item.Code)}</small></td><td>${this.escape(item.Model || '—')}</td></tr>`).join('')}</tbody></table></div><p class="bom-footnote">${rows.length > 50 ? `Hiển thị 50/${rows.length} tài sản. Tìm kiếm để thu hẹp danh sách.` : `${rows.length} tài sản`}</p>` : '<div class="bom-empty"><strong>Không tìm thấy tài sản</strong><p>Thử tìm kiếm khác hoặc chọn Nhập vật tư bên ngoài.</p></div>';
};
const setMode = async mode => {
state.mode = mode;
dialog.querySelector('.bom-asset-picker').hidden = mode !== 'asset';
dialog.querySelector('.bom-external-guide').hidden = mode !== 'manual';
dialog.querySelectorAll('[data-bom-mode]').forEach(button => button.setAttribute('aria-pressed', String(button.dataset.bomMode === mode)));
if (mode === 'asset' && !state.catalog && !state.loading) { state.loading = true; state.error = ''; renderCatalog(); try { state.catalog = await this.api('/catalog'); } catch (error) { state.error = error.message; } finally { state.loading = false; renderCatalog(); } }
};
dialog.addEventListener('click', event => {
if (event.target.closest('[data-bom-close]')) { dialog.close(); return; }
const mode = event.target.closest('[data-bom-mode]'); if (mode) setMode(mode.dataset.bomMode);
const row = event.target.closest('.bom-asset-table tbody tr'); if (row && !event.target.closest('input')) row.querySelector('input').click();
});
dialog.querySelector('#bomAssetSearch').addEventListener('input', event => { state.query = event.target.value; renderCatalog(); });
dialog.addEventListener('change', event => {
if (event.target.name !== 'assetChoice') return;
state.selected = state.catalog.find(item => item.Id === Number(event.target.value));
if (state.selected) { form.elements.name.value = state.selected.Name; form.elements.model.value = state.selected.Model || ''; form.elements.unit.value = state.selected.Unit || ''; renderCatalog(); }
});
form.addEventListener('submit', event => {
event.preventDefault(); if (!this.editable() || this.busy) return;
const candidate = { ...previous, SourceType: 'manual', SourceId: null, Name: form.elements.name.value.trim(), Model: form.elements.model.value.trim(), Quantity: form.elements.quantity.value === '' ? 1 : Number(form.elements.quantity.value), Unit: form.elements.unit.value.trim(), SourceInfo: form.elements.sourceInfo.value.trim(), Notes: form.elements.notes.value.trim() };
try { this.validateLine(candidate); } catch (error) { this.app.notifyWarning(error.message); return; }
if (index === null) this.lines.push(candidate); else this.lines[index] = candidate; this.query = ''; this.changed();
if (event.submitter?.value === 'continue') { form.reset(); state.selected = null; renderCatalog(); form.elements.name.focus({ preventScroll: true }); } else dialog.close();
});
dialog.addEventListener('close', () => dialog.remove(), { once: true });
document.body.appendChild(dialog); setMode(state.mode); dialog.showModal();
(state.mode === 'manual' ? form.elements.name : dialog.querySelector('#bomAssetSearch')).focus({ preventScroll: true });
}
exportWorkbook() {
if (!window.XLSX || !this.header) { this.app.notifyFailure('Không tìm thấy thư viện Excel hoặc BOM.'); return; }
try {
const rows = this.lines.map(line => ({ 'Tên vật tư': line.Name, 'Model': line.Model || '', 'Số lượng': Number(line.Quantity ?? 1), 'ĐVT': line.Unit || '', 'Nguồn': line.SourceInfo || '', 'Ghi chú': line.Notes || '' }));
for (const [field, label] of [['Code', 'Mã vật tư'], ['GroupName', 'Cụm lắp ráp'], ['Position', 'Vị trí lắp']]) if (this.lines.some(line => line[field])) rows.forEach((row, index) => { row[label] = this.lines[index][field] || ''; });
const book = window.XLSX.utils.book_new(); const sheet = window.XLSX.utils.json_to_sheet(rows, { header: ['Tên vật tư', 'Model', 'Số lượng', 'ĐVT', 'Nguồn', 'Ghi chú'] });
sheet['!cols'] = [36, 24, 14, 12, 55, 40, 20, 24, 24].map(wch => ({ wch })); window.XLSX.utils.book_append_sheet(book, sheet, 'BOM');
window.XLSX.utils.book_append_sheet(book, window.XLSX.utils.json_to_sheet([{ 'Model robot': this.header.RobotModel, 'Thể loại': this.selectedModel()?.Type || '', 'Phiên bản': this.header.Revision, 'Trạng thái': this.dirty ? 'Thay đổi chưa lưu' : this.header.Status === 'released' ? 'Đã phát hành' : 'Bản nháp', 'Ngày xuất': this.app.formatDateTime(new Date()) }]), 'Thong tin');
window.XLSX.writeFile(book, `BOM-${this.header.RobotModel.replace(/[^\p{L}\p{N}._-]/gu, '_').slice(0, 80)}-v${this.header.Revision}.xlsx`);
} catch (error) { this.app.notifyFailure(`Không thể xuất BOM: ${error.message}`); }
}
async importWorkbook(file) {
if (!this.editable() || this.busy) return;
if (!window.XLSX) { this.app.notifyFailure('Không tìm thấy thư viện Excel.'); return; }
if (!/\.xlsx?$/i.test(file.name) || file.size > 10 * 1024 * 1024) { this.app.notifyWarning('Chọn file .xls hoặc .xlsx, tối đa 10 MB.'); return; }
await this.run(async () => {
const book = window.XLSX.read(await file.arrayBuffer(), { type: 'array', sheetRows: 502 }); const sheet = book.Sheets.BOM || book.Sheets[book.SheetNames[0]]; const rows = window.XLSX.utils.sheet_to_json(sheet, { defval: '' });
if (!rows.length || rows.length > 500) throw new Error('File cần có từ 1 đến 500 dòng vật tư. Dùng file Xuất Excel làm mẫu.');
const next = rows.map(row => ({ SourceType: 'manual', SourceId: null, Name: String(row['Tên vật tư'] || row['Tên tài sản'] || row['Tên linh kiện'] || '').trim(), Model: String(row.Model || '').trim(), Quantity: row['Số lượng'] !== undefined && row['Số lượng'] !== '' ? row['Số lượng'] : row['SL / robot'] ?? 1, Unit: String(row['ĐVT'] || '').trim(), SourceInfo: String(row['Nguồn'] || '').trim(), Notes: String(row['Ghi chú'] || '').trim(), Code: String(row['Mã vật tư'] || row['Mã linh kiện'] || '').trim(), GroupName: String(row['Cụm lắp ráp'] || '').trim(), Position: String(row['Vị trí lắp'] || '').trim() }));
this.validateLines(next); if (this.lines.length && !window.confirm(`Thay ${this.lines.length} dòng BOM hiện tại bằng ${next.length} dòng từ Excel? Bấm Lưu thay đổi sau khi kiểm tra danh sách.`)) return;
this.lines = next; this.dirty = true; this.query = ''; this.app.notifySuccess(`Đã đọc ${next.length} vật tư. Bấm Lưu thay đổi để lưu.`);
});
}
}
window.RobotBomController = RobotBomController;
})();

View File

@@ -700,15 +700,16 @@
</div>
</div>
<div class="modal-backdrop fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="borrowAssetModal">
<div class="modal-content w-full max-w-lg bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden m-4">
<div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50">
<h3 class="text-base font-extrabold text-slate-900">Xuất tài sản</h3>
<div class="modal-content w-full max-w-lg bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden m-4 flex flex-col" style="max-height: calc(100dvh - 2rem);">
<div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50 shrink-0">
<h3 id="borrowAssetTitle" class="text-base font-extrabold text-slate-900">Tạo đơn xuất tài sản vào dự án</h3>
<button type="button" class="p-1.5 rounded-lg hover:bg-slate-200 text-slate-400 transition-colors" data-close-modal="borrowAssetModal">
<span class="material-symbols-outlined">close</span>
</button>
</div>
<form id="borrowAssetForm" class="p-6 space-y-4 overflow-y-auto" style="max-height: 80vh;">
<form id="borrowAssetForm" class="p-6 space-y-4 overflow-y-auto min-h-0">
<input type="hidden" id="borrowAssetIdInput">
<p id="borrowAssetDescription" class="text-sm text-slate-600">Xuất vào dự án, không hoàn lại kho. Số lượng chỉ trừ khi admin/asset duyệt đơn.</p>
<p id="borrowAssetStockSummary" class="text-sm font-semibold text-slate-700"></p>
<div>
<label class="text-[10px] font-bold uppercase text-slate-500 tracking-widest block mb-1">Tài sản</label>
@@ -719,10 +720,14 @@
<label for="borrowCurrentEndingInput" class="text-xs font-bold text-slate-500 block mb-1">Còn có thể xuất</label>
<input type="number" id="borrowCurrentEndingInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 bg-slate-50" readonly>
</div>
<div>
<label for="borrowAssetUserInput" class="text-xs font-bold text-slate-500 block mb-1">Người mượn</label>
<select id="borrowAssetUserInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3" required>
<option value="">-- Chọn người mượn --</option>
<div id="borrowAssetRequesterField">
<label for="borrowAssetUserInput" class="text-xs font-bold text-slate-500 block mb-1">Người đề xuất</label>
<input type="text" id="borrowAssetUserInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 bg-slate-50" readonly required>
</div>
<div id="borrowAssetRecipientField" hidden>
<label for="borrowAssetRecipientInput" class="text-xs font-bold text-slate-500 block mb-1">Người nhận</label>
<select id="borrowAssetRecipientInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3" disabled>
<option value="">-- Chọn người nhận --</option>
</select>
</div>
<div class="md:col-span-2 space-y-3">
@@ -740,22 +745,14 @@
<button type="button" id="addBorrowProjectBtn" class="mt-2 px-3 py-2 text-xs font-bold text-primary border border-slate-200 rounded-lg">+ Thêm dự án</button>
<p id="borrowAllocationSummary" class="mt-2 text-sm font-semibold" aria-live="polite"></p>
</div>
<div>
<label for="borrowByInput" class="text-xs font-bold text-slate-500 block mb-1">Người xuất</label>
<input type="text" id="borrowByInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 bg-slate-50" readonly>
</div>
<div>
<label for="borrowRoleInput" class="text-xs font-bold text-slate-500 block mb-1">Role người thao tác</label>
<input type="text" id="borrowRoleInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 bg-slate-50" readonly>
</div>
<div class="md:col-span-2">
<label for="borrowAssetNoteInput" class="text-xs font-bold text-slate-500 block mb-1">Ghi chú xuất</label>
<textarea id="borrowAssetNoteInput" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 h-20 resize-none" placeholder="Nhập ghi chú (nếu có)"></textarea>
<textarea id="borrowAssetNoteInput" maxlength="1000" class="w-full border border-slate-200 rounded-lg text-sm py-2.5 px-3 h-20 resize-none" placeholder="Nhập ghi chú (nếu có)"></textarea>
</div>
</div>
<div class="flex gap-3 pt-2">
<button type="button" class="flex-1 px-4 py-2 text-xs font-bold text-slate-600 border border-slate-200 rounded-lg" data-close-modal="borrowAssetModal">Hủy</button>
<button type="submit" class="flex-1 px-4 py-2 bg-primary hover:bg-primary-dim text-on-primary rounded-lg text-xs font-bold">Xuất và tải Excel</button>
<button type="submit" class="flex-1 px-4 py-2 bg-primary hover:bg-primary-dim text-on-primary rounded-lg text-xs font-bold">Gửi đơn chờ duyệt</button>
</div>
</form>
</div>
@@ -765,12 +762,13 @@
<div class="modal-backdrop fixed inset-0 z-[110] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="batchAssetExportModal">
<div class="modal-content w-full max-w-5xl bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden m-4 flex flex-col" style="max-height: calc(100vh - 2rem);">
<div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50">
<div><h3 class="text-base font-extrabold text-slate-900">Xuất nhiều tài sản</h3><p class="mt-1 text-xs text-slate-500">Chọn số lượng và dự án cho từng tài sản trong một phiếu.</p></div>
<div><h3 id="batchAssetExportTitle" class="text-base font-extrabold text-slate-900">Tạo đơn xuất nhiều tài sản vào dự án</h3><p id="batchAssetExportDescription" class="mt-1 text-xs text-slate-500">Chọn số lượng và dự án cho từng tài sản. Chỉ trừ kho khi được duyệt; tài sản xuất không hoàn lại kho.</p></div>
<button type="button" class="p-1.5 rounded-lg hover:bg-slate-200 text-slate-400" data-close-modal="batchAssetExportModal" aria-label="Đóng"><span class="material-symbols-outlined">close</span></button>
</div>
<form id="batchAssetExportForm" class="p-6 space-y-4 overflow-y-auto">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<label class="text-xs font-semibold text-slate-600">Người mượn<select id="batchAssetExportUserInput" class="mt-1 w-full border border-slate-200 rounded-lg px-3 py-2 text-sm" required><option value="">-- Chọn người mượn --</option></select></label>
<label id="batchAssetExportRequesterField" class="text-xs font-semibold text-slate-600">Người đề xuất<input id="batchAssetExportUserInput" class="mt-1 w-full border border-slate-200 rounded-lg px-3 py-2 text-sm bg-slate-50" readonly required></label>
<label id="batchAssetExportRecipientField" class="text-xs font-semibold text-slate-600" hidden>Người nhận<select id="batchAssetExportRecipientInput" class="mt-1 w-full border border-slate-200 rounded-lg px-3 py-2 text-sm" disabled><option value="">-- Chọn người nhận --</option></select></label>
<label class="text-xs font-semibold text-slate-600">Dự án chung (tùy chọn)<select id="batchAssetExportCommonProject" class="mt-1 w-full border border-slate-200 rounded-lg px-3 py-2 text-sm"><option value="">-- Áp dụng dự án cho tất cả --</option></select></label>
</div>
<p id="batchAssetExportSummary" class="text-sm font-semibold text-slate-700" aria-live="polite"></p>
@@ -783,7 +781,7 @@
<label class="block text-xs font-semibold text-slate-600">Ghi chú xuất<textarea id="batchAssetExportNoteInput" class="mt-1 w-full border border-slate-200 rounded-lg px-3 py-2 text-sm h-20 resize-none" maxlength="1000" placeholder="Nhập ghi chú (nếu có)"></textarea></label>
<div class="flex gap-3 pt-2">
<button type="button" class="flex-1 px-4 py-2 text-xs font-bold text-slate-600 border border-slate-200 rounded-lg" data-close-modal="batchAssetExportModal">Hủy</button>
<button type="submit" class="flex-1 px-4 py-2 bg-primary hover:bg-primary-dim text-on-primary rounded-lg text-xs font-bold">Xuất và tải Excel</button>
<button type="submit" class="flex-1 px-4 py-2 bg-primary hover:bg-primary-dim text-on-primary rounded-lg text-xs font-bold">Gửi đơn chờ duyệt</button>
</div>
</form>
</div>
@@ -864,48 +862,24 @@
</div>
</div>
<!-- Asset Export History Modal -->
<div class="modal-backdrop fixed inset-0 z-[110] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="assetExportHistoryModal" style="z-index: 125;">
<div class="modal-content asset-export-history-dialog bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden flex flex-col">
<div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50 shrink-0">
<h3 class="text-base font-extrabold text-slate-900">Lịch sử xuất tài sản</h3>
<button type="button" class="p-1.5 rounded-lg hover:bg-slate-200 text-slate-400 transition-colors" data-close-modal="assetExportHistoryModal">
<span class="material-symbols-outlined">close</span>
</button>
<!-- Approve/reject a project export proposal -->
<div class="modal-backdrop fixed inset-0 z-[110] flex items-center justify-center bg-black/40 backdrop-blur-sm" id="assetExportProcessModal">
<div class="modal-content w-full max-w-lg bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden m-4">
<div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50">
<h3 id="assetExportProcessTitle" class="text-base font-extrabold text-slate-900">Duyệt xuất dự án</h3>
<button type="button" class="p-1.5 rounded-lg text-slate-500" data-close-modal="assetExportProcessModal" aria-label="Đóng"><span class="material-symbols-outlined">close</span></button>
</div>
<div class="p-6 pt-4 min-h-0">
<div class="asset-export-history-scroll rounded-xl border border-slate-200">
<table class="asset-export-history-table w-full text-left">
<colgroup>
<col style="width: 180px;">
<col>
<col style="width: 88px;">
<col style="width: 144px;">
<col style="width: 156px;">
<col style="width: 140px;">
<col style="width: 168px;">
<col style="width: 248px;">
</colgroup>
<thead class="bg-slate-50 border-b border-slate-200">
<tr>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Ngày giờ</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Tài sản</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Số lượng</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Dự án</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Người phụ trách</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Người xuất</th>
<th class="px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">Ghi chú</th>
<th class="asset-export-history-document px-4 py-2.5 text-[10px] font-bold uppercase tracking-wider text-slate-500 whitespace-nowrap">Phiếu Excel</th>
</tr>
</thead>
<tbody id="assetExportHistoryTableBody" class="divide-y divide-slate-100">
<tr>
<td colspan="8" class="px-4 py-8 text-sm text-center text-slate-500">Chưa có dữ liệu lịch sử xuất.</td>
</tr>
</tbody>
</table>
<form id="assetExportProcessForm" class="p-6 space-y-4">
<p id="assetExportProcessMessage" class="text-sm text-slate-600"></p>
<div id="assetExportRejectField" hidden>
<label for="assetExportRejectReason" class="block mb-1 text-sm font-bold text-slate-700">Lý do từ chối</label>
<textarea id="assetExportRejectReason" maxlength="1000" class="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm h-24"></textarea>
</div>
</div>
<div class="flex gap-3 pt-2">
<button type="button" class="flex-1 px-4 py-2 text-xs font-bold border border-slate-200 rounded-lg" data-close-modal="assetExportProcessModal">Hủy</button>
<button id="assetExportProcessSubmit" type="submit" class="flex-1 px-4 py-2 bg-primary text-on-primary rounded-lg text-xs font-bold">Duyệt và xuất vào dự án</button>
</div>
</form>
</div>
</div>

View File

@@ -10,6 +10,7 @@
<!-- 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=20261019-4" />
<link rel="stylesheet" href="../css/robot-bom.css?v=20261102-5" />
<!-- 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>
@@ -250,6 +251,9 @@
</style>
<link rel="stylesheet" href="../css/responsive.css?v=20261019-3" />
<link rel="stylesheet" href="../css/asset-actions.css?v=20261111-1" />
<link rel="stylesheet" href="../css/dashboard.css?v=20261103-1" />
<link rel="stylesheet" href="../css/announcements.css?v=20261103-2" />
</head>
<body class="app-shell bg-background text-on-surface antialiased flex h-screen w-screen">
<!-- SideNavBar -->
@@ -285,11 +289,6 @@
<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">
@@ -307,6 +306,10 @@
<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="#asset-exports" data-nav="asset-exports" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">outbox</span>
<span class="sidebar-text">Xuất vào dự á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>
@@ -353,17 +356,32 @@
<span class="material-symbols-outlined" aria-hidden="true">category</span>
<span class="sidebar-text">Thể loại robot</span>
</a></li>
<li><a href="#robot-bom" data-nav="robot-bom" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">receipt_long</span>
<span class="sidebar-text">BOM 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>
<li id="usersSection" class="sidebar-admin" data-nav-group="administration" style="display: none;">
<button id="sidebarAdministrationToggle" type="button" class="sidebar-link sidebar-group-toggle" data-nav-toggle="administration" aria-expanded="false" aria-controls="sidebarAdministration">
<span class="material-symbols-outlined" aria-hidden="true">admin_panel_settings</span>
<span class="sidebar-text">Quản trị viên</span>
<span class="material-symbols-outlined sidebar-chevron" aria-hidden="true">chevron_right</span>
</button>
<ul id="sidebarAdministration" class="sidebar-children" aria-labelledby="sidebarAdministrationToggle" hidden>
<li><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">Quản lý người dùng</span>
</a></li>
<li><a href="#notification-management" data-nav="notification-management" class="sidebar-link">
<span class="material-symbols-outlined" aria-hidden="true">campaign</span>
<span class="sidebar-text">Đăng thông báo</span>
</a></li>
</ul>
</li>
</ul>
</nav>
@@ -431,6 +449,7 @@
</main>
<script src="../js/document-formats.js?v=20261019-1"></script>
<script src="../js/app.js?v=20261019-4"></script>
<script src="../js/robot-bom.js?v=20261102-5"></script>
<script src="../js/app.js?v=20261111-1"></script>
</body>
</html>