Upload via GUI (23 Dateien)

This commit is contained in:
2026-11-01 11:15:09 +00:00
parent c57918c86f
commit ba32f72275
19 changed files with 1073 additions and 73 deletions
+77 -16
View File
@@ -1,5 +1,6 @@
// Gemeinsamer Kern von Popup und Hintergrunddienst: Serveradresse, Anmeldung, API-Aufrufe, Hilfsfunktionen.
// Gemeinsamer Kern von Oberfläche und Hintergrunddienst: Serveradresse, Anmeldung, API-Aufrufe, Hilfsfunktionen.
// Das Anmelde-Token liegt nur in chrome.storage.local dieser Erweiterung (nie in sync, nie im Seitencode).
// Der Zugriff auf den Server ist im Manifest erlaubt (host_permissions): Es gibt keine Rückfrage beim Anmelden.
export class ApiError extends Error {
constructor(status, code, message) { super(message); this.status = status; this.code = code; }
@@ -25,11 +26,15 @@ export async function getSession() {
return session && session.token && session.serverUrl ? session : null;
}
export const setSession = (session) => chrome.storage.local.set({ session });
export async function clearSession() { await chrome.storage.local.remove(['session', 'lastSeen', 'badgeCount', 'meta']); }
export async function clearSession() {
const drafts = Object.keys(await chrome.storage.local.get(null)).filter((k) => k.startsWith('draft:')); // nicht gesendete Entwürfe gehören zur Anmeldung
await chrome.storage.local.remove(['session', 'lastSeen', 'badgeCount', 'meta', ...drafts]);
}
export const DEFAULT_SETTINGS = { notifications: true, notifyUnassigned: true, notifyMine: true, theme: 'auto', compact: false };
export async function getSettings() {
const { settings } = await chrome.storage.local.get('settings');
return { notifications: true, ...(settings || {}) };
return { ...DEFAULT_SETTINGS, ...(settings || {}) };
}
export const setSettings = (settings) => chrome.storage.local.set({ settings });
@@ -40,13 +45,13 @@ export async function apiCall(path, { method = 'GET', query, body, auth = true,
if (!base) throw new ApiError(401, 'UNAUTHENTICATED', 'Nicht angemeldet.');
const url = new URL(`${base}/api/staff/v1/${path}`);
for (const [k, v] of Object.entries(query || {})) if (v !== undefined && v !== null && v !== '') url.searchParams.set(k, String(v));
const headers = { Accept: 'application/json', 'Cache-Control': 'no-cache' };
const headers = { Accept: 'application/json' };
if (auth) {
if (!session?.token) throw new ApiError(401, 'UNAUTHENTICATED', 'Nicht angemeldet.');
headers.Authorization = `Bearer ${session.token}`;
headers['X-DeskHub-Authorization'] = `Bearer ${session.token}`;
}
const init = { method, headers, redirect: 'error', credentials: 'omit', signal: signal || AbortSignal.timeout(30000) };
const init = { method, headers, redirect: 'error', credentials: 'omit', cache: 'no-store', signal: signal || AbortSignal.timeout(30000) };
if (body !== undefined && method !== 'GET') { headers['Content-Type'] = 'application/json'; init.body = JSON.stringify(body); }
let res;
try { res = await fetch(url, init); } catch { throw new ApiError(0, 'NETWORK', 'Server nicht erreichbar.'); }
@@ -60,17 +65,24 @@ export async function apiCall(path, { method = 'GET', query, body, auth = true,
return { status: res.status, data };
}
/** Fragt bei Bedarf die Berechtigung für genau diesen Server ab (nur diese eine Adresse, nicht „alle Webseiten“). Muss aus einem Klick heraus aufgerufen werden. */
export async function ensureHostPermission(serverUrl) {
const pattern = new URL(serverUrl).origin + '/*';
if (await chrome.permissions.contains({ origins: [pattern] })) return true;
return chrome.permissions.request({ origins: [pattern] });
/**
* Schickt eine POST-Anfrage los, ohne auf etwas zu warten (für „beim Verlassen aufräumen“). Läuft synchron mit keepalive und überlebt deshalb
* das Schließen des Popups, das sich bei jedem Klick daneben schließt. Die Sitzung wird übergeben, weil ein Speicherzugriff dafür zu spät käme.
*/
export function apiBeacon(session, path, body) {
if (!session?.token || !session?.serverUrl) return;
try {
fetch(`${session.serverUrl}/api/staff/v1/${path}`, {
method: 'POST', keepalive: true, redirect: 'error', credentials: 'omit', cache: 'no-store',
headers: { Accept: 'application/json', 'Content-Type': 'application/json', Authorization: `Bearer ${session.token}`, 'X-DeskHub-Authorization': `Bearer ${session.token}` },
body: JSON.stringify(body),
}).catch(() => {});
} catch { /* egal */ }
}
/** Meldet an. @returns {{requiresTotp:true}|{session:object}} */
export async function login(serverUrlInput, email, password, totpCode) {
const serverUrl = normalizeServerUrl(serverUrlInput);
if (!(await ensureHostPermission(serverUrl))) throw new Error('Ohne Erlaubnis für diesen Server kann sich die Erweiterung nicht anmelden.');
const { status, data } = await apiCall('login.php', {
method: 'POST', auth: false, serverUrl,
body: { email, password, totpCode: totpCode || null, deviceName: 'Chrome-Erweiterung' },
@@ -81,16 +93,27 @@ export async function login(serverUrlInput, email, password, totpCode) {
return { session };
}
/** Meldet ab (Token auf dem Server sperren) und entfernt Daten und Berechtigung dieses Servers. */
/** Meldet ab: Token auf dem Server sperren und lokale Daten entfernen. */
export async function logout() {
const session = await getSession();
if (session) {
try { await apiCall('logout.php', { method: 'POST', body: {} }); } catch { /* Token läuft ohnehin ab */ }
try { await chrome.permissions.remove({ origins: [new URL(session.serverUrl).origin + '/*'] }); } catch { /* ignorieren */ }
}
if (session) { try { await apiCall('logout.php', { method: 'POST', body: {} }); } catch { /* Token läuft ohnehin ab */ } }
await clearSession();
}
/** Stammdaten (Abteilungen, Prioritäten, Mitarbeiter, Status, Tags) – 10 Minuten zwischengespeichert. */
export async function getMeta(force = false) {
const { meta } = await chrome.storage.local.get('meta');
if (!force && meta && Date.now() - meta.at < 10 * 60 * 1000) return meta;
const { data } = await apiCall('metadata.php');
const fresh = {
at: Date.now(),
departments: (data.departments || []).filter((d) => !/\(deaktiviert\)$/.test(d.name)),
priorities: data.priorities || [], agents: data.agents || [], statuses: data.statuses || [], tags: data.tags || [],
};
await chrome.storage.local.set({ meta: fresh });
return fresh;
}
/** Pfad eines Tickets in der Weboberfläche. Nur Ticketnummern im bekannten Format. */
export function ticketPath(number) {
const n = String(number || '');
@@ -117,3 +140,41 @@ export function plainToHtml(text) {
}
export const truncate = (s, n) => (String(s).length > n ? String(s).slice(0, n - 1) + '…' : String(s));
/** „2026-10-31 04:03:00“ (Serverzeit) → Date. Der Server liefert Zeiten ohne Zeitzone; sie werden wie lokale Zeit behandelt. */
export function parseServerTime(s) {
const m = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?/.exec(String(s || ''));
return m ? new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +(m[6] || 0)) : null;
}
/** Kurzform wie „vor 5 Min“, „gestern 14:02“, „31.10. 04:03“. */
export function timeAgo(s, now = new Date()) {
const d = parseServerTime(s);
if (!d) return '';
const diff = Math.round((now - d) / 1000);
const hm = d.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' });
if (diff < 0) { // Zukunft (z. B. Wiedervorlage)
const tomorrow = new Date(now); tomorrow.setDate(now.getDate() + 1);
if (d.toDateString() === now.toDateString()) return `heute ${hm}`;
if (d.toDateString() === tomorrow.toDateString()) return `morgen ${hm}`;
return `${String(d.getDate()).padStart(2, '0')}.${String(d.getMonth() + 1).padStart(2, '0')}. ${hm}`;
}
if (diff < 60) return 'gerade eben';
if (diff < 3600) return `vor ${Math.floor(diff / 60)} Min`;
const sameDay = d.toDateString() === now.toDateString();
if (sameDay) return `heute ${hm}`;
const yesterday = new Date(now); yesterday.setDate(now.getDate() - 1);
if (d.toDateString() === yesterday.toDateString()) return `gestern ${hm}`;
return `${String(d.getDate()).padStart(2, '0')}.${String(d.getMonth() + 1).padStart(2, '0')}. ${hm}`;
}
export const fmtBytes = (n) => (n >= 1048576 ? (n / 1048576).toFixed(1) + ' MB' : n >= 1024 ? Math.round(n / 1024) + ' KB' : n + ' B');
export const initials = (name) => String(name || '?').trim().split(/\s+/).slice(0, 2).map((p) => p[0]?.toUpperCase() || '').join('') || '?';
export const safeColor = (c) => (typeof c === 'string' && /^#[0-9a-fA-F]{3,8}$/.test(c) ? c : null);
export const RESOLUTION_REASONS = {
fixed: 'Fehler behoben', guidance: 'Anleitung oder Beratung', duplicate: 'Doppelt / zusammengeführt', not_reproducible: 'Nicht reproduzierbar',
no_action: 'Keine Maßnahme erforderlich', spam: 'Spam oder Sperre', other: 'Sonstiges',
};
export const STATUS_LABELS = { open: 'Offen', pending: 'Wartet auf Kunde', answered: 'Beantwortet', on_hold: 'Pausiert', resolved: 'Gelöst', closed: 'Geschlossen' };
export const AVAILABILITY = { available: 'Verfügbar', busy: 'Beschäftigt', break: 'Pause', offline: 'Offline' };
+67
View File
@@ -0,0 +1,67 @@
// Kleiner DOM-Baukasten. Serverdaten gelangen nie über innerHTML in die Seite (nur als Text oder Attribut).
/** h('div', {class:'x', onclick: fn}, 'Text', kind, …) */
export function h(tag, attrs = {}, ...kids) {
const el = document.createElement(tag);
for (const [k, v] of Object.entries(attrs || {})) {
if (v === undefined || v === null || v === false) continue;
if (k.startsWith('on') && typeof v === 'function') el.addEventListener(k.slice(2), v);
else if (k === 'class') el.className = v;
else if (k === 'value') el.value = v;
else if (k === 'checked') el.checked = !!v;
else if (k === 'style' && typeof v === 'object') Object.assign(el.style, v);
else el.setAttribute(k, v === true ? '' : String(v));
}
for (const kid of kids.flat(Infinity)) {
if (kid === null || kid === undefined || kid === false) continue;
el.append(kid.nodeType ? kid : document.createTextNode(String(kid)));
}
return el;
}
export const clear = (el) => { while (el.firstChild) el.removeChild(el.firstChild); return el; };
const ICONS = {
home: 'M3 11l9-8 9 8M5 10v10h5v-6h4v6h5V10',
list: 'M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01',
check: 'M20 6L9 17l-5-5',
plus: 'M12 5v14M5 12h14',
menu: 'M4 6h16M4 12h16M4 18h16',
back: 'M15 18l-6-6 6-6',
search: 'M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM21 21l-4.3-4.3',
external: 'M14 4h6v6M20 4l-9 9M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5',
panel: 'M4 5h16v14H4zM14 5v14',
send: 'M22 2L11 13M22 2l-7 20-4-9-9-4z',
note: 'M4 4h16v12H8l-4 4zM8 9h8M8 12h5',
clock: 'M12 7v5l3 2M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18z',
eye: 'M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12zM12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6z',
user: 'M20 21a8 8 0 0 0-16 0M12 3a4 4 0 1 0 0 8 4 4 0 0 0 0-8z',
refresh: 'M21 12a9 9 0 1 1-3-6.7L21 8M21 3v5h-5',
clip: 'M21 12.5l-8.5 8.5a5.5 5.5 0 0 1-8-8L13 4.5a3.5 3.5 0 0 1 5 5l-8.5 8.5a1.5 1.5 0 0 1-2-2L15 8',
logout: 'M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9',
warn: 'M12 3l10 18H2zM12 10v5M12 18h.01',
x: 'M18 6L6 18M6 6l12 12',
};
/** Symbol als SVG (nur feste Pfade aus der Liste oben). */
export function icon(name, size = 18) {
const ns = 'http://www.w3.org/2000/svg';
const svg = document.createElementNS(ns, 'svg');
for (const [k, v] of Object.entries({ viewBox: '0 0 24 24', width: size, height: size, fill: 'none', stroke: 'currentColor', 'stroke-width': 2, 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true' })) svg.setAttribute(k, String(v));
const p = document.createElementNS(ns, 'path');
p.setAttribute('d', ICONS[name] || ICONS.menu);
svg.append(p);
return svg;
}
export const errText = (e) => (e && e.message) || 'Es ist ein Fehler aufgetreten.';
let toastTimer;
/** Kurze Meldung unten im Fenster. */
export function toast(text, kind = 'ok') {
const host = document.getElementById('toasts');
if (!host) return;
clear(host).append(h('div', { class: `toast ${kind}`, role: kind === 'err' ? 'alert' : 'status' }, text));
clearTimeout(toastTimer);
toastTimer = setTimeout(() => clear(host), kind === 'err' ? 6000 : 2600);
}
+39
View File
@@ -0,0 +1,39 @@
// Gemeinsame Bausteine der Ansichten.
import { h, icon, clear, errText } from './dom.js';
import { STATUS_LABELS, safeColor, timeAgo, initials } from './core.js';
export const spinner = () => h('div', { class: 'spinner', role: 'status', 'aria-label': 'Lädt' });
export const statusPill = (status) => h('span', { class: `pill ${status}` }, STATUS_LABELS[status] || status);
export const prioPill = (p) => (p ? h('span', { class: 'pill prio', style: { background: safeColor(p.color) || '#64748b' } }, p.name) : null);
export const avatar = (name, cust = false) => h('span', { class: `avatar${cust ? ' cust' : ''}`, title: name || '' }, initials(name));
/** Eine Ticketzeile. onOpen(ticket) wird beim Klick aufgerufen. */
export function ticketCard(t, onOpen) {
const color = safeColor(t.priority?.color) || 'var(--muted)';
const due = t.isOverdue ? h('span', { class: 'over' }, t.dueLabel || 'überfällig') : (t.dueLabel ? h('span', {}, t.dueLabel) : null);
return h('li', {}, h('button', { class: `tk${t.isOverdue ? ' is-over' : ''}`, onclick: () => onOpen(t), title: `Ticket ${t.number} öffnen` },
h('span', { class: 'bar', style: { background: color } }),
h('div', { class: 'row1' }, h('div', { class: 'subj' }, t.subject)),
h('div', { class: 'row2 meta' }, statusPill(t.status), h('span', {}, `#${t.number}`), h('span', {}, t.requesterName || '—'), due),
h('div', { class: 'row2 meta' }, h('span', {}, t.department?.name || ''), t.assignedStaff ? h('span', {}, `· ${t.assignedStaff.name}`) : h('span', {}, '· nicht zugewiesen'), h('span', {}, `· ${timeAgo(t.updatedAt)}`),
t.following ? icon('eye', 12) : null, t.snoozedUntil ? icon('clock', 12) : null)));
}
export function ticketList(items, onOpen, emptyText = 'Keine Tickets.') {
if (!items.length) return h('div', { class: 'empty' }, emptyText);
return h('ul', { class: 'tickets' }, items.map((t) => ticketCard(t, onOpen)));
}
/** Zeigt einen Fehler im Container; bei abgelaufener Anmeldung zurück zur Anmeldung. */
export function showError(ctx, host, e) {
if (e && e.status === 401) { ctx.logoutExpired(); return; }
clear(host).append(h('div', { class: 'msg err', role: 'alert' }, errText(e)), h('div', { class: 'actions', style: { marginTop: '10px' } }, h('button', { class: 'btn small', onclick: () => ctx.reload() }, icon('refresh', 14), 'Erneut versuchen')));
}
/** Ein Segmentschalter: options = [[wert, beschriftung], …] */
export function segmented(options, current, onPick) {
return h('div', { class: 'seg', role: 'group' }, options.map(([v, label]) => h('button', { type: 'button', class: v === current ? 'on' : '', onclick: () => onPick(v) }, label)));
}
export function field(label, control) { return h('label', {}, label, control); }