Files
reporty/Medicus report/30 MedicusReport.py
2025-11-20 12:04:47 +01:00

145 lines
3.5 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pymysql
import pandas as pd
from datetime import datetime, timedelta
from openpyxl import load_workbook
from openpyxl.styles import Font, PatternFill, Alignment
from pathlib import Path
import os
# ==============================
# ⚙️ CONFIG
# ==============================
DB_CONFIG = {
"host": "192.168.1.76",
"port": 3307,
"user": "root",
"password": "Vlado9674+",
"database": "medevio",
"charset": "utf8mb4",
}
# Output location
timestamp = datetime.now().strftime("%Y-%m-%d %H-%M-%S")
OUTPUT_DIR = Path(r"U:\Dropbox\!!!Days\Downloads Z230")
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
OUTPUT_FILE = OUTPUT_DIR / f"{timestamp} Medevio report.xlsx"
# ==============================
# 🧹 Remove old reports
# ==============================
for file in OUTPUT_DIR.glob("* Medevio report.xlsx"):
try:
file.unlink()
print("Removed old report:", file)
except Exception as e:
print("Could not remove:", file, "Error:", e)
# ==============================
# 📥 FETCH DATA — POZADAVKY
# ==============================
conn = pymysql.connect(**DB_CONFIG)
two_months_ago = (datetime.now() - timedelta(days=1000)).strftime("%Y-%m-%d %H:%M:%S")
sql_pozadavky = """
SELECT
id,
pacient_prijmeni,
pacient_jmeno,
pacient_rodnecislo,
displayTitle,
createdAt,
updatedAt,
doneAt,
removedAt,
attachmentsProcessed,
messagesProcessed,
communicationprocessed,
questionnaireprocessed,
lastSync
FROM pozadavky
WHERE createdAt >= %s
ORDER BY updatedAt DESC
"""
df_poz = pd.read_sql(sql_pozadavky, conn, params=(two_months_ago,))
# ==============================
# 📥 FETCH DATA — MESSAGES (WITH JOIN)
# ==============================
ids = tuple(df_poz["id"].tolist())
if len(ids) == 1:
ids_sql = f"('{ids[0]}')"
else:
ids_sql = ids
sql_messages = f"""
SELECT
p.pacient_jmeno,
p.pacient_prijmeni,
p.pacient_rodnecislo,
p.displayTitle AS pozadavek_title,
m.id,
m.text,
m.sender_name,
m.created_at,
m.read_at,
m.updated_at,
m.attachment_url,
m.attachment_description,
m.attachment_content_type,
m.inserted_at
FROM medevio_conversation m
LEFT JOIN pozadavky p
ON m.request_id COLLATE utf8mb4_unicode_ci
= p.id COLLATE utf8mb4_unicode_ci
WHERE m.request_id IN {ids_sql}
ORDER BY m.created_at DESC
"""
df_msg = pd.read_sql(sql_messages, conn)
conn.close()
# ==============================
# 💾 SAVE BOTH SHEETS
# ==============================
with pd.ExcelWriter(OUTPUT_FILE, engine="openpyxl") as writer:
df_poz.to_excel(writer, sheet_name="pozadavky", index=False)
df_msg.to_excel(writer, sheet_name="messages", index=False)
# ==============================
# 🎨 FORMAT EXCEL
# ==============================
wb = load_workbook(OUTPUT_FILE)
yellow = PatternFill(start_color="FFFF00", end_color="FFFF00", fill_type="solid")
header_font = Font(bold=True)
def format_sheet(ws):
for cell in ws[1]:
cell.fill = yellow
cell.font = header_font
cell.alignment = Alignment(horizontal="center")
ws.auto_filter.ref = ws.dimensions
for column in ws.columns:
max_length = 0
col_letter = column[0].column_letter
for cell in column:
if cell.value:
max_length = max(max_length, len(str(cell.value)))
ws.column_dimensions[col_letter].width = max_length + 2
format_sheet(wb["pozadavky"])
format_sheet(wb["messages"])
wb.save(OUTPUT_FILE)
print("Report saved:", OUTPUT_FILE)