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' });
|
return res.status(409).json({ success: false, message: 'Tên thể loại robot đã tồn tại' });
|
||||||
}
|
}
|
||||||
if (error.number === 547) {
|
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);
|
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 { buildExportRequestWorkbook } = require('./export-request-workbook');
|
||||||
const { ensureAssetExportDocumentSchema } = require('./asset-export-documents');
|
const { ensureAssetExportDocumentSchema } = require('./asset-export-documents');
|
||||||
const { ensureRobotSchema, createRobotRouter } = require('./robots');
|
const { ensureRobotSchema, createRobotRouter } = require('./robots');
|
||||||
|
const { ensureRobotBomSchema, createRobotBomRouter } = require('./robot-bom');
|
||||||
const { getDocumentFormat, isPdfBuffer, validateDocumentFile, normalizeUploadedFileName,
|
const { getDocumentFormat, isPdfBuffer, validateDocumentFile, normalizeUploadedFileName,
|
||||||
sanitizeDocumentFileName, getDocumentContentDisposition, accept: documentAccept } = require('./document-files');
|
sanitizeDocumentFileName, getDocumentContentDisposition, accept: documentAccept } = require('./document-files');
|
||||||
|
|
||||||
@@ -3099,6 +3100,7 @@ async function createTables() {
|
|||||||
await ensureAssetArchiveSchema(pool);
|
await ensureAssetArchiveSchema(pool);
|
||||||
await ensureAssetExportDocumentSchema(pool);
|
await ensureAssetExportDocumentSchema(pool);
|
||||||
await ensureRobotSchema(pool);
|
await ensureRobotSchema(pool);
|
||||||
|
await ensureRobotBomSchema(pool);
|
||||||
await pool.request().query(`
|
await pool.request().query(`
|
||||||
IF COL_LENGTH('dbo.AssetInventory', 'ProjectAllocations') IS NULL
|
IF COL_LENGTH('dbo.AssetInventory', 'ProjectAllocations') IS NULL
|
||||||
ALTER TABLE dbo.AssetInventory ADD ProjectAllocations NVARCHAR(MAX) NULL;
|
ALTER TABLE dbo.AssetInventory ADD ProjectAllocations NVARCHAR(MAX) NULL;
|
||||||
@@ -9529,6 +9531,10 @@ app.use('/api/robots', createRobotRouter({
|
|||||||
sanitizeDocumentFileName, sendInternalError
|
sanitizeDocumentFileName, sendInternalError
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
app.use('/api/robot-boms', createRobotBomRouter({
|
||||||
|
getPool: () => pool, sql, requireManage: requireAssetOrAdmin, sendInternalError
|
||||||
|
}));
|
||||||
|
|
||||||
app.get('/api/documents', async (req, res) => {
|
app.get('/api/documents', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const search = String(req.query.search || '').trim().slice(0, 255);
|
const search = String(req.query.search || '').trim().slice(0, 255);
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ Thay vì lưu rải rác tài khoản ứng dụng ở nhiều nơi, AccManager
|
|||||||
- Theo dõi thông tin tài khoản rõ ràng, tránh thất lạc.
|
- Theo dõi thông tin tài khoản rõ ràng, tránh thất lạc.
|
||||||
- Lưu trữ, tìm kiếm, xem và tải xuống PDF, Word, Excel, PowerPoint, ảnh và tài liệu dùng chung.
|
- Lưu trữ, tìm kiếm, xem và tải xuống PDF, Word, Excel, PowerPoint, ảnh và tài liệu dùng chung.
|
||||||
- Quản lý robot với tên, model, loại, ảnh đại diện và tài liệu đi kèm.
|
- Quản lý robot với tên, model, loại, ảnh đại diện và tài liệu đi kèm.
|
||||||
|
- Lập BOM thành phần robot: chọn tên/model từ tài sản hoặc nhập bên ngoài, tự điền số lượng và nguồn mua/nhà sản xuất.
|
||||||
|
|
||||||
## Ai sẽ sử dụng
|
## Ai sẽ sử dụng
|
||||||
|
|
||||||
@@ -27,6 +28,7 @@ Thay vì lưu rải rác tài khoản ứng dụng ở nhiều nơi, AccManager
|
|||||||
5. Vào mục Tài liệu để tải lên, xem hoặc tải xuống tài liệu dùng chung.
|
5. Vào mục Tài liệu để tải lên, xem hoặc tải xuống tài liệu dùng chung.
|
||||||
6. Dùng nút Xem chi tiết trong danh sách người dùng để kiểm tra đầy đủ thông tin trước khi chỉnh sửa.
|
6. Dùng nút Xem chi tiết trong danh sách người dùng để kiểm tra đầy đủ thông tin trước khi chỉnh sửa.
|
||||||
7. Vào mục Quản lý robot → Danh sách robot để thêm robot, chọn ảnh và gắn tài liệu.
|
7. Vào mục Quản lý robot → Danh sách robot để thêm robot, chọn ảnh và gắn tài liệu.
|
||||||
|
8. Vào Quản lý robot → BOM robot để thêm thành phần, số lượng, nguồn và nhập/xuất Excel. BOM không thay đổi số lượng kho. Xem [hướng dẫn BOM](ROBOT_BOM.md).
|
||||||
|
|
||||||
## Kho tài liệu
|
## Kho tài liệu
|
||||||
|
|
||||||
@@ -43,6 +45,7 @@ Thay vì lưu rải rác tài khoản ứng dụng ở nhiều nơi, AccManager
|
|||||||
- Khi thêm hoặc sửa robot, có thể tải tối đa 10 file mới mỗi lần và chọn nhiều file từ kho Tài liệu, hỗ trợ cùng các định dạng với kho. Mỗi robot được gắn tối đa 100 tài liệu; dung lượng mỗi file theo cấu hình `DOCUMENT_MAX_FILE_SIZE_MB` (mặc định 25 MB).
|
- Khi thêm hoặc sửa robot, có thể tải tối đa 10 file mới mỗi lần và chọn nhiều file từ kho Tài liệu, hỗ trợ cùng các định dạng với kho. Mỗi robot được gắn tối đa 100 tài liệu; dung lượng mỗi file theo cấu hình `DOCUMENT_MAX_FILE_SIZE_MB` (mặc định 25 MB).
|
||||||
- File tải lên cùng robot cũng xuất hiện trong kho Tài liệu. Một tài liệu có thể gắn với nhiều robot.
|
- File tải lên cùng robot cũng xuất hiện trong kho Tài liệu. Một tài liệu có thể gắn với nhiều robot.
|
||||||
- Bỏ chọn tài liệu trong form sửa robot để gỡ liên kết. Xóa robot vẫn giữ tài liệu trong kho; cần gỡ hết liên kết robot trước khi xóa file khỏi kho.
|
- Bỏ chọn tài liệu trong form sửa robot để gỡ liên kết. Xóa robot vẫn giữ tài liệu trong kho; cần gỡ hết liên kết robot trước khi xóa file khỏi kho.
|
||||||
|
- Xóa robot/thể loại mở hộp xác nhận trong ứng dụng, có tên và thông tin mục đang xóa. Bấm Hủy, nút đóng hoặc Escape để quay lại.
|
||||||
- Robot, thể loại, ảnh và tài liệu được lưu trong SQL Server, không cần thư mục upload riêng. Khi khởi động lại backend, hệ thống tự tạo bảng `Robots`, `RobotTypes` và `RobotDocuments` nếu chưa có; các loại robot đã nhập trước đây được tự động chuyển sang danh mục.
|
- Robot, thể loại, ảnh và tài liệu được lưu trong SQL Server, không cần thư mục upload riêng. Khi khởi động lại backend, hệ thống tự tạo bảng `Robots`, `RobotTypes` và `RobotDocuments` nếu chưa có; các loại robot đã nhập trước đây được tự động chuyển sang danh mục.
|
||||||
- Có thể tìm theo tên/model/loại, lọc theo loại và mở hoặc tải tài liệu trong màn hình Chi tiết robot.
|
- Có thể tìm theo tên/model/loại, lọc theo loại và mở hoặc tải tài liệu trong màn hình Chi tiết robot.
|
||||||
|
|
||||||
|
|||||||
56
docs/ROBOT_BOM.md
Normal file
56
docs/ROBOT_BOM.md
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
# BOM robot
|
||||||
|
|
||||||
|
Vào **Quản lý robot → BOM robot** hoặc bấm **BOM** trên thẻ robot. Admin và Asset được lập/sửa/phát hành BOM; tài khoản đã đăng nhập được xem và xuất Excel.
|
||||||
|
|
||||||
|
## Lập BOM đầu tiên
|
||||||
|
|
||||||
|
1. Chọn model robot và bấm **Tạo BOM đầu tiên**. Model lấy từ Danh sách robot; các robot cùng model và thể loại dùng chung bộ phiên bản BOM.
|
||||||
|
2. Bấm **Thêm vật tư**. Chọn **Chọn tài sản có sẵn** để lấy tên/model từ danh sách tài sản, hoặc **Nhập vật tư bên ngoài** để tự nhập thông tin.
|
||||||
|
3. Điền **Tên tài sản / Vật tư**, **Model**, **Số lượng** cho BOM. Model và đơn vị có thể để trống. Số lượng mặc định 1 và tự sửa theo thành phần thực tế của robot.
|
||||||
|
4. Điền **Nguồn** bằng link mua hàng hoặc thông tin nhà sản xuất/nhà cung cấp. Có thể thêm ghi chú.
|
||||||
|
5. Bấm **Thêm vào BOM**, sau đó **Lưu BOM**. **Thêm và tiếp tục** giữ hộp nhập mở để thêm nhiều dòng.
|
||||||
|
|
||||||
|
Hai chế độ thêm vật tư dùng chung kích thước hộp thoại và vị trí các trường. Chuyển chế độ giữ nguyên thông tin đang nhập. **Thêm vào BOM** cập nhật danh sách đang soạn; **Lưu BOM** mới lưu các thay đổi vào hệ thống.
|
||||||
|
|
||||||
|
**Quy tắc nghiệp vụ:** BOM chỉ mô tả thành phần của robot. Chọn tài sản chỉ sao chép tên/model; số lượng BOM tự nhập, không lấy từ kho, không bị giới hạn bởi tồn kho và không trừ số lượng tài sản. Vật tư bên ngoài được thêm trực tiếp mà không cần tạo trong kho trước.
|
||||||
|
|
||||||
|
Tên vật tư là trường bắt buộc. Model, đơn vị, nguồn và ghi chú là tùy chọn. Nếu dùng đơn vị cái/bộ, số lượng cần là số nguyên; đơn vị đo như m/kg/lít hoặc để trống cho phép tối đa 4 chữ số thập phân. Mỗi BOM tối đa 500 dòng; số lượng mỗi dòng lớn hơn 0 và tối đa 100.000.
|
||||||
|
|
||||||
|
## Phiên bản
|
||||||
|
|
||||||
|
- **BOM mới** tạo phiên bản nháp trống cho model đang chọn.
|
||||||
|
- **Sao chép BOM** tạo phiên bản nháp tiếp theo từ phiên bản đang xem. Thay đổi chưa lưu được lưu trước khi sao chép.
|
||||||
|
- **Phát hành** mở hộp xác nhận với model robot, phiên bản và số dòng vật tư. Chọn **Quay lại** để tiếp tục sửa, hoặc **Phát hành BOM** để lưu các thay đổi và khóa phiên bản hiện tại. Có thể bấm Escape để đóng xác nhận. Muốn sửa tiếp, sao chép thành bản nháp mới.
|
||||||
|
- Dùng bộ chọn phiên bản hoặc tab **Lịch sử phiên bản** để xem lại.
|
||||||
|
- **Xóa BOM** xóa vĩnh viễn phiên bản đang chọn (bản nháp hoặc đã phát hành) cùng các dòng vật tư của phiên bản đó. Chỉ Admin/Asset được xóa. Hộp xác nhận hiển thị model, phiên bản và số dòng đã lưu; bấm **Hủy** hoặc Escape để giữ BOM. Các thay đổi chưa lưu của phiên bản bị xóa sẽ bị bỏ. Các phiên bản khác, robot và tài sản trong kho vẫn giữ nguyên. Sau khi xóa, hệ thống chọn phiên bản còn lại mới nhất; nếu đã xóa hết, có thể tạo BOM đầu tiên lại.
|
||||||
|
- Model và BOM cũ vẫn xem/sao chép được sau khi robot cuối cùng của model đó bị xóa hoặc đổi model.
|
||||||
|
- Khi hai người cùng sửa, hệ thống từ chối thao tác lưu/xóa trên phiên bản dữ liệu đã cũ và yêu cầu tải lại để tránh ghi đè hoặc xóa thay đổi của người khác.
|
||||||
|
|
||||||
|
## Excel
|
||||||
|
|
||||||
|
Dùng **Xuất Excel** để lấy file mẫu có sheet `BOM` và sheet thông tin phiên bản.
|
||||||
|
|
||||||
|
| Cột trên sheet BOM | Nội dung |
|
||||||
|
| --- | --- |
|
||||||
|
| Tên vật tư | Tên thành phần bắt buộc; có thể chưa có trong danh sách tài sản |
|
||||||
|
| Model | Model / quy cách tùy chọn |
|
||||||
|
| Số lượng | Số lượng trong BOM, tự nhập; mặc định 1 |
|
||||||
|
| ĐVT | Đơn vị tùy chọn |
|
||||||
|
| Nguồn | Link mua hàng hoặc thông tin nhà sản xuất / nhà cung cấp |
|
||||||
|
| Ghi chú | Ghi chú tùy chọn |
|
||||||
|
|
||||||
|
**Nhập Excel** nhận `.xls`/`.xlsx`, tối đa 10 MB và 500 dòng. Hệ thống kiểm tra toàn bộ file trước khi thay danh sách trên màn hình; file sai giữ nguyên BOM hiện tại. Sau khi nhập, bấm **Lưu thay đổi** để lưu vào database. Có thể xuất bản nháp trống để lấy tên các cột.
|
||||||
|
|
||||||
|
## Thông tin tài sản và nguồn
|
||||||
|
|
||||||
|
Danh sách chọn tài sản cung cấp tên, mã, model và đơn vị để nhập nhanh. Không hiển thị hoặc lấy số lượng kho. Tài sản hết hàng vẫn chọn được. Sau khi thêm, BOM lưu riêng mô tả thành phần; đổi/xóa tài sản không làm thay đổi BOM đã lưu.
|
||||||
|
|
||||||
|
Nguồn nhận cả URL HTTP/HTTPS và văn bản tự do. URL được hiển thị thành liên kết mở trong tab mới; thông tin nhà sản xuất hiển thị nguyên văn. Nguồn được giữ khi lưu, tải lại, sao chép phiên bản và nhập/xuất Excel.
|
||||||
|
|
||||||
|
## Triển khai và kiểm tra
|
||||||
|
|
||||||
|
Backend tự tạo/cập nhật bảng `RobotBomRevisions` và `RobotBomLines` khi khởi động. BOM cũ giữ nguyên tên/model, số lượng, mô tả và phiên bản; liên kết định danh kho cũ được gỡ và bổ sung cột `SourceInfo`. Chạy lại không làm mất BOM đã lưu. Không cần cài dependency mới. Các API `/api/robot-boms` dùng phiên đăng nhập và phân quyền hiện tại.
|
||||||
|
|
||||||
|
- `npm test`: kiểm tra hồi quy và nghiệp vụ BOM.
|
||||||
|
- `ACCMANAGER_BOM_SQL_TEST=1 node --test backend/robot-bom-sql.test.js`: kiểm tra trên database thử riêng, tự tạo/xóa trên SQL Server cấu hình trong `.env`.
|
||||||
|
- `ACCMANAGER_BOM_BROWSER_TEST=1 node --test backend/robot-bom-browser.test.js`: kiểm tra giao diện bằng Chrome với dữ liệu thử trong bộ nhớ. Ảnh kiểm tra lưu tại `output/bom-robot/`.
|
||||||
@@ -7,7 +7,7 @@
|
|||||||
"start": "node backend/server.js",
|
"start": "node backend/server.js",
|
||||||
"dev": "nodemon backend/server.js",
|
"dev": "nodemon backend/server.js",
|
||||||
"review:export": "node tools/export-review-server.js",
|
"review:export": "node tools/export-review-server.js",
|
||||||
"test": "node --test",
|
"test": "node backend/run-tests.js",
|
||||||
"check": "node --check backend/server.js && node --check public/js/app.js && npm audit",
|
"check": "node --check backend/server.js && node --check public/js/app.js && npm audit",
|
||||||
"build:css": "tailwindcss -c tailwind.config.js -i ./public/css/tailwind.css -o ./public/css/main.css --minify",
|
"build:css": "tailwindcss -c tailwind.config.js -i ./public/css/tailwind.css -o ./public/css/main.css --minify",
|
||||||
"watch:css": "tailwindcss -c tailwind.config.js -i ./public/css/tailwind.css -o ./public/css/main.css --watch"
|
"watch:css": "tailwindcss -c tailwind.config.js -i ./public/css/tailwind.css -o ./public/css/main.css --watch"
|
||||||
|
|||||||
229
public/css/robot-bom.css
Normal file
229
public/css/robot-bom.css
Normal file
@@ -0,0 +1,229 @@
|
|||||||
|
.bom-page { height:100%; overflow-y:auto; padding:24px; color:#2a3439; background:#f7f9fb; font-size:14px; }
|
||||||
|
.bom-page h1,.bom-page h2,.bom-page h3,.bom-dialog h2,.bom-dialog h3 { font-family:Manrope,Inter,sans-serif; margin:0; font-weight:800; }
|
||||||
|
.bom-page h1 { font-size:28px; line-height:1.25; margin-bottom:6px; }
|
||||||
|
.bom-page h2,.bom-dialog h3 { font-size:17px; }
|
||||||
|
.bom-page-header { display:flex; align-items:center; justify-content:space-between; gap:20px; margin-bottom:22px; flex-wrap:wrap; }
|
||||||
|
.bom-eyebrow { font-size:10px; letter-spacing:.1em; font-weight:700; color:#64748b; margin:0 0 5px; }
|
||||||
|
.bom-muted { color:#64748b; font-size:13px; }
|
||||||
|
.bom-toolbar,.bom-identity-actions { display:flex; flex-wrap:wrap; gap:8px; }
|
||||||
|
.bom-btn { display:inline-flex; align-items:center; justify-content:center; gap:6px; border:1px solid #d5deea; border-radius:7px; background:white; color:#334155; padding:9px 12px; font-size:12px; font-weight:700; line-height:1.4; white-space:nowrap; cursor:pointer; }
|
||||||
|
.bom-btn:hover:not(:disabled) { background:#edf2ff; border-color:#a9b8e9; color:#3755c3; }
|
||||||
|
.bom-btn:disabled { opacity:.45; cursor:default; }
|
||||||
|
.bom-btn-primary { color:white; background:#3755c3; border-color:#3755c3; }
|
||||||
|
.bom-btn-primary:hover:not(:disabled) { color:white; background:#2848b7; }
|
||||||
|
.bom-btn .material-symbols-outlined { font-size:18px; }
|
||||||
|
.bom-identity { display:flex; align-items:center; gap:18px; flex-wrap:wrap; padding:18px; background:white; border:1px solid #e2e8f0; border-radius:10px; }
|
||||||
|
.bom-robot-icon { display:flex; align-items:center; justify-content:center; width:64px; height:64px; border-radius:12px; background:#edf2ff; color:#3755c3; font-size:36px; flex-shrink:0; }
|
||||||
|
.bom-model-field { flex:1; min-width:180px; }
|
||||||
|
.bom-model-field label,.bom-version-field label { display:block; color:#64748b; font-size:11px; font-weight:600; margin-bottom:5px; }
|
||||||
|
.bom-model-field select { width:100%; max-width:360px; font-weight:700; }
|
||||||
|
.bom-model-field small { display:block; margin-top:5px; color:#64748b; font-size:11px; }
|
||||||
|
.bom-version-field { min-width:170px; }
|
||||||
|
.bom-page select,.bom-page input:not([type=file]),.bom-dialog select,.bom-dialog input:not([type=radio]),.bom-dialog textarea { border:1px solid #d7e0eb; border-radius:6px; background:white; font-size:13px; color:#334155; padding:9px 11px; min-height:38px; }
|
||||||
|
.bom-page input:focus,.bom-page select:focus,.bom-dialog input:focus,.bom-dialog textarea:focus { outline:2px solid #b9c7ff; outline-offset:1px; border-color:#3755c3; }
|
||||||
|
.bom-badge { display:inline-flex; align-items:center; white-space:nowrap; color:#b45309; background:#fffbeb; border:1px solid #fde68a; border-radius:5px; padding:5px 8px; font-size:11px; font-weight:700; }
|
||||||
|
.bom-badge-green { color:#15803d; background:#f0fdf4; border-color:#bbf7d0; }
|
||||||
|
.bom-tabs { display:flex; gap:16px; margin:15px 0 18px; border-bottom:1px solid #e2e8f0; overflow-x:auto; }
|
||||||
|
.bom-tabs button { padding:13px 8px; color:#64748b; font-size:13px; font-weight:600; white-space:nowrap; border-bottom:2px solid transparent; }
|
||||||
|
.bom-tabs button[aria-current=page] { color:#3755c3; border-bottom-color:#3755c3; }
|
||||||
|
.bom-workspace { display:grid; grid-template-columns:minmax(0,1fr) 335px; gap:16px; align-items:start; }
|
||||||
|
.bom-card { background:white; border:1px solid #e2e8f0; border-radius:9px; min-width:0; overflow:hidden; }
|
||||||
|
.bom-main-card { padding:18px; }
|
||||||
|
.bom-card-heading { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:18px; }
|
||||||
|
.bom-main-card>.bom-card-heading { padding:0 0 14px; }
|
||||||
|
.bom-count { display:inline-block; font-size:11px; font-weight:500; color:#64748b; background:#f1f5f9; padding:3px 6px; border-radius:5px; vertical-align:middle; }
|
||||||
|
.bom-filters { display:flex; gap:10px; margin-bottom:14px; }
|
||||||
|
.bom-search { display:flex; align-items:center; position:relative; flex:1; min-width:100px; }
|
||||||
|
.bom-search>.material-symbols-outlined { position:absolute; left:11px; color:#94a3b8; font-size:19px; pointer-events:none; }
|
||||||
|
.bom-search input { width:100%; padding-left:36px!important; }
|
||||||
|
.bom-filters select { max-width:190px; }
|
||||||
|
.bom-table-scroll { overflow-x:auto; width:100%; }
|
||||||
|
.bom-lines-table,.bom-stock-table,.bom-picker-table { width:100%; border-collapse:collapse; font-size:12px; text-align:left; }
|
||||||
|
.bom-lines-table th,.bom-stock-table th,.bom-picker-table th { font-weight:600; background:#f1f5f9; color:#475569; padding:11px 10px; white-space:nowrap; border:1px solid #e2e8f0; }
|
||||||
|
.bom-lines-table td,.bom-stock-table td,.bom-picker-table td { padding:12px 10px; border:1px solid #e2e8f0; vertical-align:middle; }
|
||||||
|
.bom-lines-table strong,.bom-stock-table strong,.bom-picker-table strong { display:block; font-weight:600; }
|
||||||
|
.bom-lines-table small,.bom-stock-table small,.bom-picker-table small,.bom-selected-summary small { display:block; color:#64748b; font-size:10px; margin-top:3px; line-height:1.45; }
|
||||||
|
.bom-lines-table td:first-child { min-width:155px; }
|
||||||
|
.bom-lines-table td:nth-child(2) { min-width:95px; }
|
||||||
|
.bom-lines-table td:nth-child(5) { min-width:140px; max-width:230px; overflow-wrap:anywhere; }
|
||||||
|
.bom-group th { background:#eef3f8; font-size:11px; text-transform:uppercase; color:#334155; padding:10px; }
|
||||||
|
.bom-group .material-symbols-outlined { font-size:17px; margin-right:7px; vertical-align:middle; }
|
||||||
|
.bom-group small { display:inline; margin-left:10px; font-weight:400; font-size:10px; text-transform:none; color:#64748b; }
|
||||||
|
.bom-page input.bom-quantity { width:76px; min-height:32px; padding:5px 6px; }
|
||||||
|
.bom-row-actions { white-space:nowrap; }
|
||||||
|
.bom-row-actions button { padding:4px; color:#64748b; }
|
||||||
|
.bom-row-actions button:hover { color:#3755c3; background:#eff6ff; border-radius:4px; }
|
||||||
|
.bom-row-actions button[data-bom-delete]:hover { color:#dc2626; background:#fef2f2; }
|
||||||
|
.bom-row-actions .material-symbols-outlined { font-size:17px; }
|
||||||
|
.bom-stock-card { padding:18px; }
|
||||||
|
.bom-stock-card>.bom-card-heading { padding:0 0 18px; }
|
||||||
|
.bom-count-field { display:flex; align-items:center; justify-content:space-between; gap:12px; font-size:12px; }
|
||||||
|
.bom-count-field input { width:100px; }
|
||||||
|
.bom-footnote { color:#64748b; font-size:11px; margin:14px 0; line-height:1.6; }
|
||||||
|
.bom-stock-card>.bom-btn { margin-bottom:14px; }
|
||||||
|
.bom-stock-table { font-size:11px; }
|
||||||
|
.bom-stock-table th,.bom-stock-table td { padding:9px 7px; }
|
||||||
|
.bom-stock-table td:not(:first-child),.bom-stock-table th:not(:first-child) { text-align:right; }
|
||||||
|
.bom-stock-table td:first-child { max-width:180px; overflow-wrap:anywhere; }
|
||||||
|
.bom-shortage td { background:#fff7ed; }
|
||||||
|
.bom-danger { color:#c2410c!important; }
|
||||||
|
.bom-success { color:#15803d; font-weight:600; }
|
||||||
|
.bom-stock-result { display:flex; align-items:center; gap:9px; padding:12px; border-radius:7px; margin-top:16px; font-size:12px; }
|
||||||
|
.bom-stock-result small { display:block; margin-top:3px; font-size:11px; }
|
||||||
|
.bom-stock-warning { background:#fff7ed; border:1px solid #fed7aa; color:#c2410c; }
|
||||||
|
.bom-stock-ok { background:#f0fdf4; border:1px solid #bbf7d0; color:#15803d; }
|
||||||
|
.bom-stock-message { padding:20px 0; }
|
||||||
|
.bom-empty { display:flex; flex-direction:column; align-items:center; justify-content:center; text-align:center; padding:52px 20px; gap:12px; color:#64748b; }
|
||||||
|
.bom-empty>.material-symbols-outlined { font-size:36px; color:#94a3b8; }
|
||||||
|
.bom-empty>strong { color:#334155; font-size:16px; }
|
||||||
|
.bom-empty p { font-size:13px; margin:0; }
|
||||||
|
.bom-empty a { color:#3755c3; }
|
||||||
|
.bom-identity+.bom-empty { margin-top:18px; }
|
||||||
|
.bom-alert { border:1px solid #fecaca; color:#b91c1c; background:#fef2f2; border-radius:7px; padding:12px; font-size:13px; margin-bottom:16px; }
|
||||||
|
.bom-sr { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip:rect(0,0,0,0); white-space:nowrap; border:0; }
|
||||||
|
.bom-dialog { margin:auto; width:min(1120px,95vw); max-width:none; max-height:92dvh; overflow-y:auto; border:0; border-radius:10px; padding:0; background:white; color:#2a3439; box-shadow:0 24px 80px #0f172a33; }
|
||||||
|
.bom-dialog::backdrop { background:#0f172a66; }
|
||||||
|
.bom-dialog-header { display:flex; justify-content:space-between; align-items:flex-start; gap:16px; padding:20px; border-bottom:1px solid #e2e8f0; }
|
||||||
|
.bom-dialog-header h2 { font-size:20px; }
|
||||||
|
.bom-dialog-header p { font-size:12px; color:#64748b; margin:5px 0 0; }
|
||||||
|
.bom-dialog-header>button { padding:3px; color:#64748b; }
|
||||||
|
.bom-picker-layout { display:grid; grid-template-columns:minmax(0,1.8fr) minmax(280px,1fr); }
|
||||||
|
.bom-picker-catalog { padding:20px; min-width:0; }
|
||||||
|
.bom-picker-tools { display:flex; gap:14px; flex-wrap:wrap; }
|
||||||
|
.bom-source-tabs { display:flex; gap:5px; }
|
||||||
|
.bom-source-tabs button { padding:9px 12px; border:1px solid #e2e8f0; border-radius:6px; background:white; font-size:12px; font-weight:600; }
|
||||||
|
.bom-source-tabs button[aria-pressed=true] { background:#3755c3; border-color:#3755c3; color:white; }
|
||||||
|
.bom-picker-table-wrap { max-height:410px; overflow:auto; }
|
||||||
|
.bom-picker-table th { position:sticky; top:0; z-index:1; }
|
||||||
|
.bom-picker-table td { padding:12px 8px; }
|
||||||
|
.bom-picker-table td:first-child { width:35px; }
|
||||||
|
.bom-picker-table td:nth-child(2) { min-width:130px; }
|
||||||
|
.bom-picker-table label { cursor:pointer; }
|
||||||
|
.bom-picked-row td { background:#edf3ff; }
|
||||||
|
.bom-picker-pagination { display:flex; align-items:center; justify-content:space-between; gap:10px; color:#64748b; font-size:11px; margin-top:16px; }
|
||||||
|
.bom-picker-pagination>div { display:flex; gap:5px; }
|
||||||
|
.bom-picker-settings { border-left:1px solid #e2e8f0; padding:20px; }
|
||||||
|
.bom-picker-settings>label { display:block; font-size:12px; font-weight:600; margin-top:15px; }
|
||||||
|
.bom-picker-settings label>input,.bom-picker-settings label>textarea { display:block; width:100%; margin-top:6px; font-weight:400; }
|
||||||
|
.bom-selected-summary { padding:12px; background:#f1f5f9; border-radius:7px; font-size:13px; margin-top:12px; }
|
||||||
|
.bom-quantity-unit { display:flex; margin-top:6px; }
|
||||||
|
.bom-quantity-unit input { width:100%; min-width:0; border-radius:6px 0 0 6px!important; font-weight:400; }
|
||||||
|
.bom-quantity-unit>span { display:flex; align-items:center; padding:0 12px; background:#f1f5f9; border:1px solid #d7e0eb; border-left:0; border-radius:0 6px 6px 0; font-size:12px; }
|
||||||
|
.bom-info { display:flex; gap:9px; background:#eff6ff; border-radius:7px; padding:12px; margin-top:20px; font-size:11px; color:#3755c3; }
|
||||||
|
.bom-info p { color:#64748b; margin:4px 0 0; font-size:11px; }
|
||||||
|
.bom-dialog-footer { display:flex; align-items:center; justify-content:space-between; gap:14px; padding:18px 20px; border-top:1px solid #e2e8f0; background:#fdfefe; }
|
||||||
|
.bom-dialog-footer>div { display:flex; flex-wrap:wrap; gap:8px; }
|
||||||
|
@media(min-width:1700px) { .bom-workspace { grid-template-columns:minmax(0,1fr) 390px; } }
|
||||||
|
@media(max-width:1250px) { .bom-workspace { grid-template-columns:minmax(0,1fr); } .bom-stock-card { max-width:none; } .bom-identity-actions { width:100%; } }
|
||||||
|
@media(max-width:760px) { .bom-page { padding:16px; } .bom-page h1 { font-size:24px; } .bom-identity { gap:12px; padding:14px; } .bom-robot-icon { width:45px; height:45px; font-size:28px; } .bom-version-field { min-width:150px; flex:1; } .bom-filters { flex-wrap:wrap; } .bom-filters select { width:100%; max-width:none; } .bom-main-card,.bom-stock-card { padding:14px; } .bom-card-heading h2 { font-size:15px; } .bom-picker-layout { grid-template-columns:minmax(0,1fr); } .bom-picker-settings { border-left:0; border-top:1px solid #e2e8f0; } .bom-picker-table-wrap { max-height:260px; } .bom-picker-pagination { flex-wrap:wrap; } .bom-dialog-footer { flex-wrap:wrap; } .bom-dialog-footer>div { width:100%; justify-content:flex-end; } .bom-tabs { gap:8px; } .bom-tabs button { font-size:12px; } .bom-picker-tools>.bom-search { min-width:100%; } }
|
||||||
|
.bom-lines-table td:first-child { min-width:0; width:48px; color:#64748b; }
|
||||||
|
.bom-lines-table td:nth-child(2) { min-width:180px; }
|
||||||
|
.bom-lines-table td:nth-child(3) { min-width:110px; }
|
||||||
|
.bom-lines-table td:nth-child(5) { min-width:180px; max-width:300px; }
|
||||||
|
.bom-lines-table .bom-quantity-unit { margin:0; align-items:center; gap:7px; }
|
||||||
|
.bom-lines-table .bom-quantity-unit input { width:76px; border-radius:6px!important; }
|
||||||
|
.bom-lines-table .bom-quantity-unit small { margin:0; white-space:nowrap; }
|
||||||
|
.bom-notes,.bom-source-cell { overflow-wrap:anywhere; white-space:pre-wrap; }
|
||||||
|
.bom-source-link { color:#3755c3; text-decoration:underline; text-underline-offset:3px; }
|
||||||
|
.bom-source-link:hover { color:#2848b7; }
|
||||||
|
.bom-history-table { width:100%; border-collapse:collapse; font-size:12px; text-align:left; }
|
||||||
|
.bom-history-table th,.bom-history-table td { border:1px solid #e2e8f0; padding:12px 10px; white-space:nowrap; }
|
||||||
|
.bom-history-table th { background:#f1f5f9; color:#475569; font-weight:600; }
|
||||||
|
.bom-dialog { width:min(620px,95vw); }
|
||||||
|
.bom-entry-tabs { display:flex; flex-wrap:wrap; gap:8px; padding:16px 20px; border-bottom:1px solid #e2e8f0; }
|
||||||
|
.bom-entry-tabs button { border:1px solid #e2e8f0; padding:9px 12px; border-radius:6px; font-size:12px; font-weight:600; }
|
||||||
|
.bom-entry-tabs button[aria-pressed=true] { background:#3755c3; color:white; border-color:#3755c3; }
|
||||||
|
.bom-material-layout { display:grid; grid-template-columns:minmax(0,1fr); }
|
||||||
|
.bom-asset-picker { padding:20px; border-right:1px solid #e2e8f0; min-width:0; }
|
||||||
|
.bom-asset-picker[hidden] { display:none; }
|
||||||
|
.bom-asset-table-wrap { max-height:410px; overflow:auto; }
|
||||||
|
.bom-asset-table { width:100%; border-collapse:collapse; font-size:12px; text-align:left; }
|
||||||
|
.bom-asset-table th,.bom-asset-table td { border:1px solid #e2e8f0; padding:11px 9px; }
|
||||||
|
.bom-asset-table th { background:#f1f5f9; position:sticky; top:0; color:#475569; font-weight:600; }
|
||||||
|
.bom-asset-table tbody tr { cursor:pointer; }
|
||||||
|
.bom-asset-table tbody tr:hover { background:#f7f9fb; }
|
||||||
|
.bom-asset-table strong,.bom-asset-table small { display:block; }
|
||||||
|
.bom-asset-table small { font-size:10px; color:#64748b; margin-top:4px; }
|
||||||
|
.bom-material-fields { padding:20px; min-width:0; }
|
||||||
|
.bom-material-fields label { display:block; font-size:12px; font-weight:600; margin-bottom:16px; }
|
||||||
|
.bom-material-fields label:last-child { margin-bottom:0; }
|
||||||
|
.bom-material-fields label>input,.bom-material-fields label>textarea { display:block; width:100%; margin-top:6px; font-weight:400; }
|
||||||
|
.bom-form-grid { display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1fr); gap:16px; }
|
||||||
|
.bom-optional { font-size:11px; color:#94a3b8; font-weight:400; }
|
||||||
|
.bom-dialog-footer { justify-content:flex-end; }
|
||||||
|
/* Both entry modes share one fixed frame and the same form column. */
|
||||||
|
.bom-entry-dialog { width:min(1100px,95vw); height:min(790px,calc(100dvh - 48px)); max-height:calc(100dvh - 48px); overflow:hidden; }
|
||||||
|
.bom-entry-dialog[open] { display:flex; }
|
||||||
|
.bom-entry-dialog>form { display:flex; flex-direction:column; width:100%; height:100%; min-height:0; }
|
||||||
|
.bom-entry-dialog .bom-dialog-header,.bom-entry-dialog .bom-entry-tabs,.bom-entry-dialog .bom-dialog-footer { flex-shrink:0; }
|
||||||
|
.bom-entry-dialog .bom-material-layout { flex:1; min-height:0; grid-template-columns:minmax(0,1fr) minmax(360px,1.1fr); overflow:hidden; }
|
||||||
|
.bom-entry-context { min-width:0; min-height:0; display:grid; grid-template-columns:minmax(0,1fr); border-right:1px solid #e2e8f0; background:#f8fafc; }
|
||||||
|
.bom-entry-dialog .bom-asset-picker { display:flex; flex-direction:column; min-height:0; border:0; }
|
||||||
|
.bom-entry-dialog .bom-asset-picker[hidden],.bom-external-guide[hidden] { display:none; }
|
||||||
|
.bom-entry-dialog .bom-asset-picker>.bom-search { flex:0 0 auto; }
|
||||||
|
.bom-entry-dialog #bomAssetResults { display:flex; flex:1; flex-direction:column; min-height:0; }
|
||||||
|
.bom-entry-dialog #bomAssetResults>.bom-footnote { flex-shrink:0; margin-bottom:0; }
|
||||||
|
.bom-entry-dialog .bom-asset-table-wrap { flex:1; min-height:0; max-height:none; scrollbar-gutter:stable; }
|
||||||
|
.bom-entry-dialog .bom-material-fields { min-height:0; overflow-y:auto; overscroll-behavior:contain; scrollbar-gutter:stable; padding:22px 24px; }
|
||||||
|
.bom-entry-dialog .bom-material-fields textarea { min-height:66px; max-height:150px; }
|
||||||
|
.bom-entry-dialog .bom-dialog-footer { justify-content:space-between; }
|
||||||
|
.bom-entry-save-hint { max-width:360px; font-size:11px; line-height:1.6; color:#64748b; margin:0; }
|
||||||
|
.bom-external-guide { padding:28px; overflow-y:auto; scrollbar-gutter:stable; }
|
||||||
|
.bom-external-icon { display:flex; align-items:center; justify-content:center; width:52px; height:52px; border-radius:12px; color:#3755c3; background:#e8edff; font-size:28px; margin-bottom:18px; }
|
||||||
|
.bom-external-guide h3 { font-size:19px; margin-bottom:9px; }
|
||||||
|
.bom-external-guide>p { font-size:13px; line-height:1.7; color:#64748b; margin:0; }
|
||||||
|
.bom-external-guide ul { display:flex; flex-direction:column; gap:22px; list-style:none; padding:0; margin:28px 0; }
|
||||||
|
.bom-external-guide li { display:flex; gap:12px; font-size:13px; }
|
||||||
|
.bom-external-guide li>.material-symbols-outlined { color:#3755c3; font-size:20px; margin-top:1px; }
|
||||||
|
.bom-external-guide li strong { font-weight:600; }
|
||||||
|
.bom-external-guide li small { display:block; color:#64748b; margin-top:5px; font-size:12px; line-height:1.6; }
|
||||||
|
.bom-external-guide p.bom-external-note { border-top:1px solid #e2e8f0; padding-top:18px; font-size:11px; }
|
||||||
|
.bom-confirm-dialog { width:min(520px,95vw); }
|
||||||
|
.bom-confirm-heading { display:flex; align-items:center; gap:13px; }
|
||||||
|
.bom-confirm-heading .bom-eyebrow { margin-bottom:4px; }
|
||||||
|
.bom-confirm-icon { display:flex; align-items:center; justify-content:center; flex-shrink:0; width:44px; height:44px; border-radius:12px; background:#e8edff; color:#3755c3; font-size:25px; }
|
||||||
|
.bom-confirm-body { padding:20px 24px 24px; }
|
||||||
|
.bom-confirm-body>p { font-size:13px; line-height:1.7; color:#64748b; margin:0 0 18px; }
|
||||||
|
.bom-publish-summary { display:grid; grid-template-columns:2fr 1fr 1.3fr; gap:16px; background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; padding:16px; margin:0 0 18px; }
|
||||||
|
.bom-publish-summary div { min-width:0; }
|
||||||
|
.bom-publish-summary dt { color:#64748b; font-size:11px; margin-bottom:6px; }
|
||||||
|
.bom-publish-summary dd { margin:0; font-size:13px; font-weight:700; overflow-wrap:anywhere; }
|
||||||
|
.bom-publish-note { display:flex; gap:9px; color:#3755c3; border-radius:7px; background:#eff3ff; padding:12px; }
|
||||||
|
.bom-publish-note>.material-symbols-outlined { font-size:18px; flex-shrink:0; margin-top:1px; }
|
||||||
|
.bom-publish-note p { font-size:12px; line-height:1.7; margin:0; }
|
||||||
|
.bom-confirm-body>p.bom-footnote { margin:14px 0 0; font-size:11px; }
|
||||||
|
.bom-btn:focus-visible { outline:2px solid #3755c3; outline-offset:3px; }
|
||||||
|
.robot-delete-dialog .bom-confirm-icon,.bom-delete-dialog .bom-confirm-icon { color:#dc2626; background:#fef2f2; }
|
||||||
|
.bom-btn.bom-btn-delete { color:#dc2626; border-color:#fecaca; }
|
||||||
|
.bom-btn.bom-btn-delete:hover:not(:disabled) { color:#b91c1c; background:#fef2f2; border-color:#fca5a5; }
|
||||||
|
.robot-delete-card { background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; padding:16px; margin:0 0 18px; }
|
||||||
|
.robot-delete-name { display:block; font-size:16px; font-weight:700; overflow-wrap:anywhere; }
|
||||||
|
.robot-delete-details { display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1fr); gap:16px; margin:16px 0 0; }
|
||||||
|
.robot-delete-details dt { color:#64748b; font-size:11px; margin-bottom:5px; }
|
||||||
|
.robot-delete-details dd { margin:0; font-size:13px; font-weight:600; overflow-wrap:anywhere; }
|
||||||
|
.bom-btn.bom-btn-danger { color:white; background:#dc2626; border-color:#dc2626; }
|
||||||
|
.bom-btn.bom-btn-danger:hover:not(:disabled) { color:white; background:#b91c1c; border-color:#b91c1c; }
|
||||||
|
.bom-btn.bom-btn-danger:focus-visible { outline-color:#dc2626; }
|
||||||
|
@media(max-width:760px) {
|
||||||
|
.bom-entry-dialog { width:calc(100vw - 24px); height:calc(100dvh - 32px); max-height:calc(100dvh - 32px); }
|
||||||
|
.bom-entry-dialog .bom-material-layout { display:flex; flex-direction:column; overflow-y:auto; overscroll-behavior:contain; }
|
||||||
|
.bom-entry-context { flex:0 0 200px; height:200px; border-right:0; border-bottom:1px solid #e2e8f0; }
|
||||||
|
.bom-entry-dialog .bom-material-fields { flex-shrink:0; overflow:visible; padding:16px; }
|
||||||
|
.bom-entry-dialog .bom-asset-picker { padding:14px 16px; overflow:hidden; }
|
||||||
|
.bom-entry-dialog .bom-asset-picker>.bom-footnote { margin:8px 0; font-size:10px; }
|
||||||
|
.bom-entry-tabs { padding:12px 16px; }
|
||||||
|
.bom-entry-tabs button { padding:9px 10px; font-size:11px; }
|
||||||
|
.bom-external-guide { padding:18px; }
|
||||||
|
.bom-external-icon { width:36px; height:36px; font-size:22px; margin-bottom:12px; }
|
||||||
|
.bom-external-guide h3 { font-size:17px; }
|
||||||
|
.bom-external-guide>p { font-size:12px; }
|
||||||
|
.bom-external-guide ul,.bom-external-guide .bom-external-note { display:none; }
|
||||||
|
.bom-entry-save-hint { max-width:none; font-size:10px; }
|
||||||
|
.bom-entry-dialog .bom-dialog-footer { gap:10px; padding:12px 16px; }
|
||||||
|
.bom-entry-dialog .bom-dialog-footer>div { width:100%; justify-content:flex-end; gap:6px; }
|
||||||
|
.bom-entry-dialog .bom-dialog-footer .bom-btn { padding:8px 10px; font-size:11px; }
|
||||||
|
.bom-confirm-body { padding:18px; }
|
||||||
|
.bom-publish-summary { gap:10px; padding:12px; }
|
||||||
|
.bom-confirm-dialog .bom-dialog-header { padding:18px; }
|
||||||
|
.bom-confirm-dialog .bom-dialog-header h2 { font-size:17px; }
|
||||||
|
}
|
||||||
@@ -317,6 +317,14 @@ class AccountManager {
|
|||||||
|
|
||||||
handleRoute(hash) {
|
handleRoute(hash) {
|
||||||
const route = (hash || '#dashboard').replace('#', '') || 'dashboard';
|
const route = (hash || '#dashboard').replace('#', '') || 'dashboard';
|
||||||
|
if (route !== this.currentPage) document.getElementById('robotDeleteDialog')?.close();
|
||||||
|
if (this.currentPage === 'robot-bom' && route !== 'robot-bom') {
|
||||||
|
if (this.robotBom?.dirty && !this.robotBom.discardChanges()) {
|
||||||
|
history.replaceState(null, '', '#robot-bom');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.robotBom?.unmount();
|
||||||
|
}
|
||||||
if (this.isMobileViewport()) {
|
if (this.isMobileViewport()) {
|
||||||
this.closeMobileNav();
|
this.closeMobileNav();
|
||||||
}
|
}
|
||||||
@@ -381,6 +389,10 @@ class AccountManager {
|
|||||||
} else if (page === 'robot-types') {
|
} else if (page === 'robot-types') {
|
||||||
mainContent.innerHTML = this.getRobotTypesContent();
|
mainContent.innerHTML = this.getRobotTypesContent();
|
||||||
this.setupRobotTypeListeners();
|
this.setupRobotTypeListeners();
|
||||||
|
} else if (page === 'robot-bom') {
|
||||||
|
this.robotBom ||= new window.RobotBomController(this);
|
||||||
|
this.robotBom.mount(mainContent, this.pendingBomModel);
|
||||||
|
this.pendingBomModel = null;
|
||||||
} else if (page === 'documents') {
|
} else if (page === 'documents') {
|
||||||
mainContent.innerHTML = this.getDocumentsContent();
|
mainContent.innerHTML = this.getDocumentsContent();
|
||||||
this.setupDocumentListeners();
|
this.setupDocumentListeners();
|
||||||
@@ -3467,9 +3479,12 @@ class AccountManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async deleteRobotType(type) {
|
async deleteRobotType(type) {
|
||||||
if (!this.canCurrentUserManageAssets() || Number(type.RobotCount) > 0) return;
|
if (!this.canCurrentUserManageAssets() || Number(type.RobotCount) > 0 || this.robotDeletionPending) return;
|
||||||
if (!window.confirm(`Xóa thể loại “${type.Name}”?`)) return;
|
this.robotDeletionPending = true;
|
||||||
try {
|
try {
|
||||||
|
if (!await this.confirmRobotDeletion({ title: 'Xóa thể loại robot?', name: type.Name,
|
||||||
|
description: 'Thể loại này sẽ được gỡ khỏi danh mục robot.', label: 'Xóa thể loại',
|
||||||
|
note: 'Chỉ xóa được thể loại chưa có robot hoặc BOM sử dụng.' })) return;
|
||||||
const response = await fetch(`${this.apiBase}/robots/types/${Number(type.TypeId)}`, { method: 'DELETE' });
|
const response = await fetch(`${this.apiBase}/robots/types/${Number(type.TypeId)}`, { method: 'DELETE' });
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
if (!response.ok || !data.success) throw new Error(data.message || 'Không thể xóa thể loại');
|
if (!response.ok || !data.success) throw new Error(data.message || 'Không thể xóa thể loại');
|
||||||
@@ -3477,6 +3492,7 @@ class AccountManager {
|
|||||||
if (this.currentPage === 'robot-types') this.renderView('robot-types');
|
if (this.currentPage === 'robot-types') this.renderView('robot-types');
|
||||||
this.notifySuccess(data.message || 'Đã xóa thể loại robot');
|
this.notifySuccess(data.message || 'Đã xóa thể loại robot');
|
||||||
} catch (error) { this.notifyFailure(error.message); }
|
} catch (error) { this.notifyFailure(error.message); }
|
||||||
|
finally { this.robotDeletionPending = false; }
|
||||||
}
|
}
|
||||||
|
|
||||||
async fetchRobots() {
|
async fetchRobots() {
|
||||||
@@ -3531,6 +3547,7 @@ class AccountManager {
|
|||||||
<div class="mt-4 flex items-center gap-2 border-t border-slate-100 pt-3">
|
<div class="mt-4 flex items-center gap-2 border-t border-slate-100 pt-3">
|
||||||
<span class="mr-auto inline-flex items-center gap-1 text-xs text-slate-500"><span class="material-symbols-outlined text-base">attach_file</span>${Number(robot.DocumentCount) || 0} tài liệu</span>
|
<span class="mr-auto inline-flex items-center gap-1 text-xs text-slate-500"><span class="material-symbols-outlined text-base">attach_file</span>${Number(robot.DocumentCount) || 0} tài liệu</span>
|
||||||
<button type="button" data-robot-action="view" data-robot-id="${Number(robot.RobotId)}" class="rounded-lg border border-slate-200 px-3 py-2 text-xs font-bold text-primary hover:bg-slate-50">Chi tiết</button>
|
<button type="button" data-robot-action="view" data-robot-id="${Number(robot.RobotId)}" class="rounded-lg border border-slate-200 px-3 py-2 text-xs font-bold text-primary hover:bg-slate-50">Chi tiết</button>
|
||||||
|
<button type="button" data-robot-action="bom" data-robot-id="${Number(robot.RobotId)}" class="rounded-lg border border-slate-200 px-3 py-2 text-xs font-bold text-primary hover:bg-slate-50">BOM</button>
|
||||||
${canManage ? `<button type="button" data-robot-action="edit" data-robot-id="${Number(robot.RobotId)}" class="rounded-lg p-2 text-slate-500 hover:bg-slate-100 hover:text-primary" aria-label="Sửa ${this.escapeHtml(robot.Name)}"><span class="material-symbols-outlined text-lg">edit</span></button>
|
${canManage ? `<button type="button" data-robot-action="edit" data-robot-id="${Number(robot.RobotId)}" class="rounded-lg p-2 text-slate-500 hover:bg-slate-100 hover:text-primary" aria-label="Sửa ${this.escapeHtml(robot.Name)}"><span class="material-symbols-outlined text-lg">edit</span></button>
|
||||||
<button type="button" data-robot-action="delete" data-robot-id="${Number(robot.RobotId)}" class="rounded-lg p-2 text-red-600 hover:bg-red-50" aria-label="Xóa ${this.escapeHtml(robot.Name)}"><span class="material-symbols-outlined text-lg">delete</span></button>` : ''}
|
<button type="button" data-robot-action="delete" data-robot-id="${Number(robot.RobotId)}" class="rounded-lg p-2 text-red-600 hover:bg-red-50" aria-label="Xóa ${this.escapeHtml(robot.Name)}"><span class="material-symbols-outlined text-lg">delete</span></button>` : ''}
|
||||||
</div>
|
</div>
|
||||||
@@ -3592,6 +3609,11 @@ class AccountManager {
|
|||||||
try {
|
try {
|
||||||
const id = Number(button.dataset.robotId);
|
const id = Number(button.dataset.robotId);
|
||||||
if (button.dataset.robotAction === 'view') await this.openRobotDetails(id);
|
if (button.dataset.robotAction === 'view') await this.openRobotDetails(id);
|
||||||
|
if (button.dataset.robotAction === 'bom') {
|
||||||
|
const robot = this.robots.find(robot => Number(robot.RobotId) === id);
|
||||||
|
this.pendingBomModel = robot ? { Model: robot.Model, TypeId: robot.TypeId } : null;
|
||||||
|
location.hash = '#robot-bom';
|
||||||
|
}
|
||||||
if (button.dataset.robotAction === 'edit') await this.openRobotForm(id);
|
if (button.dataset.robotAction === 'edit') await this.openRobotForm(id);
|
||||||
if (button.dataset.robotAction === 'delete') await this.deleteRobot(id);
|
if (button.dataset.robotAction === 'delete') await this.deleteRobot(id);
|
||||||
} finally { button.disabled = false; }
|
} finally { button.disabled = false; }
|
||||||
@@ -3788,11 +3810,43 @@ class AccountManager {
|
|||||||
finally { delete dialog.dataset.saving; controls.forEach(control => { control.disabled = false; }); saveButton.textContent = 'Lưu robot'; }
|
finally { delete dialog.dataset.saving; controls.forEach(control => { control.disabled = false; }); saveButton.textContent = 'Lưu robot'; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
confirmRobotDeletion({ title, name, description, note, label, details = [] }) {
|
||||||
|
if (document.getElementById('robotDeleteDialog')) return Promise.resolve(false);
|
||||||
|
const dialog = document.createElement('dialog');
|
||||||
|
dialog.id = 'robotDeleteDialog';
|
||||||
|
dialog.className = 'bom-dialog bom-confirm-dialog robot-delete-dialog';
|
||||||
|
dialog.setAttribute('aria-labelledby', 'robotDeleteTitle');
|
||||||
|
dialog.setAttribute('aria-describedby', 'robotDeleteDescription');
|
||||||
|
dialog.innerHTML = `<header class="bom-dialog-header"><div class="bom-confirm-heading"><span class="bom-confirm-icon material-symbols-outlined" aria-hidden="true">delete</span><div><p class="bom-eyebrow">QUẢN LÝ ROBOT</p><h2 id="robotDeleteTitle">${this.escapeHtml(title)}</h2></div></div><button type="button" data-cancel-robot-delete aria-label="Đóng"><span class="material-symbols-outlined">close</span></button></header>
|
||||||
|
<div class="bom-confirm-body"><p id="robotDeleteDescription">${this.escapeHtml(description)}</p>
|
||||||
|
<div class="robot-delete-card"><strong class="robot-delete-name">${this.escapeHtml(name)}</strong>${details.length ? `<dl class="robot-delete-details">${details.map(([key, value]) => `<div><dt>${this.escapeHtml(key)}</dt><dd>${this.escapeHtml(value || '—')}</dd></div>`).join('')}</dl>` : ''}</div>
|
||||||
|
<div class="bom-publish-note"><span class="material-symbols-outlined" aria-hidden="true">info</span><p>${this.escapeHtml(note)}</p></div></div>
|
||||||
|
<footer class="bom-dialog-footer"><div><button type="button" data-cancel-robot-delete class="bom-btn">Hủy</button><button type="button" data-confirm-robot-delete class="bom-btn bom-btn-danger"><span class="material-symbols-outlined" aria-hidden="true">delete</span>${this.escapeHtml(label)}</button></div></footer>`;
|
||||||
|
return new Promise(resolve => {
|
||||||
|
dialog.addEventListener('click', event => {
|
||||||
|
if (event.target.closest('[data-confirm-robot-delete]')) dialog.close('confirm');
|
||||||
|
else if (event.target.closest('[data-cancel-robot-delete]')) dialog.close();
|
||||||
|
else if (event.target === dialog) {
|
||||||
|
const rect = dialog.getBoundingClientRect();
|
||||||
|
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) dialog.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
dialog.addEventListener('close', () => { dialog.remove(); resolve(dialog.returnValue === 'confirm'); }, { once: true });
|
||||||
|
document.body.appendChild(dialog); dialog.showModal();
|
||||||
|
dialog.querySelector('.bom-dialog-footer [data-cancel-robot-delete]').focus({ preventScroll: true });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
async deleteRobot(robotId) {
|
async deleteRobot(robotId) {
|
||||||
if (!this.canCurrentUserManageAssets()) return;
|
if (!this.canCurrentUserManageAssets() || this.robotDeletionPending) return;
|
||||||
const robot = this.robots.find(item => Number(item.RobotId) === Number(robotId));
|
const robot = this.robots.find(item => Number(item.RobotId) === Number(robotId));
|
||||||
if (!robot || !window.confirm(`Xóa robot “${robot.Name}”? Các tài liệu vẫn được giữ trong kho.`)) return;
|
if (!robot) return;
|
||||||
|
this.robotDeletionPending = true;
|
||||||
try {
|
try {
|
||||||
|
if (!await this.confirmRobotDeletion({ title: 'Xóa robot này?', name: robot.Name,
|
||||||
|
description: 'Robot này sẽ được gỡ khỏi danh sách quản lý.', label: 'Xóa robot',
|
||||||
|
details: [['Model', robot.Model], ['Thể loại', robot.Type]],
|
||||||
|
note: 'Tài liệu đính kèm vẫn được giữ trong kho tài liệu.' })) return;
|
||||||
const response = await fetch(`${this.apiBase}/robots/${Number(robotId)}`, { method: 'DELETE' });
|
const response = await fetch(`${this.apiBase}/robots/${Number(robotId)}`, { method: 'DELETE' });
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
if (!response.ok || !data.success) throw new Error(data.message || 'Không thể xóa robot');
|
if (!response.ok || !data.success) throw new Error(data.message || 'Không thể xóa robot');
|
||||||
@@ -3800,6 +3854,7 @@ class AccountManager {
|
|||||||
if (this.currentPage === 'robots') this.renderView('robots');
|
if (this.currentPage === 'robots') this.renderView('robots');
|
||||||
this.notifySuccess(data.message || 'Đã xóa robot');
|
this.notifySuccess(data.message || 'Đã xóa robot');
|
||||||
} catch (error) { this.notifyFailure(error.message); }
|
} catch (error) { this.notifyFailure(error.message); }
|
||||||
|
finally { this.robotDeletionPending = false; }
|
||||||
}
|
}
|
||||||
|
|
||||||
isSupportedDocumentName(fileName) {
|
isSupportedDocumentName(fileName) {
|
||||||
|
|||||||
288
public/js/robot-bom.js
Normal file
288
public/js/robot-bom.js
Normal file
@@ -0,0 +1,288 @@
|
|||||||
|
/* Descriptive robot BOM: asset names/models may be copied; BOM quantities are entered independently. */
|
||||||
|
(() => {
|
||||||
|
'use strict';
|
||||||
|
const modelKey = item => JSON.stringify([Number(item.TypeId), item.Model]);
|
||||||
|
const number = value => Number(value || 0).toLocaleString('vi-VN', { maximumFractionDigits: 4 });
|
||||||
|
const fractionalUnit = unit => !String(unit).trim() || /^(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());
|
||||||
|
|
||||||
|
class RobotBomController {
|
||||||
|
constructor(app) {
|
||||||
|
this.app = app; this.models = []; this.revisions = []; this.lines = [];
|
||||||
|
this.header = null; this.modelId = ''; this.dirty = false; this.busy = false;
|
||||||
|
this.query = ''; this.tab = 'bom';
|
||||||
|
this.beforeUnload = event => { if (this.dirty) { event.preventDefault(); event.returnValue = ''; } };
|
||||||
|
}
|
||||||
|
escape(value) { return this.app.escapeHtml(String(value ?? '')); }
|
||||||
|
canManage() { return this.app.canCurrentUserManageAssets(); }
|
||||||
|
editable() { return this.canManage() && this.header?.Status === 'draft'; }
|
||||||
|
active() { return this.app.currentPage === 'robot-bom'; }
|
||||||
|
async api(suffix, options = {}) {
|
||||||
|
const response = await fetch(`${this.app.apiBase}/robot-boms${suffix}`, { cache: 'no-store', ...options,
|
||||||
|
headers: { ...(options.body ? { 'Content-Type': 'application/json' } : {}), ...options.headers } });
|
||||||
|
const result = await response.json();
|
||||||
|
if (!response.ok || !result.success) throw new Error(result.message || 'Không thể tải dữ liệu BOM');
|
||||||
|
return result.data;
|
||||||
|
}
|
||||||
|
async mount(root, preferredModel) {
|
||||||
|
this.root = root; this.busy = true; this.error = ''; this.dirty = false;
|
||||||
|
window.addEventListener('beforeunload', this.beforeUnload); this.render();
|
||||||
|
try {
|
||||||
|
this.models = await this.api('/models');
|
||||||
|
const selected = this.models.find(item => preferredModel && typeof preferredModel === 'object'
|
||||||
|
? item.Model === preferredModel.Model && item.TypeId === preferredModel.TypeId : item.Model === preferredModel)
|
||||||
|
|| this.models.find(item => modelKey(item) === this.modelId) || this.models[0];
|
||||||
|
this.modelId = selected ? modelKey(selected) : ''; await this.loadModel();
|
||||||
|
} catch (error) { this.error = error.message; }
|
||||||
|
finally { this.busy = false; this.render(); }
|
||||||
|
}
|
||||||
|
unmount() {
|
||||||
|
window.removeEventListener('beforeunload', this.beforeUnload);
|
||||||
|
document.getElementById('bomComponentDialog')?.close();
|
||||||
|
document.getElementById('bomPublishDialog')?.close();
|
||||||
|
document.getElementById('bomDeleteDialog')?.close();
|
||||||
|
}
|
||||||
|
selectedModel() { return this.models.find(item => modelKey(item) === this.modelId); }
|
||||||
|
async loadModel(preferredId) {
|
||||||
|
const model = this.selectedModel();
|
||||||
|
this.header = null; this.lines = []; this.revisions = []; this.dirty = false; this.query = ''; this.error = '';
|
||||||
|
if (!model) return;
|
||||||
|
this.revisions = await this.api(`?model=${encodeURIComponent(model.Model)}&typeId=${model.TypeId}`);
|
||||||
|
const revision = this.revisions.find(item => Number(item.BomId) === Number(preferredId)) || this.revisions[0];
|
||||||
|
if (revision) await this.loadRevision(revision.BomId);
|
||||||
|
}
|
||||||
|
async loadRevision(id) { const data = await this.api(`/${Number(id)}`); this.header = data; this.lines = data.Lines || []; this.dirty = false; }
|
||||||
|
async run(action) {
|
||||||
|
if (this.busy) return; this.busy = true; this.render();
|
||||||
|
try { await action(); } catch (error) { this.app.notifyFailure(error.message); }
|
||||||
|
finally { this.busy = false; this.render(); }
|
||||||
|
}
|
||||||
|
discardChanges() { return !this.dirty || window.confirm('BOM có thay đổi chưa lưu. Bỏ các thay đổi này?'); }
|
||||||
|
payload() {
|
||||||
|
return this.lines.map(line => ({ name: line.Name, model: line.Model || '', quantity: line.Quantity ?? 1, unit: line.Unit || '',
|
||||||
|
sourceInfo: line.SourceInfo || '', notes: line.Notes || '', code: line.Code || '', groupName: line.GroupName || '', position: line.Position || '' }));
|
||||||
|
}
|
||||||
|
validateLine(line) {
|
||||||
|
if (typeof line.Name !== 'string' || !line.Name.trim() || line.Name.trim().length > 255) throw new Error('Nhập tên tài sản / vật tư, tối đa 255 ký tự.');
|
||||||
|
const value = line.Quantity ?? 1;
|
||||||
|
if (!/^\d+(\.\d{1,4})?$/.test(String(value)) || Number(value) <= 0 || Number(value) > 100000) throw new Error('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.');
|
||||||
|
if (!fractionalUnit(line.Unit || '') && !Number.isInteger(Number(value))) throw new Error(`Đơn vị ${line.Unit} yêu cầu số lượng nguyên.`);
|
||||||
|
if ((line.Model || '').length > 255 || (line.Unit || '').length > 50 || (line.Notes || '').length > 500 || (line.SourceInfo || '').length > 1000) throw new Error('Model tối đa 255, đơn vị 50, ghi chú 500 và nguồn 1.000 ký tự.');
|
||||||
|
}
|
||||||
|
validateLines(lines) { if (lines.length > 500) throw new Error('BOM tối đa 500 dòng vật tư.'); lines.forEach(line => this.validateLine(line)); }
|
||||||
|
async persistDraft() {
|
||||||
|
this.validateLines(this.lines);
|
||||||
|
const saved = await this.api(`/${this.header.BomId}`, { method: 'PUT', body: JSON.stringify({ lockVersion: this.header.LockVersion, lines: this.payload() }) });
|
||||||
|
this.header.LockVersion = saved.LockVersion; this.lines = saved.Lines; this.dirty = false;
|
||||||
|
this.header.UpdatedDate = saved.UpdatedDate || this.header.UpdatedDate;
|
||||||
|
const revision = this.revisions.find(item => item.BomId === this.header.BomId);
|
||||||
|
if (revision) { revision.LineCount = this.lines.length; revision.LockVersion = saved.LockVersion; revision.UpdatedDate = this.header.UpdatedDate; }
|
||||||
|
}
|
||||||
|
changed() { this.dirty = true; this.render(); }
|
||||||
|
button(action, label, icon, primary = false, disabled = false) {
|
||||||
|
return `<button type="button" data-bom-action="${action}" class="bom-btn ${primary ? 'bom-btn-primary' : ''} ${action === 'delete' ? 'bom-btn-delete' : ''}" ${disabled || this.busy ? 'disabled' : ''}>${icon ? `<span class="material-symbols-outlined" aria-hidden="true">${icon}</span>` : ''}${label}</button>`;
|
||||||
|
}
|
||||||
|
sourceHtml(value) {
|
||||||
|
if (!value) return '<span class="bom-muted">—</span>';
|
||||||
|
try {
|
||||||
|
const url = new URL(value);
|
||||||
|
if (['https:', 'http:'].includes(url.protocol)) return `<a class="bom-source-link" href="${this.escape(url.href)}" target="_blank" rel="noopener noreferrer">${this.escape(value)}</a>`;
|
||||||
|
} catch {}
|
||||||
|
return `<span class="bom-source-text">${this.escape(value)}</span>`;
|
||||||
|
}
|
||||||
|
tableHtml() {
|
||||||
|
const keyword = this.query.trim().toLocaleLowerCase('vi');
|
||||||
|
const rows = this.lines.map((line, index) => ({ line, index })).filter(({ line }) => !keyword || [line.Name, line.Code, line.Model, line.SourceInfo, line.Notes].some(value => String(value || '').toLocaleLowerCase('vi').includes(keyword)));
|
||||||
|
if (!rows.length) return `<div class="bom-empty"><span class="material-symbols-outlined">view_list</span><strong>${this.lines.length ? 'Không tìm thấy vật tư phù hợp' : 'Chưa có thành phần trong BOM'}</strong><p>${this.lines.length ? 'Thử từ khóa khác.' : 'Thêm tài sản sẵn có hoặc nhập vật tư từ bên ngoài.'}</p></div>`;
|
||||||
|
const edit = this.editable() && !this.busy;
|
||||||
|
return `<div class="bom-table-scroll"><table class="bom-lines-table"><thead><tr><th>STT</th><th>Tên tài sản / Vật tư</th><th>Model</th><th>Số lượng</th><th>Nguồn</th><th>Ghi chú</th>${this.canManage() ? '<th><span class="bom-sr">Thao tác</span></th>' : ''}</tr></thead><tbody>${rows.map(({ line, index }) => `<tr><td>${index + 1}</td><td><strong>${this.escape(line.Name)}</strong>${line.Code ? `<small>${this.escape(line.Code)}</small>` : ''}</td><td>${this.escape(line.Model || '—')}</td><td><div class="bom-quantity-unit">${edit ? `<input class="bom-quantity" type="number" data-bom-quantity="${index}" min="${fractionalUnit(line.Unit || '') ? '0.0001' : '1'}" max="100000" step="${fractionalUnit(line.Unit || '') ? '0.0001' : '1'}" value="${Number(line.Quantity ?? 1)}" aria-label="Số lượng ${this.escape(line.Name)}">` : number(line.Quantity ?? 1)}${line.Unit ? `<small>${this.escape(line.Unit)}</small>` : ''}</div></td><td class="bom-source-cell">${this.sourceHtml(line.SourceInfo)}</td><td class="bom-notes">${this.escape(line.Notes || '—')}</td>${this.canManage() ? `<td class="bom-row-actions">${edit ? `<button type="button" data-bom-edit="${index}" aria-label="Sửa ${this.escape(line.Name)}"><span class="material-symbols-outlined">edit</span></button><button type="button" data-bom-delete="${index}" aria-label="Xóa ${this.escape(line.Name)}"><span class="material-symbols-outlined">delete</span></button>` : '—'}</td>` : ''}</tr>`).join('')}</tbody></table></div>`;
|
||||||
|
}
|
||||||
|
historyHtml() {
|
||||||
|
return `<div class="bom-table-scroll"><table class="bom-history-table"><thead><tr><th>Phiên bản</th><th>Trạng thái</th><th>Số dòng</th><th>Cập nhật</th><th>Phát hành</th><th></th></tr></thead><tbody>${this.revisions.map(revision => `<tr><td><strong>v${Number(revision.Revision)}</strong></td><td><span class="bom-badge ${revision.Status === 'released' ? 'bom-badge-green' : ''}">${revision.Status === 'released' ? 'Đã phát hành' : 'Bản nháp'}</span></td><td>${number(revision.LineCount)}</td><td>${this.escape(this.app.formatDateTime(revision.UpdatedDate))}</td><td>${revision.ReleasedDate ? this.escape(this.app.formatDateTime(revision.ReleasedDate)) : '—'}</td><td><button class="bom-btn" data-bom-open="${Number(revision.BomId)}" ${this.busy ? 'disabled' : ''}>Xem BOM</button></td></tr>`).join('')}</tbody></table></div>`;
|
||||||
|
}
|
||||||
|
render() {
|
||||||
|
if (!this.active()) return;
|
||||||
|
const model = this.selectedModel(); const disabled = this.busy ? 'disabled' : ''; const edit = this.editable();
|
||||||
|
this.root.innerHTML = `<section class="bom-page" data-bom-page><header class="bom-page-header"><div><p class="bom-eyebrow">THÀNH PHẦN ROBOT</p><h1>BOM robot</h1><p class="bom-muted">Danh sách tài sản và vật tư cấu tạo của robot.</p></div><div class="bom-toolbar">${this.button('refresh', 'Làm mới', 'refresh')}${this.canManage() ? this.button('import', 'Nhập Excel', 'upload', false, !edit) : ''}${this.button('export', 'Xuất Excel', 'download', false, !this.header)}${this.canManage() ? this.button('save', this.dirty ? 'Lưu thay đổi' : 'Lưu BOM', 'save', true, !edit) : ''}</div></header>${this.error ? `<div class="bom-alert" role="alert">${this.escape(this.error)}. Bấm Làm mới để thử lại.</div>` : ''}
|
||||||
|
<section class="bom-identity"><span class="bom-robot-icon material-symbols-outlined" aria-hidden="true">smart_toy</span><div class="bom-model-field"><label for="bomModel">Model robot</label><select id="bomModel" ${disabled}><option value="" ${this.models.length ? 'hidden' : ''}>${this.busy ? 'Đang tải…' : 'Chưa có robot'}</option>${this.models.map(item => `<option value="${this.escape(modelKey(item))}" ${this.modelId === modelKey(item) ? 'selected' : ''}>${this.escape(item.Model)} · ${this.escape(item.Type)}</option>`).join('')}</select><small>${this.escape(model?.Name || 'Thêm robot trong Danh sách robot để bắt đầu.')}</small></div><div class="bom-version-field"><label for="bomRevision">Phiên bản BOM</label><select id="bomRevision" ${disabled || !this.header ? 'disabled' : ''}>${this.revisions.length ? this.revisions.map(item => `<option value="${Number(item.BomId)}" ${this.header?.BomId === item.BomId ? 'selected' : ''}>v${Number(item.Revision)} · ${item.Status === 'released' ? 'Đã phát hành' : 'Bản nháp'}</option>`).join('') : '<option>Chưa có BOM</option>'}</select></div>${this.header ? `<span class="bom-badge ${this.header.Status === 'released' ? 'bom-badge-green' : ''}">${this.header.Status === 'released' ? 'Đã phát hành' : this.dirty ? 'Chưa lưu thay đổi' : 'Bản nháp'}</span>` : ''}${this.canManage() ? `<div class="bom-identity-actions">${this.button('new', 'BOM mới', 'add', false, !model?.RobotId)}${this.header ? this.button('copy', 'Sao chép BOM', 'content_copy') + this.button('publish', 'Phát hành', 'send', false, !edit || !this.lines.length) + this.button('delete', 'Xóa BOM', 'delete') : ''}</div>` : ''}</section>
|
||||||
|
${!this.header ? `<div class="bom-card bom-empty"><span class="material-symbols-outlined">inventory_2</span><strong>${this.busy ? 'Đang tải BOM…' : this.models.length ? 'Model robot này chưa có BOM' : 'Chưa có model robot'}</strong><p>${this.models.length ? 'Tạo BOM và thêm các vật tư cấu thành robot.' : '<a href="#robots">Đến Danh sách robot để thêm robot.</a>'}</p>${this.canManage() && model ? this.button('new', 'Tạo BOM đầu tiên', 'add', true) : ''}</div>` : `<nav class="bom-tabs" aria-label="Nội dung BOM">${[['bom', 'Thành phần robot'], ['history', 'Lịch sử phiên bản']].map(([tab, label]) => `<button type="button" data-bom-tab="${tab}" aria-current="${this.tab === tab ? 'page' : 'false'}">${label}</button>`).join('')}</nav><section class="bom-card bom-main-card"><div class="bom-card-heading"><h2>${this.tab === 'history' ? 'Lịch sử phiên bản' : 'Danh sách thành phần'} <span class="bom-count">${this.tab === 'history' ? this.revisions.length + ' phiên bản' : this.lines.length + ' vật tư'}</span></h2>${edit && this.tab === 'bom' ? this.button('add', 'Thêm vật tư', 'add', true) : ''}</div>${this.tab === 'history' ? this.historyHtml() : `<div class="bom-filters"><label class="bom-search"><span class="material-symbols-outlined" aria-hidden="true">search</span><input id="bomSearch" type="search" value="${this.escape(this.query)}" placeholder="Tìm tên, model, nguồn hoặc ghi chú…" aria-label="Tìm vật tư trong BOM"></label></div><div id="bomLineRows">${this.tableHtml()}</div>`}</section>`}<input id="bomImportFile" class="bom-sr" type="file" accept=".xls,.xlsx" aria-label="Chọn file BOM Excel"></section>`;
|
||||||
|
const page = this.root.querySelector('[data-bom-page]'); page.addEventListener('click', event => this.click(event)); page.addEventListener('change', event => this.change(event));
|
||||||
|
page.addEventListener('input', event => { if (event.target.id === 'bomSearch') { this.query = event.target.value; this.root.querySelector('#bomLineRows').innerHTML = this.tableHtml(); } });
|
||||||
|
}
|
||||||
|
confirmPublication() {
|
||||||
|
if (this.publishConfirmation) return this.publishConfirmation;
|
||||||
|
const dialog = document.createElement('dialog');
|
||||||
|
dialog.id = 'bomPublishDialog'; dialog.className = 'bom-dialog bom-confirm-dialog';
|
||||||
|
dialog.setAttribute('aria-labelledby', 'bomPublishTitle');
|
||||||
|
dialog.setAttribute('aria-describedby', 'bomPublishDescription');
|
||||||
|
dialog.innerHTML = `<header class="bom-dialog-header"><div class="bom-confirm-heading"><span class="bom-confirm-icon material-symbols-outlined" aria-hidden="true">task_alt</span><div><p class="bom-eyebrow">CHỐT PHIÊN BẢN</p><h2 id="bomPublishTitle">Phát hành BOM v${Number(this.header.Revision)}?</h2></div></div><button type="button" data-bom-publish-cancel aria-label="Đóng"><span class="material-symbols-outlined">close</span></button></header>
|
||||||
|
<div class="bom-confirm-body"><p id="bomPublishDescription">Phiên bản này sẽ được khóa chỉnh sửa sau khi phát hành.</p><dl class="bom-publish-summary"><div><dt>Model robot</dt><dd>${this.escape(this.header.RobotModel)}</dd></div><div><dt>Phiên bản</dt><dd>v${Number(this.header.Revision)}</dd></div><div><dt>Thành phần</dt><dd>${this.lines.length} dòng vật tư</dd></div></dl>
|
||||||
|
<div class="bom-publish-note"><span class="material-symbols-outlined" aria-hidden="true">info</span><p>Khi cần thay đổi, dùng <strong>Sao chép BOM</strong> để tạo phiên bản nháp mới.</p></div>${this.dirty ? '<p class="bom-footnote">Các thay đổi chưa lưu sẽ được lưu trước khi phát hành.</p>' : ''}</div>
|
||||||
|
<footer class="bom-dialog-footer"><div><button type="button" data-bom-publish-cancel class="bom-btn">Quay lại</button><button type="button" data-bom-publish-confirm class="bom-btn bom-btn-primary"><span class="material-symbols-outlined" aria-hidden="true">lock</span>Phát hành BOM</button></div></footer>`;
|
||||||
|
this.publishConfirmation = new Promise(resolve => {
|
||||||
|
dialog.addEventListener('click', event => {
|
||||||
|
if (event.target.closest('[data-bom-publish-confirm]')) dialog.close('confirm');
|
||||||
|
else if (event.target.closest('[data-bom-publish-cancel]')) dialog.close();
|
||||||
|
else if (event.target === dialog) {
|
||||||
|
const rect = dialog.getBoundingClientRect();
|
||||||
|
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) dialog.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
dialog.addEventListener('close', () => {
|
||||||
|
const confirmed = dialog.returnValue === 'confirm';
|
||||||
|
dialog.remove(); this.publishConfirmation = null; resolve(confirmed);
|
||||||
|
}, { once: true });
|
||||||
|
document.body.appendChild(dialog); dialog.showModal();
|
||||||
|
dialog.querySelector('.bom-dialog-footer [data-bom-publish-cancel]').focus({ preventScroll: true });
|
||||||
|
});
|
||||||
|
return this.publishConfirmation;
|
||||||
|
}
|
||||||
|
confirmDeletion() {
|
||||||
|
if (this.deleteConfirmation) return this.deleteConfirmation;
|
||||||
|
const dialog = document.createElement('dialog');
|
||||||
|
dialog.id = 'bomDeleteDialog'; dialog.className = 'bom-dialog bom-confirm-dialog bom-delete-dialog';
|
||||||
|
dialog.setAttribute('aria-labelledby', 'bomDeleteTitle');
|
||||||
|
dialog.setAttribute('aria-describedby', 'bomDeleteDescription');
|
||||||
|
const revision = this.revisions.find(item => item.BomId === this.header.BomId);
|
||||||
|
dialog.innerHTML = `<header class="bom-dialog-header"><div class="bom-confirm-heading"><span class="bom-confirm-icon material-symbols-outlined" aria-hidden="true">delete</span><div><p class="bom-eyebrow">XÓA PHIÊN BẢN</p><h2 id="bomDeleteTitle">Xóa BOM v${Number(this.header.Revision)}?</h2></div></div><button type="button" data-bom-delete-cancel aria-label="Đóng"><span class="material-symbols-outlined">close</span></button></header>
|
||||||
|
<div class="bom-confirm-body"><p id="bomDeleteDescription">BOM này và toàn bộ vật tư trong phiên bản sẽ bị xóa vĩnh viễn. Thao tác này không thể hoàn tác.</p><dl class="bom-publish-summary"><div><dt>Model robot</dt><dd>${this.escape(this.header.RobotModel)}</dd></div><div><dt>Phiên bản</dt><dd>v${Number(this.header.Revision)}</dd></div><div><dt>Thành phần đã lưu</dt><dd>${number(revision?.LineCount ?? this.lines.length)} dòng vật tư</dd></div></dl><p class="bom-footnote">Chỉ xóa phiên bản đang chọn. Các phiên bản BOM khác, robot và tài sản trong kho vẫn được giữ nguyên.</p>${this.dirty ? '<p class="bom-footnote">Các thay đổi chưa lưu của phiên bản này cũng sẽ bị bỏ.</p>' : ''}</div>
|
||||||
|
<footer class="bom-dialog-footer"><div><button type="button" data-bom-delete-cancel class="bom-btn">Hủy</button><button type="button" data-bom-delete-confirm class="bom-btn bom-btn-danger"><span class="material-symbols-outlined" aria-hidden="true">delete</span>Xóa BOM</button></div></footer>`;
|
||||||
|
this.deleteConfirmation = new Promise(resolve => {
|
||||||
|
dialog.addEventListener('click', event => {
|
||||||
|
if (event.target.closest('[data-bom-delete-confirm]')) dialog.close('confirm');
|
||||||
|
else if (event.target.closest('[data-bom-delete-cancel]')) dialog.close();
|
||||||
|
else if (event.target === dialog) {
|
||||||
|
const rect = dialog.getBoundingClientRect();
|
||||||
|
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) dialog.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
dialog.addEventListener('close', () => {
|
||||||
|
const confirmed = dialog.returnValue === 'confirm';
|
||||||
|
dialog.remove(); this.deleteConfirmation = null; resolve(confirmed);
|
||||||
|
}, { once: true });
|
||||||
|
document.body.appendChild(dialog); dialog.showModal();
|
||||||
|
dialog.querySelector('.bom-dialog-footer [data-bom-delete-cancel]').focus({ preventScroll: true });
|
||||||
|
});
|
||||||
|
return this.deleteConfirmation;
|
||||||
|
}
|
||||||
|
async click(event) {
|
||||||
|
const tab = event.target.closest('[data-bom-tab]'); if (tab && !this.busy) { this.tab = tab.dataset.bomTab; this.render(); return; }
|
||||||
|
const open = event.target.closest('[data-bom-open]'); if (open && !this.busy && this.discardChanges()) { await this.run(async () => { await this.loadRevision(open.dataset.bomOpen); this.tab = 'bom'; }); return; }
|
||||||
|
const edit = event.target.closest('[data-bom-edit]'); const remove = event.target.closest('[data-bom-delete]');
|
||||||
|
if ((edit || remove) && this.editable() && !this.busy) { const index = Number((edit || remove).dataset[edit ? 'bomEdit' : 'bomDelete']); if (!this.lines[index]) return; if (edit) this.openMaterialForm(index); else { this.lines.splice(index, 1); this.changed(); } return; }
|
||||||
|
const button = event.target.closest('[data-bom-action]'); if (!button || button.disabled || this.busy) return;
|
||||||
|
const action = button.dataset.bomAction;
|
||||||
|
if (action === 'add' && this.editable()) return this.openMaterialForm();
|
||||||
|
if (action === 'export') return this.exportWorkbook();
|
||||||
|
if (action === 'import' && this.editable()) return this.root.querySelector('#bomImportFile').click();
|
||||||
|
if (action === 'refresh' && this.discardChanges()) return this.mount(this.root, this.selectedModel());
|
||||||
|
if (!this.canManage()) return;
|
||||||
|
if (action === 'delete' && this.header) {
|
||||||
|
const { BomId: bomId, LockVersion: lockVersion, Revision: revision } = this.header;
|
||||||
|
const selectedModelId = this.modelId;
|
||||||
|
if (!await this.confirmDeletion() || this.busy || !this.active() || !this.canManage()
|
||||||
|
|| this.header?.BomId !== bomId || this.header.LockVersion !== lockVersion || this.modelId !== selectedModelId) return;
|
||||||
|
return this.run(async () => {
|
||||||
|
await this.api(`/${bomId}`, { method: 'DELETE', body: JSON.stringify({ lockVersion }) });
|
||||||
|
this.header = null; this.lines = []; this.revisions = []; this.dirty = false;
|
||||||
|
this.app.notifySuccess(`Đã xóa BOM v${revision}.`);
|
||||||
|
this.models = await this.api('/models');
|
||||||
|
this.modelId = this.models.find(item => modelKey(item) === selectedModelId) ? selectedModelId : this.models[0] ? modelKey(this.models[0]) : '';
|
||||||
|
await this.loadModel(); this.tab = 'bom';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (action === 'save' && this.editable()) return this.run(async () => { await this.persistDraft(); this.app.notifySuccess('Đã lưu BOM.'); });
|
||||||
|
if (['new', 'copy'].includes(action) && this.selectedModel()) {
|
||||||
|
if (action === 'new' && (!this.selectedModel().RobotId || !this.discardChanges())) return;
|
||||||
|
return this.run(async () => { if (action === 'copy' && this.dirty) await this.persistDraft(); const created = await this.api('', { method: 'POST', body: JSON.stringify({ robotId: this.selectedModel().RobotId ?? undefined, ...(action === 'copy' ? { copyFromId: this.header.BomId } : {}) }) }); await this.loadModel(created.BomId); this.tab = 'bom'; this.app.notifySuccess('Đã tạo BOM nháp.'); });
|
||||||
|
}
|
||||||
|
if (action === 'publish' && this.editable()) {
|
||||||
|
const bomId = this.header.BomId;
|
||||||
|
if (!await this.confirmPublication() || this.busy || !this.editable() || this.header.BomId !== bomId) return;
|
||||||
|
return this.run(async () => {
|
||||||
|
if (this.dirty) await this.persistDraft();
|
||||||
|
await this.api(`/${bomId}/publish`, { method: 'POST', body: JSON.stringify({ lockVersion: this.header.LockVersion }) });
|
||||||
|
this.header.Status = 'released'; this.dirty = false;
|
||||||
|
this.app.notifySuccess('Đã phát hành BOM.'); await this.loadModel(bomId);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async change(event) {
|
||||||
|
const target = event.target; if (target.id === 'bomImportFile' && target.files[0]) { await this.importWorkbook(target.files[0]); return; } if (this.busy) return;
|
||||||
|
if (target.id === 'bomModel') { if (!this.discardChanges()) { target.value = this.modelId; return; } this.modelId = target.value; await this.run(() => this.loadModel()); }
|
||||||
|
else if (target.id === 'bomRevision') { if (!this.discardChanges()) { target.value = String(this.header.BomId); return; } await this.run(() => this.loadRevision(target.value)); }
|
||||||
|
else if (target.hasAttribute('data-bom-quantity') && this.editable()) { const line = this.lines[Number(target.dataset.bomQuantity)]; try { this.validateLine({ ...line, Quantity: target.value }); line.Quantity = Number(target.value); this.changed(); } catch (error) { target.value = line.Quantity; this.app.notifyWarning(error.message); } }
|
||||||
|
}
|
||||||
|
openMaterialForm(index = null) {
|
||||||
|
if (!this.editable()) return; if (this.lines.length >= 500 && index === null) { this.app.notifyWarning('BOM tối đa 500 dòng vật tư.'); return; }
|
||||||
|
const previous = index === null ? null : this.lines[index]; const state = { mode: previous ? 'manual' : 'asset', catalog: null, loading: false, error: '', selected: null, query: '' };
|
||||||
|
const dialog = document.createElement('dialog'); dialog.id = 'bomComponentDialog'; dialog.className = 'bom-dialog bom-entry-dialog'; dialog.setAttribute('aria-labelledby', 'bomMaterialTitle');
|
||||||
|
dialog.innerHTML = `<form id="bomMaterialForm"><header class="bom-dialog-header"><div><h2 id="bomMaterialTitle">${previous ? 'Sửa vật tư' : 'Thêm vật tư vào BOM'}</h2><p>Chọn tên/model từ tài sản hoặc nhập vật tư bên ngoài.</p></div><button type="button" data-bom-close aria-label="Đóng"><span class="material-symbols-outlined">close</span></button></header><div class="bom-entry-tabs"><button type="button" data-bom-mode="asset">Chọn tài sản có sẵn</button><button type="button" data-bom-mode="manual">Nhập vật tư bên ngoài</button></div>
|
||||||
|
<div class="bom-material-layout">
|
||||||
|
<section class="bom-entry-context"><div class="bom-asset-picker"><label class="bom-search"><span class="material-symbols-outlined">search</span><input id="bomAssetSearch" type="search" placeholder="Tìm tên, mã hoặc model tài sản…" aria-label="Tìm tài sản"></label><p class="bom-footnote">Lấy tên và model từ tài sản. Số lượng BOM tự nhập.</p><div id="bomAssetResults"></div></div>
|
||||||
|
<div class="bom-external-guide" hidden><span class="bom-external-icon material-symbols-outlined" aria-hidden="true">edit_note</span><h3>Vật tư bên ngoài</h3><p>Thêm trực tiếp thành phần chưa có trong danh sách tài sản.</p><ul><li><span class="material-symbols-outlined" aria-hidden="true">check_circle</span><span><strong>Nhập tên vật tư</strong><small>Bổ sung model hoặc quy cách nếu có.</small></span></li><li><span class="material-symbols-outlined" aria-hidden="true">format_list_numbered</span><span><strong>Tự điền số lượng</strong><small>Theo cấu hình của robot đang lập BOM.</small></span></li><li><span class="material-symbols-outlined" aria-hidden="true">link</span><span><strong>Ghi lại nguồn cung cấp</strong><small>Link mua hàng hoặc thông tin nhà sản xuất.</small></span></li></ul><p class="bom-external-note">Có thể chuyển lại danh sách tài sản; thông tin đang nhập vẫn được giữ.</p></div>
|
||||||
|
</section>
|
||||||
|
<section class="bom-material-fields"><label>Tên tài sản / Vật tư <span class="bom-danger">*</span><input name="name" required maxlength="255" value="${this.escape(previous?.Name || '')}" placeholder="VD: Động cơ servo, cảm biến…" autocomplete="off"></label><label>Model <span class="bom-optional">(tùy chọn)</span><input name="model" maxlength="255" value="${this.escape(previous?.Model || '')}" placeholder="Model / quy cách vật tư"></label><div class="bom-form-grid"><label>Số lượng<input name="quantity" type="number" min="0.0001" max="100000" step="0.0001" value="${Number(previous?.Quantity ?? 1)}"></label><label>Đơn vị <span class="bom-optional">(tùy chọn)</span><input name="unit" maxlength="50" value="${this.escape(previous?.Unit || '')}" placeholder="VD: cái, bộ, m"></label></div><label>Nguồn <span class="bom-optional">(tùy chọn)</span><textarea name="sourceInfo" maxlength="1000" rows="2" placeholder="Link mua hàng hoặc thông tin nhà sản xuất / nhà cung cấp…">${this.escape(previous?.SourceInfo || '')}</textarea></label><label>Ghi chú <span class="bom-optional">(tùy chọn)</span><textarea name="notes" maxlength="500" rows="2" placeholder="Thông tin thêm về vật tư…">${this.escape(previous?.Notes || '')}</textarea></label></section>
|
||||||
|
</div><footer class="bom-dialog-footer"><p class="bom-entry-save-hint">Thêm vật tư, sau đó bấm <strong>Lưu BOM</strong> để lưu danh sách.</p><div><button type="button" data-bom-close class="bom-btn">Hủy</button>${!previous ? '<button type="submit" name="action" value="continue" class="bom-btn">Thêm và tiếp tục</button>' : ''}<button type="submit" name="action" value="done" class="bom-btn bom-btn-primary">${previous ? 'Cập nhật' : 'Thêm vào BOM'}</button></div></footer></form>`;
|
||||||
|
const form = dialog.querySelector('form');
|
||||||
|
const renderCatalog = () => {
|
||||||
|
const host = dialog.querySelector('#bomAssetResults');
|
||||||
|
if (state.loading) { host.innerHTML = '<p class="bom-muted bom-footnote" role="status">Đang tải danh sách tài sản…</p>'; return; }
|
||||||
|
if (state.error) { host.innerHTML = `<p class="bom-alert">${this.escape(state.error)}. Có thể chuyển sang Nhập vật tư bên ngoài.</p>`; return; }
|
||||||
|
const query = state.query.trim().toLocaleLowerCase('vi'); const rows = (state.catalog || []).filter(item => !query || [item.Name, item.Code, item.Model].some(value => String(value || '').toLocaleLowerCase('vi').includes(query)));
|
||||||
|
host.innerHTML = rows.length ? `<div class="bom-asset-table-wrap"><table class="bom-asset-table"><thead><tr><th></th><th>Tên tài sản</th><th>Model</th></tr></thead><tbody>${rows.slice(0, 50).map(item => `<tr class="${state.selected?.Id === item.Id ? 'bom-picked-row' : ''}"><td><input type="radio" name="assetChoice" value="${Number(item.Id)}" ${state.selected?.Id === item.Id ? 'checked' : ''} aria-label="Chọn ${this.escape(item.Name)}"></td><td><strong>${this.escape(item.Name)}</strong><small>${this.escape(item.Code)}</small></td><td>${this.escape(item.Model || '—')}</td></tr>`).join('')}</tbody></table></div><p class="bom-footnote">${rows.length > 50 ? `Hiển thị 50/${rows.length} tài sản. Tìm kiếm để thu hẹp danh sách.` : `${rows.length} tài sản`}</p>` : '<div class="bom-empty"><strong>Không tìm thấy tài sản</strong><p>Thử tìm kiếm khác hoặc chọn Nhập vật tư bên ngoài.</p></div>';
|
||||||
|
};
|
||||||
|
const setMode = async mode => {
|
||||||
|
state.mode = mode;
|
||||||
|
dialog.querySelector('.bom-asset-picker').hidden = mode !== 'asset';
|
||||||
|
dialog.querySelector('.bom-external-guide').hidden = mode !== 'manual';
|
||||||
|
dialog.querySelectorAll('[data-bom-mode]').forEach(button => button.setAttribute('aria-pressed', String(button.dataset.bomMode === mode)));
|
||||||
|
if (mode === 'asset' && !state.catalog && !state.loading) { state.loading = true; state.error = ''; renderCatalog(); try { state.catalog = await this.api('/catalog'); } catch (error) { state.error = error.message; } finally { state.loading = false; renderCatalog(); } }
|
||||||
|
};
|
||||||
|
dialog.addEventListener('click', event => {
|
||||||
|
if (event.target.closest('[data-bom-close]')) { dialog.close(); return; }
|
||||||
|
const mode = event.target.closest('[data-bom-mode]'); if (mode) setMode(mode.dataset.bomMode);
|
||||||
|
const row = event.target.closest('.bom-asset-table tbody tr'); if (row && !event.target.closest('input')) row.querySelector('input').click();
|
||||||
|
});
|
||||||
|
dialog.querySelector('#bomAssetSearch').addEventListener('input', event => { state.query = event.target.value; renderCatalog(); });
|
||||||
|
dialog.addEventListener('change', event => {
|
||||||
|
if (event.target.name !== 'assetChoice') return;
|
||||||
|
state.selected = state.catalog.find(item => item.Id === Number(event.target.value));
|
||||||
|
if (state.selected) { form.elements.name.value = state.selected.Name; form.elements.model.value = state.selected.Model || ''; form.elements.unit.value = state.selected.Unit || ''; renderCatalog(); }
|
||||||
|
});
|
||||||
|
form.addEventListener('submit', event => {
|
||||||
|
event.preventDefault(); if (!this.editable() || this.busy) return;
|
||||||
|
const candidate = { ...previous, SourceType: 'manual', SourceId: null, Name: form.elements.name.value.trim(), Model: form.elements.model.value.trim(), Quantity: form.elements.quantity.value === '' ? 1 : Number(form.elements.quantity.value), Unit: form.elements.unit.value.trim(), SourceInfo: form.elements.sourceInfo.value.trim(), Notes: form.elements.notes.value.trim() };
|
||||||
|
try { this.validateLine(candidate); } catch (error) { this.app.notifyWarning(error.message); return; }
|
||||||
|
if (index === null) this.lines.push(candidate); else this.lines[index] = candidate; this.query = ''; this.changed();
|
||||||
|
if (event.submitter?.value === 'continue') { form.reset(); state.selected = null; renderCatalog(); form.elements.name.focus({ preventScroll: true }); } else dialog.close();
|
||||||
|
});
|
||||||
|
dialog.addEventListener('close', () => dialog.remove(), { once: true });
|
||||||
|
document.body.appendChild(dialog); setMode(state.mode); dialog.showModal();
|
||||||
|
(state.mode === 'manual' ? form.elements.name : dialog.querySelector('#bomAssetSearch')).focus({ preventScroll: true });
|
||||||
|
}
|
||||||
|
exportWorkbook() {
|
||||||
|
if (!window.XLSX || !this.header) { this.app.notifyFailure('Không tìm thấy thư viện Excel hoặc BOM.'); return; }
|
||||||
|
try {
|
||||||
|
const rows = this.lines.map(line => ({ 'Tên vật tư': line.Name, 'Model': line.Model || '', 'Số lượng': Number(line.Quantity ?? 1), 'ĐVT': line.Unit || '', 'Nguồn': line.SourceInfo || '', 'Ghi chú': line.Notes || '' }));
|
||||||
|
for (const [field, label] of [['Code', 'Mã vật tư'], ['GroupName', 'Cụm lắp ráp'], ['Position', 'Vị trí lắp']]) if (this.lines.some(line => line[field])) rows.forEach((row, index) => { row[label] = this.lines[index][field] || ''; });
|
||||||
|
const book = window.XLSX.utils.book_new(); const sheet = window.XLSX.utils.json_to_sheet(rows, { header: ['Tên vật tư', 'Model', 'Số lượng', 'ĐVT', 'Nguồn', 'Ghi chú'] });
|
||||||
|
sheet['!cols'] = [36, 24, 14, 12, 55, 40, 20, 24, 24].map(wch => ({ wch })); window.XLSX.utils.book_append_sheet(book, sheet, 'BOM');
|
||||||
|
window.XLSX.utils.book_append_sheet(book, window.XLSX.utils.json_to_sheet([{ 'Model robot': this.header.RobotModel, 'Thể loại': this.selectedModel()?.Type || '', 'Phiên bản': this.header.Revision, 'Trạng thái': this.dirty ? 'Thay đổi chưa lưu' : this.header.Status === 'released' ? 'Đã phát hành' : 'Bản nháp', 'Ngày xuất': this.app.formatDateTime(new Date()) }]), 'Thong tin');
|
||||||
|
window.XLSX.writeFile(book, `BOM-${this.header.RobotModel.replace(/[^\p{L}\p{N}._-]/gu, '_').slice(0, 80)}-v${this.header.Revision}.xlsx`);
|
||||||
|
} catch (error) { this.app.notifyFailure(`Không thể xuất BOM: ${error.message}`); }
|
||||||
|
}
|
||||||
|
async importWorkbook(file) {
|
||||||
|
if (!this.editable() || this.busy) return;
|
||||||
|
if (!window.XLSX) { this.app.notifyFailure('Không tìm thấy thư viện Excel.'); return; }
|
||||||
|
if (!/\.xlsx?$/i.test(file.name) || file.size > 10 * 1024 * 1024) { this.app.notifyWarning('Chọn file .xls hoặc .xlsx, tối đa 10 MB.'); return; }
|
||||||
|
await this.run(async () => {
|
||||||
|
const book = window.XLSX.read(await file.arrayBuffer(), { type: 'array', sheetRows: 502 }); const sheet = book.Sheets.BOM || book.Sheets[book.SheetNames[0]]; const rows = window.XLSX.utils.sheet_to_json(sheet, { defval: '' });
|
||||||
|
if (!rows.length || rows.length > 500) throw new Error('File cần có từ 1 đến 500 dòng vật tư. Dùng file Xuất Excel làm mẫu.');
|
||||||
|
const next = rows.map(row => ({ SourceType: 'manual', SourceId: null, Name: String(row['Tên vật tư'] || row['Tên tài sản'] || row['Tên linh kiện'] || '').trim(), Model: String(row.Model || '').trim(), Quantity: row['Số lượng'] !== undefined && row['Số lượng'] !== '' ? row['Số lượng'] : row['SL / robot'] ?? 1, Unit: String(row['ĐVT'] || '').trim(), SourceInfo: String(row['Nguồn'] || '').trim(), Notes: String(row['Ghi chú'] || '').trim(), Code: String(row['Mã vật tư'] || row['Mã linh kiện'] || '').trim(), GroupName: String(row['Cụm lắp ráp'] || '').trim(), Position: String(row['Vị trí lắp'] || '').trim() }));
|
||||||
|
this.validateLines(next); if (this.lines.length && !window.confirm(`Thay ${this.lines.length} dòng BOM hiện tại bằng ${next.length} dòng từ Excel? Bấm Lưu thay đổi sau khi kiểm tra danh sách.`)) return;
|
||||||
|
this.lines = next; this.dirty = true; this.query = ''; this.app.notifySuccess(`Đã đọc ${next.length} vật tư. Bấm Lưu thay đổi để lưu.`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
window.RobotBomController = RobotBomController;
|
||||||
|
})();
|
||||||
@@ -10,6 +10,7 @@
|
|||||||
<!-- Material Symbols -->
|
<!-- Material Symbols -->
|
||||||
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200&display=swap" rel="stylesheet"/>
|
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200&display=swap" rel="stylesheet"/>
|
||||||
<link rel="stylesheet" href="../css/main.css?v=20261019-4" />
|
<link rel="stylesheet" href="../css/main.css?v=20261019-4" />
|
||||||
|
<link rel="stylesheet" href="../css/robot-bom.css?v=20261102-5" />
|
||||||
<!-- Notiflix Notify -->
|
<!-- Notiflix Notify -->
|
||||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-3.2.7.min.css" />
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-3.2.7.min.css" />
|
||||||
<script src="https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-aio-3.2.7.min.js"></script>
|
<script src="https://cdn.jsdelivr.net/npm/notiflix@3.2.7/dist/notiflix-aio-3.2.7.min.js"></script>
|
||||||
@@ -353,6 +354,10 @@
|
|||||||
<span class="material-symbols-outlined" aria-hidden="true">category</span>
|
<span class="material-symbols-outlined" aria-hidden="true">category</span>
|
||||||
<span class="sidebar-text">Thể loại robot</span>
|
<span class="sidebar-text">Thể loại robot</span>
|
||||||
</a></li>
|
</a></li>
|
||||||
|
<li><a href="#robot-bom" data-nav="robot-bom" class="sidebar-link">
|
||||||
|
<span class="material-symbols-outlined" aria-hidden="true">receipt_long</span>
|
||||||
|
<span class="sidebar-text">BOM robot</span>
|
||||||
|
</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
<li><a href="#documents" data-nav="documents" class="sidebar-link">
|
<li><a href="#documents" data-nav="documents" class="sidebar-link">
|
||||||
@@ -431,6 +436,7 @@
|
|||||||
</main>
|
</main>
|
||||||
|
|
||||||
<script src="../js/document-formats.js?v=20261019-1"></script>
|
<script src="../js/document-formats.js?v=20261019-1"></script>
|
||||||
<script src="../js/app.js?v=20261019-4"></script>
|
<script src="../js/robot-bom.js?v=20261102-5"></script>
|
||||||
|
<script src="../js/app.js?v=20261102-2"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
Reference in New Issue
Block a user