bom
This commit is contained in:
358
backend/robot-bom-browser.test.js
Normal file
358
backend/robot-bom-browser.test.js
Normal file
@@ -0,0 +1,358 @@
|
||||
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));
|
||||
}
|
||||
});
|
||||
69
backend/robot-bom-schema.sql
Normal file
69
backend/robot-bom-schema.sql
Normal file
@@ -0,0 +1,69 @@
|
||||
SET XACT_ABORT ON;
|
||||
BEGIN TRY
|
||||
BEGIN TRANSACTION;
|
||||
IF OBJECT_ID('dbo.RobotBomRevisions', 'U') IS NULL
|
||||
BEGIN
|
||||
CREATE TABLE dbo.RobotBomRevisions (
|
||||
BomId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
|
||||
RobotModel NVARCHAR(255) NOT NULL,
|
||||
RobotTypeId INT NOT NULL,
|
||||
Revision INT NOT NULL,
|
||||
Status VARCHAR(10) NOT NULL DEFAULT 'draft',
|
||||
LockVersion INT NOT NULL DEFAULT 1,
|
||||
CreatedBy INT NULL,
|
||||
CreatedDate DATETIME2 NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
|
||||
UpdatedDate DATETIME2 NOT NULL DEFAULT (DATEADD(HOUR, 7, SYSUTCDATETIME())),
|
||||
ReleasedDate DATETIME2 NULL,
|
||||
CONSTRAINT UQ_RobotBomRevisions_ModelRevision UNIQUE (RobotTypeId, RobotModel, Revision),
|
||||
CONSTRAINT CK_RobotBomRevisions_Status CHECK (Status IN ('draft', 'released')),
|
||||
CONSTRAINT FK_RobotBomRevisions_Type FOREIGN KEY (RobotTypeId) REFERENCES dbo.RobotTypes(TypeId),
|
||||
CONSTRAINT FK_RobotBomRevisions_User FOREIGN KEY (CreatedBy) REFERENCES dbo.Users(UserId) ON DELETE SET NULL
|
||||
);
|
||||
END;
|
||||
IF OBJECT_ID('dbo.RobotBomLines', 'U') IS NULL
|
||||
BEGIN
|
||||
CREATE TABLE dbo.RobotBomLines (
|
||||
LineId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
|
||||
BomId INT NOT NULL,
|
||||
SourceType VARCHAR(10) NOT NULL DEFAULT 'manual',
|
||||
SourceId INT NULL,
|
||||
Code NVARCHAR(100) NOT NULL,
|
||||
Name NVARCHAR(255) NOT NULL,
|
||||
Model NVARCHAR(255) NOT NULL,
|
||||
Unit NVARCHAR(50) NOT NULL,
|
||||
GroupName NVARCHAR(100) NOT NULL,
|
||||
Position NVARCHAR(150) NOT NULL DEFAULT '',
|
||||
Quantity DECIMAL(18,4) NOT NULL,
|
||||
Notes NVARCHAR(500) NOT NULL DEFAULT '',
|
||||
SourceInfo NVARCHAR(1000) NOT NULL DEFAULT '',
|
||||
SortOrder INT NOT NULL,
|
||||
CONSTRAINT FK_RobotBomLines_Revision FOREIGN KEY (BomId) REFERENCES dbo.RobotBomRevisions(BomId),
|
||||
CONSTRAINT CK_RobotBomLines_Source CHECK (SourceType = 'manual' AND SourceId IS NULL),
|
||||
CONSTRAINT CK_RobotBomLines_Quantity CHECK (Quantity > 0 AND Quantity <= 100000)
|
||||
);
|
||||
CREATE INDEX IX_RobotBomLines_BomId ON dbo.RobotBomLines(BomId, SortOrder);
|
||||
END;
|
||||
IF COL_LENGTH('dbo.RobotBomLines', 'SourceInfo') IS NULL
|
||||
ALTER TABLE dbo.RobotBomLines ADD SourceInfo NVARCHAR(1000) NOT NULL
|
||||
CONSTRAINT DF_RobotBomLines_SourceInfo DEFAULT '';
|
||||
-- Retain existing component descriptions and released versions while detaching
|
||||
-- the obsolete inventory references. Repeated startup leaves content intact.
|
||||
IF EXISTS (SELECT 1 FROM sys.check_constraints
|
||||
WHERE parent_object_id = OBJECT_ID('dbo.RobotBomLines')
|
||||
AND name = 'CK_RobotBomLines_Source' AND definition LIKE '%asset%')
|
||||
ALTER TABLE dbo.RobotBomLines DROP CONSTRAINT CK_RobotBomLines_Source;
|
||||
IF EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID('dbo.RobotBomLines')
|
||||
AND name = 'SourceId' AND is_nullable = 0)
|
||||
ALTER TABLE dbo.RobotBomLines ALTER COLUMN SourceId INT NULL;
|
||||
UPDATE dbo.RobotBomLines SET SourceType = 'manual', SourceId = NULL
|
||||
WHERE SourceType <> 'manual' OR SourceId IS NOT NULL;
|
||||
IF NOT EXISTS (SELECT 1 FROM sys.check_constraints WHERE parent_object_id = OBJECT_ID('dbo.RobotBomLines')
|
||||
AND name = 'CK_RobotBomLines_Source')
|
||||
ALTER TABLE dbo.RobotBomLines ADD CONSTRAINT CK_RobotBomLines_Source
|
||||
CHECK (SourceType = 'manual' AND SourceId IS NULL);
|
||||
COMMIT TRANSACTION;
|
||||
END TRY
|
||||
BEGIN CATCH
|
||||
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
|
||||
THROW;
|
||||
END CATCH;
|
||||
135
backend/robot-bom-sql.test.js
Normal file
135
backend/robot-bom-sql.test.js
Normal file
@@ -0,0 +1,135 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { randomUUID } = require('node:crypto');
|
||||
const express = require('express');
|
||||
const sql = require('mssql');
|
||||
const { ensureRobotBomSchema, createRobotBomRouter } = require('./robot-bom');
|
||||
|
||||
test('SQL Server migrates legacy BOMs, stores external parts and sources, and keeps quantities independent of inventory', {
|
||||
skip: process.env.ACCMANAGER_BOM_SQL_TEST !== '1' ? 'Set ACCMANAGER_BOM_SQL_TEST=1 to use a disposable database on the configured SQL Server' : false,
|
||||
timeout: 60000
|
||||
}, async () => {
|
||||
require('dotenv').config();
|
||||
const bool = (key, fallback) => process.env[key] === undefined ? fallback : /^(1|true|yes|on)$/i.test(process.env[key]);
|
||||
const database = `AccManagerBomTest_${randomUUID().replace(/-/g, '')}`;
|
||||
const config = { server: process.env.DB_SERVER || 'localhost', user: process.env.DB_USER || 'sa', password: process.env.DB_PASSWORD,
|
||||
database: 'master', options: { encrypt: bool('DB_ENCRYPT', false), trustServerCertificate: bool('DB_TRUST_CERTIFICATE', true), useUTC: false },
|
||||
pool: { min: 0, max: 5, idleTimeoutMillis: 1000 }, connectionTimeout: 15000, requestTimeout: 15000 };
|
||||
let admin, pool, server, created = false;
|
||||
try {
|
||||
admin = await new sql.ConnectionPool(config).connect();
|
||||
await admin.request().query(`CREATE DATABASE [${database}]`); created = true;
|
||||
pool = await new sql.ConnectionPool({ ...config, database }).connect();
|
||||
await pool.request().batch(`
|
||||
CREATE TABLE dbo.Users (UserId INT PRIMARY KEY); INSERT dbo.Users VALUES (1);
|
||||
CREATE TABLE dbo.RobotTypes (TypeId INT PRIMARY KEY, Name NVARCHAR(100)); INSERT dbo.RobotTypes VALUES (1, N'AMR');
|
||||
CREATE TABLE dbo.Robots (RobotId INT PRIMARY KEY, Name NVARCHAR(255), Model NVARCHAR(255), TypeId INT);
|
||||
INSERT dbo.Robots VALUES (1, N'Robot thử nghiệm', 'AMR-500', 1);
|
||||
CREATE TABLE dbo.AssetInventory (AssetId INT PRIMARY KEY, AssetCode NVARCHAR(100), AssetName NVARCHAR(255),
|
||||
Model NVARCHAR(255), Unit NVARCHAR(50), EndingBalance INT, Location NVARCHAR(150), IsArchived BIT);
|
||||
INSERT dbo.AssetInventory VALUES (1, 'LK-001', N'Servo', 'SV-400', N'cái', 8, N'Kho A', 0),
|
||||
(2, 'OLD', N'Archived', 'SV-400', N'cái', 100, N'Kho A', 1);
|
||||
CREATE TABLE dbo.ConsumableInventory (ConsumableId INT PRIMARY KEY, ConsumableCode NVARCHAR(100),
|
||||
ConsumableName NVARCHAR(255), Model NVARCHAR(255), Unit NVARCHAR(50), EndingBalance INT);
|
||||
INSERT dbo.ConsumableInventory VALUES (1, 'VT-001', N'Cáp', 'CB-2X2.5', 'm', 30);
|
||||
-- Simulate the earlier inventory-linked installation, including a released BOM.
|
||||
CREATE TABLE dbo.RobotBomRevisions (
|
||||
BomId INT IDENTITY PRIMARY KEY, RobotModel NVARCHAR(255) NOT NULL, RobotTypeId INT NOT NULL,
|
||||
Revision INT NOT NULL, Status VARCHAR(10) NOT NULL DEFAULT 'draft', LockVersion INT NOT NULL DEFAULT 1,
|
||||
CreatedBy INT NULL, CreatedDate DATETIME2 NOT NULL DEFAULT GETDATE(),
|
||||
UpdatedDate DATETIME2 NOT NULL DEFAULT GETDATE(), ReleasedDate DATETIME2 NULL,
|
||||
CONSTRAINT UQ_RobotBomRevisions_ModelRevision UNIQUE (RobotTypeId, RobotModel, Revision)
|
||||
);
|
||||
CREATE TABLE dbo.RobotBomLines (
|
||||
LineId INT IDENTITY PRIMARY KEY, BomId INT NOT NULL, SourceType VARCHAR(10) NOT NULL,
|
||||
SourceId INT NOT NULL, Code NVARCHAR(100) NOT NULL, Name NVARCHAR(255) NOT NULL,
|
||||
Model NVARCHAR(255) NOT NULL, Unit NVARCHAR(50) NOT NULL, GroupName NVARCHAR(100) NOT NULL,
|
||||
Position NVARCHAR(150) NOT NULL DEFAULT '', Quantity DECIMAL(18,4) NOT NULL,
|
||||
Notes NVARCHAR(500) NOT NULL DEFAULT '', SortOrder INT NOT NULL,
|
||||
CONSTRAINT CK_RobotBomLines_Source CHECK (SourceType IN ('asset', 'consumable')),
|
||||
CONSTRAINT FK_RobotBomLines_Revision FOREIGN KEY (BomId) REFERENCES dbo.RobotBomRevisions(BomId)
|
||||
);
|
||||
INSERT dbo.RobotBomRevisions (RobotModel, RobotTypeId, Revision, Status) VALUES ('AMR-500', 1, 1, 'released');
|
||||
INSERT dbo.RobotBomLines (BomId, SourceType, SourceId, Code, Name, Model, Unit, GroupName, Quantity, Notes, SortOrder)
|
||||
VALUES (1, 'asset', 1, 'LK-001', N'Servo cũ', 'SV-400', N'cái', N'Cơ khí', 2, N'Giữ nguyên mô tả', 0);
|
||||
`);
|
||||
await ensureRobotBomSchema(pool); await ensureRobotBomSchema(pool);
|
||||
const legacy = (await pool.request().query('SELECT * FROM dbo.RobotBomLines WHERE BomId = 1')).recordset[0];
|
||||
assert.equal(legacy.Name, 'Servo cũ'); assert.equal(legacy.Quantity, 2); assert.equal(legacy.Notes, 'Giữ nguyên mô tả');
|
||||
assert.equal(legacy.SourceType, 'manual'); assert.equal(legacy.SourceId, null); assert.equal(legacy.SourceInfo, '');
|
||||
assert.equal((await pool.request().query('SELECT Status FROM dbo.RobotBomRevisions WHERE BomId = 1')).recordset[0].Status, 'released');
|
||||
const app = express(); app.use(express.json());
|
||||
app.use((req, _res, next) => { req.user = { UserId: 1 }; next(); });
|
||||
app.use('/boms', createRobotBomRouter({ getPool: () => pool, sql, requireManage: (_req, _res, next) => next(),
|
||||
sendInternalError(res, error, message) { console.error('SQL BOM test:', error.message); return res.status(500).json({ success: false, message }); } }));
|
||||
server = app.listen(0, '127.0.0.1'); await new Promise(resolve => server.once('listening', resolve));
|
||||
const request = async (suffix = '', method = 'GET', body) => {
|
||||
const response = await fetch(`http://127.0.0.1:${server.address().port}/boms${suffix}`, { method,
|
||||
...(body === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) });
|
||||
return { status: response.status, ...(await response.json()) };
|
||||
};
|
||||
const catalog = await request('/catalog'); assert.equal(catalog.status, 200); assert.equal(catalog.data.length, 1);
|
||||
assert.deepEqual(Object.keys(catalog.data[0]).sort(), ['Code', 'Id', 'Model', 'Name', 'Unit']);
|
||||
const id = (await request('', 'POST', { robotId: 1 })).data.BomId;
|
||||
const lines = [
|
||||
{ name: 'Servo', model: 'SV-400', unit: 'cái', quantity: 30, sourceInfo: 'https://example.com/servo' },
|
||||
{ name: 'Khung gia công bên ngoài', model: 'CUSTOM-01', quantity: 2, sourceInfo: 'Nhà sản xuất: Cơ khí ABC' },
|
||||
{ name: 'Cáp nguồn bên ngoài', model: 'CB-NEW', unit: 'm', quantity: 1.125, notes: 'Tuyến nguồn' }
|
||||
];
|
||||
assert.equal((await request(`/${id}`, 'PUT', { lockVersion: 1, lines })).status, 200);
|
||||
const saved = (await request(`/${id}`)).data.Lines;
|
||||
assert.equal(saved[0].Quantity, 30); assert.equal(saved[0].SourceInfo, 'https://example.com/servo');
|
||||
assert.equal(saved[1].Name, 'Khung gia công bên ngoài'); assert.equal(saved[1].SourceInfo, 'Nhà sản xuất: Cơ khí ABC');
|
||||
assert.equal(saved[2].Quantity, 1.125);
|
||||
// Two clients with the same version cannot both overwrite the revision.
|
||||
const saves = await Promise.all([1, 2].map(() => request(`/${id}`, 'PUT', { lockVersion: 2, lines })));
|
||||
assert.deepEqual(saves.map(result => result.status).sort(), [200, 409]);
|
||||
// Force a real SQL failure after the DELETE, then verify full rollback.
|
||||
await pool.request().query('ALTER TABLE dbo.RobotBomLines ADD CONSTRAINT CK_BomTest_Failure CHECK (Quantity < 50)');
|
||||
assert.equal((await request(`/${id}`, 'PUT', { lockVersion: 3, lines: [{ ...lines[0], quantity: 99 }] })).status, 500);
|
||||
assert.equal((await request(`/${id}`)).data.Lines.length, 3);
|
||||
assert.equal((await request(`/${id}`)).data.LockVersion, 3);
|
||||
assert.equal((await request(`/${id}/publish`, 'POST', { lockVersion: 3 })).status, 200);
|
||||
assert.equal((await request(`/${id}`, 'PUT', { lockVersion: 4, lines: [] })).status, 409);
|
||||
const copies = await Promise.all([1, 2].map(() => request('', 'POST', { robotId: 1, copyFromId: id })));
|
||||
assert.deepEqual(copies.map(result => result.data.Revision).sort(), [3, 4]);
|
||||
await ensureRobotBomSchema(pool);
|
||||
assert.equal((await request(`/${copies[0].data.BomId}`)).data.Lines.length, 3);
|
||||
assert.equal((await request(`/${copies[0].data.BomId}`)).data.Lines[1].SourceInfo, 'Nhà sản xuất: Cơ khí ABC');
|
||||
assert.deepEqual((await pool.request().query('SELECT EndingBalance FROM dbo.AssetInventory ORDER BY AssetId')).recordset.map(item => item.EndingBalance), [8, 100]);
|
||||
assert.equal((await pool.request().query('SELECT EndingBalance FROM dbo.ConsumableInventory')).recordset[0].EndingBalance, 30);
|
||||
// Once descriptions are entered, no inventory tables are needed to save/publish/copy.
|
||||
await pool.request().query('DROP TABLE dbo.AssetInventory; DROP TABLE dbo.ConsumableInventory;');
|
||||
await pool.request().query('DELETE FROM dbo.Robots');
|
||||
const historical = await request('/models');
|
||||
assert.equal(historical.data[0].RobotId, null); assert.equal(historical.data[0].Model, 'AMR-500');
|
||||
const detached = await request('', 'POST', { copyFromId: id });
|
||||
assert.equal(detached.data.Revision, 5);
|
||||
assert.equal((await request(`/${detached.data.BomId}`, 'PUT', { lockVersion: 1, lines })).status, 200);
|
||||
assert.equal((await request(`/${detached.data.BomId}/publish`, 'POST', { lockVersion: 2 })).status, 200);
|
||||
// Deletions respect concurrent versions and remove only their own lines.
|
||||
const draftId = copies[0].data.BomId;
|
||||
assert.equal((await request(`/${id}`, 'DELETE', { lockVersion: 3 })).status, 409);
|
||||
await pool.request().query(`CREATE TABLE dbo.BomDeleteTestReferences (
|
||||
BomId INT NOT NULL REFERENCES dbo.RobotBomRevisions(BomId));
|
||||
INSERT dbo.BomDeleteTestReferences VALUES (${draftId})`);
|
||||
assert.equal((await request(`/${draftId}`, 'DELETE', { lockVersion: 1 })).status, 500);
|
||||
assert.equal((await request(`/${draftId}`)).data.Lines.length, 3);
|
||||
await pool.request().query('DROP TABLE dbo.BomDeleteTestReferences');
|
||||
const deletions = await Promise.all([1, 2].map(() => request(`/${draftId}`, 'DELETE', { lockVersion: 1 })));
|
||||
assert.deepEqual(deletions.map(result => result.status).sort(), [200, 404]);
|
||||
assert.equal((await pool.request().input('id', sql.Int, draftId).query('SELECT COUNT(*) AS Total FROM dbo.RobotBomLines WHERE BomId = @id')).recordset[0].Total, 0);
|
||||
assert.equal((await request(`/${id}`, 'DELETE', { lockVersion: 4 })).status, 200);
|
||||
assert.equal((await request(`/${id}`)).status, 404);
|
||||
assert.equal((await request(`/${copies[1].data.BomId}`)).data.Lines.length, 3);
|
||||
assert.equal((await request(`/${detached.data.BomId}`)).data.Status, 'released');
|
||||
} finally {
|
||||
if (server) { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }
|
||||
if (pool) await pool.close();
|
||||
if (admin) {
|
||||
// Only the explicitly created, randomized test database is eligible for cleanup.
|
||||
if (created && /^AccManagerBomTest_[a-f0-9]{32}$/.test(database)) await admin.request().query(`ALTER DATABASE [${database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [${database}]`);
|
||||
await admin.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
78
backend/robot-bom-test-fixture.js
Normal file
78
backend/robot-bom-test-fixture.js
Normal file
@@ -0,0 +1,78 @@
|
||||
const express = require('express');
|
||||
const { createRobotBomRouter } = require('./robot-bom');
|
||||
|
||||
function createBomFixture({ role = 'asset', failQuery } = {}) {
|
||||
const state = {
|
||||
models: [{ RobotId: 1, Model: 'AMR-500', TypeId: 1, Type: 'AMR', Name: 'Robot vận chuyển' }],
|
||||
catalog: [
|
||||
{ SourceType: 'asset', SourceId: 1, Code: 'LK-001', Name: 'Động cơ servo 400W', Model: 'SV-400', Unit: 'cái', Available: 8, Location: 'Kho A' },
|
||||
{ SourceType: 'asset', SourceId: 2, Code: 'LK-002', Name: 'Bánh xe chủ động', Model: 'WH-200', Unit: 'cái', Available: 16, Location: 'Kho A' },
|
||||
{ SourceType: 'asset', SourceId: 3, Code: 'LK-003', Name: 'Bộ pin 48V 40Ah', Model: 'BAT-48-40', Unit: 'bộ', Available: 3, Location: 'Kho A' },
|
||||
{ SourceType: 'consumable', SourceId: 1, Code: 'VT-001', Name: 'Cáp nguồn', Model: 'CB-2X2.5', Unit: 'm', Available: 30, Location: '' }
|
||||
],
|
||||
headers: [], lines: []
|
||||
};
|
||||
let nextId = 1;
|
||||
const queries = [], transactions = [];
|
||||
class Request {
|
||||
constructor(transaction) { this.transaction = transaction; this.inputs = {}; }
|
||||
input(name, _type, value) { this.inputs[name] = value; return this; }
|
||||
async query(query) {
|
||||
const inputs = this.inputs; queries.push({ query, inputs, transaction: this.transaction });
|
||||
if (failQuery?.(query, inputs)) throw new Error('test database failure');
|
||||
const rows = recordset => ({ recordset: structuredClone(recordset) });
|
||||
if (query.includes('FROM dbo.AssetInventory')) return rows(state.catalog.filter(item => item.SourceType === 'asset')
|
||||
.map(item => ({ Id: item.SourceId, Code: item.Code, Name: item.Name, Model: item.Model, Unit: item.Unit })));
|
||||
if (query.includes('WITH ModelCatalog')) {
|
||||
const models = [...state.models];
|
||||
for (const header of state.headers) {
|
||||
if (!models.some(model => model.Model === header.RobotModel && model.TypeId === header.RobotTypeId)) models.push({
|
||||
RobotId: null, Model: header.RobotModel, TypeId: header.RobotTypeId, Type: 'AMR', Name: 'BOM đã lưu theo model'
|
||||
});
|
||||
}
|
||||
return rows(models);
|
||||
}
|
||||
if (query.includes('SELECT Model, TypeId FROM dbo.Robots')) return rows(state.models.filter(item => item.RobotId === inputs.robotId));
|
||||
if (query.includes('MAX(Revision)')) return rows([{ NextRevision: Math.max(0, ...state.headers.filter(item => item.RobotModel === inputs.model && item.RobotTypeId === inputs.typeId).map(item => item.Revision)) + 1 }]);
|
||||
if (query.includes('INSERT dbo.RobotBomRevisions')) {
|
||||
const now = new Date().toISOString();
|
||||
const header = { BomId: nextId++, RobotModel: inputs.model, RobotTypeId: inputs.typeId, Revision: inputs.revision, Status: 'draft', LockVersion: 1, CreatedDate: now, UpdatedDate: now, ReleasedDate: null };
|
||||
state.headers.push(header); return rows([header]);
|
||||
}
|
||||
if (query.includes('DELETE FROM dbo.RobotBomRevisions')) { state.headers = state.headers.filter(item => item.BomId !== inputs.id); return rows([]); }
|
||||
if (query.includes('FROM dbo.RobotBomRevisions') && query.includes('WHERE BomId = @id')) return rows(state.headers.filter(item => item.BomId === inputs.id));
|
||||
if (query.includes('FROM dbo.RobotBomRevisions b')) return rows(state.headers.filter(item => item.RobotModel === inputs.model && item.RobotTypeId === inputs.typeId).map(item => ({ ...item, LineCount: state.lines.filter(line => line.BomId === item.BomId).length })).sort((a, b) => b.Revision - a.Revision));
|
||||
if (query.includes('SELECT * FROM dbo.RobotBomLines')) return rows(state.lines.filter(item => item.BomId === inputs.id).sort((a, b) => a.SortOrder - b.SortOrder));
|
||||
if (query.includes('DELETE FROM dbo.RobotBomLines')) { state.lines = state.lines.filter(item => item.BomId !== inputs.id); return rows([]); }
|
||||
if (query.includes('INSERT dbo.RobotBomLines')) {
|
||||
state.lines.push({ BomId: inputs.bomId, SourceType: inputs.sourceType, SourceId: inputs.sourceId,
|
||||
Code: inputs.code, Name: inputs.name, Model: inputs.model, Unit: inputs.unit,
|
||||
GroupName: inputs.groupName, Position: inputs.position, Quantity: inputs.quantity,
|
||||
Notes: inputs.notes, SourceInfo: inputs.sourceInfo, SortOrder: inputs.sortOrder }); return rows([]);
|
||||
}
|
||||
if (query.includes('UPDATE dbo.RobotBomRevisions')) {
|
||||
const header = state.headers.find(item => item.BomId === inputs.id);
|
||||
header.LockVersion++; header.UpdatedDate = new Date().toISOString();
|
||||
if (query.includes("Status = 'released'")) { header.Status = 'released'; header.ReleasedDate = header.UpdatedDate; }
|
||||
return rows([header]);
|
||||
}
|
||||
throw new Error(`Unexpected fixture query: ${query}`);
|
||||
}
|
||||
}
|
||||
class Transaction {
|
||||
constructor() { transactions.push(this); }
|
||||
async begin() { this.snapshot = structuredClone(state); }
|
||||
async commit() { this.committed = true; }
|
||||
async rollback() { Object.assign(state, this.snapshot); this.rolledBack = true; }
|
||||
}
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => { req.user = { UserId: 1, Role: role }; next(); });
|
||||
app.use('/api/robot-boms', createRobotBomRouter({ getPool: () => ({ request: () => new Request() }),
|
||||
sql: { ...require('mssql'), Request, Transaction },
|
||||
requireManage(req, res, next) { if (!['asset', 'admin'].includes(req.user.Role)) return res.status(403).json({ success: false }); next(); },
|
||||
sendInternalError(res, _error, message) { return res.status(500).json({ success: false, message }); }
|
||||
}));
|
||||
return { app, state, queries, transactions };
|
||||
}
|
||||
module.exports = { createBomFixture };
|
||||
186
backend/robot-bom.js
Normal file
186
backend/robot-bom.js
Normal file
@@ -0,0 +1,186 @@
|
||||
const express = require('express');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const MAX_LINES = 500;
|
||||
const fail = (message, status = 400) => Object.assign(new Error(message), { status });
|
||||
function positiveId(value) {
|
||||
if (!/^\d+$/.test(String(value)) || !Number.isSafeInteger(Number(value)) || Number(value) < 1 || Number(value) > 2147483647) {
|
||||
throw fail('Mã dữ liệu không hợp lệ');
|
||||
}
|
||||
return Number(value);
|
||||
}
|
||||
function textField(value, max, label, required = false) {
|
||||
if (typeof value !== 'string' || value.trim().length > max || (required && !value.trim())) {
|
||||
throw fail(`${label} ${required ? 'không được trống và ' : ''}tối đa ${max} ký tự`);
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
function quantity(value, unit) {
|
||||
if (!/^\d+(\.\d{1,4})?$/.test(String(value)) || !Number.isFinite(Number(value)) || Number(value) <= 0 || Number(value) > 100000) {
|
||||
throw fail('Số lượng phải lớn hơn 0, tối đa 100.000 và không quá 4 chữ số thập phân');
|
||||
}
|
||||
const fractional = /^(m|m2|m²|m3|m³|mét|met|kg|g|gam|l|lít|lit|ml|mm|cm|tấn|tan)$/i.test(String(unit).trim());
|
||||
if (String(unit).trim() && !fractional && !Number.isInteger(Number(value))) throw fail(`Đơn vị ${unit} yêu cầu số lượng nguyên`);
|
||||
return Number(value);
|
||||
}
|
||||
function normalizeLines(input) {
|
||||
if (!Array.isArray(input) || input.length > MAX_LINES) throw fail(`BOM tối đa ${MAX_LINES} dòng vật tư`);
|
||||
return input.map((line, index) => {
|
||||
if (!line || typeof line !== 'object' || Array.isArray(line)) throw fail(`Vật tư dòng ${index + 1} không hợp lệ`);
|
||||
const unit = textField(line.unit ?? '', 50, 'Đơn vị');
|
||||
return { SourceType: 'manual', SourceId: null,
|
||||
Name: textField(line.name, 255, 'Tên vật tư', true),
|
||||
Code: textField(line.code ?? '', 100, 'Mã vật tư'), Model: textField(line.model ?? '', 255, 'Model vật tư'),
|
||||
Unit: unit, GroupName: textField(line.groupName ?? '', 100, 'Cụm lắp ráp'),
|
||||
Position: textField(line.position ?? '', 150, 'Vị trí lắp'), Quantity: quantity(line.quantity ?? 1, unit),
|
||||
SourceInfo: textField(line.sourceInfo ?? '', 1000, 'Nguồn'),
|
||||
Notes: textField(line.notes ?? '', 500, 'Ghi chú'), SortOrder: index };
|
||||
});
|
||||
}
|
||||
async function ensureRobotBomSchema(pool) {
|
||||
await pool.request().batch(fs.readFileSync(path.join(__dirname, 'robot-bom-schema.sql'), 'utf8'));
|
||||
}
|
||||
function createRobotBomRouter({ getPool, sql, requireManage, sendInternalError }) {
|
||||
const router = express.Router();
|
||||
const handle = fn => async (req, res) => {
|
||||
try { req.body ??= {}; await fn(req, res); }
|
||||
catch (error) {
|
||||
if (error.status) return res.status(error.status).json({ success: false, message: error.message });
|
||||
if ([2601, 2627, 1205].includes(error.number)) return res.status(409).json({ success: false, message: 'Dữ liệu vừa được thay đổi. Hãy tải lại BOM rồi thử lại.' });
|
||||
return sendInternalError(res, error, 'Không thể xử lý BOM robot');
|
||||
}
|
||||
};
|
||||
const inTransaction = async fn => {
|
||||
const transaction = new sql.Transaction(getPool());
|
||||
await transaction.begin();
|
||||
try { const result = await fn(() => new sql.Request(transaction)); await transaction.commit(); return result; }
|
||||
catch (error) { try { await transaction.rollback(); } catch {} throw error; }
|
||||
};
|
||||
const loadHeader = async (request, id, lock = false) => {
|
||||
const result = await request.input('id', sql.Int, positiveId(id)).query(`
|
||||
SELECT * FROM dbo.RobotBomRevisions ${lock ? 'WITH (UPDLOCK, HOLDLOCK)' : ''} WHERE BomId = @id`);
|
||||
if (!result.recordset[0]) throw fail('Không tìm thấy phiên bản BOM', 404);
|
||||
return result.recordset[0];
|
||||
};
|
||||
const checkDraft = (header, version) => {
|
||||
if (header.Status !== 'draft') throw fail('BOM đã phát hành. Hãy sao chép thành phiên bản nháp mới để chỉnh sửa.', 409);
|
||||
if (header.LockVersion !== positiveId(version)) throw fail('BOM đã được người khác thay đổi. Hãy tải lại trước khi lưu.', 409);
|
||||
};
|
||||
const readLines = async (request, id) => (await request.input('id', sql.Int, id)
|
||||
.query('SELECT * FROM dbo.RobotBomLines WHERE BomId = @id ORDER BY SortOrder, LineId')).recordset;
|
||||
async function insertLines(request, id, lines) {
|
||||
for (const line of lines) {
|
||||
await request().input('bomId', sql.Int, id)
|
||||
.input('sourceType', sql.VarChar(10), line.SourceType).input('sourceId', sql.Int, line.SourceId)
|
||||
.input('code', sql.NVarChar(100), line.Code).input('name', sql.NVarChar(255), line.Name)
|
||||
.input('model', sql.NVarChar(255), line.Model).input('unit', sql.NVarChar(50), line.Unit)
|
||||
.input('groupName', sql.NVarChar(100), line.GroupName).input('position', sql.NVarChar(150), line.Position)
|
||||
.input('quantity', sql.Decimal(18, 4), line.Quantity).input('notes', sql.NVarChar(500), line.Notes)
|
||||
.input('sourceInfo', sql.NVarChar(1000), line.SourceInfo || '')
|
||||
.input('sortOrder', sql.Int, line.SortOrder).query(`
|
||||
INSERT dbo.RobotBomLines (BomId, SourceType, SourceId, Code, Name, Model, Unit, GroupName, Position, Quantity, Notes, SourceInfo, SortOrder)
|
||||
VALUES (@bomId, @sourceType, @sourceId, @code, @name, @model, @unit, @groupName, @position, @quantity, @notes, @sourceInfo, @sortOrder)`);
|
||||
}
|
||||
}
|
||||
router.get('/models', handle(async (_req, res) => {
|
||||
const result = await getPool().request().query(`
|
||||
WITH ModelCatalog AS (
|
||||
SELECT Model, TypeId FROM dbo.Robots
|
||||
UNION SELECT RobotModel, RobotTypeId FROM dbo.RobotBomRevisions
|
||||
)
|
||||
SELECT MIN(r.RobotId) AS RobotId, m.Model, m.TypeId, t.Name AS Type,
|
||||
COALESCE(MIN(r.Name), N'BOM đã lưu theo model') AS Name
|
||||
FROM ModelCatalog m JOIN dbo.RobotTypes t ON t.TypeId = m.TypeId
|
||||
LEFT JOIN dbo.Robots r ON r.Model = m.Model AND r.TypeId = m.TypeId
|
||||
GROUP BY m.Model, m.TypeId, t.Name ORDER BY m.Model, t.Name`);
|
||||
res.json({ success: true, data: result.recordset });
|
||||
}));
|
||||
router.get('/catalog', handle(async (_req, res) => {
|
||||
// This picker copies descriptions only. All quantities belong to the BOM.
|
||||
const result = await getPool().request().query(`
|
||||
SELECT AssetId AS Id, AssetCode AS Code, AssetName AS Name,
|
||||
ISNULL(Model, '') AS Model, ISNULL(Unit, '') AS Unit
|
||||
FROM dbo.AssetInventory WHERE IsArchived = 0 ORDER BY AssetName, AssetCode`);
|
||||
res.json({ success: true, data: result.recordset });
|
||||
}));
|
||||
router.get('/', handle(async (req, res) => {
|
||||
const model = textField(req.query.model, 255, 'Model robot', true);
|
||||
const result = await getPool().request().input('model', sql.NVarChar(255), model)
|
||||
.input('typeId', sql.Int, positiveId(req.query.typeId)).query(`
|
||||
SELECT b.*, (SELECT COUNT(*) FROM dbo.RobotBomLines l WHERE l.BomId = b.BomId) AS LineCount
|
||||
FROM dbo.RobotBomRevisions b WHERE RobotModel = @model AND RobotTypeId = @typeId ORDER BY Revision DESC`);
|
||||
res.json({ success: true, data: result.recordset });
|
||||
}));
|
||||
router.get('/:id', handle(async (req, res) => {
|
||||
const header = await loadHeader(getPool().request(), req.params.id);
|
||||
res.json({ success: true, data: { ...header, Lines: await readLines(getPool().request(), header.BomId) } });
|
||||
}));
|
||||
router.post('/', requireManage, handle(async (req, res) => {
|
||||
const copyFrom = req.body.copyFromId == null ? null : positiveId(req.body.copyFromId);
|
||||
const robotId = req.body.robotId == null && copyFrom ? null : positiveId(req.body.robotId);
|
||||
const header = await inTransaction(async request => {
|
||||
const source = copyFrom ? await loadHeader(request(), copyFrom, true) : null;
|
||||
const robot = robotId == null ? { Model: source.RobotModel, TypeId: source.RobotTypeId }
|
||||
: (await request().input('robotId', sql.Int, robotId)
|
||||
.query('SELECT Model, TypeId FROM dbo.Robots WITH (HOLDLOCK) WHERE RobotId = @robotId')).recordset[0];
|
||||
if (!robot) throw fail('Robot không còn trong danh mục. Hãy tải lại danh sách.', 404);
|
||||
const revision = (await request().input('model', sql.NVarChar(255), robot.Model).input('typeId', sql.Int, robot.TypeId)
|
||||
.query(`SELECT ISNULL(MAX(Revision), 0) + 1 AS NextRevision FROM dbo.RobotBomRevisions WITH (UPDLOCK, HOLDLOCK)
|
||||
WHERE RobotModel = @model AND RobotTypeId = @typeId`)).recordset[0].NextRevision;
|
||||
const inserted = (await request().input('model', sql.NVarChar(255), robot.Model).input('typeId', sql.Int, robot.TypeId)
|
||||
.input('revision', sql.Int, revision).input('userId', sql.Int, req.user.UserId)
|
||||
.query(`INSERT dbo.RobotBomRevisions (RobotModel, RobotTypeId, Revision, CreatedBy)
|
||||
OUTPUT INSERTED.* VALUES (@model, @typeId, @revision, @userId)`)).recordset[0];
|
||||
if (copyFrom) {
|
||||
await insertLines(request, inserted.BomId, await readLines(request(), copyFrom));
|
||||
}
|
||||
return inserted;
|
||||
});
|
||||
res.status(201).json({ success: true, data: header, message: 'Đã tạo phiên bản BOM nháp' });
|
||||
}));
|
||||
router.put('/:id', requireManage, handle(async (req, res) => {
|
||||
const id = positiveId(req.params.id);
|
||||
if (!Array.isArray(req.body.lines) || req.body.lines.length > MAX_LINES) throw fail(`BOM tối đa ${MAX_LINES} dòng vật tư`);
|
||||
const saved = await inTransaction(async request => {
|
||||
const header = await loadHeader(request(), id, true); checkDraft(header, req.body.lockVersion);
|
||||
const lines = normalizeLines(req.body.lines);
|
||||
await request().input('id', sql.Int, id).query('DELETE FROM dbo.RobotBomLines WHERE BomId = @id');
|
||||
await insertLines(request, id, lines);
|
||||
const updated = (await request().input('id', sql.Int, id).query(`UPDATE dbo.RobotBomRevisions
|
||||
SET LockVersion = LockVersion + 1, UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
|
||||
OUTPUT INSERTED.UpdatedDate WHERE BomId = @id`)).recordset[0];
|
||||
return { BomId: id, LockVersion: header.LockVersion + 1, UpdatedDate: updated.UpdatedDate, Lines: lines };
|
||||
});
|
||||
res.json({ success: true, data: saved, message: 'Đã lưu BOM nháp' });
|
||||
}));
|
||||
router.delete('/:id', requireManage, handle(async (req, res) => {
|
||||
const id = positiveId(req.params.id);
|
||||
await inTransaction(async request => {
|
||||
const header = await loadHeader(request(), id, true);
|
||||
if (header.LockVersion !== positiveId(req.body.lockVersion)) {
|
||||
throw fail('BOM đã được người khác thay đổi. Hãy tải lại trước khi xóa.', 409);
|
||||
}
|
||||
await request().input('id', sql.Int, id).query('DELETE FROM dbo.RobotBomLines WHERE BomId = @id');
|
||||
await request().input('id', sql.Int, id).query('DELETE FROM dbo.RobotBomRevisions WHERE BomId = @id');
|
||||
});
|
||||
res.json({ success: true, message: 'Đã xóa phiên bản BOM' });
|
||||
}));
|
||||
router.post('/:id/publish', requireManage, handle(async (req, res) => {
|
||||
const id = positiveId(req.params.id);
|
||||
await inTransaction(async request => {
|
||||
const header = await loadHeader(request(), id, true); checkDraft(header, req.body.lockVersion);
|
||||
const lines = await readLines(request(), id);
|
||||
if (!lines.length) throw fail('BOM cần có ít nhất một vật tư trước khi phát hành');
|
||||
normalizeLines(lines.map(line => ({ name: line.Name, unit: line.Unit, quantity: line.Quantity,
|
||||
code: line.Code, model: line.Model, groupName: line.GroupName, position: line.Position, notes: line.Notes,
|
||||
sourceInfo: line.SourceInfo || '' })));
|
||||
await request().input('id', sql.Int, id).query(`UPDATE dbo.RobotBomRevisions SET Status = 'released',
|
||||
LockVersion = LockVersion + 1, ReleasedDate = DATEADD(HOUR, 7, SYSUTCDATETIME()),
|
||||
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME()) WHERE BomId = @id`);
|
||||
});
|
||||
res.json({ success: true, message: 'Đã phát hành BOM. Có thể sao chép thành phiên bản mới khi cần chỉnh sửa.' });
|
||||
}));
|
||||
return router;
|
||||
}
|
||||
module.exports = { ensureRobotBomSchema, createRobotBomRouter, normalizeLines, quantity };
|
||||
212
backend/robot-bom.test.js
Normal file
212
backend/robot-bom.test.js
Normal file
@@ -0,0 +1,212 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { normalizeLines, quantity } = require('./robot-bom');
|
||||
const { createBomFixture } = require('./robot-bom-test-fixture');
|
||||
|
||||
const line = extra => ({ name: 'Động cơ servo 400W', model: 'SV-400', unit: 'cái', quantity: 2,
|
||||
sourceInfo: 'https://example.com/servo', notes: '', ...extra });
|
||||
async function fixture(t, options) {
|
||||
const f = createBomFixture(options);
|
||||
const server = f.app.listen(0, '127.0.0.1');
|
||||
await new Promise(resolve => server.once('listening', resolve));
|
||||
t.after(() => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); });
|
||||
f.request = async (suffix = '', method = 'GET', body) => {
|
||||
const response = await fetch(`http://127.0.0.1:${server.address().port}/api/robot-boms${suffix}`, { method,
|
||||
...(body === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) });
|
||||
return { status: response.status, ...(response.headers.get('content-type')?.includes('application/json')
|
||||
? await response.json() : { message: await response.text() }) };
|
||||
};
|
||||
return f;
|
||||
}
|
||||
|
||||
test('BOM stores editable names/models, quantities and supplier sources without touching inventory', async t => {
|
||||
const f = await fixture(t);
|
||||
const created = await f.request('', 'POST', { robotId: 1 });
|
||||
assert.equal(created.status, 201);
|
||||
const id = created.data.BomId;
|
||||
const saved = await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
|
||||
assert.equal(saved.status, 200); assert.equal(saved.data.LockVersion, 2);
|
||||
const reopened = await f.request(`/${id}`);
|
||||
assert.equal(reopened.data.Lines[0].Name, 'Động cơ servo 400W');
|
||||
assert.equal(reopened.data.Lines[0].Model, 'SV-400');
|
||||
assert.equal(reopened.data.Lines[0].SourceInfo, 'https://example.com/servo');
|
||||
assert.equal(reopened.data.Lines[0].SourceId, null);
|
||||
assert.equal(reopened.data.Lines[0].SourceType, 'manual');
|
||||
const revisions = await f.request('?model=AMR-500&typeId=1');
|
||||
assert.equal(revisions.data[0].LineCount, 1);
|
||||
assert.equal(f.queries.some(({ query }) => /\b(?:AssetInventory|ConsumableInventory)\b/i.test(query)), false);
|
||||
});
|
||||
|
||||
test('asset picker exposes names/models with no stock quantities, including assets with zero stock', async t => {
|
||||
const f = await fixture(t);
|
||||
f.state.catalog[0].Available = 0;
|
||||
const result = await f.request('/catalog');
|
||||
assert.equal(result.status, 200); assert.equal(result.data.length, 3);
|
||||
assert.deepEqual(Object.keys(result.data[0]).sort(), ['Code', 'Id', 'Model', 'Name', 'Unit']);
|
||||
assert.doesNotMatch(f.queries[0].query, /EndingBalance|Quantity|Available/);
|
||||
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
|
||||
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line({ quantity: 2000 })] })).status, 200);
|
||||
assert.equal(f.state.catalog[0].Available, 0);
|
||||
});
|
||||
|
||||
test('publishing freezes the saved snapshot; copying produces an editable independent revision', async t => {
|
||||
const f = await fixture(t);
|
||||
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
|
||||
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] })).status, 200);
|
||||
assert.equal((await f.request(`/${id}/publish`, 'POST', { lockVersion: 2 })).status, 200);
|
||||
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 3, lines: [] })).status, 409);
|
||||
assert.equal((await f.request(`/${id}/publish`, 'POST', { lockVersion: 3 })).status, 409);
|
||||
f.state.catalog[0].Name = 'New inventory name';
|
||||
const snapshot = await f.request(`/${id}`);
|
||||
assert.equal(snapshot.data.Lines[0].Name, 'Động cơ servo 400W');
|
||||
const copied = await f.request('', 'POST', { robotId: 1, copyFromId: id });
|
||||
assert.equal(copied.data.Revision, 2); assert.equal(copied.data.Status, 'draft');
|
||||
await f.request(`/${copied.data.BomId}`, 'PUT', { lockVersion: 1, lines: [line({ quantity: 3 })] });
|
||||
assert.equal((await f.request(`/${id}`)).data.Lines[0].Quantity, 2);
|
||||
assert.equal((await f.request(`/${copied.data.BomId}`)).data.Lines[0].Quantity, 3);
|
||||
assert.equal((await f.request(`/${copied.data.BomId}`)).data.Lines[0].SourceInfo, 'https://example.com/servo');
|
||||
});
|
||||
|
||||
test('concurrent stale saves are rejected without overwriting newer quantities', async t => {
|
||||
const f = await fixture(t);
|
||||
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
|
||||
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
|
||||
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line({ quantity: 99 })] })).status, 409);
|
||||
assert.equal((await f.request(`/${id}/publish`, 'POST', { lockVersion: 1 })).status, 409);
|
||||
assert.equal((await f.request(`/${id}`)).data.Lines[0].Quantity, 2);
|
||||
});
|
||||
|
||||
test('an insert failure rolls back a complete BOM save including deleted old lines', async t => {
|
||||
let fail = false;
|
||||
const f = await fixture(t, { failQuery: query => fail && query.includes('INSERT dbo.RobotBomLines') });
|
||||
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
|
||||
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
|
||||
fail = true;
|
||||
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 2, lines: [line({ quantity: 3 })] })).status, 500);
|
||||
assert.equal((await f.request(`/${id}`)).data.Lines[0].Quantity, 2);
|
||||
assert.equal((await f.request(`/${id}`)).data.LockVersion, 2);
|
||||
assert.equal(f.transactions.at(-1).rolledBack, true);
|
||||
});
|
||||
|
||||
test('external parts and supplier descriptions work without any inventory records', async t => {
|
||||
const f = await fixture(t);
|
||||
f.state.catalog = [];
|
||||
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
|
||||
const lines = [line({ name: 'Khung gia công bên ngoài', model: 'CUSTOM-01', quantity: 12, sourceInfo: 'Nhà sản xuất: Cơ khí ABC, liên hệ bộ phận kỹ thuật' }), { name: 'Bulong M6' }];
|
||||
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines })).status, 200);
|
||||
const saved = (await f.request(`/${id}`)).data.Lines;
|
||||
assert.equal(saved[0].Quantity, 12); assert.equal(saved[1].Quantity, 1);
|
||||
assert.equal(saved[0].SourceInfo, lines[0].sourceInfo);
|
||||
assert.equal((await f.request(`/${id}/publish`, 'POST', { lockVersion: 2 })).status, 200);
|
||||
assert.equal((await f.request('/requirements/check', 'POST', {})).status, 404);
|
||||
assert.equal(f.queries.some(({ query }) => /Inventory/.test(query)), false);
|
||||
});
|
||||
|
||||
test('viewers can read BOMs and descriptive asset choices but cannot create, edit, publish or delete', async t => {
|
||||
const f = await fixture(t, { role: 'user' });
|
||||
for (const suffix of ['/models', '/catalog', '?model=AMR-500&typeId=1']) assert.equal((await f.request(suffix)).status, 200);
|
||||
for (const [suffix, method] of [['', 'POST'], ['/1', 'PUT'], ['/1/publish', 'POST'], ['/1', 'DELETE']]) assert.equal((await f.request(suffix, method, { robotId: 1 })).status, 403);
|
||||
assert.equal(f.transactions.length, 0);
|
||||
});
|
||||
|
||||
for (const role of ['admin', 'asset']) {
|
||||
for (const released of [false, true]) {
|
||||
test(`${role} can delete a ${released ? 'released' : 'draft'} BOM with its lines while preserving copied revisions and inventory`, async t => {
|
||||
const f = await fixture(t, { role });
|
||||
const catalog = structuredClone(f.state.catalog);
|
||||
const models = structuredClone(f.state.models);
|
||||
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
|
||||
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
|
||||
if (released) await f.request(`/${id}/publish`, 'POST', { lockVersion: 2 });
|
||||
const copiedId = (await f.request('', 'POST', { copyFromId: id })).data.BomId;
|
||||
const result = await f.request(`/${id}`, 'DELETE', { lockVersion: released ? 3 : 2 });
|
||||
assert.equal(result.status, 200); assert.equal(result.success, true);
|
||||
assert.equal((await f.request(`/${id}`)).status, 404);
|
||||
assert.equal(f.state.lines.some(item => item.BomId === id), false);
|
||||
assert.deepEqual((await f.request('?model=AMR-500&typeId=1')).data.map(item => item.BomId), [copiedId]);
|
||||
assert.equal((await f.request(`/${copiedId}`)).data.Lines[0].Quantity, 2);
|
||||
assert.deepEqual(f.state.catalog, catalog); assert.deepEqual(f.state.models, models);
|
||||
const deletes = f.queries.filter(({ query }) => query.startsWith('DELETE'));
|
||||
assert.equal(deletes.at(-1).transaction, deletes.at(-2).transaction);
|
||||
assert.equal(f.transactions.at(-1).committed, true);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test('deletion rejects stale or invalid versions and invalid or missing BOM identifiers', async t => {
|
||||
const f = await fixture(t);
|
||||
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
|
||||
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
|
||||
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion: 1 })).status, 409);
|
||||
for (const lockVersion of [undefined, 0, -1, 'invalid']) {
|
||||
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion })).status, 400);
|
||||
}
|
||||
for (const badId of ['abc', '0', '-1', '2147483648']) {
|
||||
assert.equal((await f.request(`/${badId}`, 'DELETE', { lockVersion: 2 })).status, 400);
|
||||
}
|
||||
assert.equal((await f.request('/999', 'DELETE', { lockVersion: 2 })).status, 404);
|
||||
assert.equal((await f.request(`/${id}`)).data.Lines[0].Quantity, 2);
|
||||
assert.equal(f.queries.some(({ query }) => query.startsWith('DELETE FROM dbo.RobotBomRevisions')), false);
|
||||
});
|
||||
|
||||
test('a header deletion failure rolls back removed BOM lines and allows retry', async t => {
|
||||
let fail = true;
|
||||
const f = await fixture(t, { failQuery: query => fail && query.includes('DELETE FROM dbo.RobotBomRevisions') });
|
||||
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
|
||||
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
|
||||
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion: 2 })).status, 500);
|
||||
assert.equal(f.transactions.at(-1).rolledBack, true);
|
||||
const retained = (await f.request(`/${id}`)).data;
|
||||
assert.equal(retained.LockVersion, 2); assert.equal(retained.Lines[0].Quantity, 2);
|
||||
fail = false;
|
||||
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion: 2 })).status, 200);
|
||||
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion: 2 })).status, 404);
|
||||
});
|
||||
|
||||
test('deleting the final historical BOM removes its orphaned model and supports an empty BOM', async t => {
|
||||
const f = await fixture(t);
|
||||
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
|
||||
f.state.models = [];
|
||||
assert.equal((await f.request('/models')).data.length, 1);
|
||||
assert.equal((await f.request(`/${id}`, 'DELETE', { lockVersion: 1 })).status, 200);
|
||||
assert.deepEqual((await f.request('/models')).data, []);
|
||||
assert.deepEqual((await f.request('?model=AMR-500&typeId=1')).data, []);
|
||||
});
|
||||
|
||||
test('bad identifiers, empty publications, invalid lines and unsafe quantities are rejected', async t => {
|
||||
const f = await fixture(t);
|
||||
assert.equal((await f.request('/abc')).status, 400);
|
||||
assert.equal((await f.request('/999')).status, 404);
|
||||
assert.equal((await f.request('', 'POST', { robotId: 999 })).status, 404);
|
||||
assert.equal((await f.request('', 'POST')).status, 400);
|
||||
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
|
||||
assert.equal((await f.request(`/${id}/publish`, 'POST', { lockVersion: 1 })).status, 400);
|
||||
for (const bad of [null, [null], [line({ name: '' })], [line({ name: ' '.repeat(2) })], [line({ model: 'x'.repeat(256) })], [line({ sourceInfo: 'x'.repeat(1001) })], [line({ quantity: -1 })], [line({ quantity: 0.5 })], Array(501).fill(line())]) {
|
||||
assert.equal((await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: bad })).status, 400);
|
||||
}
|
||||
for (const value of [0, -1, 100001, 'NaN', Infinity, '1e4', 0.00001]) assert.throws(() => quantity(value, 'm'));
|
||||
assert.equal(quantity(0.125, 'm'), 0.125);
|
||||
});
|
||||
|
||||
test('a name alone is sufficient; inventory identity is discarded while descriptive metadata is retained', () => {
|
||||
const normalized = normalizeLines([{ name: 'Cảm biến ngoài', sourceType: 'asset', sourceId: 999 }])[0];
|
||||
assert.equal(normalized.Name, 'Cảm biến ngoài'); assert.equal(normalized.Quantity, 1);
|
||||
assert.equal(normalized.Model, ''); assert.equal(normalized.Unit, '');
|
||||
assert.equal(normalized.SourceType, 'manual'); assert.equal(normalized.SourceId, null);
|
||||
assert.equal(normalizeLines([line(), line()]).length, 2);
|
||||
assert.equal(normalizeLines([line({ unit: '', quantity: 0.125 })])[0].Quantity, 0.125);
|
||||
assert.deepEqual(normalizeLines([]), []);
|
||||
});
|
||||
|
||||
test('historical models and revisions remain accessible after their last robot is removed', async t => {
|
||||
const f = await fixture(t);
|
||||
const id = (await f.request('', 'POST', { robotId: 1 })).data.BomId;
|
||||
await f.request(`/${id}`, 'PUT', { lockVersion: 1, lines: [line()] });
|
||||
f.state.models = [];
|
||||
const models = await f.request('/models');
|
||||
assert.equal(models.data[0].Model, 'AMR-500'); assert.equal(models.data[0].RobotId, null);
|
||||
assert.equal((await f.request('?model=AMR-500&typeId=1')).data.length, 1);
|
||||
const copied = await f.request('', 'POST', { copyFromId: id });
|
||||
assert.equal(copied.status, 201); assert.equal(copied.data.Revision, 2);
|
||||
assert.equal((await f.request(`/${copied.data.BomId}`)).data.Lines.length, 1);
|
||||
});
|
||||
@@ -75,7 +75,7 @@ function createRobotRouter({ getPool, sql, requireManage, documentMaxBytes, docu
|
||||
return res.status(409).json({ success: false, message: 'Tên thể loại robot đã tồn tại' });
|
||||
}
|
||||
if (error.number === 547) {
|
||||
return res.status(409).json({ success: false, message: 'Thể loại đang được sử dụng. Hãy chuyển các robot sang thể loại khác trước khi xóa.' });
|
||||
return res.status(409).json({ success: false, message: 'Thể loại đang được robot hoặc BOM sử dụng. Không thể xóa để bảo toàn dữ liệu liên quan.' });
|
||||
}
|
||||
return fail(res, error);
|
||||
}
|
||||
|
||||
18
backend/run-tests.js
Normal file
18
backend/run-tests.js
Normal file
@@ -0,0 +1,18 @@
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { spawnSync } = require('node:child_process');
|
||||
|
||||
// Restrict discovery to source tests. Browser profiles in tmp/ can contain
|
||||
// third-party extension *.test.js files and must never enter the project suite.
|
||||
function discover(directory) {
|
||||
if (!fs.existsSync(directory)) return [];
|
||||
return fs.readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
|
||||
const target = path.join(directory, entry.name);
|
||||
if (entry.isDirectory() && entry.name !== 'node_modules') return discover(target);
|
||||
return entry.isFile() && /\.test\.[cm]?js$/.test(entry.name) ? [target] : [];
|
||||
});
|
||||
}
|
||||
const files = [__dirname, path.resolve(__dirname, '../test')].flatMap(discover);
|
||||
const result = spawnSync(process.execPath, ['--test', ...process.argv.slice(2), ...files], { stdio: 'inherit' });
|
||||
if (result.error) console.error(result.error.message);
|
||||
process.exitCode = result.status ?? 1;
|
||||
@@ -17,6 +17,7 @@ const { parseAllocations, normalizeExportAllocations, addAllocations, releaseAll
|
||||
const { buildExportRequestWorkbook } = require('./export-request-workbook');
|
||||
const { ensureAssetExportDocumentSchema } = require('./asset-export-documents');
|
||||
const { ensureRobotSchema, createRobotRouter } = require('./robots');
|
||||
const { ensureRobotBomSchema, createRobotBomRouter } = require('./robot-bom');
|
||||
const { getDocumentFormat, isPdfBuffer, validateDocumentFile, normalizeUploadedFileName,
|
||||
sanitizeDocumentFileName, getDocumentContentDisposition, accept: documentAccept } = require('./document-files');
|
||||
|
||||
@@ -3099,6 +3100,7 @@ async function createTables() {
|
||||
await ensureAssetArchiveSchema(pool);
|
||||
await ensureAssetExportDocumentSchema(pool);
|
||||
await ensureRobotSchema(pool);
|
||||
await ensureRobotBomSchema(pool);
|
||||
await pool.request().query(`
|
||||
IF COL_LENGTH('dbo.AssetInventory', 'ProjectAllocations') IS NULL
|
||||
ALTER TABLE dbo.AssetInventory ADD ProjectAllocations NVARCHAR(MAX) NULL;
|
||||
@@ -9529,6 +9531,10 @@ app.use('/api/robots', createRobotRouter({
|
||||
sanitizeDocumentFileName, sendInternalError
|
||||
}));
|
||||
|
||||
app.use('/api/robot-boms', createRobotBomRouter({
|
||||
getPool: () => pool, sql, requireManage: requireAssetOrAdmin, sendInternalError
|
||||
}));
|
||||
|
||||
app.get('/api/documents', async (req, res) => {
|
||||
try {
|
||||
const search = String(req.query.search || '').trim().slice(0, 255);
|
||||
|
||||
Reference in New Issue
Block a user