156 lines
4.4 KiB
Python
156 lines
4.4 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
|
|
import os
|
|
import json
|
|
import requests
|
|
import pymysql
|
|
from pathlib import Path
|
|
from datetime import datetime
|
|
|
|
# ==============================
|
|
# 🔧 CONFIGURATION
|
|
# ==============================
|
|
TOKEN_PATH = Path("token.txt")
|
|
CLINIC_SLUG = "mudr-buzalkova"
|
|
BASE_DIR = Path(r"d:\Dropbox\ordinace\Dokumentace_ke_zpracování\Medevio_přílohy")
|
|
BASE_DIR.mkdir(parents=True, exist_ok=True)
|
|
|
|
DB_CONFIG = {
|
|
"host": "192.168.1.76",
|
|
"port": 3307,
|
|
"user": "root",
|
|
"password": "Vlado9674+",
|
|
"database": "medevio",
|
|
"charset": "utf8mb4",
|
|
"cursorclass": pymysql.cursors.DictCursor,
|
|
}
|
|
|
|
GRAPHQL_QUERY = r"""
|
|
query ClinicRequestDetail_GetPatientRequest2(
|
|
$requestId: UUID!,
|
|
) {
|
|
patientRequestMedicalRecords: listMedicalRecordsForPatientRequest(
|
|
attachmentTypes: [ECRF_FILL_ATTACHMENT, MESSAGE_ATTACHMENT, PATIENT_REQUEST_ATTACHMENT]
|
|
patientRequestId: $requestId
|
|
pageInfo: {first: 100, offset: 0}
|
|
) {
|
|
attachmentType
|
|
id
|
|
medicalRecord {
|
|
contentType
|
|
description
|
|
downloadUrl
|
|
id
|
|
url
|
|
visibleToPatient
|
|
}
|
|
}
|
|
}
|
|
"""
|
|
|
|
# ==============================
|
|
# 🔑 TOKEN
|
|
# ==============================
|
|
def read_token(p: Path) -> str:
|
|
tok = p.read_text(encoding="utf-8").strip()
|
|
if tok.startswith("Bearer "):
|
|
tok = tok.split(" ", 1)[1]
|
|
return tok
|
|
|
|
# ==============================
|
|
# 💾 DOWNLOAD FILE
|
|
# ==============================
|
|
def download_file(url: str, out_path: Path):
|
|
try:
|
|
r = requests.get(url, timeout=30)
|
|
r.raise_for_status()
|
|
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
with open(out_path, "wb") as f:
|
|
f.write(r.content)
|
|
print(f" 💾 Saved: {out_path.relative_to(BASE_DIR)}")
|
|
except Exception as e:
|
|
print(f" ⚠️ Failed to download {out_path.name}: {e}")
|
|
|
|
# ==============================
|
|
# 📡 FETCH ATTACHMENTS
|
|
# ==============================
|
|
def fetch_attachments(headers, request_id):
|
|
variables = {
|
|
"requestId": request_id,
|
|
}
|
|
payload = {
|
|
"operationName": "ClinicRequestDetail_GetPatientRequest2",
|
|
"query": GRAPHQL_QUERY,
|
|
"variables": variables,
|
|
}
|
|
r = requests.post("https://api.medevio.cz/graphql", json=payload, headers=headers)
|
|
if r.status_code != 200:
|
|
print(f"❌ HTTP {r.status_code}")
|
|
return []
|
|
data = r.json().get("data", {}).get("patientRequestMedicalRecords", [])
|
|
return data
|
|
|
|
# ==============================
|
|
# 🧠 MAIN
|
|
# ==============================
|
|
def main():
|
|
token = read_token(TOKEN_PATH)
|
|
headers = {
|
|
"Authorization": f"Bearer {token}",
|
|
"Content-Type": "application/json",
|
|
"Accept": "application/json",
|
|
}
|
|
|
|
conn = pymysql.connect(**DB_CONFIG)
|
|
with conn.cursor() as cur:
|
|
cur.execute("""
|
|
SELECT id, displayTitle, pacient_prijmeni, pacient_jmeno, createdAt
|
|
FROM pozadavky
|
|
WHERE displayTitle = 'Odeslat lékařskou zprávu'
|
|
""")
|
|
rows = cur.fetchall()
|
|
|
|
print(f"📋 Found {len(rows)} 'Odeslat lékařskou zprávu' requests")
|
|
|
|
for i, row in enumerate(rows, 1):
|
|
req_id = row["id"]
|
|
prijmeni = row.get("pacient_prijmeni") or "Neznamy"
|
|
jmeno = row.get("pacient_jmeno") or ""
|
|
created = row.get("createdAt")
|
|
created_date = None
|
|
if created:
|
|
try:
|
|
created_date = datetime.strptime(str(created), "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d")
|
|
except Exception:
|
|
created_date = "unknown"
|
|
|
|
patient_dir = BASE_DIR / f"{prijmeni}, {jmeno}" / created_date
|
|
print(f"\n[{i}/{len(rows)}] 📂 {patient_dir.relative_to(BASE_DIR)}")
|
|
|
|
attachments = fetch_attachments(headers, req_id)
|
|
|
|
|
|
if not attachments:
|
|
print(" ⚠️ No attachments")
|
|
attachmentspocet = " (0)"
|
|
continue
|
|
else:
|
|
attachmentspocet = " ("+str(len(attachments))+")"
|
|
|
|
patient_dir=patient_dir+attachmentspocet
|
|
|
|
for a in attachments:
|
|
m = a.get("medicalRecord") or {}
|
|
fname = m.get("description") or f"{m.get('id')}.bin"
|
|
url = m.get("downloadUrl")
|
|
if url:
|
|
out_path = patient_dir / fname
|
|
download_file(url, out_path)
|
|
|
|
conn.close()
|
|
print("\n✅ Done!")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|