Sprint 15: Suche, Ausweis, Teilen, Widget
- Volltext-Suche im Tagebuch (LIKE über Titel/Text/Tags, Debounce 350ms)
- Digitaler Heimtierausweis als druckbare HTML-Seite (/ausweis/{dog_id})
Enthält Impfungen, Medikamente, Allergien, Tierärzte, Chip-Nr.
- Hund teilen: Einladungslink-System (dog_shares-Tabelle, /teilen/{token})
Geteilte Hunde erscheinen in der Hundeliste, Tagebuch/Gesundheit lesbar
- Widget-Seite /#widget: zufälliges Tagebuchbild + nächste Erinnerung
Als PWA-Shortcut im Manifest verankert
- SW-Cache by-v144, APP_VER 117
This commit is contained in:
parent
d5f09cd16b
commit
34f29f9d0a
16 changed files with 917 additions and 35 deletions
|
|
@ -630,3 +630,21 @@ def _migrate(conn_factory):
|
||||||
SELECT id, dog_id FROM diary
|
SELECT id, dog_id FROM diary
|
||||||
""")
|
""")
|
||||||
logger.info("Migration: diary_dogs Backfill abgeschlossen.")
|
logger.info("Migration: diary_dogs Backfill abgeschlossen.")
|
||||||
|
|
||||||
|
# Hund-Teilen: Einladungssystem
|
||||||
|
conn.executescript("""
|
||||||
|
CREATE TABLE IF NOT EXISTS dog_shares (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
dog_id INTEGER NOT NULL REFERENCES dogs(id) ON DELETE CASCADE,
|
||||||
|
owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
shared_with_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
invite_token TEXT NOT NULL UNIQUE,
|
||||||
|
role TEXT NOT NULL DEFAULT 'editor',
|
||||||
|
accepted_at TEXT,
|
||||||
|
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_dog_shares_dog ON dog_shares(dog_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_dog_shares_token ON dog_shares(invite_token);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_dog_shares_user ON dog_shares(shared_with_id);
|
||||||
|
""")
|
||||||
|
logger.info("Migration: dog_shares Tabelle bereit.")
|
||||||
|
|
|
||||||
211
backend/main.py
211
backend/main.py
|
|
@ -74,6 +74,8 @@ from routes.admin import router as admin_router
|
||||||
from routes.webcal import router as webcal_router
|
from routes.webcal import router as webcal_router
|
||||||
from routes.profile import router as profile_router
|
from routes.profile import router as profile_router
|
||||||
from routes.import_data import router as import_router
|
from routes.import_data import router as import_router
|
||||||
|
from routes.sharing import dog_router as sharing_dog_router, share_router as sharing_share_router
|
||||||
|
from routes.widget import router as widget_router
|
||||||
|
|
||||||
app.include_router(auth_router, prefix="/api/auth", tags=["Auth"])
|
app.include_router(auth_router, prefix="/api/auth", tags=["Auth"])
|
||||||
app.include_router(dogs_router, prefix="/api/dogs", tags=["Hunde"])
|
app.include_router(dogs_router, prefix="/api/dogs", tags=["Hunde"])
|
||||||
|
|
@ -100,6 +102,9 @@ app.include_router(admin_router, prefix="/api/admin", tags=["Admin"])
|
||||||
app.include_router(webcal_router, prefix="/api/webcal", tags=["WebCal"])
|
app.include_router(webcal_router, prefix="/api/webcal", tags=["WebCal"])
|
||||||
app.include_router(profile_router, prefix="/api/profile", tags=["Profil"])
|
app.include_router(profile_router, prefix="/api/profile", tags=["Profil"])
|
||||||
app.include_router(import_router, prefix="/api/import", tags=["Import"])
|
app.include_router(import_router, prefix="/api/import", tags=["Import"])
|
||||||
|
app.include_router(sharing_dog_router, prefix="/api/dogs", tags=["Teilen"])
|
||||||
|
app.include_router(sharing_share_router, prefix="/api/share", tags=["Teilen"])
|
||||||
|
app.include_router(widget_router, prefix="/api/widget", tags=["Widget"])
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
|
|
@ -445,6 +450,212 @@ async def public_dog_page(dog_id: int):
|
||||||
return HTMLResponse(content=html)
|
return HTMLResponse(content=html)
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Einladungsseite /teilen/{token} — SPA lädt + nimmt Einladung an
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
@app.get("/teilen/{token}")
|
||||||
|
async def invite_page(token: str):
|
||||||
|
return FileResponse(f"{STATIC_DIR}/index.html", headers={"Cache-Control": "no-cache"})
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Widget-Vorschau /widget
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
@app.get("/widget")
|
||||||
|
async def widget_page():
|
||||||
|
return FileResponse(f"{STATIC_DIR}/index.html", headers={"Cache-Control": "no-cache"})
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Digitaler Heimtierausweis /ausweis/{dog_id}
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
@app.get("/ausweis/{dog_id}")
|
||||||
|
async def ausweis_page(dog_id: int, request: Request):
|
||||||
|
from fastapi.responses import HTMLResponse
|
||||||
|
from auth import get_current_user_optional, decode_token
|
||||||
|
import json as _json
|
||||||
|
|
||||||
|
# Auth via Cookie
|
||||||
|
token = request.cookies.get("by_token")
|
||||||
|
user_id = None
|
||||||
|
if token:
|
||||||
|
try:
|
||||||
|
payload = decode_token(token)
|
||||||
|
user_id = int(payload["sub"])
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if not user_id:
|
||||||
|
return HTMLResponse(
|
||||||
|
'<meta charset="UTF-8"><p style="font-family:sans-serif;padding:2rem">'
|
||||||
|
'Bitte <a href="/">einloggen</a> um den Ausweis anzuzeigen.</p>',
|
||||||
|
status_code=401
|
||||||
|
)
|
||||||
|
|
||||||
|
from database import db as _db
|
||||||
|
with _db() as conn:
|
||||||
|
dog = conn.execute(
|
||||||
|
"""SELECT d.* FROM dogs d
|
||||||
|
LEFT JOIN dog_shares ds ON ds.dog_id=d.id AND ds.shared_with_id=? AND ds.accepted_at IS NOT NULL
|
||||||
|
WHERE d.id=? AND (d.user_id=? OR ds.id IS NOT NULL)""",
|
||||||
|
(user_id, dog_id, user_id)
|
||||||
|
).fetchone()
|
||||||
|
if not dog:
|
||||||
|
return HTMLResponse("<p>Hund nicht gefunden.</p>", status_code=404)
|
||||||
|
|
||||||
|
owner = conn.execute("SELECT name, email FROM users WHERE id=?", (dog["user_id"],)).fetchone()
|
||||||
|
|
||||||
|
health_rows = conn.execute(
|
||||||
|
"SELECT * FROM health WHERE dog_id=? ORDER BY datum DESC",
|
||||||
|
(dog_id,)
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
vets = conn.execute(
|
||||||
|
"""SELECT DISTINCT t.name, t.strasse, t.plz, t.ort, t.telefon
|
||||||
|
FROM tieraerzte t
|
||||||
|
JOIN health h ON h.tierarzt_id = t.id
|
||||||
|
WHERE h.dog_id=?""",
|
||||||
|
(dog_id,)
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
dog = dict(dog)
|
||||||
|
vets = [dict(v) for v in vets]
|
||||||
|
|
||||||
|
def esc(s):
|
||||||
|
if not s: return ""
|
||||||
|
return str(s).replace("&","&").replace("<","<").replace(">",">").replace('"',""")
|
||||||
|
|
||||||
|
def fmt_date(d):
|
||||||
|
if not d: return "–"
|
||||||
|
try:
|
||||||
|
from datetime import date
|
||||||
|
parts = d.split("-")
|
||||||
|
return f"{int(parts[2])}.{int(parts[1])}.{parts[0]}"
|
||||||
|
except Exception:
|
||||||
|
return d
|
||||||
|
|
||||||
|
geschlecht = {"m": "Rüde", "w": "Hündin"}.get(dog.get("geschlecht",""), "–")
|
||||||
|
|
||||||
|
# Impfungen
|
||||||
|
impfungen = [r for r in health_rows if r["typ"] == "impfung"]
|
||||||
|
# Medikamente (aktiv)
|
||||||
|
medis = [r for r in health_rows if r["typ"] == "medikament" and r["aktiv"]]
|
||||||
|
# Allergien
|
||||||
|
allergien = [r for r in health_rows if r["typ"] == "allergie"]
|
||||||
|
|
||||||
|
def health_rows_html(rows, cols):
|
||||||
|
if not rows:
|
||||||
|
return '<tr><td colspan="99" style="color:#999;font-style:italic">Keine Einträge</td></tr>'
|
||||||
|
out = ""
|
||||||
|
for r in rows:
|
||||||
|
out += "<tr>" + "".join(f"<td>{esc(r[c])}</td>" for c in cols) + "</tr>"
|
||||||
|
return out
|
||||||
|
|
||||||
|
photo_html = f'<img src="{esc(dog["foto_url"])}" alt="{esc(dog["name"])}" class="dog-photo">' if dog.get("foto_url") else '<div class="dog-photo-placeholder">🐕</div>'
|
||||||
|
|
||||||
|
vets_html = ""
|
||||||
|
for v in vets:
|
||||||
|
addr = ", ".join(filter(None, [v.get("strasse"), v.get("plz"), v.get("ort")]))
|
||||||
|
vets_html += f'<div class="vet-card"><strong>{esc(v["name"])}</strong>'
|
||||||
|
if addr: vets_html += f'<br><small>{esc(addr)}</small>'
|
||||||
|
if v.get("telefon"): vets_html += f'<br><small>☎ {esc(v["telefon"])}</small>'
|
||||||
|
vets_html += "</div>"
|
||||||
|
if not vets_html:
|
||||||
|
vets_html = '<span style="color:#999;font-style:italic">Keine Tierärzte eingetragen</span>'
|
||||||
|
|
||||||
|
html = f"""<!DOCTYPE html>
|
||||||
|
<html lang="de">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Heimtierausweis – {esc(dog["name"])}</title>
|
||||||
|
<style>
|
||||||
|
* {{ box-sizing: border-box; margin: 0; padding: 0; }}
|
||||||
|
body {{ font-family: "Segoe UI", Arial, sans-serif; background: #FAF7F2; color: #1a1a1a; padding: 2rem; }}
|
||||||
|
.ausweis {{ max-width: 800px; margin: 0 auto; background: #fff; border-radius: 12px; box-shadow: 0 2px 20px rgba(0,0,0,.08); overflow: hidden; }}
|
||||||
|
.header {{ background: linear-gradient(135deg, #C4843A, #e8a857); color: #fff; padding: 2rem; display: flex; gap: 1.5rem; align-items: center; }}
|
||||||
|
.dog-photo {{ width: 100px; height: 100px; border-radius: 50%; object-fit: cover; border: 3px solid rgba(255,255,255,.6); flex-shrink: 0; }}
|
||||||
|
.dog-photo-placeholder {{ width: 100px; height: 100px; border-radius: 50%; background: rgba(255,255,255,.2); display: flex; align-items: center; justify-content: center; font-size: 2.5rem; flex-shrink: 0; }}
|
||||||
|
.header-info h1 {{ font-size: 1.8rem; font-weight: 700; }}
|
||||||
|
.header-info .rasse {{ opacity: .85; font-size: 1rem; margin-top: .2rem; }}
|
||||||
|
.meta-grid {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: .5rem; margin-top: 1rem; }}
|
||||||
|
.meta-item {{ background: rgba(255,255,255,.15); border-radius: 8px; padding: .5rem .75rem; }}
|
||||||
|
.meta-item .label {{ font-size: .65rem; opacity: .8; text-transform: uppercase; letter-spacing: .05em; }}
|
||||||
|
.meta-item .value {{ font-weight: 600; font-size: .9rem; margin-top: .1rem; }}
|
||||||
|
.body {{ padding: 1.5rem 2rem; }}
|
||||||
|
.section {{ margin-bottom: 1.5rem; }}
|
||||||
|
.section h2 {{ font-size: .8rem; text-transform: uppercase; letter-spacing: .08em; color: #C4843A; font-weight: 700; margin-bottom: .75rem; padding-bottom: .4rem; border-bottom: 2px solid #f0e8dc; }}
|
||||||
|
table {{ width: 100%; border-collapse: collapse; font-size: .85rem; }}
|
||||||
|
th {{ text-align: left; font-size: .7rem; text-transform: uppercase; letter-spacing: .05em; color: #888; font-weight: 600; padding: .4rem .5rem; border-bottom: 1px solid #eee; }}
|
||||||
|
td {{ padding: .45rem .5rem; border-bottom: 1px solid #f5f5f5; vertical-align: top; }}
|
||||||
|
tr:last-child td {{ border-bottom: none; }}
|
||||||
|
.vet-card {{ display: inline-block; background: #f9f6f2; border: 1px solid #ede5d8; border-radius: 8px; padding: .6rem 1rem; margin-right: .5rem; margin-bottom: .5rem; font-size: .85rem; line-height: 1.5; }}
|
||||||
|
.print-btn {{ display: block; margin: 0 auto 1.5rem; padding: .6rem 2rem; background: #C4843A; color: #fff; border: none; border-radius: 8px; font-size: 1rem; cursor: pointer; }}
|
||||||
|
.footer {{ text-align: center; padding: 1rem; font-size: .7rem; color: #aaa; border-top: 1px solid #f0f0f0; }}
|
||||||
|
@media print {{
|
||||||
|
body {{ background: #fff; padding: 0; }}
|
||||||
|
.ausweis {{ box-shadow: none; border-radius: 0; }}
|
||||||
|
.print-btn {{ display: none; }}
|
||||||
|
.no-print {{ display: none; }}
|
||||||
|
}}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="ausweis">
|
||||||
|
<div class="header">
|
||||||
|
{photo_html}
|
||||||
|
<div class="header-info">
|
||||||
|
<h1>{esc(dog["name"])}</h1>
|
||||||
|
<div class="rasse">{esc(dog.get("rasse") or "Rasse unbekannt")}</div>
|
||||||
|
<div class="meta-grid">
|
||||||
|
<div class="meta-item"><div class="label">Geburtstag</div><div class="value">{fmt_date(dog.get("geburtstag"))}</div></div>
|
||||||
|
<div class="meta-item"><div class="label">Geschlecht</div><div class="value">{geschlecht}</div></div>
|
||||||
|
<div class="meta-item"><div class="label">Gewicht</div><div class="value">{f'{dog["gewicht_kg"]} kg' if dog.get("gewicht_kg") else "–"}</div></div>
|
||||||
|
<div class="meta-item"><div class="label">Transponder</div><div class="value">{esc(dog.get("chip_nr")) or "–"}</div></div>
|
||||||
|
<div class="meta-item"><div class="label">Besitzer</div><div class="value">{esc(owner["name"]) if owner else "–"}</div></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="body">
|
||||||
|
<button class="print-btn no-print" onclick="window.print()">🖨 Drucken / Als PDF speichern</button>
|
||||||
|
|
||||||
|
<div class="section">
|
||||||
|
<h2>Impfungen</h2>
|
||||||
|
<table>
|
||||||
|
<thead><tr><th>Impfung</th><th>Datum</th><th>Nächste Fälligkeit</th><th>Charge</th><th>Tierarzt</th></tr></thead>
|
||||||
|
<tbody>{health_rows_html(impfungen, ["bezeichnung","datum","naechstes","charge_nr","tierarzt_name"])}</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="section">
|
||||||
|
<h2>Aktive Medikamente</h2>
|
||||||
|
<table>
|
||||||
|
<thead><tr><th>Medikament</th><th>Seit</th><th>Dosierung</th><th>Häufigkeit</th></tr></thead>
|
||||||
|
<tbody>{health_rows_html(medis, ["bezeichnung","datum","dosierung","haeufigkeit"])}</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="section">
|
||||||
|
<h2>Allergien & Unverträglichkeiten</h2>
|
||||||
|
<table>
|
||||||
|
<thead><tr><th>Allergen</th><th>Schweregrad</th><th>Reaktion</th><th>Seit</th></tr></thead>
|
||||||
|
<tbody>{health_rows_html(allergien, ["bezeichnung","schweregrad","reaktion","datum"])}</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="section">
|
||||||
|
<h2>Tierärzte</h2>
|
||||||
|
{vets_html}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="footer">Erstellt mit BAN YARO · banyaro.app · {fmt_date(__import__("datetime").date.today().isoformat())}</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>"""
|
||||||
|
return HTMLResponse(html)
|
||||||
|
|
||||||
|
|
||||||
# SPA Fallback — ALLE nicht-API-Routen gehen zur index.html
|
# SPA Fallback — ALLE nicht-API-Routen gehen zur index.html
|
||||||
@app.get("/{full_path:path}")
|
@app.get("/{full_path:path}")
|
||||||
async def spa_fallback(full_path: str):
|
async def spa_fallback(full_path: str):
|
||||||
|
|
|
||||||
|
|
@ -33,9 +33,17 @@ class DiaryUpdate(BaseModel):
|
||||||
|
|
||||||
|
|
||||||
def _own_dog(dog_id: int, user_id: int, conn):
|
def _own_dog(dog_id: int, user_id: int, conn):
|
||||||
|
"""Eigener Hund ODER geteilter Hund (angenommene Einladung)."""
|
||||||
dog = conn.execute(
|
dog = conn.execute(
|
||||||
"SELECT id FROM dogs WHERE id=? AND user_id=?", (dog_id, user_id)
|
"SELECT id FROM dogs WHERE id=? AND user_id=?", (dog_id, user_id)
|
||||||
).fetchone()
|
).fetchone()
|
||||||
|
if not dog:
|
||||||
|
dog = conn.execute(
|
||||||
|
"""SELECT d.id FROM dogs d
|
||||||
|
JOIN dog_shares ds ON ds.dog_id = d.id
|
||||||
|
WHERE d.id=? AND ds.shared_with_id=? AND ds.accepted_at IS NOT NULL""",
|
||||||
|
(dog_id, user_id)
|
||||||
|
).fetchone()
|
||||||
if not dog:
|
if not dog:
|
||||||
raise HTTPException(404, "Hund nicht gefunden.")
|
raise HTTPException(404, "Hund nicht gefunden.")
|
||||||
return dog
|
return dog
|
||||||
|
|
@ -82,10 +90,22 @@ def _entry_dict(row, dog_ids_map: dict) -> dict:
|
||||||
|
|
||||||
@router.get("/{dog_id}/diary")
|
@router.get("/{dog_id}/diary")
|
||||||
async def list_diary(dog_id: int, limit: int = 20, offset: int = 0,
|
async def list_diary(dog_id: int, limit: int = 20, offset: int = 0,
|
||||||
|
q: Optional[str] = None,
|
||||||
user=Depends(get_current_user)):
|
user=Depends(get_current_user)):
|
||||||
with db() as conn:
|
with db() as conn:
|
||||||
_own_dog(dog_id, user["id"], conn)
|
_own_dog(dog_id, user["id"], conn)
|
||||||
# Einträge des primären Hundes SOWIE Einträge wo der Hund als weiterer zugeordnet ist
|
if q:
|
||||||
|
pattern = f"%{q}%"
|
||||||
|
rows = conn.execute(
|
||||||
|
"""SELECT DISTINCT d.* FROM diary d
|
||||||
|
LEFT JOIN diary_dogs dd ON dd.diary_id = d.id
|
||||||
|
WHERE (d.dog_id = ? OR dd.dog_id = ?)
|
||||||
|
AND (d.titel LIKE ? OR d.text LIKE ? OR d.tags LIKE ?)
|
||||||
|
ORDER BY d.datum DESC, d.created_at DESC
|
||||||
|
LIMIT ? OFFSET ?""",
|
||||||
|
(dog_id, dog_id, pattern, pattern, pattern, limit, offset)
|
||||||
|
).fetchall()
|
||||||
|
else:
|
||||||
rows = conn.execute(
|
rows = conn.execute(
|
||||||
"""SELECT DISTINCT d.* FROM diary d
|
"""SELECT DISTINCT d.* FROM diary d
|
||||||
LEFT JOIN diary_dogs dd ON dd.diary_id = d.id
|
LEFT JOIN diary_dogs dd ON dd.diary_id = d.id
|
||||||
|
|
|
||||||
|
|
@ -38,10 +38,19 @@ class DogUpdate(BaseModel):
|
||||||
@router.get("")
|
@router.get("")
|
||||||
async def list_dogs(user=Depends(get_current_user)):
|
async def list_dogs(user=Depends(get_current_user)):
|
||||||
with db() as conn:
|
with db() as conn:
|
||||||
rows = conn.execute(
|
own = conn.execute(
|
||||||
"SELECT * FROM dogs WHERE user_id=? ORDER BY id", (user["id"],)
|
"SELECT *, NULL AS shared_by, NULL AS share_role FROM dogs WHERE user_id=? ORDER BY id",
|
||||||
|
(user["id"],)
|
||||||
).fetchall()
|
).fetchall()
|
||||||
return [dict(r) for r in rows]
|
shared = conn.execute(
|
||||||
|
"""SELECT d.*, u.name AS shared_by, ds.role AS share_role
|
||||||
|
FROM dog_shares ds
|
||||||
|
JOIN dogs d ON d.id = ds.dog_id
|
||||||
|
JOIN users u ON u.id = ds.owner_id
|
||||||
|
WHERE ds.shared_with_id = ? AND ds.accepted_at IS NOT NULL""",
|
||||||
|
(user["id"],)
|
||||||
|
).fetchall()
|
||||||
|
return [dict(r) for r in own] + [dict(r) for r in shared]
|
||||||
|
|
||||||
|
|
||||||
@router.post("")
|
@router.post("")
|
||||||
|
|
|
||||||
141
backend/routes/sharing.py
Normal file
141
backend/routes/sharing.py
Normal file
|
|
@ -0,0 +1,141 @@
|
||||||
|
"""BAN YARO — Hund teilen (Familie/Partner)"""
|
||||||
|
|
||||||
|
import secrets
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from database import db
|
||||||
|
from auth import get_current_user
|
||||||
|
|
||||||
|
# Hunde-spezifische Routen → eingebunden unter /api/dogs
|
||||||
|
dog_router = APIRouter()
|
||||||
|
|
||||||
|
# Token-basierte Routen → eingebunden unter /api/share
|
||||||
|
share_router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
class ShareInvite(BaseModel):
|
||||||
|
role: str = "editor" # viewer | editor
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# POST /api/dogs/{dog_id}/share → Einladungs-Link erzeugen
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
@dog_router.post("/{dog_id}/share", status_code=201)
|
||||||
|
async def create_share(dog_id: int, data: ShareInvite,
|
||||||
|
user=Depends(get_current_user)):
|
||||||
|
if data.role not in ("viewer", "editor"):
|
||||||
|
raise HTTPException(400, "Rolle muss 'viewer' oder 'editor' sein.")
|
||||||
|
|
||||||
|
with db() as conn:
|
||||||
|
dog = conn.execute(
|
||||||
|
"SELECT id, name FROM dogs WHERE id=? AND user_id=?",
|
||||||
|
(dog_id, user["id"])
|
||||||
|
).fetchone()
|
||||||
|
if not dog:
|
||||||
|
raise HTTPException(404, "Hund nicht gefunden.")
|
||||||
|
|
||||||
|
token = secrets.token_urlsafe(24)
|
||||||
|
conn.execute(
|
||||||
|
"""INSERT INTO dog_shares (dog_id, owner_id, invite_token, role)
|
||||||
|
VALUES (?, ?, ?, ?)""",
|
||||||
|
(dog_id, user["id"], token, data.role),
|
||||||
|
)
|
||||||
|
return {"token": token, "invite_path": f"/teilen/{token}"}
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# GET /api/dogs/{dog_id}/shares → aktive Einladungen auflisten
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
@dog_router.get("/{dog_id}/shares")
|
||||||
|
async def list_shares(dog_id: int, user=Depends(get_current_user)):
|
||||||
|
with db() as conn:
|
||||||
|
dog = conn.execute(
|
||||||
|
"SELECT id FROM dogs WHERE id=? AND user_id=?",
|
||||||
|
(dog_id, user["id"])
|
||||||
|
).fetchone()
|
||||||
|
if not dog:
|
||||||
|
raise HTTPException(404, "Nicht gefunden.")
|
||||||
|
rows = conn.execute(
|
||||||
|
"""SELECT ds.id, ds.invite_token, ds.role, ds.accepted_at,
|
||||||
|
u.name AS shared_with_name, u.email AS shared_with_email
|
||||||
|
FROM dog_shares ds
|
||||||
|
LEFT JOIN users u ON u.id = ds.shared_with_id
|
||||||
|
WHERE ds.dog_id = ?
|
||||||
|
ORDER BY ds.created_at DESC""",
|
||||||
|
(dog_id,)
|
||||||
|
).fetchall()
|
||||||
|
return [dict(r) for r in rows]
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# DELETE /api/dogs/{dog_id}/share/{share_id} → Freigabe widerrufen
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
@dog_router.delete("/{dog_id}/share/{share_id}", status_code=204)
|
||||||
|
async def revoke_share(dog_id: int, share_id: int,
|
||||||
|
user=Depends(get_current_user)):
|
||||||
|
with db() as conn:
|
||||||
|
dog = conn.execute(
|
||||||
|
"SELECT id FROM dogs WHERE id=? AND user_id=?",
|
||||||
|
(dog_id, user["id"])
|
||||||
|
).fetchone()
|
||||||
|
if not dog:
|
||||||
|
raise HTTPException(404, "Nicht gefunden.")
|
||||||
|
conn.execute(
|
||||||
|
"DELETE FROM dog_shares WHERE id=? AND dog_id=?",
|
||||||
|
(share_id, dog_id)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# POST /api/share/accept/{token} → Einladung annehmen
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
@share_router.post("/accept/{token}")
|
||||||
|
async def accept_share(token: str, user=Depends(get_current_user)):
|
||||||
|
with db() as conn:
|
||||||
|
share = conn.execute(
|
||||||
|
"""SELECT ds.*, d.name AS dog_name, u.name AS owner_name
|
||||||
|
FROM dog_shares ds
|
||||||
|
JOIN dogs d ON d.id = ds.dog_id
|
||||||
|
JOIN users u ON u.id = ds.owner_id
|
||||||
|
WHERE ds.invite_token = ?""",
|
||||||
|
(token,)
|
||||||
|
).fetchone()
|
||||||
|
|
||||||
|
if not share:
|
||||||
|
raise HTTPException(404, "Einladungslink ungültig oder abgelaufen.")
|
||||||
|
if share["owner_id"] == user["id"]:
|
||||||
|
raise HTTPException(400, "Das ist dein eigener Hund.")
|
||||||
|
if share["accepted_at"]:
|
||||||
|
return {"message": "Bereits angenommen.", "dog_name": share["dog_name"]}
|
||||||
|
|
||||||
|
conn.execute(
|
||||||
|
"""UPDATE dog_shares
|
||||||
|
SET shared_with_id = ?, accepted_at = datetime('now')
|
||||||
|
WHERE invite_token = ?""",
|
||||||
|
(user["id"], token),
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"message": "Einladung angenommen!",
|
||||||
|
"dog_name": share["dog_name"],
|
||||||
|
"owner_name": share["owner_name"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# GET /api/share/info/{token} → Info vor dem Annehmen (kein Auth nötig)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
@share_router.get("/info/{token}")
|
||||||
|
async def share_info(token: str):
|
||||||
|
with db() as conn:
|
||||||
|
share = conn.execute(
|
||||||
|
"""SELECT d.name AS dog_name, d.foto_url, d.rasse,
|
||||||
|
u.name AS owner_name, ds.role, ds.accepted_at
|
||||||
|
FROM dog_shares ds
|
||||||
|
JOIN dogs d ON d.id = ds.dog_id
|
||||||
|
JOIN users u ON u.id = ds.owner_id
|
||||||
|
WHERE ds.invite_token = ?""",
|
||||||
|
(token,)
|
||||||
|
).fetchone()
|
||||||
|
if not share:
|
||||||
|
raise HTTPException(404, "Einladungslink ungültig.")
|
||||||
|
return dict(share)
|
||||||
56
backend/routes/widget.py
Normal file
56
backend/routes/widget.py
Normal file
|
|
@ -0,0 +1,56 @@
|
||||||
|
"""BAN YARO — Widget-Snapshot Endpoint"""
|
||||||
|
|
||||||
|
import json, random
|
||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
from database import db
|
||||||
|
from auth import get_current_user
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/snapshot")
|
||||||
|
async def widget_snapshot(user=Depends(get_current_user)):
|
||||||
|
"""Liefert kompakte Widget-Daten: Hund, nächste Erinnerung, zufälliges Tagebuchbild."""
|
||||||
|
with db() as conn:
|
||||||
|
# Aktiver Hund (erster oder letzter genutzter)
|
||||||
|
dog = conn.execute(
|
||||||
|
"SELECT id, name, rasse, foto_url FROM dogs WHERE user_id=? ORDER BY id LIMIT 1",
|
||||||
|
(user["id"],)
|
||||||
|
).fetchone()
|
||||||
|
|
||||||
|
if not dog:
|
||||||
|
return {"dog": None}
|
||||||
|
|
||||||
|
dog_id = dog["id"]
|
||||||
|
|
||||||
|
# Nächste fällige Erinnerung
|
||||||
|
reminder = conn.execute(
|
||||||
|
"""SELECT bezeichnung, naechstes, typ FROM health
|
||||||
|
WHERE dog_id=? AND naechstes IS NOT NULL AND naechstes >= date('now')
|
||||||
|
ORDER BY naechstes ASC LIMIT 1""",
|
||||||
|
(dog_id,)
|
||||||
|
).fetchone()
|
||||||
|
|
||||||
|
# Zufälliges Tagebuchbild (letzte 50 Einträge mit Bild)
|
||||||
|
photos = conn.execute(
|
||||||
|
"""SELECT media_url, titel, datum FROM diary
|
||||||
|
WHERE dog_id=? AND media_url IS NOT NULL
|
||||||
|
ORDER BY datum DESC LIMIT 50""",
|
||||||
|
(dog_id,)
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
random_photo = dict(random.choice(photos)) if photos else None
|
||||||
|
|
||||||
|
# Anzahl überfälliger Erinnerungen
|
||||||
|
overdue = conn.execute(
|
||||||
|
"""SELECT COUNT(*) as n FROM health
|
||||||
|
WHERE dog_id=? AND naechstes IS NOT NULL AND naechstes < date('now')""",
|
||||||
|
(dog_id,)
|
||||||
|
).fetchone()["n"]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"dog": dict(dog),
|
||||||
|
"reminder": dict(reminder) if reminder else None,
|
||||||
|
"random_photo": random_photo,
|
||||||
|
"overdue": overdue,
|
||||||
|
}
|
||||||
|
|
@ -239,6 +239,90 @@
|
||||||
.health-transponder-label { color: var(--c-text-muted); }
|
.health-transponder-label { color: var(--c-text-muted); }
|
||||||
.health-transponder-edit { margin-left: auto; }
|
.health-transponder-edit { margin-left: auto; }
|
||||||
|
|
||||||
|
/* Diary: Suchleiste */
|
||||||
|
.diary-search-wrap {
|
||||||
|
position: relative;
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.diary-search-icon {
|
||||||
|
position: absolute;
|
||||||
|
left: var(--space-3);
|
||||||
|
top: 50%;
|
||||||
|
transform: translateY(-50%);
|
||||||
|
color: var(--c-text-muted);
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
.diary-search-input {
|
||||||
|
width: 100%;
|
||||||
|
padding: var(--space-2) var(--space-3) var(--space-2) 2.2rem;
|
||||||
|
border: 1.5px solid var(--c-border);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
font-family: var(--font-sans);
|
||||||
|
background: var(--c-bg);
|
||||||
|
color: var(--c-text);
|
||||||
|
outline: none;
|
||||||
|
transition: border-color var(--transition-fast);
|
||||||
|
}
|
||||||
|
.diary-search-input:focus { border-color: var(--c-primary); }
|
||||||
|
|
||||||
|
/* Widget-Karte */
|
||||||
|
.widget-card {
|
||||||
|
background: var(--c-surface);
|
||||||
|
border-radius: var(--radius-xl);
|
||||||
|
overflow: hidden;
|
||||||
|
box-shadow: var(--shadow-sm);
|
||||||
|
}
|
||||||
|
.widget-dog-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-3);
|
||||||
|
padding: var(--space-4);
|
||||||
|
}
|
||||||
|
.widget-dog-av {
|
||||||
|
width: 48px; height: 48px; border-radius: 50%;
|
||||||
|
object-fit: cover; border: 2px solid var(--c-primary-light);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.widget-dog-av--placeholder {
|
||||||
|
display: flex; align-items: center; justify-content: center;
|
||||||
|
background: var(--c-surface-2); font-size: 1.5rem;
|
||||||
|
}
|
||||||
|
.widget-reminder {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-3);
|
||||||
|
padding: var(--space-3) var(--space-4);
|
||||||
|
background: var(--c-primary-subtle);
|
||||||
|
color: var(--c-primary-dark);
|
||||||
|
border-top: 1px solid var(--c-border-light);
|
||||||
|
}
|
||||||
|
.widget-reminder--overdue { background: var(--c-danger-subtle); color: var(--c-danger); }
|
||||||
|
.widget-reminder--ok { background: var(--c-success-subtle); color: var(--c-success); }
|
||||||
|
.widget-photo-wrap {
|
||||||
|
position: relative;
|
||||||
|
aspect-ratio: 4/3;
|
||||||
|
overflow: hidden;
|
||||||
|
border-top: 1px solid var(--c-border-light);
|
||||||
|
display: flex; align-items: center; justify-content: center;
|
||||||
|
background: var(--c-surface-2);
|
||||||
|
}
|
||||||
|
.widget-photo { width: 100%; height: 100%; object-fit: cover; display: block; }
|
||||||
|
.widget-photo-placeholder { flex-direction: column; gap: var(--space-2); }
|
||||||
|
.widget-photo-caption {
|
||||||
|
position: absolute;
|
||||||
|
bottom: 0; left: 0; right: 0;
|
||||||
|
padding: var(--space-2) var(--space-3);
|
||||||
|
background: linear-gradient(transparent, rgba(0,0,0,.55));
|
||||||
|
color: #fff;
|
||||||
|
font-size: var(--text-sm);
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: flex-end;
|
||||||
|
}
|
||||||
|
.widget-photo-date { font-size: var(--text-xs); opacity: .8; }
|
||||||
|
|
||||||
/* Import: Format-Auswahl-Karten */
|
/* Import: Format-Auswahl-Karten */
|
||||||
.import-format-card {
|
.import-format-card {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|
|
||||||
|
|
@ -247,6 +247,10 @@
|
||||||
<div class="page-body page-container"></div>
|
<div class="page-body page-container"></div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="page" id="page-widget">
|
||||||
|
<div class="page-body page-container"></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
<!-- MOBILE BOTTOM NAVIGATION -->
|
<!-- MOBILE BOTTOM NAVIGATION -->
|
||||||
|
|
|
||||||
|
|
@ -408,6 +408,18 @@ const API = (() => {
|
||||||
resetToken: () => del('/webcal/token'),
|
resetToken: () => del('/webcal/token'),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const sharing = {
|
||||||
|
create: (dogId, role) => post(`/dogs/${dogId}/share`, { role }),
|
||||||
|
list: (dogId) => get(`/dogs/${dogId}/shares`),
|
||||||
|
revoke: (dogId, id) => del(`/dogs/${dogId}/share/${id}`),
|
||||||
|
accept: (token) => post(`/share/accept/${token}`, {}),
|
||||||
|
info: (token) => get(`/share/info/${token}`),
|
||||||
|
};
|
||||||
|
|
||||||
|
const widget = {
|
||||||
|
snapshot: () => get('/widget/snapshot'),
|
||||||
|
};
|
||||||
|
|
||||||
const importData = {
|
const importData = {
|
||||||
notestation(dogId, file) {
|
notestation(dogId, file) {
|
||||||
const fd = new FormData();
|
const fd = new FormData();
|
||||||
|
|
@ -440,7 +452,7 @@ const API = (() => {
|
||||||
get, post, put, patch, del, upload,
|
get, post, put, patch, del, upload,
|
||||||
auth, dogs, diary, health, tieraerzte, poison,
|
auth, dogs, diary, health, tieraerzte, poison,
|
||||||
places, routes, walks, events, sitting, forum, lost, knigge, weather, push,
|
places, routes, walks, events, sitting, forum, lost, knigge, weather, push,
|
||||||
friends, chat, webcal, importData,
|
friends, chat, webcal, importData, sharing, widget,
|
||||||
subscribeToPush, getLocation,
|
subscribeToPush, getLocation,
|
||||||
APIError,
|
APIError,
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
Router, State-Management, Navigation, Initialisierung.
|
Router, State-Management, Navigation, Initialisierung.
|
||||||
============================================================ */
|
============================================================ */
|
||||||
|
|
||||||
const APP_VER = '116'; // ← bei jedem Deploy mit Frontend-Änderungen erhöhen
|
const APP_VER = '117'; // ← bei jedem Deploy mit Frontend-Änderungen erhöhen
|
||||||
|
|
||||||
const App = (() => {
|
const App = (() => {
|
||||||
|
|
||||||
|
|
@ -56,6 +56,7 @@ const App = (() => {
|
||||||
admin: { title: 'Admin', module: null, requiresAuth: true },
|
admin: { title: 'Admin', module: null, requiresAuth: true },
|
||||||
impressum: { title: 'Impressum', module: null },
|
impressum: { title: 'Impressum', module: null },
|
||||||
datenschutz: { title: 'Datenschutz', module: null },
|
datenschutz: { title: 'Datenschutz', module: null },
|
||||||
|
widget: { title: 'Widget', module: null, requiresAuth: true },
|
||||||
};
|
};
|
||||||
|
|
||||||
// ----------------------------------------------------------
|
// ----------------------------------------------------------
|
||||||
|
|
@ -573,9 +574,16 @@ const App = (() => {
|
||||||
_bindNavigation();
|
_bindNavigation();
|
||||||
await _checkAuth();
|
await _checkAuth();
|
||||||
|
|
||||||
|
// Einladungslink /teilen/{token} → direkt annehmen
|
||||||
|
const inviteMatch = location.pathname.match(/^\/teilen\/([A-Za-z0-9_-]+)$/);
|
||||||
|
if (inviteMatch) {
|
||||||
|
const token = inviteMatch[1];
|
||||||
|
navigate('diary', false);
|
||||||
|
_handleInvite(token);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// Erste Seite laden: Hash aus URL oder Standard 'diary'.
|
// Erste Seite laden: Hash aus URL oder Standard 'diary'.
|
||||||
// Bewusst NACH _checkAuth(), damit _loadPage() nur einmal aufgerufen wird
|
|
||||||
// (vorher war Hash-Navigation auch in _bindNavigation() → doppelter Aufruf).
|
|
||||||
const rawHash = location.hash.replace('#', '');
|
const rawHash = location.hash.replace('#', '');
|
||||||
const [hashPage, hashQuery] = rawHash.split('?');
|
const [hashPage, hashQuery] = rawHash.split('?');
|
||||||
const hashParams = {};
|
const hashParams = {};
|
||||||
|
|
@ -588,6 +596,38 @@ const App = (() => {
|
||||||
navigate(startPage, false, hashParams);
|
navigate(startPage, false, hashParams);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function _handleInvite(token) {
|
||||||
|
try {
|
||||||
|
const info = await API.sharing.info(token);
|
||||||
|
if (info.accepted_at) {
|
||||||
|
UI.toast.success(`Du hast bereits Zugriff auf ${info.dog_name}.`);
|
||||||
|
history.replaceState(null, '', '/');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const ok = await UI.modal.confirm(
|
||||||
|
`<strong>${UI.escape(info.owner_name)}</strong> möchte das Profil von
|
||||||
|
<strong>${UI.escape(info.dog_name)}</strong> mit dir teilen
|
||||||
|
(${info.role === 'editor' ? 'Lesen & Schreiben' : 'Nur lesen'}).
|
||||||
|
Möchtest du die Einladung annehmen?`
|
||||||
|
);
|
||||||
|
if (!ok) { history.replaceState(null, '', '/'); return; }
|
||||||
|
await API.sharing.accept(token);
|
||||||
|
// Hundeliste neu laden
|
||||||
|
state.dogs = await API.dogs.list();
|
||||||
|
const newDog = state.dogs.find(d => d.name === info.dog_name);
|
||||||
|
if (newDog) {
|
||||||
|
state.activeDog = newDog;
|
||||||
|
localStorage.setItem('by_active_dog', String(newDog.id));
|
||||||
|
_renderDogSwitcher();
|
||||||
|
}
|
||||||
|
history.replaceState(null, '', '/');
|
||||||
|
UI.toast.success(`${UI.escape(info.dog_name)} wurde deiner Liste hinzugefügt!`);
|
||||||
|
} catch (e) {
|
||||||
|
UI.toast.error(e.message || 'Einladungslink ungültig.');
|
||||||
|
history.replaceState(null, '', '/');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ----------------------------------------------------------
|
// ----------------------------------------------------------
|
||||||
// AUTH-GATE HELPER — einheitlicher "Bitte anmelden"-Block
|
// AUTH-GATE HELPER — einheitlicher "Bitte anmelden"-Block
|
||||||
// ----------------------------------------------------------
|
// ----------------------------------------------------------
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@ window.Page_diary = (() => {
|
||||||
let _appState = null;
|
let _appState = null;
|
||||||
let _entries = [];
|
let _entries = [];
|
||||||
let _offset = 0;
|
let _offset = 0;
|
||||||
|
let _searchQuery = '';
|
||||||
const LIMIT = 20;
|
const LIMIT = 20;
|
||||||
|
|
||||||
const TYPEN = {
|
const TYPEN = {
|
||||||
|
|
@ -55,7 +56,7 @@ window.Page_diary = (() => {
|
||||||
async function onDogChange(dog) {
|
async function onDogChange(dog) {
|
||||||
_offset = 0;
|
_offset = 0;
|
||||||
_entries = [];
|
_entries = [];
|
||||||
// Direkt Diary laden — Hund wurde bereits extern gewählt
|
_searchQuery = '';
|
||||||
await _renderDiary();
|
await _renderDiary();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -136,9 +137,13 @@ window.Page_diary = (() => {
|
||||||
async function _renderDiary() {
|
async function _renderDiary() {
|
||||||
_container.innerHTML = `
|
_container.innerHTML = `
|
||||||
<div class="by-toolbar diary-toolbar">
|
<div class="by-toolbar diary-toolbar">
|
||||||
<button class="btn btn-secondary btn-sm" id="diary-import-btn">
|
<div class="diary-search-wrap" id="diary-search-wrap">
|
||||||
|
<svg class="ph-icon diary-search-icon" aria-hidden="true"><use href="/icons/phosphor.svg#magnifying-glass"></use></svg>
|
||||||
|
<input type="search" class="diary-search-input" id="diary-search-input"
|
||||||
|
placeholder="Einträge durchsuchen…" autocomplete="off">
|
||||||
|
</div>
|
||||||
|
<button class="btn btn-secondary btn-sm" id="diary-import-btn" title="Importieren">
|
||||||
<svg class="ph-icon" aria-hidden="true"><use href="/icons/phosphor.svg#download-simple"></use></svg>
|
<svg class="ph-icon" aria-hidden="true"><use href="/icons/phosphor.svg#download-simple"></use></svg>
|
||||||
Importieren
|
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div id="diary-list"></div>
|
<div id="diary-list"></div>
|
||||||
|
|
@ -152,6 +157,20 @@ window.Page_diary = (() => {
|
||||||
_container.querySelector('#diary-btn-more')
|
_container.querySelector('#diary-btn-more')
|
||||||
?.addEventListener('click', () => _loadMore());
|
?.addEventListener('click', () => _loadMore());
|
||||||
|
|
||||||
|
// Suche mit Debounce
|
||||||
|
let _searchTimer = null;
|
||||||
|
_container.querySelector('#diary-search-input')
|
||||||
|
?.addEventListener('input', e => {
|
||||||
|
clearTimeout(_searchTimer);
|
||||||
|
_searchTimer = setTimeout(async () => {
|
||||||
|
_offset = 0;
|
||||||
|
_entries = [];
|
||||||
|
_searchQuery = e.target.value.trim();
|
||||||
|
await _load();
|
||||||
|
_renderList();
|
||||||
|
}, 350);
|
||||||
|
});
|
||||||
|
|
||||||
await _load();
|
await _load();
|
||||||
_renderList();
|
_renderList();
|
||||||
}
|
}
|
||||||
|
|
@ -163,7 +182,9 @@ window.Page_diary = (() => {
|
||||||
const dog = _appState.activeDog;
|
const dog = _appState.activeDog;
|
||||||
if (!dog) return;
|
if (!dog) return;
|
||||||
try {
|
try {
|
||||||
const batch = await API.diary.list(dog.id, { limit: LIMIT, offset: _offset });
|
const params = { limit: LIMIT, offset: _offset };
|
||||||
|
if (_searchQuery) params.q = _searchQuery;
|
||||||
|
const batch = await API.diary.list(dog.id, params);
|
||||||
_entries = _entries.concat(batch);
|
_entries = _entries.concat(batch);
|
||||||
|
|
||||||
// "Mehr laden" anzeigen wenn volle Page geladen wurde
|
// "Mehr laden" anzeigen wenn volle Page geladen wurde
|
||||||
|
|
|
||||||
|
|
@ -188,6 +188,16 @@ window.Page_dog_profile = (() => {
|
||||||
<button class="btn btn-primary w-full" id="dp-edit-btn">
|
<button class="btn btn-primary w-full" id="dp-edit-btn">
|
||||||
Profil bearbeiten
|
Profil bearbeiten
|
||||||
</button>
|
</button>
|
||||||
|
<div style="display:flex;gap:var(--space-2)">
|
||||||
|
<button class="btn btn-secondary" style="flex:1" id="dp-ausweis-btn">
|
||||||
|
<svg class="ph-icon" aria-hidden="true"><use href="/icons/phosphor.svg#identification-card"></use></svg>
|
||||||
|
Ausweis
|
||||||
|
</button>
|
||||||
|
<button class="btn btn-secondary" style="flex:1" id="dp-share-btn">
|
||||||
|
<svg class="ph-icon" aria-hidden="true"><use href="/icons/phosphor.svg#share-network"></use></svg>
|
||||||
|
Teilen
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
<button class="btn btn-secondary w-full" id="dp-add-dog-btn">
|
<button class="btn btn-secondary w-full" id="dp-add-dog-btn">
|
||||||
+ Weiteren Hund anlegen
|
+ Weiteren Hund anlegen
|
||||||
</button>
|
</button>
|
||||||
|
|
@ -240,6 +250,14 @@ window.Page_dog_profile = (() => {
|
||||||
_showChipEdit(dog);
|
_showChipEdit(dog);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
document.getElementById('dp-ausweis-btn')?.addEventListener('click', () => {
|
||||||
|
window.open(`/ausweis/${dog.id}`, '_blank');
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('dp-share-btn')?.addEventListener('click', () => {
|
||||||
|
_showShareModal(dog);
|
||||||
|
});
|
||||||
|
|
||||||
// Edit- und Add-Klicks laufen über Event-Delegation in init() — keine direkten Listener nötig.
|
// Edit- und Add-Klicks laufen über Event-Delegation in init() — keine direkten Listener nötig.
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -275,6 +293,102 @@ window.Page_dog_profile = (() => {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------
|
||||||
|
// TEILEN
|
||||||
|
// ----------------------------------------------------------
|
||||||
|
async function _showShareModal(dog) {
|
||||||
|
UI.modal.open({
|
||||||
|
title: `${_esc(dog.name)} teilen`,
|
||||||
|
body: `
|
||||||
|
<p style="font-size:var(--text-sm);color:var(--c-text-secondary);margin-bottom:var(--space-4)">
|
||||||
|
Erstelle einen Einladungslink, den du per WhatsApp, Signal oder E-Mail teilen kannst.
|
||||||
|
Die eingeladene Person sieht Tagebuch und Gesundheitsakte nach dem Annehmen.
|
||||||
|
</p>
|
||||||
|
<div class="form-group">
|
||||||
|
<label class="form-label">Berechtigung</label>
|
||||||
|
<select class="form-control" id="share-role-select">
|
||||||
|
<option value="editor">Mitschreiben (Tagebuch & Gesundheit bearbeiten)</option>
|
||||||
|
<option value="viewer">Nur lesen</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div id="share-link-result" style="display:none;margin-top:var(--space-4)">
|
||||||
|
<label class="form-label">Einladungslink</label>
|
||||||
|
<div style="display:flex;gap:var(--space-2);align-items:center">
|
||||||
|
<input class="form-control" id="share-link-input" type="text" readonly
|
||||||
|
style="font-size:var(--text-xs)">
|
||||||
|
<button class="btn btn-secondary btn-sm" id="share-link-copy">
|
||||||
|
<svg class="ph-icon" aria-hidden="true"><use href="/icons/phosphor.svg#clipboard-text"></use></svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p style="font-size:var(--text-xs);color:var(--c-text-muted);margin-top:var(--space-2)">
|
||||||
|
Dieser Link kann einmalig angenommen werden.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div id="share-list-wrap" style="margin-top:var(--space-4)"></div>`,
|
||||||
|
footer: `
|
||||||
|
<button class="btn btn-secondary" onclick="UI.modal.close()">Schließen</button>
|
||||||
|
<button class="btn btn-primary" id="share-create-btn">Link erstellen</button>`,
|
||||||
|
});
|
||||||
|
|
||||||
|
_loadShareList(dog.id);
|
||||||
|
|
||||||
|
document.getElementById('share-create-btn').addEventListener('click', async () => {
|
||||||
|
const role = document.getElementById('share-role-select').value;
|
||||||
|
const btn = document.getElementById('share-create-btn');
|
||||||
|
UI.setLoading(btn, true);
|
||||||
|
try {
|
||||||
|
const res = await API.sharing.create(dog.id, role);
|
||||||
|
const link = `${location.origin}${res.invite_path}`;
|
||||||
|
const inp = document.getElementById('share-link-input');
|
||||||
|
inp.value = link;
|
||||||
|
document.getElementById('share-link-result').style.display = 'block';
|
||||||
|
document.getElementById('share-link-copy').onclick = async () => {
|
||||||
|
await navigator.clipboard.writeText(link).catch(() => {});
|
||||||
|
UI.toast.success('Link kopiert!');
|
||||||
|
};
|
||||||
|
UI.setLoading(btn, false);
|
||||||
|
_loadShareList(dog.id);
|
||||||
|
} catch (e) {
|
||||||
|
UI.setLoading(btn, false);
|
||||||
|
UI.toast.error(e.message || 'Fehler');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function _loadShareList(dogId) {
|
||||||
|
const wrap = document.getElementById('share-list-wrap');
|
||||||
|
if (!wrap) return;
|
||||||
|
try {
|
||||||
|
const shares = await API.sharing.list(dogId);
|
||||||
|
if (!shares.length) { wrap.innerHTML = ''; return; }
|
||||||
|
wrap.innerHTML = `
|
||||||
|
<div style="font-size:var(--text-xs);color:var(--c-text-muted);margin-bottom:var(--space-2)">
|
||||||
|
Aktive Einladungen
|
||||||
|
</div>` +
|
||||||
|
shares.map(s => `
|
||||||
|
<div style="display:flex;align-items:center;gap:var(--space-2);
|
||||||
|
padding:var(--space-2) var(--space-3);background:var(--c-surface);
|
||||||
|
border-radius:var(--radius-md);margin-bottom:var(--space-1)">
|
||||||
|
<svg class="ph-icon" aria-hidden="true"><use href="/icons/phosphor.svg#user"></use></svg>
|
||||||
|
<div style="flex:1;font-size:var(--text-sm)">
|
||||||
|
${s.shared_with_name
|
||||||
|
? `<strong>${_esc(s.shared_with_name)}</strong> · ${s.role}`
|
||||||
|
: `<em style="color:var(--c-text-muted)">Ausstehend</em> · ${s.role}`}
|
||||||
|
</div>
|
||||||
|
<button class="btn btn-link btn-sm share-revoke-btn" data-share-id="${s.id}"
|
||||||
|
style="color:var(--c-danger);padding:0">
|
||||||
|
<svg class="ph-icon" aria-hidden="true"><use href="/icons/phosphor.svg#x"></use></svg>
|
||||||
|
</button>
|
||||||
|
</div>`).join('');
|
||||||
|
wrap.querySelectorAll('.share-revoke-btn').forEach(btn => {
|
||||||
|
btn.addEventListener('click', async () => {
|
||||||
|
await API.sharing.revoke(dogId, parseInt(btn.dataset.shareId));
|
||||||
|
_loadShareList(dogId);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
} catch (e) { /* ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
// ----------------------------------------------------------
|
// ----------------------------------------------------------
|
||||||
// NEU ANLEGEN (direkt auf der Seite, kein Modal)
|
// NEU ANLEGEN (direkt auf der Seite, kein Modal)
|
||||||
// ----------------------------------------------------------
|
// ----------------------------------------------------------
|
||||||
|
|
|
||||||
145
backend/static/js/pages/widget.js
Normal file
145
backend/static/js/pages/widget.js
Normal file
|
|
@ -0,0 +1,145 @@
|
||||||
|
/* BAN YARO — Widget-Vorschau (Home-Screen-Widget) */
|
||||||
|
|
||||||
|
window.Page_widget = (() => {
|
||||||
|
|
||||||
|
let _container = null;
|
||||||
|
let _appState = null;
|
||||||
|
let _refreshTimer = null;
|
||||||
|
|
||||||
|
async function init(container, appState) {
|
||||||
|
_container = container;
|
||||||
|
_appState = appState;
|
||||||
|
await _render();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refresh() {
|
||||||
|
await _render();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function _render() {
|
||||||
|
_container.innerHTML = `
|
||||||
|
<div style="padding:var(--space-4)">
|
||||||
|
<div style="text-align:center;color:var(--c-text-muted);padding:var(--space-8)">
|
||||||
|
<div style="font-size:2rem">⏳</div>
|
||||||
|
<div>Lade…</div>
|
||||||
|
</div>
|
||||||
|
</div>`;
|
||||||
|
|
||||||
|
if (!_appState.activeDog) {
|
||||||
|
_container.innerHTML = UI.emptyState({
|
||||||
|
icon: UI.icon('dog'),
|
||||||
|
title: 'Kein Hund angelegt',
|
||||||
|
text: 'Erstelle zuerst ein Hundeprofil.',
|
||||||
|
action: `<button class="btn btn-primary" onclick="App.navigate('dog-profile')">Profil erstellen</button>`,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let data;
|
||||||
|
try {
|
||||||
|
data = await API.widget.snapshot();
|
||||||
|
} catch (e) {
|
||||||
|
_container.innerHTML = '<p style="padding:2rem;color:red">Fehler beim Laden.</p>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const dog = data.dog;
|
||||||
|
const photo = data.random_photo;
|
||||||
|
const rem = data.reminder;
|
||||||
|
|
||||||
|
const photoHtml = photo
|
||||||
|
? `<div class="widget-photo-wrap">
|
||||||
|
<img src="${_esc(photo.media_url)}" alt="${_esc(photo.titel || '')}" class="widget-photo">
|
||||||
|
<div class="widget-photo-caption">
|
||||||
|
${_esc(photo.titel || '')}
|
||||||
|
<span class="widget-photo-date">${_fmtDate(photo.datum)}</span>
|
||||||
|
</div>
|
||||||
|
</div>`
|
||||||
|
: `<div class="widget-photo-wrap widget-photo-placeholder">
|
||||||
|
<svg class="ph-icon" style="font-size:3rem" aria-hidden="true"><use href="/icons/phosphor.svg#image"></use></svg>
|
||||||
|
<div style="color:var(--c-text-muted);font-size:var(--text-sm)">Noch keine Fotos im Tagebuch</div>
|
||||||
|
</div>`;
|
||||||
|
|
||||||
|
const reminderHtml = rem
|
||||||
|
? `<div class="widget-reminder">
|
||||||
|
<svg class="ph-icon" aria-hidden="true"><use href="/icons/phosphor.svg#calendar-check"></use></svg>
|
||||||
|
<div>
|
||||||
|
<div style="font-weight:var(--weight-semibold);font-size:var(--text-sm)">${_esc(rem.bezeichnung)}</div>
|
||||||
|
<div style="font-size:var(--text-xs);color:var(--c-text-muted)">${_fmtDate(rem.naechstes)}</div>
|
||||||
|
</div>
|
||||||
|
</div>`
|
||||||
|
: data.overdue > 0
|
||||||
|
? `<div class="widget-reminder widget-reminder--overdue">
|
||||||
|
<svg class="ph-icon" aria-hidden="true"><use href="/icons/phosphor.svg#warning"></use></svg>
|
||||||
|
<div style="font-size:var(--text-sm)">${data.overdue} überfällige Erinnerung${data.overdue > 1 ? 'en' : ''}</div>
|
||||||
|
</div>`
|
||||||
|
: `<div class="widget-reminder widget-reminder--ok">
|
||||||
|
<svg class="ph-icon" aria-hidden="true"><use href="/icons/phosphor.svg#check-circle"></use></svg>
|
||||||
|
<div style="font-size:var(--text-sm)">Keine offenen Erinnerungen</div>
|
||||||
|
</div>`;
|
||||||
|
|
||||||
|
const dogAvatar = dog.foto_url
|
||||||
|
? `<img src="${_esc(dog.foto_url)}" class="widget-dog-av" alt="${_esc(dog.name)}">`
|
||||||
|
: `<div class="widget-dog-av widget-dog-av--placeholder">🐕</div>`;
|
||||||
|
|
||||||
|
_container.innerHTML = `
|
||||||
|
<div style="padding:var(--space-4)">
|
||||||
|
|
||||||
|
<div class="widget-card">
|
||||||
|
<div class="widget-dog-row">
|
||||||
|
${dogAvatar}
|
||||||
|
<div>
|
||||||
|
<div style="font-weight:var(--weight-bold);font-size:var(--text-lg)">${_esc(dog.name)}</div>
|
||||||
|
${dog.rasse ? `<div style="font-size:var(--text-sm);color:var(--c-text-muted)">${_esc(dog.rasse)}</div>` : ''}
|
||||||
|
</div>
|
||||||
|
<button class="btn btn-secondary btn-sm" id="widget-refresh-btn" style="margin-left:auto"
|
||||||
|
title="Neues Zufallsbild">
|
||||||
|
<svg class="ph-icon" aria-hidden="true"><use href="/icons/phosphor.svg#arrows-clockwise"></use></svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
${reminderHtml}
|
||||||
|
${photoHtml}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="margin-top:var(--space-4);padding:var(--space-3) var(--space-4);
|
||||||
|
background:var(--c-surface);border-radius:var(--radius-md);
|
||||||
|
border:1px solid var(--c-border)">
|
||||||
|
<div style="font-size:var(--text-sm);font-weight:var(--weight-semibold);
|
||||||
|
margin-bottom:var(--space-2)">
|
||||||
|
<svg class="ph-icon" aria-hidden="true"><use href="/icons/phosphor.svg#device-mobile"></use></svg>
|
||||||
|
Als Home-Screen-Widget nutzen
|
||||||
|
</div>
|
||||||
|
<p style="font-size:var(--text-xs);color:var(--c-text-secondary);margin-bottom:var(--space-3)">
|
||||||
|
Füge diese Seite zum Home-Screen hinzu und öffne sie mit einem Tipp.
|
||||||
|
</p>
|
||||||
|
<div style="display:flex;flex-direction:column;gap:var(--space-2)">
|
||||||
|
<div style="font-size:var(--text-xs);color:var(--c-text-muted)">
|
||||||
|
<strong>iOS Safari:</strong> Teilen-Symbol → „Zum Home-Bildschirm"
|
||||||
|
</div>
|
||||||
|
<div style="font-size:var(--text-xs);color:var(--c-text-muted)">
|
||||||
|
<strong>Android Chrome:</strong> Menü (⋮) → „Zum Startbildschirm hinzufügen"
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>`;
|
||||||
|
|
||||||
|
_container.querySelector('#widget-refresh-btn')?.addEventListener('click', () => _render());
|
||||||
|
}
|
||||||
|
|
||||||
|
function _esc(str) {
|
||||||
|
if (!str) return '';
|
||||||
|
return String(str).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
|
||||||
|
}
|
||||||
|
|
||||||
|
function _fmtDate(d) {
|
||||||
|
if (!d) return '';
|
||||||
|
try {
|
||||||
|
const [y, m, day] = d.split('-');
|
||||||
|
return `${parseInt(day)}.${parseInt(m)}.${y}`;
|
||||||
|
} catch { return d; }
|
||||||
|
}
|
||||||
|
|
||||||
|
return { init, refresh };
|
||||||
|
|
||||||
|
})();
|
||||||
|
|
@ -31,6 +31,13 @@
|
||||||
"url": "/#diary",
|
"url": "/#diary",
|
||||||
"icons": [{ "src": "/icons/icon-192.png", "sizes": "192x192" }]
|
"icons": [{ "src": "/icons/icon-192.png", "sizes": "192x192" }]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"name": "Widget",
|
||||||
|
"short_name": "Widget",
|
||||||
|
"description": "Nächste Erinnerung + zufälliges Tagebuchbild",
|
||||||
|
"url": "/#widget",
|
||||||
|
"icons": [{ "src": "/icons/icon-192.png", "sizes": "192x192" }]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"name": "Giftköder melden",
|
"name": "Giftköder melden",
|
||||||
"url": "/#poison",
|
"url": "/#poison",
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
Offline-Cache + Push Notifications + Tile-Cache
|
Offline-Cache + Push Notifications + Tile-Cache
|
||||||
============================================================ */
|
============================================================ */
|
||||||
|
|
||||||
const CACHE_VERSION = 'by-v143';
|
const CACHE_VERSION = 'by-v144';
|
||||||
const CACHE_STATIC = `${CACHE_VERSION}-static`;
|
const CACHE_STATIC = `${CACHE_VERSION}-static`;
|
||||||
const CACHE_TILES = 'ban-yaro-tiles-v1'; // bleibt über SW-Updates erhalten
|
const CACHE_TILES = 'ban-yaro-tiles-v1'; // bleibt über SW-Updates erhalten
|
||||||
|
|
||||||
|
|
|
||||||
BIN
diary/20260417_150753_8657_rene.nsx
Normal file
BIN
diary/20260417_150753_8657_rene.nsx
Normal file
Binary file not shown.
Loading…
Add table
Add a link
Reference in a new issue