ibelsa-Bankett-Function-druck.js
Copy
// ==UserScript==
// @name ibelsa Function Sheet drucken
// @namespace http://tampermonkey.net/
// @version 4.6
// @description Drucken-Buttons für das Function Sheet: im Drawer, in der Sidebar und als Icon an jedem Event in der Bankett-Übersicht
// @author Du
// @match https://rooms.ibelsa.com/*
// @grant unsafeWindow
// @noframes
// @run-at document-idle
// ==/UserScript==
(function () {
'use strict';
// ---------- Konfiguration ----------
const IFRAME_SELECTOR = 'iframe[title="Function Sheet"]';
const DOWNLOAD_BUTTON_TEXT = 'Download';
const SIDEBAR_ITEM_SELECTOR = 'li#content-tab-fs';
const EVENT_SELECTOR = 'div.k-event';
// Schließen-Button (X) oben rechts im Event-Fenster.
// Icon-Klasse variiert (fa-xmark-large, fa-xmark, k-i-close, ...),
// daher wird über mehrere Muster gesucht.
const CLOSE_ICON_SELECTOR = [
'.k-appbar-section [class*="xmark"]',
'.k-appbar-section [class*="fa-times"]',
'.k-appbar-section .k-i-close',
'.k-appbar-section .k-i-x',
'.k-appbar-section .k-i-x-circle',
].join(', ');
// Fallback, falls kein Icon passt: Icon-Button in der rechts ausgerichteten Appbar-Sektion
const CLOSE_BUTTON_FALLBACK_SELECTOR = '.k-appbar-section[style*="right"] button.k-icon-button';
// true = fertige PDF vom Server holen und drucken (schnell, wie ibelsa-PDF)
// false = HTML-Ansicht in neuem Tab öffnen und mit CSS-Fix drucken
const USE_PDF = true;
// Preise beim Druck immer ausblenden
const HIDE_PRICES = true;
// Nach dem Druck zurück: Schließen-Button (X) im Event-Fenster drücken
// – NICHT den Bankett-Tab anklicken
const AUTO_RETURN = true;
// Wartezeiten (ms)
const WAIT_TIMEOUT = 15000;
const SETTLE_DELAY = 500; // kurze Pause nach Navigationen, bis die SPA "ruhig" ist
// -----------------------------------
// ================= Helfer =================
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// Wartet, bis predicate() einen truthy Wert liefert, und gibt diesen zurück
function waitFor(predicate, timeoutMs, label) {
return new Promise((resolve, reject) => {
const start = Date.now();
const check = () => {
let val = null;
try { val = predicate(); } catch (e) {}
if (val) { resolve(val); return; }
if (Date.now() - start > timeoutMs) {
reject(new Error((label || 'Element') + ' nicht gefunden (Timeout)'));
return;
}
setTimeout(check, 250);
};
check();
});
}
function getIframe() {
const f = document.querySelector(IFRAME_SELECTOR);
return (f && f.src && f.src.includes('function_sheet')) ? f : null;
}
// ExtJS-Buttons reagieren zuverlässiger auf eine echte Maus-Sequenz
function realClick(el) {
for (const type of ['mousedown', 'mouseup', 'click']) {
el.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true }));
}
}
function closeEventWindow() {
// 1) Über Icon-Klasse suchen
const icon = document.querySelector(CLOSE_ICON_SELECTOR);
let btn = icon ? icon.closest('button') : null;
// 2) Fallback: letzter Icon-Button in der rechts ausgerichteten Appbar-Sektion
if (!btn) {
const candidates = document.querySelectorAll(CLOSE_BUTTON_FALLBACK_SELECTOR);
if (candidates.length) btn = candidates[candidates.length - 1];
}
if (!btn) {
console.warn('Schließen-Button nicht gefunden.');
return;
}
realClick(btn);
}
// Wartet, bis der Druckdialog geschlossen wurde. print() auf dem PDF-Iframe
// blockiert in Chrome nicht, deshalb erkennen wir das Schließen über
// afterprint (falls es feuert) bzw. darüber, dass das Fenster wieder
// Fokus/Mausbewegungen bekommt (während der modale Dialog offen ist,
// kommen keine Maus-Events an).
function waitForPrintDialogClosed(frame, maxMs) {
return new Promise((resolve) => {
let done = false;
const finish = () => {
if (done) return;
done = true;
cleanup();
resolve();
};
const onAfterPrint = () => finish();
const onFocus = () => finish();
const onMouseMove = () => finish();
const cleanup = () => {
try { frame.contentWindow.removeEventListener('afterprint', onAfterPrint); } catch (e) {}
window.removeEventListener('afterprint', onAfterPrint);
window.removeEventListener('focus', onFocus);
document.removeEventListener('mousemove', onMouseMove);
};
try { frame.contentWindow.addEventListener('afterprint', onAfterPrint); } catch (e) {}
window.addEventListener('afterprint', onAfterPrint);
// Listener für Fokus/Maus erst nach kurzer Verzögerung scharf schalten,
// damit nicht das Öffnen des Dialogs selbst das Signal auslöst
setTimeout(() => {
if (done) return;
window.addEventListener('focus', onFocus);
document.addEventListener('mousemove', onMouseMove);
}, 800);
setTimeout(finish, maxMs);
});
}
function styleButton(btn) {
btn.style.display = 'block';
btn.style.marginTop = '8px';
btn.style.padding = '6px 12px';
btn.style.background = '#2563eb';
btn.style.color = '#fff';
btn.style.border = 'none';
btn.style.borderRadius = '6px';
btn.style.cursor = 'pointer';
btn.style.fontSize = '13px';
}
// ================= Buttons anlegen =================
function findDownloadButton() {
const buttons = document.querySelectorAll('button.k-button');
for (const b of buttons) {
if (b.textContent.trim().includes(DOWNLOAD_BUTTON_TEXT)) return b;
}
return null;
}
// Button 1: im Drawer unter dem Download-Button
function ensureDrawerButton() {
if (document.getElementById('tm-print-btn')) return;
const downloadBtn = findDownloadButton();
if (!downloadBtn) return;
const btn = document.createElement('button');
btn.id = 'tm-print-btn';
btn.className = 'k-button';
btn.textContent = '🖨️ Drucken';
styleButton(btn);
btn.addEventListener('click', () => printCurrentIframe());
downloadBtn.insertAdjacentElement('afterend', btn);
}
// Button 2: in der Sidebar direkt unter dem "Function Sheet"-Eintrag
function ensureSidebarButton() {
if (document.getElementById('tm-print-btn-front')) return;
const item = document.querySelector(SIDEBAR_ITEM_SELECTOR);
if (!item) return;
const li = document.createElement('li');
li.id = 'tm-print-btn-front';
li.className = 'k-drawer-item';
li.setAttribute('role', 'menuitem');
li.style.display = 'flex';
li.style.alignItems = 'center';
li.style.cursor = 'pointer';
li.style.padding = '6px 12px';
li.style.background = '#2563eb';
li.style.color = '#fff';
li.style.borderRadius = '6px';
li.style.margin = '4px 8px';
li.style.fontSize = '13px';
li.textContent = '🖨️ Function Sheet drucken';
li.addEventListener('click', (ev) => {
ev.preventDefault();
ev.stopPropagation();
openAndPrint();
});
item.insertAdjacentElement('afterend', li);
}
// Button 3: Drucker-Icon an jedem Event in der Bankett-Übersicht
function ensureEventIcons() {
const events = document.querySelectorAll(EVENT_SELECTOR);
events.forEach((ev) => {
if (ev.querySelector('.tm-event-print')) return;
const icon = document.createElement('span');
icon.className = 'tm-event-print';
icon.textContent = '🖨️';
icon.title = 'Function Sheet drucken';
icon.style.position = 'absolute';
icon.style.top = '2px';
icon.style.right = '4px';
icon.style.fontSize = '13px';
icon.style.lineHeight = '1';
icon.style.cursor = 'pointer';
icon.style.zIndex = '10';
icon.style.background = 'rgba(255,255,255,0.85)';
icon.style.borderRadius = '3px';
icon.style.padding = '1px 2px';
// Klicks auf das Icon dürfen NICHT das Event selbst öffnen
const swallow = (e) => { e.stopPropagation(); };
icon.addEventListener('mousedown', swallow);
icon.addEventListener('mouseup', swallow);
icon.addEventListener('dblclick', swallow);
icon.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
printFromOverview(ev, icon);
});
ev.appendChild(icon);
});
}
function ensureButtons() {
ensureDrawerButton();
ensureSidebarButton();
ensureEventIcons();
}
// ================= Druck-Abläufe =================
let busy = false;
// Aus der Übersicht: Event öffnen -> Function Sheet -> drucken -> zurück
async function printFromOverview(eventEl, icon) {
if (busy) return;
busy = true;
const oldIcon = icon.textContent;
icon.textContent = '⏳';
try {
// URL des evtl. noch offenen Iframes merken, damit wir nicht das
// Sheet vom VORHERIGEN Event drucken
const prevIframe = getIframe();
const prevSrc = prevIframe ? prevIframe.src : null;
// 1) Event anklicken -> SPA wechselt auf die Event-Seite
eventEl.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
// 2) Auf Sidebar-Eintrag "Function Sheet" warten
const item = await waitFor(
() => document.querySelector(SIDEBAR_ITEM_SELECTOR),
WAIT_TIMEOUT,
'Sidebar-Eintrag "Function Sheet"'
);
await sleep(SETTLE_DELAY);
// 3) Function Sheet öffnen
item.click();
// 4) Auf NEUEN Iframe warten (andere URL als vorher)
let iframe;
try {
iframe = await waitFor(() => {
const f = getIframe();
if (!f) return null;
if (prevSrc && f.src === prevSrc) return null;
return f;
}, WAIT_TIMEOUT, 'Function-Sheet-Iframe');
} catch (e) {
// Fallback: gleiches Event wie zuvor -> vorhandenen Iframe nehmen
iframe = getIframe();
if (!iframe) throw e;
console.warn('Iframe-URL unverändert, drucke vorhandenes Sheet.');
}
await sleep(SETTLE_DELAY);
// 5) Drucken (inkl. Rücksprung, siehe printFromIframe)
await printFromIframe(iframe);
} catch (e) {
console.error(e);
alert(e.message);
} finally {
icon.textContent = oldIcon;
busy = false;
}
}
// Sidebar-Button: erst "Function Sheet" klicken (falls nötig), dann drucken
async function openAndPrint() {
const front = document.getElementById('tm-print-btn-front');
const oldText = front ? front.textContent : '';
if (front) front.textContent = '⏳ Öffne Function Sheet…';
try {
let iframe = getIframe();
if (!iframe) {
const item = document.querySelector(SIDEBAR_ITEM_SELECTOR);
if (!item) throw new Error('Sidebar-Eintrag "Function Sheet" nicht gefunden');
item.click();
iframe = await waitFor(getIframe, WAIT_TIMEOUT, 'Function-Sheet-Iframe');
await sleep(SETTLE_DELAY);
}
await printFromIframe(iframe);
} catch (e) {
console.error(e);
alert(e.message);
} finally {
if (front) front.textContent = oldText;
}
}
// Drawer-Button: Iframe ist schon da
async function printCurrentIframe() {
const iframe = getIframe();
if (!iframe) {
alert('Function-Sheet-Iframe nicht gefunden. Selektor prüfen: ' + IFRAME_SELECTOR);
return;
}
await printFromIframe(iframe);
}
async function printFromIframe(iframe) {
const printUrl = buildPrintUrl(iframe.src);
if (USE_PDF) {
await printPdf(printUrl);
} else {
printHtml(printUrl);
}
// Nach dem Druck das Event-Fenster über den X-Button schließen
if (AUTO_RETURN) {
await sleep(SETTLE_DELAY);
closeEventWindow();
}
}
// Baut aus der Iframe-URL die Druck-URL:
// - hide_prices setzen
// - mode=html entfernen (-> Server liefert PDF) bzw. setzen (HTML-Variante)
function buildPrintUrl(src) {
const url = new URL(src, location.href);
url.searchParams.set('hide_prices', HIDE_PRICES ? 'true' : 'false');
if (USE_PDF) {
url.searchParams.delete('mode');
} else {
url.searchParams.set('mode', 'html');
}
return url.toString();
}
// ---------- Variante A: PDF holen und drucken ----------
// Löst erst auf, wenn der Druckdialog geschlossen wurde (Chrome blockiert in print())
async function printPdf(url) {
const btn = document.getElementById('tm-print-btn');
const oldText = btn ? btn.textContent : '';
if (btn) { btn.textContent = '⏳ Lade PDF…'; btn.disabled = true; }
try {
const resp = await fetch(url, { credentials: 'include' });
if (!resp.ok) throw new Error('HTTP ' + resp.status);
const blob = await resp.blob();
const blobUrl = URL.createObjectURL(blob);
const old = document.getElementById('tm-print-frame');
if (old) old.remove();
// Iframe darf NICHT display:none sein, sonst rendert Chrome die PDF nicht
const frame = document.createElement('iframe');
frame.id = 'tm-print-frame';
frame.style.position = 'fixed';
frame.style.right = '0';
frame.style.bottom = '0';
frame.style.width = '1px';
frame.style.height = '1px';
frame.style.opacity = '0';
frame.style.border = 'none';
frame.style.pointerEvents = 'none';
frame.src = blobUrl;
await new Promise((resolve) => {
frame.onload = () => {
setTimeout(async () => {
try {
frame.contentWindow.focus();
frame.contentWindow.print();
// erst weiter, wenn der Druckdialog zu ist (max. 5 Min.)
await waitForPrintDialogClosed(frame, 5 * 60 * 1000);
} catch (e) {
console.warn('Direkter PDF-Druck fehlgeschlagen, öffne in neuem Tab:', e);
window.open(blobUrl, '_blank');
}
resolve();
}, 300);
};
document.body.appendChild(frame);
});
} catch (e) {
console.error('PDF konnte nicht geladen werden:', e);
alert('PDF konnte nicht geladen werden (' + e.message + '). Öffne stattdessen im neuen Tab.');
window.open(url, '_blank');
} finally {
if (btn) { btn.textContent = oldText; btn.disabled = false; }
}
}
// ---------- Variante B: HTML-Ansicht drucken (Fallback) ----------
function printHtml(url) {
const win = window.open(url, '_blank');
if (!win) {
alert('Popup wurde blockiert. Bitte Popups für diese Seite erlauben.');
return;
}
win.onload = () => {
setTimeout(() => {
fixPrintStyles(win.document);
win.focus();
win.print();
}, 400);
};
}
function fixPrintStyles(doc) {
try {
Array.from(doc.styleSheets).forEach((sheet) => {
try { if (sheet.media) sheet.media.mediaText = 'all'; } catch (e) {}
});
} catch (e) {}
const style = doc.createElement('style');
style.textContent = `
@media print {
* {
-webkit-print-color-adjust: exact !important;
print-color-adjust: exact !important;
}
div, section, article,
.timeline-day,
.table-timeline > tbody {
break-inside: auto !important;
page-break-inside: auto !important;
}
tr, li {
break-inside: avoid !important;
page-break-inside: avoid !important;
}
}
`;
doc.head.appendChild(style);
}
// ================= Start =================
console.log('[FS-Print] Skript geladen, Version 4.6, URL:', location.href);
// SPA: DOM ändert sich live ohne Reload -> Buttons regelmäßig nachlegen
ensureButtons();
setInterval(ensureButtons, 1000);
})();