Pflegepilot v3 Phase 6: Pflegetagebuch, Dokumente, Aufgaben & Kalender

Pflegetagebuch-CRUD, Dokumenten-Upload mit Extension-Whitelist ueber eine
autorisierte Download-Route (statt offen gemountetem static/, gleiches
Muster wie die Briefe-PDFs aus Phase 3), Aufgaben-CRUD (bisher nur
lesend im Dashboard vorhanden), und Kalender-Aggregation (offene
Aufgaben, Widerspruchsfristen, MDK-Gutachtertermine, Archivierungsfristen,
Pflegetagebuch-Erinnerungen) - 1:1-Logik-Port aus der alten App.

Mit echten Kontenlebenszyklen verifiziert: Mandantentrennung greift auch
bei Tagebuch-Loeschung und Dokumenten-Download (404 fuer fremde Patienten-
Daten), Datei-Whitelist blockt .exe, Kalender zeigt ueberfaellige Aufgaben
und blendet die Tagebuch-Erinnerung korrekt aus sobald ein heutiger
Eintrag existiert.

Frontend: Aufgaben-Seite mit Anlegen/Erledigen, Kalender-Seite gruppiert
nach Ueberfaellig/Naechste 30 Tage/Spaeter, Pflegetagebuch- und
Dokumente-Sektionen in der Patientenakte.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
adminandClaude Sonnet 5 committed 2026-07-19 15:46:29 +02:00
1 parent cf2bd7ce43
commit b6dd56e6d1
14 files changed
+875

No files matched your search

+8
View File
@@ -11,15 +11,19 @@ from app.routers import (
abo,
admin,
antraege,
aufgaben,
auth,
briefe,
changelog,
dashboard,
dokumente,
einstellungen,
kalender,
katalog,
patienten,
pflegegrad,
stammdaten,
tagebuch,
)
@@ -73,6 +77,10 @@ app.include_router(admin.router)
app.include_router(abo.router)
app.include_router(einstellungen.router)
app.include_router(changelog.router)
app.include_router(tagebuch.router)
app.include_router(dokumente.router)
app.include_router(aufgaben.router)
app.include_router(kalender.router)
@app.get("/api/health")
@@ -0,0 +1,65 @@
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Query, Session
from app.db import get_db
from app.deps import require_active_access, require_login, require_paid_access, scoped_patienten_query
from app.models import Aufgabe, Nutzer, Patient
from app.schemas import AufgabeCreate, AufgabeOut
router = APIRouter(prefix="/api/aufgaben", tags=["aufgaben"], dependencies=[Depends(require_active_access)])
def _mit_patientenname(db: Session, aufgaben: list[Aufgabe]) -> list[AufgabeOut]:
ergebnis = []
for a in aufgaben:
name = f"{a.patient.vorname} {a.patient.nachname}" if a.patient else None
item = AufgabeOut.model_validate(a)
item.patient_name = name
ergebnis.append(item)
return ergebnis
@router.get("", response_model=list[AufgabeOut])
def liste(
db: Session = Depends(get_db),
user: Nutzer = Depends(require_login),
patienten_query: Query = Depends(scoped_patienten_query),
):
query = db.query(Aufgabe).filter(Aufgabe.erledigt.is_(False))
if user.rolle != "admin":
patient_ids = [p.id for p in patienten_query.with_entities(Patient.id).all()]
query = query.filter(Aufgabe.patient_id.in_(patient_ids))
aufgaben = query.order_by(Aufgabe.faellig_am, Aufgabe.prioritaet).all()
return _mit_patientenname(db, aufgaben)
@router.post("", response_model=AufgabeOut, status_code=201)
def anlegen(
payload: AufgabeCreate,
db: Session = Depends(get_db),
user: Nutzer = Depends(require_paid_access),
):
if payload.patient_id is not None:
patient = db.query(Patient).filter(Patient.id == payload.patient_id).first()
if patient is None or (user.rolle != "admin" and patient.nutzer_id != user.id):
raise HTTPException(status_code=404, detail="Patient nicht gefunden")
elif user.rolle != "admin":
raise HTTPException(status_code=400, detail="patient_id erforderlich")
aufgabe = Aufgabe(**payload.model_dump())
db.add(aufgabe)
db.commit()
db.refresh(aufgabe)
return _mit_patientenname(db, [aufgabe])[0]
@router.post("/{aid}/erledigt")
def erledigt(aid: int, db: Session = Depends(get_db), user: Nutzer = Depends(require_login)):
aufgabe = db.get(Aufgabe, aid)
if aufgabe is None:
raise HTTPException(status_code=404, detail="Nicht gefunden")
if user.rolle != "admin" and not (aufgabe.patient_id and aufgabe.patient and aufgabe.patient.nutzer_id == user.id):
raise HTTPException(status_code=404, detail="Nicht gefunden")
aufgabe.erledigt = True
db.commit()
return {"ok": True}
@@ -0,0 +1,90 @@
import os
import re
import time
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile
from fastapi.responses import FileResponse
from sqlalchemy.orm import Session
from app.config import settings
from app.db import get_db
from app.deps import get_owned_patient, require_active_access, require_login
from app.models import Dokument, Nutzer, Patient
from app.schemas import DokumentOut
router = APIRouter(tags=["dokumente"], dependencies=[Depends(require_active_access)])
ERLAUBTE_ENDUNGEN = {".pdf", ".jpg", ".jpeg", ".png", ".gif", ".webp", ".doc", ".docx", ".txt", ".eml"}
@router.get("/api/patienten/{pid}/dokumente", response_model=list[DokumentOut])
def liste(patient: Patient = Depends(get_owned_patient), db: Session = Depends(get_db)):
return (
db.query(Dokument)
.filter(Dokument.patient_id == patient.id)
.order_by(Dokument.datum.desc(), Dokument.erstellt_am.desc())
.all()
)
@router.post("/api/patienten/{pid}/dokumente", response_model=DokumentOut, status_code=201)
def hochladen(
datei: UploadFile = File(...),
typ: str = Form("sonstiges"),
bezeichnung: str = Form(""),
datum: str | None = Form(None),
notizen: str = Form(""),
patient: Patient = Depends(get_owned_patient),
db: Session = Depends(get_db),
):
ext = os.path.splitext(datei.filename or "")[1].lower()
if ext not in ERLAUBTE_ENDUNGEN:
raise HTTPException(status_code=400, detail=f"Format nicht erlaubt: {ext}")
dok_dir = os.path.join(settings.uploads_dir, "dokumente", str(patient.id))
os.makedirs(dok_dir, exist_ok=True)
safe_name = re.sub(r"[^\w\-.]", "_", datei.filename or "datei")
unique_name = f"{int(time.time())}_{safe_name}"
with open(os.path.join(dok_dir, unique_name), "wb") as fh:
fh.write(datei.file.read())
pfad = f"dokumente/{patient.id}/{unique_name}"
dokument = Dokument(
patient_id=patient.id,
typ=typ,
bezeichnung=bezeichnung or (datei.filename or unique_name),
dateiname=unique_name,
pfad=pfad,
datum=datum or None,
notizen=notizen,
)
db.add(dokument)
db.commit()
db.refresh(dokument)
return dokument
@router.get("/api/patienten/{pid}/dokumente/{did}/datei")
def datei_herunterladen(
did: int, patient: Patient = Depends(get_owned_patient), db: Session = Depends(get_db)
):
dokument = db.query(Dokument).filter(Dokument.id == did, Dokument.patient_id == patient.id).first()
if dokument is None:
raise HTTPException(status_code=404, detail="Nicht gefunden")
full_path = os.path.join(settings.uploads_dir, dokument.pfad)
if not os.path.exists(full_path):
raise HTTPException(status_code=404, detail="Datei nicht gefunden")
return FileResponse(full_path, filename=dokument.dateiname)
@router.delete("/api/dokumente/{did}")
def loeschen(did: int, db: Session = Depends(get_db), user: Nutzer = Depends(require_login)):
dokument = db.get(Dokument, did)
if dokument is None or (user.rolle != "admin" and dokument.patient.nutzer_id != user.id):
raise HTTPException(status_code=404, detail="Nicht gefunden")
full_path = os.path.join(settings.uploads_dir, dokument.pfad)
if os.path.exists(full_path):
os.remove(full_path)
db.delete(dokument)
db.commit()
return {"ok": True}
@@ -0,0 +1,98 @@
import datetime
from fastapi import APIRouter, Depends
from sqlalchemy import func
from sqlalchemy.orm import Query, Session
from app.db import get_db
from app.deps import require_active_access, require_login, scoped_patienten_query
from app.models import Antrag, Aufgabe, Nutzer, Patient, PflegetagebuchEintrag
from app.schemas import KalenderEvent
router = APIRouter(prefix="/api/kalender", tags=["kalender"], dependencies=[Depends(require_active_access)])
@router.get("", response_model=list[KalenderEvent])
def kalender(
db: Session = Depends(get_db),
user: Nutzer = Depends(require_login),
patienten_query: Query = Depends(scoped_patienten_query),
):
heute = datetime.date.today()
events: list[KalenderEvent] = []
scoped = user.rolle != "admin"
patient_ids = [p.id for p in patienten_query.with_entities(Patient.id).all()] if scoped else None
# Offene Aufgaben mit Faelligkeitsdatum
aufgaben_q = db.query(Aufgabe).filter(Aufgabe.erledigt.is_(False), Aufgabe.faellig_am.isnot(None))
if scoped:
aufgaben_q = aufgaben_q.filter(Aufgabe.patient_id.in_(patient_ids))
for a in aufgaben_q.order_by(Aufgabe.faellig_am).all():
events.append(KalenderEvent(
typ="aufgabe", id=a.id, titel=a.titel, beschreibung=a.beschreibung or "",
datum=a.faellig_am, prioritaet=a.prioritaet,
patient_id=a.patient_id, patient_name=f"{a.patient.vorname} {a.patient.nachname}" if a.patient else None,
ueberfaellig=a.faellig_am < heute,
))
# Widerspruchsfristen (nur bei abgelehnten Antraegen)
antraege_q = db.query(Antrag).filter(Antrag.widerspruch_frist.isnot(None), Antrag.status == "abgelehnt")
if scoped:
antraege_q = antraege_q.filter(Antrag.patient_id.in_(patient_ids))
for a in antraege_q.order_by(Antrag.widerspruch_frist).all():
events.append(KalenderEvent(
typ="widerspruch_frist", id=a.id, titel="⚖ Widerspruchsfrist läuft ab",
beschreibung="Widerspruch gem. § 84 SGG einreichen",
datum=a.widerspruch_frist, prioritaet="hoch",
patient_id=a.patient_id, patient_name=f"{a.patient.vorname} {a.patient.nachname}",
ueberfaellig=a.widerspruch_frist < heute,
))
# MDK-Gutachtertermine
gutachter_q = db.query(Antrag).filter(Antrag.gutachter_termin.isnot(None))
if scoped:
gutachter_q = gutachter_q.filter(Antrag.patient_id.in_(patient_ids))
for a in gutachter_q.order_by(Antrag.gutachter_termin).all():
events.append(KalenderEvent(
typ="gutachter", id=a.id, titel="🩺 MDK-Begutachtung",
beschreibung="Pflegetagebuch bereitlegen, Arztberichte sammeln",
datum=a.gutachter_termin, prioritaet="hoch",
patient_id=a.patient_id, patient_name=f"{a.patient.vorname} {a.patient.nachname}",
ueberfaellig=a.gutachter_termin < heute,
))
# Archivierungsfristen (Hinweis, wenn Frist < 1 Jahr entfernt ist)
patienten_mit_frist = patienten_query.filter(Patient.archiv_frist.isnot(None)).order_by(Patient.archiv_frist).all()
for p in patienten_mit_frist:
tage = (p.archiv_frist - heute).days
if tage <= 365:
events.append(KalenderEvent(
typ="archivierung", id=p.id, titel="📁 Archivierungsfrist",
beschreibung=f"Akte {p.patient_status} – Aufbewahrungsfrist endet",
datum=p.archiv_frist, prioritaet="mittel",
patient_id=p.id, patient_name=f"{p.vorname} {p.nachname}",
ueberfaellig=tage < 0,
))
# Tagebuch-Erinnerung: aktive Patienten mit Pflegegrad ohne heutigen Eintrag
aktive_patienten = patienten_query.filter(Patient.patient_status == "aktiv", Patient.pflegegrad > 0).all()
for p in aktive_patienten:
letzter = (
db.query(func.max(PflegetagebuchEintrag.datum))
.filter(PflegetagebuchEintrag.patient_id == p.id)
.scalar()
)
if letzter == heute:
continue
tage_seit = (heute - letzter).days if letzter else 999
events.append(KalenderEvent(
typ="tagebuch_erinnerung", id=p.id, titel=f"Pflegetagebuch führen – {p.vorname} {p.nachname}",
beschreibung=f"Heute noch kein Eintrag · Letzter Eintrag: {letzter.isoformat() if letzter else 'nie'}",
datum=heute, prioritaet="hoch" if tage_seit >= 2 else "mittel",
patient_id=p.id, patient_name=f"{p.vorname} {p.nachname}",
ueberfaellig=tage_seit >= 2,
))
events.sort(key=lambda e: e.datum or datetime.date.max)
return events
@@ -0,0 +1,70 @@
import datetime
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import func
from sqlalchemy.orm import Query, Session
from app.db import get_db
from app.deps import get_owned_patient, require_active_access, require_login, scoped_patienten_query
from app.models import Nutzer, Patient, PflegetagebuchEintrag
from app.schemas import TagebuchCreate, TagebuchOut, TagebuchReminderOut
router = APIRouter(tags=["tagebuch"], dependencies=[Depends(require_active_access)])
@router.get("/api/patienten/{pid}/tagebuch", response_model=list[TagebuchOut])
def liste(patient: Patient = Depends(get_owned_patient), db: Session = Depends(get_db)):
return (
db.query(PflegetagebuchEintrag)
.filter(PflegetagebuchEintrag.patient_id == patient.id)
.order_by(PflegetagebuchEintrag.datum.desc(), PflegetagebuchEintrag.erstellt_am.desc())
.all()
)
@router.post("/api/patienten/{pid}/tagebuch", response_model=TagebuchOut, status_code=201)
def anlegen(
payload: TagebuchCreate,
patient: Patient = Depends(get_owned_patient),
db: Session = Depends(get_db),
):
eintrag = PflegetagebuchEintrag(patient_id=patient.id, **payload.model_dump())
db.add(eintrag)
db.commit()
db.refresh(eintrag)
return eintrag
@router.delete("/api/tagebuch/{tid}")
def loeschen(tid: int, db: Session = Depends(get_db), user: Nutzer = Depends(require_login)):
eintrag = db.get(PflegetagebuchEintrag, tid)
if eintrag is None or (user.rolle != "admin" and eintrag.patient.nutzer_id != user.id):
raise HTTPException(status_code=404, detail="Nicht gefunden")
db.delete(eintrag)
db.commit()
return {"ok": True}
@router.get("/api/tagebuch/reminder-status", response_model=list[TagebuchReminderOut])
def reminder_status(
db: Session = Depends(get_db), patienten_query: Query = Depends(scoped_patienten_query)
):
heute = datetime.date.today()
ergebnis = []
patienten = patienten_query.filter(Patient.patient_status == "aktiv", Patient.pflegegrad > 0).all()
for p in patienten:
letzter = (
db.query(func.max(PflegetagebuchEintrag.datum))
.filter(PflegetagebuchEintrag.patient_id == p.id)
.scalar()
)
ergebnis.append(
TagebuchReminderOut(
id=p.id,
name=f"{p.vorname} {p.nachname}",
pflegegrad=p.pflegegrad,
letzter_eintrag=letzter,
heute=letzter == heute,
)
)
return ergebnis
+76
View File
@@ -304,6 +304,82 @@ class RechnungRequest(BaseModel):
leistungsbeschreibung: str = "Pflegepilot – Nutzung der Anwendung"
class TagebuchCreate(BaseModel):
datum: datetime.date
koerperpflege: str | None = None
anziehen: str | None = None
ernaehrung: str | None = None
mobilitaet: str | None = None
orientierung: str | None = None
medikamente: str | None = None
soziales: str | None = None
allgemein: str | None = None
class TagebuchOut(TagebuchCreate):
model_config = ConfigDict(from_attributes=True)
id: int
patient_id: int
erstellt_am: datetime.datetime
class TagebuchReminderOut(BaseModel):
id: int
name: str
pflegegrad: int
letzter_eintrag: datetime.date | None
heute: bool
class DokumentOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
patient_id: int
typ: str
bezeichnung: str
dateiname: str
pfad: str
datum: datetime.date | None
notizen: str | None
erstellt_am: datetime.datetime
class AufgabeCreate(BaseModel):
patient_id: int | None = None
titel: str
beschreibung: str | None = None
prioritaet: str = "normal"
faellig_am: datetime.date | None = None
class AufgabeOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
patient_id: int | None
titel: str
beschreibung: str | None
faellig_am: datetime.date | None
prioritaet: str
erledigt: bool
erstellt_am: datetime.datetime
patient_name: str | None = None
class KalenderEvent(BaseModel):
typ: str
id: int
titel: str
beschreibung: str
datum: datetime.date | None
prioritaet: str
patient_id: int | None
patient_name: str | None
ueberfaellig: bool
class KrankenkasseOut(BaseModel):
name: str
kurzname: str
@@ -0,0 +1,104 @@
"use client";
import { useState } from "react";
import { usePatienten } from "@/lib/patienten";
import { useAufgaben, useAufgabenMutationen } from "@/lib/aufgaben";
import { ResponsiveTable, type Column } from "@/components/ResponsiveTable";
import type { Aufgabe } from "@/lib/aufgaben";
export default function AufgabenPage() {
const { data: aufgaben, isLoading } = useAufgaben();
const { data: patienten } = usePatienten();
const { anlegen, erledigen } = useAufgabenMutationen();
const [titel, setTitel] = useState("");
const [patientId, setPatientId] = useState<number | "">("");
const [prioritaet, setPrioritaet] = useState("normal");
const [faelligAm, setFaelligAm] = useState("");
const submit = (e: React.FormEvent) => {
e.preventDefault();
if (!titel.trim()) return;
anlegen.mutate(
{
titel,
patient_id: patientId === "" ? undefined : patientId,
prioritaet,
faellig_am: faelligAm || undefined,
},
{ onSuccess: () => setTitel("") }
);
};
const columns: Column<Aufgabe>[] = [
{ key: "titel", label: "Aufgabe", head: true, render: (a) => a.titel },
{ key: "patient", label: "Patient", render: (a) => a.patient_name ?? "–" },
{ key: "faellig", label: "Fällig am", render: (a) => a.faellig_am ?? "–" },
{ key: "prioritaet", label: "Priorität", render: (a) => a.prioritaet },
{
key: "aktion",
label: "",
render: (a) => (
<button onClick={() => erledigen.mutate(a.id)} className="text-xs text-emerald-600 underline">
Erledigt
</button>
),
},
];
return (
<div className="mx-auto max-w-3xl p-6">
<h1 className="mb-4 text-2xl font-semibold text-slate-800">Aufgaben</h1>
<form onSubmit={submit} className="mb-6 flex flex-wrap items-end gap-2 rounded-2xl border border-slate-200 bg-white p-4">
<input
placeholder="Neue Aufgabe…"
value={titel}
onChange={(e) => setTitel(e.target.value)}
className="rounded-lg border border-slate-300 px-3 py-2 text-sm"
/>
<select
value={patientId}
onChange={(e) => setPatientId(e.target.value ? Number(e.target.value) : "")}
className="rounded-lg border border-slate-300 px-3 py-2 text-sm"
>
<option value="">Kein Patient</option>
{patienten?.map((p) => (
<option key={p.id} value={p.id}>
{p.vorname} {p.nachname}
</option>
))}
</select>
<select
value={prioritaet}
onChange={(e) => setPrioritaet(e.target.value)}
className="rounded-lg border border-slate-300 px-3 py-2 text-sm"
>
<option value="normal">Normal</option>
<option value="mittel">Mittel</option>
<option value="hoch">Hoch</option>
</select>
<input
type="date"
value={faelligAm}
onChange={(e) => setFaelligAm(e.target.value)}
className="rounded-lg border border-slate-300 px-3 py-2 text-sm"
/>
<button
type="submit"
disabled={anlegen.isPending}
className="rounded-lg bg-slate-800 px-4 py-2 text-sm font-medium text-white"
>
Anlegen
</button>
</form>
{anlegen.isError && <p className="mb-3 text-sm text-red-600">{(anlegen.error as Error).message}</p>}
{isLoading ? (
<p className="text-slate-400">Lädt…</p>
) : (
<ResponsiveTable columns={columns} rows={aufgaben ?? []} rowKey={(a) => a.id} />
)}
</div>
);
}
@@ -0,0 +1,63 @@
"use client";
import { useKalender, type KalenderEvent } from "@/lib/kalender";
const TYP_LABEL: Record<string, string> = {
aufgabe: "Aufgabe",
widerspruch_frist: "Widerspruchsfrist",
gutachter: "MDK-Begutachtung",
archivierung: "Archivierung",
tagebuch_erinnerung: "Pflegetagebuch",
};
export default function KalenderPage() {
const { data, isLoading } = useKalender();
const heute = new Date().toISOString().slice(0, 10);
const in30Tagen = new Date(Date.now() + 30 * 86400000).toISOString().slice(0, 10);
const gruppen = {
ueberfaellig: (data ?? []).filter((e) => e.ueberfaellig),
dieseWoche: (data ?? []).filter((e) => !e.ueberfaellig && e.datum && e.datum <= in30Tagen),
spaeter: (data ?? []).filter((e) => !e.ueberfaellig && (!e.datum || e.datum > in30Tagen)),
};
return (
<div className="mx-auto max-w-2xl p-6">
<h1 className="mb-4 text-2xl font-semibold text-slate-800">Kalender & Fristen</h1>
{isLoading ? (
<p className="text-slate-400">Lädt…</p>
) : (
<>
<Gruppe titel="Überfällig" farbe="border-red-200 bg-red-50" events={gruppen.ueberfaellig} />
<Gruppe titel="Nächste 30 Tage" farbe="border-amber-200 bg-amber-50" events={gruppen.dieseWoche} />
<Gruppe titel="Später" farbe="border-slate-200 bg-white" events={gruppen.spaeter} />
</>
)}
<p className="mt-2 text-xs text-slate-400">heute: {heute}</p>
</div>
);
}
function Gruppe({ titel, farbe, events }: { titel: string; farbe: string; events: KalenderEvent[] }) {
if (events.length === 0) return null;
return (
<section className="mb-6">
<p className="mb-2 text-sm font-semibold text-slate-600">{titel}</p>
<div className="flex flex-col gap-2">
{events.map((e) => (
<div key={`${e.typ}-${e.id}`} className={`rounded-xl border p-3 text-sm ${farbe}`}>
<div className="flex items-center justify-between">
<span className="font-medium text-slate-800">{e.titel}</span>
<span className="text-xs text-slate-400">{TYP_LABEL[e.typ] ?? e.typ}</span>
</div>
<p className="text-xs text-slate-500">{e.beschreibung}</p>
<p className="mt-1 text-xs text-slate-400">
{e.datum} {e.patient_name && `· ${e.patient_name}`}
</p>
</div>
))}
</div>
</section>
);
}
@@ -9,6 +9,7 @@ import { ChangelogModal } from "@/components/ChangelogModal";
const NUTZER_NUR_PFADE = [
"/dashboard", "/patienten", "/katalog", "/rechner", "/widerspruch", "/musterbrief", "/meinabo",
"/aufgaben", "/kalender",
];
export default function AppLayout({ children }: { children: React.ReactNode }) {
@@ -69,6 +70,12 @@ export default function AppLayout({ children }: { children: React.ReactNode }) {
<Link href="/musterbrief" className="text-slate-600 hover:text-slate-900">
Musterbrief
</Link>
<Link href="/aufgaben" className="text-slate-600 hover:text-slate-900">
Aufgaben
</Link>
<Link href="/kalender" className="text-slate-600 hover:text-slate-900">
Kalender
</Link>
<Link href="/meinabo" className="text-slate-600 hover:text-slate-900">
Mein Abo
</Link>
@@ -5,6 +5,8 @@ import { useRouter } from "next/navigation";
import Link from "next/link";
import { usePatient, useNotizenVerlauf, usePatientMutations } from "@/lib/patienten";
import { useAntraegeFuerPatient, pdfUrl } from "@/lib/briefe";
import { useTagebuch, useTagebuchMutationen } from "@/lib/tagebuch";
import { useDokumente, useDokumentMutationen, dokumentUrl } from "@/lib/dokumente";
export default function PatientDetailPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = use(params);
@@ -14,10 +16,15 @@ export default function PatientDetailPage({ params }: { params: Promise<{ id: st
const { data: patient, isLoading } = usePatient(pid);
const { data: verlauf } = useNotizenVerlauf(pid);
const { data: antraege } = useAntraegeFuerPatient(pid);
const { data: tagebuch } = useTagebuch(pid);
const { anlegen: tagebuchAnlegen, loeschen: tagebuchLoeschen } = useTagebuchMutationen(pid);
const { data: dokumente } = useDokumente(pid);
const { hochladen, loeschen: dokumentLoeschen } = useDokumentMutationen(pid);
const { pflegegradSetzen, notizenAendern, loeschen } = usePatientMutations();
const [notizText, setNotizText] = useState("");
const [grund, setGrund] = useState("");
const [tbForm, setTbForm] = useState({ datum: new Date().toISOString().slice(0, 10), allgemein: "" });
if (isLoading || !patient) {
return <div className="mx-auto max-w-3xl p-6 text-slate-400">Lädt…</div>;
@@ -162,6 +169,102 @@ export default function PatientDetailPage({ params }: { params: Promise<{ id: st
</ul>
)}
</section>
<section className="mb-6 rounded-2xl border border-slate-200 bg-white p-5">
<p className="mb-2 text-sm font-semibold text-slate-700">Pflegetagebuch</p>
<form
onSubmit={(e) => {
e.preventDefault();
tagebuchAnlegen.mutate(
{
datum: tbForm.datum,
allgemein: tbForm.allgemein,
koerperpflege: null,
anziehen: null,
ernaehrung: null,
mobilitaet: null,
orientierung: null,
medikamente: null,
soziales: null,
},
{ onSuccess: () => setTbForm((f) => ({ ...f, allgemein: "" })) }
);
}}
className="mb-3 flex flex-col gap-2"
>
<div className="flex gap-2">
<input
type="date"
value={tbForm.datum}
onChange={(e) => setTbForm((f) => ({ ...f, datum: e.target.value }))}
className="rounded-lg border border-slate-300 px-3 py-2 text-sm"
/>
<button
type="submit"
disabled={tagebuchAnlegen.isPending}
className="rounded-lg bg-slate-800 px-4 py-2 text-sm font-medium text-white"
>
Eintrag speichern
</button>
</div>
<textarea
placeholder="Notizen zum Tag (Allgemein)…"
value={tbForm.allgemein}
onChange={(e) => setTbForm((f) => ({ ...f, allgemein: e.target.value }))}
rows={2}
className="rounded-lg border border-slate-300 px-3 py-2 text-sm"
/>
</form>
<ul className="divide-y divide-slate-100">
{tagebuch?.map((t) => (
<li key={t.id} className="flex items-start justify-between py-2 text-sm">
<div>
<span className="font-medium text-slate-700">{t.datum}</span>
{t.allgemein && <p className="text-xs text-slate-500">{t.allgemein}</p>}
</div>
<button
onClick={() => tagebuchLoeschen.mutate(t.id)}
className="text-xs text-red-600 underline"
>
Löschen
</button>
</li>
))}
{(!tagebuch || tagebuch.length === 0) && (
<p className="py-2 text-sm text-slate-400">Noch keine Einträge.</p>
)}
</ul>
</section>
<section className="mb-6 rounded-2xl border border-slate-200 bg-white p-5">
<p className="mb-2 text-sm font-semibold text-slate-700">Dokumente</p>
<input
type="file"
onChange={(e) => {
const datei = e.target.files?.[0];
if (!datei) return;
hochladen.mutate({ datei, typ: "sonstiges", bezeichnung: datei.name });
e.target.value = "";
}}
className="mb-3 text-sm"
/>
{hochladen.isError && <p className="mb-2 text-sm text-red-600">{(hochladen.error as Error).message}</p>}
<ul className="divide-y divide-slate-100">
{dokumente?.map((d) => (
<li key={d.id} className="flex items-center justify-between py-2 text-sm">
<a href={dokumentUrl(pid, d.id)} target="_blank" rel="noreferrer" className="text-slate-700 underline">
{d.bezeichnung}
</a>
<button onClick={() => dokumentLoeschen.mutate(d.id)} className="text-xs text-red-600 underline">
Löschen
</button>
</li>
))}
{(!dokumente || dokumente.length === 0) && (
<p className="py-2 text-sm text-slate-400">Noch keine Dokumente.</p>
)}
</ul>
</section>
</div>
);
}
@@ -0,0 +1,50 @@
"use client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "./api";
export type Aufgabe = {
id: number;
patient_id: number | null;
titel: string;
beschreibung: string | null;
faellig_am: string | null;
prioritaet: string;
erledigt: boolean;
erstellt_am: string;
patient_name: string | null;
};
export function useAufgaben() {
return useQuery<Aufgabe[]>({
queryKey: ["aufgaben"],
queryFn: () => api<Aufgabe[]>("/api/aufgaben"),
});
}
export function useAufgabenMutationen() {
const queryClient = useQueryClient();
const invalidate = () => {
queryClient.invalidateQueries({ queryKey: ["aufgaben"] });
queryClient.invalidateQueries({ queryKey: ["dashboard"] });
queryClient.invalidateQueries({ queryKey: ["kalender"] });
};
const anlegen = useMutation({
mutationFn: (payload: {
patient_id?: number;
titel: string;
beschreibung?: string;
prioritaet?: string;
faellig_am?: string;
}) => api("/api/aufgaben", { method: "POST", body: JSON.stringify(payload) }),
onSuccess: invalidate,
});
const erledigen = useMutation({
mutationFn: (id: number) => api(`/api/aufgaben/${id}/erledigt`, { method: "POST" }),
onSuccess: invalidate,
});
return { anlegen, erledigen };
}
@@ -0,0 +1,70 @@
"use client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "./api";
export type Dokument = {
id: number;
patient_id: number;
typ: string;
bezeichnung: string;
dateiname: string;
pfad: string;
datum: string | null;
notizen: string | null;
erstellt_am: string;
};
export function useDokumente(pid: number) {
return useQuery<Dokument[]>({
queryKey: ["dokumente", pid],
queryFn: () => api<Dokument[]>(`/api/patienten/${pid}/dokumente`),
enabled: !!pid,
});
}
export function dokumentUrl(pid: number, did: number) {
const apiUrl = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8100";
return `${apiUrl}/api/patienten/${pid}/dokumente/${did}/datei`;
}
export function useDokumentMutationen(pid: number) {
const queryClient = useQueryClient();
const invalidate = () => queryClient.invalidateQueries({ queryKey: ["dokumente", pid] });
const hochladen = useMutation({
mutationFn: async ({
datei,
typ,
bezeichnung,
}: {
datei: File;
typ: string;
bezeichnung: string;
}) => {
const apiUrl = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8100";
const form = new FormData();
form.append("datei", datei);
form.append("typ", typ);
form.append("bezeichnung", bezeichnung);
const res = await fetch(`${apiUrl}/api/patienten/${pid}/dokumente`, {
method: "POST",
credentials: "include",
body: form,
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.detail || "Upload fehlgeschlagen");
}
return res.json();
},
onSuccess: invalidate,
});
const loeschen = useMutation({
mutationFn: (did: number) => api(`/api/dokumente/${did}`, { method: "DELETE" }),
onSuccess: invalidate,
});
return { hochladen, loeschen };
}
@@ -0,0 +1,23 @@
"use client";
import { useQuery } from "@tanstack/react-query";
import { api } from "./api";
export type KalenderEvent = {
typ: string;
id: number;
titel: string;
beschreibung: string;
datum: string | null;
prioritaet: string;
patient_id: number | null;
patient_name: string | null;
ueberfaellig: boolean;
};
export function useKalender() {
return useQuery<KalenderEvent[]>({
queryKey: ["kalender"],
queryFn: () => api<KalenderEvent[]>("/api/kalender"),
});
}
@@ -0,0 +1,48 @@
"use client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "./api";
export type TagebuchEintrag = {
id: number;
patient_id: number;
datum: string;
koerperpflege: string | null;
anziehen: string | null;
ernaehrung: string | null;
mobilitaet: string | null;
orientierung: string | null;
medikamente: string | null;
soziales: string | null;
allgemein: string | null;
erstellt_am: string;
};
export function useTagebuch(pid: number) {
return useQuery<TagebuchEintrag[]>({
queryKey: ["tagebuch", pid],
queryFn: () => api<TagebuchEintrag[]>(`/api/patienten/${pid}/tagebuch`),
enabled: !!pid,
});
}
export function useTagebuchMutationen(pid: number) {
const queryClient = useQueryClient();
const invalidate = () => {
queryClient.invalidateQueries({ queryKey: ["tagebuch", pid] });
queryClient.invalidateQueries({ queryKey: ["kalender"] });
};
const anlegen = useMutation({
mutationFn: (payload: Omit<TagebuchEintrag, "id" | "patient_id" | "erstellt_am">) =>
api(`/api/patienten/${pid}/tagebuch`, { method: "POST", body: JSON.stringify(payload) }),
onSuccess: invalidate,
});
const loeschen = useMutation({
mutationFn: (tid: number) => api(`/api/tagebuch/${tid}`, { method: "DELETE" }),
onSuccess: invalidate,
});
return { anlegen, loeschen };
}