Z230
This commit is contained in:
@@ -1,60 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
import requests
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pymysql
|
||||
from datetime import datetime
|
||||
TOKEN_PATH = Path("token.txt")
|
||||
REQUEST_ID = "092a0c63-28be-4c6b-ab3b-204e1e2641d4"
|
||||
CLINIC_SLUG = "mudr-buzalkova"
|
||||
|
||||
# ==============================
|
||||
# ⚙️ CONFIGURATION
|
||||
# ==============================
|
||||
DB_CONFIG = {
|
||||
"host": "192.168.1.76",
|
||||
"port": 3307,
|
||||
"user": "root",
|
||||
"password": "Vlado9674+",
|
||||
"database": "medevio",
|
||||
"charset": "utf8mb4",
|
||||
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
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
REQUEST_ID = "4476f9f8-d7b7-4381-b056-a44897413bcd"
|
||||
|
||||
# ==============================
|
||||
# 🧩 READ CONVERSATION
|
||||
# ==============================
|
||||
conn = pymysql.connect(**DB_CONFIG)
|
||||
cur = conn.cursor(pymysql.cursors.DictCursor)
|
||||
|
||||
sql = """
|
||||
SELECT
|
||||
id,
|
||||
sender_name,
|
||||
text,
|
||||
created_at,
|
||||
attachment_url,
|
||||
attachment_description,
|
||||
attachment_content_type
|
||||
FROM medevio_conversation
|
||||
WHERE request_id = %s
|
||||
ORDER BY created_at ASC;
|
||||
"""
|
||||
|
||||
cur.execute(sql, (REQUEST_ID,))
|
||||
rows = cur.fetchall()
|
||||
|
||||
print(f"💬 Conversation for request {REQUEST_ID}:")
|
||||
print("─" * 100)
|
||||
variables = {
|
||||
"requestId": REQUEST_ID,
|
||||
}
|
||||
|
||||
for r in rows:
|
||||
created = r["created_at"].strftime("%Y-%m-%d %H:%M") if r["created_at"] else "unknown"
|
||||
sender = r["sender_name"] or "(unknown)"
|
||||
text = (r["text"] or "").strip().replace("\n", " ")
|
||||
headers = {
|
||||
"Authorization": f"Bearer {read_token(TOKEN_PATH)}",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
|
||||
print(f"[{created}] {sender}: {text}")
|
||||
payload = {
|
||||
"operationName": "ClinicRequestDetail_GetPatientRequest2",
|
||||
"query": GRAPHQL_QUERY,
|
||||
"variables": variables,
|
||||
}
|
||||
|
||||
if r["attachment_url"]:
|
||||
print(f" 📎 Attachment: {r['attachment_description']} ({r['attachment_content_type']})")
|
||||
print(f" URL: {r['attachment_url']}")
|
||||
print()
|
||||
|
||||
cur.close()
|
||||
conn.close()
|
||||
print("📡 Querying Medevio API...\n")
|
||||
r = requests.post("https://api.medevio.cz/graphql", json=payload, headers=headers)
|
||||
print(f"HTTP status: {r.status_code}\n")
|
||||
print(json.dumps(r.json(), indent=2, ensure_ascii=False))
|
||||
|
||||
59
10ReadPozadavky/10 ReportpozadavkyExcel.py
Normal file
59
10ReadPozadavky/10 ReportpozadavkyExcel.py
Normal file
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import pandas as pd
|
||||
import pymysql
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
# ================================
|
||||
# ⚙️ CONFIGURATION
|
||||
# ================================
|
||||
DB_CONFIG = {
|
||||
"host": "192.168.1.76",
|
||||
"port": 3307,
|
||||
"user": "root",
|
||||
"password": "Vlado9674+",
|
||||
"database": "medevio",
|
||||
"charset": "utf8mb4",
|
||||
}
|
||||
|
||||
# kam uložit výstup
|
||||
OUTPUT_DIR = r"U:\Dropbox\!!!Days\Downloads Z230"
|
||||
DAYS_BACK = 700 # posledních X dní
|
||||
|
||||
# ================================
|
||||
# 📘 SQL dotaz
|
||||
# ================================
|
||||
SQL = f"""
|
||||
SELECT
|
||||
m.id AS Message_ID,
|
||||
m.request_id AS Request_ID,
|
||||
m.created_at AS Datum_vytvoření,
|
||||
m.sender_name AS Odesílatel,
|
||||
m.text AS Text_zprávy,
|
||||
m.pacient_jmeno AS Pacient_jméno,
|
||||
m.pacient_prijmeni AS Pacient_příjmení,
|
||||
m.pacient_rodnecislo AS Rodné_číslo
|
||||
FROM medevio_messages m
|
||||
WHERE m.created_at >= NOW() - INTERVAL {DAYS_BACK} DAY
|
||||
ORDER BY m.created_at DESC;
|
||||
"""
|
||||
|
||||
# ================================
|
||||
# 🧠 MAIN
|
||||
# ================================
|
||||
def main():
|
||||
conn = pymysql.connect(**DB_CONFIG)
|
||||
df = pd.read_sql(SQL, conn)
|
||||
conn.close()
|
||||
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
output_path = f"{OUTPUT_DIR}\\Medevio_messages_report_{today}.xlsx"
|
||||
|
||||
df.to_excel(output_path, index=False)
|
||||
|
||||
print(f"✅ Export hotov: {output_path}")
|
||||
print(f"📄 Počet řádků: {len(df)}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
153
10ReadPozadavky/10 UpdateMessageswithJmeno.py
Normal file
153
10ReadPozadavky/10 UpdateMessageswithJmeno.py
Normal file
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import pymysql
|
||||
import requests
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
import time, socket
|
||||
|
||||
# ===============================
|
||||
# ⚙️ CONFIG
|
||||
# ===============================
|
||||
TOKEN_PATH = Path("token.txt")
|
||||
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,
|
||||
}
|
||||
|
||||
GRAPHQL_QUERY = r"""
|
||||
query ClinicRequestDetail_GetMessages(
|
||||
$clinicSlug: String!,
|
||||
$requestId: ID!
|
||||
) {
|
||||
clinicRequestDetail_GetPatientRequestMessages(
|
||||
clinicSlug: $clinicSlug,
|
||||
requestId: $requestId
|
||||
) {
|
||||
id
|
||||
text
|
||||
createdAt
|
||||
sender {
|
||||
id
|
||||
name
|
||||
}
|
||||
extendedPatient {
|
||||
name
|
||||
surname
|
||||
identificationNumber
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
# ===============================
|
||||
# 🔑 Token reader
|
||||
# ===============================
|
||||
def read_token(path: Path) -> str:
|
||||
tok = path.read_text(encoding="utf-8").strip()
|
||||
return tok.split(" ", 1)[1] if tok.startswith("Bearer ") else tok
|
||||
|
||||
# ===============================
|
||||
# 🕒 Helper
|
||||
# ===============================
|
||||
def to_mysql_dt(iso_str):
|
||||
if not iso_str:
|
||||
return None
|
||||
try:
|
||||
dt = datetime.fromisoformat(iso_str.replace("Z", "+00:00"))
|
||||
return dt.strftime("%Y-%m-%d %H:%M:%S")
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
# ===============================
|
||||
# 💾 Upsert
|
||||
# ===============================
|
||||
def upsert_message(conn, msg, request_id):
|
||||
s = msg.get("sender") or {}
|
||||
p = msg.get("extendedPatient") or {}
|
||||
|
||||
sql = """
|
||||
INSERT INTO medevio_messages (
|
||||
id, request_id, sender_name, sender_id, text, created_at,
|
||||
pacient_jmeno, pacient_prijmeni, pacient_rodnecislo
|
||||
) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
text=VALUES(text),
|
||||
created_at=VALUES(created_at),
|
||||
pacient_jmeno=VALUES(pacient_jmeno),
|
||||
pacient_prijmeni=VALUES(pacient_prijmeni),
|
||||
pacient_rodnecislo=VALUES(pacient_rodnecislo)
|
||||
"""
|
||||
|
||||
vals = (
|
||||
msg.get("id"),
|
||||
request_id,
|
||||
s.get("name"),
|
||||
s.get("id"),
|
||||
msg.get("text"),
|
||||
to_mysql_dt(msg.get("createdAt")),
|
||||
p.get("name"),
|
||||
p.get("surname"),
|
||||
p.get("identificationNumber"),
|
||||
)
|
||||
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(sql, vals)
|
||||
conn.commit()
|
||||
|
||||
# ===============================
|
||||
# 📡 Fetch messages for one request
|
||||
# ===============================
|
||||
def fetch_messages(headers, request_id):
|
||||
payload = {
|
||||
"operationName": "ClinicRequestDetail_GetMessages",
|
||||
"query": GRAPHQL_QUERY,
|
||||
"variables": {"clinicSlug": CLINIC_SLUG, "requestId": request_id},
|
||||
}
|
||||
r = requests.post("https://api.medevio.cz/graphql", json=payload, headers=headers)
|
||||
r.raise_for_status()
|
||||
data = r.json().get("data", {}).get("clinicRequestDetail_GetPatientRequestMessages", [])
|
||||
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)
|
||||
cur = conn.cursor()
|
||||
|
||||
# vezmeme všechny request_id z tabulky pozadavky
|
||||
cur.execute("SELECT id FROM pozadavky ORDER BY updatedAt DESC")
|
||||
request_ids = [r["id"] for r in cur.fetchall()]
|
||||
print(f"📋 Found {len(request_ids)} požadavků.")
|
||||
|
||||
for i, rid in enumerate(request_ids, 1):
|
||||
try:
|
||||
msgs = fetch_messages(headers, rid)
|
||||
for msg in msgs:
|
||||
upsert_message(conn, msg, rid)
|
||||
print(f"[{i}/{len(request_ids)}] {rid} → {len(msgs)} zpráv uloženo.")
|
||||
time.sleep(0.4)
|
||||
except Exception as e:
|
||||
print(f"❌ Chyba při načítání {rid}: {e}")
|
||||
|
||||
conn.close()
|
||||
print("\n✅ Hotovo, všechny zprávy synchronizovány.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
179
10ReadPozadavky/10 test2.py
Normal file
179
10ReadPozadavky/10 test2.py
Normal file
@@ -0,0 +1,179 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import pymysql
|
||||
import requests
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
import time
|
||||
|
||||
# ================================
|
||||
# ⚙️ CONFIGURATION
|
||||
# ================================
|
||||
TOKEN_PATH = Path("token.txt")
|
||||
CLINIC_SLUG = "mudr-buzalkova"
|
||||
BATCH_SIZE = 100
|
||||
|
||||
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 ClinicRequestGrid_ListPatientRequestsForClinic2(
|
||||
$clinicSlug: String!,
|
||||
$queueId: String,
|
||||
$queueAssignment: QueueAssignmentFilter!,
|
||||
$pageInfo: PageInfo!,
|
||||
$locale: Locale!,
|
||||
$state: PatientRequestState
|
||||
) {
|
||||
requestsResponse: listPatientRequestsForClinic2(
|
||||
clinicSlug: $clinicSlug,
|
||||
queueId: $queueId,
|
||||
queueAssignment: $queueAssignment,
|
||||
pageInfo: $pageInfo,
|
||||
state: $state
|
||||
) {
|
||||
count
|
||||
patientRequests {
|
||||
id
|
||||
displayTitle(locale: $locale)
|
||||
createdAt
|
||||
updatedAt
|
||||
doneAt
|
||||
removedAt
|
||||
extendedPatient {
|
||||
name
|
||||
surname
|
||||
identificationNumber
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
# ================================
|
||||
# 🔑 TOKEN
|
||||
# ================================
|
||||
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 FUNCTION
|
||||
# ================================
|
||||
def fetch_requests(headers, state, offset=0):
|
||||
"""Fetch a batch of patient requests for a given state."""
|
||||
variables = {
|
||||
"clinicSlug": CLINIC_SLUG,
|
||||
"queueId": None,
|
||||
"queueAssignment": "ANY",
|
||||
"pageInfo": {"first": BATCH_SIZE, "offset": offset},
|
||||
"locale": "cs",
|
||||
"state": state,
|
||||
}
|
||||
payload = {
|
||||
"operationName": "ClinicRequestGrid_ListPatientRequestsForClinic2",
|
||||
"query": GRAPHQL_QUERY,
|
||||
"variables": variables,
|
||||
}
|
||||
|
||||
for attempt in range(3): # up to 3 attempts
|
||||
try:
|
||||
r = requests.post("https://api.medevio.cz/graphql", json=payload, headers=headers, timeout=30)
|
||||
r.raise_for_status()
|
||||
resp = r.json().get("data", {}).get("requestsResponse", {})
|
||||
return resp.get("patientRequests", []), resp.get("count", 0)
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"⚠️ Chyba při načítání (pokus {attempt+1}/3): {e}")
|
||||
time.sleep(5)
|
||||
return [], 0
|
||||
|
||||
# ================================
|
||||
# 💾 UPDATE ALL MESSAGES BY PATIENT DATA
|
||||
# ================================
|
||||
def update_all_messages(conn, patient):
|
||||
"""Update all messages belonging to this request with patient data."""
|
||||
p = patient.get("extendedPatient") or {}
|
||||
if not p:
|
||||
return 0
|
||||
|
||||
sql = """
|
||||
UPDATE medevio_messages
|
||||
SET pacient_jmeno=%s,
|
||||
pacient_prijmeni=%s,
|
||||
pacient_rodnecislo=%s
|
||||
WHERE request_id=%s
|
||||
"""
|
||||
vals = (p.get("name"), p.get("surname"), p.get("identificationNumber"), patient.get("id"))
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(sql, vals)
|
||||
affected = cur.rowcount
|
||||
conn.commit()
|
||||
return affected
|
||||
|
||||
# ================================
|
||||
# 🧠 MAIN
|
||||
# ================================
|
||||
def process_state(conn, headers, state):
|
||||
print(f"\n=== 🟦 Zpracovávám {state} požadavky ===")
|
||||
offset = 0
|
||||
total_processed = 0
|
||||
total_updated = 0
|
||||
|
||||
while True:
|
||||
batch, total_count = fetch_requests(headers, state, offset)
|
||||
if not batch:
|
||||
break
|
||||
|
||||
print(f"📦 Dávka od offsetu {offset} ({len(batch)} záznamů z {total_count})")
|
||||
for r in batch:
|
||||
updated = update_all_messages(conn, r)
|
||||
total_processed += 1
|
||||
total_updated += updated
|
||||
if updated:
|
||||
print(f" ↳ {r.get('id')} → {updated} zpráv aktualizováno")
|
||||
|
||||
offset += BATCH_SIZE
|
||||
if offset >= total_count:
|
||||
break
|
||||
|
||||
time.sleep(0.4)
|
||||
|
||||
print(f"✅ {state}: zpracováno {total_processed} požadavků, aktualizováno {total_updated} zpráv.")
|
||||
return total_processed, total_updated
|
||||
|
||||
# ================================
|
||||
# 🚀 ENTRY POINT
|
||||
# ================================
|
||||
def main():
|
||||
token = read_token(TOKEN_PATH)
|
||||
headers = {
|
||||
"Authorization": f"Bearer {token}",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
|
||||
conn = pymysql.connect(**DB_CONFIG)
|
||||
|
||||
print(f"\n=== Medevio mass patient sync @ {datetime.now():%Y-%m-%d %H:%M:%S} ===")
|
||||
|
||||
total_p, total_u = process_state(conn, headers, "ACTIVE")
|
||||
done_p, done_u = process_state(conn, headers, "DONE")
|
||||
|
||||
conn.close()
|
||||
|
||||
print("\n=== 🧾 SOUHRN ===")
|
||||
print(f"ACTIVE: {total_p} požadavků, {total_u} zpráv aktualizováno")
|
||||
print(f"DONE: {done_p} požadavků, {done_u} zpráv aktualizováno")
|
||||
print("===========================================")
|
||||
print(f"CELKEM: {total_p + done_p} požadavků, {total_u + done_u} zpráv aktualizováno ✅")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
296
10ReadPozadavky/PRAVIDELNE_StahniKomunikaci.py
Normal file
296
10ReadPozadavky/PRAVIDELNE_StahniKomunikaci.py
Normal file
@@ -0,0 +1,296 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
Read conversation messages for pozadavky where messagesProcessed IS NULL
|
||||
(Optionally filtered by createdAt), insert them into `medevio_conversation`,
|
||||
and if a message has an attachment (medicalRecord), download it and save into
|
||||
`medevio_downloads` (same logic as your attachments script).
|
||||
Finally, mark pozadavky.messagesProcessed = NOW().
|
||||
"""
|
||||
|
||||
import zlib
|
||||
import json
|
||||
import requests
|
||||
import pymysql
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
import time
|
||||
|
||||
# ==============================
|
||||
# 🔧 CONFIGURATION
|
||||
# ==============================
|
||||
TOKEN_PATH = Path("token.txt")
|
||||
DB_CONFIG = {
|
||||
"host": "192.168.1.76",
|
||||
"port": 3307,
|
||||
"user": "root",
|
||||
"password": "Vlado9674+",
|
||||
"database": "medevio",
|
||||
"charset": "utf8mb4",
|
||||
"cursorclass": pymysql.cursors.DictCursor,
|
||||
}
|
||||
|
||||
# ✅ Optional: Only process requests created after this date ("" = no limit)
|
||||
CREATED_AFTER = "2024-01-01"
|
||||
|
||||
GRAPHQL_QUERY_MESSAGES = r"""
|
||||
query UseMessages_ListMessages($requestId: String!, $updatedSince: DateTime) {
|
||||
messages: listMessages(patientRequestId: $requestId, updatedSince: $updatedSince) {
|
||||
id
|
||||
createdAt
|
||||
updatedAt
|
||||
readAt
|
||||
text
|
||||
type
|
||||
sender {
|
||||
id
|
||||
name
|
||||
surname
|
||||
clinicId
|
||||
}
|
||||
medicalRecord {
|
||||
id
|
||||
description
|
||||
contentType
|
||||
url
|
||||
downloadUrl
|
||||
token
|
||||
createdAt
|
||||
updatedAt
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
# ==============================
|
||||
# 🧮 HELPERS
|
||||
# ==============================
|
||||
def short_crc8(uuid_str: str) -> str:
|
||||
return f"{zlib.crc32(uuid_str.encode('utf-8')) & 0xffffffff:08x}"
|
||||
|
||||
def extract_filename_from_url(url: str) -> str:
|
||||
try:
|
||||
return url.split("/")[-1].split("?")[0]
|
||||
except Exception:
|
||||
return "unknown_filename"
|
||||
|
||||
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
|
||||
|
||||
def parse_dt(s):
|
||||
if not s:
|
||||
return None
|
||||
# handle both "YYYY-mm-ddTHH:MM:SS" and "YYYY-mm-dd HH:MM:SS"
|
||||
s = s.replace("T", " ")
|
||||
fmts = ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M")
|
||||
for f in fmts:
|
||||
try:
|
||||
return datetime.strptime(s[:19], f)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
# ==============================
|
||||
# 📡 FETCH MESSAGES
|
||||
# ==============================
|
||||
def fetch_messages(headers, request_id):
|
||||
variables = {"requestId": request_id, "updatedSince": None}
|
||||
payload = {
|
||||
"operationName": "UseMessages_ListMessages",
|
||||
"query": GRAPHQL_QUERY_MESSAGES,
|
||||
"variables": variables,
|
||||
}
|
||||
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 messages of request {request_id}")
|
||||
return []
|
||||
data = r.json().get("data", {}).get("messages", [])
|
||||
return data or []
|
||||
|
||||
# ==============================
|
||||
# 💾 SAVE: conversation row
|
||||
# ==============================
|
||||
def insert_message(cur, req_id, msg):
|
||||
sender = msg.get("sender") or {}
|
||||
sender_name = " ".join(x for x in [sender.get("name"), sender.get("surname")] if x).strip() or None
|
||||
sender_id = sender.get("id")
|
||||
sender_clinic_id = sender.get("clinicId")
|
||||
|
||||
text = msg.get("text")
|
||||
created_at = parse_dt(msg.get("createdAt"))
|
||||
read_at = parse_dt(msg.get("readAt"))
|
||||
updated_at = parse_dt(msg.get("updatedAt"))
|
||||
|
||||
mr = msg.get("medicalRecord") or {}
|
||||
attachment_url = mr.get("downloadUrl") or mr.get("url")
|
||||
attachment_description = mr.get("description")
|
||||
attachment_content_type = mr.get("contentType")
|
||||
|
||||
sql = """
|
||||
INSERT INTO medevio_conversation (
|
||||
id, request_id, sender_name, sender_id, sender_clinic_id,
|
||||
text, created_at, read_at, updated_at,
|
||||
attachment_url, attachment_description, attachment_content_type
|
||||
) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
sender_name = VALUES(sender_name),
|
||||
sender_id = VALUES(sender_id),
|
||||
sender_clinic_id = VALUES(sender_clinic_id),
|
||||
text = VALUES(text),
|
||||
created_at = VALUES(created_at),
|
||||
read_at = VALUES(read_at),
|
||||
updated_at = VALUES(updated_at),
|
||||
attachment_url = VALUES(attachment_url),
|
||||
attachment_description = VALUES(attachment_description),
|
||||
attachment_content_type = VALUES(attachment_content_type)
|
||||
"""
|
||||
cur.execute(sql, (
|
||||
msg.get("id"),
|
||||
req_id,
|
||||
sender_name,
|
||||
sender_id,
|
||||
sender_clinic_id,
|
||||
text,
|
||||
created_at,
|
||||
read_at,
|
||||
updated_at,
|
||||
attachment_url,
|
||||
attachment_description,
|
||||
attachment_content_type
|
||||
))
|
||||
|
||||
# ==============================
|
||||
# 💾 SAVE: download attachment (from message)
|
||||
# ==============================
|
||||
def insert_download_from_message(cur, req_id, msg, existing_ids):
|
||||
mr = msg.get("medicalRecord") or {}
|
||||
attachment_id = mr.get("id")
|
||||
if not attachment_id:
|
||||
return False
|
||||
if attachment_id in existing_ids:
|
||||
print(f" ⏭️ Skipping already downloaded message-attachment {attachment_id}")
|
||||
return False
|
||||
|
||||
url = mr.get("downloadUrl") or mr.get("url")
|
||||
if not url:
|
||||
return False
|
||||
|
||||
try:
|
||||
r = requests.get(url, timeout=30)
|
||||
r.raise_for_status()
|
||||
content = r.content
|
||||
except Exception as e:
|
||||
print(f" ⚠️ Failed to download message attachment {attachment_id}: {e}")
|
||||
return False
|
||||
|
||||
filename = extract_filename_from_url(url)
|
||||
content_type = mr.get("contentType")
|
||||
file_size = len(content)
|
||||
created_date = parse_dt(msg.get("createdAt"))
|
||||
|
||||
# We don't have patient names on the message level here; keep NULLs.
|
||||
cur.execute("""
|
||||
INSERT INTO medevio_downloads (
|
||||
request_id, attachment_id, attachment_type, filename,
|
||||
content_type, file_size, pacient_jmeno, pacient_prijmeni,
|
||||
created_at, file_content
|
||||
) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
file_content = VALUES(file_content),
|
||||
file_size = VALUES(file_size),
|
||||
downloaded_at = NOW()
|
||||
""", (
|
||||
req_id,
|
||||
attachment_id,
|
||||
"MESSAGE_ATTACHMENT",
|
||||
filename,
|
||||
content_type,
|
||||
file_size,
|
||||
None,
|
||||
None,
|
||||
created_date,
|
||||
content
|
||||
))
|
||||
existing_ids.add(attachment_id)
|
||||
print(f" 💾 Saved msg attachment {filename} ({file_size/1024:.1f} kB)")
|
||||
return True
|
||||
|
||||
# ==============================
|
||||
# 🧠 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)
|
||||
|
||||
# Load existing download IDs to skip duplicates (same logic as your script)
|
||||
print("📦 Loading list of already downloaded 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"✅ Found {len(existing_ids)} attachments already saved.")
|
||||
|
||||
# Pull pozadavky where messagesProcessed IS NULL (optionally by createdAt)
|
||||
sql = """
|
||||
SELECT id, displayTitle, pacient_prijmeni, pacient_jmeno, createdAt
|
||||
FROM pozadavky
|
||||
WHERE messagesProcessed IS NULL
|
||||
"""
|
||||
params = []
|
||||
if CREATED_AFTER:
|
||||
sql += " AND createdAt >= %s"
|
||||
params.append(CREATED_AFTER)
|
||||
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(sql, params)
|
||||
rows = cur.fetchall()
|
||||
|
||||
print(f"📋 Found {len(rows)} pozadavky to process (messagesProcessed IS NULL"
|
||||
+ (f", created >= {CREATED_AFTER}" if CREATED_AFTER else "") + ")")
|
||||
|
||||
for i, row in enumerate(rows, 1):
|
||||
req_id = row["id"]
|
||||
prijmeni = row.get("pacient_prijmeni") or "Neznamy"
|
||||
jmeno = row.get("pacient_jmeno") or ""
|
||||
print(f"\n[{i}/{len(rows)}] 💬 {prijmeni}, {jmeno} ({req_id})")
|
||||
|
||||
messages = fetch_messages(headers, req_id)
|
||||
if not messages:
|
||||
print(" ⚠️ No messages found")
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("UPDATE pozadavky SET messagesProcessed = NOW() WHERE id = %s", (req_id,))
|
||||
conn.commit()
|
||||
continue
|
||||
|
||||
inserted = 0
|
||||
with conn.cursor() as cur:
|
||||
for msg in messages:
|
||||
insert_message(cur, req_id, msg)
|
||||
# also pull any message attachments into downloads table
|
||||
insert_download_from_message(cur, req_id, msg, existing_ids)
|
||||
inserted += 1
|
||||
conn.commit()
|
||||
|
||||
# mark processed
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("UPDATE pozadavky SET messagesProcessed = NOW() WHERE id = %s", (req_id,))
|
||||
conn.commit()
|
||||
|
||||
print(f" ✅ {inserted} messages processed for {prijmeni}, {jmeno}")
|
||||
time.sleep(0.3) # polite API delay
|
||||
|
||||
conn.close()
|
||||
print("\n✅ Done! All new conversations processed and pozadavky updated.")
|
||||
|
||||
# ==============================
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -22,7 +22,7 @@ TOKEN_PATH = Path("token.txt")
|
||||
CLINIC_SLUG = "mudr-buzalkova"
|
||||
|
||||
DB_CONFIG = {
|
||||
"host": "127.0.0.1",
|
||||
"host": "192.168.1.76",
|
||||
"port": 3307,
|
||||
"user": "root",
|
||||
"password": "Vlado9674+",
|
||||
|
||||
@@ -32,7 +32,7 @@ DB_CONFIG = {
|
||||
}
|
||||
|
||||
# ✅ Optional: Only process requests created after this date ("" = no limit)
|
||||
CREATED_AFTER = "2025-1-01"
|
||||
CREATED_AFTER = "2024-01-01"
|
||||
|
||||
GRAPHQL_QUERY_MESSAGES = r"""
|
||||
query UseMessages_ListMessages($requestId: String!, $updatedSince: DateTime) {
|
||||
|
||||
1
Testy/token.txt
Normal file
1
Testy/token.txt
Normal file
@@ -0,0 +1 @@
|
||||
nYvrvgflIKcDiQg8Hhpud+qG8iGZ8eH8su4nyT/Mgcm7XQp65ygY9s39+O01wIpk/7sKd6fBHkiKvsqH
|
||||
Reference in New Issue
Block a user