app.js hinzugefügt

This commit is contained in:
tim committed 2026-10-01 05:59:00 +00:00
1 parent fccd49596d
commit 84f63f5c4d
1 file changed
+290
+290
View File
@@ -0,0 +1,290 @@
// ============================================================
// 🐕 Hunde-Business Tracker – App-Logik
// ============================================================
"use strict";
/* ---------- Login (Token, Client-seitig, ohne Ambitions) ---------- */
function toHash(str) {
let h = 5381;
for (let i = 0; i < str.length; i++) h = ((h << 5) + h + str.charCodeAt(i)) >>> 0;
return h.toString(36);
}
function saveSession() {
const exp = Date.now() + SESSION_HOURS * 3600 * 1000;
localStorage.setItem("hb_session", JSON.stringify({ h: toHash(APP_TOKEN), exp }));
}
function hasValidSession() {
try {
const s = JSON.parse(localStorage.getItem("hb_session"));
return s && s.h === toHash(APP_TOKEN) && s.exp > Date.now();
} catch { return false; }
}
function showLogin() {
document.getElementById("login-screen").classList.remove("hidden");
document.getElementById("app-screen").classList.add("hidden");
}
function showApp() {
document.getElementById("login-screen").classList.add("hidden");
document.getElementById("app-screen").classList.remove("hidden");
refreshList();
}
document.getElementById("login-btn").addEventListener("click", tryLogin);
document.getElementById("token-input").addEventListener("keydown", (e) => {
if (e.key === "Enter") tryLogin();
});
function tryLogin() {
const val = document.getElementById("token-input").value.trim();
const err = document.getElementById("login-error");
if (val === APP_TOKEN) {
err.classList.add("hidden");
saveSession();
showApp();
} else {
err.classList.remove("hidden");
document.getElementById("token-input").value = "";
}
}
document.getElementById("logout-btn").addEventListener("click", () => {
localStorage.removeItem("hb_session");
showLogin();
});
/* ---------- Konsistenz-Slider (1–5) ---------- */
const KOT_LEVELS = {
1: { emoji: "🏆", caption: "Perfekt! Preisverdächtig! 🏆" },
2: { emoji: "👍", caption: "Alles gut, nichts zu meckern 👍" },
3: { emoji: "🤏", caption: "Etwas weich, aber noch okay 🤏" },
4: { emoji: "😖", caption: "Ziemlich breiig… Durchfall-Alarm 😖" },
5: { emoji: "🚨", caption: "Voller Durchfall! Water bitte! 🚨" },
};
const URIN_LEVELS = {
1: { emoji: "💧", caption: "Nur ein Tropfen 💧" },
2: { emoji: "💦", caption: "Kleine Menge 💦" },
3: { emoji: "👍", caption: "Normale Menge 👍" },
4: { emoji: "🌊", caption: "Ziemlich viel 🌊" },
5: { emoji: "🌊", caption: "Richtig viel! Wer war das? 🌊" },
};
let currentType = "kot"; // oder "urin"
const kotSlider = document.getElementById("consistency");
const kotEmoji = document.getElementById("consistency-emoji");
const kotCaption = document.getElementById("consistency-caption");
const diarrheaAlert = document.getElementById("diarrhea-alert");
const urinSlider = document.getElementById("urin-amount");
const urinEmoji = document.getElementById("urin-emoji");
const urinCaption = document.getElementById("urin-caption");
const urinWrap = document.getElementById("urin-slider-wrap");
function renderKotSlider() {
const lvl = KOT_LEVELS[kotSlider.value];
kotEmoji.textContent = lvl.emoji;
kotCaption.textContent = lvl.caption;
const isDiarrhea = Number(kotSlider.value) >= 4;
diarrheaAlert.classList.toggle("hidden", !isDiarrhea || currentType !== "kot");
}
function renderUrinSlider() {
const lvl = URIN_LEVELS[urinSlider.value];
urinEmoji.textContent = lvl.emoji;
urinCaption.textContent = lvl.caption;
}
kotSlider.addEventListener("input", renderKotSlider);
urinSlider.addEventListener("input", renderUrinSlider);
document.querySelectorAll(".type-btn").forEach((btn) => {
btn.addEventListener("click", () => {
document.querySelectorAll(".type-btn").forEach((b) => b.classList.remove("selected"));
btn.classList.add("selected");
currentType = btn.dataset.type;
const isKot = currentType === "kot";
document.getElementById("consistency-label").textContent = "Konsistenz";
document.getElementById("consistency-label").style.display = isKot ? "block" : "none";
kotSlider.closest(".slider-row").style.display = isKot ? "flex" : "none";
document.getElementById("consistency-caption").style.display = isKot ? "block" : "none";
document.querySelector(".slider-scale").style.display = isKot ? "flex" : "none";
urinWrap.classList.toggle("hidden", isKot);
diarrheaAlert.classList.toggle("hidden", !isKot || Number(kotSlider.value) < 4);
});
});
/* ---------- Zeitstempel ---------- */
function nowLocalISO() {
const d = new Date();
const pad = (n) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
function initTimestamp() {
document.getElementById("timestamp").value = nowLocalISO();
}
function formatTime(iso) {
const d = new Date(iso);
if (isNaN(d)) return iso;
return d.toLocaleString("de-DE", {
weekday: "short", day: "2-digit", month: "2-digit",
hour: "2-digit", minute: "2-digit",
});
}
/* ---------- Speichern ---------- */
document.getElementById("save-btn").addEventListener("click", async () => {
const ts = document.getElementById("timestamp").value || nowLocalISO();
const note = document.getElementById("note").value.trim();
const entry = {
id: crypto.randomUUID(),
type: currentType,
ts,
note,
createdAt: Date.now(),
};
if (currentType === "kot") entry.consistency = Number(kotSlider.value);
else entry.amount = Number(urinSlider.value);
try {
await dbAdd(entry);
const fb = document.getElementById("save-feedback");
fb.classList.remove("hidden");
fb.textContent = currentType === "kot" ? "Eingetragen! 💩✨" : "Eingetragen! 💦✨";
setTimeout(() => fb.classList.add("hidden"), 2200);
document.getElementById("note").value = "";
initTimestamp();
refreshList();
} catch (err) {
alert("Speichern fehlgeschlagen: " + err);
}
});
/* ---------- Liste ---------- */
function entryIcon(e) {
if (e.type === "urin") return "💦";
return e.consistency >= 4 ? "🚨" : "💩";
}
function entryTitle(e) {
if (e.type === "urin") return `Pipi (Menge: ${e.amount}/5)`;
const labels = { 1: "Top-Form! 🏆", 2: "Solide 👍", 3: "Weich 🤏", 4: "Breiig 😖", 5: "Durchfall 🚨" };
return `Kacka – ${labels[e.consistency] || "?"}`;
}
async function refreshList() {
const list = document.getElementById("entry-list");
const empty = document.getElementById("empty-list");
const entries = (await dbGetAll()).sort((a, b) => (a.ts < b.ts ? 1 : -1));
list.innerHTML = "";
empty.classList.toggle("hidden", entries.length > 0);
for (const e of entries) {
const div = document.createElement("div");
div.className = "entry";
const noteHtml = e.note ? `<div class="entry-note">📝 ${escapeHtml(e.note)}</div>` : "";
div.innerHTML = `
<div class="entry-icon">${entryIcon(e)}</div>
<div class="entry-body">
<div class="entry-meta">${escapeHtml(formatTime(e.ts))}</div>
<div class="entry-title">${entryTitle(e)}</div>
${noteHtml}
</div>
<button class="entry-del" title="Löschen">🗑️</button>`;
div.querySelector(".entry-del").addEventListener("click", async () => {
if (confirm("Dieses Geschäft wirklich entsorgen? 🗑️")) {
await dbDelete(e.id);
refreshList();
}
});
list.appendChild(div);
}
}
function escapeHtml(s) {
const d = document.createElement("div");
d.textContent = s;
return d.innerHTML;
}
/* ---------- Statistik ---------- */
document.getElementById("stats-btn").addEventListener("click", async () => {
const entries = await dbGetAll();
const dayAgo = Date.now() - 24 * 3600 * 1000;
const recent = entries.filter((e) => new Date(e.ts).getTime() >= dayAgo);
const kot = recent.filter((e) => e.type === "kot");
const urin = recent.filter((e) => e.type === "urin");
const diarrhea = kot.filter((e) => e.consistency >= 4).length;
const avgConsistency = kot.length
? (kot.reduce((s, e) => s + e.consistency, 0) / kot.length).toFixed(1)
: "–";
document.getElementById("stats-content").innerHTML = `
<div class="stat-row"><span>💩 Kacka (24h)</span><span class="stat-val">${kot.length}</span></div>
<div class="stat-row"><span>💦 Pipi (24h)</span><span class="stat-val">${urin.length}</span></div>
<div class="stat-row"><span>🚨 Durchfall (24h)</span><span class="stat-val">${diarrhea}</span></div>
<div class="stat-row"><span>Ø Konsistenz (24h)</span><span class="stat-val">${avgConsistency} / 5</span></div>
<div class="stat-row"><span>📜 Einträge gesamt</span><span class="stat-val">${entries.length}</span></div>`;
document.getElementById("stats-dialog").showModal();
});
/* ---------- Export / Import ---------- */
document.getElementById("export-btn").addEventListener("click", () => {
document.getElementById("export-dialog").showModal();
});
document.getElementById("do-export-btn").addEventListener("click", async () => {
const entries = await dbGetAll();
const blob = new Blob([JSON.stringify(entries, null, 2)], { type: "application/json" });
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = `hunde-business-${new Date().toISOString().slice(0, 10)}.json`;
a.click();
URL.revokeObjectURL(a.href);
});
document.getElementById("import-file").addEventListener("change", async (e) => {
const file = e.target.files[0];
if (!file) return;
try {
const data = JSON.parse(await file.text());
if (!Array.isArray(data)) throw new Error("Kein gültiges Format");
for (const entry of data) {
if (entry && entry.id && entry.type && entry.ts) {
await dbAdd(entry).catch(() => {});
}
}
refreshList();
document.getElementById("export-dialog").close();
} catch (err) {
alert("Import fehlgeschlagen: " + err.message);
}
e.target.value = "";
});
/* ---------- Init ---------- */
initTimestamp();
renderKotSlider();
renderUrinSlider();
if (hasValidSession()) showApp();
else showLogin();