Pflegepilot v3 Phase 1: Patienten-CRUD, Mandantentrennung, Dashboard

get_owned_patient/scoped_patienten_query als typsichere FastAPI-Dependencies
(Ersatz fuer die alten SQL-String-Helper), Patienten-CRUD mit 3er-Cap pro
Konto, Notizen mit Aenderungshistorie, Pflegegrad-Patch, Dashboard-Route.
Frontend: ResponsiveTable/DateWheelPicker/BentoGrid als wiederverwendbare
Bausteine, Patientenliste, Patientenakte, Kurzformular fuer neue Patienten.

Isolation Ende-zu-Ende verifiziert: zweites Konto sieht/erreicht die
Patienten des ersten Kontos nicht (404 statt 403, um Existenz nicht zu
verraten), Admin sieht weiterhin alle Konten uebergreifend.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
adminandClaude Sonnet 5 committed 2026-07-19 13:46:48 +02:00
1 parent 47f1665f0f
commit 81156f5239
17 files changed
+1139 -30

No files matched your search

+4 -3
View File
@@ -45,7 +45,8 @@ Reihenfolge unten nach Abhängigkeit/Aufwand sortiert (nicht nach ursprüngliche
- ~~Toter Code `admin_password`/`session["admin_pw"]`~~ – entfernt aus `api_admin_get`/`api_admin_save`, kein Frontend-Bezug vorhanden (geprüft).
- ~~Unbenutzter `urllib.request`/`urllib.error`-Import~~ – Import-Zeile bereinigt.
- [ ] **6. ⚠️ Separates Grossvorhaben: Migration zu React + PostgreSQL**
- [ ] **6. ⚠️ Separates Grossvorhaben: Migration zu React + PostgreSQL** *(läuft, Phase 0 erledigt)*
- Vollständiger Technologiewechsel weg von Flask/vanilla-JS/SQLite — deutlich grösserer Umfang als die Punkte oben, keine Nebenbei-Aufgabe
- Braucht eine eigene Versionierungs-/Update-Strategie, da die App online ist und nicht für immer im jetzigen Stack bleiben wird
- Bevor hier irgendetwas beginnt: eigene Planungsrunde nötig (Umfang, Reihenfolge der Migration, ob schrittweise oder Neubau, Datenmigration aus der bestehenden SQLite-DB)
- Entscheidung: **kompletter Parallel-Neubau** in `pflegepilot_v3/` (neuer Ordner im selben Repo), alte App (`pflegepilot_alpha_v2/`) bleibt unverändert online. Keine Datenmigration – frische Postgres-DB, Demo-Daten, Admin-Zugang gemeinsam interaktiv angelegt. Stack: FastAPI + PostgreSQL + Next.js. Architekturplan mit 8 Phasen liegt in `C:\Users\Daniel\.claude\plans\cheerful-shimmying-pnueli.md`.
- ~~Phase 0 – Grundgerüst~~ *(erledigt)*: Docker-Setup (3 Services: db/api/web, eigene Ports 5532/8100/3100, kein Konflikt mit der alten App), 11 Postgres-Tabellen per Alembic-Migration, Auth Ende-zu-Ende (Login/Registrierung/Logout/Demo-Login, Rate-Limiting, Security-Header), WeasyPrint-PDF-Smoke-Test, Next.js-Grundgerüst mit Login-Overlay. Admin-Konto gemeinsam mit dem Betreiber angelegt (nicht hartkodiert).
- Noch offen: Phase 1 (Patienten-CRUD + Isolation + Dashboard) bis Phase 7 (Feinschliff + Deployment) – Details im Architekturplan.
+34 -6
View File
@@ -1,13 +1,12 @@
from fastapi import Depends, HTTPException, Request
from sqlalchemy.orm import Session
from sqlalchemy.orm import Query, Session
from app.db import get_db
from app.models import Nutzer
from app.models import Nutzer, Patient
# Phase 0: nur Login/Rollen-Grundbausteine. get_owned_patient/
# scoped_patienten_query, require_active_access und require_paid_access
# kommen in Phase 1 bzw. Phase 3/5 dazu (siehe Plan-Datei) - erst dort gibt
# es ueberhaupt Patienten- bzw. Abo-Daten, gegen die man pruefen koennte.
# require_active_access/require_paid_access (Abo-Gate/Freemium-Sperre)
# kommen erst in Phase 3/5 dazu (siehe Plan-Datei) - erst dort gibt es
# ueberhaupt Abo-Daten, gegen die man pruefen koennte.
def get_current_user(request: Request, db: Session = Depends(get_db)) -> Nutzer | None:
@@ -30,3 +29,32 @@ def require_admin(user: Nutzer = Depends(require_login)) -> Nutzer:
if user.rolle != "admin":
raise HTTPException(status_code=403, detail="Kein Zugriff")
return user
def scoped_patienten_query(
db: Session = Depends(get_db), user: Nutzer = Depends(require_login)
) -> Query:
"""ORM-Query auf 'patienten', bereits auf die eigenen Patienten des
aktuellen Nutzers eingeschraenkt (Admin sieht alle). Ersatz fuer das
alte SQL-String-Fragment _scope_sql() - hier typsicher als Query-Objekt,
das jeder Router mit weiteren .filter()/.order_by() verfeinern kann."""
query = db.query(Patient)
if user.rolle != "admin":
query = query.filter(Patient.nutzer_id == user.id)
return query
def get_owned_patient(
pid: int, db: Session = Depends(get_db), user: Nutzer = Depends(require_login)
) -> Patient:
"""Einzelner Patient, wenn der aktuelle Nutzer zugreifen darf (Admin
oder Eigentuemer), sonst 404 - bewusst 404 statt 403, damit die Existenz
fremder Patienten-IDs nicht erraten werden kann. Ersatz fuer das alte
_get_owned_patient()."""
query = db.query(Patient).filter(Patient.id == pid)
if user.rolle != "admin":
query = query.filter(Patient.nutzer_id == user.id)
patient = query.first()
if patient is None:
raise HTTPException(status_code=404, detail="Nicht gefunden")
return patient
+3 -1
View File
@@ -6,7 +6,7 @@ from starlette.middleware.sessions import SessionMiddleware
from app.config import settings
from app.pdf import render_pdf
from app.routers import auth
from app.routers import auth, dashboard, patienten
app = FastAPI(title="Pflegepilot API")
@@ -37,6 +37,8 @@ async def security_headers(request, call_next):
app.include_router(auth.router)
app.include_router(patienten.router)
app.include_router(dashboard.router)
@app.get("/api/health")
@@ -0,0 +1,35 @@
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Query, Session
from app.db import get_db
from app.deps import require_login, scoped_patienten_query
from app.models import Antrag, Aufgabe, Nutzer, Patient
from app.schemas import DashboardOut
router = APIRouter(prefix="/api/dashboard", tags=["dashboard"])
@router.get("", response_model=DashboardOut)
def dashboard(
db: Session = Depends(get_db),
user: Nutzer = Depends(require_login),
patienten_query: Query = Depends(scoped_patienten_query),
):
patient_ids = [p.id for p in patienten_query.with_entities(Patient.id).all()]
offene_antraege_q = db.query(Antrag).filter(Antrag.status.in_(["offen", "in_pruefung"]))
offene_aufgaben_q = db.query(Aufgabe).filter(Aufgabe.erledigt.is_(False))
if user.rolle != "admin":
offene_antraege_q = offene_antraege_q.filter(Antrag.patient_id.in_(patient_ids))
offene_aufgaben_q = offene_aufgaben_q.filter(Aufgabe.patient_id.in_(patient_ids))
letzte_patienten = (
patienten_query.order_by(Patient.geaendert_am.desc()).limit(5).all()
)
return DashboardOut(
patienten_anzahl=len(patient_ids),
offene_antraege=offene_antraege_q.count(),
offene_aufgaben=offene_aufgaben_q.count(),
letzte_patienten=letzte_patienten,
)
@@ -0,0 +1,127 @@
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import or_
from sqlalchemy.orm import Query, Session
from app.db import get_db
from app.deps import get_owned_patient, require_login, scoped_patienten_query
from app.models import NotizVerlauf, Nutzer, Patient
from app.schemas import (
NotizUpdate,
NotizVerlaufOut,
PatientCreate,
PatientOut,
PatientUpdate,
PflegegradPatch,
)
router = APIRouter(prefix="/api/patienten", tags=["patienten"])
MAX_PATIENTEN_PRO_KONTO = 3
@router.get("", response_model=list[PatientOut])
def liste(
q: str | None = None,
pflegegrad: int | None = None,
zielgruppe: str | None = None,
query: Query = Depends(scoped_patienten_query),
):
if q:
like = f"%{q}%"
query = query.filter(or_(Patient.vorname.ilike(like), Patient.nachname.ilike(like)))
if pflegegrad is not None:
query = query.filter(Patient.pflegegrad == pflegegrad)
if zielgruppe:
query = query.filter(Patient.zielgruppe == zielgruppe)
return query.order_by(Patient.nachname, Patient.vorname).all()
@router.get("/{pid}", response_model=PatientOut)
def detail(patient: Patient = Depends(get_owned_patient)):
return patient
@router.post("", response_model=PatientOut, status_code=201)
def anlegen(
payload: PatientCreate,
db: Session = Depends(get_db),
user: Nutzer = Depends(require_login),
):
if user.rolle != "admin":
anzahl = db.query(Patient).filter(Patient.nutzer_id == user.id).count()
if anzahl >= MAX_PATIENTEN_PRO_KONTO:
raise HTTPException(
status_code=400,
detail=f"Maximal {MAX_PATIENTEN_PRO_KONTO} Patienten pro Konto erreicht.",
)
patient = Patient(**payload.model_dump(), nutzer_id=user.id)
db.add(patient)
db.commit()
db.refresh(patient)
return patient
@router.put("/{pid}", response_model=PatientOut)
def aktualisieren(
payload: PatientUpdate,
patient: Patient = Depends(get_owned_patient),
db: Session = Depends(get_db),
):
for feld, wert in payload.model_dump(exclude_unset=True).items():
setattr(patient, feld, wert)
db.commit()
db.refresh(patient)
return patient
@router.delete("/{pid}", status_code=204)
def loeschen(patient: Patient = Depends(get_owned_patient), db: Session = Depends(get_db)):
db.delete(patient)
db.commit()
@router.patch("/{pid}/pflegegrad", response_model=PatientOut)
def pflegegrad_setzen(
payload: PflegegradPatch,
patient: Patient = Depends(get_owned_patient),
db: Session = Depends(get_db),
):
patient.pflegegrad = payload.pflegegrad
db.commit()
db.refresh(patient)
return patient
@router.post("/{pid}/notizen", response_model=PatientOut)
def notizen_aendern(
payload: NotizUpdate,
patient: Patient = Depends(get_owned_patient),
db: Session = Depends(get_db),
user: Nutzer = Depends(require_login),
):
db.add(
NotizVerlauf(
patient_id=patient.id,
notizen_alt=patient.notizen,
notizen_neu=payload.notizen_neu,
aenderungsgrund=payload.aenderungsgrund,
geaendert_von=user.name or user.benutzername,
)
)
patient.notizen = payload.notizen_neu
db.commit()
db.refresh(patient)
return patient
@router.get("/{pid}/notizen/verlauf", response_model=list[NotizVerlaufOut])
def notizen_verlauf(
patient: Patient = Depends(get_owned_patient), db: Session = Depends(get_db)
):
return (
db.query(NotizVerlauf)
.filter(NotizVerlauf.patient_id == patient.id)
.order_by(NotizVerlauf.geaendert_am.desc())
.all()
)
+78 -1
View File
@@ -1,4 +1,6 @@
from pydantic import BaseModel
import datetime
from pydantic import BaseModel, ConfigDict, Field
class LoginRequest(BaseModel):
@@ -30,3 +32,78 @@ class MeResponse(BaseModel):
rolle: str
ist_demo: bool
selbst_registriert: bool
class PatientBase(BaseModel):
vorname: str
nachname: str
geburtsdatum: datetime.date | None = None
strasse: str | None = None
plz: str | None = None
ort: str | None = None
telefon: str | None = None
email: str | None = None
krankenkasse: str | None = None
versichertennummer: str | None = None
versicherungsart: str = "GKV"
pflegegrad: int = Field(default=0, ge=0, le=5)
pflegeperson: str | None = None
zielgruppe: str = "alterspflege"
notizen: str | None = None
class PatientCreate(PatientBase):
pass
class PatientUpdate(BaseModel):
vorname: str | None = None
nachname: str | None = None
geburtsdatum: datetime.date | None = None
strasse: str | None = None
plz: str | None = None
ort: str | None = None
telefon: str | None = None
email: str | None = None
krankenkasse: str | None = None
versichertennummer: str | None = None
versicherungsart: str | None = None
pflegeperson: str | None = None
zielgruppe: str | None = None
class PatientOut(PatientBase):
model_config = ConfigDict(from_attributes=True)
id: int
patient_status: str
nutzer_id: int
erstellt_am: datetime.datetime
geaendert_am: datetime.datetime
class PflegegradPatch(BaseModel):
pflegegrad: int = Field(ge=0, le=5)
class NotizUpdate(BaseModel):
notizen_neu: str
aenderungsgrund: str
class NotizVerlaufOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
notizen_alt: str | None
notizen_neu: str
aenderungsgrund: str
geaendert_von: str
geaendert_am: datetime.datetime
class DashboardOut(BaseModel):
patienten_anzahl: int
offene_antraege: int
offene_aufgaben: int
letzte_patienten: list[PatientOut]
+12
View File
@@ -24,6 +24,11 @@ services:
ports:
- "${API_PORT:-8100}:5050"
volumes:
# Bind-Mounts fuer schnelle Iteration ueber viele Phasen hinweg (kein
# Image-Rebuild noetig, nur "docker compose restart api" nach Aenderungen
# an app-Code - neue requirements.txt-Pakete brauchen weiterhin ein Rebuild).
- ./backend/app:/app/app
- ./backend/migrations:/app/migrations
- pflegepilot_v3_uploads:/app/app/uploads
depends_on:
db:
@@ -35,6 +40,13 @@ services:
NEXT_PUBLIC_API_URL: ${NEXT_PUBLIC_API_URL}
ports:
- "${WEB_PORT:-3100}:3000"
volumes:
- ./frontend:/app
# Anonyme Volumes shadowen den Bind-Mount, damit die im Image
# (Linux) installierten node_modules genutzt werden statt der
# ggf. Windows-spezifischen node_modules vom Host.
- /app/node_modules
- /app/.next
depends_on:
- api
@@ -1,24 +1,58 @@
"use client";
import { useAuth } from "@/lib/auth";
import Link from "next/link";
import { useDashboard } from "@/lib/patienten";
import { BentoGrid, BentoTile } from "@/components/BentoGrid";
export default function DashboardPage() {
const { meQuery, logout } = useAuth();
const me = meQuery.data;
const { data, isLoading } = useDashboard();
return (
<main className="mx-auto max-w-2xl p-8">
<h1 className="text-2xl font-semibold text-slate-800">Dashboard</h1>
<p className="mt-2 text-slate-600">
Eingeloggt als <strong>{me?.name ?? me?.benutzername}</strong> ({me?.rolle})
{me?.ist_demo && " · Demo-Konto"}
</p>
<button
onClick={() => logout.mutate()}
className="mt-6 rounded-lg border border-slate-300 px-3 py-2 text-sm text-slate-700"
>
Abmelden
</button>
</main>
<div className="mx-auto max-w-5xl p-6">
<h1 className="mb-4 text-2xl font-semibold text-slate-800">Dashboard</h1>
{isLoading || !data ? (
<p className="text-slate-400">Lädt…</p>
) : (
<BentoGrid>
<BentoTile accent="mint">
<p className="text-xs font-medium text-slate-500">Patienten</p>
<p className="mt-1 text-3xl font-semibold text-slate-800">{data.patienten_anzahl}</p>
</BentoTile>
<BentoTile accent="lavender">
<p className="text-xs font-medium text-slate-500">Offene Anträge</p>
<p className="mt-1 text-3xl font-semibold text-slate-800">{data.offene_antraege}</p>
</BentoTile>
<BentoTile accent="peach">
<p className="text-xs font-medium text-slate-500">Offene Aufgaben</p>
<p className="mt-1 text-3xl font-semibold text-slate-800">{data.offene_aufgaben}</p>
</BentoTile>
<BentoTile accent="rose">
<p className="text-xs font-medium text-slate-500">Schnellzugriff</p>
<Link href="/patienten/neu" className="mt-1 block text-sm font-medium text-slate-700 underline">
+ Neuer Patient
</Link>
</BentoTile>
<BentoTile span={4}>
<p className="mb-3 text-sm font-semibold text-slate-700">Zuletzt bearbeitete Patienten</p>
{data.letzte_patienten.length === 0 ? (
<p className="text-sm text-slate-400">Noch keine Patienten angelegt.</p>
) : (
<ul className="divide-y divide-slate-100">
{data.letzte_patienten.map((p) => (
<li key={p.id} className="py-2">
<Link href={`/patienten/${p.id}`} className="text-sm text-slate-700 hover:underline">
{p.vorname} {p.nachname}
<span className="ml-2 text-xs text-slate-400">Pflegegrad {p.pflegegrad}</span>
</Link>
</li>
))}
</ul>
)}
</BentoTile>
</BentoGrid>
)}
</div>
);
}
@@ -1,18 +1,44 @@
"use client";
import Link from "next/link";
import { useAuth } from "@/lib/auth";
import { AuthOverlay } from "@/components/AuthOverlay";
export default function AppLayout({ children }: { children: React.ReactNode }) {
const { meQuery } = useAuth();
const { meQuery, logout } = useAuth();
const me = meQuery.data;
if (meQuery.isLoading) {
return <div className="flex min-h-screen items-center justify-center text-slate-400">Lädt…</div>;
}
if (!meQuery.data) {
if (!me) {
return <AuthOverlay />;
}
return <div className="min-h-screen bg-slate-50">{children}</div>;
return (
<div className="min-h-screen bg-slate-50">
<header className="flex items-center justify-between border-b border-slate-200 bg-white px-6 py-3">
<nav className="flex items-center gap-4 text-sm">
<span className="font-semibold text-slate-800">Pflegepilot</span>
<Link href="/dashboard" className="text-slate-600 hover:text-slate-900">
Dashboard
</Link>
<Link href="/patienten" className="text-slate-600 hover:text-slate-900">
Patienten
</Link>
</nav>
<div className="flex items-center gap-3 text-sm text-slate-500">
<span>
{me.name ?? me.benutzername}
{me.ist_demo && " · Demo"}
</span>
<button onClick={() => logout.mutate()} className="text-slate-500 underline">
Abmelden
</button>
</div>
</header>
<main>{children}</main>
</div>
);
}
@@ -0,0 +1,132 @@
"use client";
import { use, useState } from "react";
import { useRouter } from "next/navigation";
import { usePatient, useNotizenVerlauf, usePatientMutations } from "@/lib/patienten";
export default function PatientDetailPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = use(params);
const pid = Number(id);
const router = useRouter();
const { data: patient, isLoading } = usePatient(pid);
const { data: verlauf } = useNotizenVerlauf(pid);
const { pflegegradSetzen, notizenAendern, loeschen } = usePatientMutations();
const [notizText, setNotizText] = useState("");
const [grund, setGrund] = useState("");
if (isLoading || !patient) {
return <div className="mx-auto max-w-3xl p-6 text-slate-400">Lädt…</div>;
}
const notizSpeichern = (e: React.FormEvent) => {
e.preventDefault();
if (!grund.trim()) return;
notizenAendern.mutate(
{ id: pid, notizen_neu: notizText, aenderungsgrund: grund },
{ onSuccess: () => setGrund("") }
);
};
return (
<div className="mx-auto max-w-3xl p-6">
<div className="mb-4 flex items-center justify-between">
<h1 className="text-2xl font-semibold text-slate-800">
{patient.vorname} {patient.nachname}
</h1>
<button
onClick={() => {
if (confirm("Diesen Patienten wirklich löschen?")) {
loeschen.mutate(pid, { onSuccess: () => router.push("/patienten") });
}
}}
className="text-sm text-red-600 underline"
>
Löschen
</button>
</div>
<section className="mb-6 grid grid-cols-2 gap-x-6 gap-y-2 rounded-2xl border border-slate-200 bg-white p-5 text-sm">
<Field label="Geburtsdatum" value={patient.geburtsdatum} />
<Field label="Zielgruppe" value={patient.zielgruppe} />
<Field label="Adresse" value={[patient.strasse, [patient.plz, patient.ort].filter(Boolean).join(" ")].filter(Boolean).join(", ")} />
<Field label="Telefon" value={patient.telefon} />
<Field label="Krankenkasse" value={patient.krankenkasse} />
<Field label="Status" value={patient.patient_status} />
</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">Pflegegrad</p>
<div className="flex flex-wrap gap-2">
{[0, 1, 2, 3, 4, 5].map((g) => (
<button
key={g}
onClick={() => pflegegradSetzen.mutate({ id: pid, pflegegrad: g })}
className={`rounded-full px-3 py-1 text-sm ${
patient.pflegegrad === g
? "bg-slate-800 text-white"
: "border border-slate-300 text-slate-600"
}`}
>
{g === 0 ? "keiner" : g}
</button>
))}
</div>
</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">Notizen</p>
<p className="mb-3 whitespace-pre-wrap text-sm text-slate-600">
{patient.notizen || "Noch keine Notizen."}
</p>
<form onSubmit={notizSpeichern} className="flex flex-col gap-2">
<textarea
placeholder="Neue Notiz…"
value={notizText}
onChange={(e) => setNotizText(e.target.value)}
className="rounded-lg border border-slate-300 px-3 py-2 text-sm"
rows={3}
/>
<input
required
placeholder="Änderungsgrund (Pflicht)"
value={grund}
onChange={(e) => setGrund(e.target.value)}
className="rounded-lg border border-slate-300 px-3 py-2 text-sm"
/>
<button
type="submit"
disabled={notizenAendern.isPending}
className="self-start rounded-lg bg-slate-800 px-4 py-2 text-sm font-medium text-white disabled:opacity-50"
>
Notiz speichern
</button>
</form>
{verlauf && verlauf.length > 0 && (
<div className="mt-4 border-t border-slate-100 pt-3">
<p className="mb-2 text-xs font-semibold text-slate-500">Verlauf</p>
<ul className="flex flex-col gap-2">
{verlauf.map((v) => (
<li key={v.id} className="text-xs text-slate-500">
<span className="font-medium text-slate-700">{v.geaendert_von}</span> ·{" "}
{new Date(v.geaendert_am).toLocaleString("de-DE")} · {v.aenderungsgrund}
</li>
))}
</ul>
</div>
)}
</section>
</div>
);
}
function Field({ label, value }: { label: string; value?: string | null }) {
return (
<div>
<p className="text-xs text-slate-400">{label}</p>
<p className="text-slate-700">{value || "–"}</p>
</div>
);
}
@@ -0,0 +1,100 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { usePatientMutations } from "@/lib/patienten";
import { DateWheelPicker } from "@/components/DateWheelPicker";
const vorEinemJahrhundert = () => {
const d = new Date();
d.setFullYear(d.getFullYear() - 75);
return d;
};
export default function NeuerPatientPage() {
const router = useRouter();
const { anlegen } = usePatientMutations();
const [form, setForm] = useState({
vorname: "",
nachname: "",
geburtsdatum: null as string | null,
zielgruppe: "alterspflege",
pflegegrad: 0,
});
const submit = async (e: React.FormEvent) => {
e.preventDefault();
const patient = await anlegen.mutateAsync(form);
router.push(`/patienten/${patient.id}`);
};
return (
<div className="mx-auto max-w-md p-6">
<h1 className="mb-4 text-2xl font-semibold text-slate-800">Neuer Patient</h1>
<p className="mb-4 text-sm text-slate-500">
Kurzformular für Phase 1 – der ausführliche Interview-Assistent folgt in Phase 2.
</p>
<form onSubmit={submit} className="flex flex-col gap-3">
<input
required
placeholder="Vorname"
value={form.vorname}
onChange={(e) => setForm((f) => ({ ...f, vorname: e.target.value }))}
className="rounded-lg border border-slate-300 px-3 py-2 text-sm"
/>
<input
required
placeholder="Nachname"
value={form.nachname}
onChange={(e) => setForm((f) => ({ ...f, nachname: e.target.value }))}
className="rounded-lg border border-slate-300 px-3 py-2 text-sm"
/>
<label className="text-xs font-medium text-slate-500">Geburtsdatum</label>
<DateWheelPicker
value={form.geburtsdatum}
onChange={(iso) => setForm((f) => ({ ...f, geburtsdatum: iso }))}
fallbackDate={vorEinemJahrhundert()}
label="Geburtsdatum"
/>
<label className="text-xs font-medium text-slate-500">Zielgruppe</label>
<select
value={form.zielgruppe}
onChange={(e) => setForm((f) => ({ ...f, zielgruppe: e.target.value }))}
className="rounded-lg border border-slate-300 px-3 py-2 text-sm"
>
<option value="alterspflege">Altersbedingt</option>
<option value="beduerftige">Bedürftige</option>
<option value="behinderte">Behinderung</option>
</select>
<label className="text-xs font-medium text-slate-500">Pflegegrad</label>
<select
value={form.pflegegrad}
onChange={(e) => setForm((f) => ({ ...f, pflegegrad: Number(e.target.value) }))}
className="rounded-lg border border-slate-300 px-3 py-2 text-sm"
>
{[0, 1, 2, 3, 4, 5].map((g) => (
<option key={g} value={g}>
{g === 0 ? "Noch kein Pflegegrad" : `Pflegegrad ${g}`}
</option>
))}
</select>
{anlegen.isError && (
<p className="text-sm text-red-600">{(anlegen.error as Error).message}</p>
)}
<button
type="submit"
disabled={anlegen.isPending}
className="mt-2 rounded-lg bg-slate-800 px-4 py-2 text-sm font-medium text-white disabled:opacity-50"
>
Patient anlegen
</button>
</form>
</div>
);
}
@@ -0,0 +1,80 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import { usePatienten } from "@/lib/patienten";
import { ResponsiveTable, type Column } from "@/components/ResponsiveTable";
import type { Patient } from "@/lib/patienten";
const ZIELGRUPPEN = [
{ value: "", label: "Alle Zielgruppen" },
{ value: "alterspflege", label: "Altersbedingt" },
{ value: "beduerftige", label: "Bedürftige" },
{ value: "behinderte", label: "Behinderung" },
];
export default function PatientenPage() {
const [q, setQ] = useState("");
const [zielgruppe, setZielgruppe] = useState("");
const { data, isLoading } = usePatienten({ q: q || undefined, zielgruppe: zielgruppe || undefined });
const columns: Column<Patient>[] = [
{
key: "name",
label: "Name",
head: true,
render: (p) => (
<Link href={`/patienten/${p.id}`} className="font-medium text-slate-800 hover:underline">
{p.vorname} {p.nachname}
</Link>
),
},
{ key: "pflegegrad", label: "Pflegegrad", render: (p) => p.pflegegrad },
{
key: "zielgruppe",
label: "Zielgruppe",
render: (p) => ZIELGRUPPEN.find((z) => z.value === p.zielgruppe)?.label ?? p.zielgruppe,
},
{ key: "status", label: "Status", render: (p) => p.patient_status },
];
return (
<div className="mx-auto max-w-5xl p-6">
<div className="mb-4 flex items-center justify-between">
<h1 className="text-2xl font-semibold text-slate-800">Patienten</h1>
<Link
href="/patienten/neu"
className="rounded-lg bg-slate-800 px-4 py-2 text-sm font-medium text-white"
>
+ Neuer Patient
</Link>
</div>
<div className="mb-4 flex flex-wrap gap-2">
<input
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder="Suche nach Name…"
className="rounded-lg border border-slate-300 px-3 py-2 text-sm"
/>
<select
value={zielgruppe}
onChange={(e) => setZielgruppe(e.target.value)}
className="rounded-lg border border-slate-300 px-3 py-2 text-sm"
>
{ZIELGRUPPEN.map((z) => (
<option key={z.value} value={z.value}>
{z.label}
</option>
))}
</select>
</div>
{isLoading ? (
<p className="text-slate-400">Lädt…</p>
) : (
<ResponsiveTable columns={columns} rows={data ?? []} rowKey={(p) => p.id} />
)}
</div>
);
}
@@ -24,3 +24,56 @@ body {
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
}
/* Responsive-Tabelle: normale <table> ab 700px, darunter Akkordeon-Karten.
Muster aus der alten App (.rtable/rtInit) uebernommen - siehe CLAUDE.md
"Responsive tables -> cards". */
@media (max-width: 700px) {
.rtable table,
.rtable thead,
.rtable tbody,
.rtable tr,
.rtable td {
display: block;
width: 100%;
}
.rtable thead {
display: none;
}
.rtable tr {
margin-bottom: 0.75rem;
border: 1px solid #e2e8f0;
border-radius: 0.75rem;
overflow: hidden;
background: white;
}
.rtable td {
padding: 0 1rem;
max-height: 0;
opacity: 0;
overflow: hidden;
transition: max-height 0.2s ease, opacity 0.2s ease, padding 0.2s ease;
}
.rtable td[data-label]::before {
content: attr(data-label);
display: block;
font-size: 0.7rem;
font-weight: 600;
color: #64748b;
margin-top: 0.5rem;
}
.rtable td.rt-head {
max-height: 130px;
opacity: 1;
padding: 0.75rem 1rem;
cursor: pointer;
}
.rtable tr.rt-open td {
max-height: 130px;
opacity: 1;
padding-bottom: 0.5rem;
}
.rtable tr.rt-open td:last-child {
padding-bottom: 0.75rem;
}
}
@@ -0,0 +1,34 @@
export function BentoGrid({ children }: { children: React.ReactNode }) {
return (
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">{children}</div>
);
}
const gradients: Record<string, string> = {
mint: "from-emerald-50 to-teal-50 border-emerald-100",
lavender: "from-violet-50 to-indigo-50 border-violet-100",
peach: "from-orange-50 to-amber-50 border-orange-100",
rose: "from-rose-50 to-pink-50 border-rose-100",
};
export function BentoTile({
children,
span = 1,
accent,
className = "",
}: {
children: React.ReactNode;
span?: 1 | 2 | 4;
accent?: keyof typeof gradients;
className?: string;
}) {
const spanClass = span === 4 ? "lg:col-span-4" : span === 2 ? "lg:col-span-2" : "";
const accentClass = accent ? `bg-gradient-to-br ${gradients[accent]}` : "bg-white border-slate-200";
return (
<div
className={`rounded-2xl border p-5 shadow-sm ${accentClass} ${spanClass} ${className}`}
>
{children}
</div>
);
}
@@ -0,0 +1,163 @@
"use client";
import { useEffect, useRef, useState } from "react";
const ITEM_H = 40;
const VISIBLE = 5;
const PAD = Math.floor(VISIBLE / 2) * ITEM_H;
const MONATE = [
"Januar",
"Februar",
"März",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember",
];
function daysInMonth(year: number, month: number) {
return new Date(year, month, 0).getDate();
}
function WheelColumn({
items,
selectedIndex,
onSelect,
}: {
items: string[];
selectedIndex: number;
onSelect: (index: number) => void;
}) {
const ref = useRef<HTMLDivElement>(null);
const timeout = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
ref.current?.scrollTo({ top: selectedIndex * ITEM_H });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handleScroll = () => {
if (timeout.current) clearTimeout(timeout.current);
timeout.current = setTimeout(() => {
const el = ref.current;
if (!el) return;
const index = Math.round(el.scrollTop / ITEM_H);
const clamped = Math.min(Math.max(index, 0), items.length - 1);
onSelect(clamped);
}, 120);
};
return (
<div
ref={ref}
onScroll={handleScroll}
className="h-[200px] flex-1 snap-y snap-mandatory overflow-y-auto scroll-smooth [scrollbar-width:none]"
style={{ paddingTop: PAD, paddingBottom: PAD }}
>
{items.map((item, i) => (
<div
key={item + i}
className={`flex h-10 snap-center items-center justify-center text-sm ${
i === selectedIndex ? "font-semibold text-slate-900" : "text-slate-400"
}`}
>
{item}
</div>
))}
</div>
);
}
export function DateWheelPicker({
value,
onChange,
fallbackDate,
label = "Datum",
}: {
value: string | null;
onChange: (iso: string) => void;
fallbackDate?: Date;
label?: string;
}) {
const [open, setOpen] = useState(false);
const base = value ? new Date(value) : fallbackDate ?? new Date();
const [day, setDay] = useState(base.getDate());
const [month, setMonth] = useState(base.getMonth() + 1);
const [year, setYear] = useState(base.getFullYear());
const nowYear = new Date().getFullYear();
const years = Array.from({ length: 130 }, (_, i) => String(nowYear + 5 - i));
const days = Array.from({ length: daysInMonth(year, month) }, (_, i) => String(i + 1));
const confirm = () => {
const clampedDay = Math.min(day, daysInMonth(year, month));
const iso = `${year}-${String(month).padStart(2, "0")}-${String(clampedDay).padStart(2, "0")}`;
onChange(iso);
setOpen(false);
};
const display = value
? new Date(value).toLocaleDateString("de-DE", { day: "2-digit", month: "2-digit", year: "numeric" })
: "Datum wählen";
return (
<>
<button
type="button"
onClick={() => setOpen(true)}
className="w-full rounded-lg border border-slate-300 px-3 py-2 text-left text-sm text-slate-700"
>
{display}
</button>
{open && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 p-4">
<div className="w-full max-w-xs rounded-2xl bg-white p-5 shadow-xl">
<h2 className="mb-3 text-sm font-semibold text-slate-700">{label}</h2>
<div className="relative flex">
<div className="pointer-events-none absolute inset-x-0 top-1/2 h-10 -translate-y-1/2 rounded-lg bg-slate-100" />
<WheelColumn
items={days}
selectedIndex={Math.min(day, days.length) - 1}
onSelect={(i) => setDay(i + 1)}
/>
<WheelColumn
items={MONATE}
selectedIndex={month - 1}
onSelect={(i) => setMonth(i + 1)}
/>
<WheelColumn
items={years}
selectedIndex={years.indexOf(String(year))}
onSelect={(i) => setYear(Number(years[i]))}
/>
</div>
<div className="mt-4 flex gap-2">
<button
type="button"
onClick={() => setOpen(false)}
className="flex-1 rounded-lg border border-slate-300 px-3 py-2 text-sm text-slate-600"
>
Abbrechen
</button>
<button
type="button"
onClick={confirm}
className="flex-1 rounded-lg bg-slate-800 px-3 py-2 text-sm font-medium text-white"
>
Übernehmen
</button>
</div>
</div>
</div>
)}
</>
);
}
@@ -0,0 +1,70 @@
"use client";
import { useState } from "react";
export type Column<T> = {
key: string;
label: string;
render: (row: T) => React.ReactNode;
/** Diese Spalte bleibt auch im collapsed Mobile-Zustand sichtbar (Kopfzeile der Karte). */
head?: boolean;
};
export function ResponsiveTable<T>({
columns,
rows,
rowKey,
}: {
columns: Column<T>[];
rows: T[];
rowKey: (row: T) => string | number;
}) {
const [openId, setOpenId] = useState<string | number | null>(
rows.length > 0 ? rowKey(rows[0]) : null
);
if (rows.length === 0) {
return <p className="py-8 text-center text-sm text-slate-400">Keine Einträge.</p>;
}
return (
<div className="rtable">
<table className="w-full border-collapse text-left text-sm">
<thead>
<tr className="border-b border-slate-200 text-xs font-semibold text-slate-500">
{columns.map((col) => (
<th key={col.key} className="px-4 py-2">
{col.label}
</th>
))}
</tr>
</thead>
<tbody>
{rows.map((row) => {
const id = rowKey(row);
const isOpen = openId === id;
return (
<tr
key={id}
className={`border-b border-slate-100 last:border-0 ${isOpen ? "rt-open" : ""}`}
>
{columns.map((col) => (
<td
key={col.key}
data-label={col.label}
className={col.head ? "rt-head" : undefined}
onClick={col.head ? () => setOpenId(isOpen ? null : id) : undefined}
>
<span className="px-4 py-2 max-sm:px-0 max-sm:py-0 block">
{col.render(row)}
</span>
</td>
))}
</tr>
);
})}
</tbody>
</table>
</div>
);
}
@@ -0,0 +1,135 @@
"use client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "./api";
export type Patient = {
id: number;
vorname: string;
nachname: string;
geburtsdatum: string | null;
strasse: string | null;
plz: string | null;
ort: string | null;
telefon: string | null;
email: string | null;
krankenkasse: string | null;
versichertennummer: string | null;
versicherungsart: string;
pflegegrad: number;
pflegeperson: string | null;
zielgruppe: string;
notizen: string | null;
patient_status: string;
nutzer_id: number;
erstellt_am: string;
geaendert_am: string;
};
export type Dashboard = {
patienten_anzahl: number;
offene_antraege: number;
offene_aufgaben: number;
letzte_patienten: Patient[];
};
export type NotizVerlauf = {
id: number;
notizen_alt: string | null;
notizen_neu: string;
aenderungsgrund: string;
geaendert_von: string;
geaendert_am: string;
};
export function usePatienten(filter: { q?: string; pflegegrad?: number; zielgruppe?: string } = {}) {
const params = new URLSearchParams();
if (filter.q) params.set("q", filter.q);
if (filter.pflegegrad !== undefined) params.set("pflegegrad", String(filter.pflegegrad));
if (filter.zielgruppe) params.set("zielgruppe", filter.zielgruppe);
const qs = params.toString();
return useQuery<Patient[]>({
queryKey: ["patienten", filter],
queryFn: () => api<Patient[]>(`/api/patienten${qs ? `?${qs}` : ""}`),
});
}
export function usePatient(id: number) {
return useQuery<Patient>({
queryKey: ["patienten", id],
queryFn: () => api<Patient>(`/api/patienten/${id}`),
enabled: !!id,
});
}
export function useDashboard() {
return useQuery<Dashboard>({
queryKey: ["dashboard"],
queryFn: () => api<Dashboard>("/api/dashboard"),
});
}
export function useNotizenVerlauf(id: number) {
return useQuery<NotizVerlauf[]>({
queryKey: ["patienten", id, "notizen-verlauf"],
queryFn: () => api<NotizVerlauf[]>(`/api/patienten/${id}/notizen/verlauf`),
enabled: !!id,
});
}
export function usePatientMutations() {
const queryClient = useQueryClient();
const invalidate = () => {
queryClient.invalidateQueries({ queryKey: ["patienten"] });
queryClient.invalidateQueries({ queryKey: ["dashboard"] });
};
const anlegen = useMutation({
mutationFn: (payload: Partial<Patient> & { vorname: string; nachname: string }) =>
api<Patient>("/api/patienten", { method: "POST", body: JSON.stringify(payload) }),
onSuccess: invalidate,
});
const aktualisieren = useMutation({
mutationFn: ({ id, payload }: { id: number; payload: Partial<Patient> }) =>
api<Patient>(`/api/patienten/${id}`, { method: "PUT", body: JSON.stringify(payload) }),
onSuccess: invalidate,
});
const loeschen = useMutation({
mutationFn: (id: number) => api<void>(`/api/patienten/${id}`, { method: "DELETE" }),
onSuccess: invalidate,
});
const pflegegradSetzen = useMutation({
mutationFn: ({ id, pflegegrad }: { id: number; pflegegrad: number }) =>
api<Patient>(`/api/patienten/${id}/pflegegrad`, {
method: "PATCH",
body: JSON.stringify({ pflegegrad }),
}),
onSuccess: invalidate,
});
const notizenAendern = useMutation({
mutationFn: ({
id,
notizen_neu,
aenderungsgrund,
}: {
id: number;
notizen_neu: string;
aenderungsgrund: string;
}) =>
api<Patient>(`/api/patienten/${id}/notizen`, {
method: "POST",
body: JSON.stringify({ notizen_neu, aenderungsgrund }),
}),
onSuccess: (_data, vars) => {
invalidate();
queryClient.invalidateQueries({ queryKey: ["patienten", vars.id, "notizen-verlauf"] });
},
});
return { anlegen, aktualisieren, loeschen, pflegegradSetzen, notizenAendern };
}