update export

This commit is contained in:
2026-11-11 10:48:31 +07:00
parent 00122e5b4a
commit 03a481f20d
7 changed files with 741 additions and 90 deletions

View File

@@ -37,7 +37,7 @@ class Browser {
}
}
test('Chrome submits project export proposals, approves/rejects, isolates creators and displays saved files on desktop/mobile', {
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 () => {
@@ -49,6 +49,9 @@ test('Chrome submits project export proposals, approves/rejects, isolates creato
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(){}}};'));
@@ -71,6 +74,7 @@ test('Chrome submits project export proposals, approves/rejects, isolates creato
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');
@@ -122,7 +126,57 @@ test('Chrome submits project export proposals, approves/rejects, isolates creato
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();

View File

@@ -1,8 +1,54 @@
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

View File

@@ -6,20 +6,26 @@ 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: '' } };
const requests = [], messages = [];
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' } }) }; } };
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 };
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 () => {
@@ -71,3 +77,80 @@ test('ordinary users cannot invoke the proposal decision UI', async () => {
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');
});