184 lines
4.7 KiB
Python
184 lines
4.7 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
|
||
import json
|
||
import time
|
||
import random
|
||
import requests
|
||
import pymysql
|
||
from pathlib import Path
|
||
|
||
from datetime import datetime
|
||
|
||
# Patients with details_updated_at older than this date will be refreshed
|
||
# UpdateOlderThan = datetime(2025, 2, 20) # example date
|
||
UpdateOlderThan = None #když chceš všechny aktualizovat
|
||
|
||
TOKEN_PATH = Path("token.txt")
|
||
GRAPHQL_URL = "https://api.medevio.cz/graphql"
|
||
CLINIC_SLUG = "mudr-buzalkova"
|
||
|
||
DB_CONFIG = {
|
||
"host": "192.168.1.76",
|
||
"port": 3307,
|
||
"user": "root",
|
||
"password": "Vlado9674+",
|
||
"database": "medevio",
|
||
"charset": "utf8mb4",
|
||
"cursorclass": pymysql.cursors.DictCursor,
|
||
}
|
||
|
||
def normalize_dt(dt_str):
|
||
if not dt_str:
|
||
return None
|
||
dt_str = dt_str.replace("Z", "").replace("T", " ")
|
||
if "." in dt_str:
|
||
dt_str = dt_str.split(".")[0]
|
||
return dt_str
|
||
|
||
def save_patient_detail(cur, p):
|
||
user = p.get("user") or {}
|
||
ins = p.get("insuranceCompanyObject") or {}
|
||
tags = p.get("tags") or []
|
||
clinics = p.get("clinics") or []
|
||
|
||
sql = """
|
||
UPDATE medevio_pacienti SET
|
||
email = %s,
|
||
telefon = %s,
|
||
dob = %s,
|
||
street = %s,
|
||
house_number = %s,
|
||
city = %s,
|
||
|
||
user_id = %s,
|
||
user_email = %s,
|
||
user_name = %s,
|
||
user_surname = %s,
|
||
user_phone = %s,
|
||
user_reg_time = %s,
|
||
user_deactivated_time = %s,
|
||
|
||
created_at = %s,
|
||
note = %s,
|
||
has_mobile_app = %s,
|
||
user_relationship = %s,
|
||
|
||
pojistovna_code = %s,
|
||
tags_json = %s,
|
||
clinics_json = %s,
|
||
last_update = NOW(),
|
||
details_updated_at = NOW()
|
||
|
||
WHERE id = %s
|
||
"""
|
||
|
||
cur.execute(sql, (
|
||
p.get("email"),
|
||
p.get("phone"),
|
||
p.get("dob"),
|
||
|
||
p.get("street"),
|
||
p.get("houseNumber"),
|
||
p.get("city"),
|
||
|
||
user.get("id"),
|
||
user.get("email"),
|
||
user.get("name"),
|
||
user.get("surname"),
|
||
user.get("phone"),
|
||
normalize_dt(user.get("registrationCompletedTime")),
|
||
normalize_dt(user.get("deactivatedTime")),
|
||
|
||
normalize_dt(p.get("createdAt")),
|
||
p.get("note"),
|
||
1 if p.get("hasMobileApp") else 0,
|
||
p.get("userRelationship"),
|
||
|
||
ins.get("code"),
|
||
json.dumps(tags, ensure_ascii=False),
|
||
json.dumps(clinics, ensure_ascii=False),
|
||
|
||
p.get("id")
|
||
))
|
||
|
||
# === PLACEHOLDER: Insert your full GraphQL query here ===
|
||
QUERY = Path("patient_detail.graphql").read_text(encoding="utf-8")
|
||
|
||
def main():
|
||
token = TOKEN_PATH.read_text().strip()
|
||
|
||
headers = {
|
||
"Authorization": f"Bearer {token}",
|
||
"Content-Type": "application/json",
|
||
"Accept": "application/json",
|
||
}
|
||
|
||
conn = pymysql.connect(**DB_CONFIG)
|
||
cur = conn.cursor()
|
||
|
||
if UpdateOlderThan:
|
||
print(f"🔎 Updating patients with details_updated_at NULL or < {UpdateOlderThan}")
|
||
cur.execute("""
|
||
SELECT id, prijmeni, jmeno, details_updated_at
|
||
FROM medevio_pacienti
|
||
WHERE details_updated_at IS NULL OR details_updated_at < %s
|
||
ORDER BY prijmeni, jmeno
|
||
""", (UpdateOlderThan,))
|
||
else:
|
||
print("🔎 Updating only patients with details_updated_at NULL")
|
||
cur.execute("""
|
||
SELECT id, prijmeni, jmeno, details_updated_at
|
||
FROM medevio_pacienti
|
||
WHERE details_updated_at IS NULL
|
||
ORDER BY prijmeni, jmeno
|
||
""")
|
||
patients = cur.fetchall()
|
||
|
||
total = len(patients)
|
||
print(f"⏳ Starting full patient detail sync for {total} patients...")
|
||
|
||
for idx, row in enumerate(patients, start=1):
|
||
pid = row["id"]
|
||
name = f"{row.get('prijmeni','')}, {row.get('jmeno','')}"
|
||
print(f"[{idx}/{total}] Updating: {name} ({pid})")
|
||
|
||
variables = {
|
||
"clinicSlug": CLINIC_SLUG,
|
||
"patientId": pid,
|
||
"patientUuid": pid,
|
||
"challengesStatus": "SENT",
|
||
"locale": "cs",
|
||
}
|
||
|
||
try:
|
||
r = requests.post(
|
||
GRAPHQL_URL,
|
||
json={"query": QUERY, "variables": variables},
|
||
headers=headers,
|
||
timeout=30
|
||
)
|
||
r.raise_for_status()
|
||
js = r.json()
|
||
|
||
p = js["data"]["patient"]
|
||
if p:
|
||
save_patient_detail(cur, p)
|
||
conn.commit()
|
||
print(" ✔ saved")
|
||
else:
|
||
print(" ⚠ no patient data returned")
|
||
|
||
except Exception as e:
|
||
print(f" ❌ ERROR: {e}")
|
||
time.sleep(2)
|
||
continue
|
||
|
||
time.sleep(random.uniform(0.5, 1.5))
|
||
|
||
conn.close()
|
||
print("✅ DONE – full detail sync completed.")
|
||
|
||
if __name__ == "__main__":
|
||
main()
|