Drink it cold: Terminplanung für Kühlanhänger
This commit is contained in:
commit
ec88c8ebac
55 changed files with 7091 additions and 0 deletions
485
web/assets/app.js
Normal file
485
web/assets/app.js
Normal file
|
|
@ -0,0 +1,485 @@
|
|||
/* Drink it cold – Terminplanung: Interaktionen ohne Framework. */
|
||||
(() => {
|
||||
'use strict';
|
||||
|
||||
const csrf = document.querySelector('meta[name="csrf-token"]')?.content || '';
|
||||
let toastTimer = 0;
|
||||
|
||||
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}`;
|
||||
});
|
||||
});
|
||||
})();
|
||||
Loading…
Add table
Add a link
Reference in a new issue