/
Starolat
/
DeepDive
Обзор
Документация
Войти
/
Starolat
/
DeepDive
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
js/components/MaterialDeliveryImportModal.js
942 строки
28 KB
Starolat Sergei
feat: управление источниками реестров поставок МТР, UI импорта и .dddb v2.6.0
09 июл 2026, 18:34
09 июл 2026, 18:34
2b928c6
Код
Авторство
О чём код?
// @ts-check /** * @fileoverview MaterialDeliveryImportModal — модальное окно импорта реестра поставок МТР. * @module js/components/MaterialDeliveryImportModal * @version 1.0.0 * * Phase 4 UI: отдельная кнопка в шапке → модалка выбора Excel → импорт через * MaterialDeliveryService. Визуализация и расчёт дефицита не входят. * * @see docs/material-delivery-import-workflow-plan.md */ import { X, FilePlus, Upload, AlertCircle, Check, Trash2 } from "./ConstantinIcons.js"; import { materialDeliveryService } from "../services/MaterialDeliveryService.js"; import { dataService } from "../services/DataService.js"; import { ToastManager } from "./ToastManager.js"; /** * Создать SVG-элемент из строки ConstantinIcons * @param {string} svgString * @param {string} [className] * @returns {string} */ function icon(svgString, className = "") { const cls = className ? ` class="${className}"` : ""; return svgString.replace("<svg", `<svg${cls}`); } class MaterialDeliveryImportModal extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); /** @type {File|null} */ this._selectedFile = null; /** @type {boolean} */ this._isImporting = false; /** @type {boolean} */ this.isOpen = false; /** @type {HTMLElement|null} */ this._triggerElement = null; // Bind handlers this.open = this.open.bind(this); this.close = this.close.bind(this); this._handleKeyDown = this._handleKeyDown.bind(this); this._handleFileSelect = this._handleFileSelect.bind(this); this._handleImport = this._handleImport.bind(this); } static get observedAttributes() { return ["open"]; } connectedCallback() { this._render(); this._setupEventListeners(); this._syncTheme(); this._themeObserver = new MutationObserver(() => this._syncTheme()); this._themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"], }); this._themeChangedHandler = () => this._syncTheme(); document.addEventListener("theme-changed", this._themeChangedHandler); } disconnectedCallback() { document.removeEventListener("keydown", this._handleKeyDown); if (this._themeObserver) { this._themeObserver.disconnect(); } if (this._themeChangedHandler) { document.removeEventListener("theme-changed", this._themeChangedHandler); } } attributeChangedCallback(name, oldValue, newValue) { if (oldValue === newValue) return; if (name === "open") { this.isOpen = newValue !== null; this._updateVisibility(); } } // ==================== Public API ==================== /** * Открыть модалку * @public */ open() { this._triggerElement = /** @type {HTMLElement|null} */ ( document.activeElement ); this._resetState(); this._renderSourcesList(); this.setAttribute("open", ""); this.dispatchEvent( new CustomEvent("modal-open", { detail: { timestamp: Date.now() }, bubbles: true, composed: true, }), ); } /** * Закрыть модалку * @public */ close() { this.removeAttribute("open"); this.dispatchEvent( new CustomEvent("modal-close", { detail: { timestamp: Date.now() }, bubbles: true, composed: true, }), ); if (this._triggerElement) { this._triggerElement.focus(); this._triggerElement = null; } } // ==================== Private Methods ==================== _resetState() { this._selectedFile = null; this._isImporting = false; const fileInput = this.shadowRoot?.getElementById("file-input"); if (fileInput instanceof HTMLInputElement) { fileInput.value = ""; } this._updateFileName(""); this._updateResult(null); this._setImporting(false); } /** * @param {string} fileName */ _updateFileName(fileName) { const fileNameEl = this.shadowRoot?.getElementById("file-name"); const importBtn = this.shadowRoot?.getElementById("import-btn"); if (fileNameEl) { fileNameEl.textContent = fileName || "Файл не выбран"; fileNameEl.classList.toggle("has-file", !!fileName); } if (importBtn instanceof HTMLButtonElement) { importBtn.disabled = !fileName || this._isImporting; } } /** * @param {import('../services/MaterialDeliveryService.js').MaterialDeliveryImportResult|null} result */ _updateResult(result) { const resultEl = this.shadowRoot?.getElementById("result"); if (!resultEl) return; if (!result) { resultEl.style.display = "none"; resultEl.innerHTML = ""; return; } const unmatchedCount = result.unmatched?.length ?? 0; const previewHtml = this._renderPreviewTable(result); resultEl.style.display = "block"; resultEl.innerHTML = ` <div class="result-icon">${icon(Check, "icon-check")}</div> <div class="result-title">Импорт завершён</div> <div class="result-stats"> <div class="stat"><span class="stat-value">${result.totalRows}</span><span class="stat-label">всего строк</span></div> <div class="stat"><span class="stat-value">${result.importedCount}</span><span class="stat-label">сопоставлено</span></div> <div class="stat"><span class="stat-value">${result.skippedCount}</span><span class="stat-label">пропущено</span></div> <div class="stat"><span class="stat-value">${unmatchedCount}</span><span class="stat-label">не сопоставлено</span></div> </div> ${previewHtml} `; } /** * Отрисовать таблицу preview импортированных строк. * @private * @param {import('../services/MaterialDeliveryService.js').MaterialDeliveryImportResult} result * @returns {string} */ _renderPreviewTable(result) { const MAX_ROWS = 50; const rows = result.mappings?.slice(0, MAX_ROWS) ?? []; if (rows.length === 0) return ""; const tableRows = rows .map((m, index) => { const d = m.delivery; const status = m.matched ? `<span class="status-badge status-ok">✓ сопоставлено</span>` : `<span class="status-badge status-warn" title="${m.unmatchedReason || ""}">⚠ ${m.unmatchedReason || "не сопоставлено"}</span>`; return ` <tr> <td>${index + 1}</td> <td>${d.activityCode || "—"}</td> <td>${d.materialType || "—"}</td> <td class="cell-material">${d.materialName || "—"}</td> <td class="cell-number">${d.quantity ?? "—"}</td> <td>${d.unit || "—"}</td> <td>${d.deliveryDate || "—"}</td> <td>${status}</td> </tr> `; }) .join(""); const moreCount = (result.mappings?.length ?? 0) - MAX_ROWS; const moreHtml = moreCount > 0 ? `<div class="preview-more">... и ещё ${moreCount} строк</div>` : ""; return ` <div class="preview-title">Результат сопоставления</div> <div class="preview-table-wrapper"> <table class="preview-table"> <thead> <tr> <th>№</th> <th>ID Раб.</th> <th>Вид МТР</th> <th>Материал</th> <th>Кол-во</th> <th>ЕИ</th> <th>Дата</th> <th>Статус</th> </tr> </thead> <tbody>${tableRows}</tbody> </table> </div> ${moreHtml} `; } /** * @param {boolean} importing */ _setImporting(importing) { this._isImporting = importing; const importBtn = this.shadowRoot?.getElementById("import-btn"); const selectBtn = this.shadowRoot?.getElementById("select-btn"); const fileInput = this.shadowRoot?.getElementById("file-input"); if (importBtn instanceof HTMLButtonElement) { importBtn.disabled = importing || !this._selectedFile; importBtn.innerHTML = importing ? `<span class="spinner"></span> Импорт...` : `${icon(Upload, "btn-icon")} Импортировать`; } if (selectBtn instanceof HTMLButtonElement) { selectBtn.disabled = importing; } if (fileInput instanceof HTMLInputElement) { fileInput.disabled = importing; } } /** * @param {Event} e */ _handleFileSelect(e) { const input = /** @type {HTMLInputElement} */ (e.target); const file = input.files?.[0]; if (!file) return; if (!file.name.match(/\.(xlsx|xls)$/i)) { ToastManager.getInstance().warning( "Выберите файл Excel (.xlsx или .xls)", 4000, ); input.value = ""; return; } this._selectedFile = file; this._updateFileName(file.name); this._updateResult(null); } async _handleImport() { if (!this._selectedFile || this._isImporting) return; const databaseId = dataService.getActiveDatabaseId(); if (!databaseId) { ToastManager.getInstance().error( "Нет активной базы данных. Сначала загрузите проект.", 5000, ); return; } this._setImporting(true); try { const result = await materialDeliveryService.importFromExcel( this._selectedFile, databaseId, ); this._updateResult(result); this._renderSourcesList(); const unmatchedCount = result.unmatched?.length ?? 0; if (result.importedCount > 0) { ToastManager.getInstance().success( `Импортировано ${result.importedCount} поставок из «${this._selectedFile.name}»`, 4000, ); } else if (unmatchedCount > 0) { ToastManager.getInstance().warning( `Ни одна строка не сопоставлена. Проверьте ID Раб. и материалы.`, 5000, ); } this.dispatchEvent( new CustomEvent("material-delivery-import-complete", { detail: { result, fileName: this._selectedFile.name, databaseId }, bubbles: true, composed: true, }), ); } catch (error) { console.error("[MaterialDeliveryImportModal] Import failed:", error); ToastManager.getInstance().error( `Ошибка импорта: ${error instanceof Error ? error.message : String(error)}`, 6000, ); } finally { this._setImporting(false); } } _handleKeyDown(e) { if (e.key === "Escape" && this.isOpen) { this.close(); } } /** * Отрисовать список загруженных источников реестров. * @private */ _renderSourcesList() { const container = this.shadowRoot?.getElementById("sources-list"); if (!container) return; const databaseId = dataService.getActiveDatabaseId(); if (!databaseId) { container.innerHTML = ""; container.style.display = "none"; return; } const sources = materialDeliveryService.getSources(databaseId); if (!sources || sources.length === 0) { container.innerHTML = ""; container.style.display = "none"; return; } const itemsHtml = sources .map((source) => { const date = source.uploadedAt ? new Date(source.uploadedAt).toLocaleString("ru-RU") : "—"; return ` <div class="source-item" data-source-id="${source.sourceId}"> <div class="source-info"> <div class="source-name" title="${source.fileName}">${source.fileName}</div> <div class="source-meta"> ${source.rowCount} строк · ${source.importedCount} сопоставлено · ${source.unmatchedCount} не сопоставлено </div> <div class="source-date">${date}</div> </div> <button class="source-delete-btn" type="button" title="Удалить источник" aria-label="Удалить источник"> ${icon(Trash2, "source-delete-icon")} </button> </div> `; }) .join(""); container.innerHTML = ` <div class="sources-title">Загруженные реестры</div> <div class="sources-items">${itemsHtml}</div> `; container.style.display = "block"; container.querySelectorAll(".source-delete-btn").forEach((btn) => { btn.addEventListener("click", (e) => { const item = /** @type {HTMLElement} */ (e.currentTarget).closest( ".source-item", ); const sourceId = item?.getAttribute("data-source-id"); if (sourceId) { this._handleDeleteSource(sourceId); } }); }); } /** * Удалить источник реестра. * @private * @param {string} sourceId */ _handleDeleteSource(sourceId) { const databaseId = dataService.getActiveDatabaseId(); if (!databaseId) return; const source = materialDeliveryService.getSource(databaseId, sourceId); if (!source) return; const confirmed = confirm( `Удалить реестр «${source.fileName}» и все связанные поставки?`, ); if (!confirmed) return; const removed = materialDeliveryService.removeSource(databaseId, sourceId); if (removed) { ToastManager.getInstance().success( `Реестр «${source.fileName}» удалён`, 3000, ); this._renderSourcesList(); this.dispatchEvent( new CustomEvent("material-delivery-source-removed", { detail: { databaseId, sourceId }, bubbles: true, composed: true, }), ); } } _setupEventListeners() { const closeBtn = this.shadowRoot?.getElementById("close-btn"); const selectBtn = this.shadowRoot?.getElementById("select-btn"); const fileInput = this.shadowRoot?.getElementById("file-input"); const importBtn = this.shadowRoot?.getElementById("import-btn"); const overlay = this.shadowRoot?.getElementById("overlay"); closeBtn?.addEventListener("click", this.close); selectBtn?.addEventListener("click", () => fileInput?.click()); fileInput?.addEventListener("change", this._handleFileSelect); importBtn?.addEventListener("click", this._handleImport); overlay?.addEventListener("click", (e) => { if (e.target === overlay) this.close(); }); document.addEventListener("keydown", this._handleKeyDown); } _updateVisibility() { const overlay = this.shadowRoot?.getElementById("overlay"); if (overlay) { overlay.style.display = this.isOpen ? "flex" : "none"; } } _syncTheme() { const theme = document.documentElement.getAttribute("data-theme") || "consta-light"; if (this.shadowRoot) { this.shadowRoot.host.setAttribute("data-theme", theme); } } _render() { this.shadowRoot.innerHTML = ` <style> :host { display: contents; } #overlay { position: fixed; z-index: 3000; left: 0; top: 0; width: 100%; height: 100%; background: var(--modal-overlay-bg, rgba(0, 32, 51, 0.6)); display: none; align-items: center; justify-content: center; backdrop-filter: blur(2px); } .modal-content { background: var(--surface-bg); border-radius: var(--border-radius, 4px); box-shadow: var(--shadow-lg); display: flex; flex-direction: column; min-width: 360px; max-width: 90vw; max-height: 90vh; border: 1px solid var(--border-color); font-family: var(--font-family, 'Inter', sans-serif); color: var(--text-primary); } .modal-header { display: flex; justify-content: space-between; align-items: center; padding: var(--space-sm, 8px) var(--space-md, 12px); border-bottom: 1px solid var(--border-light); } .modal-header h3 { margin: 0; font-size: var(--font-size-md, 14px); font-weight: var(--font-weight-semibold, 600); color: var(--text-primary); } .close-btn { background: transparent; border: none; color: var(--text-secondary); cursor: pointer; padding: var(--space-xs, 4px); border-radius: var(--border-radius, 4px); display: flex; align-items: center; justify-content: center; } .close-btn:hover { background: var(--surface-hover); color: var(--text-primary); } .close-btn svg { width: 18px; height: 18px; } .modal-body { padding: var(--space-md, 12px); overflow-y: auto; display: flex; flex-direction: column; gap: var(--space-md, 12px); } .modal-footer { padding: var(--space-sm, 8px) var(--space-md, 12px); border-top: 1px solid var(--border-light); display: flex; justify-content: flex-end; gap: var(--space-xs, 4px); } .description { font-size: var(--font-size-xs, 10px); color: var(--text-secondary); line-height: 1.4; margin: 0; } .file-section { display: flex; flex-direction: column; gap: var(--space-xs, 4px); } .file-row { display: flex; align-items: center; gap: var(--space-xs, 4px); } #file-input { display: none; } .file-name { flex: 1; font-size: var(--font-size-xs, 10px); color: var(--text-secondary); padding: var(--space-xs, 4px) var(--space-sm, 8px); border: 1px solid var(--border-color); border-radius: var(--border-radius, 4px); min-height: 24px; display: flex; align-items: center; background: var(--surface-bg); } .file-name.has-file { color: var(--text-primary); } button { height: 24px; font-size: var(--font-size-xs, 10px); padding: 0 var(--space-sm, 8px); border-radius: var(--border-radius, 4px); border: 1px solid var(--border-color); background: var(--surface-bg); color: var(--text-primary); cursor: pointer; display: inline-flex; align-items: center; gap: var(--space-xs, 4px); transition: all var(--transition, 0.15s); } button:disabled { opacity: 0.5; cursor: not-allowed; } button:hover:not(:disabled) { background: var(--surface-hover); } button.primary { background: var(--color-control-bg-primary, #0071b2); border-color: var(--color-control-bg-primary, #0071b2); color: var(--color-control-typo-primary, #fff); } button.primary:hover:not(:disabled) { background: var(--color-control-bg-primary-hover, #005f94); } .btn-icon { width: 14px; height: 14px; } .spinner { width: 14px; height: 14px; border: 2px solid rgba(255, 255, 255, 0.3); border-top-color: currentColor; border-radius: 50%; animation: spin 0.8s linear infinite; display: inline-block; } @keyframes spin { to { transform: rotate(360deg); } } #result { display: none; padding: var(--space-sm, 8px); border: 1px solid var(--border-color); border-radius: var(--border-radius, 4px); background: var(--surface-bg); text-align: center; } .result-icon { color: var(--color-typo-success, #22c55e); margin-bottom: var(--space-xs, 4px); } .result-icon svg { width: 24px; height: 24px; } .result-title { font-size: var(--font-size-sm, 12px); font-weight: var(--font-weight-semibold, 600); color: var(--text-primary); margin-bottom: var(--space-sm, 8px); } .result-stats { display: grid; grid-template-columns: repeat(2, 1fr); gap: var(--space-xs, 4px); } .stat { display: flex; flex-direction: column; align-items: center; padding: var(--space-xs, 4px); background: var(--surface-bg); border-radius: var(--border-radius, 4px); } .stat-value { font-size: var(--font-size-md, 14px); font-weight: var(--font-weight-semibold, 600); color: var(--text-primary); } .stat-label { font-size: var(--font-size-xs, 10px); color: var(--text-secondary); } .preview-title { font-size: var(--font-size-sm, 12px); font-weight: var(--font-weight-semibold, 600); color: var(--text-primary); margin-top: var(--space-md, 12px); margin-bottom: var(--space-xs, 4px); text-align: left; } .preview-table-wrapper { max-height: 240px; overflow-y: auto; border: 1px solid var(--border-color); border-radius: var(--border-radius, 4px); } .preview-table { width: 100%; border-collapse: collapse; font-size: var(--font-size-xs, 10px); } .preview-table th, .preview-table td { padding: 4px 6px; text-align: left; border-bottom: 1px solid var(--border-light); white-space: nowrap; } .preview-table th { background: var(--surface-bg); color: var(--text-secondary); font-weight: var(--font-weight-medium, 500); position: sticky; top: 0; z-index: 1; } .preview-table tbody tr:last-child td { border-bottom: none; } .preview-table td.cell-material { max-width: 160px; overflow: hidden; text-overflow: ellipsis; } .preview-table td.cell-number { text-align: right; } .preview-more { font-size: var(--font-size-xs, 10px); color: var(--text-secondary); text-align: center; padding: var(--space-xs, 4px); } .status-badge { display: inline-flex; align-items: center; gap: 2px; font-size: var(--font-size-xs, 10px); padding: 1px 4px; border-radius: var(--border-radius, 4px); } .status-ok { background: var(--color-bg-success, rgba(34, 197, 94, 0.1)); color: var(--color-typo-success, #22c55e); } .status-warn { background: var(--color-bg-warning, rgba(245, 159, 11, 0.1)); color: var(--color-typo-warning, #f59e0b); } .hint { display: flex; align-items: flex-start; gap: var(--space-xs, 4px); font-size: var(--font-size-xs, 10px); color: var(--text-secondary); } .hint svg { width: 14px; height: 14px; flex-shrink: 0; margin-top: 1px; } #sources-list { display: none; border-top: 1px solid var(--border-light); padding-top: var(--space-sm, 8px); } .sources-title { font-size: var(--font-size-sm, 12px); font-weight: var(--font-weight-semibold, 600); color: var(--text-primary); margin-bottom: var(--space-xs, 4px); } .sources-items { display: flex; flex-direction: column; gap: var(--space-xs, 4px); max-height: 200px; overflow-y: auto; } .source-item { display: flex; align-items: center; justify-content: space-between; gap: var(--space-xs, 4px); padding: var(--space-xs, 4px) var(--space-sm, 8px); border: 1px solid var(--border-color); border-radius: var(--border-radius, 4px); background: var(--surface-bg); } .source-info { display: flex; flex-direction: column; gap: 2px; min-width: 0; flex: 1; } .source-name { font-size: var(--font-size-xs, 10px); font-weight: var(--font-weight-medium, 500); color: var(--text-primary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .source-meta { font-size: var(--font-size-xs, 10px); color: var(--text-secondary); } .source-date { font-size: var(--font-size-xs, 10px); color: var(--text-secondary); } .source-delete-btn { background: transparent; border: none; color: var(--text-secondary); cursor: pointer; padding: var(--space-xs, 4px); border-radius: var(--border-radius, 4px); display: flex; align-items: center; justify-content: center; flex-shrink: 0; } .source-delete-btn:hover { background: var(--color-bg-alert, rgba(235, 87, 87, 0.1)); color: var(--color-typo-alert, #eb5757); } .source-delete-icon svg { width: 14px; height: 14px; } </style> <div id="overlay" role="dialog" aria-modal="true" aria-labelledby="modal-title"> <div class="modal-content"> <div class="modal-header"> <h3 id="modal-title">Импорт реестра поставок МТР</h3> <button id="close-btn" class="close-btn" aria-label="Закрыть"> ${icon(X)} </button> </div> <div class="modal-body"> <p class="description"> Загрузите Excel-файл реестра поставок материалов. Строки будут сопоставлены с работами графика по столбцу «ID Раб.» и материалам по назначениям ресурсов. </p> <div class="file-section"> <div class="file-row"> <span id="file-name" class="file-name">Файл не выбран</span> <button id="select-btn" type="button"> ${icon(FilePlus, "btn-icon")} Выбрать </button> </div> <input id="file-input" type="file" accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"> </div> <div class="hint"> ${icon(AlertCircle)} <span>Ожиется лист «РЕЕСТР» со строкой заголовков на 3-й строке. Поддерживаются форматы .xlsx и .xls.</span> </div> <div id="result"></div> <div id="sources-list"></div> </div> <div class="modal-footer"> <button id="import-btn" class="primary" type="button" disabled> ${icon(Upload, "btn-icon")} Импортировать </button> </div> </div> </div> `; } } customElements.define("material-delivery-import-modal", MaterialDeliveryImportModal); export default MaterialDeliveryImportModal;