Compare commits
7 Commits
6a872e8c8b
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 6e919fde45 | |||
| 1b1012dbed | |||
| 03a481f20d | |||
| 00122e5b4a | |||
| 63866b14a1 | |||
| ea6768f90d | |||
| a41bd9c193 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -12,3 +12,4 @@ outputs
|
||||
test/
|
||||
tools
|
||||
output
|
||||
docs
|
||||
86
backend/announcements.js
Normal file
86
backend/announcements.js
Normal 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 };
|
||||
183
backend/announcements.test.js
Normal file
183
backend/announcements.test.js
Normal 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);
|
||||
});
|
||||
185
backend/asset-export-browser.test.js
Normal file
185
backend/asset-export-browser.test.js
Normal 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();
|
||||
}
|
||||
});
|
||||
135
backend/asset-export-requests-sql.test.js
Normal file
135
backend/asset-export-requests-sql.test.js
Normal 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(); }
|
||||
});
|
||||
176
backend/asset-export-requests.js
Normal file
176
backend/asset-export-requests.js
Normal 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 };
|
||||
31
backend/asset-export-requests.sql
Normal file
31
backend/asset-export-requests.sql
Normal 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;
|
||||
53
backend/asset-export-requests.test.js
Normal file
53
backend/asset-export-requests.test.js
Normal 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);
|
||||
}
|
||||
});
|
||||
78
backend/asset-export-sql-fixture.js
Normal file
78
backend/asset-export-sql-fixture.js
Normal 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 };
|
||||
48
backend/asset-export-test-fixture.js
Normal file
48
backend/asset-export-test-fixture.js
Normal 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 };
|
||||
156
backend/asset-export-ui.test.js
Normal file
156
backend/asset-export-ui.test.js
Normal 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, /<Máy khoan>/);
|
||||
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');
|
||||
});
|
||||
@@ -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
131
backend/dashboard.test.js
Normal 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, /<img src=x onerror=alert\(1\)>/);
|
||||
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);
|
||||
});
|
||||
75
backend/notifications-ui.test.js
Normal file
75
backend/notifications-ui.test.js
Normal 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/);
|
||||
});
|
||||
@@ -13,11 +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');
|
||||
|
||||
@@ -3071,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
|
||||
@@ -3099,6 +3113,7 @@ 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(`
|
||||
@@ -4273,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);
|
||||
@@ -4360,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();
|
||||
@@ -4379,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' });
|
||||
}
|
||||
|
||||
@@ -4490,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) {
|
||||
@@ -4499,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;
|
||||
`);
|
||||
|
||||
@@ -8568,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,
|
||||
@@ -8581,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
|
||||
`);
|
||||
|
||||
@@ -8597,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.' });
|
||||
@@ -8611,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.' });
|
||||
@@ -8910,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);
|
||||
@@ -8924,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 {
|
||||
@@ -9721,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) {
|
||||
|
||||
@@ -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
|
||||
|
||||
Binary file not shown.
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -1,62 +0,0 @@
|
||||
# Cấu hình tên miền robot.dvex.io.vn
|
||||
|
||||
Địa chỉ mới của AccManager là **https://robot.dvex.io.vn**. Các bước dưới đây cần được áp dụng trên hệ thống triển khai; thay đổi file trong dự án không tự cập nhật DNS, reverse proxy hoặc chứng chỉ HTTPS.
|
||||
|
||||
## Cấu hình ứng dụng
|
||||
|
||||
Trong `.env` trên máy chạy ứng dụng, đặt:
|
||||
|
||||
```dotenv
|
||||
APP_BASE_URL=https://robot.dvex.io.vn
|
||||
CORS_ALLOWED_ORIGINS=https://robot.dvex.io.vn
|
||||
COOKIE_SECURE=true
|
||||
TRUST_PROXY_HOPS=1
|
||||
```
|
||||
|
||||
`APP_BASE_URL` được dùng để tạo liên kết xác thực email và đặt lại mật khẩu. `CORS_ALLOWED_ORIGINS` cho phép trình duyệt gọi API từ tên miền mới. Không thêm tên miền đã ngừng sử dụng vào danh sách này.
|
||||
|
||||
`TRUST_PROXY_HOPS=1` phù hợp khi có đúng một reverse proxy giữa trình duyệt và ứng dụng; điều chỉnh theo số proxy thực tế. Giữ các giá trị kết nối SQL Server, SMTP và `DATA_ENCRYPTION_SECRET` hiện có. Đổi tên miền không yêu cầu chuyển dữ liệu hoặc đổi khóa mã hóa.
|
||||
|
||||
## DNS và reverse proxy
|
||||
|
||||
1. Tạo hoặc cập nhật bản ghi DNS cho `robot.dvex.io.vn` tại nơi quản lý `dvex.io.vn`. Nếu truy cập từ Internet, trỏ bản ghi tới IP public đang phục vụ reverse proxy; cấu hình đường vào cổng 80/443 tương ứng. Các IP nội bộ `172.20.235.176` và `10.70.21.5` không phải địa chỉ truy cập Internet.
|
||||
2. Nếu chỉ dùng LAN/VPN, cấu hình DNS nội bộ trỏ tới IP phù hợp với mạng hoặc làm theo [LOCAL_ACCESS.md](LOCAL_ACCESS.md). **Các vị trí khác tầng 11 trong khuôn viên trường dùng `10.70.21.5`**, tương ứng dòng `10.70.21.5 robot.dvex.io.vn` trong file `hosts`. Tại tầng 11, dùng IP nội bộ đã được quản trị viên xác nhận; hướng dẫn trước ghi nhận `172.20.235.176`. Chỉ giữ một ánh xạ đang hoạt động cho cùng tên miền trên mỗi máy.
|
||||
3. Trên reverse proxy, tạo hoặc cập nhật virtual host/Proxy Host với tên `robot.dvex.io.vn`. Chuyển tiếp HTTP tới ứng dụng ở cổng `3000`, dùng địa chỉ máy chủ và cổng thực tế của hệ thống triển khai. Nếu proxy chạy trong container, dùng địa chỉ mà container truy cập được; `localhost` trong container là chính container đó.
|
||||
4. Giữ header `Host` của yêu cầu và thiết lập đúng `X-Forwarded-Proto` cùng `X-Forwarded-For` để backend nhận biết kết nối HTTPS qua proxy.
|
||||
5. Cấp và gắn chứng chỉ HTTPS hợp lệ cho `robot.dvex.io.vn`, được máy người dùng tin cậy; bật chuyển hướng HTTP sang HTTPS. Chứng chỉ của tên miền trước không tự áp dụng cho tên miền mới.
|
||||
|
||||
## Áp dụng `.env` trên máy triển khai
|
||||
|
||||
Tại thư mục chứa file Compose và `.env` của hệ thống đang chạy, dùng lệnh tương ứng với cách triển khai hiện tại.
|
||||
|
||||
Nếu dùng `docker-compose.yml`:
|
||||
|
||||
```sh
|
||||
docker compose up -d --no-deps --force-recreate accmanager
|
||||
```
|
||||
|
||||
Nếu dùng image qua `docker-compose.image.yml`:
|
||||
|
||||
```sh
|
||||
docker compose -f docker-compose.image.yml up -d --no-deps --force-recreate accmanager
|
||||
```
|
||||
|
||||
Container cần được tạo lại để nhận biến môi trường mới; `docker compose restart` không nạp lại `.env`. Chỉ đổi các biến tên miền không yêu cầu build lại image. Nếu chạy bằng Node hoặc trình quản lý tiến trình khác, cập nhật môi trường của tiến trình đó và khởi động lại backend theo cách triển khai hiện tại.
|
||||
|
||||
## Kiểm tra sau khi áp dụng
|
||||
|
||||
Trong PowerShell trên máy người dùng:
|
||||
|
||||
```powershell
|
||||
Resolve-DnsName robot.dvex.io.vn
|
||||
curl.exe --fail --show-error --connect-timeout 5 --max-time 15 https://robot.dvex.io.vn/api/health
|
||||
curl.exe --fail --show-error --connect-timeout 5 --max-time 15 -H "Origin: https://robot.dvex.io.vn" -D - https://robot.dvex.io.vn/api/health
|
||||
```
|
||||
|
||||
Địa chỉ DNS phải phù hợp với mạng đang dùng, HTTPS phải xác minh được chứng chỉ và health check phải trả `"status":"ok"`. Với yêu cầu có `Origin`, kiểm tra header `Access-Control-Allow-Origin: https://robot.dvex.io.vn` và `Access-Control-Allow-Credentials: true`.
|
||||
|
||||
Mở `https://robot.dvex.io.vn/pages/login.html`, đăng nhập và kiểm tra thao tác gọi API. Người dùng cần đăng nhập lại vì cookie của tên miền trước không được gửi tới tên miền mới.
|
||||
|
||||
Kiểm tra email xác thực hoặc email đặt lại mật khẩu mới gửi: liên kết phải bắt đầu bằng `https://robot.dvex.io.vn/`. Liên kết trong email đã gửi trước khi chuyển đổi giữ nguyên địa chỉ cũ; người dùng cần yêu cầu gửi lại nếu không còn truy cập được.
|
||||
|
||||
Các lệnh và kết quả mong đợi trên là hướng dẫn kiểm tra, không xác nhận DNS, proxy, chứng chỉ hay container thực tế đã được cập nhật.
|
||||
@@ -1,81 +0,0 @@
|
||||
# Dùng AccManager qua mạng nội bộ với robot.dvex.io.vn
|
||||
|
||||
Địa chỉ truy cập mới là **https://robot.dvex.io.vn**. Nếu cần truy cập trực tiếp qua LAN/VPN, có thể ánh xạ tên này tới IP nội bộ của reverse proxy bằng DNS nội bộ hoặc file `hosts`.
|
||||
|
||||
Chọn IP theo vị trí truy cập trong khuôn viên trường:
|
||||
|
||||
| Vị trí | IP dùng cho tên `robot.dvex.io.vn` |
|
||||
| --- | --- |
|
||||
| Các vị trí khác tầng 11 trong khuôn viên trường | `10.70.21.5` |
|
||||
| Tại tầng 11 | Dùng IP nội bộ đã được quản trị viên xác nhận; địa chỉ ghi nhận trong hướng dẫn trước là `172.20.235.176`. |
|
||||
|
||||
Máy sử dụng cần kết nối mạng nội bộ hoặc VPN có đường tới IP tương ứng. Chỉ giữ **một dòng ánh xạ đang hoạt động** cho `robot.dvex.io.vn`; khi đổi vị trí, sửa dòng này thay vì thêm nhiều IP cho cùng tên miền.
|
||||
|
||||
## Điều kiện trên máy chủ
|
||||
|
||||
Hoàn tất [cấu hình tên miền mới](DOMAIN_SETUP.md) trước khi thiết lập máy người dùng:
|
||||
|
||||
- Ứng dụng dùng `APP_BASE_URL=https://robot.dvex.io.vn` và `CORS_ALLOWED_ORIGINS=https://robot.dvex.io.vn`.
|
||||
- Reverse proxy nhận tên `robot.dvex.io.vn` và chuyển tiếp tới ứng dụng.
|
||||
- Reverse proxy có chứng chỉ HTTPS hợp lệ cho `robot.dvex.io.vn`, được máy người dùng tin cậy.
|
||||
|
||||
Ánh xạ `hosts` chỉ thay cách phân giải tên miền; ánh xạ này không cấu hình reverse proxy hoặc cấp chứng chỉ.
|
||||
|
||||
## 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. Với các vị trí **khác tầng 11 trong khuôn viên trường**, thêm hoặc sửa dòng ánh xạ thành:
|
||||
|
||||
```text
|
||||
10.70.21.5 robot.dvex.io.vn # AccManager temporary LAN
|
||||
```
|
||||
|
||||
Tại tầng 11, dùng IP đã được quản trị viên xác nhận theo bảng trên. Nếu có dòng đang hoạt động cho `robot.dvex.io.vn`, sửa dòng đó thay vì thêm trùng; không để cả hai IP cùng hoạt động. Ghi lại nội dung cũ để hoàn tác và giữ nguyên các dòng của tên khá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://robot.dvex.io.vn** và đăng nhập bằng tài khoản hiện có. Cookie của tên miền trước không được gửi tới tên miền mới, nên cần đăng nhập lại.
|
||||
|
||||
Thực hiện trên từng máy cần dùng. Nếu á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à cấu hình các máy sử dụng DNS đó.
|
||||
|
||||
## 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://robot.dvex.io.vn/api/health
|
||||
```
|
||||
|
||||
Kết quả mong đợi có `"status":"ok"` và xác minh chứng chỉ thành công. Mở `/pages/login.html` và đăng nhập để kiểm tra phiên làm việc.
|
||||
|
||||
Với các vị trí khác tầng 11 trong khuôn viên trường, có thể kiểm tra trước khi sửa `hosts` bằng lệnh sau; ánh xạ chỉ áp dụng cho lần gọi này. Nếu dùng IP khác theo vị trí, thay `10.70.21.5` bằng IP tương ứng:
|
||||
|
||||
```powershell
|
||||
curl.exe --noproxy "*" --fail --show-error --connect-timeout 5 --max-time 15 --resolve robot.dvex.io.vn:443:10.70.21.5 https://robot.dvex.io.vn/api/health
|
||||
```
|
||||
|
||||
Đây là các bước kiểm tra cần thực hiện sau khi triển khai, chưa phải kết quả xác nhận tên miền mới đã hoạt động.
|
||||
|
||||
Nếu chưa truy cập được, kiểm tra LAN/VPN, IP reverse proxy, dòng `hosts`, cache DNS, cấu hình host và chứng chỉ HTTPS. Nếu máy sử dụng proxy web, cấu hình cho địa chỉ này đi trực tiếp qua LAN.
|
||||
|
||||
## Vì sao vẫn dùng tên miền khi truy cập qua LAN?
|
||||
|
||||
Tên `robot.dvex.io.vn` giúp HTTPS khớp chứng chỉ và reverse proxy chọn đúng ứng dụng. Truy cập bằng IP có thể không khớp chứng chỉ hoặc host của proxy. Cookie `Secure` cần kết nối HTTPS.
|
||||
|
||||
Sau khi máy chủ đã cấu hình tên miền mới, thay đổi DNS/`hosts` trên máy người dùng không cần khởi động lại ứng dụng hay chuyển cơ sở dữ liệu.
|
||||
|
||||
## Gỡ ánh xạ tạm khi DNS đã sẵn sàng
|
||||
|
||||
1. Xác nhận DNS mà máy sử dụng đã phân giải `robot.dvex.io.vn` tới địa chỉ phù hợp và truy cập HTTPS thành công.
|
||||
2. Mở `hosts` với quyền Administrator, xóa riêng dòng đã thêm 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 **https://robot.dvex.io.vn**.
|
||||
@@ -1,90 +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.
|
||||
- Lập BOM thành phần robot: chọn tên/model từ tài sản hoặc nhập bên ngoài, tự điền số lượng và nguồn mua/nhà sản xuất.
|
||||
|
||||
## 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.
|
||||
8. Vào Quản lý robot → BOM robot để thêm thành phần, số lượng, nguồn và nhập/xuất Excel. BOM không thay đổi số lượng kho. Xem [hướng dẫn BOM](ROBOT_BOM.md).
|
||||
|
||||
## 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.
|
||||
- Xóa robot/thể loại mở hộp xác nhận trong ứng dụng, có tên và thông tin mục đang xóa. Bấm Hủy, nút đóng hoặc Escape để quay lại.
|
||||
- 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)
|
||||
- Cấu hình tên miền `robot.dvex.io.vn`: [DOMAIN_SETUP.md](DOMAIN_SETUP.md)
|
||||
- Phiếu đề nghị xuất Excel và review với dữ liệu test: [ASSET_EXPORT_EXCEL.md](ASSET_EXPORT_EXCEL.md)
|
||||
- Truy cập `robot.dvex.io.vn` qua LAN/VPN: [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
|
||||
@@ -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ữ.
|
||||
@@ -1,56 +0,0 @@
|
||||
# BOM robot
|
||||
|
||||
Vào **Quản lý robot → BOM robot** hoặc bấm **BOM** trên thẻ robot. Admin và Asset được lập/sửa/phát hành BOM; tài khoản đã đăng nhập được xem và xuất Excel.
|
||||
|
||||
## Lập BOM đầu tiên
|
||||
|
||||
1. Chọn model robot và bấm **Tạo BOM đầu tiên**. Model lấy từ Danh sách robot; các robot cùng model và thể loại dùng chung bộ phiên bản BOM.
|
||||
2. Bấm **Thêm vật tư**. Chọn **Chọn tài sản có sẵn** để lấy tên/model từ danh sách tài sản, hoặc **Nhập vật tư bên ngoài** để tự nhập thông tin.
|
||||
3. Điền **Tên tài sản / Vật tư**, **Model**, **Số lượng** cho BOM. Model và đơn vị có thể để trống. Số lượng mặc định 1 và tự sửa theo thành phần thực tế của robot.
|
||||
4. Điền **Nguồn** bằng link mua hàng hoặc thông tin nhà sản xuất/nhà cung cấp. Có thể thêm ghi chú.
|
||||
5. Bấm **Thêm vào BOM**, sau đó **Lưu BOM**. **Thêm và tiếp tục** giữ hộp nhập mở để thêm nhiều dòng.
|
||||
|
||||
Hai chế độ thêm vật tư dùng chung kích thước hộp thoại và vị trí các trường. Chuyển chế độ giữ nguyên thông tin đang nhập. **Thêm vào BOM** cập nhật danh sách đang soạn; **Lưu BOM** mới lưu các thay đổi vào hệ thống.
|
||||
|
||||
**Quy tắc nghiệp vụ:** BOM chỉ mô tả thành phần của robot. Chọn tài sản chỉ sao chép tên/model; số lượng BOM tự nhập, không lấy từ kho, không bị giới hạn bởi tồn kho và không trừ số lượng tài sản. Vật tư bên ngoài được thêm trực tiếp mà không cần tạo trong kho trước.
|
||||
|
||||
Tên vật tư là trường bắt buộc. Model, đơn vị, nguồn và ghi chú là tùy chọn. Nếu dùng đơn vị cái/bộ, số lượng cần là số nguyên; đơn vị đo như m/kg/lít hoặc để trống cho phép tối đa 4 chữ số thập phân. Mỗi BOM tối đa 500 dòng; số lượng mỗi dòng lớn hơn 0 và tối đa 100.000.
|
||||
|
||||
## Phiên bản
|
||||
|
||||
- **BOM mới** tạo phiên bản nháp trống cho model đang chọn.
|
||||
- **Sao chép BOM** tạo phiên bản nháp tiếp theo từ phiên bản đang xem. Thay đổi chưa lưu được lưu trước khi sao chép.
|
||||
- **Phát hành** mở hộp xác nhận với model robot, phiên bản và số dòng vật tư. Chọn **Quay lại** để tiếp tục sửa, hoặc **Phát hành BOM** để lưu các thay đổi và khóa phiên bản hiện tại. Có thể bấm Escape để đóng xác nhận. Muốn sửa tiếp, sao chép thành bản nháp mới.
|
||||
- Dùng bộ chọn phiên bản hoặc tab **Lịch sử phiên bản** để xem lại.
|
||||
- **Xóa BOM** xóa vĩnh viễn phiên bản đang chọn (bản nháp hoặc đã phát hành) cùng các dòng vật tư của phiên bản đó. Chỉ Admin/Asset được xóa. Hộp xác nhận hiển thị model, phiên bản và số dòng đã lưu; bấm **Hủy** hoặc Escape để giữ BOM. Các thay đổi chưa lưu của phiên bản bị xóa sẽ bị bỏ. Các phiên bản khác, robot và tài sản trong kho vẫn giữ nguyên. Sau khi xóa, hệ thống chọn phiên bản còn lại mới nhất; nếu đã xóa hết, có thể tạo BOM đầu tiên lại.
|
||||
- Model và BOM cũ vẫn xem/sao chép được sau khi robot cuối cùng của model đó bị xóa hoặc đổi model.
|
||||
- Khi hai người cùng sửa, hệ thống từ chối thao tác lưu/xóa trên phiên bản dữ liệu đã cũ và yêu cầu tải lại để tránh ghi đè hoặc xóa thay đổi của người khác.
|
||||
|
||||
## Excel
|
||||
|
||||
Dùng **Xuất Excel** để lấy file mẫu có sheet `BOM` và sheet thông tin phiên bản.
|
||||
|
||||
| Cột trên sheet BOM | Nội dung |
|
||||
| --- | --- |
|
||||
| Tên vật tư | Tên thành phần bắt buộc; có thể chưa có trong danh sách tài sản |
|
||||
| Model | Model / quy cách tùy chọn |
|
||||
| Số lượng | Số lượng trong BOM, tự nhập; mặc định 1 |
|
||||
| ĐVT | Đơn vị tùy chọn |
|
||||
| Nguồn | Link mua hàng hoặc thông tin nhà sản xuất / nhà cung cấp |
|
||||
| Ghi chú | Ghi chú tùy chọn |
|
||||
|
||||
**Nhập Excel** nhận `.xls`/`.xlsx`, tối đa 10 MB và 500 dòng. Hệ thống kiểm tra toàn bộ file trước khi thay danh sách trên màn hình; file sai giữ nguyên BOM hiện tại. Sau khi nhập, bấm **Lưu thay đổi** để lưu vào database. Có thể xuất bản nháp trống để lấy tên các cột.
|
||||
|
||||
## Thông tin tài sản và nguồn
|
||||
|
||||
Danh sách chọn tài sản cung cấp tên, mã, model và đơn vị để nhập nhanh. Không hiển thị hoặc lấy số lượng kho. Tài sản hết hàng vẫn chọn được. Sau khi thêm, BOM lưu riêng mô tả thành phần; đổi/xóa tài sản không làm thay đổi BOM đã lưu.
|
||||
|
||||
Nguồn nhận cả URL HTTP/HTTPS và văn bản tự do. URL được hiển thị thành liên kết mở trong tab mới; thông tin nhà sản xuất hiển thị nguyên văn. Nguồn được giữ khi lưu, tải lại, sao chép phiên bản và nhập/xuất Excel.
|
||||
|
||||
## Triển khai và kiểm tra
|
||||
|
||||
Backend tự tạo/cập nhật bảng `RobotBomRevisions` và `RobotBomLines` khi khởi động. BOM cũ giữ nguyên tên/model, số lượng, mô tả và phiên bản; liên kết định danh kho cũ được gỡ và bổ sung cột `SourceInfo`. Chạy lại không làm mất BOM đã lưu. Không cần cài dependency mới. Các API `/api/robot-boms` dùng phiên đăng nhập và phân quyền hiện tại.
|
||||
|
||||
- `npm test`: kiểm tra hồi quy và nghiệp vụ BOM.
|
||||
- `ACCMANAGER_BOM_SQL_TEST=1 node --test backend/robot-bom-sql.test.js`: kiểm tra trên database thử riêng, tự tạo/xóa trên SQL Server cấu hình trong `.env`.
|
||||
- `ACCMANAGER_BOM_BROWSER_TEST=1 node --test backend/robot-bom-browser.test.js`: kiểm tra giao diện bằng Chrome với dữ liệu thử trong bộ nhớ. Ảnh kiểm tra lưu tại `output/bom-robot/`.
|
||||
@@ -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.
|
||||
|
||||
48
public/css/announcements.css
Normal file
48
public/css/announcements.css
Normal 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; }
|
||||
}
|
||||
364
public/css/asset-actions.css
Normal file
364
public/css/asset-actions.css
Normal 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
139
public/css/dashboard.css
Normal 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
@@ -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 {
|
||||
|
||||
1173
public/js/app.js
1173
public/js/app.js
File diff suppressed because it is too large
Load Diff
@@ -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>
|
||||
|
||||
|
||||
@@ -251,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 -->
|
||||
@@ -286,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">
|
||||
@@ -308,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>
|
||||
@@ -364,11 +366,22 @@
|
||||
<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>
|
||||
@@ -437,6 +450,6 @@
|
||||
|
||||
<script src="../js/document-formats.js?v=20261019-1"></script>
|
||||
<script src="../js/robot-bom.js?v=20261102-5"></script>
|
||||
<script src="../js/app.js?v=20261102-2"></script>
|
||||
<script src="../js/app.js?v=20261111-1"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user