commit b45a8b2d003c1de95b14ff1d846114b8985db267 Author: michaela.buzalkova Date: Tue Sep 30 08:22:44 2025 +0200 Initial commit diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/PycharmProjects.iml b/.idea/PycharmProjects.iml new file mode 100644 index 0000000..f571432 --- /dev/null +++ b/.idea/PycharmProjects.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..105ce2d --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..db8786c --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..5895f80 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/02 Zapis dekurs.py b/02 Zapis dekurs.py new file mode 100644 index 0000000..652a4f4 --- /dev/null +++ b/02 Zapis dekurs.py @@ -0,0 +1,20 @@ +import fdb,os +from datetime import date + +from pathlib import Path +import time +import funkce + +# Connect to the Firebird database +conn = fdb.connect( + dsn=r'localhost:c:\medicus 3\data\medicus.fdb', # Database path + user='SYSDBA', # Username + password="masterkey", # Password, + charset="win1250") +cur = conn.cursor() + +cur.execute("delete from dekurs where idpac=9742") +conn.commit() + +print(funkce.zapis_dekurs(conn,cur,9742,2,6,2,3,"Příloha.pdf","test text",date(2023, 10, 15),date(2023, 10, 15))) +print(funkce.zapis_dekurs(conn,cur,9742,2,6,2,3,"Příloha.pdf","test text",date(2023, 10, 15),date(2023, 10, 15))) \ No newline at end of file diff --git a/04 kontrola souboru.py b/04 kontrola souboru.py new file mode 100644 index 0000000..2b419c9 --- /dev/null +++ b/04 kontrola souboru.py @@ -0,0 +1,23 @@ + +import os,shutil,fdb +import re,datetime,funkce1 + +# Connect to the Firebird database +conn = fdb.connect( + dsn=r'localhost:c:\medicus 3\data\medicus.fdb', # Database path + user='SYSDBA', # Username + password="masterkey", # Password, + charset="win1250") + +cesta=r"u:\NextcloudOrdinace\Dokumentace_ke_zpracování" + + +for soubor in os.listdir(cesta): + print(soubor) + if os.path.isfile(os.path.join(cesta, soubor)): + if funkce1.kontrola_struktury(soubor,conn): + # info.append(vrat_info_o_souboru(soubor,conn)) + # os.remove(os.path.join(cesta,soubor)) + continue + else: + funkce1.prejmenuj_chybny_soubor(soubor,cesta) \ No newline at end of file diff --git a/A4.py b/A4.py new file mode 100644 index 0000000..04fae2a --- /dev/null +++ b/A4.py @@ -0,0 +1,42 @@ +from PyPDF2 import PdfReader, PdfWriter + +# A4 dimensions in points (1mm = 2.83465 points) +A4_WIDTH = 210 * 2.83465 # ≈ 595.276 pts (width) +A4_HEIGHT = 297 * 2.83465 # ≈ 841.89 pts (height) + +def fit_to_a4(input_pdf_path, output_pdf_path): + reader = PdfReader(input_pdf_path) + writer = PdfWriter() + + for page in reader.pages: + # Get original page dimensions + orig_width = float(page.mediabox.width) + orig_height = float(page.mediabox.height) + + # Calculate scaling factor to fit A4 (preserve aspect ratio) + scale = min(A4_WIDTH / orig_width, A4_HEIGHT / orig_height) + + # Scale the page content + page.scale_by(scale) + + # Calculate offsets to center on A4 + new_width = orig_width * scale + new_height = orig_height * scale + x_offset = (A4_WIDTH - new_width) / 2 + y_offset = (A4_HEIGHT - new_height) / 2 + + # Set A4 mediabox and shift content + page.mediabox.lower_left = (x_offset, y_offset) + page.mediabox.upper_right = (x_offset + new_width, y_offset + new_height) + + writer.add_page(page) + + # Save the output PDF + with open(output_pdf_path, "wb") as out_file: + writer.write(out_file) + + + +# Example usage +fit_to_a4(r"z:\Dropbox\Ordinace\Dokumentace_ke_zpracování\untitled.pdf", r"z:\Dropbox\Ordinace\Dokumentace_ke_zpracování\output_a4.pdf") +print("PDF adjusted to A4 portrait successfully!") \ No newline at end of file diff --git a/Dokumentace_uprava_jmena_souboru.py b/Dokumentace_uprava_jmena_souboru.py new file mode 100644 index 0000000..e4f6501 --- /dev/null +++ b/Dokumentace_uprava_jmena_souboru.py @@ -0,0 +1,24 @@ +import os,re + +def set_single_page_view (filepdfin): + from pikepdf import Pdf, Dictionary, Name + import os + from pathlib import Path + pdf=Pdf.open(filepdfin,allow_overwriting_input=True) + # file_only_path=os.path.dirname(filepdfin) + # file_without_ext = Path(filepdfin).stem + pdf.Root.PageLayout=Name('/SinglePage') + pdf.Root.PageMode=Name('/UseNone') + pdf.save() + + +cesta=r"u:\NextCloudOrdinace\Dokumentace" + +for file in os.listdir(cesta): + if file.upper().endswith((".PDF")) and os.path.isfile(os.path.join(cesta,file)): + nalezeno=re.search('(\d{9,10} \S*)( )(.*)',file) + if nalezeno: + print(nalezeno.group(1),nalezeno.group(2),nalezeno.group(3)) + newfilename=nalezeno.group(1)+", "+nalezeno.group(3) + print(newfilename) + os.rename(os.path.join(cesta,file),os.path.join(cesta,newfilename)) \ No newline at end of file diff --git a/ECGAnthem.py b/ECGAnthem.py new file mode 100644 index 0000000..94a963d --- /dev/null +++ b/ECGAnthem.py @@ -0,0 +1,32 @@ +import re, os + +cesta=r"u:\Dropbox\!77242113UCO2001\#250 ECG\#010 Široký" + + + +from openpyxl import Workbook +wb = Workbook() +ws = wb.active +# Add headers +ws.append(['Filename', 'Datetime']) + + +for file in os.listdir(cesta): + filename = os.path.join(cesta, file) + with open(filename,"rb") as f: + nacteno=f.read() + vyhledani=re.search(rb"202[3|4|5]-\d\d-\d\dT\d\d:\d\d:\d\d",nacteno) + if vyhledani: + print(file,vyhledani.group().decode("ASCII")) + ws.append((file,vyhledani.group().decode("ASCII"))) + # print(len(nacteno)) +wb.save(os.path.join(cesta,'output_openpyxl.xlsx')) + +# filename=r"u:\Dropbox\!77242113UCO2001\#250 ECG\#010 Široký\0000003C.ECG" +# +# with open(filename,"rb") as f: +# nacteno=f.read() +# match=re.search(rb"202[3|4|5]-\d\d-\d\dT\d\d:\d\d:\d\d",nacteno) +# if match: +# print(match.group()) +# print(match.group().decode("ASCII")) \ No newline at end of file diff --git a/EmptyFolders.py b/EmptyFolders.py new file mode 100644 index 0000000..dc91078 --- /dev/null +++ b/EmptyFolders.py @@ -0,0 +1,19 @@ +import os + +cesta=r"u:\d1" + +folders=[] +for root,dirs,files in os.walk(cesta): + for dir in dirs: + folders.append(os.path.join(root,dir)) + + +print(folders) + +sorted_list = sorted(folders, key=len, reverse=True) +print(sorted_list) + +for item in sorted_list: + if len(os.listdir(item)) == 0: + print(item) + os.rmdir(item) diff --git a/GetDevices.py b/GetDevices.py new file mode 100644 index 0000000..fe351bf --- /dev/null +++ b/GetDevices.py @@ -0,0 +1,43 @@ + +def disk_info(path,conn): + import wmi + DRIVE_TYPES = { + 0 : "Unknown", + 1 : "No Root Directory", + 2 : "Removable Disk", + 3 : "Local Disk", + 4 : "Network Drive", + 5 : "Compact Disc", + 6 : "RAM Disk" + } + if path[1]==":": + c = wmi.WMI () + for drive in c.Win32_LogicalDisk (): + # prints all the drives details including name, type and size + if drive.Caption.upper()==path[0:2].upper(): + # print(drive) + # print (drive.Caption, drive.SystemName,drive.VolumeSerialNumber,drive.VolumeName, DRIVE_TYPES[drive.DriveType]) + cur = conn.cursor() + cur.execute("select id from tdevices where volumename=%s and devicecaption=%s and systemname=%s and volumeserial=%s and type=%s",(drive.Caption, drive.SystemName,drive.VolumeSerialNumber,drive.VolumeName, DRIVE_TYPES[drive.DriveType])) + f=cur.fetchone() + if len(f)==0: + cur.execute("insert into tdevices (volumename, devicecaption, systemname, volumeserial, type) values (%s,%s,%s,%s,%s)",(drive.Caption, drive.SystemName,drive.VolumeSerialNumber,drive.VolumeName, DRIVE_TYPES[drive.DriveType])) + conn.commit() + returnvalue=cur.lastrowid + else: + returnvalue=f['id'] + return returnvalue + else: + return [] + + +# import pymysql +# from pymysql.cursors import DictCursor +# from GetFunctions import * +# conn = pymysql.connect(host='192.168.1.76', user="root", password="Vlado9674+", database="Duplicates", port=3307,cursorclass=DictCursor) +# cur1 = conn.cursor() +# # set_sql_mode_no_escape(cur1) +# +# cesta=r"c:\pomoc" +# +# print(disk_info(r"C:\\",conn)) \ No newline at end of file diff --git a/GetFiles.py b/GetFiles.py new file mode 100644 index 0000000..967574f --- /dev/null +++ b/GetFiles.py @@ -0,0 +1,86 @@ +import os, shutil, win32api, pathlib, pymysql, timeit, ListFolders_functions, sys, hashlib + +from pathlib import Path +from datetime import datetime +from ListFolders_functions import * + +conn = pymysql.connect(host='192.168.1.76', user="root", password="Vlado9674+", database="Python", port=3307) +cur1 = conn.cursor() +set_sql_mode_no_escape(cur1) + +# FolderToScan = r'\\192.168.1.121\public\winsusoft' +# FolderToScan = r'\\192.168.1.50\#Fotky' +FolderToScan = r'\\192.168.1.50\#ebooks' +# FolderToScan = r'd:\\onedrive' +# FolderToScan = r'\\192.168.1.121\public\puzzle' +ConditionFolderToScan=FolderToScan+"%" + + +print("Start cteni adresaru") +# update testing na 1 +cur1.execute("update tFilesRepository set btesting=1 where cfilename like %s",ConditionFolderToScan) +conn.commit() + +for root, dirs, files in os.walk(FolderToScan): + # print(root) + for file in files: + print(file) + fullfilename=os.path.join(root,file) + # print(fullfilename) + filesize=os.stat(fullfilename).st_size + print(filesize) + filectime=datetime.fromtimestamp(os.stat(fullfilename).st_ctime) + filemtime=datetime.fromtimestamp(os.stat(fullfilename).st_mtime) + # print(filemtime) + # vloz.append((fullfilename,filesize,filectime,filemtime)) + + cur1.execute("select id,cfilename,isize,mtime,ctime from tFilesRepository where cfilename=%s",(fullfilename)) + record=cur1.fetchone() + if cur1.rowcount==0: + entrycreated = datetime.now() + cur1.execute("insert into tFilesRepository (cfilename,isize,mtime,ctime,entrycreated) values (%s,%s,%s,%s,%s)",(fullfilename,filesize,filemtime,filectime,entrycreated)) + conn.commit() + else: + # check if update needed + # print(cur1.rowcount) + # print(record[0]) + # print(record[1]) + # print(fullfilename) + # print(record[2]) + # print(filesize) + # print(record[3]) + # print(filemtime) + # print(record[4]) + # print(filectime) + if record[2]==filesize and record[3]==filemtime and record[4]==filectime: + cur1.execute("update tFilesRepository set btesting=0 where id=%s",record[0]) + conn.commit() + else: + print("Zde zacina ELSE") + entrycreated = datetime.now() + # print(entrycreated) + # print(filesize) + # print(record[0]) + cur1.execute("update tFilesRepository set cfilename=%s,isize=%s,mtime=%s,ctime=%s,entrycreated=%s,btesting=0" + " where id=%s",(fullfilename, filesize, filemtime, filectime, entrycreated,record[0])) + conn.commit() + + +cur1.execute("delete from tFilesRepository where cfilename like %s and btesting=1 ",ConditionFolderToScan) +conn.commit() + +#update MD5 +cur1.execute("select id, cfilename, isize from tFilesRepository where md5 is NULL") + +FilesToHash=cur1.fetchall() +print(FilesToHash) +for Soubor in FilesToHash: + with open(Soubor[1], "rb") as f: + print(Soubor[1]) + file_hash = hashlib.md5() + while chunk := f.read(8192): + file_hash.update(chunk) + print(file_hash.hexdigest()) + md5calculated = datetime.now() + cur1.execute("update tFilesRepository set md5=%s, md5calculated=%s where id=%s",(file_hash.hexdigest(),md5calculated,Soubor[0])) + conn.commit() \ No newline at end of file diff --git a/GetFolders.py b/GetFolders.py new file mode 100644 index 0000000..4d9dcb5 --- /dev/null +++ b/GetFolders.py @@ -0,0 +1,48 @@ +import os, datetime + +def get_folders(path): + folders=[] + for root,dirs,files in os.walk(path): + for dir in dirs: + moddatetime=datetime.datetime.fromtimestamp(os.path.getmtime(os.path.join(root,dir))) + folders.append((os.path.join(root,dir),moddatetime)) + return folders + + + + + + + +import pymysql +from pymysql.cursors import DictCursor +from GetFunctions import * +conn = pymysql.connect(host='192.168.1.76', user="root", password="Vlado9674+", database="Duplicates", port=3307,cursorclass=DictCursor,init_command="SET SESSION sql_mode='NO_BACKSLASH_ESCAPES'") +cur1 = conn.cursor() +# set_sql_mode_no_escape(cur1) + +cpath=r"U:\a" +folds=get_folders(cpath) + +print("folds",folds) +search_pattern=cpath +# print(f"{search_pattern}%") + +cur1.execute("select folder,modified from tfolders where folder like %s",[f"{search_pattern}%"]) +vtabulce=([(row["folder"],row["modified"]) for row in cur1.fetchall()]) +# vtabulce.append((row["folder"],row["modified"]) for row in cur1.fetchall()) +print("vtabulce",vtabulce) +print(type(vtabulce)) + +new=list(set(folds) - set(vtabulce)) +todelete=list(set(vtabulce) - set(folds)) +print("MISSING",new) +print("TODELETE",todelete) + +#zde vložení nových +cur1.executemany("insert into tfolders (folder,modified) values (%s,%s)",new) +conn.commit() + +#zde smazání neexistujících +cur1.executemany("delete from tfolders where folder=%s and modified=%s",todelete) +conn.commit() diff --git a/GetFunctions.py b/GetFunctions.py new file mode 100644 index 0000000..9f28c14 --- /dev/null +++ b/GetFunctions.py @@ -0,0 +1,37 @@ +import hashlib + + +def create_entry_hash(cfilename, isize, ctime, mtime): + entryhash = "" + entryhash = hashlib.md5( + cfilename.upper().encode() + str(isize).encode() + str(ctime).encode() + str(mtime).encode()).hexdigest() + return (entryhash) + + +def create_filename_hash(cfilename): + filenamehash = "" + filenamehash = hashlib.md5(cfilename.upper().encode()).hexdigest() + return (filenamehash) + + +def delete_all_from_tfolders(cursor, connection): + cursor.execute("delete from tFolders") + connection.commit() + + +def check_folder_exists(folder, connection): + curtmp = connection.cursor() + escfolder = connection.escape_string(folder) + print(escfolder) + pocettmp = curtmp.execute("select id from tFolders where cfoldername=%s", escfolder) + if pocettmp == 0: + return [0, 0] + else: + return [pocettmp, curtmp.fetchone()[0]] + + +def set_sql_mode_no_escape(cursor): + cursor.execute("SELECT @@sql_mode") + newmode = cursor.fetchone()[0] + newmode = newmode + ",NO_BACKSLASH_ESCAPES" + cursor.execute("set @@sql_mode=%s", newmode) diff --git a/PDF - doplnění jména.py b/PDF - doplnění jména.py new file mode 100644 index 0000000..ad7c412 --- /dev/null +++ b/PDF - doplnění jména.py @@ -0,0 +1,58 @@ +import os,re,fdb,time +import logging +logging.basicConfig(level=logging.DEBUG) + + +def set_single_page_view (filepdfin): + from pikepdf import Pdf, Dictionary, Name + import os + from pathlib import Path + pdf=Pdf.open(filepdfin,allow_overwriting_input=True) + # file_only_path=os.path.dirname(filepdfin) + # file_without_ext = Path(filepdfin).stem + pdf.Root.PageLayout=Name('/SinglePage') + pdf.Root.PageMode=Name('/UseNone') + pdf.save() + + +# Connect to the Firebird database +conn = fdb.connect( + dsn=r'192.168.1.10:m:\medicus\data\medicus.fdb', # Database path + user='SYSDBA', # Username + password="masterkey", # Password, + charset="win1250") +# cur = conn.cursor() + +cesta=r"z:\dropbox\ordinace\Dokumentace_ke_zpracování" + +for file in os.listdir(cesta): + if file.upper().endswith((".PDF")) and os.path.isfile(os.path.join(cesta,file)): + pattern=r"^(\d{9,10}) ((?:(?:19|20)\d\d)-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])) (\[.*)" + nalezeno=re.search(pattern,file) + if nalezeno: + print(nalezeno.groups()) + x=nalezeno.groups() + rodcis=nalezeno.group(1) + datum=nalezeno.group(2) + konec=nalezeno.group(5) + print(datum) + print(konec) + print(rodcis,type(rodcis)) + cur = conn.cursor() + cur.execute("select prijmeni, jmeno from kar where rodcis=?",(rodcis,)) + x = cur.fetchone() + if x: + if len(x[0].split(" "))==1: + prijmeni=x[0] + else: + prijmeni=x[0].split(" ")[0] + if len(x[1].split(" "))==1: + jmeno=x[1] + else: + prijmeni=x[1].split(" ")[0] + konecsouboru=file.split(rodcis)[1] + novejmeno=rodcis+" "+datum+" "+prijmeni.strip()+", "+jmeno.strip()+" "+konec + print(novejmeno) + os.rename(os.path.join(cesta,file),os.path.join(cesta,novejmeno)) + cur.close() + diff --git a/PDFmanipulation.py b/PDFmanipulation.py new file mode 100644 index 0000000..28add14 --- /dev/null +++ b/PDFmanipulation.py @@ -0,0 +1,22 @@ +import os,re + + +def set_single_page_view (filepdfin): + from pikepdf import Pdf, Dictionary, Name + import os + from pathlib import Path + pdf=Pdf.open(filepdfin,allow_overwriting_input=True) + # file_only_path=os.path.dirname(filepdfin) + # file_without_ext = Path(filepdfin).stem + pdf.Root.PageLayout=Name('/SinglePage') + pdf.Root.PageMode=Name('/UseNone') + pdf.save() + + +# set_single_page_view(r"u:\Dropbox\!!!Days\Downloads Z230\Dokumentace\a.pdf") + +cesta=r"z:\dropbox\ordinace\Dokumentace_ke_zpracování" + +for file in os.listdir(cesta): + if file.upper().endswith((".PDF")) and os.path.isfile(os.path.join(cesta,file)): + set_single_page_view(os.path.join(cesta,file)) diff --git a/ReportDokladyPandas.py b/ReportDokladyPandas.py new file mode 100644 index 0000000..34de49b --- /dev/null +++ b/ReportDokladyPandas.py @@ -0,0 +1,35 @@ +from sqlalchemy import create_engine +import pandas as pd +import time,os + +PathToSaveCSV=r"u:\NextCloudOrdinace\Reporty\testy" +timestr = time.strftime("%Y-%m-%d %H-%M-%S ") +reportname=os.path.join(PathToSaveCSV,(timestr+"Výkony.xlsx")) +print(reportname) + +# Create connection string +connection_string = ( + "firebird+fdb://SYSDBA:masterkey@localhost/u:/MEDICUS 3/data/medicus.FDB" + "?charset=WIN1250") + +# Create engine +engine = create_engine(connection_string) + +# Read data +query = "SELECT idpac, rodcis FROM kar" +df = pd.read_sql(query, engine) + +# Close connection (SQLAlchemy handles this automatically in most cases) +engine.dispose() + +print(df.head()) + +with pd.ExcelWriter(reportname, engine='openpyxl') as writer: + df.to_excel(writer, index=False) + # Access the worksheet + worksheet = writer.sheets['Sheet1'] + + # Apply text format to specific columns + for col in ['B']: # Columns A and C (ID and ProductCode) + for cell in worksheet[col]: + cell.number_format = '@' # Excel text format \ No newline at end of file diff --git a/ReportDokladyPojišťovna.py b/ReportDokladyPojišťovna.py new file mode 100644 index 0000000..bc54102 --- /dev/null +++ b/ReportDokladyPojišťovna.py @@ -0,0 +1,114 @@ +import os +import fdb +import csv,time,pandas as pd +import openpyxl + + +PathToSaveCSV=r"u:\NextCloudOrdinace\Reporty\testy" +timestr = time.strftime("%Y-%m-%d %H-%M-%S ") +CSVname="Výkony pojišťovna.xlsx" +# PathToSaveCSV=r"//tower/tempspeed" + +con = fdb.connect( + host='localhost', database=r'u:\MEDICUS 3\data\medicus.FDB', + user='sysdba', password='masterkey',charset='WIN1250') + +# Create a Cursor object that operates in the context of Connection con: +cur = con.cursor() + +# import openpyxl module +import openpyxl +import xlwings as xw +wb = openpyxl.Workbook() +sheet = wb.active +# wb.save("sample.xlsx") + + +#Načtení dokladů pojišťovny +# cur.execute("select davka, rok, typ, poj,dokladh.rodcis,prijmeni||', '||jmeno, datose,kod,pocvyk,ddgn from dokladh " +# "join dokladd on dokladd.idhlav=dokladh.idhlav " +# "join kar on kar.rodcis=dokladh.rodcis " +# " order by datose desc;") # where dokladh.rodcis=7401270052 Schořálek +cur.execute("select davka, CAST(rok AS FLOAT) as rok, dokladh.typ, dokladh.poj,dokladh.rodcis,kar.prijmeni||', '||kar.jmeno as jmenokomplet,datose,kod,pocvyk,ddgn from dokladh " + "join dokladd on dokladh.idhlav=dokladd.idhlav " + "join kar on kar.rodcis=dokladh.rodcis " + "order by datose desc;") # Schořálek where dokladh.rodcis=7401270052 + +nacteno=cur.fetchall() +pocet_radku=len(nacteno) +print(len(nacteno)) + +sheet.title="Doklady pojišťovny" +sheet.append(["Dávka","Rok","Typ","Pojišťovna","Rodné číslo","Jméno","Datum výkonu","Kód","Počet","Dg."]) +#nacteno jsou výkony pro pojišťovnu +print("Zapisuji data do excelu") +for row in nacteno: + sheet.append(row) +wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname)) + +# autofilter +print("Aplikuji autofilter") +for ws in wb.worksheets: + # Get the maximum number of rows and columns + max_row = ws.max_row + max_column = ws.max_column + ws.auto_filter.ref = f"A1:{openpyxl.utils.get_column_letter(max_column)}{max_row}" + # ws.auto_filter.ref = ws.dimensions + +print("Aplikuji format datumu dd.mm.yyyy") +for row in ws.iter_rows(min_col=6, max_col=6): + for cell in row: + if cell.value: # Only format cells with values + cell.number_format = 'DD.MM.YY' + +print("aplikuji ohraničení") +from openpyxl.styles import Border,Side,Alignment,PatternFill,Font,numbers +#Definition of border +thin_border = Border(left=Side(style='thin'),right=Side(style='thin'),top=Side(style='thin'),bottom=Side(style='thin')) +#Definition of yellow fill +yellow_fill = PatternFill(start_color='FFFF00', # Yellow color code + end_color='FFFF00', + fill_type='solid') + + +min_row=1 +max_row=pocet_radku+1 +min_column=1 +max_column=10 +for row in ws.iter_rows(min_row=min_row,max_row=max_row,min_col=min_column,max_col=max_column): #(min_row=1, max_col=3, max_row=2): + for cell in row: + cell.border = Border(left=Side(style='thin'), + right=Side(style='thin'), + top=Side(style='thin'), + bottom=Side(style='thin')) + cell.alignment=Alignment(horizontal='center', vertical='center') + #Aplikace yellow line a bold jen na první řádek + if cell.row==1: + cell.fill=yellow_fill + cell.font = Font(bold=True) + # if cell.column in (2,4,5,7): #Aplikuji číselný formát '0' + # cell.number_format = '0' + if cell.column in (2,4,5,8): #Aplikuji textový formát '@' + cell.number_format = numbers.FORMAT_TEXT + cell.value=cell.value + + + +wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname)) + + + + +# Tento modul je pouze na autofit jednotlivych sloupcu na vsech listech workbooku +print("Aplikuji autofit") +file = os.path.join(PathToSaveCSV ,timestr+CSVname) +with xw.App(visible=False) as app: + wb = xw.Book(file) + for sheet in range(len(wb.sheets)): + ws = wb.sheets[sheet] + ws.autofit() + + wb.save() + wb.close() + + diff --git a/Reporty.py b/Reporty.py new file mode 100644 index 0000000..0bb1dd1 --- /dev/null +++ b/Reporty.py @@ -0,0 +1,101 @@ +import os +import fdb +import csv,time,pandas as pd +import openpyxl + + +PathToSaveCSV=r"z:\NextCloudOrdinace\Reporty" +timestr = time.strftime("%Y-%m-%d %H-%M-%S ") +CSVname="Pacienti.xlsx" +# PathToSaveCSV=r"//tower/tempspeed" + +con = fdb.connect( + host='localhost', database=r'm:\MEDICUS\data\medicus.FDB', + user='sysdba', password='masterkey',charset='WIN1250') + +# Create a Cursor object that operates in the context of Connection con: +cur = con.cursor() + +# import openpyxl module +import openpyxl +import xlwings as xw +wb = openpyxl.Workbook() +sheet = wb.active +# wb.save("sample.xlsx") + + + +#Načtení receptů +cur.execute("""select +kar.rodcis, +TRIM(kar.prijmeni) ||' '|| substring(kar.jmeno from 1 for 1) ||'.' as jmeno, +recept.datum, +TRIM(recept.lek) ||' '|| trim(recept.dop) as lek, +recept.expori AS Poc, +CASE + WHEN recept.opakovani is null THEN 1 + ELSE recept.opakovani + END AS OP, +recept.uhrada, +recept.dsig, +recept.NOTIFIKACE_KONTAKT as notifikace, +recept_epodani.erp, +recept_epodani.vystavitel_jmeno, +recept.atc, +recept.CENAPOJ, +recept.cenapac +from recept LEFT Join RECEPT_EPODANI on recept.id_epodani=recept_epodani.id +LEFT join kar on recept.idpac=kar.idpac +order by datum desc,erp desc""" +) +nacteno=cur.fetchall() +print(len(nacteno)) + +wb.create_sheet('Recepty',0) +sheet=wb['Recepty'] + +sheet.title="Recepty" +sheet.append(["Rodné číslo","Jméno","Datum vystavení","Název leku","Poč.","Op.","Úhr.","Da signa","Notifikace","eRECEPT","Vystavil","ATC","Cena pojišťovna","Cena pacient"]) + +for row in nacteno: + try: + sheet.append(row) + except: + continue + +wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname)) + + +# autofilter +for ws in wb.worksheets: + # Get the maximum number of rows and columns + max_row = ws.max_row + max_column = ws.max_column + ws.auto_filter.ref = f"A1:{openpyxl.utils.get_column_letter(max_column)}{max_row}" + # ws.auto_filter.ref = ws.dimensions + + + + + +wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname)) + + +# Tento modul je pouze na autofit jednotlivych sloupcu na vsech listech workbooku +file = os.path.join(PathToSaveCSV ,timestr+CSVname) +with xw.App(visible=False) as app: + wb = xw.Book(file) + for sheet in range(len(wb.sheets)): + ws = wb.sheets[sheet] + ws.autofit() + + # centrování receptů + sheet = wb.sheets['Recepty'] + for sloupec in ["C:C", "E:E", "F:F", "G:G", "I:I", "M:M", "N:N"]: + sheet.range(sloupec).api.HorizontalAlignment = 3 # 3 = Center + + + wb.save() + wb.close() + + diff --git a/Reporty_jeden_pacient.py b/Reporty_jeden_pacient.py new file mode 100644 index 0000000..5c5f7ce --- /dev/null +++ b/Reporty_jeden_pacient.py @@ -0,0 +1,98 @@ +import os +import fdb +import csv,time,pandas as pd +import openpyxl + + +PathToSaveCSV=r"u:\NextCloudOrdinace\Reporty" +timestr = time.strftime("%Y-%m-%d %H-%M-%S ") +CSVname="Pacienti.xlsx" +# PathToSaveCSV=r"//tower/tempspeed" + +con = fdb.connect( + host='localhost', database=r'u:\MEDICUS 3\data\medicus.FDB', + user='sysdba', password='masterkey',charset='WIN1250') + +#Server=192.168.1.10 +#Path=M:\Medicus\Data\Medicus.fdb + +# Create a Cursor object that operates in the context of Connection con: +cur = con.cursor() + +#rc hledaného pacienta +rc="495220197" + +# import openpyxl module +import openpyxl +import xlwings as xw +wb = openpyxl.Workbook() +sheet = wb.active +# wb.save("sample.xlsx") + +#Načtení očkování +cur.execute("select ockzaz.datum,latka from registr join kar on registr.idpac=kar.idpac join ockzaz on registr.idpac=ockzaz.idpac " + "where rodcis=?",(rc,)) +nacteno=cur.fetchall() +print(len(nacteno)) + +sheet.title="Očkování" +sheet.append(["Očkování"]) +#nacteno jsou ockovani +for row in nacteno: + row_datum=row[0].strftime('%d-%m-%Y') #date_obj.strftime('%Y-%m-%d') + sheet.append((row_datum.strip()+chr(9)+row[1].strip(),)) + +sheet.column_dimensions['A'].width = 100 # Column A +wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname)) + + +#RECEPTY +wb.create_sheet('Recepty',0) +sheet=wb['Recepty'] + +#Načtení receptů +cur.execute("""select +recept.datum,recept.lek,recept.dop,recept.expori AS Poc, +CASE + WHEN recept.opakovani is null THEN 1 + ELSE recept.opakovani + END AS OP, +recept.dsig, +recept.NOTIFIKACE_KONTAKT as notifikace +from recept LEFT Join RECEPT_EPODANI on recept.id_epodani=recept_epodani.id +LEFT join kar on recept.idpac=kar.idpac where rodcis=? and recept.lek is not null +order by datum desc,erp desc """,(rc,)) + +nacteno=cur.fetchall() +print(len(nacteno)) + +sheet.title="Recepty" +sheet.append(["Recept"]) +#nacteno jsou ockovani +for row in nacteno: + row_datum=row[0].strftime('%d-%m-%Y') + if row[2]: + row_lek=row[1].strip()+" ("+row[2].strip()+")" + else: + row_lek = row[1].strip() + " ()" + row_pocet=str(row[3]).strip()+"x"+chr(9) + if row[4]: + row_opakovani="op:"+str(row[4]).strip()+"x"+chr(9) + else: + row_opakovani = "op:1x"+chr(9) + if row[5]: + row_dsig=row[5].strip()+chr(9) + else: + row_dsig="" + print(row_datum+row_lek+row_pocet+row_opakovani+row_dsig) + + sheet.append((row_datum,row_lek,row_pocet+row_opakovani+row_dsig,)) + +sheet.column_dimensions['A'].width = 12 # Column A +sheet.column_dimensions['B'].width = 50 # Column B +sheet.column_dimensions['C'].width = 50 # Column C +wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname)) + +wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname)) + + diff --git a/TestFileSizeZero.py b/TestFileSizeZero.py new file mode 100644 index 0000000..08cf173 --- /dev/null +++ b/TestFileSizeZero.py @@ -0,0 +1,68 @@ +import os + +# filename=r"u:\D1\Days\Stefajir\core\misc\draggable.png" +filename=r"u:\1.png" + +import ctypes +from ctypes import wintypes + + +def getfilesize(file_path): + # Get compressed size (if file is compressed) + file_size_high = wintypes.DWORD() + file_size_real = ctypes.windll.kernel32.GetFileSizeEx( + file_path, + ctypes.byref(file_size_high), + ) + return file_size_real + + +def get_real_file_size_win(file_path): + # Get cluster size (allocation unit) from the filesystem + drive = os.path.splitdrive(file_path)[0] + "\\" + sectors_per_cluster = wintypes.DWORD() + bytes_per_sector = wintypes.DWORD() + ctypes.windll.kernel32.GetDiskFreeSpaceW( + drive, + ctypes.byref(sectors_per_cluster), + ctypes.byref(bytes_per_sector), + None, + None, + ) + cluster_size = sectors_per_cluster.value * bytes_per_sector.value + + # Get compressed size (if file is compressed) + file_size_high = wintypes.DWORD() + file_size_low = ctypes.windll.kernel32.GetCompressedFileSizeW( + file_path, + ctypes.byref(file_size_high), + ) + # compressed_size = (file_size_high.value << 32) + file_size_low #.value + # + # # If not compressed, fall back to cluster-based allocation + # if compressed_size == 0: + # file_size = os.path.getsize(file_path) + # real_size = ((file_size + cluster_size - 1) // cluster_size) * cluster_size + # else: + # real_size = compressed_size + + return file_size_low + +# print(get_real_file_size_win(filename)) +print(getfilesize(filename)) + + + +# cesta=r"u:\d1" +# +# for root, dirs, files in os.walk(cesta): +# for file in files: +# soubor=os.path.join(root,file) +# print(soubor) +# realsize=get_real_file_size_win(soubor) +# print(realsize) +# # print(soubor,f"Real size on disk (Windows): {realsize} bytes") +# if realsize==0 or file[0]=="~" or file.upper()=="THUMBS.DB" or file.upper()=="DESCR.WD3": +# print(f"Deleting file {soubor}") +# os.remove(soubor) +# diff --git a/TestFileSizeZero1.py b/TestFileSizeZero1.py new file mode 100644 index 0000000..642f316 --- /dev/null +++ b/TestFileSizeZero1.py @@ -0,0 +1,44 @@ +import os,stat +filename=r"u:\1.png" +# filename=r"u:\D1\Days\Stefajir\core\misc\draggable.png" + + +def is_sparse_file_win(path): + try: + import ctypes + from ctypes import wintypes + + FILE_ATTRIBUTE_SPARSE_FILE = 0x00000200 + GetFileAttributes = ctypes.windll.kernel32.GetFileAttributesW + GetFileAttributes.argtypes = [wintypes.LPCWSTR] + GetFileAttributes.restype = wintypes.DWORD + + attrs = GetFileAttributes(path) + return attrs & FILE_ATTRIBUTE_SPARSE_FILE != 0 + except: + return False + + +# import mmap +# +# def is_memory_mapped_file(path): +# try: +# with open(path, 'r+b') as f: +# try: +# mmap.mmap(f.fileno(), 0) +# return True +# except: +# return False +# except OSError: +# return False + +# def is_windows_virtual_file(path): +# try: +# st = os.stat(path) +# # Check if it's a character or block device (common for virtual files) +# return stat.S_ISCHR(st.st_mode) or stat.S_ISBLK(st.st_mode) +# except (OSError, AttributeError): +# return False + + +print(is_sparse_file_win(filename)) \ No newline at end of file diff --git a/TestFileSizeZero2.py b/TestFileSizeZero2.py new file mode 100644 index 0000000..eff4de6 --- /dev/null +++ b/TestFileSizeZero2.py @@ -0,0 +1,41 @@ +import os +import ctypes as ct +import ctypes.wintypes as w + +NO_ERROR = 0 + +INVALID_FILE_SIZE = w.DWORD(0xFFFFFFFF).value +INVALID_FILE_ATTRIBUTES = w.DWORD(-1).value + +FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS = 0x00400000 + +# Helpers to raise exceptions on API failures. + +def filesizecheck(result, func, args): + if result == INVALID_FILE_SIZE and (err := ct.get_last_error()) != NO_ERROR: + raise ct.WinError(err) + return result + +def attributecheck(result, func, args): + if result == INVALID_FILE_ATTRIBUTES: + raise ct.WinError(ct.get_last_error()) + return result + +kernel32 = ct.WinDLL('kernel32', use_last_error=True) +GetCompressedFileSize = kernel32.GetCompressedFileSizeW +GetCompressedFileSize.argtypes = w.LPCWSTR, w.LPDWORD +GetCompressedFileSize.restype = w.DWORD +GetCompressedFileSize.errcheck = filesizecheck +GetFileAttributes = kernel32.GetFileAttributesW +GetFileAttributes.argtypes = w.LPCWSTR, +GetFileAttributes.restype = w.DWORD +GetFileAttributes.errcheck = attributecheck + +fullpath=r"u:\D1\Days\Stefajir\user\default.htm" +local_size = GetCompressedFileSize(fullpath, None) +attributes = GetFileAttributes(fullpath) +print(local_size) +print(attributes) +print(FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS) +if attributes & FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS and local_size != 0: + print(f'0x{attributes:08X} {local_size:6d} {fullpath}') \ No newline at end of file diff --git a/funkce.py b/funkce.py new file mode 100644 index 0000000..8520764 --- /dev/null +++ b/funkce.py @@ -0,0 +1,114 @@ +import os,fdb,datetime + +# conn = fdb.connect( +# dsn=r'localhost:u:\medicus 3\data\medicus.fdb', # Database path +# user='SYSDBA', # Username +# password="masterkey", # Password, +# charset="win1250") +# cur = conn.cursor() + +def zapis_file(vstupconnection,idpac,cesta,souborname,prvnizavorka,soubordate,souborfiledate,poznamka): + import funkce + cur=vstupconnection.cursor() + fileid = funkce.get_files_id(vstupconnection) + with open(os.path.join(cesta,souborname), 'rb') as f: + daticka = f.read() + query = "insert into files (id,iduzi,iddoctyp,typ,idpac,filename,body,datum,datsouboru,poznamka) values(?,?,?,?,?,?,?,?,?,?)" + cur.execute(query,(fileid,6,1,1,idpac,prvnizavorka+".pdf",daticka,soubordate,souborfiledate,poznamka[:99])) + vstupconnection.commit() + return fileid +def zapis_dekurs(vstupconnection, idpac, idodd, iduzi, idprac, idfile, filename, text, datumzpravy, + datumsouboru): + import funkce + dekursid = funkce.get_dekurs_id(vstupconnection) + cur = vstupconnection.cursor() + print("Funkce zapis_dekurs hlasí OK") + print("idpac", idpac) + print("idodd", idodd) + print("iduzi", iduzi) + print("idfile", idfile) + print("filename", filename) + print("text", text) + print("datumzpravy", datumzpravy) + print("datumsouboru", datumsouboru) + print("dekursid", dekursid) + +# rtf = r"""{\rtf1\ansi\ansicpg1250\uc1\deff0\deflang1029{\info{\bookmarks "BOOKMARKNAME","Files:FILEID",9}}{\fonttbl{\f0\fnil\fcharset238 Arial;}{\f5\fnil\fcharset238 Symbol;}} +# {\colortbl ;\red0\green0\blue255;\red0\green128\blue0;\red0\green0\blue0;} +# {\stylesheet{\s0\fi0\li0\ql\ri0\sb0\sa0 Norm\'e1ln\'ed;}{\*\cs15\f0\fs20 Norm\'e1ln\'ed;}{\*\cs20\f0\i\fs20 Z\'e1hlav\'ed;}{\*\cs32\f0\ul\fs20\cf1 Odkaz;}} +# \uc1\pard\s0\plain\cs20\f0\i\fs20 P\'f8\'edlohy: {\*\bkmkstart 0}\plain\cs32\f0\ul\fs20\cf1 BOOKMARKNAME{\*\bkmkend 0}\par +# \pard\s0\plain\cs15\f0\fs20 \par +# } +# """ + rtf = r"""{\rtf1\ansi\ansicpg1250\uc1\deff0\deflang1029{\info{\bookmarks "BOOKMARKNAME","Files:FILEID",9}}{\fonttbl{\f0\fnil\fcharset238 Arial;}{\f5\fnil\fcharset238 Symbol;}} +{\colortbl ;\red0\green0\blue255;\red0\green128\blue0;\red0\green0\blue0;} +{\stylesheet{\s10\fi0\li0\ql\ri0\sb0\sa0 Vlevo;}{\*\cs15\f0\fs20 Norm\'e1ln\'ed;}{\*\cs20\f0\i\fs20 Z\'e1hlav\'ed;}{\*\cs22\f0\ul\fs20\cf1 Odkaz;}} +\uc1\pard\s10\plain\cs20\f0\i\fs20 P\'f8\'edlohy:\par +\pard\s10{\*\bkmkstart 0}\plain\cs22\f0\ul\fs20\cf1 BOOKMARKNAME{\*\bkmkend 0}\par +\pard\s10\plain\cs15\f0\fs20 \par +} + + """ + # id idpac filename body docid typ datum iddoctyp poznamka idpac=2 iduzi=2 datsouboru id_edokument ext_id + encodedbookmark = funkce.convert_to1250(filename) + print("Encodedbookmark", encodedbookmark) + rtf = rtf.replace("BOOKMARKNAME", encodedbookmark) + rtf = rtf.replace("FILEID", str(idfile)) + rtf = rtf.replace("TEXTENTER", text) + datumzapisu = datetime.datetime.now().date() + caszapisu = datetime.datetime.now().time() + print("Datumzapisu", datumzapisu) + print("Caszapisu", caszapisu) + print("RTF", rtf) + cur.execute("insert into dekurs (id,idpac,idodd,iduzi,idprac,datum,cas,dekurs) values(?,?,?,?,?,?,?,?)", + (dekursid, idpac, idodd, iduzi, idprac, datumzapisu, caszapisu, rtf)) + vstupconnection.commit() + + +def convert_to1250(retezec): + retezec=retezec.encode("cp1250") + retezec=str(retezec)[2:] + retezec = retezec[:-1] + retezec=retezec.replace(r"\x",r"\'") + return retezec + + +# x=convert_to1250("Příloha") +# print(x,len(x)) + +def get_dekurs_id(connection): + try: + query = "SELECT GEN_ID(Gen_Dekurs, 1) FROM RDB$DATABASE" + cur = connection.cursor() + cur.execute(query) + newid=cur.fetchone()[0] + print("Funkce GET_DEKURS_ID přiřadila nové ID:",newid) + return(newid) + except: + print("Funkce GET_DEKURS_ID nepřiřadila nové ID") + return(None) + +def get_files_id(connection): + try: + query = "SELECT GEN_ID(Gen_Files, 1) FROM RDB$DATABASE" + cur=connection.cursor() + cur.execute(query) + newid=cur.fetchone()[0] + print(newid) + return(newid) + except: + return(None) + +def get_idpac(rodnecislo,connection): + try: + query = "SELECT idpac,prijmeni FROM kar where rodcis=?" + cur = connection.cursor() + cur.execute(query,(rodnecislo,)) + tmp_nacteno=cur.fetchone() + tmp_id = tmp_nacteno[0] + tmp_jmeno=tmp_nacteno[1] + print(f"Pacient s rodným číslem {rodnecislo} má ID {tmp_id} a jméno {tmp_jmeno}") + return (tmp_id) + except: + return(None) + diff --git a/funkce1.py b/funkce1.py new file mode 100644 index 0000000..edd6aac --- /dev/null +++ b/funkce1.py @@ -0,0 +1,38 @@ +import os, fdb,re +import datetime + + +def prejmenuj_chybny_soubor(souborname,cesta): + if souborname[0]!="♥": + soubornovy = "♥" + souborname + os.rename(os.path.join(cesta,souborname),os.path.join(cesta,soubornovy)) + + +def kontrola_struktury(souborname,connection): + if souborname.endswith('.pdf'): + #kontrola struktury + pattern=re.compile(r'(\d{9,10}) (\d{4}-\d{2}-\d{2}) (\w+, \w.+?) \[(.+?)\] \[(.*?)\]') + match=pattern.search(souborname) + # print(souborname) + vpohode=True + if match and len(match.groups())==5: + datum=match.group(2) + try: + datum_object = datetime.datetime.strptime(datum,"%Y-%m-%d").date() + # print(datum_object) + except: + vpohode=False + return vpohode + cur = connection.cursor() + cur.execute("select count(*) from kar where rodcis=?", (match.group(1),)) + row = cur.fetchone()[0] + if row!=1: + vpohode = False + return vpohode + else: + vpohode=False + return vpohode + else: + vpohode=False + return vpohode + return vpohode \ No newline at end of file diff --git a/p01.py b/p01.py new file mode 100644 index 0000000..83f2c90 --- /dev/null +++ b/p01.py @@ -0,0 +1,94 @@ +import os,re,fdb,time +import datetime +import funkce + +con = fdb.connect( + host='localhost', database=r'u:\MEDICUS 3\data\medicus.FDB', + user='sysdba', password='masterkey',charset='WIN1250') + +# Create a Cursor object that operates in the context of Connection con: +cur = con.cursor() + +cesta=r"u:\Dropbox\!!!Days\Downloads Z230\Dokumentace" + + +for soubor in os.listdir(cesta): + if soubor.endswith('.pdf'): + #kontrola struktury + pattern=re.compile(r'(\d{9,10}) (\d{4}-\d{2}-\d{2}) (\w+, \w.+?) \[(.+?)\] \[(.+?)\]') + match=pattern.search(soubor) + print(soubor) + chyba=False + if match and len(match.groups())==5: + rc=match.group(1) + datum=match.group(2) + try: + datum_object = datetime.datetime.strptime(datum,"%Y-%m-%d").date() + print(datum_object) + except: + chyba=True + jmeno=match.group(3) + prvnizavorka=match.group(4) + druhazavorka = match.group(5) + else: chyba=True + if chyba: + soubornovy="♥"+soubor + if soubor[0]!="♥": + os.rename(os.path.join(cesta,soubor),os.path.join(cesta,soubornovy)) + continue + + #zde máme všechno OK rc, datum_object,jmeno,prvnizavorka,druhazavorka + + #Nyní kontrola délky jména soubor, akceptáno max 100 znamk + + + + print(soubor) + filetoinsert=os.path.join(cesta,soubor) + print(time.ctime(os.path.getctime(filetoinsert))) + datumsouboru=datetime.datetime.fromtimestamp(os.path.getctime(filetoinsert)) + with open(filetoinsert, 'rb') as f: + daticka = f.read() + + #newid generation + newfileid = funkce.get_files_id(con) + if newfileid is None: + print("Chyba") + continue + + newdekursid=funkce.get_dekurs_id(con) + if newdekursid is None: + print("Chyba") + continue + + idpac=funkce.get_idpac(rc,con) + if idpac is None: + print("Chyba") + continue + + print("Bude vlozeno:") + print(f"""id: {newfileid} + iddoctyp: 2 + idpac: {idpac} + filename: {soubor} + datum: {datum_object} + datsouboru: {datumsouboru} + poznamka: {prvnizavorka} {druhazavorka}""") + + print(datum_object.strftime('%Y-%m-%d')) + #id idpac filename body docid typ datum iddoctyp poznamka idpac=2 iduzi=2 datsouboru id_edokument ext_id + query = "insert into files (id,iduzi,iddoctyp,typ,idpac,filename,body,datum,datsouboru,poznamka) values(?,?,?,?,?,?,?,?,?,?)" + # cur.execute(query,(newfileid,6,1,1,idpac,prvnizavorka+".pdf",daticka,datum_object,datumsouboru,druhazavorka[:99])) + cur.execute(query, (newfileid, 6, 1, 1, 9742, prvnizavorka + ".pdf", daticka, datum_object, datumsouboru, druhazavorka[:99])) + con.commit() + + #zapis do dekurzu + # funkce.zapis_dekurs(con, idpac, 2, 6, 2, newfileid, prvnizavorka, "test text", datetime.date(2023, 10, 15),datetime.date(2023, 10, 15)) + funkce.zapis_dekurs(con, 9742, 2, 6, 2, newfileid, datum_object.strftime('%Y-%m-%d')+" "+ prvnizavorka+ ": "+druhazavorka, "test text", datetime.date(2023, 10, 15), + datetime.date(2023, 10, 15)) + + #vymazat zpracovaný soubor + # os.remove(filetoinsert) +con.close() + + diff --git a/s03soubory.py b/s03soubory.py new file mode 100644 index 0000000..94182a3 --- /dev/null +++ b/s03soubory.py @@ -0,0 +1,242 @@ +import os,shutil,fdb,time +import re,datetime,funkce + +# Connect to the Firebird database +conn = fdb.connect( + dsn=r'localhost:u:\medicus 3\data\medicus.fdb', # Database path + user='SYSDBA', # Username + password="masterkey", # Password, + charset="win1250") + +# cesta=r"u:\Dropbox\!!!Days\Downloads Z230\Dokumentace" +cesta=r"u:\NextcloudOrdinace\Dokumentace_ke_zpracování" +# cestazpracovana=r"u:\Dropbox\!!!Days\Downloads Z230\Dokument" +cestazpracovana=r"z:\NextcloudOrdinace\Dokumentace_zpracovaná" + + +def restore_files_for_import(retezec): + drop=r"u:\Dropbox\!!!Days\Downloads Z230\Dokumentace" + next=r"u:\NextcloudOrdinace\Dokumentace_ke_zpracování" + + # Check if the directory exists + if not os.path.exists(drop): + print(f"The directory '{drop}' does not exist.") + return + + # Iterate over all files and subdirectories in the directory + for item in os.listdir(drop): + item_path = os.path.join(drop, item) + + # If it's a file or a symbolic link, delete it + if os.path.isfile(item_path) or os.path.islink(item_path): + os.unlink(item_path) + print(f"Deleted file: {item_path}") + + # If it's a directory, delete it recursively + elif os.path.isdir(item_path): + shutil.rmtree(item_path) + print(f"Deleted directory: {item_path}") + + for item in os.listdir(next): + item_path = os.path.join(next, item) + # If it's a file finished with PDF, copy it + if os.path.isfile(item_path) and item_path.endswith(".pdf") and retezec in item_path: + shutil.copy(item_path,os.path.join(drop,item)) + print(f"Copied file: {item_path}") + + +def kontrola_rc(rc,connection): + cur = connection.cursor() + cur.execute("select count(*),idpac from kar where rodcis=? group by idpac",(rc,)) + row = cur.fetchone() + if row: + return row[1] + else: + return False + +def kontrola_struktury(souborname,connection): + if souborname.endswith('.pdf'): + #kontrola struktury + pattern=re.compile(r'(^\d{9,10}) (\d{4}-\d{2}-\d{2}) (\w+, \w.+?) \[(.+?)\] \[(.*?)\]') + match=pattern.search(souborname) + # print(souborname) + vpohode=True + if match and len(match.groups())==5: + datum=match.group(2) + try: + datum_object = datetime.datetime.strptime(datum,"%Y-%m-%d").date() + # print(datum_object) + except: + vpohode=False + return vpohode + cur = connection.cursor() + cur.execute("select count(*) from kar where rodcis=?", (match.group(1),)) + row = cur.fetchone()[0] + if row!=1: + vpohode = False + return vpohode + else: + vpohode=False + return vpohode + else: + vpohode=False + return vpohode + return vpohode + +def vrat_info_o_souboru(souborname, connection): + pattern = re.compile(r'(^\d{9,10}) (\d{4}-\d{2}-\d{2}) (\w+, \w.+?) \[(.+?)\] \[(.*?)\]') + match = pattern.search(souborname) + rc = match.group(1) + datum = datetime.datetime.strptime(match.group(2), "%Y-%m-%d").date() + jmeno = match.group(3) + prvnizavorka = match.group(4) + druhazavorka = match.group(5) + cur=connection.cursor() + cur.execute("select idpac from kar where rodcis=?",(rc,)) + idpac = cur.fetchone()[0] + datumsouboru = datetime.datetime.fromtimestamp(os.path.getctime(os.path.join(cesta,souborname))) + return (rc,idpac,datum,jmeno,prvnizavorka,druhazavorka,souborname,datumsouboru) + +def prejmenuj_chybny_soubor(souborname,cesta): + if souborname[0]!="♥": + soubornovy = "♥" + souborname + os.rename(os.path.join(cesta,souborname),os.path.join(cesta,soubornovy)) + + + +# print(kontrola_struktury(ss)) +# info=vrat_info_o_souboru(ss) +# print(kontrola_rc(info[0],conn)) + +# restore_files_for_import("") +# restore_files_for_import("346204097") + +info=[] +for soubor in os.listdir(cesta): + print(soubor) + if kontrola_struktury(soubor,conn): + info.append(vrat_info_o_souboru(soubor,conn)) + # os.remove(os.path.join(cesta,soubor)) + else: + prejmenuj_chybny_soubor(soubor,cesta) + +info = sorted(info, key=lambda x: (x[0], x[1])) +print(info) + +skupiny={} +for row in info: + skupiny[row[0]]=[] +for row in info: + skupiny[row[0]].append(row) +# print(skupiny) + +# rtf = r"""{\rtf1\ansi\ansicpg1250\uc1\deff0\deflang1029{\info{\bookmarks BOOKMARKNAMES }}{\fonttbl{\f0\fnil\fcharset238 Arial;}{\f5\fnil\fcharset238 Symbol;}} +# {\colortbl ;\red0\green0\blue255;\red0\green128\blue0;\red0\green0\blue0;} +# {\stylesheet{\s10\fi0\li0\ql\ri0\sb0\sa0 Vlevo;}{\*\cs15\f0\fs20 Norm\'e1ln\'ed;}{\*\cs20\f0\i\fs20 Z\'e1hlav\'ed;}{\*\cs22\f0\ul\fs20\cf1 Odkaz;}} +# \uc1\pard\s10\plain\cs20\f0\i\fs20 P\'f8\'edlohy:\par +# \pard\s10{\*\bkmkstart 0}\plain\cs22\f0\ul\fs20\cf1 BOOKMARKNAMESTEXT{\*\bkmkend 0}\par +# \pard\s10\plain\cs15\f0\fs20 \par +# }""" + +rtf = r"""{\rtf1\ansi\ansicpg1250\uc1\deff0\deflang1029{\info{\bookmarks BOOKMARKNAMES }}{\fonttbl{\f0\fnil\fcharset238 Arial;}{\f5\fnil\fcharset238 Symbol;}} +{\colortbl ;\red0\green0\blue255;\red0\green128\blue0;\red0\green0\blue0;} +{\stylesheet{\s10\fi0\li0\ql\ri0\sb0\sa0 Vlevo;}{\*\cs15\f0\fs20 Norm\'e1ln\'ed;}{\*\cs20\f0\i\fs20 Z\'e1hlav\'ed;}{\*\cs22\f0\ul\fs20\cf1 Odkaz;}} +\uc1\pard\s10\plain\cs20\f0\i\fs20 P\'f8\'edlohy:\par +BOOKMARKSTEXT +\pard\s10\plain\cs15\f0\fs20 \par +}""" + +for key in skupiny.keys(): + rtf = r"""{\rtf1\ansi\ansicpg1250\uc1\deff0\deflang1029{\info{\bookmarks BOOKMARKNAMES }}{\fonttbl{\f0\fnil\fcharset238 Arial;}{\f5\fnil\fcharset238 Symbol;}} +{\colortbl ;\red0\green0\blue255;\red0\green128\blue0;\red0\green0\blue0;} +{\stylesheet{\s10\fi0\li0\ql\ri0\sb0\sa0 Vlevo;}{\*\cs15\f0\fs20 Norm\'e1ln\'ed;}{\*\cs20\f0\i\fs20 Z\'e1hlav\'ed;}{\*\cs22\f0\ul\fs20\cf1 Odkaz;}} +\uc1\pard\s10\plain\cs20\f0\i\fs20 Vlo\'9eena skenovan\'e1 dokumentace:\par +BOOKMARKSTEXT +\pard\s10\plain\cs15\f0\fs20\par +}""" + + + # if key=="8257300425": #346204097 + if True: + prvnibookmark=True + print(key,len(skupiny[key])) + cislo=9 + poradi=0 + bookmark="" + bookmarks="" + for row in skupiny[key]: + # print(row) + pacid=row[1] + filename=row[6] + + + for attempt in range(3): + try: + # Replace this with the command that might raise an error + if not os.path.exists(os.path.join(cestazpracovana,row[6])): + shutil.move(os.path.join(cesta,row[6]), os.path.join(cestazpracovana,row[6])) + print("Command succeeded!") + break # Exit the loop if the command succeeds + else: + now = datetime.datetime.now() + datetime_string = now.strftime("%Y-%m-%d %H-%M-%S") + print(os.path.join(cestazpracovana,row[6][:-4]+" "+datetime_string+".pdf")) + shutil.move(os.path.join(cesta,row[6]),os.path.join(cestazpracovana,row[6][:-4]+" "+datetime_string+".pdf")) + print("Command succeeded!") + break # Exit the loop if the command succeeds + except Exception as e: + print(f"Attempt {attempt + 1} failed: {e}") + if attempt < 3 - 1: + print(f"Retrying in {5} seconds...") + time.sleep(5) + else: + print("Max retries reached. Command failed.") + Problem_s_ulozenim=True + + if Problem_s_ulozenim: + print("Problem s ulozenim",row[6]) + break + + fileid=funkce.zapis_file(vstupconnection=conn, idpac=row[1], + cesta=cesta, souborname=row[6], prvnizavorka=row[4], + soubordate=row[2], souborfiledate=row[7], poznamka=row[5]) + + filename=funkce.convert_to1250(filename) + print("Encodedfilename", filename) + filenameforbookmark=row[2].strftime('%Y-%m-%d')+" "+row[4]+": "+row[5] + bookmark=bookmark+'"'+filenameforbookmark+'","Files:'+str(fileid)+'",'+str(cislo)+";" + cislo+=7 + # print(bookmark) + if prvnibookmark: + bookmarks=bookmarks+r'\pard\s10{\*\bkmkstart '+str(poradi)+r"}\plain\cs22\f0\ul\fs20\cf1 "+filenameforbookmark+r"{\*\bkmkend "+str(poradi)+r"}\par" + prvnibookmark=False + else: + bookmarks=bookmarks+r'\pard\s10{\*\bkmkstart '+str(poradi)+r"}" + filenameforbookmark + r"{\*\bkmkend " + str(poradi) + r"}\par" + if not Problem_s_ulozenim: + bookmark=bookmark[:-1] + # bookmarks=bookmarks[:-2] + print(bookmark) + print(bookmarks) + + rtf = rtf.replace("BOOKMARKNAMES", bookmark) + rtf=rtf.replace("BOOKMARKSTEXT",bookmarks) + print(rtf) + dekursid = funkce.get_dekurs_id(conn) + datumzapisu = datetime.datetime.now().date() + caszapisu = datetime.datetime.now().time() + cur=conn.cursor() + cur.execute("insert into dekurs (id,iduzi,idprac,idodd,idpac,datum,cas,dekurs)" + " values(?,?,?,?,?,?,?,?)", + (dekursid,6,2,2, row[1],datumzapisu,caszapisu, rtf)) + conn.commit() + # rtf = rtf.replace("FILEID", str(idfile)) + #Zde zapisujeme soubor + # fileid=funkce.zapis_file(conn,row[1],cesta,row[6],row[4],row[2],row[7],row[5]) + # zapis_dekurs(vstupconnection, idpac, idodd, iduzi, idprac, idfile, filename, text, datumzpravy,datumsouboru) + # return (rc, idpac, datum, jmeno, prvnizavorka, druhazavorka, souborname, datumsouboru) + + # Zde zapisujeme dekurs + # text=row[2].strftime("%Y-%m-%d")+" "+row[4].strip()+": "+row[5].strip() + # funkce.zapis_dekurs(conn, row[1], 2, 6, 2, fileid, text, text, row[7], row[2]) + # os.remove(os.path.join(cesta, soubor)) +