359 lines
33 KiB
JavaScript
359 lines
33 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 { createBomFixture } = require('./robot-bom-test-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 checks robot confirmations and BOM forms with independent quantities and supplier sources', {
|
|
skip: process.env.ACCMANAGER_BOM_BROWSER_TEST !== '1' ? 'Set ACCMANAGER_BOM_BROWSER_TEST=1 for the isolated Chrome UI check' : false,
|
|
timeout: 90000
|
|
}, async () => {
|
|
const root = path.resolve(__dirname, '..');
|
|
const output = path.join(root, 'output/bom-robot'); fs.mkdirSync(output, { recursive: true });
|
|
let forceSaveFailure = false;
|
|
let forceBomDeleteFailure = false;
|
|
let failRobotDelete = false;
|
|
const robotDeleteRequests = [];
|
|
const fixture = createBomFixture({ failQuery: query => (forceSaveFailure && query.includes('INSERT dbo.RobotBomLines'))
|
|
|| (forceBomDeleteFailure && query.includes('DELETE FROM dbo.RobotBomRevisions')) });
|
|
const review = fixture.app;
|
|
const reviewRobots = fixture.state.models.map(robot => ({ ...robot, Name: 'TESTBOM', DocumentCount: 2 }));
|
|
review.get('/api/auth/session', (_req, res) => res.json({ success: true, user: { UserId: 1, Username: 'bom-review', FullName: 'Kiểm tra BOM', Role: 'admin' } }));
|
|
review.get('/api/robots/types', (_req, res) => res.json({ success: true, data: [{ TypeId: 1, Name: 'AMR' }] }));
|
|
review.get('/api/robots', (_req, res) => res.json({ success: true, data: reviewRobots }));
|
|
review.delete('/api/robots/:id', (req, res) => {
|
|
robotDeleteRequests.push(Number(req.params.id));
|
|
if (failRobotDelete) return res.status(500).json({ success: false, message: 'Không thể xóa robot thử nghiệm. Hãy thử lại.' });
|
|
const index = reviewRobots.findIndex(robot => robot.RobotId === Number(req.params.id));
|
|
if (index < 0) return res.status(404).json({ success: false, message: 'Robot không tồn tại' });
|
|
reviewRobots.splice(index, 1); res.json({ success: true, message: 'Đã xóa robot thử nghiệm' });
|
|
});
|
|
review.use('/api', (_req, res) => res.json({ success: true, data: [], unreadCount: 0, pagination: { total: 0, totalPages: 1 } }));
|
|
review.get('/test-xlsx.js', (_req, res) => res.sendFile(require.resolve('xlsx/dist/xlsx.full.min.js')));
|
|
review.get('/test-notiflix.js', (_req, res) => res.type('js').send('window.Notiflix={Notify:{init(){},success(){},failure(){},warning(){}}};'));
|
|
review.get('/pages/index.html', (_req, res) => {
|
|
const source = 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');
|
|
res.type('html').send(source);
|
|
});
|
|
review.use(require('express').static(path.join(root, 'public')));
|
|
const server = review.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 chromePath = process.env.ACCMANAGER_TEST_CHROME || 'C:/Program Files/Google/Chrome/Application/chrome.exe';
|
|
// Keep browser-managed extension files outside Node's automatic test discovery.
|
|
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'accmanager-bom-chrome-'));
|
|
const chrome = spawn(chromePath, ['--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('Page.addScriptToEvaluateOnNewDocument', { source: 'window.confirm=()=>true;window.alert=()=>{};' });
|
|
await client.send('Emulation.setDeviceMetricsOverride', { width: 1600, height: 1050, deviceScaleFactor: 1, mobile: false });
|
|
await client.send('Page.navigate', { url: `${origin}/pages/index.html#robot-bom` });
|
|
await client.until('typeof app !== "undefined" && app?.robotBom?.models.length === 1 && !app.robotBom.busy');
|
|
const prepareNotifications = () => client.evaluate('window.bomMessages=[]; app.notifyFailure=app.notifyWarning=app.notifySuccess=(message)=>bomMessages.push(message); true');
|
|
await prepareNotifications();
|
|
await client.evaluate('document.querySelector("[data-bom-action=new]").click()');
|
|
await client.until('app.robotBom.header?.BomId && !app.robotBom.busy');
|
|
const entryGeometry = () => client.evaluate(`(() => {
|
|
const dialog=document.querySelector('#bomComponentDialog');
|
|
const rect=element=>{const value=element.getBoundingClientRect();return [value.x,value.y,value.width,value.height].map(number=>Math.round(number*100)/100)};
|
|
return {dialog:rect(dialog),name:rect(dialog.querySelector('[name=name]')),footer:rect(dialog.querySelector('.bom-dialog-footer')),scroll:dialog.querySelector('.bom-material-layout').scrollTop};
|
|
})()`);
|
|
const add = async ({ id = null, name, model, unit, quantity, sourceInfo = '', screenshot = false }) => {
|
|
await client.evaluate('document.querySelector("[data-bom-action=add]").click()');
|
|
const opened = await entryGeometry();
|
|
if (id !== null) {
|
|
await client.until('document.querySelectorAll("#bomComponentDialog [name=assetChoice]").length>0');
|
|
await client.evaluate(`document.querySelector('#bomComponentDialog input[name=assetChoice][value="${id}"]').click()`);
|
|
assert.equal(await client.evaluate('document.querySelector("#bomMaterialForm").elements.quantity.value'), '1');
|
|
assert.equal(await client.evaluate('document.querySelector("#bomMaterialForm").elements.name.value'), 'Động cơ servo 400W');
|
|
assert.equal(await client.evaluate('document.querySelector("#bomMaterialForm").elements.model.value'), 'SV-400');
|
|
assert.equal(await client.evaluate('/Tồn|Khả dụng/.test(document.querySelector("#bomAssetResults").innerText)'), false);
|
|
} else await client.evaluate('document.querySelector("[data-bom-mode=manual]").click()');
|
|
await client.evaluate(`(() => { const form = document.querySelector('#bomMaterialForm'); ${name === undefined ? '' : `form.elements.name.value=${JSON.stringify(name)};`} ${model === undefined ? '' : `form.elements.model.value=${JSON.stringify(model)};`} ${unit === undefined ? '' : `form.elements.unit.value=${JSON.stringify(unit)};`} form.elements.quantity.value=${JSON.stringify(String(quantity))}; form.elements.sourceInfo.value=${JSON.stringify(sourceInfo)}; return true; })()`);
|
|
const entered = await client.evaluate('Array.from(document.querySelector("#bomMaterialForm").elements).filter(element=>["name","model","quantity","unit","sourceInfo","notes"].includes(element.name)).map(element=>[element.name,element.value])');
|
|
for (const mode of ['manual', 'asset', 'manual', 'asset', id === null ? 'manual' : 'asset']) {
|
|
await client.evaluate(`(() => { const button=document.querySelector('[data-bom-mode="${mode}"]');button.focus({preventScroll:true});button.click();return true; })()`);
|
|
await client.evaluate('new Promise(resolve=>requestAnimationFrame(()=>resolve(true)))');
|
|
assert.deepEqual(await entryGeometry(), opened, 'switching modes must not move or resize the dialog/form/footer');
|
|
}
|
|
assert.deepEqual(await client.evaluate('Array.from(document.querySelector("#bomMaterialForm").elements).filter(element=>["name","model","quantity","unit","sourceInfo","notes"].includes(element.name)).map(element=>[element.name,element.value])'), entered);
|
|
if (screenshot) {
|
|
const shot = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
|
|
fs.writeFileSync(path.join(output, 'bom-component-picker.png'), Buffer.from(shot.data, 'base64'));
|
|
}
|
|
if (id === null && name === 'Khung gia công bên ngoài') {
|
|
const shot = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
|
|
fs.writeFileSync(path.join(output, 'bom-external-entry.png'), Buffer.from(shot.data, 'base64'));
|
|
}
|
|
await client.evaluate('(() => { const form=document.querySelector("#bomMaterialForm"); form.requestSubmit(form.querySelector("button[value=done]")); return true; })()');
|
|
await client.until('!document.querySelector("#bomComponentDialog")');
|
|
};
|
|
await add({ id: 1, quantity: 200, sourceInfo: 'https://example.com/servo', screenshot: true });
|
|
await add({ name: 'Khung gia công bên ngoài', model: 'CUSTOM-01', quantity: 12, sourceInfo: 'Nhà sản xuất: Cơ khí ABC' });
|
|
await add({ name: 'Cáp nguồn bên ngoài', model: 'CB-NEW', unit: 'm', quantity: 1.25, sourceInfo: 'https://example.com/cable' });
|
|
assert.equal(await client.evaluate('app.robotBom.lines.length'), 3);
|
|
assert.equal(await client.evaluate('document.querySelector("#bomRobotCount")===null && document.querySelector("[data-bom-stock]")===null'), true);
|
|
assert.equal(await client.evaluate('app.robotBom.sourceHtml("javascript:alert(1)").includes("<a")'), false);
|
|
assert.equal(await client.evaluate('document.querySelector(".bom-source-link").getAttribute("href")'), 'https://example.com/servo');
|
|
await client.evaluate('document.querySelector("[data-bom-action=save]").click()');
|
|
await client.until('!app.robotBom.busy && !app.robotBom.dirty');
|
|
await client.evaluate('(() => { const input=document.querySelector("[data-bom-quantity]" );input.value="0.5";input.dispatchEvent(new Event("change",{bubbles:true})); })()');
|
|
assert.equal(await client.evaluate('app.robotBom.lines[0].Quantity'), 200);
|
|
assert.match(await client.evaluate('bomMessages.at(-1)'), /số lượng nguyên/);
|
|
await client.evaluate('window.XLSX.writeFile=(book,name)=>{window.bomExport={book,name}};document.querySelector("[data-bom-action=export]").click()');
|
|
assert.equal(await client.evaluate('bomExport.name'), 'BOM-AMR-500-v1.xlsx');
|
|
assert.equal(await client.evaluate('XLSX.utils.sheet_to_json(bomExport.book.Sheets.BOM).length'), 3);
|
|
await client.evaluate('(async()=>{const bytes=XLSX.write(bomExport.book,{bookType:"xlsx",type:"array"});await app.robotBom.importWorkbook(new File([bytes],"roundtrip.xlsx"));return true})()');
|
|
assert.equal(await client.evaluate('app.robotBom.lines[2].Quantity'), 1.25);
|
|
assert.equal(await client.evaluate('app.robotBom.lines[1].SourceInfo'), 'Nhà sản xuất: Cơ khí ABC');
|
|
await client.evaluate('document.querySelector("[data-bom-action=save]").click()');
|
|
await client.until('!app.robotBom.busy && !app.robotBom.dirty');
|
|
const screenshot = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
|
|
fs.writeFileSync(path.join(output, 'bom-desktop.png'), Buffer.from(screenshot.data, 'base64'));
|
|
await client.send('Page.reload'); await delay(300);
|
|
await client.until('typeof app !== "undefined" && app?.robotBom?.lines.length===3 && !app.robotBom.busy');
|
|
await prepareNotifications();
|
|
assert.equal(await client.evaluate('app.robotBom.lines[0].SourceInfo'), 'https://example.com/servo');
|
|
fixture.state.catalog = [];
|
|
await client.evaluate('window.nativeConfirmCalls=0;window.confirm=()=>{nativeConfirmCalls++;return true};document.querySelector("[data-bom-action=publish]").click()');
|
|
await client.until('document.querySelector("#bomPublishDialog")?.open');
|
|
assert.equal(await client.evaluate('app.robotBom.header.Status'), 'draft');
|
|
await client.evaluate('document.querySelector("#bomPublishDialog .bom-dialog-footer [data-bom-publish-cancel]").click()');
|
|
await client.until('!document.querySelector("#bomPublishDialog")');
|
|
assert.equal(await client.evaluate('app.robotBom.header.Status'), 'draft');
|
|
await client.evaluate('document.querySelector("[data-bom-action=publish]").click()');
|
|
await client.until('document.querySelector("#bomPublishDialog")?.open');
|
|
await client.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
|
|
await client.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
|
|
await client.until('!document.querySelector("#bomPublishDialog")');
|
|
assert.equal(await client.evaluate('app.robotBom.header.Status'), 'draft');
|
|
await client.evaluate('document.querySelector("[data-bom-action=publish]").click();document.querySelector("[data-bom-action=publish]").click()');
|
|
await client.until('document.querySelector("#bomPublishDialog")?.open');
|
|
assert.equal(await client.evaluate('document.querySelectorAll("#bomPublishDialog").length'), 1);
|
|
const confirmation = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
|
|
fs.writeFileSync(path.join(output, 'bom-publish-confirmation.png'), Buffer.from(confirmation.data, 'base64'));
|
|
await client.evaluate('document.querySelector("[data-bom-publish-confirm]").click()');
|
|
await client.until('app.robotBom.header?.Status==="released" && !app.robotBom.busy');
|
|
assert.equal(await client.evaluate('nativeConfirmCalls'), 0);
|
|
assert.equal(fixture.queries.filter(({ query }) => query.includes("Status = 'released'")).length, 1);
|
|
assert.equal(await client.evaluate('document.querySelector("[data-bom-action=add]")===null'), true);
|
|
await client.evaluate('document.querySelector("[data-bom-action=copy]").click()');
|
|
await client.until('app.robotBom.header?.Revision===2 && !app.robotBom.busy');
|
|
assert.equal(await client.evaluate('app.robotBom.lines.length'), 3);
|
|
await client.evaluate('(() => { const input=document.querySelector("[data-bom-quantity]");input.value="3";input.dispatchEvent(new Event("change",{bubbles:true}));window.confirm=()=>false;location.hash="#robots"; })()');
|
|
await client.until('location.hash==="#robot-bom"');
|
|
assert.equal(await client.evaluate('app.robotBom.dirty && app.currentPage==="robot-bom"'), true);
|
|
forceSaveFailure = true;
|
|
await client.evaluate('window.confirm=()=>true;document.querySelector("[data-bom-action=save]").click()');
|
|
await client.until('!app.robotBom.busy');
|
|
assert.equal(await client.evaluate('app.robotBom.dirty && app.robotBom.lines[0].Quantity===3'), true);
|
|
forceSaveFailure = false;
|
|
await client.evaluate('document.querySelector("[data-bom-action=save]").click()');
|
|
await client.until('!app.robotBom.busy && !app.robotBom.dirty');
|
|
assert.equal(fixture.state.lines.find(line => line.BomId === 1).Quantity, 200);
|
|
assert.equal(fixture.state.lines.find(line => line.BomId === 1).SourceId, null);
|
|
await client.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
|
|
await delay(200);
|
|
assert.equal(await client.evaluate('document.documentElement.scrollWidth<=390'), true);
|
|
const mobile = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
|
|
fs.writeFileSync(path.join(output, 'bom-mobile.png'), Buffer.from(mobile.data, 'base64'));
|
|
await client.evaluate('document.querySelector("[data-bom-action=add]").click()');
|
|
assert.equal(await client.evaluate('document.querySelector("#bomComponentDialog").getBoundingClientRect().width<=390'), true);
|
|
const mobileGeometry = await entryGeometry();
|
|
for (const mode of ['manual', 'asset', 'manual']) {
|
|
await client.evaluate(`document.querySelector('[data-bom-mode="${mode}"]').click()`);
|
|
assert.deepEqual(await entryGeometry(), mobileGeometry, 'mobile mode switches must retain geometry and scroll');
|
|
}
|
|
assert.equal(await client.evaluate('document.querySelector("#bomComponentDialog .bom-dialog-footer").getBoundingClientRect().bottom<=844'), true);
|
|
const mobileEntry = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
|
|
fs.writeFileSync(path.join(output, 'bom-external-mobile.png'), Buffer.from(mobileEntry.data, 'base64'));
|
|
await client.evaluate('document.querySelector("[data-bom-close]").click();app.currentUser.Role="user";app.robotBom.render()');
|
|
assert.equal(await client.evaluate('document.querySelector("[data-bom-action=save]")===null && document.querySelector("[data-bom-action=add]")===null && document.querySelector("[data-bom-action=delete]")===null'), true);
|
|
fixture.state.models.push({ RobotId: 2, Model: 'AMR-500', TypeId: 2, Type: 'AMR khác cấu hình', Name: 'Robot khác' });
|
|
await client.evaluate('app.currentUser.Role="admin";app.robotBom.mount(document.getElementById("mainContent"),{Model:"AMR-500",TypeId:2})');
|
|
assert.equal(await client.evaluate('app.robotBom.selectedModel().TypeId'), 2);
|
|
assert.equal(await client.evaluate('app.robotBom.header===null'), true);
|
|
assert.equal(fixture.state.headers.length, 2);
|
|
await client.send('Emulation.setDeviceMetricsOverride', { width: 1600, height: 1050, deviceScaleFactor: 1, mobile: false });
|
|
await client.evaluate('window.nativeConfirmCalls=0;window.confirm=()=>{nativeConfirmCalls++;return true};location.hash="#robots"');
|
|
await client.until('app.currentPage==="robots" && document.querySelector("[data-robot-action=delete]")');
|
|
const openRobotDelete = async () => {
|
|
await client.evaluate('document.querySelector("[data-robot-action=delete]").click()');
|
|
await client.until('document.querySelector("#robotDeleteDialog")?.open');
|
|
assert.equal(await client.evaluate('document.querySelector("#robotDeleteDialog .robot-delete-name").textContent'), 'TESTBOM');
|
|
assert.equal(await client.evaluate('document.querySelector("#robotDeleteDialog").innerText.includes("AMR-500")'), true);
|
|
};
|
|
const waitRobotDeleteClosed = () => client.until('!document.querySelector("#robotDeleteDialog") && !app.robotDeletionPending');
|
|
await openRobotDelete();
|
|
const robotConfirmation = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
|
|
fs.writeFileSync(path.join(output, 'robot-delete-confirmation.png'), Buffer.from(robotConfirmation.data, 'base64'));
|
|
await client.evaluate('document.querySelector("#robotDeleteDialog .bom-dialog-footer [data-cancel-robot-delete]").click()');
|
|
await waitRobotDeleteClosed(); assert.equal(robotDeleteRequests.length, 0);
|
|
await openRobotDelete();
|
|
await client.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
|
|
await client.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
|
|
await waitRobotDeleteClosed(); assert.equal(robotDeleteRequests.length, 0);
|
|
await openRobotDelete();
|
|
await client.evaluate('document.querySelector("#robotDeleteDialog .bom-dialog-header [data-cancel-robot-delete]").click()');
|
|
await waitRobotDeleteClosed(); assert.equal(robotDeleteRequests.length, 0);
|
|
await openRobotDelete(); await client.evaluate('location.hash="#robot-types"');
|
|
await waitRobotDeleteClosed(); assert.equal(robotDeleteRequests.length, 0);
|
|
await client.until('app.currentPage==="robot-types"');
|
|
await client.evaluate('document.querySelector("[data-robot-type-action=delete]").click()');
|
|
await client.until('document.querySelector("#robotDeleteDialog")?.open');
|
|
assert.equal(await client.evaluate('document.querySelector("#robotDeleteTitle").textContent'), 'Xóa thể loại robot?');
|
|
await client.evaluate('document.querySelector("#robotDeleteDialog [data-cancel-robot-delete]").click()');
|
|
await waitRobotDeleteClosed();
|
|
await client.evaluate('location.hash="#robots"');
|
|
await client.until('app.currentPage==="robots"');
|
|
await client.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
|
|
await openRobotDelete();
|
|
assert.equal(await client.evaluate('document.querySelector("#robotDeleteDialog").getBoundingClientRect().width<=390 && document.querySelector("#robotDeleteDialog .bom-dialog-footer").getBoundingClientRect().bottom<=844'), true);
|
|
const robotMobile = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
|
|
fs.writeFileSync(path.join(output, 'robot-delete-mobile.png'), Buffer.from(robotMobile.data, 'base64'));
|
|
await client.evaluate('document.querySelector("#robotDeleteDialog [data-cancel-robot-delete]").click()');
|
|
await waitRobotDeleteClosed();
|
|
await client.send('Emulation.setDeviceMetricsOverride', { width: 1600, height: 1050, deviceScaleFactor: 1, mobile: false });
|
|
failRobotDelete = true;
|
|
await openRobotDelete(); await client.evaluate('document.querySelector("[data-confirm-robot-delete]").click()');
|
|
await waitRobotDeleteClosed();
|
|
assert.equal(robotDeleteRequests.length, 1); assert.equal(reviewRobots.length, 1);
|
|
assert.match(await client.evaluate('bomMessages.at(-1)'), /Không thể xóa robot thử nghiệm/);
|
|
failRobotDelete = false;
|
|
await client.evaluate('app.deleteRobot(1);app.deleteRobot(1);true');
|
|
await client.until('document.querySelector("#robotDeleteDialog")?.open');
|
|
assert.equal(await client.evaluate('document.querySelectorAll("#robotDeleteDialog").length'), 1);
|
|
await client.evaluate('document.querySelector("[data-confirm-robot-delete]").click()');
|
|
await waitRobotDeleteClosed();
|
|
assert.equal(robotDeleteRequests.length, 2); assert.equal(reviewRobots.length, 0);
|
|
assert.equal(await client.evaluate('app.robots.length'), 0);
|
|
assert.equal(await client.evaluate('nativeConfirmCalls'), 0);
|
|
assert.equal(fixture.state.headers.length, 2);
|
|
// Delete only the selected revision, with styled confirmation and no implicit save.
|
|
await client.evaluate('location.hash="#robot-bom"');
|
|
await client.until('app.currentPage==="robot-bom" && !app.robotBom.busy');
|
|
await client.evaluate('app.robotBom.mount(document.getElementById("mainContent"),{Model:"AMR-500",TypeId:1})');
|
|
await prepareNotifications();
|
|
const markBomDirty = () => client.evaluate('(() => { const input=document.querySelector("[data-bom-quantity]");input.value="7";input.dispatchEvent(new Event("change",{bubbles:true}));return true; })()');
|
|
const openBomDelete = async () => {
|
|
await client.evaluate('document.querySelector("[data-bom-action=delete]").click()');
|
|
await client.until('document.querySelector("#bomDeleteDialog")?.open');
|
|
};
|
|
const bomDeleteCount = () => fixture.queries.filter(({ query }) => query.includes('DELETE FROM dbo.RobotBomRevisions')).length;
|
|
await markBomDirty();
|
|
await openBomDelete();
|
|
assert.equal(await client.evaluate('document.querySelector("#bomDeleteDialog .bom-publish-summary").innerText.includes("AMR-500") && document.querySelector("#bomDeleteTitle").innerText.includes("v2")'), true);
|
|
assert.equal(await client.evaluate('document.querySelector("#bomDeleteDialog").innerText.includes("chưa lưu")'), true);
|
|
assert.equal(await client.evaluate('document.activeElement.matches(".bom-dialog-footer [data-bom-delete-cancel]")'), true);
|
|
await client.evaluate('document.querySelector("#bomDeleteDialog .bom-dialog-footer [data-bom-delete-cancel]").click()');
|
|
await client.until('!document.querySelector("#bomDeleteDialog")');
|
|
assert.equal(await client.evaluate('app.robotBom.dirty && app.robotBom.lines[0].Quantity===7'), true);
|
|
await openBomDelete();
|
|
await client.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
|
|
await client.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
|
|
await client.until('!document.querySelector("#bomDeleteDialog")');
|
|
await openBomDelete();
|
|
await client.evaluate('document.querySelector("#bomDeleteDialog .bom-dialog-header [data-bom-delete-cancel]").click()');
|
|
await client.until('!document.querySelector("#bomDeleteDialog")');
|
|
await openBomDelete();
|
|
await client.evaluate('app.robotBom.unmount()');
|
|
await client.until('!document.querySelector("#bomDeleteDialog")');
|
|
assert.equal(bomDeleteCount(), 0); assert.equal(fixture.state.headers.length, 2);
|
|
// A stale client cannot delete a newer saved version.
|
|
const draft = fixture.state.headers.find(item => item.Revision === 2);
|
|
draft.LockVersion++;
|
|
await openBomDelete();
|
|
await client.evaluate('document.querySelector("[data-bom-delete-confirm]").click()');
|
|
await client.until('!app.robotBom.busy && !document.querySelector("#bomDeleteDialog")');
|
|
assert.equal(bomDeleteCount(), 0); assert.equal(fixture.state.headers.length, 2);
|
|
assert.equal(await client.evaluate('app.robotBom.dirty && app.robotBom.lines[0].Quantity===7'), true);
|
|
assert.match(await client.evaluate('bomMessages.at(-1)'), /tải lại trước khi xóa/);
|
|
await client.evaluate('app.robotBom.mount(document.getElementById("mainContent"),{Model:"AMR-500",TypeId:1})');
|
|
await markBomDirty();
|
|
forceBomDeleteFailure = true;
|
|
await openBomDelete();
|
|
const deleteConfirmation = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
|
|
fs.writeFileSync(path.join(output, 'bom-delete-confirmation.png'), Buffer.from(deleteConfirmation.data, 'base64'));
|
|
await client.evaluate('document.querySelector("[data-bom-delete-confirm]").click()');
|
|
await client.until('!app.robotBom.busy && !document.querySelector("#bomDeleteDialog")');
|
|
assert.equal(bomDeleteCount(), 1); assert.equal(fixture.state.headers.length, 2);
|
|
assert.equal(fixture.state.lines.filter(line => line.BomId === draft.BomId).length, 3);
|
|
assert.equal(await client.evaluate('app.robotBom.dirty && app.robotBom.lines[0].Quantity===7'), true);
|
|
forceBomDeleteFailure = false;
|
|
await client.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
|
|
await openBomDelete();
|
|
await client.evaluate('document.querySelector("[data-bom-action=delete]").click()');
|
|
assert.equal(await client.evaluate('document.querySelectorAll("#bomDeleteDialog").length'), 1);
|
|
assert.equal(await client.evaluate('document.querySelector("#bomDeleteDialog").getBoundingClientRect().width<=390 && document.querySelector("#bomDeleteDialog .bom-dialog-footer").getBoundingClientRect().bottom<=844'), true);
|
|
const deleteMobile = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
|
|
fs.writeFileSync(path.join(output, 'bom-delete-mobile.png'), Buffer.from(deleteMobile.data, 'base64'));
|
|
await client.evaluate('document.querySelector("[data-bom-delete-confirm]").click();document.querySelector("[data-bom-delete-confirm]")?.click()');
|
|
await client.until('!app.robotBom.busy && app.robotBom.header?.Revision===1');
|
|
assert.equal(bomDeleteCount(), 2); assert.equal(fixture.state.headers.length, 1);
|
|
assert.equal(await client.evaluate('!app.robotBom.dirty && app.robotBom.header.Status==="released" && app.robotBom.revisions.length===1'), true);
|
|
assert.equal(fixture.state.lines[0].Quantity, 200);
|
|
// Deleting the last historical version refreshes the model picker too.
|
|
fixture.state.models = fixture.state.models.filter(item => item.TypeId !== 1);
|
|
await openBomDelete();
|
|
await client.evaluate('document.querySelector("[data-bom-delete-confirm]").click()');
|
|
await client.until('!app.robotBom.busy && app.robotBom.header===null');
|
|
assert.equal(bomDeleteCount(), 3); assert.equal(fixture.state.headers.length, 0); assert.equal(fixture.state.lines.length, 0);
|
|
assert.equal(await client.evaluate('app.robotBom.models.length===1 && app.robotBom.selectedModel().TypeId===2 && app.robotBom.revisions.length===0'), true);
|
|
assert.equal(await client.evaluate('document.querySelector("[data-bom-action=delete]")===null && document.querySelector("#bomRevision").disabled'), true);
|
|
assert.equal(await client.evaluate('nativeConfirmCalls'), 0);
|
|
assert.equal(fixture.queries.some(({ query }) => /(?:UPDATE|INSERT|DELETE).*Inventory/i.test(query)), false);
|
|
assert.deepEqual(client.errors, []);
|
|
fs.writeFileSync(path.join(output, 'verification.json'), JSON.stringify({ passed: true, checks: ['BOM draft/released deletion', 'BOM delete cancel/Escape/close/unmount', 'stale BOM deletion rejected', 'BOM deletion rollback and retry', 'BOM dirty state preserved on failure and discarded on success', 'double click deletes one BOM', 'remaining revisions and orphaned models refresh', 'styled robot/type deletion confirmations', 'cancel/Escape/close/navigation send no delete', 'failed robot deletion supports retry', 'double click deletes once', 'mobile deletion confirmation', 'stable entry mode geometry and retained fields', 'desktop/mobile mode switching', 'custom publication confirmation', 'cancel and Escape preserve draft', 'double click publishes once', 'asset name/model picker', 'external components', 'BOM quantity independent of stock', 'supplier URL/text', 'safe source links', 'Excel export/import with sources', 'save/reload', 'publish/copy with no inventory', 'mobile overflow', 'viewer controls'], screenshots: ['bom-delete-confirmation.png', 'bom-delete-mobile.png', 'bom-desktop.png', 'bom-component-picker.png', 'bom-external-entry.png', 'bom-publish-confirmation.png', 'bom-mobile.png', 'bom-external-mobile.png', 'robot-delete-confirmation.png', 'robot-delete-mobile.png'] }, null, 2));
|
|
} finally {
|
|
if (client) { try { await client.send('Browser.close'); } catch {} client.socket.close(); }
|
|
chrome.kill();
|
|
if (chrome.exitCode === null) await Promise.race([new Promise(resolve => chrome.once('exit', resolve)), delay(2000)]);
|
|
const resolved = path.resolve(profile);
|
|
if (path.dirname(resolved) === path.resolve(os.tmpdir()) && path.basename(resolved).startsWith('accmanager-bom-chrome-')) {
|
|
fs.rmSync(resolved, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
|
}
|
|
server.closeAllConnections(); await new Promise(resolve => server.close(resolve));
|
|
}
|
|
});
|