Files
ManagerAccount/backend/dashboard.test.js
2026-11-04 09:54:17 +07:00

132 lines
7.1 KiB
JavaScript

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