157 lines
11 KiB
JavaScript
157 lines
11 KiB
JavaScript
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');
|
|
});
|