reporter
This commit is contained in:
@@ -14,6 +14,36 @@ import pymysql
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
import time
|
||||
import sys
|
||||
|
||||
# Force UTF-8 output even under Windows Task Scheduler
|
||||
import sys
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding='utf-8')
|
||||
sys.stderr.reconfigure(encoding='utf-8')
|
||||
except AttributeError:
|
||||
# Python < 3.7 fallback (not needed for you, but safe)
|
||||
import io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
|
||||
|
||||
|
||||
# ==============================
|
||||
# 🛡 SAFE PRINT FOR CP1250 / EMOJI
|
||||
# ==============================
|
||||
def safe_print(text: str):
|
||||
enc = sys.stdout.encoding or ""
|
||||
if not enc or not enc.lower().startswith("utf"):
|
||||
# strip emoji + characters outside BMP
|
||||
text = ''.join(ch for ch in text if ord(ch) < 65536)
|
||||
|
||||
try:
|
||||
print(text)
|
||||
except UnicodeEncodeError:
|
||||
# ASCII fallback
|
||||
text = ''.join(ch for ch in text if ord(ch) < 128)
|
||||
print(text)
|
||||
|
||||
|
||||
# ==============================
|
||||
# 🔧 CONFIGURATION
|
||||
@@ -67,6 +97,7 @@ def read_token(p: Path) -> str:
|
||||
tok = p.read_text(encoding="utf-8").strip()
|
||||
return tok.split(" ", 1)[1] if tok.startswith("Bearer ") else tok
|
||||
|
||||
|
||||
# ==============================
|
||||
# 📡 FETCH ATTACHMENTS
|
||||
# ==============================
|
||||
@@ -78,42 +109,40 @@ def fetch_attachments(headers, request_id):
|
||||
}
|
||||
r = requests.post("https://api.medevio.cz/graphql", json=payload, headers=headers, timeout=30)
|
||||
if r.status_code != 200:
|
||||
print(f"❌ HTTP {r.status_code} for request {request_id}")
|
||||
safe_print(f"❌ HTTP {r.status_code} for request {request_id}")
|
||||
return []
|
||||
return r.json().get("data", {}).get("patientRequestMedicalRecords", [])
|
||||
|
||||
|
||||
# ==============================
|
||||
# 💾 SAVE TO MYSQL (clean version)
|
||||
# 💾 SAVE TO MYSQL
|
||||
# ==============================
|
||||
def insert_download(cur, req_id, a, m, created_date, existing_ids):
|
||||
|
||||
attachment_id = a.get("id")
|
||||
if attachment_id in existing_ids:
|
||||
print(f" ⏭️ Already downloaded {attachment_id}")
|
||||
safe_print(f" ⏭️ Already downloaded {attachment_id}")
|
||||
return False
|
||||
|
||||
url = m.get("downloadUrl")
|
||||
if not url:
|
||||
print(" ⚠️ Missing download URL")
|
||||
safe_print(" ⚠️ Missing download URL")
|
||||
return False
|
||||
|
||||
filename = extract_filename_from_url(url)
|
||||
|
||||
# Download file
|
||||
try:
|
||||
r = requests.get(url, timeout=30)
|
||||
r.raise_for_status()
|
||||
content = r.content
|
||||
except Exception as e:
|
||||
print(f" ⚠️ Download failed {url}: {e}")
|
||||
safe_print(f" ⚠️ Download failed {url}: {e}")
|
||||
return False
|
||||
|
||||
file_size = len(content)
|
||||
attachment_type = a.get("attachmentType")
|
||||
content_type = m.get("contentType")
|
||||
|
||||
# 🚨 CLEAN INSERT — no patient_jmeno/no patient_prijmeni
|
||||
cur.execute("""
|
||||
INSERT INTO medevio_downloads (
|
||||
request_id, attachment_id, attachment_type,
|
||||
@@ -136,7 +165,7 @@ def insert_download(cur, req_id, a, m, created_date, existing_ids):
|
||||
))
|
||||
|
||||
existing_ids.add(attachment_id)
|
||||
print(f" 💾 Saved {filename} ({file_size/1024:.1f} kB)")
|
||||
safe_print(f" 💾 Saved {filename} ({file_size/1024:.1f} kB)")
|
||||
return True
|
||||
|
||||
|
||||
@@ -152,11 +181,12 @@ def main():
|
||||
|
||||
conn = pymysql.connect(**DB_CONFIG)
|
||||
|
||||
# Load existing IDs
|
||||
# Load existing attachments
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT attachment_id FROM medevio_downloads")
|
||||
existing_ids = {row["attachment_id"] for row in cur.fetchall()}
|
||||
print(f"✅ {len(existing_ids)} attachments already saved.")
|
||||
|
||||
safe_print(f"✅ {len(existing_ids)} attachments already saved.")
|
||||
|
||||
# Build query for pozadavky
|
||||
sql = """
|
||||
@@ -173,7 +203,7 @@ def main():
|
||||
cur.execute(sql, params)
|
||||
req_rows = cur.fetchall()
|
||||
|
||||
print(f"📋 Found {len(req_rows)} pozadavky to process.")
|
||||
safe_print(f"📋 Found {len(req_rows)} pozadavky to process.")
|
||||
|
||||
# Process each pozadavek
|
||||
for i, row in enumerate(req_rows, 1):
|
||||
@@ -182,12 +212,12 @@ def main():
|
||||
jmeno = row.get("pacient_jmeno") or ""
|
||||
created_date = row.get("createdAt") or datetime.now()
|
||||
|
||||
print(f"\n[{i}/{len(req_rows)}] 🧾 {prijmeni}, {jmeno} ({req_id})")
|
||||
safe_print(f"\n[{i}/{len(req_rows)}] 🧾 {prijmeni}, {jmeno} ({req_id})")
|
||||
|
||||
attachments = fetch_attachments(headers, req_id)
|
||||
|
||||
if not attachments:
|
||||
print(" ⚠️ No attachments found")
|
||||
safe_print(" ⚠️ No attachments found")
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("UPDATE pozadavky SET attachmentsProcessed = NOW() WHERE id = %s", (req_id,))
|
||||
conn.commit()
|
||||
@@ -199,17 +229,16 @@ def main():
|
||||
insert_download(cur, req_id, a, m, created_date, existing_ids)
|
||||
conn.commit()
|
||||
|
||||
# Mark processed
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("UPDATE pozadavky SET attachmentsProcessed = NOW() WHERE id = %s", (req_id,))
|
||||
conn.commit()
|
||||
|
||||
print(f" ✅ Done ({len(attachments)} attachments)")
|
||||
|
||||
safe_print(f" ✅ Done ({len(attachments)} attachments)")
|
||||
time.sleep(0.3)
|
||||
|
||||
conn.close()
|
||||
print("\n🎯 All attachments processed.")
|
||||
safe_print("\n🎯 All attachments processed.")
|
||||
|
||||
|
||||
# ==============================
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user