732 lines
27 KiB
JavaScript
732 lines
27 KiB
JavaScript
/* Drink it cold – Terminplanung: Interaktionen ohne Framework. */
|
||
(() => {
|
||
'use strict';
|
||
|
||
const csrf = document.querySelector('meta[name="csrf-token"]')?.content || '';
|
||
const swMeta = document.querySelector('meta[name="sw-url"]');
|
||
let toastTimer = 0;
|
||
let installPrompt = null;
|
||
|
||
/* --------------------------------------------------------------- PWA */
|
||
const registerServiceWorker = () => {
|
||
if (!('serviceWorker' in navigator) || !swMeta) return;
|
||
navigator.serviceWorker.register(swMeta.content).catch(() => {
|
||
/* Installation ist optional; die App funktioniert auch ohne SW. */
|
||
});
|
||
};
|
||
if (document.readyState === 'complete') {
|
||
registerServiceWorker();
|
||
} else {
|
||
window.addEventListener('load', registerServiceWorker, { once: true });
|
||
}
|
||
|
||
window.addEventListener('beforeinstallprompt', (event) => {
|
||
event.preventDefault();
|
||
installPrompt = event;
|
||
document.querySelectorAll('[data-install-app]').forEach((button) => { button.hidden = false; });
|
||
});
|
||
|
||
window.addEventListener('appinstalled', () => {
|
||
installPrompt = null;
|
||
document.querySelectorAll('[data-install-app]').forEach((button) => { button.hidden = true; });
|
||
toast('Die App wurde installiert.');
|
||
});
|
||
|
||
document.addEventListener('click', async (event) => {
|
||
const button = event.target.closest('[data-install-app]');
|
||
if (!button || !installPrompt) return;
|
||
const prompt = installPrompt;
|
||
installPrompt = null;
|
||
button.hidden = true;
|
||
try {
|
||
prompt.prompt();
|
||
await prompt.userChoice;
|
||
} catch (error) {
|
||
/* Der Browser kann die Installation trotzdem abgelehnt haben. */
|
||
}
|
||
});
|
||
|
||
const toast = (message, isError = false) => {
|
||
const el = document.getElementById('toast');
|
||
if (!el) return;
|
||
el.textContent = message;
|
||
el.hidden = false;
|
||
el.classList.toggle('is-error', isError);
|
||
window.clearTimeout(toastTimer);
|
||
toastTimer = window.setTimeout(() => { el.hidden = true; }, isError ? 5200 : 3200);
|
||
};
|
||
|
||
try {
|
||
const storedToast = window.sessionStorage.getItem('dic-toast');
|
||
if (storedToast) {
|
||
window.sessionStorage.removeItem('dic-toast');
|
||
toast(storedToast);
|
||
}
|
||
} catch (error) { /* sessionStorage kann blockiert sein */ }
|
||
|
||
/* ------------------------------------------------------------- Meldungen */
|
||
document.addEventListener('click', (event) => {
|
||
const dismiss = event.target.closest('[data-dismiss]');
|
||
if (dismiss) {
|
||
dismiss.closest('.flash')?.remove();
|
||
}
|
||
});
|
||
|
||
/* --------------------------------------------------------------- Toasts */
|
||
const flash = document.querySelector('.flash--success');
|
||
if (flash) {
|
||
// Server-Flash bleibt sichtbar; kein zusätzlicher Toast nötig.
|
||
}
|
||
|
||
/* --------------------------------------------------------- Formulare */
|
||
document.addEventListener('change', (event) => {
|
||
const control = event.target.closest('[data-autosubmit]');
|
||
if (control) {
|
||
const form = control.form;
|
||
if (form) form.submit();
|
||
}
|
||
});
|
||
|
||
document.addEventListener('submit', (event) => {
|
||
const form = event.target;
|
||
if (!(form instanceof HTMLFormElement)) return;
|
||
const message = form.dataset.confirm;
|
||
if (message && !window.confirm(message)) {
|
||
event.preventDefault();
|
||
return;
|
||
}
|
||
const submitter = event.submitter;
|
||
if (submitter && !submitter.disabled) {
|
||
window.setTimeout(() => { submitter.disabled = true; }, 30);
|
||
}
|
||
});
|
||
|
||
/* ------------------------------------------------------------- Kopieren */
|
||
const copyToClipboard = async (text) => {
|
||
if (navigator.clipboard && window.isSecureContext) {
|
||
await navigator.clipboard.writeText(text);
|
||
return;
|
||
}
|
||
const helper = document.createElement('textarea');
|
||
helper.value = text;
|
||
helper.setAttribute('readonly', '');
|
||
helper.style.position = 'fixed';
|
||
helper.style.left = '-9999px';
|
||
document.body.appendChild(helper);
|
||
helper.select();
|
||
document.execCommand('copy');
|
||
helper.remove();
|
||
};
|
||
|
||
document.addEventListener('click', async (event) => {
|
||
const button = event.target.closest('[data-copy]');
|
||
if (!button) return;
|
||
const wrap = button.closest('[data-copy-wrap]');
|
||
const source = wrap?.querySelector('.copy-source');
|
||
if (!source) return;
|
||
try {
|
||
await copyToClipboard(source.value);
|
||
toast('Buchungstext kopiert.');
|
||
const original = button.innerHTML;
|
||
button.innerHTML = '<svg class="ico" aria-hidden="true"><use href="#i-check"/></svg> Kopiert';
|
||
window.setTimeout(() => { button.innerHTML = original; }, 1800);
|
||
} catch (error) {
|
||
toast('Kopieren nicht möglich. Bitte den Text markieren und manuell kopieren.', true);
|
||
}
|
||
});
|
||
|
||
/* --------------------------------------------------------- Buchungsdialog */
|
||
const dialog = document.getElementById('booking-dialog');
|
||
const dialogContent = document.getElementById('booking-dialog-content');
|
||
|
||
const closeDialog = () => {
|
||
if (dialog?.open) dialog.close();
|
||
};
|
||
|
||
document.addEventListener('click', async (event) => {
|
||
const trigger = event.target.closest('a[data-panel]');
|
||
if (!trigger || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
||
if (!dialog || !dialogContent || typeof dialog.showModal !== 'function') return;
|
||
event.preventDefault();
|
||
const id = trigger.dataset.panel;
|
||
try {
|
||
const response = await fetch(trigger.href.replace(/\/?$/, '') + '/panel', {
|
||
headers: { 'Accept': 'text/html', 'X-Requested-With': 'fetch' },
|
||
credentials: 'same-origin'
|
||
});
|
||
if (!response.ok || response.url.includes('/login')) {
|
||
window.location.href = trigger.href;
|
||
return;
|
||
}
|
||
dialogContent.innerHTML = await response.text();
|
||
dialog.showModal();
|
||
dialogContent.querySelector('[data-close-dialog]')?.focus();
|
||
} catch (error) {
|
||
window.location.href = trigger.href;
|
||
}
|
||
});
|
||
|
||
document.addEventListener('click', (event) => {
|
||
if (event.target.closest('[data-close-dialog]')) closeDialog();
|
||
});
|
||
|
||
if (dialog) {
|
||
dialog.addEventListener('click', (event) => {
|
||
if (event.target === dialog) closeDialog();
|
||
});
|
||
dialog.addEventListener('close', () => {
|
||
if (dialogContent) dialogContent.innerHTML = '';
|
||
});
|
||
}
|
||
|
||
/* --------------------------------------------------------- Nutzermenü */
|
||
document.addEventListener('click', (event) => {
|
||
document.querySelectorAll('details.user-menu[open]').forEach((menu) => {
|
||
if (!menu.contains(event.target)) menu.removeAttribute('open');
|
||
});
|
||
});
|
||
|
||
/* ------------------------------------------------------------ Buchungsformular */
|
||
const bookingForm = document.querySelector('[data-booking-form]');
|
||
if (bookingForm) {
|
||
const trailerSelect = bookingForm.querySelector('[data-trailer-select]');
|
||
const employeeSelect = bookingForm.querySelector('select[name="employee_id"]');
|
||
const startInput = bookingForm.querySelector('[data-date-start]');
|
||
const endInput = bookingForm.querySelector('[data-date-end]');
|
||
const depositInput = bookingForm.querySelector('[data-money="deposit"]');
|
||
const totalInput = bookingForm.querySelector('[data-money="total"]');
|
||
const dueOutput = bookingForm.querySelector('[data-due]');
|
||
const conflictBox = bookingForm.querySelector('[data-conflict]');
|
||
const availabilityUrl = bookingForm.dataset.availabilityUrl;
|
||
const excludeId = bookingForm.dataset.exclude || '0';
|
||
|
||
const parseMoney = (value) => {
|
||
let text = String(value || '').replace(/[^\d,.\-]/g, '');
|
||
if (text.includes(',')) {
|
||
text = text.replace(/\./g, '').replace(',', '.');
|
||
} else if (/^\d{1,3}(\.\d{3})+$/.test(text)) {
|
||
text = text.replace(/\./g, '');
|
||
}
|
||
const number = Number.parseFloat(text || '0');
|
||
return Number.isFinite(number) ? Math.round(number * 100) : 0;
|
||
};
|
||
const formatMoney = (cents) => {
|
||
return (cents / 100).toLocaleString('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €';
|
||
};
|
||
const formatDate = (iso) => {
|
||
if (!/^\d{4}-\d{2}-\d{2}$/.test(iso)) return '–';
|
||
const [y, m, d] = iso.split('-');
|
||
return `${d}.${m}.${y}`;
|
||
};
|
||
const formatRange = (a, b) => {
|
||
if (!a || !b) return '–';
|
||
return a === b ? formatDate(a) : `${formatDate(a)} – ${formatDate(b)}`;
|
||
};
|
||
const contrast = (hex) => {
|
||
const clean = String(hex || '').replace('#', '');
|
||
if (clean.length !== 6) return '#ffffff';
|
||
const channels = [0, 2, 4].map((i) => {
|
||
const c = Number.parseInt(clean.slice(i, i + 2), 16) / 255;
|
||
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
||
});
|
||
const luminance = 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2];
|
||
return luminance > 0.46 ? '#10202c' : '#ffffff';
|
||
};
|
||
|
||
const updateTrailer = () => {
|
||
if (!trailerSelect) return;
|
||
const option = trailerSelect.selectedOptions[0];
|
||
if (!option) return;
|
||
const color = option.dataset.color || '#196abc';
|
||
const name = option.dataset.colorName || '';
|
||
const label = option.textContent.split('·')[0].trim();
|
||
const preview = bookingForm.querySelector('[data-trailer-preview]');
|
||
if (preview) {
|
||
preview.style.setProperty('--trailer', color);
|
||
preview.style.setProperty('--trailer-text', contrast(color));
|
||
const dot = preview.querySelector('.trailer-dot');
|
||
if (dot) dot.style.setProperty('--trailer', color);
|
||
const text = preview.querySelector('[data-trailer-preview-label]');
|
||
if (text) text.textContent = `${label} · ${name}`;
|
||
}
|
||
const summary = bookingForm.querySelector('[data-summary-trailer]');
|
||
if (summary) summary.textContent = label;
|
||
};
|
||
|
||
const updateTotals = () => {
|
||
const deposit = parseMoney(depositInput?.value);
|
||
const total = parseMoney(totalInput?.value);
|
||
const due = total - deposit;
|
||
if (dueOutput) dueOutput.textContent = formatMoney(due);
|
||
const totalSummary = bookingForm.querySelector('[data-summary-total]');
|
||
const depositSummary = bookingForm.querySelector('[data-summary-deposit]');
|
||
const dueSummary = bookingForm.querySelector('[data-summary-due]');
|
||
if (totalSummary) totalSummary.textContent = formatMoney(total);
|
||
if (depositSummary) depositSummary.textContent = formatMoney(deposit);
|
||
if (dueSummary) dueSummary.textContent = formatMoney(due);
|
||
};
|
||
|
||
const updateSummary = () => {
|
||
const dates = bookingForm.querySelector('[data-summary-dates]');
|
||
if (dates) dates.textContent = formatRange(startInput?.value, endInput?.value);
|
||
const employee = bookingForm.querySelector('[data-summary-employee]');
|
||
if (employee && employeeSelect) {
|
||
employee.textContent = employeeSelect.selectedOptions[0]?.textContent.trim() || '–';
|
||
}
|
||
};
|
||
|
||
const showConflict = (html, ok = false) => {
|
||
if (!conflictBox) return;
|
||
if (!html) {
|
||
conflictBox.hidden = true;
|
||
conflictBox.innerHTML = '';
|
||
conflictBox.classList.remove('is-ok');
|
||
return;
|
||
}
|
||
conflictBox.hidden = false;
|
||
conflictBox.innerHTML = html;
|
||
conflictBox.classList.toggle('is-ok', ok);
|
||
};
|
||
|
||
let availabilityTimer = 0;
|
||
const checkAvailability = () => {
|
||
if (!availabilityUrl || !trailerSelect || !startInput || !endInput) return;
|
||
const start = startInput.value;
|
||
const end = endInput.value;
|
||
if (!start || !end || end < start) {
|
||
showConflict('');
|
||
return;
|
||
}
|
||
window.clearTimeout(availabilityTimer);
|
||
availabilityTimer = window.setTimeout(async () => {
|
||
const params = new URLSearchParams({
|
||
trailer: trailerSelect.value,
|
||
start,
|
||
end,
|
||
exclude: excludeId
|
||
});
|
||
try {
|
||
const response = await fetch(`${availabilityUrl}?${params.toString()}`, {
|
||
headers: { 'Accept': 'application/json', 'X-Requested-With': 'fetch' },
|
||
credentials: 'same-origin'
|
||
});
|
||
if (!response.ok) {
|
||
showConflict('');
|
||
return;
|
||
}
|
||
const data = await response.json();
|
||
if (data.ok) {
|
||
showConflict('<svg class="ico" aria-hidden="true"><use href="#i-check"/></svg><span>Der Zeitraum ist für diesen Anhänger frei.</span>', true);
|
||
return;
|
||
}
|
||
const conflict = data.conflicts && data.conflicts[0];
|
||
if (conflict) {
|
||
showConflict(`<svg class="ico" aria-hidden="true"><use href="#i-alert"/></svg><span>Belegt: ${formatDate(conflict.start)} – ${formatDate(conflict.end)} (${conflict.customer}). Ein Wechseltag ist erlaubt.</span>`);
|
||
} else {
|
||
showConflict('');
|
||
}
|
||
} catch (error) {
|
||
showConflict('');
|
||
}
|
||
}, 320);
|
||
};
|
||
|
||
trailerSelect?.addEventListener('change', () => { updateTrailer(); checkAvailability(); });
|
||
employeeSelect?.addEventListener('change', updateSummary);
|
||
startInput?.addEventListener('change', () => {
|
||
if (endInput && endInput.value && endInput.value < startInput.value) {
|
||
endInput.value = startInput.value;
|
||
}
|
||
updateSummary();
|
||
checkAvailability();
|
||
});
|
||
endInput?.addEventListener('change', () => { updateSummary(); checkAvailability(); });
|
||
depositInput?.addEventListener('input', updateTotals);
|
||
totalInput?.addEventListener('input', updateTotals);
|
||
|
||
updateTrailer();
|
||
updateTotals();
|
||
updateSummary();
|
||
if (startInput?.value && endInput?.value) checkAvailability();
|
||
}
|
||
|
||
/* -------------------------------------------------------- Kalender: Ziehen */
|
||
const calendar = document.querySelector('.cal-shell');
|
||
if (calendar && window.matchMedia('(pointer: fine)').matches) {
|
||
let drag = null;
|
||
let suppressClick = false;
|
||
|
||
const addDays = (iso, days) => {
|
||
const date = new Date(`${iso}T12:00:00Z`);
|
||
date.setUTCDate(date.getUTCDate() + days);
|
||
return date.toISOString().slice(0, 10);
|
||
};
|
||
|
||
const resetDrag = () => {
|
||
if (!drag) return;
|
||
drag.bar.style.transform = '';
|
||
drag.bar.classList.remove('is-dragging');
|
||
drag.target?.classList.remove('is-drop-target');
|
||
drag = null;
|
||
};
|
||
|
||
calendar.addEventListener('pointerdown', (event) => {
|
||
if (event.button !== 0) return;
|
||
const bar = event.target.closest('.cal-bar');
|
||
if (!bar || bar.classList.contains('is-cancelled')) return;
|
||
const track = bar.closest('.cal-track');
|
||
if (!track) return;
|
||
const cell = track.querySelector('.cal-cell');
|
||
if (!cell) return;
|
||
drag = {
|
||
bar,
|
||
track,
|
||
startX: event.clientX,
|
||
startY: event.clientY,
|
||
dayWidth: cell.getBoundingClientRect().width || 1,
|
||
moved: false,
|
||
target: null,
|
||
pointerId: event.pointerId
|
||
};
|
||
});
|
||
|
||
document.addEventListener('pointermove', (event) => {
|
||
if (!drag || event.pointerId !== drag.pointerId) return;
|
||
const dx = event.clientX - drag.startX;
|
||
const dy = event.clientY - drag.startY;
|
||
if (!drag.moved && Math.abs(dx) > 6 && Math.abs(dx) > Math.abs(dy)) {
|
||
drag.moved = true;
|
||
drag.bar.classList.add('is-dragging');
|
||
drag.bar.style.transform = `translateX(${dx}px)`;
|
||
} else if (drag.moved) {
|
||
event.preventDefault();
|
||
drag.bar.style.transform = `translateX(${dx}px)`;
|
||
}
|
||
if (drag.moved) {
|
||
const hit = document.elementFromPoint(event.clientX, event.clientY)?.closest('.cal-track');
|
||
if (hit !== drag.target) {
|
||
drag.target?.classList.remove('is-drop-target');
|
||
drag.target = hit && hit !== drag.track ? hit : null;
|
||
drag.target?.classList.add('is-drop-target');
|
||
}
|
||
}
|
||
}, { passive: false });
|
||
|
||
document.addEventListener('pointerup', async (event) => {
|
||
if (!drag || event.pointerId !== drag.pointerId) return;
|
||
const active = drag;
|
||
if (!active.moved) {
|
||
resetDrag();
|
||
return;
|
||
}
|
||
suppressClick = true;
|
||
window.setTimeout(() => { suppressClick = false; }, 120);
|
||
|
||
const dx = event.clientX - active.startX;
|
||
const shift = Math.round(dx / active.dayWidth);
|
||
const startDate = active.bar.dataset.startDate;
|
||
const originalTrailer = active.bar.dataset.trailerId;
|
||
const targetTrailer = active.target?.dataset.trailerId || originalTrailer;
|
||
const bookingId = active.bar.dataset.bookingId;
|
||
|
||
resetDrag();
|
||
|
||
if ((shift === 0 && targetTrailer === originalTrailer) || !bookingId || !startDate) {
|
||
return;
|
||
}
|
||
|
||
try {
|
||
const body = new URLSearchParams({
|
||
start_date: addDays(startDate, shift),
|
||
trailer_id: targetTrailer,
|
||
_csrf: csrf
|
||
});
|
||
const response = await fetch(`/bookings/${bookingId}/move`, {
|
||
method: 'POST',
|
||
body,
|
||
headers: {
|
||
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
|
||
'Accept': 'application/json',
|
||
'X-Requested-With': 'fetch',
|
||
'X-CSRF-Token': csrf
|
||
},
|
||
credentials: 'same-origin'
|
||
});
|
||
if (response.url.includes('/login')) {
|
||
window.location.reload();
|
||
return;
|
||
}
|
||
const data = await response.json().catch(() => ({}));
|
||
if (!response.ok || !data.ok) {
|
||
toast(data.error || 'Verschieben nicht möglich.', true);
|
||
return;
|
||
}
|
||
const message = 'Buchung verschoben – Erinnerungen wurden angepasst.';
|
||
try { window.sessionStorage.setItem('dic-toast', message); } catch (error) { /* ignore */ }
|
||
toast(message);
|
||
window.setTimeout(() => window.location.reload(), 500);
|
||
} catch (error) {
|
||
toast('Verschieben fehlgeschlagen. Bitte erneut versuchen.', true);
|
||
}
|
||
});
|
||
|
||
document.addEventListener('pointercancel', resetDrag);
|
||
|
||
document.addEventListener('click', (event) => {
|
||
if (!suppressClick) return;
|
||
if (event.target.closest('.cal-bar')) {
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
}
|
||
}, true);
|
||
}
|
||
|
||
/* --------------------------------------------------- Anhängerfarben (Admin) */
|
||
document.querySelectorAll('[data-color-sync]').forEach((colorInput) => {
|
||
const row = colorInput.closest('.trailer-admin__row');
|
||
const textInput = row?.querySelector('[data-color-text]');
|
||
const preview = row?.querySelector('[data-color-preview]');
|
||
const dot = preview?.querySelector('.trailer-dot');
|
||
const labelInput = row?.querySelector('input[name^="label"]');
|
||
|
||
const contrast = (hex) => {
|
||
const clean = String(hex || '').replace('#', '');
|
||
if (clean.length !== 6) return '#ffffff';
|
||
const channels = [0, 2, 4].map((i) => {
|
||
const c = Number.parseInt(clean.slice(i, i + 2), 16) / 255;
|
||
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
||
});
|
||
const luminance = 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2];
|
||
return luminance > 0.46 ? '#10202c' : '#ffffff';
|
||
};
|
||
const apply = (hex) => {
|
||
if (!/^#[0-9a-fA-F]{6}$/.test(hex) || !preview) return;
|
||
preview.style.setProperty('--trailer', hex);
|
||
preview.style.setProperty('--trailer-text', contrast(hex));
|
||
if (dot) dot.style.setProperty('--trailer', hex);
|
||
};
|
||
|
||
colorInput.addEventListener('input', () => {
|
||
if (textInput) textInput.value = colorInput.value;
|
||
apply(colorInput.value);
|
||
});
|
||
textInput?.addEventListener('input', () => {
|
||
const value = textInput.value.startsWith('#') ? textInput.value : `#${textInput.value}`;
|
||
if (/^#[0-9a-fA-F]{6}$/.test(value)) {
|
||
colorInput.value = value;
|
||
apply(value);
|
||
}
|
||
});
|
||
labelInput?.addEventListener('input', () => {
|
||
if (!preview) return;
|
||
const textNode = [...preview.childNodes].find((node) => node.nodeType === Node.TEXT_NODE && node.textContent.trim());
|
||
if (textNode) textNode.textContent = ` ${labelInput.value}`;
|
||
});
|
||
});
|
||
})();
|
||
|
||
/* ------------------------------------------------------- Web-Push (VAPID) */
|
||
(() => {
|
||
const card = document.querySelector('[data-push]');
|
||
if (!card) return;
|
||
|
||
const toggle = card.querySelector('[data-push-toggle]');
|
||
const controls = card.querySelector('[data-push-controls]');
|
||
const browserHint = card.querySelector('[data-push-browser-hint]');
|
||
const statusEl = card.querySelector('[data-push-status]');
|
||
const testButton = card.querySelector('[data-push-test]');
|
||
const countEl = card.querySelector('[data-push-count]');
|
||
const vapidKey = card.dataset.vapidKey || '';
|
||
const subscribeUrl = card.dataset.subscribeUrl;
|
||
const unsubscribeUrl = card.dataset.unsubscribeUrl;
|
||
const testUrl = card.dataset.testUrl;
|
||
const csrf = document.querySelector('meta[name="csrf-token"]')?.content || '';
|
||
if (!toggle || !controls || !statusEl || !testButton || !subscribeUrl || !unsubscribeUrl || !testUrl) {
|
||
return;
|
||
}
|
||
|
||
const standalone = window.matchMedia('(display-mode: standalone)').matches
|
||
|| window.navigator.standalone === true;
|
||
const supported = 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window;
|
||
|
||
const setStatus = (text, isError = false) => {
|
||
statusEl.textContent = text || '';
|
||
statusEl.classList.toggle('is-error', isError);
|
||
};
|
||
|
||
const updateCount = (count) => {
|
||
if (!countEl || typeof count !== 'number') return;
|
||
countEl.textContent = count > 0
|
||
? `${count} Gerät${count === 1 ? '' : 'e'} aktiv`
|
||
: 'nicht aktiviert';
|
||
countEl.classList.toggle('pill--green', count > 0);
|
||
countEl.classList.toggle('pill--grey', count === 0);
|
||
};
|
||
|
||
const postJson = async (url, payload) => {
|
||
const response = await fetch(url, {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json;charset=UTF-8',
|
||
'Accept': 'application/json',
|
||
'X-Requested-With': 'fetch',
|
||
'X-CSRF-Token': csrf
|
||
},
|
||
credentials: 'same-origin',
|
||
body: JSON.stringify(payload || {})
|
||
});
|
||
const type = response.headers.get('content-type') || '';
|
||
if (!type.includes('application/json')) {
|
||
throw new Error('Die Sitzung ist abgelaufen. Bitte die Seite neu laden.');
|
||
}
|
||
const data = await response.json().catch(() => ({}));
|
||
if (!response.ok) {
|
||
throw new Error(data.error || `Server meldet HTTP ${response.status}.`);
|
||
}
|
||
return data;
|
||
};
|
||
|
||
const keyToBytes = (base64url) => {
|
||
const padding = '='.repeat((4 - (base64url.length % 4)) % 4);
|
||
const base64 = (base64url + padding).replace(/-/g, '+').replace(/_/g, '/');
|
||
const raw = window.atob(base64);
|
||
const bytes = new Uint8Array(raw.length);
|
||
for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);
|
||
return bytes;
|
||
};
|
||
|
||
if (!supported || !vapidKey) {
|
||
if (browserHint) {
|
||
browserHint.innerHTML = '<svg class="ico" aria-hidden="true"><use href="#i-alert"/></svg><div><strong>Push wird von diesem Browser nicht unterstützt.</strong><p>Bitte die installierte App auf einem aktuellen Android-Gerät oder iPhone verwenden.</p></div>';
|
||
}
|
||
return;
|
||
}
|
||
|
||
if (!standalone) {
|
||
controls.hidden = true;
|
||
if (browserHint) browserHint.hidden = false;
|
||
return;
|
||
}
|
||
|
||
if (browserHint) browserHint.hidden = true;
|
||
controls.hidden = false;
|
||
|
||
let registration = null;
|
||
|
||
const getRegistration = async () => {
|
||
if (!registration) {
|
||
registration = await navigator.serviceWorker.ready;
|
||
}
|
||
return registration;
|
||
};
|
||
|
||
const getSubscription = async () => {
|
||
const reg = await getRegistration();
|
||
return reg.pushManager.getSubscription();
|
||
};
|
||
|
||
const subscribe = async () => {
|
||
const reg = await getRegistration();
|
||
let subscription = await reg.pushManager.getSubscription();
|
||
if (subscription) return subscription;
|
||
|
||
try {
|
||
subscription = await reg.pushManager.subscribe({
|
||
userVisibleOnly: true,
|
||
applicationServerKey: keyToBytes(vapidKey)
|
||
});
|
||
} catch (error) {
|
||
if (error && error.name === 'InvalidStateError') {
|
||
const old = await reg.pushManager.getSubscription();
|
||
if (old) await old.unsubscribe();
|
||
subscription = await reg.pushManager.subscribe({
|
||
userVisibleOnly: true,
|
||
applicationServerKey: keyToBytes(vapidKey)
|
||
});
|
||
} else {
|
||
throw error;
|
||
}
|
||
}
|
||
return subscription;
|
||
};
|
||
|
||
const syncExisting = async () => {
|
||
const subscription = await getSubscription();
|
||
toggle.checked = !!subscription;
|
||
testButton.hidden = !subscription;
|
||
if (subscription) {
|
||
// Gerät beim Öffnen dem aktuell angemeldeten Konto zuordnen.
|
||
try {
|
||
const data = await postJson(subscribeUrl, subscription.toJSON());
|
||
updateCount(data.count);
|
||
} catch (error) {
|
||
setStatus('Das bestehende Abo konnte nicht zugeordnet werden. Bitte aus- und wieder einschalten.', true);
|
||
}
|
||
}
|
||
};
|
||
|
||
if (Notification.permission === 'denied') {
|
||
toggle.disabled = true;
|
||
setStatus('Benachrichtigungen sind für diese App blockiert. Bitte in den Systemeinstellungen erlauben.', true);
|
||
return;
|
||
}
|
||
|
||
syncExisting().catch(() => {
|
||
setStatus('Push konnte nicht initialisiert werden.', true);
|
||
});
|
||
|
||
toggle.addEventListener('change', async () => {
|
||
toggle.disabled = true;
|
||
testButton.disabled = true;
|
||
setStatus(toggle.checked ? 'Erinnerungen werden aktiviert …' : 'Erinnerungen werden deaktiviert …');
|
||
try {
|
||
if (toggle.checked) {
|
||
const permission = await Notification.requestPermission();
|
||
if (permission !== 'granted') {
|
||
throw new Error('Benachrichtigungen wurden nicht erlaubt. Bitte in den Einstellungen freigeben.');
|
||
}
|
||
const subscription = await subscribe();
|
||
const data = await postJson(subscribeUrl, subscription.toJSON());
|
||
updateCount(data.count);
|
||
testButton.hidden = false;
|
||
setStatus('Aktiviert. Erinnerungen erscheinen jetzt auf diesem Gerät.');
|
||
} else {
|
||
const subscription = await getSubscription();
|
||
const endpoint = subscription ? subscription.endpoint : '';
|
||
if (subscription) {
|
||
await subscription.unsubscribe();
|
||
}
|
||
const data = await postJson(unsubscribeUrl, { endpoint });
|
||
updateCount(data.count);
|
||
testButton.hidden = true;
|
||
setStatus('Erinnerungen sind auf diesem Gerät ausgeschaltet.');
|
||
}
|
||
} catch (error) {
|
||
const subscription = await getSubscription().catch(() => null);
|
||
toggle.checked = !!subscription;
|
||
testButton.hidden = !subscription;
|
||
setStatus(error && error.message ? error.message : 'Aktion fehlgeschlagen.', true);
|
||
} finally {
|
||
toggle.disabled = false;
|
||
testButton.disabled = false;
|
||
}
|
||
});
|
||
|
||
testButton.addEventListener('click', async () => {
|
||
if (testButton.disabled) return;
|
||
testButton.disabled = true;
|
||
setStatus('Test-Erinnerung wird gesendet …');
|
||
try {
|
||
const subscription = await getSubscription();
|
||
if (!subscription) {
|
||
throw new Error('Dieses Gerät ist noch nicht angemeldet.');
|
||
}
|
||
await postJson(testUrl, { endpoint: subscription.endpoint });
|
||
setStatus('Test-Erinnerung gesendet. Sie sollte jetzt erscheinen.');
|
||
} catch (error) {
|
||
setStatus(error && error.message ? error.message : 'Test fehlgeschlagen.', true);
|
||
} finally {
|
||
testButton.disabled = false;
|
||
}
|
||
});
|
||
})();
|