289 lines
38 KiB
JavaScript
289 lines
38 KiB
JavaScript
/* 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;
|
|
})();
|