1052 lines
36 KiB
JavaScript
1052 lines
36 KiB
JavaScript
/*
|
|
* Mobile Views: Dispatcher-Mobil & Gruppen
|
|
*/
|
|
const tenant = window.CMBNET_TENANT || window.location.pathname.split('/')[1];
|
|
const apiBase = `/${tenant}/api`;
|
|
const wsUrl = `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${window.location.host}/${tenant}/ws`;
|
|
const storageKey = `cmbnet:${tenant}:mobile`;
|
|
const viewMode = window.CMBNET_VIEW_MODE || 'mobile_dispatcher';
|
|
const currentAccountId = Number(window.CMBNET_ACCOUNT_ID) || null;
|
|
const currentRole = window.CMBNET_ROLE || null;
|
|
|
|
const DEFAULT_SETTINGS = {
|
|
opacity: 0.7,
|
|
weight: 20,
|
|
baseLayer: 'osm'
|
|
};
|
|
|
|
const STREET_STATES = ['unbearbeitet', 'zugewiesen', 'erledigt'];
|
|
const STREET_COLORS = {
|
|
unbearbeitet: '#1f6feb',
|
|
zugewiesen: '#d62828',
|
|
erledigt: '#2e9e4f'
|
|
};
|
|
|
|
const state = {
|
|
settings: {...DEFAULT_SETTINGS},
|
|
streets: [],
|
|
streetById: new Map(),
|
|
groups: [],
|
|
groupById: new Map(),
|
|
accounts: [],
|
|
accountById: new Map(),
|
|
me: null,
|
|
currentGroupId: null,
|
|
polylinesByStreetId: new Map(),
|
|
groupMarkers: new Map(),
|
|
currentPolyline: null,
|
|
currentStreetId: null,
|
|
ws: null,
|
|
authenticated: false,
|
|
reconnectTimer: null,
|
|
chatMessages: [],
|
|
chatKeys: new Set(),
|
|
userMarker: null,
|
|
userArrow: null,
|
|
watchId: null
|
|
};
|
|
|
|
const AudioContext = window.AudioContext || window.webkitAudioContext;
|
|
const audioCtx = new AudioContext();
|
|
|
|
let map, osmLayer, aerialLayer, currentBaseLayer;
|
|
|
|
document.addEventListener('DOMContentLoaded', initMobile);
|
|
|
|
async function initMobile() {
|
|
loadSettings();
|
|
initMap();
|
|
bindTabs();
|
|
bindButtons();
|
|
registerServiceWorker();
|
|
initPwaInstall();
|
|
initNotifications();
|
|
|
|
if (viewMode === 'mobile_dispatcher') {
|
|
try {
|
|
const [groups, accounts, me] = await Promise.all([
|
|
fetchJson(`${apiBase}/init/groups`),
|
|
fetchJson(`${apiBase}/init/accounts`).catch(() => []),
|
|
fetchJson(`${apiBase}/init/me`).catch(() => null)
|
|
]);
|
|
state.groups = Array.isArray(groups) ? groups : [];
|
|
state.accounts = Array.isArray(accounts) ? accounts : [];
|
|
state.me = me;
|
|
indexGroups();
|
|
indexAccounts();
|
|
buildGroupSelect();
|
|
const firstGroup = state.groups[0];
|
|
if (firstGroup) {
|
|
await loadGroupData(firstGroup.id);
|
|
}
|
|
} catch (e) {
|
|
console.error(e);
|
|
}
|
|
} else if (viewMode === 'mobile_group') {
|
|
try {
|
|
const [group, accounts, me] = await Promise.all([
|
|
fetchJson(`${apiBase}/groups/me`),
|
|
fetchJson(`${apiBase}/init/accounts`).catch(() => []),
|
|
fetchJson(`${apiBase}/init/me`).catch(() => null)
|
|
]);
|
|
state.accounts = Array.isArray(accounts) ? accounts : [];
|
|
state.me = me;
|
|
indexAccounts();
|
|
if (group && group.id) {
|
|
state.groups = [group];
|
|
state.currentGroupId = group.id;
|
|
indexGroups();
|
|
const nameEl = document.getElementById('groupNameDisplay');
|
|
if (nameEl) nameEl.textContent = groupDisplayName(group);
|
|
await loadGroupData(group.id);
|
|
}
|
|
} catch (e) {
|
|
console.error(e);
|
|
}
|
|
}
|
|
|
|
startGeolocation();
|
|
connectWebSocket();
|
|
window.addEventListener('beforeunload', () => {
|
|
if (state.watchId !== null && navigator.geolocation) {
|
|
navigator.geolocation.clearWatch(state.watchId);
|
|
}
|
|
if (state.ws) state.ws.close();
|
|
});
|
|
}
|
|
|
|
function fetchJson(url, options={}) {
|
|
return fetch(url, {credentials:'same-origin', ...options}).then(r => {
|
|
if (!r.ok) throw new Error(r.status);
|
|
return r.json();
|
|
});
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* Progressive Web App */
|
|
/* ------------------------------------------------------------------ */
|
|
|
|
let deferredInstallPrompt = null;
|
|
|
|
function isStandaloneMode() {
|
|
return window.matchMedia('(display-mode: standalone)').matches
|
|
|| window.navigator.standalone === true;
|
|
}
|
|
|
|
function isIosDevice() {
|
|
return /iphone|ipad|ipod/i.test(navigator.userAgent)
|
|
|| (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
|
|
}
|
|
|
|
function registerServiceWorker() {
|
|
if (!('serviceWorker' in navigator)) return;
|
|
|
|
const swUrl = window.CMBNET_SW_URL || '/sw.js';
|
|
window.addEventListener('load', () => {
|
|
navigator.serviceWorker.register(swUrl).catch(error => {
|
|
console.warn('Service Worker konnte nicht registriert werden.', error);
|
|
});
|
|
});
|
|
}
|
|
|
|
function initPwaInstall() {
|
|
const button = document.getElementById('mobileInstallBtn');
|
|
if (!button) return;
|
|
|
|
if (isStandaloneMode()) {
|
|
button.hidden = true;
|
|
return;
|
|
}
|
|
|
|
// Unter iOS gibt es kein beforeinstallprompt. Dort zeigen wir den Button
|
|
// dauerhaft an und erklären die Installation über das Teilen-Menü.
|
|
if (isIosDevice()) button.hidden = false;
|
|
|
|
window.addEventListener('beforeinstallprompt', event => {
|
|
event.preventDefault();
|
|
deferredInstallPrompt = event;
|
|
button.hidden = false;
|
|
});
|
|
|
|
window.addEventListener('appinstalled', () => {
|
|
deferredInstallPrompt = null;
|
|
button.hidden = true;
|
|
});
|
|
|
|
button.addEventListener('click', async () => {
|
|
if (deferredInstallPrompt) {
|
|
const prompt = deferredInstallPrompt;
|
|
deferredInstallPrompt = null;
|
|
prompt.prompt();
|
|
try {
|
|
const choice = await prompt.userChoice;
|
|
if (choice.outcome === 'accepted') button.hidden = true;
|
|
} catch (error) {
|
|
// Der Dialog kann abgelehnt oder geschlossen werden.
|
|
}
|
|
return;
|
|
}
|
|
|
|
const dialog = document.getElementById('mobileInstallDialog');
|
|
const iosHint = document.getElementById('mobileInstallIosHint');
|
|
const genericHint = document.getElementById('mobileInstallGenericHint');
|
|
if (iosHint) iosHint.hidden = !isIosDevice();
|
|
if (genericHint) genericHint.hidden = isIosDevice();
|
|
|
|
if (dialog && typeof dialog.showModal === 'function') {
|
|
dialog.showModal();
|
|
} else if (dialog) {
|
|
dialog.show();
|
|
}
|
|
});
|
|
}
|
|
|
|
function closeMobileInstall() {
|
|
const dialog = document.getElementById('mobileInstallDialog');
|
|
if (dialog && dialog.open) dialog.close();
|
|
}
|
|
|
|
function initNotifications() {
|
|
const button = document.getElementById('mobileNotifyBtn');
|
|
if (!button) return;
|
|
|
|
button.addEventListener('click', requestNotifications);
|
|
updateNotificationUi();
|
|
}
|
|
|
|
function updateNotificationUi() {
|
|
const button = document.getElementById('mobileNotifyBtn');
|
|
if (!button) return;
|
|
|
|
if (!('Notification' in window)) {
|
|
button.textContent = 'Nicht verfügbar';
|
|
button.disabled = true;
|
|
return;
|
|
}
|
|
|
|
const permission = Notification.permission;
|
|
button.classList.toggle('is-active', permission === 'granted');
|
|
button.disabled = permission === 'denied';
|
|
|
|
if (permission === 'granted') {
|
|
button.textContent = 'Aktiv';
|
|
} else if (permission === 'denied') {
|
|
button.textContent = 'Blockiert';
|
|
} else {
|
|
button.textContent = 'Aktivieren';
|
|
}
|
|
}
|
|
|
|
async function requestNotifications() {
|
|
if (!('Notification' in window)) return;
|
|
|
|
try {
|
|
const permission = await Notification.requestPermission();
|
|
updateNotificationUi();
|
|
|
|
if (permission === 'granted' && navigator.serviceWorker) {
|
|
const registration = await navigator.serviceWorker.getRegistration();
|
|
if (registration && registration.showNotification) {
|
|
await registration.showNotification('CMBNet', {
|
|
body: 'Benachrichtigungen sind aktiviert.',
|
|
icon: window.CMBNET_ICON_URL || undefined,
|
|
tag: 'cmbnet-permission'
|
|
});
|
|
}
|
|
}
|
|
} catch (error) {
|
|
console.warn('Benachrichtigungen konnten nicht aktiviert werden.', error);
|
|
}
|
|
}
|
|
|
|
function loadSettings() {
|
|
try {
|
|
const raw = localStorage.getItem(storageKey);
|
|
if (raw) {
|
|
const saved = JSON.parse(raw);
|
|
state.settings.opacity = typeof saved.opacity === 'number' ? saved.opacity : DEFAULT_SETTINGS.opacity;
|
|
state.settings.weight = typeof saved.weight === 'number' ? saved.weight : DEFAULT_SETTINGS.weight;
|
|
state.settings.baseLayer = saved.baseLayer === 'aerial' ? 'aerial' : 'osm';
|
|
}
|
|
} catch(e) {}
|
|
}
|
|
|
|
function saveSettings() {
|
|
try {
|
|
localStorage.setItem(storageKey, JSON.stringify(state.settings));
|
|
} catch(e) {}
|
|
}
|
|
|
|
function initMap() {
|
|
map = L.map('mobileMap', {zoomControl: false, preferCanvas: true});
|
|
map.setView([51.0, 10.0], 6);
|
|
osmLayer = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {maxZoom: 19});
|
|
aerialLayer = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {maxZoom: 19});
|
|
setBaseLayer(state.settings.baseLayer, false);
|
|
map.on('zoomend', updateAllPolylineStyles);
|
|
}
|
|
|
|
function setBaseLayer(name, persist=true) {
|
|
if (currentBaseLayer) map.removeLayer(currentBaseLayer);
|
|
currentBaseLayer = name === 'aerial' ? aerialLayer : osmLayer;
|
|
currentBaseLayer.addTo(map);
|
|
state.settings.baseLayer = name === 'aerial' ? 'aerial' : 'osm';
|
|
const sel = document.getElementById('mobileBaseLayerSelect');
|
|
if (sel) sel.value = state.settings.baseLayer;
|
|
if (persist) saveSettings();
|
|
}
|
|
|
|
function bindTabs() {
|
|
document.querySelectorAll('.mobile-tab').forEach(btn => {
|
|
btn.addEventListener('click', () => {
|
|
document.querySelectorAll('.mobile-tab').forEach(b => {b.classList.remove('active'); b.setAttribute('aria-selected','false');});
|
|
document.querySelectorAll('.mobile-tab-panel').forEach(p => p.classList.remove('active'));
|
|
btn.classList.add('active');
|
|
btn.setAttribute('aria-selected','true');
|
|
const panel = document.getElementById(`tab-${btn.dataset.tab}`);
|
|
if (panel) panel.classList.add('active');
|
|
if (btn.dataset.tab === 'chat') {
|
|
const cont = document.getElementById('mobileChatMessages');
|
|
if (cont) cont.scrollTop = cont.scrollHeight;
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
function bindButtons() {
|
|
const logout = document.getElementById('mobileLogout');
|
|
if (logout) logout.addEventListener('click', () => {window.location.href = window.CMBNET_LOGOUT_URL || '/';});
|
|
|
|
const todoBtn = document.getElementById('mobileTodoBtn');
|
|
if (todoBtn) todoBtn.addEventListener('click', openStreetSelectDialog);
|
|
|
|
const settingsBtn = document.getElementById('mobileSettingsBtn');
|
|
if (settingsBtn) settingsBtn.addEventListener('click', openSettingsDialog);
|
|
|
|
const workBtn = document.getElementById('mobileWorkBtn');
|
|
if (workBtn) workBtn.addEventListener('click', openStreetStateDialog);
|
|
|
|
const chatForm = document.getElementById('mobileChatForm');
|
|
if (chatForm) {
|
|
chatForm.addEventListener('submit', (e) => {
|
|
e.preventDefault();
|
|
sendChat();
|
|
});
|
|
}
|
|
|
|
const groupSel = document.getElementById('mobileGroupSelect');
|
|
if (groupSel) {
|
|
groupSel.addEventListener('change', () => {
|
|
loadGroupData(groupSel.value);
|
|
});
|
|
}
|
|
|
|
// Settings
|
|
const opacitySlider = document.getElementById('mobileOpacitySlider');
|
|
if (opacitySlider) {
|
|
opacitySlider.addEventListener('input', (e) => {
|
|
state.settings.opacity = Number(e.target.value);
|
|
const out = document.getElementById('mobileOpacityValue');
|
|
if (out) out.textContent = state.settings.opacity.toFixed(2);
|
|
updateAllPolylineStyles();
|
|
saveSettings();
|
|
});
|
|
}
|
|
const weightSlider = document.getElementById('mobileWeightSlider');
|
|
if (weightSlider) {
|
|
weightSlider.addEventListener('input', (e) => {
|
|
state.settings.weight = Number(e.target.value);
|
|
const out = document.getElementById('mobileWeightValue');
|
|
if (out) out.textContent = `${state.settings.weight} m`;
|
|
updateAllPolylineStyles();
|
|
saveSettings();
|
|
});
|
|
}
|
|
const baseSel = document.getElementById('mobileBaseLayerSelect');
|
|
if (baseSel) {
|
|
baseSel.addEventListener('change', (e) => setBaseLayer(e.target.value));
|
|
}
|
|
}
|
|
|
|
function indexGroups() {
|
|
state.groupById.clear();
|
|
state.groups.forEach(g => {
|
|
g.id = Number(g.id);
|
|
state.groupById.set(g.id, g);
|
|
});
|
|
}
|
|
|
|
function indexAccounts() {
|
|
state.accountById.clear();
|
|
state.accounts.forEach(account => {
|
|
const id = Number(account.id);
|
|
if (!Number.isFinite(id)) return;
|
|
account.id = id;
|
|
state.accountById.set(id, account);
|
|
});
|
|
}
|
|
|
|
function groupDisplayName(group) {
|
|
if (!group) return 'Gruppe';
|
|
const alias = group.aliasname && String(group.aliasname).trim();
|
|
return alias || 'Gruppe';
|
|
}
|
|
|
|
function findGroupForAccount(accountId) {
|
|
const id = Number(accountId);
|
|
return state.groups.find(group => Number(group.account_id) === id) || null;
|
|
}
|
|
|
|
/**
|
|
* Formatiert "Accountname" bzw. "Accountname (Gruppe: Alias)".
|
|
*/
|
|
function formatPersonName(name, role, groupAlias) {
|
|
const base = String(name || '').trim() || 'Unbekannt';
|
|
const alias = groupAlias && String(groupAlias).trim();
|
|
if (alias) return `${base} (Gruppe: ${alias})`;
|
|
if (role === 'Gruppe') return `${base} (Gruppe)`;
|
|
return base;
|
|
}
|
|
|
|
function getAccount(accountId) {
|
|
const id = Number(accountId);
|
|
if (!Number.isFinite(id)) return null;
|
|
return state.accountById.get(id) || null;
|
|
}
|
|
|
|
function getAccountDisplayName(accountId) {
|
|
const id = Number(accountId);
|
|
if (!Number.isFinite(id)) return null;
|
|
|
|
const account = getAccount(id);
|
|
if (account) {
|
|
const group = findGroupForAccount(id);
|
|
return formatPersonName(account.name, account.role, group ? group.aliasname : null);
|
|
}
|
|
|
|
if (state.me && Number(state.me.id) === id) {
|
|
const group = findGroupForAccount(id);
|
|
return formatPersonName(
|
|
state.me.name,
|
|
state.me.role,
|
|
group ? group.aliasname : null
|
|
);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
function getSenderName(message, payload) {
|
|
const payloadSender = payload && typeof payload.sender === 'object'
|
|
? payload.sender
|
|
: null;
|
|
|
|
if (payloadSender && payloadSender.name) {
|
|
return formatPersonName(
|
|
payloadSender.name,
|
|
payloadSender.role,
|
|
payloadSender.group_alias
|
|
);
|
|
}
|
|
|
|
const senderId = Number(message.sender_id);
|
|
const known = getAccountDisplayName(senderId);
|
|
if (known) return known;
|
|
|
|
if (state.me && senderId === Number(state.me.id)) {
|
|
return formatPersonName(state.me.name, state.me.role, null);
|
|
}
|
|
|
|
return 'Unbekannt';
|
|
}
|
|
|
|
function getReceiverName(message, payload) {
|
|
const code = Number(message.code);
|
|
if (code === 1000 || (payload && payload.broadcast)) return 'alle';
|
|
|
|
const payloadSender = payload && typeof payload.sender === 'object'
|
|
? payload.sender
|
|
: null;
|
|
const senderRole = payloadSender?.role || getAccount(message.sender_id)?.role;
|
|
if (code === 2000 && senderRole === 'Gruppe') {
|
|
// Gruppen senden mit Code 2000 an Dispatcher und Beobachter.
|
|
return 'Dispatcher';
|
|
}
|
|
|
|
let receiverId = Number(message.receiver_id);
|
|
if (!Number.isFinite(receiverId) || receiverId <= 0) {
|
|
if (payload && payload.group_id !== undefined) {
|
|
receiverId = Number(payload.group_id);
|
|
} else if (payload && payload.receiver_id !== undefined) {
|
|
receiverId = Number(payload.receiver_id);
|
|
}
|
|
}
|
|
|
|
if (!Number.isFinite(receiverId) || receiverId <= 0) return 'alle';
|
|
|
|
let group = state.groupById.get(receiverId);
|
|
if (!group && receiverId === Number(state.currentGroupId) && state.groups.length) {
|
|
group = state.groups[0];
|
|
}
|
|
if (group) {
|
|
const accountName = getAccountDisplayName(group.account_id);
|
|
return accountName || groupDisplayName(group) || 'Gruppe';
|
|
}
|
|
|
|
const accountName = getAccountDisplayName(receiverId);
|
|
if (accountName) return accountName;
|
|
|
|
return 'Unbekannt';
|
|
}
|
|
|
|
|
|
function buildGroupSelect() {
|
|
const sel = document.getElementById('mobileGroupSelect');
|
|
if (!sel) return;
|
|
sel.innerHTML = '';
|
|
state.groups.forEach(g => {
|
|
const opt = document.createElement('option');
|
|
opt.value = g.id;
|
|
opt.textContent = g.aliasname || g.id;
|
|
sel.appendChild(opt);
|
|
});
|
|
}
|
|
|
|
async function loadGroupData(groupId) {
|
|
groupId = Number(groupId);
|
|
state.currentGroupId = groupId;
|
|
const sel = document.getElementById('mobileGroupSelect');
|
|
if (sel && viewMode === 'mobile_dispatcher') sel.value = String(groupId);
|
|
|
|
clearPolylines();
|
|
if (state.currentPolyline) {
|
|
map.removeLayer(state.currentPolyline);
|
|
state.currentPolyline = null;
|
|
}
|
|
state.currentStreetId = null;
|
|
|
|
try {
|
|
const streets = await fetchJson(`${apiBase}/init/groups/${groupId}/streets`);
|
|
state.streets = Array.isArray(streets) ? streets : [];
|
|
indexStreets();
|
|
buildStreetList();
|
|
if (state.streets.length) {
|
|
const first = state.streets[0];
|
|
state.currentStreetId = first.id;
|
|
loadStreetPolyline(first.name);
|
|
fitToPositionAndPolyline();
|
|
updateWorkButton();
|
|
} else {
|
|
updateWorkButton();
|
|
}
|
|
} catch(e) {
|
|
console.error(e);
|
|
}
|
|
|
|
// Show all group positions like observer (only for dispatcher mobile)
|
|
if (viewMode === 'mobile_dispatcher') {
|
|
showAllGroupPositions();
|
|
}
|
|
}
|
|
|
|
function indexStreets() {
|
|
state.streetById.clear();
|
|
state.streets.forEach(s => {
|
|
s.id = Number(s.id);
|
|
state.streetById.set(s.id, s);
|
|
});
|
|
}
|
|
|
|
function buildStreetList() {
|
|
const list = document.getElementById('mobileStreetList');
|
|
if (!list) return;
|
|
list.innerHTML = '';
|
|
state.streets.forEach(street => {
|
|
const li = document.createElement('li');
|
|
const btn = document.createElement('button');
|
|
btn.type = 'button';
|
|
btn.className = 'mobile-street-item';
|
|
if (state.currentStreetId == street.id) btn.classList.add('active');
|
|
btn.textContent = `${street.name} (${street.state || 'unbearbeitet'})`;
|
|
btn.addEventListener('click', () => {
|
|
selectStreet(street);
|
|
closeMobileStreetSelect();
|
|
});
|
|
li.appendChild(btn);
|
|
list.appendChild(li);
|
|
});
|
|
}
|
|
|
|
function selectStreet(street) {
|
|
state.currentStreetId = street.id;
|
|
if (state.currentPolyline) {
|
|
map.removeLayer(state.currentPolyline);
|
|
state.currentPolyline = null;
|
|
}
|
|
loadStreetPolyline(street.name);
|
|
fitToPositionAndPolyline();
|
|
updateWorkButton();
|
|
buildStreetList();
|
|
}
|
|
|
|
function getStreetFragments() {
|
|
if (typeof STRASSE2POLYLINES !== 'undefined') return STRASSE2POLYLINES;
|
|
if (typeof Strasse2Polylines !== 'undefined') return Strasse2Polylines;
|
|
return window.STRASSE2POLYLINES || window.Strasse2Polylines || {};
|
|
}
|
|
|
|
function loadStreetPolyline(name) {
|
|
const fragments = getStreetFragments();
|
|
const segments = fragments[name];
|
|
if (!Array.isArray(segments)) return;
|
|
const latlngs = [];
|
|
segments.forEach(seg => {
|
|
if (!Array.isArray(seg)) return;
|
|
seg.forEach(pt => {
|
|
if (!Array.isArray(pt) || pt.length < 2) return;
|
|
// try lat,lng or lng,lat
|
|
const a = Number(pt[0]), b = Number(pt[1]);
|
|
if (!Number.isFinite(a) || !Number.isFinite(b)) return;
|
|
if (Math.abs(a) <= 90 && Math.abs(b) <= 180) latlngs.push([a,b]);
|
|
else if (Math.abs(b) <= 90 && Math.abs(a) <= 180) latlngs.push([b,a]);
|
|
});
|
|
});
|
|
if (latlngs.length < 2) return;
|
|
const street = state.streetById.get(Number(state.currentStreetId));
|
|
const color = STREET_COLORS[street?.state] || STREET_COLORS.unbearbeitet;
|
|
state.currentPolyline = L.polyline(latlngs, {
|
|
color, opacity: state.settings.opacity, weight: state.settings.weight, lineCap: 'round', lineJoin: 'round'
|
|
}).addTo(map);
|
|
}
|
|
|
|
function clearPolylines() {
|
|
state.polylinesByStreetId.forEach(lines => {
|
|
if (Array.isArray(lines)) lines.forEach(l => map.removeLayer(l));
|
|
});
|
|
state.polylinesByStreetId.clear();
|
|
}
|
|
|
|
function updateAllPolylineStyles() {
|
|
if (state.currentPolyline) {
|
|
state.currentPolyline.setStyle({opacity: state.settings.opacity, weight: state.settings.weight});
|
|
}
|
|
}
|
|
|
|
function fitToPositionAndPolyline() {
|
|
const bounds = L.latLngBounds([]);
|
|
if (state.currentPolyline) {
|
|
state.currentPolyline.getLatLngs().forEach(ll => {
|
|
if (Array.isArray(ll)) ll.forEach(p => bounds.extend(p));
|
|
else bounds.extend(ll);
|
|
});
|
|
}
|
|
if (state.userMarker) {
|
|
bounds.extend(state.userMarker.getLatLng());
|
|
}
|
|
if (bounds.isValid()) {
|
|
map.fitBounds(bounds, {padding: [40, 40], maxZoom: 17});
|
|
}
|
|
}
|
|
|
|
function updateWorkButton() {
|
|
const btn = document.getElementById('mobileWorkBtn');
|
|
if (!btn) return;
|
|
btn.disabled = !state.currentStreetId;
|
|
}
|
|
|
|
function openStreetSelectDialog() {
|
|
buildStreetList();
|
|
const dlg = document.getElementById('mobileStreetSelectDialog');
|
|
if (dlg && typeof dlg.showModal === 'function') dlg.showModal();
|
|
else if (dlg) dlg.show();
|
|
}
|
|
|
|
function closeMobileStreetSelect() {
|
|
const dlg = document.getElementById('mobileStreetSelectDialog');
|
|
if (dlg && dlg.open) dlg.close();
|
|
}
|
|
|
|
function openStreetStateDialog() {
|
|
const street = state.streetById.get(Number(state.currentStreetId));
|
|
if (!street) {
|
|
alert('Bitte erst eine Straße auswählen.');
|
|
return;
|
|
}
|
|
document.getElementById('mobileStreetStateTitle').textContent = `Straße: ${street.name}`;
|
|
document.getElementById('mobileStreetStateSelect').value = street.state || 'unbearbeitet';
|
|
fillMobileStreetGroupSelect(street.group_id);
|
|
updateMobileStreetGroupVisibility();
|
|
const dlg = document.getElementById('mobileStreetStateDialog');
|
|
if (dlg && typeof dlg.showModal === 'function') dlg.showModal();
|
|
else if (dlg) dlg.show();
|
|
}
|
|
|
|
function closeMobileStreetState() {
|
|
const dlg = document.getElementById('mobileStreetStateDialog');
|
|
if (dlg && dlg.open) dlg.close();
|
|
}
|
|
|
|
function fillMobileStreetGroupSelect(selected) {
|
|
const sel = document.getElementById('mobileStreetGroupSelect');
|
|
if (!sel) return;
|
|
sel.innerHTML = '';
|
|
const empty = document.createElement('option');
|
|
empty.value = '';
|
|
empty.textContent = '-';
|
|
sel.appendChild(empty);
|
|
state.groups.forEach(g => {
|
|
const opt = document.createElement('option');
|
|
opt.value = g.id;
|
|
opt.textContent = g.aliasname || g.id;
|
|
if (Number(selected) === g.id) opt.selected = true;
|
|
sel.appendChild(opt);
|
|
});
|
|
}
|
|
|
|
function updateMobileStreetGroupVisibility() {
|
|
const stateSel = document.getElementById('mobileStreetStateSelect');
|
|
const groupSel = document.getElementById('mobileStreetGroupSelect');
|
|
const label = document.getElementById('mobileStreetGroupLabel');
|
|
const enabled = stateSel && stateSel.value === 'zugewiesen';
|
|
if (groupSel) groupSel.disabled = !enabled;
|
|
if (label) label.style.opacity = enabled ? '1' : '0.5';
|
|
}
|
|
|
|
document.getElementById('mobileStreetStateSelect')?.addEventListener('change', updateMobileStreetGroupVisibility);
|
|
|
|
function saveMobileStreetState() {
|
|
const street = state.streetById.get(Number(state.currentStreetId));
|
|
if (!street) return;
|
|
const newState = document.getElementById('mobileStreetStateSelect').value;
|
|
if (!STREET_STATES.includes(newState)) return;
|
|
let groupId = null;
|
|
if (newState === 'zugewiesen') {
|
|
groupId = Number(document.getElementById('mobileStreetGroupSelect').value) || null;
|
|
if (!groupId) { alert('Bitte eine Gruppe auswählen.'); return; }
|
|
} else if (newState === 'erledigt' && street.group_id) {
|
|
groupId = Number(street.group_id);
|
|
}
|
|
if (state.ws && state.ws.readyState === WebSocket.OPEN && state.authenticated) {
|
|
state.ws.send(JSON.stringify({
|
|
code: 100,
|
|
msg: JSON.stringify({name: street.name, state: newState, actor: currentAccountId, street_id: street.id, group_id: groupId})
|
|
}));
|
|
}
|
|
closeMobileStreetState();
|
|
}
|
|
|
|
function openSettingsDialog() {
|
|
const opacitySlider = document.getElementById('mobileOpacitySlider');
|
|
const weightSlider = document.getElementById('mobileWeightSlider');
|
|
if (opacitySlider) { opacitySlider.value = state.settings.opacity; document.getElementById('mobileOpacityValue').textContent = state.settings.opacity.toFixed(2); }
|
|
if (weightSlider) { weightSlider.value = state.settings.weight; document.getElementById('mobileWeightValue').textContent = `${state.settings.weight} m`; }
|
|
const baseSel = document.getElementById('mobileBaseLayerSelect');
|
|
if (baseSel) baseSel.value = state.settings.baseLayer;
|
|
const dlg = document.getElementById('mobileSettingsDialog');
|
|
if (dlg && typeof dlg.showModal === 'function') dlg.showModal();
|
|
else if (dlg) dlg.show();
|
|
}
|
|
|
|
function closeMobileSettings() {
|
|
const dlg = document.getElementById('mobileSettingsDialog');
|
|
if (dlg && dlg.open) dlg.close();
|
|
}
|
|
|
|
function startGeolocation() {
|
|
if (!navigator.geolocation) return;
|
|
if (state.userMarker) {
|
|
map.removeLayer(state.userMarker);
|
|
state.userMarker = null;
|
|
}
|
|
if (state.userArrow) {
|
|
map.removeLayer(state.userArrow);
|
|
state.userArrow = null;
|
|
}
|
|
const icon = L.divIcon({
|
|
className: 'mobile-user-marker',
|
|
html: '<div class="mobile-user-dot"></div><div class="mobile-user-arrow" id="mobileUserArrow"></div>',
|
|
iconSize: [16, 16],
|
|
iconAnchor: [8, 8]
|
|
});
|
|
state.userMarker = L.marker(map.getCenter(), {icon, interactive: false}).addTo(map);
|
|
state.userArrow = document.getElementById('mobileUserArrow');
|
|
|
|
state.watchId = navigator.geolocation.watchPosition((pos) => {
|
|
const latlng = [pos.coords.latitude, pos.coords.longitude];
|
|
state.userMarker.setLatLng(latlng);
|
|
}, (err) => {
|
|
console.warn(err);
|
|
}, {enableHighAccuracy: true, maximumAge: 2000, timeout: 10000});
|
|
|
|
if (window.DeviceOrientationEvent) {
|
|
window.addEventListener('deviceorientationabsolute', handleOrientation, true);
|
|
window.addEventListener('deviceorientation', handleOrientation, true);
|
|
}
|
|
}
|
|
|
|
function handleOrientation(e) {
|
|
let heading = e.alpha;
|
|
if (typeof e.webkitCompassHeading === 'number') {
|
|
heading = e.webkitCompassHeading;
|
|
}
|
|
if (typeof heading !== 'number' || isNaN(heading)) return;
|
|
if (state.userArrow) {
|
|
state.userArrow.style.transform = `translate(-50%, -100%) rotate(${heading}deg)`;
|
|
}
|
|
}
|
|
|
|
function showAllGroupPositions() {
|
|
// Remove old markers
|
|
state.groupMarkers.forEach(m => map.removeLayer(m));
|
|
state.groupMarkers.clear();
|
|
|
|
state.groups.forEach(group => {
|
|
if (group.last_lat !== null && group.last_lat !== undefined && group.last_lon !== null && group.last_lon !== undefined) {
|
|
const lat = Number(group.last_lat), lon = Number(group.last_lon);
|
|
if (!isFinite(lat) || !isFinite(lon)) return;
|
|
const color = getGroupColor(group.id);
|
|
const icon = L.divIcon({
|
|
className: 'mobile-group-marker',
|
|
html: `<div class="mobile-group-dot" style="--marker-color:${color}"></div>`,
|
|
iconSize: [14, 14],
|
|
iconAnchor: [7, 7]
|
|
});
|
|
const marker = L.marker([lat, lon], {icon}).addTo(map);
|
|
marker.bindTooltip(group.aliasname || String(group.id));
|
|
state.groupMarkers.set(group.id, marker);
|
|
}
|
|
});
|
|
}
|
|
|
|
function getGroupColor(id) {
|
|
const hue = Math.round((Number(id) * 137.508) % 360);
|
|
return `hsl(${hue}, 72%, 45%)`;
|
|
}
|
|
|
|
function connectWebSocket() {
|
|
if (state.ws && (state.ws.readyState === WebSocket.OPEN || state.ws.readyState === WebSocket.CONNECTING)) return;
|
|
fetchJson(`${apiBase}/auth/ws-token`).then(res => {
|
|
const token = res.token;
|
|
const ws = new WebSocket(wsUrl);
|
|
state.ws = ws;
|
|
ws.addEventListener('open', () => {
|
|
ws.send(JSON.stringify({code: 0, msg: token}));
|
|
state.authenticated = true;
|
|
});
|
|
ws.addEventListener('message', handleWs);
|
|
ws.addEventListener('close', () => {
|
|
state.authenticated = false;
|
|
setTimeout(connectWebSocket, 3000);
|
|
});
|
|
}).catch(() => {
|
|
setTimeout(connectWebSocket, 3000);
|
|
});
|
|
}
|
|
|
|
function sendChat() {
|
|
const input = document.getElementById('mobileChatInput');
|
|
if (!input) return;
|
|
const text = input.value.trim();
|
|
if (!text) return;
|
|
if (!state.ws || state.ws.readyState !== WebSocket.OPEN || !state.authenticated) return;
|
|
|
|
if (viewMode === 'mobile_group' && state.currentGroupId) {
|
|
state.ws.send(JSON.stringify({code: 2000, msg: JSON.stringify({group_id: state.currentGroupId, text})}));
|
|
} else if (viewMode === 'mobile_dispatcher') {
|
|
// For dispatcher mobile, could send 1000 broadcast or 1100 - follow general behavior
|
|
state.ws.send(JSON.stringify({code: 1000, msg: JSON.stringify({text})}));
|
|
}
|
|
input.value = '';
|
|
}
|
|
|
|
function addChatEntry(entry) {
|
|
const key = `${entry.code}|${entry.sender_id}|${entry.ts}|${entry.text}`;
|
|
if (state.chatKeys.has(key)) return;
|
|
state.chatKeys.add(key);
|
|
state.chatMessages.push(entry);
|
|
renderChat();
|
|
}
|
|
|
|
function renderChat() {
|
|
const cont = document.getElementById('mobileChatMessages');
|
|
if (!cont) return;
|
|
cont.innerHTML = '';
|
|
state.chatMessages.slice().sort((a,b) => a.ts - b.ts).forEach(entry => {
|
|
const card = document.createElement('div');
|
|
card.className = 'mobile-chat-card';
|
|
if (entry.sender_id == currentAccountId) card.classList.add('own');
|
|
const meta = document.createElement('div');
|
|
meta.className = 'mobile-chat-meta';
|
|
meta.textContent = new Date(entry.ts).toLocaleString('de-DE');
|
|
const fromto = document.createElement('div');
|
|
fromto.className = 'mobile-chat-fromto';
|
|
const fromName = entry.fromName
|
|
|| getSenderName({sender_id: entry.sender_id}, null);
|
|
const toName = entry.toName
|
|
|| (Number(entry.code) === 1000 ? 'alle' : 'Unbekannt');
|
|
fromto.textContent = `${fromName} -> ${toName}`;
|
|
const text = document.createElement('div');
|
|
text.className = 'mobile-chat-text';
|
|
text.textContent = entry.text;
|
|
card.append(meta, fromto, text);
|
|
cont.appendChild(card);
|
|
});
|
|
cont.scrollTop = cont.scrollHeight;
|
|
}
|
|
|
|
function playSound() {
|
|
try {
|
|
if (audioCtx.state === 'suspended') audioCtx.resume();
|
|
const osc = audioCtx.createOscillator();
|
|
const gain = audioCtx.createGain();
|
|
osc.connect(gain);
|
|
gain.connect(audioCtx.destination);
|
|
osc.frequency.setValueAtTime(880, audioCtx.currentTime);
|
|
osc.frequency.exponentialRampToValueAtTime(440, audioCtx.currentTime + 0.15);
|
|
gain.gain.setValueAtTime(0.1, audioCtx.currentTime);
|
|
gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.3);
|
|
osc.start(audioCtx.currentTime);
|
|
osc.stop(audioCtx.currentTime + 0.3);
|
|
} catch(e) {}
|
|
}
|
|
|
|
async function showChatPopup(text, senderName) {
|
|
if (!('Notification' in window) || Notification.permission !== 'granted') return;
|
|
|
|
const options = {
|
|
body: text,
|
|
icon: window.CMBNET_ICON_URL || undefined,
|
|
badge: window.CMBNET_ICON_URL || undefined,
|
|
tag: 'cmbnet-chat',
|
|
renotify: true,
|
|
data: {url: window.location.href}
|
|
};
|
|
|
|
try {
|
|
if (navigator.serviceWorker) {
|
|
const registration = await navigator.serviceWorker.getRegistration();
|
|
if (registration && registration.showNotification) {
|
|
await registration.showNotification(senderName || 'CMBNet', options);
|
|
return;
|
|
}
|
|
}
|
|
new Notification(senderName || 'CMBNet', options);
|
|
} catch (error) {
|
|
// Benachrichtigungen sind optional.
|
|
}
|
|
}
|
|
|
|
function extractText(msg) {
|
|
if (!msg) return '';
|
|
if (typeof msg === 'object') {
|
|
if (msg.text) return String(msg.text);
|
|
if (msg.msg) return extractText(msg.msg);
|
|
return '';
|
|
}
|
|
if (typeof msg === 'string') {
|
|
try {
|
|
const p = JSON.parse(msg);
|
|
if (typeof p === 'object') return extractText(p);
|
|
} catch(e) {}
|
|
const idx = msg.indexOf(':');
|
|
if (idx > 0 && idx < 80) return msg.slice(idx+1).trim();
|
|
return msg;
|
|
}
|
|
return String(msg);
|
|
}
|
|
|
|
function parseMessagePayload(value) {
|
|
if (value && typeof value === 'object') return value;
|
|
if (typeof value !== 'string') return null;
|
|
try {
|
|
const parsed = JSON.parse(value);
|
|
return parsed && typeof parsed === 'object' ? parsed : null;
|
|
} catch (e) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function normalizeTs(value) {
|
|
const number = Number(value);
|
|
if (!Number.isFinite(number) || number <= 0) return null;
|
|
return number < 1e12 ? number * 1000 : number;
|
|
}
|
|
|
|
function handleWs(event) {
|
|
let message;
|
|
try { message = JSON.parse(event.data); } catch(e) { return; }
|
|
|
|
if (message.code === 0) {
|
|
state.authenticated = true;
|
|
} else if (message.code === 1) {
|
|
if (state.ws && state.ws.readyState === WebSocket.OPEN) {
|
|
state.ws.send(JSON.stringify({code: 2, msg: 'pong'}));
|
|
}
|
|
} else if (message.code === 100) {
|
|
// Street update
|
|
try {
|
|
const p = typeof message.msg === 'string' ? JSON.parse(message.msg) : message.msg;
|
|
if (p && p.street_id) {
|
|
const street = state.streetById.get(Number(p.street_id));
|
|
if (street) {
|
|
if (p.state) street.state = p.state;
|
|
if (p.group_id !== undefined) street.group_id = p.group_id;
|
|
if (state.currentStreetId == street.id && state.currentPolyline) {
|
|
state.currentPolyline.setStyle({color: STREET_COLORS[street.state] || STREET_COLORS.unbearbeitet});
|
|
}
|
|
buildStreetList();
|
|
}
|
|
}
|
|
} catch(e) {}
|
|
} else if (message.code === 300) {
|
|
// Group position
|
|
try {
|
|
const p = typeof message.msg === 'string' ? JSON.parse(message.msg) : message.msg;
|
|
const gid = Number(p.group_id || message.receiver_id);
|
|
const g = state.groupById.get(gid);
|
|
if (g && p.lat && p.lon) {
|
|
g.last_lat = p.lat; g.last_lon = p.lon;
|
|
if (viewMode === 'mobile_dispatcher') showAllGroupPositions();
|
|
}
|
|
} catch(e) {}
|
|
} else if (message.code === 2000 || message.code === 1000 || message.code === 1100) {
|
|
// Chat messages
|
|
const payload = parseMessagePayload(message.msg);
|
|
const text = extractText(payload ?? message.msg);
|
|
|
|
// Im Gruppen-View nur Nachrichten an alle oder an die eigene Gruppe.
|
|
if (viewMode === 'mobile_group') {
|
|
const gid = Number(payload?.group_id ?? message.receiver_id);
|
|
const ownGroupId = Number(state.currentGroupId);
|
|
if (Number.isFinite(gid) && gid > 0 && ownGroupId && gid !== ownGroupId) {
|
|
return;
|
|
}
|
|
}
|
|
|
|
addChatEntry({
|
|
sender_id: message.sender_id,
|
|
code: message.code,
|
|
ts: normalizeTs(message.ts) || Date.now(),
|
|
text,
|
|
fromName: getSenderName(message, payload),
|
|
toName: getReceiverName(message, payload)
|
|
});
|
|
|
|
if (Number(message.sender_id) !== currentAccountId) {
|
|
playSound();
|
|
showChatPopup(text, getSenderName(message, payload));
|
|
// Switch to chat tab
|
|
document.querySelectorAll('.mobile-tab').forEach(b => {
|
|
if (b.dataset.tab === 'chat') b.click();
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
window.openMobileStreetSelect = openStreetSelectDialog;
|
|
window.closeMobileStreetSelect = closeMobileStreetSelect;
|
|
window.closeMobileStreetState = closeMobileStreetState;
|
|
window.saveMobileStreetState = saveMobileStreetState;
|
|
window.closeMobileSettings = closeMobileSettings;
|
|
window.closeMobileInstall = closeMobileInstall;
|