Upload via GUI (10 Dateien)

This commit is contained in:
Git Manager GUI
2026-09-14 20:56:41 +02:00
commit 6733901d99
10 changed files with 8679 additions and 0 deletions
+135
View File
@@ -0,0 +1,135 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src https://fonts.gstatic.com; script-src 'self'">
<title>Fellakte</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Dancing+Script:wght@600;700&family=Montserrat:wght@500;600;700&family=Source+Sans+Pro:wght@400;600;700&display=swap">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<svg width="0" height="0" style="position:absolute">
<defs>
<symbol id="i-id" viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="2.5" fill="none" stroke="currentColor" stroke-width="1.7"/><circle cx="8.3" cy="11" r="1.8" fill="none" stroke="currentColor" stroke-width="1.5"/><path d="M6 15.3c.5-1.4 1.6-2 2.3-2s1.8.6 2.3 2M13.5 9.5h5M13.5 12.5h5M13.5 15.5h3" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></symbol>
<symbol id="i-clip" viewBox="0 0 24 24"><rect x="5" y="4" width="14" height="17" rx="2" fill="none" stroke="currentColor" stroke-width="1.7"/><rect x="9" y="2.5" width="6" height="3.5" rx="1.2" fill="none" stroke="currentColor" stroke-width="1.5"/><path d="M8 10.5h8M8 14h8M8 17.5h5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></symbol>
<symbol id="i-pencil" viewBox="0 0 24 24"><path d="M4 20l.9-3.9L15.6 5.4a1.6 1.6 0 0 1 2.3 0l.7.7a1.6 1.6 0 0 1 0 2.3L8 19.1 4 20z" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/><path d="M14 7l3 3" stroke="currentColor" stroke-width="1.6"/></symbol>
<symbol id="i-paw" viewBox="0 0 24 24"><ellipse cx="12" cy="16" rx="5.4" ry="4.4" fill="currentColor"/><circle cx="5.6" cy="9.8" r="2.1" fill="currentColor"/><circle cx="10.2" cy="6.3" r="2.1" fill="currentColor"/><circle cx="14.8" cy="6.3" r="2.1" fill="currentColor"/><circle cx="18.4" cy="9.8" r="2.1" fill="currentColor"/></symbol>
<symbol id="i-clock" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5" fill="none" stroke="currentColor" stroke-width="1.7"/><path d="M12 7.5V12l3 2" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></symbol>
<symbol id="i-tube" viewBox="0 0 24 24"><path d="M9 3h6M10 3v11.5a2 2 0 0 0 4 0V3" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/><path d="M10 12.5h4" stroke="currentColor" stroke-width="1.6"/><circle cx="12" cy="17.5" r="3.3" fill="none" stroke="currentColor" stroke-width="1.6"/></symbol>
<symbol id="i-image" viewBox="0 0 24 24"><rect x="3.5" y="4.5" width="17" height="15" rx="2" fill="none" stroke="currentColor" stroke-width="1.6"/><circle cx="8.5" cy="9.5" r="1.6" fill="none" stroke="currentColor" stroke-width="1.4"/><path d="M4.5 16.5l5-4.5 3 2.5 3.5-3.5 4.5 4.5" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/></symbol>
<symbol id="i-file" viewBox="0 0 24 24"><path d="M6 3h8l4.5 4.5V21H6z" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/><path d="M14 3v4.5h4.5" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/></symbol>
<symbol id="i-shield" viewBox="0 0 24 24"><path d="M12 3l7 3v5.5c0 5-3 8-7 9.5-4-1.5-7-4.5-7-9.5V6z" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/><path d="M9 12l2 2 4-4.3" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-search" viewBox="0 0 24 24"><circle cx="10.5" cy="10.5" r="6.5" fill="none" stroke="currentColor" stroke-width="1.7"/><path d="M15.5 15.5L20 20" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></symbol>
<symbol id="i-phone" viewBox="0 0 24 24"><path d="M6 3.5h3l1.5 4-2 1.5a11 11 0 0 0 5 5l1.5-2 4 1.5v3a1.5 1.5 0 0 1-1.6 1.5C10.5 17.7 6.3 13.5 4.5 6.6A1.5 1.5 0 0 1 6 3.5z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/></symbol>
<symbol id="i-mail" viewBox="0 0 24 24"><rect x="3.5" y="5.5" width="17" height="13" rx="2" fill="none" stroke="currentColor" stroke-width="1.5"/><path d="M4.5 6.5l7.5 6 7.5-6" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></symbol>
<symbol id="i-check" viewBox="0 0 24 24"><path d="M5 12.5l4.5 4.5L19 7" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-plus" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"/></symbol>
<symbol id="i-upload" viewBox="0 0 24 24"><path d="M12 15V4M8 8l4-4 4 4" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/><path d="M4 15v3.5A1.5 1.5 0 0 0 5.5 20h13a1.5 1.5 0 0 0 1.5-1.5V15" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></symbol>
<symbol id="i-x" viewBox="0 0 24 24"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></symbol>
<symbol id="i-dog" viewBox="0 0 24 24"><path d="M8 15.5c-2.2 0-3.5-1.6-3.5-3.3 0-1.9 1.5-3.4 2.7-4.3-.3-1-.1-2 .6-2.6.9-.8 2.1-.3 2.5.6.6-.2 1.3-.3 1.9 0 .4-.9 1.6-1.4 2.5-.6.7.6.9 1.6.6 2.6 1.2.9 2.7 2.4 2.7 4.3 0 1.7-1.3 3.3-3.5 3.3" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/><circle cx="9.3" cy="11.3" r=".9" fill="currentColor"/><circle cx="14.3" cy="11.3" r=".9" fill="currentColor"/><path d="M10.5 13.3c.5.5 1.5.5 2 0" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/></symbol>
<symbol id="i-cat" viewBox="0 0 24 24"><path d="M6.5 6l1.8 3.2M17.5 6l-1.8 3.2" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/><path d="M6 12a6 6 0 0 1 12 0c0 2.7-1.3 4.2-3 4.8-.8-.5-2.2-.5-3 0-1.7-.6-6-2.1-6-4.8z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/><circle cx="9.6" cy="11.6" r=".85" fill="currentColor"/><circle cx="14.4" cy="11.6" r=".85" fill="currentColor"/><path d="M11.2 13.2h1.6l-.8 1z" fill="currentColor"/></symbol>
<symbol id="i-turtle" viewBox="0 0 24 24"><ellipse cx="12" cy="13" rx="7" ry="5.4" fill="none" stroke="currentColor" stroke-width="1.5"/><path d="M12 7.6v10.8M5.6 13h12.8M7.2 9.2l3 2M16.8 9.2l-3 2M7.2 16.8l3-2M16.8 16.8l-3-2" stroke="currentColor" stroke-width="1.1"/><circle cx="4" cy="9.5" r="1.5" fill="none" stroke="currentColor" stroke-width="1.4"/></symbol>
<symbol id="i-contract" viewBox="0 0 24 24"><rect x="4" y="3" width="16" height="18" rx="2" fill="none" stroke="currentColor" stroke-width="1.6"/><path d="M8 7.5h8M8 10.5h8M8 13.5h5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/><path d="M7 17.3c1-1.1 2-1.1 3 0s2 1.1 3 0 2-1.1 3 0" stroke="currentColor" stroke-width="1.4" fill="none" stroke-linecap="round"/></symbol>
<symbol id="i-gear" viewBox="0 0 24 24"><circle cx="12" cy="12" r="3" fill="none" stroke="currentColor" stroke-width="1.6"/><path d="M12 3.5v2.4M12 18.1v2.4M20.5 12h-2.4M5.9 12H3.5M17.7 6.3l-1.7 1.7M8 16l-1.7 1.7M17.7 17.7L16 16M8 8 6.3 6.3" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></symbol>
<symbol id="i-trash" viewBox="0 0 24 24"><path d="M5 7h14M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2m-8 0v12a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V7" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M10 11v6M14 11v6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></symbol>
<symbol id="i-rip" viewBox="0 0 24 24"><path d="M8 21V11a4 4 0 0 1 8 0v10" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M12 3v5M9.5 5.5h5" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/><path d="M5 21h14" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></symbol>
<symbol id="i-calendar" viewBox="0 0 24 24"><rect x="3.5" y="5" width="17" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="1.6"/><path d="M3.5 9.5h17M8 3v4M16 3v4" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></symbol>
<symbol id="i-folder" viewBox="0 0 24 24"><path d="M3.5 6.5a1.5 1.5 0 0 1 1.5-1.5h4l2 2h9a1.5 1.5 0 0 1 1.5 1.5v9a1.5 1.5 0 0 1-1.5 1.5H5A1.5 1.5 0 0 1 3.5 17.5z" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/></symbol>
<symbol id="i-chevron-left" viewBox="0 0 24 24"><path d="M15 5l-7 7 7 7" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-chevron-right" viewBox="0 0 24 24"><path d="M9 5l7 7-7 7" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-external" viewBox="0 0 24 24"><path d="M9 6H6a1.5 1.5 0 0 0-1.5 1.5v10A1.5 1.5 0 0 0 6 19h10a1.5 1.5 0 0 0 1.5-1.5V15" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M13 5h6v6M19 5l-9 9" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-flask" viewBox="0 0 24 24"><path d="M10 3h4M10 3v6l-5 9.5A1.5 1.5 0 0 0 6.3 21h11.4a1.5 1.5 0 0 0 1.3-2.5L14 9V3" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M8.5 15h7" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></symbol>
<symbol id="i-rabbit" viewBox="0 0 24 24"><path d="M9 10c-1-3-.5-6 1-7s2 1.5 1.5 4.5M15 10c1-3 .5-6-1-7s-2 1.5-1.5 4.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/><ellipse cx="12" cy="15" rx="6" ry="5.5" fill="none" stroke="currentColor" stroke-width="1.5"/><circle cx="9.7" cy="13.5" r=".9" fill="currentColor"/><circle cx="14.3" cy="13.5" r=".9" fill="currentColor"/><path d="M11 16.2c.6.5 1.4.5 2 0" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/></symbol>
</defs>
</svg>
<div class="app">
<header class="topbar">
<div class="brandmark">
<img src="../assets/logo.png" alt="Tierheilpraxis Iris Hack" class="brand-logo">
<div>
<div class="brand-word">Fellakte</div>
<div class="brand-sub">Tierheilpraxis Iris Hack</div>
</div>
</div>
<div class="view-switch">
<button class="view-switch-btn active" id="view-patients-btn" data-view="patients"><svg><use href="#i-folder"/></svg>Patienten</button>
<button class="view-switch-btn" id="view-calendar-btn" data-view="calendar"><svg><use href="#i-calendar"/></svg>Kalender</button>
<button class="view-switch-btn" id="view-remedies-btn" data-view="remedies"><svg><use href="#i-flask"/></svg>Verzeichnis</button>
</div>
<button class="btn ghost icon-btn" id="mobile-back-btn" title="Zurück zur Liste"><svg><use href="#i-chevron-left"/></svg></button>
<div class="crumb" id="crumb"></div>
<div class="topbar-spacer"></div>
<span class="chip" id="sync-status" style="background:var(--ok-tint); color:var(--ok); border-color:transparent">Verbunden</span>
<!-- kept in the DOM (boot() wires these unconditionally) but hidden — Phase 1 is read-only -->
<button class="btn ghost" id="lexware-btn" hidden><svg><use href="#i-external"/></svg>Lexware</button>
<button class="btn ghost icon-btn" id="settings-btn" hidden><svg><use href="#i-gear"/></svg></button>
</header>
<div class="shell">
<nav class="directory" id="directory">
<div class="search"><svg width="15" height="15"><use href="#i-search"/></svg><input id="search-input" placeholder="Besitzer oder Tier suchen…" aria-label="Suche"></div>
<button class="btn primary block" id="new-owner-btn" hidden><svg><use href="#i-plus"/></svg>Neuer Besitzer</button>
<div id="directory-list"></div>
</nav>
<main class="main" id="main">
<div class="empty-state" id="empty-state">
<svg viewBox="0 0 24 24" width="40" height="40"><use href="#i-paw"/></svg>
<p>Noch kein Tier ausgewählt.<br>Links einen Besitzer bzw. ein Tier antippen, um seine Mappe zu öffnen.</p>
</div>
<div id="folder-view" hidden>
<div class="folder-head">
<div class="folder-title">
<div class="avatar-lg" id="avatar-lg"></div>
<div>
<h1 id="animal-name"></h1>
<div class="chips" id="animal-chips"></div>
</div>
</div>
<div class="owner-card" id="owner-card"></div>
</div>
<div class="tabstrip" id="tabstrip"></div>
<div id="panels"></div>
</div>
<div id="calendar-view" hidden></div>
<div id="remedies-view" hidden></div>
</main>
</div>
</div>
<div class="modal-overlay" id="modal-overlay" hidden>
<div class="modal-card" id="modal-card"></div>
</div>
<div class="modal-overlay" id="pairing-overlay">
<div class="modal-card" style="text-align:center">
<img src="../assets/logo.png" alt="" style="height:44px;margin-bottom:12px">
<h2>Mit Praxis-PC verbinden</h2>
<p class="hint" style="margin:-4px 0 18px">Code eingeben, der gerade am PC unter Einstellungen → Tablet-Zugang angezeigt wird.</p>
<form id="pair-form">
<div class="modal-field">
<input id="pair-code-input" type="text" inputmode="numeric" pattern="[0-9]*" maxlength="6" placeholder="123456" autocomplete="off" style="text-align:center;font-size:24px;letter-spacing:.25em;font-family:var(--font-head);font-weight:700" autofocus>
</div>
<div id="pair-status" class="hint" style="min-height:16px;margin-bottom:10px"></div>
<button type="submit" class="btn primary block">Verbinden</button>
</form>
</div>
</div>
<div id="readonly-toast" hidden style="position:fixed;bottom:20px;left:50%;transform:translateX(-50%);background:var(--ink);color:var(--surface);padding:10px 20px;border-radius:99px;font-family:var(--font-head);font-size:12.5px;font-weight:600;box-shadow:var(--shadow);z-index:300;white-space:nowrap">Bearbeiten kommt in einer späteren Phase — aktuell nur zum Ansehen.</div>
<div id="warning-banner" hidden style="position:fixed;top:14px;left:50%;transform:translateX(-50%);background:var(--warn-tint);color:var(--warn);border:1px solid var(--warn);padding:10px 16px;border-radius:var(--radius-m);font-family:var(--font-head);font-size:12.5px;font-weight:600;box-shadow:var(--shadow);z-index:300;display:flex;align-items:center;gap:12px;max-width:calc(100vw - 40px)">
<span id="warning-banner-text"></span>
<button type="button" id="warning-banner-close" style="background:none;border:0;color:inherit;font-size:16px;line-height:1;cursor:pointer;padding:0"></button>
</div>
<script src="offline-store.js"></script>
<script src="pair-client.js"></script>
</body>
</html>
+91
View File
@@ -0,0 +1,91 @@
// offline-store.js — the tablet's local data store (IndexedDB), so the app keeps
// working with zero connectivity once the directory/an animal has been opened while
// still on the practice WiFi. Two jobs: (1) cache what's been read, so it can be
// re-displayed offline; (2) queue what's been written while offline, so it can be
// replayed against the practice PC once reachable again.
"use strict";
(function () {
const DB_NAME = "fellakte-offline";
const DB_VERSION = 1;
let dbPromise = null;
function openDb() {
if (dbPromise) return dbPromise;
dbPromise = new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, DB_VERSION);
req.onupgradeneeded = () => {
const db = req.result;
if (!db.objectStoreNames.contains("bundles")) db.createObjectStore("bundles", { keyPath: "id" });
if (!db.objectStoreNames.contains("meta")) db.createObjectStore("meta", { keyPath: "key" });
if (!db.objectStoreNames.contains("queue")) db.createObjectStore("queue", { keyPath: "id", autoIncrement: true });
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
return dbPromise;
}
// Runs a write (put/add/delete) against `name` and resolves once the transaction
// commits. The return value of `fn` (an IDBRequest) is not needed by any caller.
async function runWrite(name, fn) {
const db = await openDb();
return new Promise((resolve, reject) => {
const t = db.transaction(name, "readwrite");
fn(t.objectStore(name));
t.oncomplete = () => resolve();
t.onerror = () => reject(t.error);
});
}
// Runs a single read request against `name` and resolves with its result
// (undefined on error, so callers can treat a miss the same as "not cached").
async function runRead(name, fn) {
const db = await openDb();
return new Promise((resolve) => {
const t = db.transaction(name, "readonly");
const req = fn(t.objectStore(name));
req.onsuccess = () => resolve(req.result);
req.onerror = () => resolve(undefined);
});
}
window.offlineStore = {
async saveDirectory(list) {
await runWrite("meta", (s) => s.put({ key: "directory", value: list, at: Date.now() }));
},
async getDirectory() {
const row = await runRead("meta", (s) => s.get("directory"));
return row ? row.value : null;
},
async saveBundle(bundle) {
if (!bundle || !bundle.animal) return;
await runWrite("bundles", (s) => s.put({ id: bundle.animal.id, bundle, at: Date.now() }));
},
async getBundle(id) {
const row = await runRead("bundles", (s) => s.get(id));
return row ? row.bundle : null;
},
// Scans cached bundles for one containing a finding with this id — used for
// update/delete offline, where the caller only has the finding id, not the
// animal it belongs to (same shape as the desktop IPC calls).
async findAnimalIdForFinding(findingId) {
const rows = (await runRead("bundles", (s) => s.getAll())) || [];
const hit = rows.find((r) => r.bundle.findings.some((f) => f.id === findingId));
return hit ? hit.id : null;
},
async enqueue(op) {
await runWrite("queue", (s) => s.add({ ...op, createdAt: Date.now() }));
},
async listQueue() {
return (await runRead("queue", (s) => s.getAll())) || [];
},
async removeFromQueue(id) {
await runWrite("queue", (s) => s.delete(id));
},
async queueCount() {
return (await this.listQueue()).length;
},
};
})();
+435
View File
@@ -0,0 +1,435 @@
// pair-client.js — loaded before app.js. Defines window.api for the web client
// (talking to main/webserver.js over the local network instead of Electron IPC),
// handles the one-time pairing screen, and only injects app.js once a valid
// session is confirmed — app.js calls window.api immediately on load, so it must
// never run before window.api (and a working session) exist.
//
// Phase 3: offline. Reads fall back to the local cache (offline-store.js) when the
// practice PC isn't reachable; writes to Notizen/Befunde queue locally and apply
// optimistically to the cache, then replay automatically once reachable again. This
// only works for a tab that was already open (and the animal already viewed) while
// still on the practice WiFi — a from-scratch cold load with zero network needs a
// Service Worker, which needs HTTPS, which this plain-WLAN setup deliberately skips.
"use strict";
(function () {
const TOKEN_KEY = "fellakte_token";
let token = localStorage.getItem(TOKEN_KEY);
let isOnline = true;
let syncing = false;
const overlay = document.getElementById("pairing-overlay");
const form = document.getElementById("pair-form");
const codeInput = document.getElementById("pair-code-input");
const status = document.getElementById("pair-status");
const toast = document.getElementById("readonly-toast");
function showPairing(prefillCode) {
overlay.hidden = false;
if (prefillCode) codeInput.value = prefillCode;
codeInput.focus();
}
function hidePairing() {
overlay.hidden = true;
}
function authHeaders() {
return token ? { Authorization: "Bearer " + token } : {};
}
let toastTimer = null;
function showToast(text) {
if (!toast) return;
toast.textContent = text;
toast.hidden = false;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => (toast.hidden = true), 3200);
}
function readOnlyNotice() {
showToast("Bearbeiten kommt in einer späteren Phase — aktuell nur zum Ansehen.");
}
function offlineUnavailableNotice() {
showToast("Ohne Verbindung aktuell nicht möglich.");
}
function showWarningBanner(info) {
const banner = document.getElementById("warning-banner");
const text = document.getElementById("warning-banner-text");
if (!banner || !text) return;
const when = new Date(info.updatedAt).toLocaleTimeString("de-DE", { hour: "2-digit", minute: "2-digit" });
text.textContent = `Achtung: "${info.host}" wurde zuletzt um ${when} Uhr ebenfalls verwendet — kurz absprechen, bevor beide gleichzeitig speichern.`;
banner.hidden = false;
}
async function renderSyncStatus() {
const chip = document.getElementById("sync-status");
if (!chip) return;
const pending = await window.offlineStore.queueCount();
if (isOnline && pending === 0) {
chip.textContent = "Verbunden";
chip.style.background = "var(--ok-tint)";
chip.style.color = "var(--ok)";
} else if (isOnline && pending > 0) {
chip.textContent = `Synchronisiere … (${pending})`;
chip.style.background = "var(--warn-tint)";
chip.style.color = "var(--warn)";
} else if (pending > 0) {
chip.textContent = `Offline — ${pending} wartend`;
chip.style.background = "var(--warn-tint)";
chip.style.color = "var(--warn)";
} else {
chip.textContent = "Offline";
chip.style.background = "var(--surface-alt)";
chip.style.color = "var(--ink-faint)";
}
}
function setOnline(v) {
const changed = v !== isOnline;
isOnline = v;
renderSyncStatus();
if (changed && v) trySync();
}
// ---- reads: network first, cache fallback ----
async function apiGet(path, cache) {
try {
const res = await fetch(path, { headers: authHeaders() });
if (res.status === 401) {
token = null;
localStorage.removeItem(TOKEN_KEY);
showPairing();
throw new Error("unauthorized");
}
if (!res.ok) throw new Error("request-failed:" + res.status);
const data = await res.json();
setOnline(true);
if (cache && cache.kind === "directory") window.offlineStore.saveDirectory(data);
if (cache && cache.kind === "bundle") window.offlineStore.saveBundle(data);
return data;
} catch (err) {
if (err.message === "unauthorized") throw err;
setOnline(false);
if (cache && cache.kind === "directory") {
const cached = await window.offlineStore.getDirectory();
if (cached) return cached;
}
if (cache && cache.kind === "bundle") {
const cached = await window.offlineStore.getBundle(cache.key);
if (cached) return cached;
}
throw err;
}
}
// ---- writes: network first; on failure, queue + apply optimistically to the
// cache when `offlineSpec` says this kind of write supports that (Notizen,
// Befunde). Surfaces the server's "someone else is using this data folder right
// now" advisory as a dismissible banner (same idea as the desktop app's startup
// dialog) — advisory only, matching how the two practice PCs already behave.
async function apiSend(method, path, body, offlineSpec) {
try {
const res = await fetch(path, {
method,
headers: { ...authHeaders(), "Content-Type": "application/json" },
body: body !== undefined ? JSON.stringify(body) : undefined,
});
if (res.status === 401) {
token = null;
localStorage.removeItem(TOKEN_KEY);
showPairing();
throw new Error("unauthorized");
}
if (!res.ok) throw new Error("request-failed:" + res.status);
const data = await res.json().catch(() => ({}));
setOnline(true);
if (data && data.warning) showWarningBanner(data.warning);
return data;
} catch (err) {
if (err.message === "unauthorized") throw err;
setOnline(false);
if (!offlineSpec) {
offlineUnavailableNotice();
throw err;
}
await window.offlineStore.enqueue({ method, path, body });
await applyOptimistic(offlineSpec, body);
renderSyncStatus();
return { ok: true, offline: true };
}
}
async function applyOptimistic(spec, body) {
const nowIso = new Date().toISOString();
const localId = () => "lokal-" + Date.now() + "-" + Math.random().toString(36).slice(2, 7);
if (spec.kind === "note") {
const bundle = await window.offlineStore.getBundle(body.animalId);
if (!bundle) return;
bundle.notes.unshift({
id: localId(),
animal_id: body.animalId,
date: new Date().toLocaleDateString("de-DE"),
text: body.text,
created_at: nowIso,
});
await window.offlineStore.saveBundle(bundle);
} else if (spec.kind === "finding-add") {
const bundle = await window.offlineStore.getBundle(body.animalId);
if (!bundle) return;
bundle.findings.push({
id: localId(),
animal_id: body.animalId,
x: body.x,
y: body.y,
severity: body.severity,
text: body.text,
created_at: nowIso,
});
await window.offlineStore.saveBundle(bundle);
} else if (spec.kind === "finding-update") {
const animalId = await window.offlineStore.findAnimalIdForFinding(spec.findingId);
if (!animalId) return;
const bundle = await window.offlineStore.getBundle(animalId);
const f = bundle.findings.find((x) => x.id === spec.findingId);
if (f) {
f.severity = body.severity;
f.text = body.text;
await window.offlineStore.saveBundle(bundle);
}
} else if (spec.kind === "finding-delete") {
const animalId = await window.offlineStore.findAnimalIdForFinding(spec.findingId);
if (!animalId) return;
const bundle = await window.offlineStore.getBundle(animalId);
bundle.findings = bundle.findings.filter((x) => x.id !== spec.findingId);
await window.offlineStore.saveBundle(bundle);
}
}
// Replays the queue in order against the real server. Stops (leaves the rest
// queued) at the first failure — still offline, or the practice PC went away
// mid-sync. On a full, non-empty drain, reloads so the whole page re-reads fresh,
// server-confirmed data instead of the optimistic local copies.
async function trySync() {
if (syncing) return;
syncing = true;
try {
const queue = await window.offlineStore.listQueue();
if (!queue.length) {
setOnline(await pingServer());
return;
}
let drained = 0;
for (const op of queue) {
try {
const res = await fetch(op.path, {
method: op.method,
headers: { ...authHeaders(), "Content-Type": "application/json" },
body: op.body !== undefined ? JSON.stringify(op.body) : undefined,
});
if (res.status === 401) {
token = null;
localStorage.removeItem(TOKEN_KEY);
showPairing();
return;
}
if (!res.ok) throw new Error("sync-failed:" + res.status);
await window.offlineStore.removeFromQueue(op.id);
drained++;
} catch {
setOnline(false);
return; // still offline (or PC unreachable) — rest stays queued for next try
}
}
setOnline(true);
if (drained > 0) location.reload();
} finally {
syncing = false;
}
}
async function pingServer() {
try {
await fetch("/api/directory", { headers: authHeaders() });
return true; // any HTTP response at all means the practice PC is reachable
} catch {
return false;
}
}
// Resolves with `fallback` after showing the read-only notice — safe for callers
// that just re-render afterward (await refreshBundle(); renderPanels();).
function stub(fallback) {
return async () => {
readOnlyNotice();
return fallback;
};
}
// Rejects instead — used only where the caller immediately depends on the result
// (e.g. `const id = await createAnimal(...); await selectAnimal(id)`), so a
// silently-wrong id can't cascade into a broken render.
function rejectingStub() {
return async () => {
readOnlyNotice();
throw new Error("read-only");
};
}
window.api = {
listDirectory: () => apiGet("/api/directory", { kind: "directory" }),
getAnimalBundle: (id) => apiGet("/api/animal/" + encodeURIComponent(id), { kind: "bundle", key: id }),
listAppointments: (fromDate, toDate) =>
apiGet(`/api/appointments?from=${encodeURIComponent(fromDate || "")}&to=${encodeURIComponent(toDate || "")}`),
listRemedies: (query) => apiGet("/api/remedies?q=" + encodeURIComponent(query || "")),
searchNotes: (query) => apiGet("/api/search-notes?q=" + encodeURIComponent(query || "")),
openDocument: async (documentId) => {
const { url } = await apiGet("/api/document-url/" + encodeURIComponent(documentId));
window.open(url, "_blank");
return true;
},
documentAbsPath: stub(null),
dataFolder: stub(null),
createOwner: rejectingStub(),
createAnimal: rejectingStub(),
updateAnimalField: stub(true),
updateOwnerField: stub(true),
deleteAnimal: stub(true),
deleteOwner: stub(true),
addNote: (animalId, text) => apiSend("POST", "/api/note", { animalId, text }, { kind: "note" }),
addHistoryEntry: stub(true),
addLabResult: stub(null),
addLabValue: stub(true),
deleteLabResult: stub(true),
addFinding: (animalId, finding) => apiSend("POST", "/api/finding", { animalId, ...finding }, { kind: "finding-add" }),
updateFinding: (id, patch) =>
apiSend("PATCH", "/api/finding/" + encodeURIComponent(id), patch, { kind: "finding-update", findingId: id }),
deleteFinding: (id) =>
apiSend("DELETE", "/api/finding/" + encodeURIComponent(id), undefined, { kind: "finding-delete", findingId: id }),
addExam: stub(null),
// Phase 4: needs a live connection to the practice PC (PDF/E-Mail are server-side
// operations — see the file header) — not queued offline like Notizen/Befunde.
setConsent: (animalId, patch) => apiSend("POST", "/api/consent", { animalId, ...patch }),
saveSignature: (animalId, dataUrl) => apiSend("POST", "/api/consent/signature", { animalId, dataUrl }),
setContract: (animalId, patch) => apiSend("POST", "/api/contract", { animalId, ...patch }),
saveContractSignature: (animalId, dataUrl) => apiSend("POST", "/api/contract/signature", { animalId, dataUrl }),
generatePdf: (animalId, kind, content) => apiSend("POST", "/api/document/pdf", { animalId, kind, ...content }),
generateTemplatePdf: (animalId, filenamePrefix, content) =>
apiSend("POST", "/api/document/template-pdf", { animalId, filenamePrefix, ...content }),
sendDocumentEmail: (animalId, kind, file) => apiSend("POST", "/api/document/email", { animalId, kind, ...file }),
addRemedy: stub(null),
updateRemedy: stub(true),
deleteRemedy: stub(true),
// Termine: not yet queued for offline (Phase 3 scope is Notizen/Befunde) — a
// clear "not available offline" notice instead of queueing silently.
addAppointment: (data) => apiSend("POST", "/api/appointment", data),
updateAppointment: (id, data) => apiSend("PATCH", "/api/appointment/" + encodeURIComponent(id), data),
deleteAppointment: (id) => apiSend("DELETE", "/api/appointment/" + encodeURIComponent(id)),
getLexwarePath: stub(null),
setLexwarePath: stub(true),
openLexware: stub({ ok: false, error: "not-available" }),
getSmtpSettings: stub(null),
setSmtpSettings: stub(true),
testSmtpSettings: stub({ ok: false, error: "not-available" }),
getReminderLead: stub(30),
setReminderLead: stub(true),
backupNow: stub({ ok: false, error: "not-available" }),
getBackupInfo: stub({ count: 0, last: null }),
listBackups: stub([]),
openBackupFolder: stub(true),
restoreBackup: stub({ ok: false, error: "not-available" }),
addDocument: stub([]),
};
const warningClose = document.getElementById("warning-banner-close");
if (warningClose) warningClose.addEventListener("click", () => (document.getElementById("warning-banner").hidden = true));
function loadApp() {
const s = document.createElement("script");
s.src = "app.js";
document.body.appendChild(s);
}
// Distinguishes "token is genuinely invalid" (401 → must re-pair) from "can't
// reach the practice PC right now" (network error → proceed in offline mode with
// whatever's cached, a valid token just can't be re-confirmed this moment).
async function checkSession() {
try {
const res = await fetch("/api/directory", { headers: authHeaders() });
if (res.status === 401) return "invalid";
return "online";
} catch {
return "offline";
}
}
form.addEventListener("submit", async (e) => {
e.preventDefault();
const code = codeInput.value.trim();
if (!code) return;
status.textContent = "Verbinde …";
try {
const res = await fetch("/api/pair", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ code, deviceName: guessDeviceName() }),
});
if (!res.ok) {
status.textContent = res.status === 410 || res.status === 429
? "Code abgelaufen. Am PC einen neuen Code erzeugen."
: "Code falsch — bitte nochmal prüfen.";
return;
}
const data = await res.json();
token = data.token;
localStorage.setItem(TOKEN_KEY, token);
location.reload();
} catch {
status.textContent = "Keine Verbindung zum Praxis-PC — gleiches WLAN?";
}
});
function guessDeviceName() {
const ua = navigator.userAgent || "";
if (/iPad/.test(ua)) return "iPad";
if (/iPhone/.test(ua)) return "iPhone";
if (/Android/.test(ua)) return "Android-Gerät";
if (/Macintosh/.test(ua)) return "Mac";
return "Gerät";
}
(async function init() {
const params = new URLSearchParams(location.search);
const prefill = params.get("pair");
if (!token) {
showPairing(prefill);
return;
}
const state = await checkSession();
if (state === "invalid") {
showPairing(prefill);
return;
}
hidePairing();
if (prefill) history.replaceState(null, "", location.pathname);
isOnline = state === "online";
loadApp();
renderSyncStatus();
setInterval(trySync, 15000);
window.addEventListener("online", trySync);
if (state === "online") trySync(); // drain any queue left over from last time
})();
})();