/* 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 ``; } sourceHtml(value) { if (!value) return '—'; try { const url = new URL(value); if (['https:', 'http:'].includes(url.protocol)) return `${this.escape(value)}`; } catch {} return `${this.escape(value)}`; } 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 `
view_list${this.lines.length ? 'Không tìm thấy vật tư phù hợp' : 'Chưa có thành phần trong BOM'}

${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.'}

`; const edit = this.editable() && !this.busy; return `
${this.canManage() ? '' : ''}${rows.map(({ line, index }) => `${this.canManage() ? `` : ''}`).join('')}
STTTên tài sản / Vật tưModelSố lượngNguồnGhi chúThao tác
${index + 1}${this.escape(line.Name)}${line.Code ? `${this.escape(line.Code)}` : ''}${this.escape(line.Model || '—')}
${edit ? `` : number(line.Quantity ?? 1)}${line.Unit ? `${this.escape(line.Unit)}` : ''}
${this.sourceHtml(line.SourceInfo)}${this.escape(line.Notes || '—')}${edit ? `` : '—'}
`; } historyHtml() { return `
${this.revisions.map(revision => ``).join('')}
Phiên bảnTrạng tháiSố dòngCập nhậtPhát hành
v${Number(revision.Revision)}${revision.Status === 'released' ? 'Đã phát hành' : 'Bản nháp'}${number(revision.LineCount)}${this.escape(this.app.formatDateTime(revision.UpdatedDate))}${revision.ReleasedDate ? this.escape(this.app.formatDateTime(revision.ReleasedDate)) : '—'}
`; } render() { if (!this.active()) return; const model = this.selectedModel(); const disabled = this.busy ? 'disabled' : ''; const edit = this.editable(); this.root.innerHTML = `

THÀNH PHẦN ROBOT

BOM robot

Danh sách tài sản và vật tư cấu tạo của robot.

${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) : ''}
${this.error ? `` : ''}
${this.escape(model?.Name || 'Thêm robot trong Danh sách robot để bắt đầu.')}
${this.header ? `${this.header.Status === 'released' ? 'Đã phát hành' : this.dirty ? 'Chưa lưu thay đổi' : 'Bản nháp'}` : ''}${this.canManage() ? `
${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') : ''}
` : ''}
${!this.header ? `
inventory_2${this.busy ? 'Đang tải BOM…' : this.models.length ? 'Model robot này chưa có BOM' : 'Chưa có model robot'}

${this.models.length ? 'Tạo BOM và thêm các vật tư cấu thành robot.' : 'Đến Danh sách robot để thêm robot.'}

${this.canManage() && model ? this.button('new', 'Tạo BOM đầu tiên', 'add', true) : ''}
` : `

${this.tab === 'history' ? 'Lịch sử phiên bản' : 'Danh sách thành phần'} ${this.tab === 'history' ? this.revisions.length + ' phiên bản' : this.lines.length + ' vật tư'}

${edit && this.tab === 'bom' ? this.button('add', 'Thêm vật tư', 'add', true) : ''}
${this.tab === 'history' ? this.historyHtml() : `
${this.tableHtml()}
`}
`}
`; 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 = `

CHỐT PHIÊN BẢN

Phát hành BOM v${Number(this.header.Revision)}?

Phiên bản này sẽ được khóa chỉnh sửa sau khi phát hành.

Model robot
${this.escape(this.header.RobotModel)}
Phiên bản
v${Number(this.header.Revision)}
Thành phần
${this.lines.length} dòng vật tư

Khi cần thay đổi, dùng Sao chép BOM để tạo phiên bản nháp mới.

${this.dirty ? '

Các thay đổi chưa lưu sẽ được lưu trước khi phát hành.

' : ''}
`; 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 = `

XÓA PHIÊN BẢN

Xóa BOM v${Number(this.header.Revision)}?

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.

Model robot
${this.escape(this.header.RobotModel)}
Phiên bản
v${Number(this.header.Revision)}
Thành phần đã lưu
${number(revision?.LineCount ?? this.lines.length)} dòng vật tư

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.

${this.dirty ? '

Các thay đổi chưa lưu của phiên bản này cũng sẽ bị bỏ.

' : ''}
`; 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 = `

${previous ? 'Sửa vật tư' : 'Thêm vật tư vào BOM'}

Chọn tên/model từ tài sản hoặc nhập vật tư bên ngoài.

Lấy tên và model từ tài sản. Số lượng BOM tự nhập.

`; const form = dialog.querySelector('form'); const renderCatalog = () => { const host = dialog.querySelector('#bomAssetResults'); if (state.loading) { host.innerHTML = '

Đang tải danh sách tài sản…

'; return; } if (state.error) { host.innerHTML = `

${this.escape(state.error)}. Có thể chuyển sang Nhập vật tư bên ngoài.

`; 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 ? `
${rows.slice(0, 50).map(item => ``).join('')}
Tên tài sảnModel
${this.escape(item.Name)}${this.escape(item.Code)}${this.escape(item.Model || '—')}

${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`}

` : '
Không tìm thấy tài sản

Thử tìm kiếm khác hoặc chọn Nhập vật tư bên ngoài.

'; }; 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; })();