Backend-Isolation: Nutzer sehen nur eigene Patienten
- patienten.nutzer_id (FK -> nutzer.id) als neue Migration in init_db() - _get_owned_patient(pid) und _scope_sql(column) als zentrale Helper, auf alle patientenbezogenen Routen angewendet (patienten, antraege, leistungen, aufgaben, pflegetagebuch, dokumente, kalender, dashboard) - Admin-Rolle bleibt von der Isolation ausgenommen (sieht weiterhin alle) - Neue Patienten werden automatisch dem anlegenden Nutzer zugeordnet - aufgaben ohne patient_id: Erstellung durch Nicht-Admins jetzt patient_id-pflichtig, damit Lese-/Schreibpfad konsistent bleiben - Verifiziert per End-to-End-Test mit zwei Nutzerkonten + Admin Erster Baustein aus refactoring.md; Interview-Flow und Admin-Dashboard folgen nach Rücksprache (siehe CLAUDE.md).
This commit is contained in:
1 parent
f234399d28
commit
022a286c55
2 files changed
+136
-46
No files matched your search
@@ -42,18 +42,19 @@ Default login after first start: `admin` / `admin` (created automatically by `in
|
||||
- `db/schema.sql` — base SQLite schema (`patienten`, `antraege`, `leistungen`, `aufgaben`, `pflegetagebuch`, `einstellungen`, `dokumente`) plus demo seed rows.
|
||||
- **Schema evolution pattern**: `init_db()` in `app.py` runs `schema.sql` once, then re-applies a hardcoded list of `ALTER TABLE` / `CREATE TABLE IF NOT EXISTS` statements on every startup, each wrapped in its own try/except so an already-applied migration is silently skipped. When adding a column or table, add a new entry to that list rather than editing `schema.sql` (existing DBs won't be recreated) — and keep entries idempotent/backward-compatible since this list re-runs on every process start.
|
||||
- **Auth**: session-cookie based. `_get_current_user()` / `_check_admin()` read `session["nutzer_id"]`; `login_required` / `admin_required` decorators guard individual routes, while `global_auth_check()` (a Flask `before_request` hook) blanket-blocks any `/api/*` path not in the small public allowlist (`/api/auth/login`, `/api/auth/me`, `/api/einstellungen/public`). Two roles exist: `admin` and `nutzer`. Passwords are hashed with `werkzeug.security` (PBKDF2).
|
||||
- **Patient isolation**: `patienten.nutzer_id` (FK to `nutzer.id`) records who owns each patient — set automatically to the creating user on `POST /api/patienten`. Two helpers in `app.py` enforce it everywhere: `_get_owned_patient(pid)` (single-patient routes — returns the row if the current user is the owner or an admin, else `None` → caller returns 404) and `_scope_sql(column="id")` (list/aggregate routes — returns a SQL fragment + params to append to a `WHERE` clause; empty for admins, `AND {column} IN (SELECT id FROM patienten WHERE nutzer_id=?)` otherwise). `admin` role is exempt and always sees every patient. Every route touching `patienten` or a child table (`antraege`, `leistungen`, `aufgaben`, `pflegetagebuch`, `dokumente`) must go through one of these two helpers — when adding a new patient-scoped route, follow the existing pattern rather than querying the table directly. `aufgaben.patient_id` is nullable in the schema, but the API now requires a `patient_id` from non-admin callers on creation (admins may still create patient-less tasks) so the isolation model stays consistent between write and read paths.
|
||||
- **File storage**: everything is local under `static/` — `static/fotos/<patient_id>.<ext>` (profile photos), `static/briefe/<patient_id>/…` (generated letter PDFs), `static/dokumente/<patient_id>/…` (uploaded documents), `static/logo/` (company branding). No object storage/CDN involved.
|
||||
- **Settings**: a generic key-value `einstellungen` table (accessed via `get_setting()`) holds SMTP credentials, company branding/address, and an (unused-in-current-flow) Claude API token — surfaced through `/api/admin/einstellungen`.
|
||||
|
||||
## Planned architecture pivot (see `refactoring.md`)
|
||||
|
||||
The app currently runs as a **central multi-patient service**: any logged-in user can see all patients. The product owner has specified a pivot to:
|
||||
The product owner specified a pivot away from the original **central multi-patient service** (any logged-in user could see all patients) toward three changes:
|
||||
|
||||
1. **Per-account patient isolation** — a logged-in user (a family member/informal caregiver) should only ever see their own 1–3 patients, with no way to browse or discover other patients. This is a real authorization boundary to add to every `/api/patienten*` (and related) route, not just a UI filter.
|
||||
2. **No-AI interview flow** — a plain web-form "interview" for onboarding a new patient, aimed at non-technical relatives, replacing/supplementing the current `pgNeu()` single-form patient creation.
|
||||
3. **Admin dashboard** — for the operator: lock/delete accounts, and export archived patient data under lawful (attorney/court) order, with GDPR (DSGVO) compliance as a hard requirement — this affects both the operator's own liability and every caregiver's/patient's rights.
|
||||
1. **Per-account patient isolation** — ✅ implemented. Data model: 1 `nutzer` = 1 account, `patienten.nutzer_id` FK, `admin` role exempt (sees everything). See "Patient isolation" above for the enforcement mechanism. Verified end-to-end (two non-admin accounts cannot see or directly access each other's patients; admin sees all).
|
||||
2. **No-AI interview flow** — not started. A plain web-form "interview" for onboarding a new patient, aimed at non-technical relatives, replacing/supplementing the current `pgNeu()` single-form patient creation.
|
||||
3. **Admin dashboard** — not started. Lock/delete accounts, and export archived patient data under lawful (attorney/court) order, with GDPR (DSGVO) compliance as a hard requirement.
|
||||
|
||||
The user has explicitly asked to be asked clarifying questions about architecture, data model, and server structure before this refactor is implemented — don't assume a specific multi-tenancy design (e.g. per-user `nutzer_id` foreign key on `patienten` vs. a separate `familien`/account entity) without confirming it first.
|
||||
The user has asked to be asked clarifying questions about architecture/data model before each piece of this refactor — confirmed decisions so far: 1 nutzer = 1 account (no separate `familien` entity), admin bypasses isolation entirely, backend isolation was built before the interview flow or admin dashboard. Apply the same "ask before assuming" approach to the remaining two pieces.
|
||||
|
||||
## Known constraints worth knowing before touching auth/security-sensitive code
|
||||
|
||||
|
||||
@@ -59,6 +59,7 @@ def init_db():
|
||||
"ALTER TABLE patienten ADD COLUMN status_datum TEXT",
|
||||
"ALTER TABLE patienten ADD COLUMN archiv_frist TEXT",
|
||||
"ALTER TABLE patienten ADD COLUMN archiv_hinweis TEXT",
|
||||
"ALTER TABLE patienten ADD COLUMN nutzer_id INTEGER REFERENCES nutzer(id)",
|
||||
"""CREATE TABLE IF NOT EXISTS dokumente (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
patient_id INTEGER NOT NULL REFERENCES patienten(id) ON DELETE CASCADE,
|
||||
@@ -126,6 +127,34 @@ def _check_admin():
|
||||
u = _get_current_user()
|
||||
return u is not None and u["rolle"] == "admin"
|
||||
|
||||
# ─── Patienten-Isolation ──────────────────────────────────────────────────────
|
||||
# Jeder Nutzer verwaltet i.d.R. 1-3 eigene Angehörige (patienten.nutzer_id).
|
||||
# Admins sind von der Isolation ausgenommen und sehen alle Patienten.
|
||||
def _scope_sql(column="id"):
|
||||
"""SQL-Fragment + Params, um eine Query auf die eigenen Patienten des
|
||||
aktuellen Nutzers einzuschränken. Admins bekommen kein Fragment (= alle).
|
||||
column ist die Patienten-ID-Spalte der Query ('id' bei direkten Abfragen
|
||||
auf patienten, 'patient_id' bei Kindtabellen)."""
|
||||
u = _get_current_user()
|
||||
if u is None:
|
||||
return " AND 0", []
|
||||
if u["rolle"] == "admin":
|
||||
return "", []
|
||||
return f" AND {column} IN (SELECT id FROM patienten WHERE nutzer_id=?)", [u["id"]]
|
||||
|
||||
def _get_owned_patient(pid):
|
||||
"""Patienten-Datensatz, falls der aktuelle Nutzer zugreifen darf
|
||||
(Admin oder Eigentümer), sonst None."""
|
||||
db = get_db()
|
||||
u = _get_current_user()
|
||||
if u is None:
|
||||
return None
|
||||
if u["rolle"] == "admin":
|
||||
return db.execute("SELECT * FROM patienten WHERE id=?", (pid,)).fetchone()
|
||||
return db.execute(
|
||||
"SELECT * FROM patienten WHERE id=? AND nutzer_id=?", (pid, u["id"])
|
||||
).fetchone()
|
||||
|
||||
def login_required(f):
|
||||
@functools.wraps(f)
|
||||
def decorated(*args, **kwargs):
|
||||
@@ -333,6 +362,9 @@ def api_patienten():
|
||||
zg = request.args.get("zielgruppe", "")
|
||||
sql = "SELECT * FROM patienten WHERE 1=1"
|
||||
params = []
|
||||
scope, scope_params = _scope_sql("id")
|
||||
sql += scope
|
||||
params += scope_params
|
||||
if q:
|
||||
sql += " AND (vorname||' '||nachname LIKE ? OR krankenkasse LIKE ?)"
|
||||
params += [f"%{q}%", f"%{q}%"]
|
||||
@@ -349,7 +381,7 @@ def api_patienten():
|
||||
@app.route("/api/patienten/<int:pid>", methods=["GET"])
|
||||
def api_patient(pid):
|
||||
db = get_db()
|
||||
p = db.execute("SELECT * FROM patienten WHERE id=?", (pid,)).fetchone()
|
||||
p = _get_owned_patient(pid)
|
||||
if not p: return jsonify({"error": "Nicht gefunden"}), 404
|
||||
antraege = db.execute("SELECT * FROM antraege WHERE patient_id=? ORDER BY erstellt_am DESC", (pid,)).fetchall()
|
||||
leistungen = db.execute("SELECT * FROM leistungen WHERE patient_id=? AND aktiv=1", (pid,)).fetchall()
|
||||
@@ -373,23 +405,27 @@ def api_patient(pid):
|
||||
def api_neuer_patient():
|
||||
db = get_db()
|
||||
d = request.json
|
||||
u = _get_current_user()
|
||||
cur = db.execute("""
|
||||
INSERT INTO patienten (vorname,nachname,geburtsdatum,strasse,plz,ort,
|
||||
telefon,email,krankenkasse,versichertennummer,versicherungsart,
|
||||
pflegegrad,pflegeperson,zielgruppe,notizen)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
pflegegrad,pflegeperson,zielgruppe,notizen,nutzer_id)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
""", (d["vorname"], d["nachname"], d.get("geburtsdatum",""),
|
||||
d.get("strasse",""), d.get("plz",""), d.get("ort",""),
|
||||
d.get("telefon",""), d.get("email",""), d.get("krankenkasse",""),
|
||||
d.get("versichertennummer",""), d.get("versicherungsart","GKV"),
|
||||
int(d.get("pflegegrad",0)), d.get("pflegeperson",""),
|
||||
d.get("zielgruppe","alterspflege"), d.get("notizen","")))
|
||||
d.get("zielgruppe","alterspflege"), d.get("notizen",""),
|
||||
u["id"] if u else None))
|
||||
db.commit()
|
||||
return jsonify({"id": cur.lastrowid, "ok": True})
|
||||
|
||||
@app.route("/api/patienten/<int:pid>", methods=["PUT"])
|
||||
def api_update_patient(pid):
|
||||
db = get_db()
|
||||
if not _get_owned_patient(pid):
|
||||
return jsonify({"error": "Nicht gefunden"}), 404
|
||||
d = request.json
|
||||
db.execute("""
|
||||
UPDATE patienten SET vorname=?,nachname=?,geburtsdatum=?,strasse=?,plz=?,ort=?,
|
||||
@@ -407,6 +443,8 @@ def api_update_patient(pid):
|
||||
|
||||
@app.route("/api/patienten/<int:pid>", methods=["DELETE"])
|
||||
def api_delete_patient(pid):
|
||||
if not _get_owned_patient(pid):
|
||||
return jsonify({"error": "Nicht gefunden"}), 404
|
||||
db = get_db()
|
||||
db.execute("DELETE FROM patienten WHERE id=?", (pid,))
|
||||
db.commit()
|
||||
@@ -420,10 +458,10 @@ def api_notizen_aendern(pid):
|
||||
grund = (d.get("aenderungsgrund") or "").strip()
|
||||
if not grund:
|
||||
return jsonify({"error": "Änderungsgrund erforderlich"}), 400
|
||||
row = db.execute("SELECT notizen FROM patienten WHERE id=?", (pid,)).fetchone()
|
||||
row = _get_owned_patient(pid)
|
||||
if not row:
|
||||
return jsonify({"error": "Patient nicht gefunden"}), 404
|
||||
alte_notiz = row[0] or ""
|
||||
alte_notiz = row["notizen"] or ""
|
||||
db.execute("""
|
||||
INSERT INTO notizen_verlauf (patient_id, notizen_alt, notizen_neu, aenderungsgrund)
|
||||
VALUES (?, ?, ?, ?)
|
||||
@@ -435,6 +473,8 @@ def api_notizen_aendern(pid):
|
||||
|
||||
@app.route("/api/patienten/<int:pid>/notizen/verlauf", methods=["GET"])
|
||||
def api_notizen_verlauf(pid):
|
||||
if not _get_owned_patient(pid):
|
||||
return jsonify({"error": "Nicht gefunden"}), 404
|
||||
db = get_db()
|
||||
rows = db.execute("""
|
||||
SELECT id, notizen_alt, notizen_neu, aenderungsgrund, geaendert_von, geaendert_am
|
||||
@@ -447,6 +487,8 @@ def api_notizen_verlauf(pid):
|
||||
def api_neuer_antrag():
|
||||
db = get_db()
|
||||
d = request.json
|
||||
if not _get_owned_patient(d.get("patient_id")):
|
||||
return jsonify({"error": "Patient nicht gefunden"}), 404
|
||||
cur = db.execute("""
|
||||
INSERT INTO antraege (patient_id,typ,status,antragsdatum,beantragter_pflegegrad,
|
||||
notizen,brief_text,leistung_ids)
|
||||
@@ -466,6 +508,9 @@ def api_neuer_antrag():
|
||||
@app.route("/api/antraege/<int:aid>", methods=["PUT"])
|
||||
def api_update_antrag(aid):
|
||||
db = get_db()
|
||||
row = db.execute("SELECT patient_id FROM antraege WHERE id=?", (aid,)).fetchone()
|
||||
if not row or not _get_owned_patient(row["patient_id"]):
|
||||
return jsonify({"error": "Nicht gefunden"}), 404
|
||||
d = request.json
|
||||
db.execute("""
|
||||
UPDATE antraege SET status=?,bescheid_datum=?,zugeteilter_pflegegrad=?,
|
||||
@@ -480,6 +525,8 @@ def api_update_antrag(aid):
|
||||
|
||||
@app.route("/api/patienten/<int:pid>/pflegegrad", methods=["PATCH"])
|
||||
def api_patch_pflegegrad(pid):
|
||||
if not _get_owned_patient(pid):
|
||||
return jsonify({"error": "Nicht gefunden"}), 404
|
||||
db = get_db()
|
||||
d = request.json
|
||||
grad = d.get("pflegegrad")
|
||||
@@ -496,16 +543,20 @@ def api_patch_pflegegrad(pid):
|
||||
@app.route("/api/aufgaben", methods=["GET"])
|
||||
def api_aufgaben():
|
||||
db = get_db()
|
||||
rows = db.execute("""
|
||||
scope, scope_params = _scope_sql("a.patient_id")
|
||||
rows = db.execute(f"""
|
||||
SELECT a.*, p.vorname||' '||p.nachname AS patient_name
|
||||
FROM aufgaben a LEFT JOIN patienten p ON a.patient_id=p.id
|
||||
WHERE a.erledigt=0 ORDER BY a.faellig_am, a.prioritaet
|
||||
""").fetchall()
|
||||
WHERE a.erledigt=0{scope} ORDER BY a.faellig_am, a.prioritaet
|
||||
""", scope_params).fetchall()
|
||||
return jsonify([dict(r) for r in rows])
|
||||
|
||||
@app.route("/api/aufgaben/<int:aid>/erledigt", methods=["POST"])
|
||||
def api_aufgabe_erledigt(aid):
|
||||
db = get_db()
|
||||
row = db.execute("SELECT patient_id FROM aufgaben WHERE id=?", (aid,)).fetchone()
|
||||
if not row or not (_check_admin() or (row["patient_id"] and _get_owned_patient(row["patient_id"]))):
|
||||
return jsonify({"error": "Nicht gefunden"}), 404
|
||||
db.execute("UPDATE aufgaben SET erledigt=1 WHERE id=?", (aid,))
|
||||
db.commit()
|
||||
return jsonify({"ok": True})
|
||||
@@ -514,6 +565,12 @@ def api_aufgabe_erledigt(aid):
|
||||
def api_neue_aufgabe():
|
||||
db = get_db()
|
||||
d = request.json
|
||||
pid = d.get("patient_id")
|
||||
if pid:
|
||||
if not _get_owned_patient(pid):
|
||||
return jsonify({"error": "Patient nicht gefunden"}), 404
|
||||
elif not _check_admin():
|
||||
return jsonify({"error": "patient_id erforderlich"}), 400
|
||||
cur = db.execute("""INSERT INTO aufgaben (patient_id,titel,beschreibung,prioritaet,faellig_am)
|
||||
VALUES (?,?,?,?,?)""",
|
||||
(d.get("patient_id"), d["titel"], d.get("beschreibung",""),
|
||||
@@ -525,26 +582,31 @@ def api_neue_aufgabe():
|
||||
@app.route("/api/dashboard", methods=["GET"])
|
||||
def api_dashboard():
|
||||
db = get_db()
|
||||
pat_scope, pat_params = _scope_sql("id")
|
||||
ant_scope, ant_params = _scope_sql("patient_id")
|
||||
auf_scope, auf_params = _scope_sql("patient_id")
|
||||
stats = {
|
||||
"patienten": db.execute("SELECT COUNT(*) FROM patienten").fetchone()[0],
|
||||
"offene_antraege": db.execute("SELECT COUNT(*) FROM antraege WHERE status IN ('offen','in_pruefung')").fetchone()[0],
|
||||
"bescheide": db.execute("SELECT COUNT(*) FROM antraege WHERE status='in_pruefung'").fetchone()[0],
|
||||
"widersprueche": db.execute("SELECT COUNT(*) FROM antraege WHERE typ='widerspruch'").fetchone()[0],
|
||||
"offene_aufgaben": db.execute("SELECT COUNT(*) FROM aufgaben WHERE erledigt=0").fetchone()[0],
|
||||
"patienten": db.execute(f"SELECT COUNT(*) FROM patienten WHERE 1=1{pat_scope}", pat_params).fetchone()[0],
|
||||
"offene_antraege": db.execute(f"SELECT COUNT(*) FROM antraege WHERE status IN ('offen','in_pruefung'){ant_scope}", ant_params).fetchone()[0],
|
||||
"bescheide": db.execute(f"SELECT COUNT(*) FROM antraege WHERE status='in_pruefung'{ant_scope}", ant_params).fetchone()[0],
|
||||
"widersprueche": db.execute(f"SELECT COUNT(*) FROM antraege WHERE typ='widerspruch'{ant_scope}", ant_params).fetchone()[0],
|
||||
"offene_aufgaben": db.execute(f"SELECT COUNT(*) FROM aufgaben WHERE erledigt=0{auf_scope}", auf_params).fetchone()[0],
|
||||
"katalog_gesamt": len(KATALOG),
|
||||
}
|
||||
recent = db.execute("""
|
||||
recent_scope, recent_params = _scope_sql("p.id")
|
||||
recent = db.execute(f"""
|
||||
SELECT p.id, p.vorname, p.nachname, p.pflegegrad, p.zielgruppe,
|
||||
a.status, a.typ
|
||||
FROM patienten p
|
||||
LEFT JOIN antraege a ON a.id=(SELECT id FROM antraege WHERE patient_id=p.id ORDER BY erstellt_am DESC LIMIT 1)
|
||||
WHERE 1=1{recent_scope}
|
||||
ORDER BY p.geaendert_am DESC LIMIT 5
|
||||
""").fetchall()
|
||||
aufgaben = db.execute("""
|
||||
""", recent_params).fetchall()
|
||||
aufgaben = db.execute(f"""
|
||||
SELECT a.*, p.vorname||' '||p.nachname AS patient_name
|
||||
FROM aufgaben a LEFT JOIN patienten p ON a.patient_id=p.id
|
||||
WHERE a.erledigt=0 ORDER BY a.faellig_am LIMIT 5
|
||||
""").fetchall()
|
||||
WHERE a.erledigt=0{auf_scope} ORDER BY a.faellig_am LIMIT 5
|
||||
""", auf_params).fetchall()
|
||||
return jsonify({
|
||||
"stats": stats,
|
||||
"recent": [dict(r) for r in recent],
|
||||
@@ -574,8 +636,7 @@ def api_katalog_item(lid):
|
||||
@app.route("/api/katalog/patient/<int:pid>", methods=["GET"])
|
||||
def api_katalog_patient(pid):
|
||||
"""Alle passenden Leistungen für einen Patienten"""
|
||||
db = get_db()
|
||||
p = db.execute("SELECT * FROM patienten WHERE id=?", (pid,)).fetchone()
|
||||
p = _get_owned_patient(pid)
|
||||
if not p: return jsonify({"error":"Nicht gefunden"}), 404
|
||||
pd = dict(p)
|
||||
grad = pd.get("pflegegrad",0) or 0
|
||||
@@ -592,6 +653,8 @@ def api_katalog_patient(pid):
|
||||
# ─── API: Katalog-Leistung einem Patienten zuweisen ──────────────────────────
|
||||
@app.route("/api/patienten/<int:pid>/leistungen/katalog", methods=["POST"])
|
||||
def api_assign_katalog(pid):
|
||||
if not _get_owned_patient(pid):
|
||||
return jsonify({"error": "Nicht gefunden"}), 404
|
||||
db = get_db()
|
||||
d = request.json
|
||||
lid = d.get("katalog_id", "")
|
||||
@@ -623,6 +686,9 @@ def api_assign_katalog(pid):
|
||||
@app.route("/api/leistungen/<int:lid>/deaktivieren", methods=["POST"])
|
||||
def api_leistung_deaktivieren(lid):
|
||||
db = get_db()
|
||||
row = db.execute("SELECT patient_id FROM leistungen WHERE id=?", (lid,)).fetchone()
|
||||
if not row or not _get_owned_patient(row["patient_id"]):
|
||||
return jsonify({"error": "Nicht gefunden"}), 404
|
||||
db.execute("UPDATE leistungen SET aktiv=0 WHERE id=?", (lid,))
|
||||
db.commit()
|
||||
return jsonify({"ok": True})
|
||||
@@ -635,6 +701,8 @@ def api_widerspruch():
|
||||
# ─── API: Brief in Patientenakte speichern ───────────────────────────────────
|
||||
@app.route("/api/patienten/<int:pid>/briefe", methods=["POST"])
|
||||
def api_brief_speichern(pid):
|
||||
if not _get_owned_patient(pid):
|
||||
return jsonify({"error": "Nicht gefunden"}), 404
|
||||
db = get_db()
|
||||
d = request.json
|
||||
typ = d.get("typ", "musterbrief")
|
||||
@@ -705,6 +773,8 @@ def api_krankenkassen():
|
||||
# ─── API: Profilfoto ─────────────────────────────────────────────────────────
|
||||
@app.route("/api/patienten/<int:pid>/foto", methods=["POST"])
|
||||
def api_foto_upload(pid):
|
||||
if not _get_owned_patient(pid):
|
||||
return jsonify({"error": "Nicht gefunden"}), 404
|
||||
if "foto" not in request.files:
|
||||
return jsonify({"error": "Keine Datei"}), 400
|
||||
file = request.files["foto"]
|
||||
@@ -725,6 +795,8 @@ def api_foto_upload(pid):
|
||||
# ─── API: Pflegetagebuch ──────────────────────────────────────────────────────
|
||||
@app.route("/api/patienten/<int:pid>/tagebuch", methods=["GET"])
|
||||
def api_tagebuch_list(pid):
|
||||
if not _get_owned_patient(pid):
|
||||
return jsonify({"error": "Nicht gefunden"}), 404
|
||||
db = get_db()
|
||||
rows = db.execute(
|
||||
"SELECT * FROM pflegetagebuch WHERE patient_id=? ORDER BY datum DESC, erstellt_am DESC",
|
||||
@@ -734,6 +806,8 @@ def api_tagebuch_list(pid):
|
||||
|
||||
@app.route("/api/patienten/<int:pid>/tagebuch", methods=["POST"])
|
||||
def api_tagebuch_neu(pid):
|
||||
if not _get_owned_patient(pid):
|
||||
return jsonify({"error": "Nicht gefunden"}), 404
|
||||
db = get_db()
|
||||
d = request.json
|
||||
cur = db.execute("""
|
||||
@@ -750,6 +824,9 @@ def api_tagebuch_neu(pid):
|
||||
@app.route("/api/tagebuch/<int:tid>", methods=["DELETE"])
|
||||
def api_tagebuch_delete(tid):
|
||||
db = get_db()
|
||||
row = db.execute("SELECT patient_id FROM pflegetagebuch WHERE id=?", (tid,)).fetchone()
|
||||
if not row or not _get_owned_patient(row["patient_id"]):
|
||||
return jsonify({"error": "Nicht gefunden"}), 404
|
||||
db.execute("DELETE FROM pflegetagebuch WHERE id=?", (tid,))
|
||||
db.commit()
|
||||
return jsonify({"ok": True})
|
||||
@@ -838,27 +915,28 @@ def api_kalender():
|
||||
today_str = date.today().isoformat()
|
||||
|
||||
# Offene Aufgaben mit Fälligkeitsdatum
|
||||
for r in db.execute("""
|
||||
scope, scope_params = _scope_sql("a.patient_id")
|
||||
for r in db.execute(f"""
|
||||
SELECT a.id, a.titel, a.beschreibung, a.faellig_am, a.prioritaet,
|
||||
a.patient_id, p.vorname||' '||p.nachname AS pname
|
||||
FROM aufgaben a LEFT JOIN patienten p ON a.patient_id=p.id
|
||||
WHERE a.erledigt=0 AND a.faellig_am IS NOT NULL AND a.faellig_am != ''
|
||||
WHERE a.erledigt=0 AND a.faellig_am IS NOT NULL AND a.faellig_am != ''{scope}
|
||||
ORDER BY a.faellig_am
|
||||
""").fetchall():
|
||||
""", scope_params).fetchall():
|
||||
events.append({"typ":"aufgabe","id":r["id"],"titel":r["titel"],
|
||||
"beschreibung":r["beschreibung"],"datum":r["faellig_am"],
|
||||
"prioritaet":r["prioritaet"],"patient_id":r["patient_id"],
|
||||
"patient_name":r["pname"],"ueberfaellig":r["faellig_am"]<today_str})
|
||||
|
||||
# Widerspruchsfristen
|
||||
for r in db.execute("""
|
||||
for r in db.execute(f"""
|
||||
SELECT a.id, a.widerspruch_frist, a.patient_id,
|
||||
p.vorname||' '||p.nachname AS pname
|
||||
FROM antraege a LEFT JOIN patienten p ON a.patient_id=p.id
|
||||
WHERE a.widerspruch_frist IS NOT NULL AND a.widerspruch_frist != ''
|
||||
AND a.status='abgelehnt'
|
||||
AND a.status='abgelehnt'{scope}
|
||||
ORDER BY a.widerspruch_frist
|
||||
""").fetchall():
|
||||
""", scope_params).fetchall():
|
||||
events.append({"typ":"widerspruch_frist","id":r["id"],
|
||||
"titel":"⚖ Widerspruchsfrist läuft ab",
|
||||
"beschreibung":"Widerspruch gem. § 84 SGG einreichen",
|
||||
@@ -867,13 +945,13 @@ def api_kalender():
|
||||
"ueberfaellig":r["widerspruch_frist"]<today_str})
|
||||
|
||||
# MDK-Gutachter-Termine
|
||||
for r in db.execute("""
|
||||
for r in db.execute(f"""
|
||||
SELECT a.id, a.gutachter_termin, a.patient_id,
|
||||
p.vorname||' '||p.nachname AS pname
|
||||
FROM antraege a LEFT JOIN patienten p ON a.patient_id=p.id
|
||||
WHERE a.gutachter_termin IS NOT NULL AND a.gutachter_termin != ''
|
||||
WHERE a.gutachter_termin IS NOT NULL AND a.gutachter_termin != ''{scope}
|
||||
ORDER BY a.gutachter_termin
|
||||
""").fetchall():
|
||||
""", scope_params).fetchall():
|
||||
events.append({"typ":"gutachter","id":r["id"],
|
||||
"titel":"🩺 MDK-Begutachtung",
|
||||
"beschreibung":"Pflegetagebuch bereitlegen, Arztberichte sammeln",
|
||||
@@ -882,12 +960,13 @@ def api_kalender():
|
||||
"ueberfaellig":r["gutachter_termin"]<today_str})
|
||||
|
||||
# Archivierungsfristen (Hinweis wenn Frist < 1 Jahr)
|
||||
for r in db.execute("""
|
||||
pat_scope, pat_scope_params = _scope_sql("id")
|
||||
for r in db.execute(f"""
|
||||
SELECT id, vorname||' '||nachname AS pname, archiv_frist, patient_status
|
||||
FROM patienten
|
||||
WHERE archiv_frist IS NOT NULL AND archiv_frist != ''
|
||||
WHERE archiv_frist IS NOT NULL AND archiv_frist != ''{pat_scope}
|
||||
ORDER BY archiv_frist
|
||||
""").fetchall():
|
||||
""", pat_scope_params).fetchall():
|
||||
try:
|
||||
af = datetime.strptime(r["archiv_frist"], "%Y-%m-%d").date()
|
||||
days_left = (af - date.today()).days
|
||||
@@ -902,16 +981,17 @@ def api_kalender():
|
||||
pass
|
||||
|
||||
# Tagebuch-Erinnerung: aktive Patienten mit Pflegegrad und fehlendem heutigen Eintrag
|
||||
for r in db.execute("""
|
||||
p_scope, p_scope_params = _scope_sql("p.id")
|
||||
for r in db.execute(f"""
|
||||
SELECT p.id, p.vorname||' '||p.nachname AS pname, p.pflegegrad,
|
||||
MAX(t.datum) AS letzter_tb,
|
||||
SUM(CASE WHEN t.datum=? THEN 1 ELSE 0 END) AS heute
|
||||
FROM patienten p
|
||||
LEFT JOIN pflegetagebuch t ON t.patient_id=p.id
|
||||
WHERE p.patient_status='aktiv' AND p.pflegegrad>0
|
||||
WHERE p.patient_status='aktiv' AND p.pflegegrad>0{p_scope}
|
||||
GROUP BY p.id
|
||||
HAVING heute=0
|
||||
""", (today_str,)).fetchall():
|
||||
""", [today_str] + p_scope_params).fetchall():
|
||||
letzter = r["letzter_tb"]
|
||||
try:
|
||||
tage_seit = (date.today() - datetime.strptime(letzter, "%Y-%m-%d").date()).days if letzter else 999
|
||||
@@ -931,15 +1011,16 @@ def api_kalender():
|
||||
def api_tagebuch_reminder_status():
|
||||
db = get_db()
|
||||
today_str = date.today().isoformat()
|
||||
rows = db.execute("""
|
||||
p_scope, p_scope_params = _scope_sql("p.id")
|
||||
rows = db.execute(f"""
|
||||
SELECT p.id, p.vorname||' '||p.nachname AS name, p.pflegegrad,
|
||||
MAX(t.datum) AS letzter_eintrag,
|
||||
SUM(CASE WHEN t.datum=? THEN 1 ELSE 0 END) AS heute
|
||||
FROM patienten p
|
||||
LEFT JOIN pflegetagebuch t ON t.patient_id=p.id
|
||||
WHERE p.patient_status='aktiv' AND p.pflegegrad>0
|
||||
WHERE p.patient_status='aktiv' AND p.pflegegrad>0{p_scope}
|
||||
GROUP BY p.id
|
||||
""", (today_str,)).fetchall()
|
||||
""", [today_str] + p_scope_params).fetchall()
|
||||
return jsonify([{"id": r["id"], "name": r["name"], "pflegegrad": r["pflegegrad"],
|
||||
"letzter_eintrag": r["letzter_eintrag"], "heute": bool(r["heute"])}
|
||||
for r in rows])
|
||||
@@ -947,6 +1028,8 @@ def api_tagebuch_reminder_status():
|
||||
# ─── API: Dokumente ───────────────────────────────────────────────────────────
|
||||
@app.route("/api/patienten/<int:pid>/dokumente", methods=["GET"])
|
||||
def api_dokumente_list(pid):
|
||||
if not _get_owned_patient(pid):
|
||||
return jsonify({"error": "Nicht gefunden"}), 404
|
||||
db = get_db()
|
||||
rows = db.execute(
|
||||
"SELECT * FROM dokumente WHERE patient_id=? ORDER BY datum DESC, erstellt_am DESC",
|
||||
@@ -956,6 +1039,8 @@ def api_dokumente_list(pid):
|
||||
|
||||
@app.route("/api/patienten/<int:pid>/dokumente", methods=["POST"])
|
||||
def api_dokument_upload(pid):
|
||||
if not _get_owned_patient(pid):
|
||||
return jsonify({"error": "Nicht gefunden"}), 404
|
||||
if "datei" not in request.files:
|
||||
return jsonify({"error": "Keine Datei"}), 400
|
||||
file = request.files["datei"]
|
||||
@@ -984,7 +1069,9 @@ def api_dokument_upload(pid):
|
||||
@app.route("/api/dokumente/<int:did>", methods=["DELETE"])
|
||||
def api_dokument_delete(did):
|
||||
db = get_db()
|
||||
row = db.execute("SELECT pfad FROM dokumente WHERE id=?", (did,)).fetchone()
|
||||
row = db.execute("SELECT pfad, patient_id FROM dokumente WHERE id=?", (did,)).fetchone()
|
||||
if not row or not _get_owned_patient(row["patient_id"]):
|
||||
return jsonify({"error": "Nicht gefunden"}), 404
|
||||
if row:
|
||||
full = os.path.join(BASE_DIR, "static", row["pfad"])
|
||||
if os.path.exists(full):
|
||||
@@ -996,6 +1083,8 @@ def api_dokument_delete(did):
|
||||
# ─── API: Patient archivieren / Status setzen ─────────────────────────────────
|
||||
@app.route("/api/patienten/<int:pid>/archivieren", methods=["PATCH"])
|
||||
def api_patient_archivieren(pid):
|
||||
if not _get_owned_patient(pid):
|
||||
return jsonify({"error": "Nicht gefunden"}), 404
|
||||
db = get_db()
|
||||
d = request.json
|
||||
status = d.get("status", "archiviert")
|
||||
@@ -1021,7 +1110,7 @@ def api_patient_archivieren(pid):
|
||||
@app.route("/api/patienten/<int:pid>/akte", methods=["GET"])
|
||||
def api_akte(pid):
|
||||
db = get_db()
|
||||
p = db.execute("SELECT * FROM patienten WHERE id=?", (pid,)).fetchone()
|
||||
p = _get_owned_patient(pid)
|
||||
if not p:
|
||||
return jsonify({"error": "Nicht gefunden"}), 404
|
||||
antraege = db.execute("SELECT * FROM antraege WHERE patient_id=? ORDER BY erstellt_am DESC", (pid,)).fetchall()
|
||||
|
||||
Reference in new issue
Block a user