Sprint 8: Events + Hundesitting

Events:
- Backend events.py: CRUD, Typen (ausstellung/training/treffen/markt/wettkampf/sonstiges)
  Haversine-Filter, Monats-Gruppierung in der Liste
- Frontend events.js: Liste/Karte-Toggle, Typ-Filter-Chips, farbige Marker,
  Detail-Modal, Erstellen/Bearbeiten-Formular mit GPS-Button

Hundesitting:
- Backend sitting.py: Sitter-Profile (create/update/me), Anfragen (send/accept/decline/cancel),
  Inbox für Sitter, Haversine-Sortierung, Service-Filter
- Frontend sitting.js: 3 Tabs (Suchen/Profil/Anfragen), Sitter-Karten mit Distanz,
  Detail-Modal + Anfrage-Formular, Profil-Verwaltung

DB: events, sitters, sitting_requests Tabellen hinzugefügt
SW-Cache: by-v21 → by-v22
This commit is contained in:
rene 2026-04-14 06:19:15 +02:00
parent ec17dfb029
commit 5f8fd3bd51
9 changed files with 1680 additions and 2 deletions

153
backend/routes/events.py Normal file
View file

@ -0,0 +1,153 @@
"""BAN YARO — Events (Hundeveranstaltungen)"""
import math
from datetime import date
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from typing import Optional
from database import db
from auth import get_current_user
router = APIRouter()
TYPEN = {'ausstellung', 'training', 'treffen', 'markt', 'wettkampf', 'sonstiges'}
def _haversine(lat1, lon1, lat2, lon2):
R = 6_371_000
p1, p2 = math.radians(lat1), math.radians(lat2)
dp = math.radians(lat2 - lat1)
dl = math.radians(lon2 - lon1)
a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
return 2 * R * math.asin(math.sqrt(a))
# ------------------------------------------------------------------
# Schemas
# ------------------------------------------------------------------
class EventCreate(BaseModel):
titel: str
datum: str # YYYY-MM-DD
uhrzeit: Optional[str] = None
lat: Optional[float] = None
lon: Optional[float] = None
ort_name: Optional[str] = None
typ: str = 'sonstiges'
beschreibung: Optional[str] = None
link: Optional[str] = None
class EventUpdate(BaseModel):
titel: Optional[str] = None
datum: Optional[str] = None
uhrzeit: Optional[str] = None
lat: Optional[float] = None
lon: Optional[float] = None
ort_name: Optional[str] = None
typ: Optional[str] = None
beschreibung: Optional[str] = None
link: Optional[str] = None
# ------------------------------------------------------------------
# GET /api/events
# ------------------------------------------------------------------
@router.get("")
async def list_events(
lat: Optional[float] = None,
lon: Optional[float] = None,
radius: int = 50000,
typ: Optional[str] = None,
alle: bool = False,
):
today = date.today().isoformat()
with db() as conn:
q = "SELECT e.*, u.name AS veranstalter_name FROM events e LEFT JOIN users u ON u.id = e.user_id WHERE e.status = 'aktiv'"
if not alle:
q += f" AND e.datum >= '{today}'"
if typ and typ in TYPEN:
q += f" AND e.typ = '{typ}'"
q += " ORDER BY e.datum ASC, e.uhrzeit ASC"
rows = conn.execute(q).fetchall()
result = [dict(r) for r in rows]
if lat is not None and lon is not None:
result = [r for r in result
if r['lat'] is None or _haversine(lat, lon, r['lat'], r['lon']) <= radius]
return result
# ------------------------------------------------------------------
# POST /api/events
# ------------------------------------------------------------------
@router.post("", status_code=201)
async def create_event(data: EventCreate, user=Depends(get_current_user)):
if data.typ not in TYPEN:
raise HTTPException(400, f"Ungültiger Typ. Erlaubt: {', '.join(TYPEN)}")
with db() as conn:
cur = conn.execute("""
INSERT INTO events (user_id, titel, datum, uhrzeit, lat, lon, ort_name, typ, beschreibung, link)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (user['id'], data.titel, data.datum, data.uhrzeit,
data.lat, data.lon, data.ort_name,
data.typ, data.beschreibung, data.link))
row = conn.execute(
"SELECT e.*, u.name AS veranstalter_name FROM events e "
"LEFT JOIN users u ON u.id = e.user_id WHERE e.id = ?",
(cur.lastrowid,)
).fetchone()
return dict(row)
# ------------------------------------------------------------------
# GET /api/events/{id}
# ------------------------------------------------------------------
@router.get("/{event_id}")
async def get_event(event_id: int):
with db() as conn:
row = conn.execute(
"SELECT e.*, u.name AS veranstalter_name FROM events e "
"LEFT JOIN users u ON u.id = e.user_id WHERE e.id = ?",
(event_id,)
).fetchone()
if not row:
raise HTTPException(404, "Event nicht gefunden.")
return dict(row)
# ------------------------------------------------------------------
# PATCH /api/events/{id}
# ------------------------------------------------------------------
@router.patch("/{event_id}")
async def update_event(event_id: int, data: EventUpdate, user=Depends(get_current_user)):
with db() as conn:
ev = conn.execute("SELECT * FROM events WHERE id = ?", (event_id,)).fetchone()
if not ev:
raise HTTPException(404, "Event nicht gefunden.")
if ev['user_id'] != user['id']:
raise HTTPException(403, "Nur der Veranstalter kann das Event bearbeiten.")
updates = data.model_dump(exclude_none=True)
if updates:
if 'typ' in updates and updates['typ'] not in TYPEN:
raise HTTPException(400, "Ungültiger Typ.")
cols = ', '.join(f"{k} = ?" for k in updates)
conn.execute(f"UPDATE events SET {cols} WHERE id = ?", [*updates.values(), event_id])
row = conn.execute(
"SELECT e.*, u.name AS veranstalter_name FROM events e "
"LEFT JOIN users u ON u.id = e.user_id WHERE e.id = ?",
(event_id,)
).fetchone()
return dict(row)
# ------------------------------------------------------------------
# DELETE /api/events/{id}
# ------------------------------------------------------------------
@router.delete("/{event_id}", status_code=204)
async def delete_event(event_id: int, user=Depends(get_current_user)):
with db() as conn:
ev = conn.execute("SELECT * FROM events WHERE id = ?", (event_id,)).fetchone()
if not ev:
raise HTTPException(404, "Event nicht gefunden.")
if ev['user_id'] != user['id']:
raise HTTPException(403, "Nur der Veranstalter kann das Event löschen.")
conn.execute("UPDATE events SET status = 'geloescht' WHERE id = ?", (event_id,))

259
backend/routes/sitting.py Normal file
View file

@ -0,0 +1,259 @@
"""BAN YARO — Hundesitting"""
import json
import math
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from typing import Optional, List
from database import db
from auth import get_current_user
router = APIRouter()
SERVICES = {'tagesbetreuung', 'uebernachtung', 'gassi', 'hausbesuch'}
def _haversine(lat1, lon1, lat2, lon2):
R = 6_371_000
p1, p2 = math.radians(lat1), math.radians(lat2)
dp = math.radians(lat2 - lat1)
dl = math.radians(lon2 - lon1)
a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
return 2 * R * math.asin(math.sqrt(a))
# ------------------------------------------------------------------
# Schemas
# ------------------------------------------------------------------
class SitterCreate(BaseModel):
beschreibung: Optional[str] = None
preis_pro_tag: float = 0
max_hunde: int = 1
lat: Optional[float] = None
lon: Optional[float] = None
radius_km: int = 20
services: List[str] = []
class SitterUpdate(BaseModel):
beschreibung: Optional[str] = None
preis_pro_tag: Optional[float] = None
max_hunde: Optional[int] = None
lat: Optional[float] = None
lon: Optional[float] = None
radius_km: Optional[int] = None
services: Optional[List[str]] = None
aktiv: Optional[int] = None
class RequestCreate(BaseModel):
sitter_id: int
dog_ids: List[int] = []
von: str # YYYY-MM-DD
bis: str
nachricht: Optional[str] = None
class RequestUpdate(BaseModel):
status: str # angenommen | abgelehnt | abgebrochen
# ------------------------------------------------------------------
# GET /api/sitting — Sitter-Liste
# ------------------------------------------------------------------
@router.get("")
async def list_sitters(
lat: Optional[float] = None,
lon: Optional[float] = None,
radius: int = 30000,
service: Optional[str] = None,
):
with db() as conn:
rows = conn.execute("""
SELECT s.*, u.name AS sitter_name
FROM sitters s
JOIN users u ON u.id = s.user_id
WHERE s.aktiv = 1
""").fetchall()
result = []
for r in rows:
d = dict(r)
d['services'] = json.loads(d['services'] or '[]')
if service and service not in d['services']:
continue
if lat is not None and lon is not None and d['lat'] and d['lon']:
dist = _haversine(lat, lon, d['lat'], d['lon'])
if dist > radius:
continue
d['distanz_m'] = round(dist)
result.append(d)
if lat is not None:
result.sort(key=lambda x: x.get('distanz_m', 999999))
return result
# ------------------------------------------------------------------
# GET /api/sitting/me — eigenes Sitter-Profil
# ------------------------------------------------------------------
@router.get("/me")
async def get_my_sitter_profile(user=Depends(get_current_user)):
with db() as conn:
row = conn.execute(
"SELECT * FROM sitters WHERE user_id = ?", (user['id'],)
).fetchone()
if not row:
return None
d = dict(row)
d['services'] = json.loads(d['services'] or '[]')
return d
# ------------------------------------------------------------------
# POST /api/sitting — Sitter-Profil erstellen oder aktualisieren
# ------------------------------------------------------------------
@router.post("", status_code=201)
async def create_sitter(data: SitterCreate, user=Depends(get_current_user)):
services_json = json.dumps([s for s in data.services if s in SERVICES])
with db() as conn:
existing = conn.execute(
"SELECT id FROM sitters WHERE user_id = ?", (user['id'],)
).fetchone()
if existing:
raise HTTPException(409, "Du hast bereits ein Sitter-Profil. Nutze PATCH zum Aktualisieren.")
cur = conn.execute("""
INSERT INTO sitters (user_id, beschreibung, preis_pro_tag, max_hunde, lat, lon, radius_km, services)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""", (user['id'], data.beschreibung, data.preis_pro_tag,
data.max_hunde, data.lat, data.lon, data.radius_km, services_json))
row = conn.execute("SELECT * FROM sitters WHERE id = ?", (cur.lastrowid,)).fetchone()
d = dict(row)
d['services'] = json.loads(d['services'] or '[]')
return d
# ------------------------------------------------------------------
# PATCH /api/sitting/me — eigenes Profil bearbeiten
# ------------------------------------------------------------------
@router.patch("/me")
async def update_sitter(data: SitterUpdate, user=Depends(get_current_user)):
with db() as conn:
sitter = conn.execute(
"SELECT * FROM sitters WHERE user_id = ?", (user['id'],)
).fetchone()
if not sitter:
raise HTTPException(404, "Kein Sitter-Profil gefunden.")
updates = data.model_dump(exclude_none=True)
if 'services' in updates:
updates['services'] = json.dumps([s for s in updates['services'] if s in SERVICES])
if updates:
cols = ', '.join(f"{k} = ?" for k in updates)
conn.execute(f"UPDATE sitters SET {cols} WHERE user_id = ?",
[*updates.values(), user['id']])
row = conn.execute("SELECT * FROM sitters WHERE user_id = ?", (user['id'],)).fetchone()
d = dict(row)
d['services'] = json.loads(d['services'] or '[]')
return d
# ------------------------------------------------------------------
# GET /api/sitting/requests — meine Anfragen (als Anfragender)
# ------------------------------------------------------------------
@router.get("/requests")
async def list_my_requests(user=Depends(get_current_user)):
with db() as conn:
rows = conn.execute("""
SELECT sr.*, u.name AS sitter_name
FROM sitting_requests sr
JOIN sitters s ON s.id = sr.sitter_id
JOIN users u ON u.id = s.user_id
WHERE sr.user_id = ?
ORDER BY sr.created_at DESC
""", (user['id'],)).fetchall()
result = []
for r in rows:
d = dict(r)
d['dog_ids'] = json.loads(d['dog_ids'] or '[]')
result.append(d)
return result
# ------------------------------------------------------------------
# GET /api/sitting/inbox — eingehende Anfragen (als Sitter)
# ------------------------------------------------------------------
@router.get("/inbox")
async def sitter_inbox(user=Depends(get_current_user)):
with db() as conn:
sitter = conn.execute(
"SELECT id FROM sitters WHERE user_id = ?", (user['id'],)
).fetchone()
if not sitter:
return []
rows = conn.execute("""
SELECT sr.*, u.name AS anfragender_name
FROM sitting_requests sr
JOIN users u ON u.id = sr.user_id
WHERE sr.sitter_id = ?
ORDER BY sr.created_at DESC
""", (sitter['id'],)).fetchall()
result = []
for r in rows:
d = dict(r)
d['dog_ids'] = json.loads(d['dog_ids'] or '[]')
result.append(d)
return result
# ------------------------------------------------------------------
# POST /api/sitting/requests — Anfrage senden
# ------------------------------------------------------------------
@router.post("/requests", status_code=201)
async def create_request(data: RequestCreate, user=Depends(get_current_user)):
with db() as conn:
sitter = conn.execute(
"SELECT * FROM sitters WHERE id = ?", (data.sitter_id,)
).fetchone()
if not sitter or not sitter['aktiv']:
raise HTTPException(404, "Sitter nicht gefunden oder nicht aktiv.")
if sitter['user_id'] == user['id']:
raise HTTPException(400, "Du kannst keine Anfrage an dich selbst schicken.")
cur = conn.execute("""
INSERT INTO sitting_requests (user_id, sitter_id, dog_ids, von, bis, nachricht)
VALUES (?, ?, ?, ?, ?, ?)
""", (user['id'], data.sitter_id, json.dumps(data.dog_ids),
data.von, data.bis, data.nachricht))
row = conn.execute("SELECT * FROM sitting_requests WHERE id = ?", (cur.lastrowid,)).fetchone()
d = dict(row)
d['dog_ids'] = json.loads(d['dog_ids'] or '[]')
return d
# ------------------------------------------------------------------
# PATCH /api/sitting/requests/{id} — Status ändern
# ------------------------------------------------------------------
@router.patch("/requests/{req_id}")
async def update_request(req_id: int, data: RequestUpdate, user=Depends(get_current_user)):
allowed = {'angenommen', 'abgelehnt', 'abgebrochen'}
if data.status not in allowed:
raise HTTPException(400, f"Status muss einer von {allowed} sein.")
with db() as conn:
req = conn.execute("SELECT * FROM sitting_requests WHERE id = ?", (req_id,)).fetchone()
if not req:
raise HTTPException(404, "Anfrage nicht gefunden.")
# Anfragender kann nur abbrechen; Sitter kann annehmen/ablehnen
sitter = conn.execute(
"SELECT * FROM sitters WHERE id = ?", (req['sitter_id'],)
).fetchone()
is_requester = req['user_id'] == user['id']
is_sitter = sitter['user_id'] == user['id']
if not is_requester and not is_sitter:
raise HTTPException(403, "Kein Zugriff.")
if is_requester and data.status != 'abgebrochen':
raise HTTPException(403, "Du kannst die Anfrage nur abbrechen.")
if is_sitter and data.status == 'abgebrochen':
raise HTTPException(403, "Als Sitter kannst du nur annehmen oder ablehnen.")
conn.execute(
"UPDATE sitting_requests SET status = ? WHERE id = ?", (data.status, req_id)
)
row = conn.execute("SELECT * FROM sitting_requests WHERE id = ?", (req_id,)).fetchone()
d = dict(row)
d['dog_ids'] = json.loads(d['dog_ids'] or '[]')
return d