132 lines
12 KiB
JavaScript
132 lines
12 KiB
JavaScript
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 submits project export proposals, approves/rejects, isolates creators and displays saved files 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.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")');
|
|
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.deepEqual(client.errors, []);
|
|
} finally {
|
|
if (client) client.socket.close();
|
|
chrome.kill();
|
|
await f.cleanup();
|
|
}
|
|
});
|