Initial commit - Insurance VZP ověření pojištění
This commit is contained in:
@@ -0,0 +1,199 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# this script can be run several times on the same day, in such case it works incrementally
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# ==========================================
|
||||
# PROJECT ROOT (import fix)
|
||||
# ==========================================
|
||||
PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(PROJECT_ROOT))
|
||||
|
||||
import time
|
||||
import logging
|
||||
from Knihovny.medicus_db import MedicusDB
|
||||
from Knihovny.vzpb2b_client import VZPB2BClient
|
||||
import pymysql
|
||||
from datetime import date
|
||||
|
||||
# ==========================================
|
||||
# LOGGING SETUP
|
||||
# ==========================================
|
||||
logging.basicConfig(
|
||||
filename="insurance_check.log",
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(message)s",
|
||||
encoding="utf-8"
|
||||
)
|
||||
|
||||
console = logging.getLogger("console")
|
||||
console.setLevel(logging.INFO)
|
||||
handler = logging.StreamHandler()
|
||||
handler.setFormatter(logging.Formatter("%(message)s"))
|
||||
console.addHandler(handler)
|
||||
|
||||
def log_info(msg):
|
||||
logging.info(msg)
|
||||
console.info(msg)
|
||||
|
||||
def log_error(msg):
|
||||
logging.error(msg)
|
||||
console.error(msg)
|
||||
|
||||
# ==========================================
|
||||
# MYSQL CONNECTION
|
||||
# ==========================================
|
||||
mysql = pymysql.connect(
|
||||
host="192.168.1.76",
|
||||
port=3306,
|
||||
user="root",
|
||||
password="Vlado9674+",
|
||||
database="medevio",
|
||||
charset="utf8mb4",
|
||||
autocommit=True
|
||||
)
|
||||
|
||||
# ==========================================
|
||||
# SAVE RESULT
|
||||
# ==========================================
|
||||
def save_insurance_status(mysql_conn, rc, prijmeni, jmeno, k_datu, result, xml_text):
|
||||
"""
|
||||
Uloží čistou odpověď VZP + identifikační údaje pacienta.
|
||||
Pojišťovna je VÝHRADNĚ z odpovědi VZP.
|
||||
"""
|
||||
sql = """
|
||||
INSERT INTO vzp_stav_pojisteni
|
||||
(rc, prijmeni, jmeno, k_datu,
|
||||
stav, kod_pojistovny, nazev_pojistovny,
|
||||
pojisteni_kod, stav_vyrizeni, response_xml)
|
||||
VALUES (%s, %s, %s, %s,
|
||||
%s, %s, %s,
|
||||
%s, %s, %s)
|
||||
"""
|
||||
|
||||
with mysql_conn.cursor() as cur:
|
||||
cur.execute(sql, (
|
||||
rc,
|
||||
prijmeni,
|
||||
jmeno,
|
||||
k_datu,
|
||||
result["stav"],
|
||||
result["kodPojistovny"], # ← VZP
|
||||
result["nazevPojistovny"], # ← VZP
|
||||
result["pojisteniKod"], # ← VZP
|
||||
result["stavVyrizeni"], # ← VZP
|
||||
xml_text
|
||||
))
|
||||
|
||||
|
||||
# ==========================================
|
||||
# CONFIGURATION
|
||||
# ==========================================
|
||||
# con = fdb.connect(
|
||||
# host='192.168.1.10', database=r'm:\MEDICUS\data\medicus.FDB',
|
||||
# user='sysdba', password='masterkey',charset='WIN1250')
|
||||
HOST = "192.168.1.4"
|
||||
DB_PATH = r"c:\Medicus 3\data\MEDICUS.FDB"
|
||||
|
||||
PFX_PATH = Path(__file__).resolve().parent / "Certificates" / "picka.pfx"
|
||||
# PFX_PATH = PROJECT_ROOT / "certificates" / "MBcert.pfx"
|
||||
PFX_PASSWORD = "Vlado7309208104+"
|
||||
|
||||
ENV = "prod"
|
||||
ICZ = "00000000"
|
||||
DIC = "00000000"
|
||||
|
||||
# sanity check
|
||||
if not PFX_PATH.exists():
|
||||
raise FileNotFoundError(f"PFX certificate not found: {PFX_PATH}")
|
||||
|
||||
# ==========================================
|
||||
# INIT CONNECTIONS
|
||||
# ==========================================
|
||||
db = MedicusDB(HOST, DB_PATH)
|
||||
vzp = VZPB2BClient(
|
||||
ENV,
|
||||
str(PFX_PATH), # <-- important: pass as string
|
||||
PFX_PASSWORD,
|
||||
icz=ICZ,
|
||||
dic=DIC
|
||||
)
|
||||
|
||||
# ==========================================
|
||||
# FETCH REGISTERED PATIENTS
|
||||
# ==========================================
|
||||
patients = db.get_active_registered_patients()
|
||||
log_info(f"Loaded {len(patients)} registered patients")
|
||||
|
||||
today = date.today()
|
||||
|
||||
# ==========================================
|
||||
# FILTER: ONLY PATIENTS NOT CHECKED TODAY
|
||||
# ==========================================
|
||||
patients_to_check = []
|
||||
|
||||
with mysql.cursor(pymysql.cursors.DictCursor) as cur:
|
||||
for rc, prijmeni, jmeno, poj in patients:
|
||||
cur.execute(
|
||||
"SELECT MAX(k_datu) AS last_check FROM vzp_stav_pojisteni WHERE rc = %s",
|
||||
(rc,)
|
||||
)
|
||||
row = cur.fetchone()
|
||||
last_check = row["last_check"]
|
||||
|
||||
if last_check is None or last_check < today:
|
||||
patients_to_check.append((rc, prijmeni, jmeno))
|
||||
|
||||
log_info(f"Incremental run: {len(patients_to_check)} patients to check today\n")
|
||||
|
||||
# ==========================================
|
||||
# MAIN LOOP (1 of N)
|
||||
# ==========================================
|
||||
total = len(patients_to_check)
|
||||
|
||||
for idx, (rodcis, prijmeni, jmeno) in enumerate(patients_to_check, 1):
|
||||
|
||||
log_info(f"[{idx}/{total}] Checking {prijmeni} {jmeno} ({rodcis})")
|
||||
|
||||
try:
|
||||
xml = vzp.stav_pojisteni(rc=rodcis, k_datu=today.isoformat())
|
||||
except Exception as e:
|
||||
log_error(f"❌ VZP REQUEST FAILED for {rodcis}: {e}")
|
||||
time.sleep(2)
|
||||
continue
|
||||
|
||||
if not xml.strip().startswith("<"):
|
||||
log_error(f"❌ INVALID XML for RC {rodcis}")
|
||||
time.sleep(2)
|
||||
continue
|
||||
|
||||
try:
|
||||
result = vzp.parse_stav_pojisteni(xml)
|
||||
except Exception as e:
|
||||
log_error(f"❌ XML PARSE ERROR for RC {rodcis}: {e}")
|
||||
time.sleep(2)
|
||||
continue
|
||||
|
||||
try:
|
||||
save_insurance_status(
|
||||
mysql,
|
||||
rodcis,
|
||||
prijmeni,
|
||||
jmeno,
|
||||
today,
|
||||
result,
|
||||
xml
|
||||
)
|
||||
except Exception as e:
|
||||
log_error(f"❌ MYSQL INSERT ERROR for RC {rodcis}: {e}")
|
||||
time.sleep(2)
|
||||
continue
|
||||
|
||||
log_info(f" ✔ OK ({result['nazevPojistovny']})")
|
||||
time.sleep(1.4)
|
||||
|
||||
db.close()
|
||||
mysql.close()
|
||||
log_info("\nDONE – incremental insurance check finished.")
|
||||
@@ -0,0 +1,209 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from datetime import datetime, date, timedelta
|
||||
import os
|
||||
import pymysql
|
||||
|
||||
from Knihovny.medicus_db import MedicusDB
|
||||
from Knihovny.vzpb2b_client import VZPB2BClient
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
from weasyprint import HTML
|
||||
|
||||
# ==========================================
|
||||
# PROJECT ROOT (import + paths)
|
||||
# ==========================================
|
||||
script_location = Path(__file__).resolve().parent
|
||||
project_root = script_location.parent
|
||||
sys.path.insert(0, str(project_root))
|
||||
|
||||
# ==========================================
|
||||
# CONFIGURATION
|
||||
# ==========================================
|
||||
MEDICUS_HOST = "192.168.1.4"
|
||||
MEDICUS_DB_PATH = r"c:\Medicus 3\data\MEDICUS.FDB"
|
||||
|
||||
MYSQL_CONFIG = {
|
||||
"host": "192.168.1.76",
|
||||
"port": 3306,
|
||||
"user": "root",
|
||||
"password": "Vlado9674+",
|
||||
"database": "medevio",
|
||||
"charset": "utf8mb4",
|
||||
"autocommit": True
|
||||
}
|
||||
|
||||
PFX_PATH = script_location / "Certificates" / "MBcert.pfx"
|
||||
PFX_PASSWORD = "Vlado7309208104++"
|
||||
|
||||
ENV = "prod"
|
||||
ICZ = "00000000"
|
||||
DIC = "00000000"
|
||||
|
||||
if not PFX_PATH.exists():
|
||||
raise FileNotFoundError(f"PFX certificate not found: {PFX_PATH}")
|
||||
|
||||
# ==========================================
|
||||
# PATHS (templates, output)
|
||||
# ==========================================
|
||||
template_dir = script_location / "Templates"
|
||||
output_dir = script_location / "Output"
|
||||
output_dir.mkdir(exist_ok=True)
|
||||
|
||||
font_regular = (template_dir / "fonts" / "DejaVuSans.ttf").as_uri()
|
||||
font_bold = (template_dir / "fonts" / "DejaVuSans-Bold.ttf").as_uri()
|
||||
font_italic = (template_dir / "fonts" / "DejaVuSans-Oblique.ttf").as_uri()
|
||||
|
||||
# ==========================================
|
||||
# INIT CONNECTIONS
|
||||
# ==========================================
|
||||
print("Connecting to Medicus...")
|
||||
medicus = MedicusDB(MEDICUS_HOST, MEDICUS_DB_PATH)
|
||||
|
||||
print("Connecting to MySQL...")
|
||||
mysql = pymysql.connect(
|
||||
cursorclass=pymysql.cursors.DictCursor,
|
||||
**MYSQL_CONFIG
|
||||
)
|
||||
|
||||
print("Initializing VZP B2B client...")
|
||||
vzp = VZPB2BClient(
|
||||
ENV,
|
||||
str(PFX_PATH),
|
||||
PFX_PASSWORD,
|
||||
icz=ICZ,
|
||||
dic=DIC
|
||||
)
|
||||
|
||||
# ==========================================
|
||||
# BINÁRNÍ HLEDÁNÍ DATA ZLOMU
|
||||
# ==========================================
|
||||
def find_insurance_break_date(vzp_client, rc, start_date, end_date):
|
||||
try:
|
||||
low = start_date
|
||||
high = end_date
|
||||
|
||||
stav_low = vzp_client.parse_stav_pojisteni(
|
||||
vzp_client.stav_pojisteni(rc=rc, k_datu=low.isoformat())
|
||||
)["stav"]
|
||||
|
||||
stav_high = vzp_client.parse_stav_pojisteni(
|
||||
vzp_client.stav_pojisteni(rc=rc, k_datu=high.isoformat())
|
||||
)["stav"]
|
||||
|
||||
if stav_low != "1" or stav_high == "1":
|
||||
return None, None
|
||||
|
||||
while (high - low).days > 1:
|
||||
mid = low + timedelta(days=(high - low).days // 2)
|
||||
|
||||
xml = vzp_client.stav_pojisteni(rc=rc, k_datu=mid.isoformat())
|
||||
stav_mid = vzp_client.parse_stav_pojisteni(xml)["stav"]
|
||||
|
||||
if stav_mid == "1":
|
||||
low = mid
|
||||
else:
|
||||
high = mid
|
||||
|
||||
return low, high
|
||||
|
||||
except Exception:
|
||||
return None, None
|
||||
|
||||
# ==========================================
|
||||
# FETCH REGISTERED PATIENTS
|
||||
# ==========================================
|
||||
print("Fetching registered patients from Medicus...")
|
||||
patients = medicus.get_active_registered_patients(as_dict=True)
|
||||
patients_by_rc = {p["rodcis"]: p for p in patients}
|
||||
print(f"Loaded {len(patients_by_rc)} registered patients")
|
||||
|
||||
# ==========================================
|
||||
# FETCH LAST INSURANCE STATES
|
||||
# ==========================================
|
||||
sql_last_states = """
|
||||
SELECT rc, stav
|
||||
FROM (
|
||||
SELECT rc, stav,
|
||||
ROW_NUMBER() OVER (PARTITION BY rc ORDER BY k_datu DESC) AS rn
|
||||
FROM vzp_stav_pojisteni
|
||||
) t
|
||||
WHERE rn = 1
|
||||
"""
|
||||
|
||||
with mysql.cursor() as cur:
|
||||
cur.execute(sql_last_states)
|
||||
last_states = cur.fetchall()
|
||||
|
||||
# ==========================================
|
||||
# COMPARE + BREAK DATE
|
||||
# ==========================================
|
||||
suspected = []
|
||||
today = date.today()
|
||||
|
||||
for row in last_states:
|
||||
rc = row["rc"]
|
||||
stav = row["stav"]
|
||||
|
||||
if rc in patients_by_rc and stav != "1":
|
||||
p = patients_by_rc[rc]
|
||||
|
||||
with mysql.cursor() as c2:
|
||||
c2.execute("""
|
||||
SELECT MAX(k_datu) AS last_insured
|
||||
FROM vzp_stav_pojisteni
|
||||
WHERE rc = %s AND stav = '1'
|
||||
""", (rc,))
|
||||
r2 = c2.fetchone()
|
||||
last_known_insured = r2["last_insured"]
|
||||
|
||||
insured_to = uninsured_from = None
|
||||
if last_known_insured:
|
||||
insured_to, uninsured_from = find_insurance_break_date(
|
||||
vzp, rc, last_known_insured, today
|
||||
)
|
||||
|
||||
suspected.append({
|
||||
"rc": rc,
|
||||
"prijmeni": p["prijmeni"],
|
||||
"jmeno": p["jmeno"],
|
||||
"poj": p["poj"],
|
||||
"stav": stav,
|
||||
"insured_to": insured_to,
|
||||
"uninsured_from": uninsured_from
|
||||
})
|
||||
|
||||
print(f"Nalezeno {len(suspected)} problémových záznamů")
|
||||
|
||||
# ==========================================
|
||||
# CLEANUP DB
|
||||
# ==========================================
|
||||
medicus.close()
|
||||
mysql.close()
|
||||
|
||||
# ==========================================
|
||||
# PDF GENERATION
|
||||
# ==========================================
|
||||
env = Environment(loader=FileSystemLoader(str(template_dir)), autoescape=True)
|
||||
template = env.get_template("vzp_console_report.html")
|
||||
|
||||
html_content = template.render(
|
||||
patients=suspected,
|
||||
generated_at=datetime.now().strftime("%d. %m. %Y %H:%M"),
|
||||
font_regular=font_regular,
|
||||
font_bold=font_bold,
|
||||
font_italic=font_italic
|
||||
)
|
||||
|
||||
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
||||
pdf_file = output_dir / f"kontrola_pojisteni_{timestamp}.pdf"
|
||||
|
||||
print("Generuji PDF přes WeasyPrint...")
|
||||
HTML(string=html_content, base_url=str(template_dir)).write_pdf(pdf_file)
|
||||
|
||||
print("\n✅ PDF REPORT VYTVOŘEN:")
|
||||
print(pdf_file.resolve())
|
||||
|
||||
try:
|
||||
os.startfile(pdf_file)
|
||||
except Exception:
|
||||
pass
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,136 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="cs">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Kontrola stavu pojištění</title>
|
||||
|
||||
<style>
|
||||
@font-face {
|
||||
font-family: 'DejaVu';
|
||||
src: url('{{ font_regular }}');
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: 'DejaVu';
|
||||
src: url('{{ font_bold }}');
|
||||
font-weight: bold;
|
||||
font-style: normal;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: 'DejaVu';
|
||||
src: url('{{ font_italic }}');
|
||||
font-weight: normal;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@page {
|
||||
size: A4;
|
||||
margin: 1.5cm;
|
||||
@bottom-right {
|
||||
content: "Strana " counter(page) " z " counter(pages);
|
||||
font-size: 9pt;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'DejaVu', sans-serif;
|
||||
font-size: 10pt;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 16pt;
|
||||
border-bottom: 2px solid #2c3e50;
|
||||
padding-bottom: 5px;
|
||||
}
|
||||
|
||||
.meta {
|
||||
font-size: 9pt;
|
||||
margin-bottom: 15px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
th, td {
|
||||
border: 1px solid #ccc;
|
||||
padding: 6px 8px;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
th {
|
||||
background-color: #f2f2f2;
|
||||
}
|
||||
|
||||
tr {
|
||||
page-break-inside: avoid;
|
||||
}
|
||||
|
||||
tr:nth-child(even) {
|
||||
background-color: #f9f9f9;
|
||||
}
|
||||
|
||||
.status-bad {
|
||||
color: #d9534f;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.date-info {
|
||||
font-size: 9pt;
|
||||
color: #555;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<h1>Kontrola stavu pojištění (VZP)</h1>
|
||||
|
||||
<div class="meta">
|
||||
Vygenerováno: {{ generated_at }}
|
||||
</div>
|
||||
|
||||
{% if patients %}
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Rodné číslo</th>
|
||||
<th>Příjmení a jméno</th>
|
||||
<th>Pojišťovna</th>
|
||||
<th>Stav</th>
|
||||
<th>Platnost pojištění</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for p in patients %}
|
||||
<tr>
|
||||
<td>{{ p.rc }}</td>
|
||||
<td><strong>{{ p.prijmeni }}</strong> {{ p.jmeno }}</td>
|
||||
<td>{{ p.poj }}</td>
|
||||
<td class="status-bad">{{ p.stav }}</td>
|
||||
<td class="date-info">
|
||||
{% if p.insured_to %}
|
||||
pojištěn do {{ p.insured_to.strftime("%d.%m.%Y") }}<br>
|
||||
nepojištěn od {{ p.uninsured_from.strftime("%d.%m.%Y") }}
|
||||
{% else %}
|
||||
nelze určit
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% else %}
|
||||
<p style="color: green; font-weight: bold;">
|
||||
✔ Vše v pořádku – žádné neshody nenalezeny.
|
||||
</p>
|
||||
{% endif %}
|
||||
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user