feat: v3.0 - canvas editor, JSON-only, no Excel, new UI
Some checks failed
Build & Push Docker / build (push) Has been cancelled

- Remove all Excel code (import, export, template, pandas, openpyxl)
- New canvas-based schedule editor with drag & drop (interact.js)
- Modern 3-panel UI: sidebar, canvas, documentation tab
- New data model: Block with id/date/start/end, ProgramType with id/name/color
- Clean API: GET /api/health, POST /api/validate, GET /api/sample, POST /api/generate-pdf
- Rewritten PDF generator using ScenarioDocument directly (no DataFrame)
- Professional PDF output: dark header, colored blocks, merged cells, legend, footer
- Sample JSON: "Zimní výjezd oddílu" with 11 blocks, 3 program types
- 30 tests passing (API, core models, PDF generation)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-20 17:02:51 +01:00
parent e2bdadd0ce
commit 25fd578543
27 changed files with 2004 additions and 3016 deletions

View File

@@ -1,258 +1,304 @@
/**
* Main application logic for Scenar Creator SPA.
* Main application logic for Scenar Creator v3.
* State management, UI wiring, modal handling.
*/
window.currentDocument = null;
let typeCounter = 1;
let scheduleCounter = 1;
const App = {
state: {
event: { title: '', subtitle: '', date: '', location: '' },
program_types: [],
blocks: []
},
/* --- Tab switching --- */
function switchTab(event, tabId) {
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
event.target.classList.add('active');
document.getElementById(tabId).classList.add('active');
}
init() {
this.bindEvents();
this.newScenario();
},
/* --- Status messages --- */
function showStatus(message, type) {
const el = document.getElementById('statusMessage');
el.textContent = message;
el.className = 'status-message ' + type;
el.style.display = 'block';
setTimeout(() => { el.style.display = 'none'; }, 5000);
}
// --- State ---
/* --- Type management --- */
function addTypeRow() {
const container = document.getElementById('typesContainer');
const idx = typeCounter++;
const div = document.createElement('div');
div.className = 'type-row';
div.setAttribute('data-index', idx);
div.innerHTML = `
<input type="text" name="type_name_${idx}" placeholder="Kód typu" class="type-code">
<input type="text" name="type_desc_${idx}" placeholder="Popis">
<input type="color" name="type_color_${idx}" value="#0070C0">
<button type="button" class="btn btn-danger btn-sm" onclick="removeTypeRow(${idx})">X</button>
`;
container.appendChild(div);
updateTypeDatalist();
}
getDocument() {
this.syncEventFromUI();
return {
version: '1.0',
event: { ...this.state.event },
program_types: this.state.program_types.map(pt => ({ ...pt })),
blocks: this.state.blocks.map(b => ({ ...b }))
};
},
function removeTypeRow(idx) {
const row = document.querySelector(`.type-row[data-index="${idx}"]`);
if (row) row.remove();
updateTypeDatalist();
}
function updateTypeDatalist() {
const datalist = document.getElementById('availableTypes');
datalist.innerHTML = '';
document.querySelectorAll('#typesContainer .type-row').forEach(row => {
const nameInput = row.querySelector('input[name^="type_name_"]');
if (nameInput && nameInput.value.trim()) {
const opt = document.createElement('option');
opt.value = nameInput.value.trim();
datalist.appendChild(opt);
}
});
}
// Update datalist on type name changes
document.getElementById('typesContainer').addEventListener('input', function (e) {
if (e.target.name && e.target.name.startsWith('type_name_')) {
updateTypeDatalist();
}
});
/* --- Schedule management --- */
function addScheduleRow() {
const tbody = document.getElementById('scheduleBody');
const idx = scheduleCounter++;
const tr = document.createElement('tr');
tr.setAttribute('data-index', idx);
tr.innerHTML = `
<td><input type="date" name="datum_${idx}" required></td>
<td><input type="time" name="zacatek_${idx}" required></td>
<td><input type="time" name="konec_${idx}" required></td>
<td><input type="text" name="program_${idx}" required placeholder="Název bloku"></td>
<td><input type="text" name="typ_${idx}" list="availableTypes" required placeholder="Typ"></td>
<td><input type="text" name="garant_${idx}" placeholder="Garant"></td>
<td><input type="text" name="poznamka_${idx}" placeholder="Poznámka"></td>
<td><button type="button" class="btn btn-danger btn-sm" onclick="removeScheduleRow(${idx})">X</button></td>
`;
tbody.appendChild(tr);
}
function removeScheduleRow(idx) {
const row = document.querySelector(`#scheduleBody tr[data-index="${idx}"]`);
if (row) row.remove();
}
/* --- Build ScenarioDocument from builder form --- */
function buildDocumentFromForm() {
const title = document.getElementById('builderTitle').value.trim();
const detail = document.getElementById('builderDetail').value.trim();
if (!title || !detail) {
throw new Error('Název akce a detail jsou povinné');
}
// Collect types
const programTypes = [];
document.querySelectorAll('#typesContainer .type-row').forEach(row => {
const code = row.querySelector('input[name^="type_name_"]').value.trim();
const desc = row.querySelector('input[name^="type_desc_"]').value.trim();
const color = row.querySelector('input[name^="type_color_"]').value;
if (code) {
programTypes.push({ code, description: desc, color });
}
});
// Collect blocks
const blocks = [];
document.querySelectorAll('#scheduleBody tr').forEach(tr => {
const inputs = tr.querySelectorAll('input');
const datum = inputs[0].value;
const zacatek = inputs[1].value;
const konec = inputs[2].value;
const program = inputs[3].value.trim();
const typ = inputs[4].value.trim();
const garant = inputs[5].value.trim() || null;
const poznamka = inputs[6].value.trim() || null;
if (datum && zacatek && konec && program && typ) {
blocks.push({ datum, zacatek, konec, program, typ, garant, poznamka });
}
});
if (blocks.length === 0) {
throw new Error('Přidejte alespoň jeden blok');
}
return {
version: "1.0",
event: { title, detail },
program_types: programTypes,
blocks
};
}
/* --- Handle builder form submit (Excel) --- */
async function handleBuild(event) {
event.preventDefault();
try {
const doc = buildDocumentFromForm();
const blob = await API.postBlob('/api/generate-excel', doc);
API.downloadBlob(blob, 'scenar_timetable.xlsx');
showStatus('Excel vygenerován', 'success');
} catch (err) {
showStatus('Chyba: ' + err.message, 'error');
}
return false;
}
/* --- Handle builder PDF --- */
async function handleBuildPdf() {
try {
const doc = buildDocumentFromForm();
const blob = await API.postBlob('/api/generate-pdf', doc);
API.downloadBlob(blob, 'scenar_timetable.pdf');
showStatus('PDF vygenerován', 'success');
} catch (err) {
showStatus('Chyba: ' + err.message, 'error');
}
}
/* --- Handle Excel import --- */
async function handleImport(event) {
event.preventDefault();
const form = document.getElementById('importForm');
const formData = new FormData(form);
try {
const result = await API.postFormData('/api/import-excel', formData);
if (result.success && result.document) {
window.currentDocument = result.document;
showImportedDocument(result.document);
if (result.warnings && result.warnings.length > 0) {
showStatus('Import OK, warnings: ' + result.warnings.join('; '), 'success');
} else {
showStatus('Excel importován', 'success');
}
} else {
showStatus('Import failed: ' + (result.errors || []).join('; '), 'error');
}
} catch (err) {
showStatus('Chyba importu: ' + err.message, 'error');
}
return false;
}
/* --- Show imported document in editor --- */
function showImportedDocument(doc) {
const area = document.getElementById('editorArea');
area.style.display = 'block';
// Info
document.getElementById('importedInfo').innerHTML =
`<strong>${doc.event.title}</strong> — ${doc.event.detail}`;
// Types
const typesHtml = doc.program_types.map((pt, i) => `
<div class="imported-type-row">
<input type="text" value="${pt.code}" data-field="code" data-idx="${i}">
<input type="text" value="${pt.description}" data-field="description" data-idx="${i}">
<input type="color" value="${pt.color}" data-field="color" data-idx="${i}">
</div>
`).join('');
document.getElementById('importedTypesContainer').innerHTML = typesHtml;
// Blocks
const blocksHtml = doc.blocks.map(b =>
`<div class="block-item">${b.datum} ${b.zacatek}${b.konec} | <strong>${b.program}</strong> [${b.typ}] ${b.garant || ''}</div>`
).join('');
document.getElementById('importedBlocksContainer').innerHTML = blocksHtml;
}
/* --- Get current document (with any edits from import editor) --- */
function getCurrentDocument() {
if (!window.currentDocument) {
throw new Error('No document loaded');
}
// Update types from editor
const typeRows = document.querySelectorAll('#importedTypesContainer .imported-type-row');
if (typeRows.length > 0) {
window.currentDocument.program_types = Array.from(typeRows).map(row => ({
code: row.querySelector('[data-field="code"]').value.trim(),
description: row.querySelector('[data-field="description"]').value.trim(),
color: row.querySelector('[data-field="color"]').value,
loadDocument(doc) {
this.state.event = { ...doc.event };
this.state.program_types = (doc.program_types || []).map(pt => ({ ...pt }));
this.state.blocks = (doc.blocks || []).map(b => ({
...b,
id: b.id || this.uid()
}));
}
return window.currentDocument;
}
this.syncEventToUI();
this.renderTypes();
this.renderCanvas();
},
/* --- Generate Excel from imported data --- */
async function generateExcelFromImport() {
try {
const doc = getCurrentDocument();
const blob = await API.postBlob('/api/generate-excel', doc);
API.downloadBlob(blob, 'scenar_timetable.xlsx');
showStatus('Excel vygenerován', 'success');
} catch (err) {
showStatus('Chyba: ' + err.message, 'error');
}
}
newScenario() {
const today = new Date().toISOString().split('T')[0];
this.state = {
event: { title: 'Nová akce', subtitle: '', date: today, location: '' },
program_types: [
{ id: 'main', name: 'Hlavní program', color: '#3B82F6' },
{ id: 'rest', name: 'Odpočinek', color: '#22C55E' }
],
blocks: []
};
this.syncEventToUI();
this.renderTypes();
this.renderCanvas();
},
/* --- Generate PDF from imported data --- */
async function generatePdfFromImport() {
try {
const doc = getCurrentDocument();
const blob = await API.postBlob('/api/generate-pdf', doc);
API.downloadBlob(blob, 'scenar_timetable.pdf');
showStatus('PDF vygenerován', 'success');
} catch (err) {
showStatus('Chyba: ' + err.message, 'error');
// --- Sync sidebar <-> state ---
syncEventFromUI() {
this.state.event.title = document.getElementById('eventTitle').value.trim() || 'Nová akce';
this.state.event.subtitle = document.getElementById('eventSubtitle').value.trim() || null;
this.state.event.date = document.getElementById('eventDate').value || null;
this.state.event.location = document.getElementById('eventLocation').value.trim() || null;
},
syncEventToUI() {
document.getElementById('eventTitle').value = this.state.event.title || '';
document.getElementById('eventSubtitle').value = this.state.event.subtitle || '';
document.getElementById('eventDate').value = this.state.event.date || '';
document.getElementById('eventLocation').value = this.state.event.location || '';
},
// --- Program types ---
renderTypes() {
const container = document.getElementById('programTypesContainer');
container.innerHTML = '';
this.state.program_types.forEach((pt, i) => {
const row = document.createElement('div');
row.className = 'type-row';
row.innerHTML = `
<input type="color" value="${pt.color}" data-idx="${i}">
<input type="text" value="${pt.name}" placeholder="Název typu" data-idx="${i}">
<button class="type-remove" data-idx="${i}">&times;</button>
`;
// Color change
row.querySelector('input[type="color"]').addEventListener('change', (e) => {
this.state.program_types[i].color = e.target.value;
this.renderCanvas();
});
// Name change
row.querySelector('input[type="text"]').addEventListener('change', (e) => {
this.state.program_types[i].name = e.target.value.trim();
});
// Remove
row.querySelector('.type-remove').addEventListener('click', () => {
this.state.program_types.splice(i, 1);
this.renderTypes();
this.renderCanvas();
});
container.appendChild(row);
});
},
addType() {
const id = 'type_' + this.uid().substring(0, 6);
this.state.program_types.push({
id,
name: 'Nový typ',
color: '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0')
});
this.renderTypes();
},
// --- Blocks ---
createBlock(date, start, end) {
const typeId = this.state.program_types.length > 0 ? this.state.program_types[0].id : 'main';
const block = {
id: this.uid(),
date: date || this.state.event.date || new Date().toISOString().split('T')[0],
start: start || '09:00',
end: end || '10:00',
title: 'Nový blok',
type_id: typeId,
responsible: null,
notes: null
};
this.state.blocks.push(block);
this.renderCanvas();
this.editBlock(block.id);
},
updateBlockTime(blockId, start, end) {
const block = this.state.blocks.find(b => b.id === blockId);
if (block) {
block.start = start;
block.end = end;
this.renderCanvas();
}
},
deleteBlock(blockId) {
this.state.blocks = this.state.blocks.filter(b => b.id !== blockId);
this.renderCanvas();
},
// --- Canvas rendering ---
renderCanvas() {
const dates = this.getUniqueDates();
Canvas.renderTimeAxis();
Canvas.renderDayColumns(dates);
Canvas.renderBlocks(this.state.blocks, this.state.program_types);
},
getUniqueDates() {
const dateSet = new Set();
this.state.blocks.forEach(b => dateSet.add(b.date));
if (this.state.event.date) dateSet.add(this.state.event.date);
const dates = Array.from(dateSet).sort();
return dates.length > 0 ? dates : [new Date().toISOString().split('T')[0]];
},
// --- Modal ---
editBlock(blockId) {
const block = this.state.blocks.find(b => b.id === blockId);
if (!block) return;
document.getElementById('modalBlockId').value = block.id;
document.getElementById('modalBlockTitle').value = block.title;
document.getElementById('modalBlockStart').value = block.start;
document.getElementById('modalBlockEnd').value = block.end;
document.getElementById('modalBlockResponsible').value = block.responsible || '';
document.getElementById('modalBlockNotes').value = block.notes || '';
// Populate type select
const select = document.getElementById('modalBlockType');
select.innerHTML = '';
this.state.program_types.forEach(pt => {
const opt = document.createElement('option');
opt.value = pt.id;
opt.textContent = pt.name;
if (pt.id === block.type_id) opt.selected = true;
select.appendChild(opt);
});
document.getElementById('blockModal').classList.remove('hidden');
},
saveBlockFromModal() {
const blockId = document.getElementById('modalBlockId').value;
const block = this.state.blocks.find(b => b.id === blockId);
if (!block) return;
block.title = document.getElementById('modalBlockTitle').value.trim() || 'Blok';
block.type_id = document.getElementById('modalBlockType').value;
block.start = document.getElementById('modalBlockStart').value;
block.end = document.getElementById('modalBlockEnd').value;
block.responsible = document.getElementById('modalBlockResponsible').value.trim() || null;
block.notes = document.getElementById('modalBlockNotes').value.trim() || null;
this.closeModal();
this.renderCanvas();
},
closeModal() {
document.getElementById('blockModal').classList.add('hidden');
},
// --- Toast ---
toast(message, type) {
const el = document.getElementById('toast');
el.textContent = message;
el.className = 'toast ' + (type || 'info');
setTimeout(() => el.classList.add('hidden'), 3000);
},
// --- PDF ---
async generatePdf() {
try {
const doc = this.getDocument();
if (doc.blocks.length === 0) {
this.toast('Přidejte alespoň jeden blok', 'error');
return;
}
const blob = await API.postBlob('/api/generate-pdf', doc);
API.downloadBlob(blob, 'scenar_timetable.pdf');
this.toast('PDF vygenerován', 'success');
} catch (err) {
this.toast('Chyba: ' + err.message, 'error');
}
},
// --- Utility ---
uid() {
return 'xxxx-xxxx-xxxx'.replace(/x/g, () =>
Math.floor(Math.random() * 16).toString(16)
);
},
// --- Event binding ---
bindEvents() {
// Tabs
document.querySelectorAll('.tab').forEach(tab => {
tab.addEventListener('click', () => {
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(c => c.classList.add('hidden'));
tab.classList.add('active');
document.getElementById('tab-' + tab.dataset.tab).classList.remove('hidden');
});
});
// Header buttons
document.getElementById('newScenarioBtn').addEventListener('click', () => this.newScenario());
document.getElementById('exportJsonBtn').addEventListener('click', () => exportJson());
document.getElementById('generatePdfBtn').addEventListener('click', () => this.generatePdf());
// Import JSON
document.getElementById('importJsonInput').addEventListener('change', (e) => {
if (e.target.files[0]) importJson(e.target.files[0]);
e.target.value = '';
});
// Sidebar
document.getElementById('addTypeBtn').addEventListener('click', () => this.addType());
document.getElementById('addBlockBtn').addEventListener('click', () => this.createBlock());
// Modal
document.getElementById('modalSaveBtn').addEventListener('click', () => this.saveBlockFromModal());
document.getElementById('modalClose').addEventListener('click', () => this.closeModal());
document.getElementById('modalDeleteBtn').addEventListener('click', () => {
const blockId = document.getElementById('modalBlockId').value;
this.closeModal();
this.deleteBlock(blockId);
});
// Close modal on overlay click
document.getElementById('blockModal').addEventListener('click', (e) => {
if (e.target.classList.contains('modal-overlay')) this.closeModal();
});
// Drag & drop JSON on canvas
const canvasWrapper = document.querySelector('.canvas-wrapper');
if (canvasWrapper) {
canvasWrapper.addEventListener('dragover', (e) => e.preventDefault());
canvasWrapper.addEventListener('drop', (e) => {
e.preventDefault();
const file = e.dataTransfer.files[0];
if (file && file.name.endsWith('.json')) {
importJson(file);
}
});
}
}
}
};
// Boot
document.addEventListener('DOMContentLoaded', () => App.init());