// ==UserScript== // @name Base.com — edytor eksportów i JSON // @namespace base-export-template // @author supakuit // @version 0.0.30 // @description Szablony wydruków zamówień i eksportów magazynu: JSON, cache i narzędzia sekcji. // @include /^https:\/\/panel-[a-z]\.baselinker\.com\/(?:printout_manager|inventory_export\.php)\?edit_id=(?:-1|[0-9]+)(?:[&#].*)?$/ // @run-at document-idle // @grant none // @noframes // ==/UserScript== // Plik generowany automatycznie. Edytuj src/ i uruchom npm run build. (() => { // src/catalog.js var SECTION_ROWS = [ ["root", "[ROOT]", null], ["order", "[ZAMOWIENIA]", "root"], ["product", "[ZAMOWIENIE_POZYCJE]", "order"], ["package", "[ZAMOWIENIE_PACZKI]", "order"], ["order_document", "[DOKUMENTY_MAGAZYNOWE]", "order"], ["order_document_item", "[POZYCJE_DOKUMENTU]", "order_document"], ["invoice", "[FAKTURA]", "order"], ["invoice_items", "[FAKTURA_POZYCJE]", "invoice"], ["invoice_vat", "[FAKTURA_STAWKI_VAT]", "invoice"], ["invoice_correction", "[FAKTURA_KORYGUJACA]", "order"], ["invoice_correction_items_before", "[FAKTURA_KORYGUJACA_POZYCJE_PRZED]", "invoice_correction"], ["invoice_correction_items_after", "[FAKTURA_KORYGUJACA_POZYCJE_PO]", "invoice_correction"], ["invoice_correction_tax", "[FAKTURA_KORYGUJACA_STAWKI_VAT]", "invoice_correction"], ["receipt", "[PARAGON]", "order"], ["receipt_items", "[PARAGON_POZYCJE]", "receipt"], ["message", "[HISTORIA_WIADOMOSCI]", "order"], ["order_history", "[HISTORIA_STATUSY]", "order"], ["payment", "[HISTORIA_PLATNOSCI]", "order"], ["pickpack", "[HISTORIA_PAKOWANIA]", "order"], ["return", "[ZWROT]", "order"], ["return_items", "[ZWROT_POZYCJE]", "return"], ["return_history", "[ZWROT_HISTORIA_STATUSY]", "return"], ["return_payment", "[ZWROT_HISTORIA_PLATNOSCI]", "return"], ["return_pickpack", "[ZWROT_HISTORIA_PAKOWANIA]", "return"], ["stats", "[STATYSTYKI]", "root"], ["list_products", "[SPIS_PRODUKTOW]", "root"], ["list_products_stats", "[SPIS_PRODUKTOW_PODSUMOWANIE]", "root"] ]; var FIELD_LABELS = { "name": "Nazwa", "type": "Rodzaj", "force_download": "Wyświetlanie", "format_pdf_height": "PDF - Wysokość", "format_pdf_width": "PDF - Szerokość", "format_pdf_margin_top": "PDF - Margines górny", "format_pdf_margin_bottom": "PDF - Margines dolny", "format_pdf_margin_left": "PDF - Margines (w poziomie)", "format_pdf_page_numbers": "PDF - Numeracja stron", "format_pdf_insert_label": "PDF - Wstaw etykietę", "format_pdf_insert_label_top": "PDF (Etykieta) - Pozycja etykiety od góry (mm)", "format_pdf_insert_label_left": "PDF (Etykieta) - Pozycja etykiety od lewej (mm)", "format_pdf_insert_label_height": "PDF (Etykieta) - Wysokość etykiety (mm)", "format_pdf_insert_label_width": "PDF (Etykieta) - Szerokość etykiety (mm)", "format_pdf_insert_label_orientation": "PDF (Etykieta) - Orientacja etykiety", "format_pdf_insert_label_rotate_after": "PDF (Etykieta) - Obróć stronę o 90 stopni", "template_lang": "Język szablonu", "document_type_filter": "Filtr typu dokumentu", "returns_mode": "Wykonaj dla", "description": "Opis", "sort_fields[product]": "Sortowanie sekcji - [ZAMOWIENIE_POZYCJE]", "sort_fields[return_items]": "Sortowanie sekcji - [ZWROT_POZYCJE]", "sort_fields[list_products]": "Sortowanie sekcji - [SPIS_PRODUKTOW]", "group_fields[list_products]": "Grupowanie produktów - [SPIS_PRODUKTOW]" }; var FIELD_SECTIONS = { document_type_filter: "order_document", returns_mode: "return", "sort_fields[product]": "product", "sort_fields[return_items]": "return_items", "sort_fields[list_products]": "list_products", "group_fields[list_products]": "list_products" }; var fieldSection = (field, profile = PRINTOUT_PROFILE) => field.startsWith("code_") ? field.slice(5) : profile.fieldSections[field]; var FIELD_FORMATS = Object.fromEntries(Object.keys(FIELD_LABELS).filter((key) => key.startsWith("format_pdf_")).map((key) => [key, "PDF"])); var labelDetail = (key) => key.startsWith("format_pdf_insert_label_"); var formatFieldEnabled = (key, fields) => !FIELD_FORMATS[key] || fields.type === FIELD_FORMATS[key] && (!labelDetail(key) || !!fields.format_pdf_insert_label && fields.format_pdf_insert_label !== "0"); var COLLECTIONS = { modifiers: { table: "modificators_box", row: ".modificator_row", prefix: "modificators", props: ["tag", "type", "from", "to"], add: "addNewModificator", label: "Modyfikatory (cała lista)" }, settingsTags: { table: "tags_settings_box", row: ".settings_tag_row", prefix: "tags_settings", props: ["name", "value", "desc"], add: "addNewSettingsTag", label: "Tagi ustawień (cała lista)" } }; function createProfile(id, label, rows, labels, fieldSections = {}, collections = COLLECTIONS, extraCallers = {}) { return { id, label, rows, labels, fieldSections, collections, sections: new Map(rows.map(([key, tag, parent]) => [key, { tag, parent }])), callers: Object.fromEntries(rows.map(([key, , parent]) => [key, extraCallers[key] || (parent === null ? [] : [parent])])), fields: [...Object.keys(labels), ...rows.map(([key]) => `code_${key}`)] }; } var PRINTOUT_PROFILE = createProfile("printout_manager", "Wydruki zamówień", SECTION_ROWS, FIELD_LABELS, FIELD_SECTIONS); var INVENTORY_PROFILE = createProfile("inventory_export", "Eksport magazynu", [ ["root", "[ROOT]", null], ["product", "[PRODUKT]", "root"], ["parametr", "[PARAMETR]", "product"], ["link", "[POWIAZANIE]", "product"], ["publication", "[KANAŁ]", "product"], ["relationship", "[RELACJA]", "product"], ["variant", "[WARIANT]", "product"], ["bundle", "[ZESTAW]", "root"], ["manufactory", "[PRODUCENT]", "root"], ["supplier", "[DOSTAWCA]", "root"], ["category", "[KATEGORIA]", "root"], ["stats", "[STATYSTYKI]", "root"] ], { ...Object.fromEntries([ "name", "type", "force_download", "format_pdf_height", "format_pdf_width", "format_pdf_margin_top", "format_pdf_margin_bottom", "format_pdf_margin_left", "format_pdf_page_numbers", "description" ].map((key) => [key, FIELD_LABELS[key]])), change_tags_in_description: "Podmieniaj tagi w opisie produktu" }, {}, { modifiers: COLLECTIONS.modifiers }, { product: ["root", "bundle"] }); var PROFILES = new Map([PRINTOUT_PROFILE, INVENTORY_PROFILE].map((profile) => [profile.id, profile])); function profileForPatch(patch) { const id = Object.prototype.hasOwnProperty.call(patch, "generator") ? patch.generator : PRINTOUT_PROFILE.id; const profile = PROFILES.get(id); if (!profile) { throw new Error(`Nieznany generator: ${String(id)}`); } return profile; } function profileForForm(form) { const action = form.getAttribute("data-action") || ""; return /(?:[?&])form_id=InventoryExport(?:&|$)/.test(action) || /\/inventory_export\.php(?:[?#]|$)/.test(form.getAttribute("action") || "") ? INVENTORY_PROFILE : PRINTOUT_PROFILE; } // src/utils.js var has = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key); function same(a, b) { if (a === b) { return true; } if (!a || !b || typeof a !== "object" || typeof b !== "object" || Array.isArray(a) !== Array.isArray(b)) { return false; } const keys = Object.keys(a); return keys.length === Object.keys(b).length && keys.every((key) => has(b, key) && same(a[key], b[key])); } var emptyPatch = () => ({ format: "base-export-template", version: 1 }); var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value); var fail = (message) => { throw new Error(message); }; var MAX_BYTES = 5 * 1024 * 1024; // src/text-operations.js function verifyQuotes(text, format = "TXT") { let opening = -1; let count = 0; for (let index = 0; index < text.length; index++) { if (format !== "CSV" && text[index] === "\\") { index++; continue; } if (text[index] !== '"') { continue; } count++; if (format === "CSV" && opening !== -1 && text[index + 1] === '"') { count++; index++; continue; } opening = opening === -1 ? index : -1; } if (opening === -1) { return { balanced: true, count }; } const lines = text.slice(0, opening).split(/\r\n|\r|\n/); return { balanced: false, count, index: opening, line: lines.length, column: Array.from(lines[lines.length - 1]).length + 1 }; } function replaceSeparators(text, direction) { const signs = { commaToSemicolon: [",", ";"], semicolonToComma: [";", ","] }; if (!has(signs, direction)) { fail("Wybierz kierunek zamiany znaków."); } const [from, to] = signs[direction]; const parts = text.split(from); return { text: parts.join(to), count: parts.length - 1 }; } function applySectionOperation(text, operation) { if (operation === "commaToSemicolon" || operation === "semicolonToComma") { return replaceSeparators(text, operation); } const removals = { removeLeftBracket: "[", removeRightBracket: "]", removeBrackets: "[]" }; if (!has(removals, operation)) { fail("Nieznana operacja sekcji."); } let result = text; let count = 0; for (const sign of removals[operation]) { const parts = result.split(sign); count += parts.length - 1; result = parts.join(""); } return { text: result, count }; } // src/validation.js function parseJSON(text, limit = MAX_BYTES) { if (typeof text !== "string" || text.length > limit) { fail(`Plik JSON jest za duży (limit ${Math.ceil(limit / 1024 / 1024)} MB).`); } text = text.replace(/^\uFEFF/, ""); const result = JSON.parse(text); let pos = 0; const space = () => { while (/\s/.test(text[pos] || "") && pos < text.length) { pos++; } }; function string() { const start2 = pos++; while (pos < text.length) { if (text[pos] === "\\") { pos += 2; } else if (text[pos++] === '"') { break; } } return JSON.parse(text.slice(start2, pos)); } function value(depth = 0) { if (depth > 30) { fail("JSON ma zbyt wiele poziomów zagnieżdżenia."); } space(); if (text[pos] === '"') { string(); return; } if (text[pos] === "{") { pos++; space(); const keys = /* @__PURE__ */ new Set(); if (text[pos] === "}") { pos++; return; } while (pos < text.length) { space(); const key = string(); if (keys.has(key)) { fail(`Powtórzony klucz JSON: ${key}`); } keys.add(key); space(); pos++; value(depth + 1); space(); if (text[pos++] === "}") { return; } } } else if (text[pos] === "[") { pos++; space(); if (text[pos] === "]") { pos++; return; } while (pos < text.length) { value(depth + 1); space(); if (text[pos++] === "]") { return; } } } else { while (pos < text.length && !/[\s,}\]]/.test(text[pos])) { pos++; } } } value(); return result; } function validatePatch(patch, expectedProfile) { if (!object(patch)) { fail("JSON musi zawierać obiekt konfiguracji."); } const profile = profileForPatch(patch); if (expectedProfile && expectedProfile.id !== profile.id) { fail(`Szablon jest przeznaczony dla generatora „${profile.label}”, a otwarty jest „${expectedProfile.label}”.`); } const top = /* @__PURE__ */ new Set(["format", "version", "generator", "fields", "sections", "modifiers", "settingsTags"]); for (const key of Object.keys(patch)) { if (!top.has(key)) { fail(`Nieznany klucz: ${key}`); } } if (patch.format !== "base-export-template" || patch.version !== 1) { fail("Nieobsługiwany format lub wersja JSON (wymagana wersja 1)."); } let operations = 0; for (const group of ["fields", "sections"]) { if (!has(patch, group)) { continue; } if (!object(patch[group])) { fail(`${group}: wymagana mapa pól.`); } for (const [key, value] of Object.entries(patch[group])) { if (group === "fields") { if (!profile.fields.includes(key) || typeof value !== "string") { fail(`Niedozwolone pole lub typ: fields.${key}`); } } else if (key === "root" || !profile.sections.has(key) || typeof value !== "boolean") { fail(`Niedozwolona sekcja lub typ: sections.${key}`); } operations++; } } for (const [group, config] of Object.entries(COLLECTIONS)) { if (!has(patch, group)) { continue; } if (!profile.collections[group]) { fail(`Kolekcja ${group} nie jest obsługiwana przez generator „${profile.label}”.`); } if (!Array.isArray(patch[group]) || patch[group].length > 500) { fail(`${group}: oczekiwana lista do 500 wierszy.`); } const names = /* @__PURE__ */ new Set(); patch[group].forEach((row, index) => { if (!object(row) || Object.keys(row).length !== config.props.length || config.props.some((key) => !has(row, key) || typeof row[key] !== "string")) { fail(`${group}, wiersz ${index + 1}: błędne pola.`); } const tag = group === "modifiers" ? row.tag : row.name; if (!/^\[[^[\]\r\n]+\]$/.test(tag)) { fail(`${group}, wiersz ${index + 1}: nazwa tagu musi mieć nawiasy kwadratowe.`); } if (group === "modifiers" && !row.type) { fail(`Modyfikator ${index + 1}: brak typu.`); } if (group === "settingsTags" && names.has(tag)) { fail(`Powtórzony tag ustawień: ${tag}`); } names.add(tag); }); operations++; } if (!operations) { fail("Nie wybrano żadnych pól."); } return patch; } function mergeState(before, patch) { return { fields: { ...before.fields, ...patch.fields }, sections: { ...before.sections, ...patch.sections }, modifiers: has(patch, "modifiers") ? patch.modifiers : before.modifiers, settingsTags: has(patch, "settingsTags") ? patch.settingsTags : before.settingsTags }; } function prepareFormImport(patch) { validatePatch(patch); const profile = profileForPatch(patch); const ready = { ...patch, fields: { ...patch.fields }, sections: { ...patch.sections } }; for (const field of Object.keys(ready.fields)) { let key = fieldSection(field, profile); while (key && key !== "root") { ready.sections[key] = true; key = profile.sections.get(key).parent; } } return ready; } function checkDependencies(before, patch) { const { sections: SECTIONS, callers } = profileForPatch(patch); const target = mergeState(before, patch); const problems = /* @__PURE__ */ new Set(); const enabled = (key) => key === "root" || target.sections[key] === true; function requirePath(key) { while (key && key !== "root") { const { parent, tag } = SECTIONS.get(key); if (!enabled(key)) { problems.add(`Włącz sekcję ${key} (sections.${key}).`); } const caller = callers[key].find((candidate) => enabled(candidate) && (target.fields[`code_${candidate}`] || "").includes(tag)); if (!caller) { problems.add(`Dodaj ${tag} do code_${parent}.`); } key = caller || parent; } } for (const [field, value] of Object.entries(patch.fields || {})) { if (field.startsWith("code_") && value.trim()) { requirePath(field.slice(5)); } } for (const [child, { tag }] of SECTIONS) { for (const parent of callers[child]) { if (!enabled(parent)) { continue; } const code = target.fields[`code_${parent}`] || ""; const affected = has(patch.fields || {}, `code_${parent}`) || has(patch.sections || {}, child) || has(patch.sections || {}, parent); if (affected && code.includes(tag) && !enabled(child)) { problems.add(`${tag} w code_${parent} wymaga włączonej sekcji ${child}.`); } } } for (const [child, { parent }] of SECTIONS) { if (parent && patch.sections?.[parent] === false && enabled(child)) { problems.add(`Wyłącz także sekcję potomną ${child}.`); } } if (problems.size) { fail(`Brakujące zależności (popraw wybór lub edytuj pola razem): ${[...problems].join("\n")}`); } return target; } var copyPatch = (patch, profile) => validatePatch(JSON.parse(JSON.stringify(validatePatch(patch, profile))), profile); // src/template-cache.js var BACKUP_MAX_BYTES = MAX_BYTES + 1024; var backupFormat = "base-template-cache-backup"; var validDate = (value) => typeof value === "string" && Number.isFinite(Date.parse(value)); function validateCache(data) { if (!object(data) || data.version !== 1 || !Array.isArray(data.items) || data.items.length > 100) { fail("Nieprawidłowy format cache (wersja 1, maksymalnie 100 kopii)."); } const ids = /* @__PURE__ */ new Set(); const items = Array.from(data.items, (item) => { const keys = ["id", "name", "savedAt", "lastReadAt", "template"]; if (!object(item) || Object.keys(item).length !== keys.length || keys.some((key) => !has(item, key)) || typeof item.id !== "string" || !item.id || item.id.length > 200 || ids.has(item.id) || typeof item.name !== "string" || !item.name.trim() || item.name.length > 120 || !validDate(item.savedAt) || !(item.lastReadAt === null || validDate(item.lastReadAt))) { fail("Nieprawidłowa kopia w cache: identyfikator, nazwa, daty lub pola."); } ids.add(item.id); return { id: item.id, name: item.name, savedAt: item.savedAt, lastReadAt: item.lastReadAt, template: copyPatch(item.template) }; }); const result = { version: 1, items }; if (new Blob([JSON.stringify(result)]).size > MAX_BYTES) { fail("Cache przekracza limit 5 MB. Usuń niepotrzebne szablony lub użyj eksportu JSON."); } return result; } function validateBackup(data) { const keys = ["format", "version", "createdAt", "items"]; if (!object(data) || Object.keys(data).length !== keys.length || keys.some((key) => !has(data, key)) || data.format !== backupFormat || data.version !== 1 || !validDate(data.createdAt)) { fail("Nieprawidłowy backup cache: wymagany format base-template-cache-backup, wersja 1."); } const cache = validateCache({ version: 1, items: data.items }); return { format: backupFormat, version: 1, createdAt: data.createdAt, items: cache.items }; } var TemplateCache = class { constructor(storage = () => localStorage) { this.storage = storage; this.key = "bex-template-cache-v1"; } readRaw() { try { return this.storage().getItem(this.key); } catch { fail("Przeglądarka blokuje dostęp do pamięci lokalnej."); } } read() { const raw = this.readRaw(); if (raw === null) { return { version: 1, items: [] }; } try { return validateCache(parseJSON(raw)); } catch { fail("Zapisany cache ma nieprawidłowy format. Dane zachowano. Możesz wczytać poprawny backup cache."); } } write(data) { const raw = JSON.stringify(validateCache(data)); try { this.storage().setItem(this.key, raw); } catch { fail("Nie zapisano cache: brak miejsca lub zablokowana pamięć przeglądarki."); } } addTemplate(template, name) { const patch = copyPatch(template); if (typeof name !== "string" || !name.trim() || name.trim().length > 120) { fail("Podaj nazwę kopii (od 1 do 120 znaków)."); } name = name.trim(); const data = this.read(); if (data.items.some((item2) => item2.name === name)) { fail("Kopia o tej nazwie już istnieje. Zmień nazwę importowanej kopii."); } if (data.items.length >= 100) { fail("Limit 100 kopii. Usuń niepotrzebne szablony."); } const item = { id: crypto.randomUUID(), name, savedAt: (/* @__PURE__ */ new Date()).toISOString(), lastReadAt: null, template: patch }; data.items.push(item); this.write(data); return item; } exportTemplate(id) { const item = this.read().items.find((entry) => entry.id === id); if (!item) { fail("Szablon został usunięty. Otwórz listę ponownie."); } return copyPatch(item.template); } exportBackup() { return validateBackup({ format: backupFormat, version: 1, createdAt: (/* @__PURE__ */ new Date()).toISOString(), items: this.read().items }); } restoreBackup(backup, expectedRaw) { const valid = validateBackup(backup); if (this.readRaw() !== expectedRaw) { fail("Cache zmienił się od podglądu backupu. Wczytaj backup ponownie przed potwierdzeniem."); } this.write({ version: 1, items: valid.items }); return valid.items.length; } }; // src/dom.js function el(tag, text, attrs = {}) { const node = document.createElement(tag); if (text !== null) { node.textContent = text; } for (const [key, value] of Object.entries(attrs)) { node.setAttribute(key, value); } return node; } function button(text, action) { const node = el("button", text, { type: "button" }); node.addEventListener("click", action); return node; } // src/json-files.js function downloadJSON(data, filename, compact = false) { const name = filename.replace(/[^\p{L}\p{N}._-]+/gu, "-").slice(0, 150); const blob = new Blob([JSON.stringify(data, null, compact ? void 0 : 2) + "\n"], { type: "application/json;charset=utf-8" }); const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = url; link.download = name; document.body.append(link); try { link.click(); } finally { link.remove(); setTimeout(() => URL.revokeObjectURL(url), 1e4); } } // src/dialog.js function createDialog(title, prefix, canClose) { const root = el("dialog", null, { class: `bex-panel-dialog ${prefix}-dialog`, "aria-labelledby": `${prefix}-title` }); const content = el("div", null, { class: "modal-content panel" }); const header = el("div", null, { class: `modal-header bex-dialog-header ${prefix}-header` }); const close = () => { if (canClose()) { root.close(); } }; const cross = button("×", close); cross.className = "close"; cross.setAttribute("aria-label", "Zamknij"); cross.title = "Zamknij"; header.append(cross, el("h4", title, { id: `${prefix}-title`, class: "modal-title" })); const body = el("div", null, { class: `modal-body bex-dialog-body ${prefix}-body` }); const footer = el("div", null, { class: `modal-footer bex-dialog-footer ${prefix}-footer` }); const dismiss = button("Zamknij", close); dismiss.className = "btn btn-default"; footer.append(dismiss); content.append(header, body, footer); root.append(content); root.addEventListener("cancel", (event) => { if (!canClose()) { event.preventDefault(); } }); return { root, body, footer }; } // src/cache-dialog.js function button2(text, action, variant = "default", small = false) { const control = button(text, action); control.className = `btn btn-${variant}${small ? " btn-sm" : ""}`; return control; } function panel(title) { const root = el("section", null, { class: "panel" }); const heading = el("div", title, { class: "panel-heading" }); const body = el("div", null, { class: "panel-body" }); root.append(heading, body); return { root, heading, body }; } var CacheDialog = class { constructor(editor) { this.editor = editor; this.cache = new TemplateCache(); } cacheMessage(text, error = false) { this.cacheFeedback.textContent = text; this.cacheFeedback.dataset.error = String(error); this.cacheFeedback.className = `bex-cache-feedback alert ${error ? "alert-danger" : "alert-success"}`; this.cacheFeedback.hidden = !text; } async cacheAction(action) { if (this.editor.busy) { return; } this.editor.lock(true); try { this.editor.model.ensure(); await action(); } catch (error) { this.cacheMessage(error.message, true); } finally { this.editor.lock(false); } } openCache() { if (this.editor.busy) { return; } if (!this.cacheDialog) { const { root, body, footer } = createDialog("Cache szablonów", "bex-cache", () => !this.editor.busy); this.cacheDialog = root; const top = el("div", null, { class: "row" }); const saveColumn = el("div", null, { class: "col-sm-6" }); const filesColumn = el("div", null, { class: "col-sm-6" }); const savePanel = panel("Zapis bieżącego szablonu"); const filePanel = panel("Pliki i backup"); const field = el("div", null, { class: "form-group" }); const label = el("label", "Nazwa kopii", { for: "bex-cache-name", class: "control-label" }); this.cacheName = el("input", null, { id: "bex-cache-name", class: "form-control", type: "text", maxlength: "120", autocomplete: "off" }); field.append(label, this.cacheName); const save = button2("Zapisz nowy szablon", () => this.cacheAction(() => this.saveCache()), "primary"); savePanel.body.append(field, save, el("p", "Zapisuje aktualną zawartość formularza do pamięci przeglądarki.", { class: "help-block" })); filePanel.body.append(this.createTransferControls()); saveColumn.append(savePanel.root); filesColumn.append(filePanel.root); top.append(saveColumn, filesColumn); this.cacheFeedback = el("div", "", { class: "bex-cache-feedback alert", role: "status", "aria-live": "polite", hidden: "" }); this.cacheTransfer = el("div", null, { class: "bex-cache-transfer", "aria-label": "Podgląd importu do cache" }); const listPanel = panel("Zapisane szablony"); this.cacheCount = el("span", "0", { class: "badge pull-right", "aria-label": "Liczba zapisanych kopii" }); listPanel.heading.append(this.cacheCount); this.cacheList = el("div", null, { class: "table-responsive bex-cache-list", "aria-label": "Zapisane szablony" }); listPanel.body.append(el("p", "„Wczytaj” uzupełnia formularz. Eksport i backup operują na zapisanych kopiach.", { class: "help-block" }), this.cacheList); body.append(top, this.cacheFeedback, this.cacheTransfer, listPanel.root); footer.prepend(el("span", "Kopie są przechowywane lokalnie w tej przeglądarce.", { class: "text-muted" })); this.cacheDialog.addEventListener("close", () => this.cacheTransfer.replaceChildren()); document.body.append(this.cacheDialog); } this.cacheName.value = (this.editor.model.control("name")?.value || "Szablon").slice(0, 120); this.cacheMessage(""); this.cacheTransfer.replaceChildren(); this.cacheDialog.showModal(); try { this.renderCache(); } catch (error) { this.cacheList.replaceChildren(); this.cacheCount.textContent = "—"; this.cacheMessage(error.message, true); } this.cacheName.focus(); } renderCache() { const data = this.cache.read(); const date = (value) => value ? new Date(value).toLocaleString("pl-PL") : "jeszcze nie wczytano"; this.cacheList.replaceChildren(); this.cacheCount.textContent = String(data.items.length); if (!data.items.length) { this.cacheList.append(el("p", "Brak zapisanych szablonów.", { class: "text-muted" })); return; } const table = el("table", null, { class: "table table-light table-hover" }); const head = el("thead", null); const titles = el("tr", null); for (const label of ["Szablon", "Zapisano", "Ostatni odczyt", "Operacje"]) { titles.append(el("th", label, { scope: "col" })); } head.append(titles); const rows = el("tbody", null); table.append(head, rows); this.cacheList.append(table); for (const item of [...data.items].sort((a, b) => b.savedAt.localeCompare(a.savedAt))) { const profile = profileForPatch(item.template); const compatible = profile.id === this.editor.model.profile.id; const row = el("tr", null, { class: "bex-cache-row", "data-cache-id": item.id }); const actions = el("div", null, { class: "bex-cache-actions" }); const load = button2("Wczytaj", () => this.cacheAction(async () => { this.cacheMessage(""); load.replaceChildren(el("span", "", { class: "bex-import-spinner", "aria-hidden": "true" }), document.createTextNode(" Wczytywanie…")); load.setAttribute("aria-busy", "true"); try { const current = this.cache.read().items.find((entry2) => entry2.id === item.id); if (!current) { fail("Szablon został usunięty. Otwórz listę ponownie."); } await this.editor.model.apply(prepareFormImport(current.template), { formImport: true }); this.cacheMessage(`✓ Wczytano „${current.name}”.`); const latest = this.cache.read(); const entry = latest.items.find((entry2) => entry2.id === item.id); if (entry) { entry.lastReadAt = (/* @__PURE__ */ new Date()).toISOString(); this.cache.write(latest); } this.renderCache(); this.cacheMessage(`✓ Wczytano „${current.name}” — ${date((/* @__PURE__ */ new Date()).toISOString())}.`); } catch (error) { this.cacheMessage(`${this.cacheFeedback.textContent.startsWith("✓ Wczytano") ? this.cacheFeedback.textContent + " Nie zapisano informacji o odczycie: " : ""}${error.message}`, true); } finally { load.replaceChildren(document.createTextNode("Wczytaj")); load.removeAttribute("aria-busy"); } }), "primary", true); const confirm = (label, action) => button2(label, () => { actions.replaceChildren(el("span", `${label}: „${item.name}”?`), button2("Potwierdź", () => this.cacheAction(action), label === "Usuń" ? "danger" : "warning", true), button2("Anuluj", () => this.renderCache(), "default", true)); }, "default", true); const exportItem = button2("Eksportuj JSON", () => this.cacheAction(() => { downloadJSON(this.cache.exportTemplate(item.id), `base-${item.name}.json`); this.cacheMessage(`✓ Wyeksportowano „${item.name}” z cache do JSON.`); }), "default", true); const overwrite = confirm("Nadpisz", () => this.saveCache(item.id)); for (const control of [load, overwrite]) { control.dataset.bexIncompatible = String(!compatible); control.disabled = !compatible; if (!compatible) { control.title = `Otwórz generator „${profile.label}”, aby użyć tej kopii.`; } } actions.append(load, exportItem, overwrite, confirm("Usuń", () => { const latest = this.cache.read(); latest.items = latest.items.filter((entry) => entry.id !== item.id); this.cache.write(latest); this.renderCache(); this.cacheMessage(`Usunięto „${item.name}” z pamięci przeglądarki.`); })); const name = el("td", null); name.append(el("strong", item.name), el("div", profile.label, { class: "text-muted" })); const controls = el("td", null); controls.append(actions); row.append(name, el("td", date(item.savedAt), { class: "text-muted" }), el("td", date(item.lastReadAt), { class: "text-muted" }), controls); rows.append(row); } } saveCache(id = null) { const data = this.cache.read(); let item = data.items.find((entry) => entry.id === id); if (id && item && profileForPatch(item.template).id !== this.editor.model.profile.id) { fail("Nie można nadpisać kopii innego generatora. Otwórz właściwy edytor."); } const name = id ? item?.name : this.cacheName.value.trim(); if (!name) { fail("Podaj nazwę kopii lub otwórz listę ponownie, jeśli kopię usunięto."); } if (name.length > 120) { fail("Nazwa kopii może mieć maksymalnie 120 znaków."); } if (!id && data.items.some((entry) => entry.name === name)) { fail("Kopia o tej nazwie już istnieje. Użyj „Nadpisz” przy zapisanym szablonie albo zmień nazwę."); } if (!item) { if (data.items.length >= 100) { fail("Limit 100 kopii. Usuń niepotrzebne szablony."); } item = { id: crypto.randomUUID(), name, lastReadAt: null }; data.items.push(item); } item.template = this.editor.model.template(); item.savedAt = (/* @__PURE__ */ new Date()).toISOString(); this.cache.write(data); this.renderCache(); this.cacheMessage(`✓ Zapisano „${name}” — ${new Date(item.savedAt).toLocaleString("pl-PL")}.`); } createTransferControls() { const actions = el("div", null, { class: "bex-cache-file-actions" }); for (const [kind, label] of [["template", "Importuj szablon do cache"], ["backup", "Wczytaj backup cache"]]) { const input = el("input", null, { type: "file", accept: ".json,application/json", hidden: "", "data-bex-cache-file": kind }); const choose = button2(label, () => input.click()); input.addEventListener("change", () => { const file = input.files[0]; input.value = ""; if (file) { this.cacheAction(async () => { this.cacheTransfer.replaceChildren(); this.cacheMessage(""); const original = choose.textContent; choose.replaceChildren(el("span", "", { class: "bex-import-spinner", "aria-hidden": "true" }), document.createTextNode(" Wczytywanie…")); choose.setAttribute("aria-busy", "true"); try { const limit = kind === "backup" ? BACKUP_MAX_BYTES : MAX_BYTES; if (file.size > limit) { fail("Plik przekracza dopuszczalny rozmiar. Szablon: 5 MB; backup: 5 MB + 1 KB metadanych."); } const parsed = parseJSON(await file.text(), limit); this.editor.model.ensure(); if (kind === "backup") { this.previewBackup(validateBackup(parsed)); } else { this.previewTemplate(validatePatch(parsed), file.name); } } finally { choose.replaceChildren(document.createTextNode(original)); choose.removeAttribute("aria-busy"); } }); } }); actions.append(choose, input); } actions.append(button2("Pobierz backup cache", () => this.cacheAction(() => { const backup = this.cache.exportBackup(); downloadJSON(backup, `base-cache-backup-${backup.createdAt.replace(/[:.]/g, "-")}.json`, true); this.cacheMessage(`✓ Pobrano backup cache: ${backup.items.length} kopii.`); }))); return actions; } previewTemplate(template, filename) { const name = el("input", null, { type: "text", class: "form-control", maxlength: "120", "aria-label": "Nazwa importowanej kopii", "data-bex-import-name": "" }); name.value = (template.fields?.name || filename.replace(/\.json$/i, "") || "Importowany szablon").slice(0, 120); const confirm = button2("Dodaj do cache", () => this.cacheAction(() => { const item = this.cache.addTemplate(template, name.value); this.cacheTransfer.replaceChildren(); this.renderCache(); this.cacheMessage(`✓ Zaimportowano „${item.name}” do cache. Formularz pozostał bez zmian.`); }), "primary"); this.cacheTransfer.className = "bex-cache-transfer alert alert-info"; this.cacheTransfer.replaceChildren( el("p", "Import pojedynczego szablonu JSON do cache. Podaj nazwę kopii:"), name, confirm, button2("Anuluj import", () => this.cacheTransfer.replaceChildren()) ); } previewBackup(backup) { const expectedRaw = this.cache.readRaw(); let count; try { count = this.cache.read().items.length; } catch { count = "nie można odczytać (uszkodzony cache)"; } const names = el("ul", null, { class: "bex-cache-backup-list" }); for (const item of backup.items) { names.append(el("li", item.name)); } this.cacheTransfer.className = "bex-cache-transfer alert alert-warning"; this.cacheTransfer.replaceChildren( el("strong", `Odtworzenie zastąpi cały cache: ${count} obecnych kopii → ${backup.items.length} kopii z backupu.`), el("p", `Backup z ${new Date(backup.createdAt).toLocaleString("pl-PL")}. Zachowa nazwy, daty i zawartość kopii. Formularz nie zostanie zmieniony.`), names, button2("Zastąp cache backupem", () => this.cacheAction(() => { const restored = this.cache.restoreBackup(backup, expectedRaw); this.cacheTransfer.replaceChildren(); this.renderCache(); this.cacheMessage(`✓ Odtworzono backup cache: ${restored} kopii.`); }), "danger"), button2("Anuluj odtwarzanie", () => this.cacheTransfer.replaceChildren()) ); } destroy() { this.cacheDialog?.close(); this.cacheDialog?.remove(); } }; // src/sections.js var SectionCatalog = class { static list(profile = PRINTOUT_PROFILE) { return profile.rows.map(([key, tag, parent]) => ({ key, tag, parent, field: `code_${key}` })); } static resolve(reference, profile = PRINTOUT_PROFILE) { const section = this.list(profile).find((item) => item.key === reference || item.tag === reference); if (!section) { fail(`Nieznana sekcja: ${String(reference)}`); } return section; } static activation(reference, profile = PRINTOUT_PROFILE) { let section = this.resolve(reference, profile); const sections = {}; while (section.parent !== null) { sections[section.key] = true; section = this.resolve(section.parent, profile); } return sections; } static deactivation(reference, profile = PRINTOUT_PROFILE) { const section = this.resolve(reference, profile); if (section.key === "root") { fail("Sekcja [ROOT] nie może zostać wyłączona."); } const sections = { [section.key]: false }; for (const item of this.list(profile)) { if (has(sections, item.parent)) { sections[item.key] = false; } } return sections; } }; // src/template-form.js var TemplateForm = class { constructor(form, isCurrent, onBusy, profile = PRINTOUT_PROFILE) { this.form = form; this.isCurrent = isCurrent; this.onBusy = onBusy; this.applying = false; this.profile = profile; } patch(data = {}) { return { ...emptyPatch(), generator: this.profile.id, ...data }; } fieldSection(key) { return fieldSection(key, this.profile); } tagLists() { return this.profile.fields.filter((field) => field.startsWith("code_")).map((field) => this.control(`list_tags_${field}`)).filter(Boolean); } sectionTags(reference) { this.ensure(); const section = SectionCatalog.resolve(reference, this.profile); const list = this.control(`list_tags_${section.field}`); return [...list?.querySelectorAll("span,button.bex-catalog-tag") || []].flatMap((node) => { const tag = node.textContent.trim(); return /^\[[^[\]\r\n]+\]$/.test(tag) ? [{ tag, description: node.getAttribute("data-original-title") || node.getAttribute("title") || "" }] : []; }); } control(id) { return [...this.form.querySelectorAll("[id]")].find((n) => n.id === id) || null; } ensure() { if (!this.form.isConnected || !this.isCurrent()) { fail("Formularz został zmieniony. Otwórz operację ponownie."); } } rows(group) { const config = COLLECTIONS[group], table = this.control(config.table); if (!table) { fail(`Brak tabeli ${config.table}.`); } return [...table.querySelectorAll(config.row)]; } rowControl(row, prop) { return [...row.querySelectorAll("input,select,textarea")].find((n) => n.name.endsWith(`[${prop}]`)); } readCollection(group) { if (!this.control(COLLECTIONS[group].table)) { return []; } return this.rows(group).map((row) => Object.fromEntries(COLLECTIONS[group].props.map((prop) => { const control = this.rowControl(row, prop); if (!control) { fail(`Brak pola ${prop} w ${group}.`); } return [prop, control.value]; }))); } snapshot() { this.ensure(); return { fields: Object.fromEntries(this.profile.fields.flatMap((key) => { const n = this.control(key); return n ? [[key, n.value]] : []; })), sections: Object.fromEntries(this.profile.rows.filter(([key]) => key !== "root").flatMap(([key]) => { const n = this.control(`sections_${key}`); return n ? [[key, n.checked]] : []; })), modifiers: this.readCollection("modifiers"), settingsTags: this.readCollection("settingsTags") }; } entries() { return [ ...this.profile.fields.map((key) => ({ group: "fields", key, label: this.profile.labels[key] || `Kod ${this.profile.sections.get(key.slice(5)).tag}`, available: !!this.control(key) })), ...this.profile.rows.filter(([key]) => key !== "root").map(([key, tag]) => ({ group: "sections", key, label: `Włączona sekcja ${tag}`, available: !!this.control(`sections_${key}`) })), ...Object.entries(this.profile.collections).map(([key, config]) => ({ group: key, key, label: config.label, available: !!this.control(config.table) })) ]; } cleanRows(group, rows) { return rows.filter((row) => group === "modifiers" ? row.tag !== "" || row.from !== "" || row.to !== "" : Object.values(row).some((value) => value !== "")); } pick(state, selection) { const patch = this.patch(); for (const [group, key] of selection) { if (COLLECTIONS[group]) { patch[group] = this.cleanRows(group, state[group]); } else { patch[group] ||= {}; if (!has(state[group], key)) { fail(`Pole ${key} nie jest dostępne.`); } patch[group][key] = state[group][key]; } } return patch; } template() { const state = this.snapshot(); const selection = this.entries().filter((item) => { const section = item.group === "fields" && this.fieldSection(item.key); return item.available && formatFieldEnabled(item.key, state.fields) && (!section || section === "root" || state.sections[section] === true); }).map((item) => [item.group, item.key]); return validatePatch(this.pick(state, selection)); } async waitFor(read, description) { const end = Date.now() + 6e3; while (Date.now() < end) { this.ensure(); const result = read(); if (result) { return result; } await new Promise((resolve) => setTimeout(resolve, 60)); } fail(`Nie pojawiła się kontrolka/opcja: ${description}.`); } setValue(node, value) { this.ensure(); if (!node) { fail("Brak kontrolki do uzupełnienia."); } if (node.disabled) { fail(`Pole ${node.name || node.id} jest zablokowane.`); } if (node.tagName === "SELECT" && ![...node.options].some((o) => o.value === value && !o.disabled)) { fail(`Niedostępna opcja „${value}” w ${node.name || node.id}.`); } if (node.value === value) { return; } const proto = node.tagName === "TEXTAREA" ? HTMLTextAreaElement.prototype : node.tagName === "SELECT" ? HTMLSelectElement.prototype : HTMLInputElement.prototype; Object.getOwnPropertyDescriptor(proto, "value").set.call(node, value); node.dispatchEvent(new Event("input", { bubbles: true })); node.dispatchEvent(new Event("change", { bubbles: true })); } assertSectionEnabled(reference) { this.ensure(); const section = SectionCatalog.resolve(reference, this.profile); for (const key of Object.keys(SectionCatalog.activation(reference, this.profile))) { if (!this.control(`sections_${key}`)?.checked) { fail(`Sekcja ${this.profile.sections.get(key).tag} jest wyłączona. Najpierw użyj sections.enable().`); } } return section; } readySectionEditor(reference) { const section = this.assertSectionEnabled(reference); const node = this.control(section.field); return node && !node.disabled && node.getClientRects().length > 0 ? node : null; } async waitForSectionEditor(reference) { const section = this.assertSectionEnabled(reference); return this.waitFor(() => this.readySectionEditor(reference), `gotowa sekcja ${section.tag}`); } async insertTag(reference, tag) { if (typeof tag !== "string" || !/^\[[^[\]\r\n]+\]$/.test(tag)) { fail("Wymagany tag w nawiasach kwadratowych."); } const section = this.assertSectionEnabled(reference); const node = this.readySectionEditor(reference); if (!node) { fail("Edytor sekcji nie jest gotowy."); } const start2 = node.selectionStart, end = node.selectionEnd; const value = node.value.slice(0, start2) + tag + node.value.slice(end); const result = await this.apply(this.patch({ fields: { [section.field]: value } }), { formImport: true, requireActiveSections: true }); const current = this.readySectionEditor(reference); if (current) { current.focus(); current.setSelectionRange(start2 + tag.length, start2 + tag.length); } return result; } async setSection(key, value) { this.ensure(); const node = this.control(`sections_${key}`); if (!node || node.disabled) { fail(`Brak dostępnego checkboxa sekcji ${key}.`); } if (node.checked !== value) { node.click(); } if (node.checked !== value) { fail(`Nie udało się przełączyć sekcji ${key}.`); } if (value) { await this.waitFor(() => { const editor = this.control(`code_${key}`); return editor && !editor.disabled && editor.getClientRects().length > 0 && editor; }, `widoczne pole code_${key}`); } } collectionAddButton(group) { const config = COLLECTIONS[group]; const controls = [...this.control(config.table).querySelectorAll("[onclick]")].filter((node) => (node.getAttribute("onclick") || "").trim().replace(/;$/, "").trim() === `${config.add}()` && !node.disabled); return controls.find((node) => node.getClientRects().length > 0) || controls[0]; } modifierDeleteButton(row) { const icon = row.querySelector(".fa-trash,.fa-trash-alt,.fa-trash-can"); return icon?.closest("a,button") || [...row.querySelectorAll("a,button")].find((node) => /usuń|usun|delete/i.test(`${node.title} ${node.getAttribute("aria-label") || ""}`)); } async writeModifierRow(row, values) { let type = await this.waitFor(() => this.rowControl(row, "type"), "typ nowego modyfikatora"); if (![...type.options].some((option) => option.value === values.type)) { type.dispatchEvent(new MouseEvent("mousedown", { bubbles: true })); type.dispatchEvent(new FocusEvent("focusin", { bubbles: true })); type = await this.waitFor(() => { const current = this.rowControl(row, "type"); return current && [...current.options].some((option) => option.value === values.type) && current; }, `typ modyfikatora ${values.type}`); } this.setValue(type, values.type); for (const prop of ["tag", "from", "to"]) { const control = await this.waitFor(() => this.rowControl(row, prop), `modyfikator: ${prop}`); if (control.value !== values[prop]) { this.setValue(control, values[prop]); } } } async replaceModifiers(data) { const removals = this.rows("modifiers").map((row) => ({ row, button: this.modifierDeleteButton(row) })); if (removals.some((item) => !item.button || item.button.disabled)) { fail("Brak dostępnej ikony usuwania modyfikatora. Lista nie została zastąpiona."); } if (data.length && !this.collectionAddButton("modifiers")) { fail("Brak przycisku „Dodaj modyfikator”. Lista nie została zastąpiona."); } for (const item of removals.reverse()) { this.ensure(); item.button.click(); await this.waitFor(() => !this.rows("modifiers").includes(item.row), "usunięcie modyfikatora"); } for (const values of data) { const existing = this.rows("modifiers"); const add = this.collectionAddButton("modifiers"); if (!add) { fail("Brak przycisku „Dodaj modyfikator”."); } add.click(); const added = await this.waitFor(() => { const rows = this.rows("modifiers").filter((row) => !existing.includes(row)); return rows.length && rows; }, "nowy wiersz modyfikatora"); if (added.length !== 1 || this.rows("modifiers").length !== existing.length + 1) { fail("Przycisk „Dodaj modyfikator” utworzył nieoczekiwaną liczbę wierszy."); } await this.writeModifierRow(added[0], values); } } async writeCollection(group, data) { if (!this.control(COLLECTIONS[group].table) && data.length === 0) { return; } if (group === "modifiers") { await this.replaceModifiers(data); return; } const config = COLLECTIONS[group]; let rows = this.rows(group); while (rows.length < data.length) { const count = rows.length; const add = this.collectionAddButton(group); if (!add) { fail(`Brak przycisku dodawania: ${config.label}.`); } add.click(); rows = await this.waitFor(() => { const current = this.rows(group); return current.length > count && current; }, `nowy wiersz ${group}`); } for (let i = 0; i < data.length; i++) { this.ensure(); const row = rows[i], values = data[i]; for (const prop of config.props) { const node = this.rowControl(row, prop); if (!node) { fail(`Brak ${group}.${prop}.`); } this.setValue(node, values[prop]); } } for (const row of rows.slice(data.length)) { row.remove(); } } async fieldForWrite(key, value, fields) { if (FIELD_FORMATS[key] && !formatFieldEnabled(key, fields)) { return null; } return this.waitFor(() => { const node = this.control(key); if (!node) { return false; } if (FIELD_FORMATS[key] && formatFieldEnabled(key, fields)) { if (node.disabled || !node.getClientRects().length) { return false; } if (node.tagName === "SELECT" && ![...node.options].some((option) => option.value === value && !option.disabled)) { return false; } } return node; }, `gotowe pole ${key}`); } preflight(patch, before, { formImport = false, requireActiveSections = false } = {}) { validatePatch(patch, this.profile); if (!formImport) { checkDependencies(before, patch); } for (const [key, value] of Object.entries(patch.fields || {})) { if (requireActiveSections && key.startsWith("code_")) { this.assertSectionEnabled(key.slice(5)); continue; } const node = this.control(key); const targetFields = { ...before.fields, ...patch.fields }; if (FIELD_FORMATS[key] && !formatFieldEnabled(key, targetFields)) { continue; } const formatChanges = FIELD_FORMATS[key] && (has(patch.fields, "type") && patch.fields.type !== before.fields.type || labelDetail(key) && has(patch.fields, "format_pdf_insert_label") && patch.fields.format_pdf_insert_label !== before.fields.format_pdf_insert_label); if (formatChanges || FIELD_FORMATS[key] && formatFieldEnabled(key, targetFields) && (!node || node.disabled || !node.getClientRects().length)) { continue; } if (!node && !key.startsWith("code_") && !formImport) { fail(`Brak pola ${key}.`); } if (node?.disabled) { fail(`Pole ${key} jest zablokowane.`); } if (node?.tagName === "SELECT" && ![...node.options].some((o) => o.value === value && !o.disabled)) { fail(`Nieznana opcja ${key}: ${value}`); } } for (const key of Object.keys(patch.sections || {})) { if (!this.control(`sections_${key}`)) { fail(`Brak checkboxa ${key}.`); } } } async write(patch, { requireActiveSections = false } = {}) { const fields = { ...this.snapshot().fields, ...patch.fields }; const priority = ["type", "template_lang", "format_pdf_insert_label"]; for (const key of priority) { if (has(patch.fields || {}, key)) { const node = await this.fieldForWrite(key, patch.fields[key], fields); if (node) { this.setValue(node, patch.fields[key]); } } } for (const [key] of this.profile.rows) { if (patch.sections?.[key] === true) { await this.setSection(key, true); } } for (const entry of Object.entries(patch.fields || {})) { const [key, value] = entry; if (priority.includes(key)) { continue; } const node = requireActiveSections && key.startsWith("code_") ? await this.waitForSectionEditor(key.slice(5)) : await this.fieldForWrite(key, value, fields); if (node) { this.setValue(node, value); } } for (const group of Object.keys(this.profile.collections)) { if (has(patch, group)) { await this.writeCollection(group, patch[group]); } } for (const [key] of [...this.profile.rows].reverse()) { if (patch.sections?.[key] === false) { await this.setSection(key, false); } } await new Promise((resolve) => setTimeout(resolve, 150)); this.ensure(); } differences(expected, actual) { const result = []; for (const group of ["fields", "sections"]) { for (const key of Object.keys(expected[group] || {})) { if (group === "fields" && FIELD_FORMATS[key] && !formatFieldEnabled(key, expected.fields)) { continue; } if (group === "fields" && this.fieldSection(key) && expected.sections[this.fieldSection(key)] === false && !has(actual.fields, key)) { continue; } let value = expected[group][key]; if (group === "fields" && this.control(key)?.tagName === "TEXTAREA") { value = value.replace(/\r\n?/g, "\n"); } if (!same(value, actual[group][key])) { result.push(`${group}.${key}`); } } } for (const group of Object.keys(COLLECTIONS)) { if (!same(expected[group], actual[group])) { result.push(group); } } return result; } async restore(state) { for (const [key] of this.profile.rows) { if (key !== "root" && has(state.fields, `code_${key}`) && !this.control(`code_${key}`)) { await this.setSection(key, true); } } const restorePatch = { ...state }; for (const group of Object.keys(COLLECTIONS)) { if (same(this.readCollection(group), state[group])) { delete restorePatch[group]; } } await this.write(restorePatch); for (const group of Object.keys(COLLECTIONS)) { if (!same(this.readCollection(group), state[group])) { await this.writeCollection(group, state[group]); } } const diff = this.differences(state, this.snapshot()); if (diff.length) { fail(`Nie odtworzono: ${diff.join(", ")}`); } } async apply(patch, options = {}) { this.ensure(); if (this.applying) { fail("Trwa już modyfikacja formularza. Poczekaj na jej zakończenie."); } patch = copyPatch(patch, this.profile); const before = this.snapshot(); this.preflight(patch, before, options); this.applying = true; this.onBusy(true); const target = mergeState(before, patch); try { await this.write(patch, options); const after = this.snapshot(), diff = this.differences(target, after); if (diff.length) { fail(`Odczyt po zmianie jest niezgodny: ${diff.join(", ")}`); } return after; } catch (error) { try { await this.restore(before); } catch (rollback) { fail(`${error.message} Przywracanie niepełne: ${rollback.message} Sprawdź formularz przed zapisem.`); } fail(`${error.message} Przywrócono poprzedni stan formularza.`); } finally { this.applying = false; this.onBusy(false); } } }; // src/inventory-product-tags.js var INVENTORY_PRODUCT_TAGS = [ { "tag": "[produkt_id]", "description": "ID produktu" }, { "tag": "[produkt_ean]", "description": "Główny kod EAN produktu" }, { "tag": "[produkt_ean_wszystkie]", "description": "Wszystkie kody EAN produktu oddzielone przecinkiem (produkt może posiadać wiele kodów)" }, { "tag": "[produkt_ean_szczegoly]", "description": "Dodatkowe kody EAN produktu wraz z ilością i opisem w formacie JSON" }, { "tag": "[produkt_sku]", "description": "Kod SKU" }, { "tag": "[produkt_asin]", "description": "Kod ASIN" }, { "tag": "[produkt_tagi]", "description": "Wszystkie tagi produktu oddzielone przecinkiem" }, { "tag": "[produkt_kategoria_id]", "description": "ID kategorii" }, { "tag": "[produkt_kategoria_nazwa]", "description": "Nazwa kategorii" }, { "tag": "[produkt_kategoria_sciezka_1]", "description": 'Ścieżka kategorii oddzielona znakiem "/"' }, { "tag": "[produkt_kategoria_sciezka_2]", "description": 'Ścieżka kategorii oddzielona znakiem ">"' }, { "tag": "[produkt_kategoria_sciezka_3]", "description": 'Ścieżka kategorii oddzielona znakiem " > "' }, { "tag": "[stawka_vat]", "description": "Podatek VAT procent" }, { "tag": "[waga]", "description": "Waga pojedynczej sztuki" }, { "tag": "[wysokosc]", "description": "Wysokość produktu" }, { "tag": "[dlugosc]", "description": "Długość produktu" }, { "tag": "[szerokosc]", "description": "Szerokość produktu" }, { "tag": "[id_produktu_rodzica]", "description": "Wariant - ID produktu rodzica" }, { "tag": "[ilosc_wariantow]", "description": "Ilość wariantów przypisanych do tego produktu" }, { "tag": "[gwiazdka]", "description": "Identyfikator oznaczenia gwiazdką" }, { "tag": "[produkt_producent_id]", "description": "Producent ID" }, { "tag": "[produkt_producent_nazwa]", "description": "Nazwa producenta" }, { "tag": "[produkt_lp]", "description": "Liczba porządkowa" }, { "tag": "[zdjecie_1]", "description": "Zdjęcie 1" }, { "tag": "[zdjecie_2]", "description": "Zdjęcie 2" }, { "tag": "[zdjecie_3]", "description": "Zdjęcie 3" }, { "tag": "[zdjecie_4]", "description": "Zdjęcie 4" }, { "tag": "[zdjecie_5]", "description": "Zdjęcie 5" }, { "tag": "[zdjecie_6]", "description": "Zdjęcie 6" }, { "tag": "[zdjecie_7]", "description": "Zdjęcie 7" }, { "tag": "[zdjecie_8]", "description": "Zdjęcie 8" }, { "tag": "[zdjecie_9]", "description": "Zdjęcie 9" }, { "tag": "[zdjecie_10]", "description": "Zdjęcie 10" }, { "tag": "[zdjecie_11]", "description": "Zdjęcie 11" }, { "tag": "[zdjecie_12]", "description": "Zdjęcie 12" }, { "tag": "[zdjecie_13]", "description": "Zdjęcie 13" }, { "tag": "[zdjecie_14]", "description": "Zdjęcie 14" }, { "tag": "[zdjecie_15]", "description": "Zdjęcie 15" }, { "tag": "[zdjecie_16]", "description": "Zdjęcie 16" }, { "tag": "[ilosc]", "description": "Ilość produktów w magazynie" }, { "tag": "[ilosc_wszystkie_magazyny]", "description": 'Wszystkie ilości per magazyn, w formacie "magazyn 1:ilość;magazyn 2:ilość" (np. "db|2:43;shop|23:0;shop|12:0;db|30:33")' }, { "tag": "[ilosc_domyslny]", "description": "Ilość produktów w magazynie (Domyślny)" }, { "tag": "[prog_domyslny]", "description": "Próg dla magazynu (Domyślny)" }, { "tag": "[ilosc_zarezerwowanych]", "description": "Ilość zarezerwowanych sztuk (Wszystkie magazyny)" }, { "tag": "[ilosc_zarezerwowanych_domyslny]", "description": "Ilość zarezerwowanych sztuk (Domyślny)" }, { "tag": "[ilosc_zamowiona]", "description": "Ilość zamówionych sztuk (Wszystkie magazyny)" }, { "tag": "[ilosc_zamowiona_domyslny]", "description": "Ilość zamówionych sztuk (Domyślny)" }, { "tag": "[cena]", "description": "Cena brutto za sztukę" }, { "tag": "[cena_wszystkie_grupy_cenowe]", "description": 'Wszystkie grupy cenowe z wartościami, w formacie "grupa cenowa 1:wartość;grupa cenowa 2:wartość" (np. "10:123.45;11:234.55")' }, { "tag": "[cena_domyslna_583]", "description": "Cena brutto za sztukę (Domyślna)" }, { "tag": "[kod]", "description": "Kod" }, { "tag": "[kod_wszyscy_dostawcy]", "description": 'Wszyscy dostawcy z kodami z wartościami, w formacie "dostawca 1:wartość;dostawca 2: wartość" (np. "3:kod1;20:kod2")' }, { "tag": "[cena_zakupu]", "description": "Cena brutto zakupu za sztukę" }, { "tag": "[cena_zakupu_srednia]", "description": "Średnia cena brutto zakupu za sztukę" }, { "tag": "[cena_zakupu_ostatnia]", "description": "Ostatnia cena zakupu produktu ze zrealizowanej dostawy" }, { "tag": "[produkt_data_dostawy_ostatnia]", "description": "Data ostatniej dostawy produktu" }, { "tag": "[sredni_koszt_dodatkowy_zakupu]", "description": "Średni koszt dodatkowy brutto zakupu za sztukę" }, { "tag": "[cena_zakupu_wszyscy_dostawcy]", "description": 'Wszyscy dostawcy z cenami zakupu z wartościami, w formacie "dostawca 1:wartość;dostawca 2:wartość" (np. "3:250.00;20:800.00")' }, { "tag": "[produkt_lokalizacja_wszystkie]", "description": 'Wszystkie lokalizacje, w formacie "magazyn 1:lokalizacja;magazyn 2:lokalizacja" (np. "db|2:ABC1;shop|23:ABC2")' }, { "tag": "[produkt_lokalizacja_domyslny]", "description": "Lokalizacja produktu w magazynie (Domyślny)" }, { "tag": "[produkt_nazwa]", "description": "Nazwa" }, { "tag": "[produkt_nazwa_pl]", "description": "Nazwa (pl)" }, { "tag": "[opis]", "description": "Opis" }, { "tag": "[opis_pl]", "description": "Opis (pl)" }, { "tag": "[opis_dodatkowy_1]", "description": "Opis dodatkowy 1" }, { "tag": "[opis_dodatkowy_1_pl]", "description": "Opis dodatkowy 1 (pl)" }, { "tag": "[opis_dodatkowy_2]", "description": "Opis dodatkowy 2" }, { "tag": "[opis_dodatkowy_2_pl]", "description": "Opis dodatkowy 2 (pl)" }, { "tag": "[opis_dodatkowy_3]", "description": "Opis dodatkowy 3" }, { "tag": "[opis_dodatkowy_3_pl]", "description": "Opis dodatkowy 3 (pl)" }, { "tag": "[opis_dodatkowy_4]", "description": "Opis dodatkowy 4" }, { "tag": "[opis_dodatkowy_4_pl]", "description": "Opis dodatkowy 4 (pl)" }, { "tag": "[parametr=X]", "description": "Parametr produktu (zamiast X wpisz nazwę parametru produktu), aby wybrać język wpisz np. [parametr=en=kolor]" }, { "tag": "[ilosc_produktow_w_zestawie]", "description": "Ilość produktów w danym zestawie, tylko przy użyciu jako podsekcja zestawu" }, { "tag": "[ilosc_sztuk_w_zestawie]", "description": "Ilość sztuk w danym zestawie, tylko przy użyciu jako podsekcja zestawu" }, { "tag": "[aktualna_data]", "description": "Data wygenerowania wydruku" }, { "tag": "[profil_nazwisko]", "description": "Nazwisko zalogowanego użytkownika (osoby która tworzy wydruk)" } ]; function catalogTags(tags = INVENTORY_PRODUCT_TAGS) { return tags.map(({ tag, description }) => ({ tag: `[katalog=${tag.slice(1, -1)}]`, description, sourceTag: tag })); } // src/catalog-tag-lists.js var CatalogTagLists = class { constructor(editor) { this.editor = editor; this.groups = /* @__PURE__ */ new Map(); } mount() { const model = this.editor.model; const lists = new Set(model.tagLists().filter((list) => [...list.querySelectorAll("span")].some((node) => node.textContent.trim() === "[katalog=X]"))); for (const [list, group] of this.groups) { if (!lists.has(list) || group.parentElement !== list) { group.remove(); this.groups.delete(list); } } for (const list of lists) { let group = this.groups.get(list); if (!group) { for (const stale of list.querySelectorAll("[data-bex-catalog-tags]")) { stale.remove(); } group = this.create(list.id.slice("list_tags_code_".length)); this.groups.set(list, group); } if (list.lastElementChild !== group) { list.append(group); } } this.setBusy(this.editor.busy); } create(section) { const group = el("li", null, { "data-bex-catalog-tags": "", class: "bex-catalog-tags" }); const list = el("ul", null, { class: "list_tags" }); group.append(el("hr", null), el("p", "Tagi z sekcji [PRODUKT] — eksport magazynu", { class: "text-bold" }), list); for (const { tag, description } of catalogTags()) { const control = button(tag, () => this.editor.run(() => this.editor.model.insertTag(section, tag))); control.className = "bex-catalog-tag"; control.title = `${description} Tag z sekcji [PRODUKT] eksportu magazynu. Wartości X i identyfikatory dopasuj do katalogu.`; const row = el("li", null); row.append(control); list.append(row); } return group; } setBusy(locked) { for (const group of this.groups.values()) { for (const control of group.querySelectorAll("button")) { control.disabled = locked; } } } destroy() { for (const group of this.groups.values()) { group.remove(); } this.groups.clear(); } }; // src/tag-list-search.js var searchText = (value) => value.toLocaleLowerCase("pl").normalize("NFD").replace(/\p{M}/gu, "").replace(/ł/g, "l"); var TagListSearch = class { constructor(model) { this.model = model; this.filters = /* @__PURE__ */ new Map(); } mount() { const lists = new Set(this.model.tagLists()); for (const [list, filter] of this.filters) { if (!lists.has(list) || !filter.root.isConnected) { this.remove(list, filter); this.filters.delete(list); } } for (const list of lists) { const panel2 = list.closest(".panel"); const heading = panel2?.querySelector(".panel-heading"); if (!heading) { continue; } let filter = this.filters.get(list); if (!filter) { const stale = [...panel2.querySelectorAll("[data-bex-tag-search-for]")].filter((node) => node.dataset.bexTagSearchFor === list.id); const query = stale[0]?.querySelector("input")?.value || ""; stale.forEach((node) => node.remove()); const root = el("div", null, { class: "bex-tag-search", "data-bex-tag-search-for": list.id }); const input = el("input", null, { type: "search", class: "form-control input-sm", placeholder: "Szukaj po nazwie lub opisie…", "aria-label": `Szukaj tagów: ${list.id.slice("list_tags_code_".length)}`, autocomplete: "off", spellcheck: "false" }); input.value = query; filter = { root, input, onInput: () => this.apply(list, input.value) }; input.addEventListener("input", filter.onInput); input.addEventListener("search", filter.onInput); input.addEventListener("keydown", (event) => { if (event.key === "Enter") { event.preventDefault(); } }); root.append(input); this.filters.set(list, filter); } if (heading.nextElementSibling !== filter.root) { heading.after(filter.root); } this.apply(list, filter.input.value); } } apply(list, query) { const phrase = searchText(query.trim()); this.applyGroup(list, phrase); for (const group of list.querySelectorAll("[data-bex-catalog-tags]")) { group.removeAttribute("data-bex-tag-filtered"); this.applyGroup(group.querySelector("ul"), phrase); } } applyGroup(list, phrase) { let matches = 0; for (const row of list.children) { const controls = [...row.children].filter((node) => node.matches("span,button")); if (!controls.length) { continue; } const text = controls.map((node) => `${node.textContent} ${node.getAttribute("data-original-title") || ""} ${node.title}`).join(" "); const matched = !phrase || searchText(text).includes(phrase); row.toggleAttribute("data-bex-tag-filtered", !matched); if (matched && controls.some((node) => !node.hidden && node.style.display !== "none")) { matches++; } } let empty = [...list.children].find((node) => node.hasAttribute("data-bex-tag-empty")); if (!empty) { empty = el("li", "Brak pasujących tagów w tej grupie.", { "data-bex-tag-empty": "", class: "text-muted", role: "status" }); list.prepend(empty); } empty.hidden = !phrase || matches > 0; } remove(list, filter) { filter.input.removeEventListener("input", filter.onInput); filter.input.removeEventListener("search", filter.onInput); filter.root.remove(); for (const node of list.querySelectorAll("[data-bex-tag-filtered]")) { node.removeAttribute("data-bex-tag-filtered"); } for (const node of list.querySelectorAll("[data-bex-tag-empty]")) { node.remove(); } } destroy() { for (const [list, filter] of this.filters) { this.remove(list, filter); } this.filters.clear(); } }; // src/import-dialog.js var IMPORT_LABELS = { file: "Wczytaj z pliku", text: "Wczytaj wklejony JSON" }; var ImportDialog = class { constructor(editor) { this.editor = editor; } open() { if (this.editor.busy) { return; } this.editor.model.ensure(); if (!this.dialog) { const { root, body } = createDialog("Import szablonu", "bex-import", () => !this.editor.busy); this.dialog = root; const filePanel = el("section", null, { class: "panel" }); const fileBody = el("div", null, { class: "panel-body" }); this.file = el("input", null, { type: "file", accept: ".json,application/json", hidden: "", "data-bex-import-file": "" }); this.choose = button(IMPORT_LABELS.file, () => this.file.click()); this.choose.className = "btn btn-primary"; this.file.addEventListener("change", () => { const file = this.file.files[0]; this.file.value = ""; if (file) { this.load(() => { if (file.size > MAX_BYTES) { fail("Plik przekracza limit 5 MB."); } return file.text(); }, this.choose); } }); fileBody.append(this.choose, this.file); filePanel.append(el("div", "1. Plik JSON", { class: "panel-heading" }), fileBody); const textPanel = el("section", null, { class: "panel" }); const textBody = el("div", null, { class: "panel-body" }); const field = el("div", null, { class: "form-group" }); this.text = el("textarea", null, { id: "bex-import-json", class: "form-control", rows: "12", spellcheck: "false", placeholder: "Wklej treść szablonu JSON…" }); field.append(el("label", "Treść JSON", { for: "bex-import-json", class: "control-label" }), this.text); this.paste = button(IMPORT_LABELS.text, () => { const text = this.text.value; this.load(() => text, this.paste); }); this.paste.className = "btn btn-primary"; textBody.append(field, this.paste); textPanel.append(el("div", "2. Wklej JSON", { class: "panel-heading" }), textBody); this.feedback = el("div", "", { class: "alert alert-danger bex-import-error", role: "alert", hidden: "" }); body.append(filePanel, textPanel, this.feedback); document.body.append(this.dialog); } this.message(""); if (!this.dialog.open) { this.dialog.showModal(); } this.choose.focus(); } message(text) { this.feedback.textContent = text; this.feedback.hidden = !text; } async load(readText, control) { if (this.editor.busy || !this.dialog.open) { return; } this.editor.lock(true); this.editor.setImportState("loading"); this.editor.status.textContent = ""; this.editor.status.hidden = true; this.message(""); this.setLoading(control, true); try { const text = await readText(); this.editor.model.ensure(); if (new Blob([text]).size > MAX_BYTES) { fail("Treść JSON przekracza limit 5 MB."); } const patch = copyPatch(parseJSON(text), this.editor.model.profile); await this.editor.model.apply(prepareFormImport(patch), { formImport: true }); this.editor.setImportState("success"); this.text.value = ""; this.dialog.close(); } catch (error) { this.editor.setImportState("idle"); this.message(error.message); } finally { this.setLoading(control, false); this.editor.lock(false); } } setLoading(control, loading) { if (loading) { control.replaceChildren(el("span", "", { class: "bex-import-spinner", "aria-hidden": "true" }), document.createTextNode(" Wczytywanie…")); control.setAttribute("aria-busy", "true"); } else { control.textContent = IMPORT_LABELS[control === this.choose ? "file" : "text"]; control.removeAttribute("aria-busy"); } } setBusy(locked) { for (const control of this.dialog?.querySelectorAll("button,input,textarea") || []) { control.disabled = locked; } } destroy() { this.dialog?.remove(); } }; // src/section-size.js var SectionSize = class { constructor(editor) { this.editor = editor; this.original = null; this.root = button("↕", () => this.toggle()); this.root.className = "btn btn-default btn-xs bex-section-resize"; this.root.dataset.bexResize = editor.id; this.root.setAttribute("aria-controls", editor.id); this.updateLabel(); } updateLabel() { const label = this.original ? "Przywróć poprzednią wysokość sekcji" : "Podwój wysokość sekcji"; this.root.title = label; this.root.setAttribute("aria-label", label); this.root.setAttribute("aria-pressed", String(!!this.original)); } toggle() { if (this.root.disabled) { return; } if (this.original) { this.restore(); return; } const delta = this.editor.getBoundingClientRect().height; if (!delta) { return; } const wrapper = this.editor.closest(".highlightTextarea"); const layers = [this.editor, wrapper, ...wrapper?.querySelectorAll(".highlightTextarea-container,.highlightTextarea-highlighter") || []].filter(Boolean); this.original = layers.map((node) => ({ node, height: node.style.getPropertyValue("height"), priority: node.style.getPropertyPriority("height"), maxHeight: node.style.getPropertyValue("max-height"), maxPriority: node.style.getPropertyPriority("max-height"), target: (parseFloat(getComputedStyle(node).height) || node.getBoundingClientRect().height) + delta })); for (const { node, target } of this.original) { node.style.setProperty("max-height", "none", "important"); node.style.setProperty("height", `${target}px`, "important"); } this.updateLabel(); } restore() { for (const { node, height, priority, maxHeight, maxPriority } of this.original || []) { if (height) { node.style.setProperty("height", height, priority); } else { node.style.removeProperty("height"); } if (maxHeight) { node.style.setProperty("max-height", maxHeight, maxPriority); } else { node.style.removeProperty("max-height"); } } this.original = null; this.updateLabel(); } destroy() { this.restore(); this.root.remove(); } }; // src/editor.js var ACTION_LABELS = { import: { idle: "Import szablonu", loading: "Wczytywanie szablonu…", success: "Szablon wczytany" }, export: { idle: "Eksport szablonu", success: "Szablon wyeksportowany" } }; var Editor = class { constructor(form, getActive, profile = PRINTOUT_PROFILE) { this.form = form; this.isCurrent = () => getActive() === this; this.model = new TemplateForm(form, () => this.isCurrent(), (locked) => this.lock(locked), profile); this.cacheUI = new CacheDialog(this); this.importUI = new ImportDialog(this); this.catalogTagsUI = new CatalogTagLists(this); this.tagSearchUI = new TagListSearch(this.model); this.busy = false; this.actionResetTimers = {}; this.sectionTools = /* @__PURE__ */ new Map(); this.onOutsideClick = (event) => { for (const tool of this.sectionTools.values()) { if (!tool.operations.contains(event.target)) { tool.operations.open = false; } } }; this.onEscape = (event) => { if (event.key === "Escape") { for (const tool of this.sectionTools.values()) { if (tool.operations.open) { tool.operations.open = false; tool.summary.focus(); } } } }; document.addEventListener("click", this.onOutsideClick); document.addEventListener("keydown", this.onEscape); this.status = el("span", "", { id: "bex-template-status", role: "status", "aria-live": "polite", hidden: "" }); } attachTemplateActions() { const back = document.getElementById("product-add-button") || [...document.querySelectorAll("a,button")].find((node) => /powrót do listy/i.test(node.textContent.trim())); if (!back) { this.toolbar?.remove(); return; } if (!this.toolbar) { this.toolbar = el("span", null, { id: "bex-template-actions", role: "group", "aria-label": "Import i eksport szablonu" }); this.exportButton = button("Eksport szablonu", () => this.run(() => this.download())); this.importButton = button("Import szablonu", () => this.run(() => { this.importUI.open(); })); this.exportButton.className = "btn btn-lg btn-success bex-export-button"; this.exportButton.dataset.exportState = "idle"; this.exportButton.setAttribute("aria-live", "polite"); this.importButton.className = "btn btn-lg btn-primary bex-import-button"; this.importButton.dataset.importState = "idle"; this.importButton.setAttribute("aria-live", "polite"); const cacheButton = button("Cache", () => this.cacheUI.openCache()); cacheButton.className = "btn btn-lg btn-default"; this.toolbar.append(this.exportButton, this.importButton, cacheButton, this.status); } if (back.nextElementSibling !== this.toolbar) { back.after(this.toolbar); } } setImportState(state) { this.setActionState("import", state); } setActionState(action, state) { clearTimeout(this.actionResetTimers[action]); delete this.actionResetTimers[action]; const control = this[`${action}Button`]; if (!control) { return; } control.dataset[`${action}State`] = state; control.setAttribute("aria-busy", String(state === "loading")); if (state === "idle") { control.textContent = ACTION_LABELS[action].idle; control.title = ""; control.style.minWidth = ""; control.style.height = ""; return; } if (!control.style.minWidth) { const size = control.getBoundingClientRect(); control.style.minWidth = `${size.width}px`; control.style.height = `${size.height}px`; } const label = ACTION_LABELS[action][state]; const icon = el("span", state === "loading" ? "" : "✓", { class: state === "loading" ? "bex-import-spinner" : "bex-import-check", "aria-hidden": "true" }); control.replaceChildren(icon, el("span", label, { class: "bex-sr-only" })); control.title = label; if (state === "success") { this.actionResetTimers[action] = setTimeout(() => { delete this.actionResetTimers[action]; if (this.form.isConnected && this.isCurrent()) { this.setActionState(action, "idle"); } }, 3e3); } } attachSectionTools() { for (const [field, tool] of this.sectionTools) { if (this.model.control(field) !== tool.editor || !tool.root.isConnected) { this.removeSectionTool(tool); this.sectionTools.delete(field); } } for (const [key] of this.model.profile.rows) { const field = `code_${key}`; const editor = this.model.control(field); const heading = editor?.closest(".panel")?.querySelector(".panel-heading"); if (!editor || !heading) { continue; } const title = heading.querySelector(".panel-title") || heading; let help = title.querySelector(".fa-question-circle,.fa-circle-question,.bex-section-help"); if (!help) { help = el("span", "?", { class: "bex-section-help", title: "Sprawdzenie cudzysłowów i zamiana znaków w tej sekcji." }); title.append(help); } let tool = this.sectionTools.get(field); if (!tool) { for (const stale of heading.querySelectorAll("[data-bex-section]")) { if (stale.dataset.bexSection === field) { stale.remove(); } } tool = this.createSectionTool(field, editor); for (const stale of heading.querySelectorAll("[data-bex-resize]")) { if (stale.dataset.bexResize === field) { stale.remove(); } } tool.help = help.classList.contains("bex-section-help") ? help : null; this.sectionTools.set(field, tool); } if (tool.size.root.parentElement !== heading) { heading.prepend(tool.size.root); } if (help) { if (help.nextElementSibling !== tool.root) { help.after(tool.root); } } else if (tool.root.parentElement !== title) { title.append(tool.root); } } } createSectionTool(field, editor) { const root = el("span", null, { class: "bex-section-tools", "data-bex-section": field, role: "group", "aria-label": `Narzędzia ${field}` }); const result = el("span", "", { class: "bex-section-result", role: "status", "aria-live": "polite", hidden: "" }); const operations = el("details", null, { class: "bex-operations" }); const summary = el("summary", "Operacje", { "aria-label": `Operacje w ${field}` }); const menu = el("span", null, { class: "bex-operation-menu", role: "group", "aria-label": `Operacje tekstowe w ${field}` }); operations.append(summary, menu); const tool = { field, editor, root, result, operations, summary, undo: null, size: new SectionSize(editor) }; tool.check = button("Sprawdź cudzysłowy", () => this.run(() => { const report = verifyQuotes(editor.value, this.model.control("type")?.value || "TXT"); if (report.balanced) { this.sectionMessage(tool, report.count ? `Cudzysłowy domknięte (${report.count}).` : 'Brak cudzysłowów ".'); } else { this.sectionMessage(tool, `Niedomknięty cudzysłów " — wiersz ${report.line}, kolumna ${report.column}.`, true); editor.focus(); editor.setSelectionRange(report.index, report.index + 1); } })); tool.check.title = 'Sprawdza domknięcie prostych cudzysłowów podwójnych (") w tej sekcji.'; for (const [operation, label] of [ ["commaToSemicolon", "Wszystkie , → ;"], ["semicolonToComma", "Wszystkie ; → ,"], ["removeLeftBracket", "Usuń wszystkie ["], ["removeRightBracket", "Usuń wszystkie ]"], ["removeBrackets", "Usuń wszystkie [ i ]"] ]) { const action = button(label, () => { operations.open = false; this.run(() => { const before = editor.value; const converted = applySectionOperation(before, operation); if (converted.count) { this.model.setValue(editor, converted.text); tool.undo = { before, after: editor.value }; tool.undoButton.hidden = false; } this.sectionMessage(tool, `${operation.startsWith("remove") ? "Usunięto" : "Zamieniono"} ${converted.count} znaków w tej sekcji.`); summary.focus(); }); }); action.dataset.bexOperation = operation; action.title = "Operacja dotyczy całej sekcji, również treści w cudzysłowach i tagów."; menu.append(action); } summary.addEventListener("click", (event) => { if (this.busy) { event.preventDefault(); } }); operations.addEventListener("toggle", () => { if (operations.open) { if (this.busy) { operations.open = false; } for (const other of this.sectionTools.values()) { if (other !== tool) { other.operations.open = false; } } } }); tool.undoButton = button("Cofnij operację", () => this.run(() => { if (!tool.undo || editor.value !== tool.undo.after) { fail("Treść sekcji została zmieniona po wykonaniu operacji."); } const before = tool.undo.before; this.model.setValue(editor, before); tool.undo = null; tool.undoButton.hidden = true; this.sectionMessage(tool, "Cofnięto operację."); })); tool.undoButton.hidden = true; tool.onEdit = () => { result.hidden = true; if (tool.undo && editor.value !== tool.undo.after) { tool.undo = null; tool.undoButton.hidden = true; } }; editor.addEventListener("input", tool.onEdit); editor.addEventListener("change", tool.onEdit); root.append(tool.check, operations, tool.undoButton, result); this.setSectionToolBusy(tool, this.busy); return tool; } setSectionToolBusy(tool, locked) { tool.size.root.disabled = locked; for (const control of tool.root.querySelectorAll("button")) { control.disabled = locked; } tool.summary.setAttribute("aria-disabled", String(locked)); tool.summary.tabIndex = locked ? -1 : 0; if (locked) { tool.operations.open = false; } } sectionMessage(tool, text, error = false) { tool.result.textContent = text; tool.result.dataset.error = String(error); tool.result.hidden = false; } removeSectionTool(tool) { tool.size.destroy(); tool.editor.removeEventListener("input", tool.onEdit); tool.editor.removeEventListener("change", tool.onEdit); tool.root.remove(); tool.help?.remove(); } message(text, error = false) { this.status.textContent = text; this.status.dataset.error = String(error); this.status.hidden = false; } async run(action) { if (this.busy) { return; } try { this.model.ensure(); await action(); } catch (error) { this.message(error.message, true); } } download() { this.status.hidden = true; this.status.textContent = ""; this.setActionState("export", "idle"); const patch = this.model.template(); const name = (this.model.control("name")?.value || "szablon").slice(0, 80); downloadJSON(patch, `base-${name}.json`); this.setActionState("export", "success"); } lock(locked) { this.busy = locked; this.catalogTagsUI.setBusy(locked); this.importUI.setBusy(locked); for (const root of [this.toolbar, this.cacheUI.cacheDialog].filter(Boolean)) { for (const n of root.querySelectorAll("button")) { n.disabled = locked || n.dataset.bexIncompatible === "true"; } } for (const tool of this.sectionTools.values()) { this.setSectionToolBusy(tool, locked); } } destroy() { document.removeEventListener("click", this.onOutsideClick); document.removeEventListener("keydown", this.onEscape); Object.values(this.actionResetTimers).forEach(clearTimeout); this.actionResetTimers = {}; this.toolbar?.remove(); this.cacheUI.destroy(); this.importUI.destroy(); this.catalogTagsUI.destroy(); this.tagSearchUI.destroy(); for (const tool of this.sectionTools.values()) { this.removeSectionTool(tool); } this.sectionTools.clear(); } }; // src/api.js var TemplateAPI = class { constructor(getEditor) { this.getEditor = getEditor; } editor() { const editor = this.getEditor(); if (!editor) { fail("Brak aktywnego formularza szablonu."); } editor.model.ensure(); if (editor.busy || editor.model.applying) { fail("Trwa operacja na formularzu. Poczekaj na jej zakończenie."); } return editor; } schema() { const model = this.editor().model; return { apiVersion: 1, templateFormat: "base-export-template", templateVersion: 1, generator: model.profile.id, generatorLabel: model.profile.label, sections: SectionCatalog.list(model.profile).map((section) => ({ ...section, enabled: section.key === "root" || model.control(`sections_${section.key}`)?.checked === true, available: !!model.control(section.field), callers: [...model.profile.callers[section.key]], tags: model.sectionTags(section.key) })), fields: model.profile.fields.map((key) => { const control = model.control(key); return { key, label: model.profile.labels[key] || key, section: model.fieldSection(key) || null, format: FIELD_FORMATS[key] || null, available: !!control, disabled: !!control?.disabled, options: control?.tagName === "SELECT" ? [...control.options].map((option) => ({ value: option.value, label: option.text, disabled: option.disabled })) : null }; }), collections: Object.fromEntries(Object.entries(model.profile.collections).map(([key, config]) => [key, { fields: [...config.props], maxRows: 500, ...key === "modifiers" ? { observedTypes: [...new Map((model.control(config.table) ? model.rows(key) : []).flatMap((row) => [...model.rowControl(row, "type")?.options || []].map((option) => [option.value, { value: option.value, label: option.text, disabled: option.disabled }]))).values()] } : {} }])) }; } preview(patch) { const model = this.editor().model; const prepared = prepareFormImport(copyPatch(patch, model.profile)); const before = model.snapshot(); model.preflight(prepared, before, { formImport: true }); const warnings = []; try { checkDependencies(before, prepared); } catch (error) { warnings.push(error.message); } return { patch: prepared, target: mergeState(before, prepared), warnings }; } async apply(patch) { const model = this.editor().model; return model.apply(prepareFormImport(copyPatch(patch, model.profile)), { formImport: true }); } sectionPatch(reference) { const model = this.editor().model; const sections = SectionCatalog.activation(reference, model.profile); const before = model.snapshot(); const fields = Object.fromEntries(Object.keys(sections).flatMap((key) => { const field = `code_${key}`; return has(before.fields, field) ? [[field, before.fields[field]]] : []; })); return model.patch({ sections, ...Object.keys(fields).length ? { fields } : {} }); } async enableSection(reference) { const section = SectionCatalog.resolve(reference, this.editor().model.profile); if (section.key === "root") { return this.editor().model.snapshot(); } return this.apply(this.sectionPatch(reference)); } async setSection(reference, code) { const section = SectionCatalog.resolve(reference, this.editor().model.profile); const patch = this.sectionPatch(reference); patch.fields = { ...patch.fields, [section.field]: code }; return this.apply(patch); } async waitForSection(reference) { const model = this.editor().model; const section = SectionCatalog.resolve(reference, model.profile); await model.waitForSectionEditor(reference); return { key: section.key, tag: section.tag, field: section.field, ready: true }; } readSection(reference) { const node = this.editor().model.readySectionEditor(reference); if (!node) { fail("Edytor sekcji nie jest gotowy. Użyj sections.waitReady()."); } return node.value; } async fillSection(reference, code) { const model = this.editor().model; const section = SectionCatalog.resolve(reference, model.profile); const patch = model.patch({ fields: { [section.field]: code } }); return model.apply(patch, { formImport: true, requireActiveSections: true }); } async disableSection(reference) { const model = this.editor().model; return this.apply(model.patch({ sections: SectionCatalog.deactivation(reference, model.profile) })); } async setModifiersForTag(tag, rules) { if (typeof tag !== "string" || !/^\[[^[\]\r\n]+\]$/.test(tag) || !Array.isArray(rules)) { fail("Wymagany tag w nawiasach kwadratowych i lista reguł."); } const model = this.editor().model; const modifiers = model.cleanRows("modifiers", model.snapshot().modifiers); const replacement = rules.map((rule) => { if (!object(rule) || has(rule, "tag") && rule.tag !== tag) { fail("Reguła modyfikatora wskazuje inny tag lub ma nieprawidłowy format."); } return { ...rule, tag }; }); const first = modifiers.findIndex((rule) => rule.tag === tag); const remaining = modifiers.filter((rule) => rule.tag !== tag); remaining.splice(first < 0 ? remaining.length : first, 0, ...replacement); return this.apply(model.patch({ modifiers: remaining })); } public() { return Object.freeze({ apiVersion: 1, schema: () => this.schema(), snapshot: () => this.editor().model.snapshot(), exportTemplate: () => this.editor().model.template(), validate: (patch) => copyPatch(patch), preview: (patch) => this.preview(patch), apply: (patch) => this.apply(patch), sections: Object.freeze({ list: () => this.schema().sections, enable: (tag) => this.enableSection(tag), waitReady: (tag) => this.waitForSection(tag), read: (tag) => this.readSection(tag), fill: (tag, code) => this.fillSection(tag, code), set: (tag, code) => this.setSection(tag, code), disable: (tag) => this.disableSection(tag) }), modifiers: Object.freeze({ list: () => { const model = this.editor().model; return model.cleanRows("modifiers", model.snapshot().modifiers); }, replace: (modifiers) => this.apply(this.editor().model.patch({ modifiers })), setForTag: (tag, rules) => this.setModifiersForTag(tag, rules) }), settingsTags: Object.freeze({ list: () => { const model = this.editor().model; return model.cleanRows("settingsTags", model.snapshot().settingsTags); }, replace: (settingsTags) => this.apply(this.editor().model.patch({ settingsTags })) }) }); } }; // src/styles.js function installStyles() { const style = el("style", ` #bex-template-actions {display:inline-flex;gap:8px;flex-wrap:wrap;vertical-align:middle;margin-left:8px} #bex-template-actions [hidden] {display:none!important} .bex-tag-search {padding:8px 10px} .bex-section-resize {float:right;margin-left:8px;font-size:18px;line-height:1;padding:3px 7px;cursor:pointer} .bex-tag-search .form-control {width:100%} [data-bex-tag-filtered] {display:none!important} [data-bex-tag-empty][hidden] {display:none!important} .bex-catalog-tags > .list_tags {list-style:none;padding:0} .bex-catalog-tag {border:0;background:none;padding:0;color:inherit;font:inherit;line-height:inherit;text-align:left;cursor:pointer} .bex-catalog-tag:disabled {opacity:.5;cursor:default} #bex-template-status {flex-basis:100%;white-space:pre-wrap;overflow-wrap:anywhere;text-align:left;font-size:13px} #bex-template-status[data-error=true] {color:#b42318} .bex-import-spinner {display:inline-block;width:16px;height:16px;vertical-align:middle;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;animation:bex-import-spin .75s linear infinite} .bex-import-check {display:inline-block;font-size:20px;line-height:1;vertical-align:middle} #bex-template-actions .bex-import-button[data-import-state=success] {background:#238636;border-color:#238636} .bex-sr-only {position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0} @keyframes bex-import-spin {to {transform:rotate(360deg)}} @media(prefers-reduced-motion:reduce) {.bex-import-spinner {animation:none}} .bex-section-tools {--bex-control-bg:#fff;--bex-control-text:#183b59;--bex-control-border:#a8b8c7;--bex-control-success:#17603b;--bex-control-error:#b42318;color-scheme:light;display:inline-flex;gap:6px;align-items:center;flex-wrap:wrap;margin-left:10px;vertical-align:middle;font-size:12px;font-weight:normal;text-transform:none} html[data-theme=theme-dark] .bex-section-tools,html[data-theme=dark] .bex-section-tools {--bex-control-bg:#25313d;--bex-control-text:#e6edf3;--bex-control-border:#63788b;--bex-control-success:#7ee2a8;--bex-control-error:#ff9c9c;color-scheme:dark} @media(prefers-color-scheme:dark) {html:not([data-theme]) .bex-section-tools {--bex-control-bg:#25313d;--bex-control-text:#e6edf3;--bex-control-border:#63788b;--bex-control-success:#7ee2a8;--bex-control-error:#ff9c9c;color-scheme:dark}} .bex-section-tools [hidden] {display:none!important} .bex-section-tools button,.bex-section-tools summary {font:inherit;line-height:1.4;padding:3px 7px;border:1px solid var(--bex-control-border);border-radius:4px;background:var(--bex-control-bg);color:var(--bex-control-text);max-width:100%;text-transform:none} .bex-operations {display:inline-block;position:relative} .bex-operations summary {list-style:none;cursor:pointer;user-select:none} .bex-operations summary::-webkit-details-marker {display:none} .bex-operations summary::after {content:' ▾'} .bex-operation-menu {position:absolute;inset-inline-start:0;top:calc(100% + 4px);z-index:1000;display:grid;gap:3px;min-width:210px;max-width:calc(100vw - 40px);padding:5px;border:1px solid var(--bex-control-border);border-radius:5px;background:var(--bex-control-bg);color:var(--bex-control-text);box-shadow:0 5px 18px #0003} .bex-section-tools .bex-operation-menu button {text-align:left;width:100%;border-color:transparent;white-space:normal} .bex-operation-menu button:hover {border-color:var(--bex-control-border);text-decoration:underline} .bex-operations summary[aria-disabled=true] {opacity:.5;cursor:default} .bex-section-tools button {cursor:pointer} .bex-section-tools :disabled {opacity:.5;cursor:default} .bex-section-tools :focus-visible {outline:2px solid #2379bd;outline-offset:2px} .bex-section-result {white-space:normal;overflow-wrap:anywhere;background:var(--bex-control-bg);color:var(--bex-control-success);border-radius:3px;padding:2px 6px} .bex-section-result[data-error=true] {color:var(--bex-control-error)} .bex-panel-dialog {width:1000px;max-width:calc(100% - 32px);max-height:calc(100vh - 48px);padding:0;border:0;background:transparent;color:inherit;font:inherit;overflow:visible;color-scheme:light} html[data-theme=theme-dark] .bex-panel-dialog,html[data-theme=dark] .bex-panel-dialog {color-scheme:dark} @media(prefers-color-scheme:dark) {html:not([data-theme]) .bex-panel-dialog {color-scheme:dark}} .bex-import-dialog {width:720px} #bex-import-json {resize:vertical;min-height:160px} .bex-import-error {white-space:pre-wrap;overflow-wrap:anywhere} .bex-panel-dialog::backdrop {background:rgba(0,0,0,.5)} .bex-panel-dialog .modal-content {display:flex;flex-direction:column;max-height:calc(100vh - 48px);margin:0} .bex-dialog-header,.bex-dialog-footer {flex:none} .bex-dialog-body {overflow:auto;min-height:0} .bex-panel-dialog [hidden] {display:none!important} .bex-cache-transfer:empty {display:none} .bex-cache-transfer .form-control {margin-bottom:12px} .bex-cache-transfer .btn {margin-right:6px;margin-bottom:4px} .bex-cache-backup-list {max-height:180px;overflow:auto;overflow-wrap:anywhere} .bex-cache-file-actions {display:flex;flex-direction:column;align-items:stretch;gap:8px} .bex-cache-actions {display:flex;gap:6px;align-items:center;flex-wrap:wrap} .bex-cache-list {overflow-x:auto} .bex-cache-list .table {width:100%;min-width:680px;margin-bottom:0} .bex-cache-row td {vertical-align:middle} .bex-cache-row td:first-child {min-width:140px;max-width:280px;overflow-wrap:anywhere} .bex-cache-row td:last-child {min-width:320px} .bex-cache-feedback {white-space:pre-wrap;overflow-wrap:anywhere} .bex-cache-footer {display:flex;align-items:center;justify-content:space-between;gap:12px} @media(max-width:767px) {.bex-panel-dialog {max-width:calc(100% - 16px)}.bex-cache-footer {align-items:flex-end}.bex-cache-footer .text-muted {text-align:left}} .bex-section-help {display:inline-flex;align-items:center;justify-content:center;width:14px;height:14px;margin-left:5px;border:1px solid currentColor;border-radius:50%;font-size:11px;cursor:help} `, { id: "bex-style" }); document.head.append(style); } // src/main.js function start() { if (window.top !== window.self || document.getElementById("bex-style")) { return; } installStyles(); let active = null; const api = new TemplateAPI(() => active).public(); Object.defineProperty(window, "BaseExportTemplate", { value: api, configurable: true }); let scheduled = false; function mount() { scheduled = false; const form = document.querySelector("#form_printout_manager form"); const profile = form && profileForForm(form); if (active && (active.form !== form || active.model.profile !== profile)) { active.destroy(); active = null; } if (form && !active) { active = new Editor(form, () => active, profile); } active?.attachTemplateActions(); active?.attachSectionTools(); active?.catalogTagsUI.mount(); active?.tagSearchUI.mount(); } new MutationObserver(() => { if (!scheduled) { scheduled = true; setTimeout(mount, 80); } }).observe(document.body, { childList: true, subtree: true }); mount(); } start(); })();