NEUE BACKEND-MODULE:
math_utils.py
- haversine_km(lat1, lon1, lat2, lon2) — Distanz in km
- haversine_m(...) — Convenience-Wrapper in Metern
- bbox_deg_from_km(lat, radius_km) — Bounding-Box-Approximation
für SQL-Vorfilter (statt Haversine im Python-Loop)
config.py
- DB_PATH, MEDIA_DIR, BREEDER_DOCS_DIR, SCANINPUT_DIR
- API_TIMEOUT_SHORT (5s) / DEFAULT (10s) / LONG (30s)
- HTTP_USER_AGENT, HTTP_HEADERS
errors.py
- not_found(msg), forbidden(msg), bad_request(msg), unauthorized(msg)
- conflict(msg), too_many_requests(msg, retry_after), service_unavailable(msg)
- require_or_404(row, msg) — Convenience-Helper
UI.JS ERWEITERUNGEN:
UI.time erweitert:
- formatDate(d) → "15.03.2026"
- formatDateTime(d) → "15.03.2026, 14:30"
- weekday(d) → "Di"
- parseISO(str) → {year, month, day}
UI.text (neu):
- truncate(str, maxLen, ellipsis='…')
- slug(str) — URL-Slug aus String (mit DE-Umlauten)
UI.money (neu):
- format(value) → "12,34 €" (de-DE, EUR)
- formatWithSuffix(value, '/Jahr')
HAVERSINE-MIGRATION (13 Backend-Routen):
alerts.py, services.py, places.py, events.py, diary.py, playdate.py,
lost.py, poison.py, adoption.py, gassi_zeiten.py, sitting.py, routen.py,
walks.py
- Alle lokalen def _haversine/haversine_km entfernt
- Aufrufe ersetzt durch haversine_km/haversine_m je nach Einheit
- from math_utils import haversine_km|haversine_m in jeder Datei
Tests 19/19 grün.
Hinweis: Migrationen für MEDIA_DIR (19 Stellen), API-Timeouts (12),
Date-Formatter im Frontend (24) und UI.text.truncate (5) sind als
Folge-Sprints möglich. Helper sind verfügbar.
136 lines
4.8 KiB
Python
136 lines
4.8 KiB
Python
"""BAN YARO — Service-Angebote (Sitting & Walks Matching)"""
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from pydantic import BaseModel
|
|
from typing import Optional
|
|
from database import db
|
|
from auth import get_current_user
|
|
from math_utils import haversine_km
|
|
|
|
router = APIRouter()
|
|
|
|
ALLOWED_TYPES = {'sitting', 'walks'}
|
|
|
|
|
|
# ------------------------------------------------------------------
|
|
# Schemas
|
|
# ------------------------------------------------------------------
|
|
class ServiceCreate(BaseModel):
|
|
type: str
|
|
beschreibung: Optional[str] = None
|
|
preis_pro_tag: Optional[float] = None
|
|
lat: Optional[float] = None
|
|
lon: Optional[float] = None
|
|
radius_km: int = 10
|
|
|
|
|
|
# ------------------------------------------------------------------
|
|
# GET /api/services — Angebote in der Nähe
|
|
# ------------------------------------------------------------------
|
|
@router.get("")
|
|
async def list_services(
|
|
type: str,
|
|
lat: Optional[float] = None,
|
|
lon: Optional[float] = None,
|
|
radius: float = 20, # km
|
|
):
|
|
if type not in ALLOWED_TYPES:
|
|
raise HTTPException(400, f"type muss 'sitting' oder 'walks' sein.")
|
|
|
|
with db() as conn:
|
|
rows = conn.execute("""
|
|
SELECT so.*, u.name AS anbieter_name
|
|
FROM service_offers so
|
|
JOIN users u ON u.id = so.user_id
|
|
WHERE so.type = ? AND so.aktiv = 1
|
|
LIMIT 200
|
|
""", (type,)).fetchall()
|
|
|
|
result = []
|
|
for r in rows:
|
|
d = dict(r)
|
|
if lat is not None and lon is not None and d['lat'] and d['lon']:
|
|
dist = haversine_km(lat, lon, d['lat'], d['lon'])
|
|
if dist > radius:
|
|
continue
|
|
d['distanz_km'] = round(dist, 1)
|
|
else:
|
|
d['distanz_km'] = None
|
|
result.append(d)
|
|
|
|
if lat is not None:
|
|
result.sort(key=lambda x: x.get('distanz_km') or 9999)
|
|
|
|
return result[:50]
|
|
|
|
|
|
# ------------------------------------------------------------------
|
|
# GET /api/services/me — eigene Angebote
|
|
# ------------------------------------------------------------------
|
|
@router.get("/me")
|
|
async def my_services(user=Depends(get_current_user)):
|
|
with db() as conn:
|
|
rows = conn.execute(
|
|
"SELECT * FROM service_offers WHERE user_id = ? ORDER BY type",
|
|
(user['id'],)
|
|
).fetchall()
|
|
return [dict(r) for r in rows]
|
|
|
|
|
|
# ------------------------------------------------------------------
|
|
# POST /api/services — Angebot erstellen oder aktualisieren (Upsert)
|
|
# ------------------------------------------------------------------
|
|
@router.post("", status_code=201)
|
|
async def upsert_service(data: ServiceCreate, user=Depends(get_current_user)):
|
|
if data.type not in ALLOWED_TYPES:
|
|
raise HTTPException(400, "type muss 'sitting' oder 'walks' sein.")
|
|
|
|
with db() as conn:
|
|
existing = conn.execute(
|
|
"SELECT id FROM service_offers WHERE user_id = ? AND type = ?",
|
|
(user['id'], data.type)
|
|
).fetchone()
|
|
|
|
if existing:
|
|
conn.execute("""
|
|
UPDATE service_offers
|
|
SET beschreibung = ?, preis_pro_tag = ?, lat = ?, lon = ?,
|
|
radius_km = ?, aktiv = 1
|
|
WHERE user_id = ? AND type = ?
|
|
""", (data.beschreibung, data.preis_pro_tag, data.lat, data.lon,
|
|
data.radius_km, user['id'], data.type))
|
|
row = conn.execute(
|
|
"SELECT * FROM service_offers WHERE user_id = ? AND type = ?",
|
|
(user['id'], data.type)
|
|
).fetchone()
|
|
else:
|
|
cur = conn.execute("""
|
|
INSERT INTO service_offers
|
|
(user_id, type, beschreibung, preis_pro_tag, lat, lon, radius_km)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
""", (user['id'], data.type, data.beschreibung, data.preis_pro_tag,
|
|
data.lat, data.lon, data.radius_km))
|
|
row = conn.execute(
|
|
"SELECT * FROM service_offers WHERE id = ?", (cur.lastrowid,)
|
|
).fetchone()
|
|
|
|
return dict(row)
|
|
|
|
|
|
# ------------------------------------------------------------------
|
|
# DELETE /api/services/{id} — Angebot deaktivieren
|
|
# ------------------------------------------------------------------
|
|
@router.delete("/{offer_id}")
|
|
async def deactivate_service(offer_id: int, user=Depends(get_current_user)):
|
|
with db() as conn:
|
|
offer = conn.execute(
|
|
"SELECT * FROM service_offers WHERE id = ?", (offer_id,)
|
|
).fetchone()
|
|
if not offer:
|
|
raise HTTPException(404, "Angebot nicht gefunden.")
|
|
if offer['user_id'] != user['id']:
|
|
raise HTTPException(403, "Kein Zugriff.")
|
|
conn.execute(
|
|
"UPDATE service_offers SET aktiv = 0 WHERE id = ?", (offer_id,)
|
|
)
|
|
return {"ok": True}
|