Repository navigation
Expand file tree
/
Copy pathMainWindow.py
More file actions
404 lines (337 loc) · 14.1 KB
/
Copy pathMainWindow.py
File metadata and controls
404 lines (337 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
from PyQt6.QtWidgets import QMainWindow, QApplication, QPushButton, QHBoxLayout, QListWidgetItem, QLabel, QComboBox
from PyQt6.uic import loadUi
from PyQt6 import QtCore
import sys
import os, subprocess, platform
from os import sep
from datetime import datetime
import dropbox as Dropbox
from dropbox.files import WriteMode
from pathlib import Path
import shutil
from SQL import executeScriptsFromFile as RunScript
from docxtpl import DocxTemplate
import json
from ListBoxes.label_PhotoClone import label_PhotoClone
from ListBoxes.ListBoxes import ListBoxAddresses, ListBoxEmails, ListBoxTelephones, ListBoxReferringDoctors
from ListBoxes.ListBoxes import ListBoxSearchablePatientsWithPhoto
from Dialogs.DoctorsDialog import DoctorsDialog
from Dialogs.LettersDialog import LettersDialog
from ListBoxes.CDropLabel import dropLabel
from GoogleDriveFunctions import *
INFO_PATHS = ["%APPDATA%\Dropbox\info.json",
"%LOCALAPPDATA%\Dropbox\info.json", " ~/.dropbox/info.json"]
APP_PATH = "/Apps/Patient Handler"
class MainUI(QMainWindow):
def __init__(self):
super(MainUI, self).__init__()
loadUi('MainWindow.ui', self)
self.patientID = -1
self.locationID = -1
# Photo label
self.childListBoxes = {} # stores dict of the boxes
self.addSearhablePatientListBox()
self.addPatientButtons()
self.addPatientListBoxes()
self.fillComboBoxLocations()
self.dropLabel=dropLabel(self)
self.gridLayout_Right.addWidget(self.dropLabel)
self.actionDoctors_Show.triggered.connect(self.showDoctors)
self.actionLetters_Show.triggered.connect(self.showLetters)
self.comboBoxLocation.activated.connect(self.ComboBoxLocationsChanged)
self.dbx = Dropbox.Dropbox(
'ABC')
def showDoctors(self):
doctorsDialog = DoctorsDialog(self)
doctorsDialog.exec()
def showLetters(self):
lettersDialog = LettersDialog(self)
lettersDialog.exec()
def updateDoctorItem(self,ID):
self.childListBoxes['REFERRING_DOCTORS'].RowEditedSignalled(ID)
def deleteDoctorItem(self,ID):
self.childListBoxes['REFERRING_DOCTORS'].fillBox()
@QtCore.pyqtSlot(int)
def patientChanged(self, ID):
self.setPatientID(ID)
for k,v in self.childListBoxes.items(): v.fillBox()
print('Patient ID set, ',self.patientID)
def addSearhablePatientListBox(self):
#Photo for locations
self.location_photo=label_PhotoClone(self, "LOCATIONS")
#Combobox for locations
self.comboBoxLocation=QComboBox(self)
f = self.comboBoxLocation.font()
f.setPointSize(27) # sets the size to 27
self.comboBoxLocation.setFont(f)
#add to hlayout
self.horizontalLayout_Top.addWidget(self.location_photo)
self.horizontalLayout_Top.addWidget(self.comboBoxLocation)
hlayout=QHBoxLayout()
self.searchablePatientList = ListBoxSearchablePatientsWithPhoto(self, "PATIENTS")
self.verticalLayout_Top.addLayout(hlayout)
self.verticalLayout_Top.addLayout(self.searchablePatientList)
self.searchablePatientList.list.itemChangedSignal.connect(self.patientChanged)
self.patientChanged(self.searchablePatientList.list.ID)
def getListBox(self,type):
match type:
case 'ADDRESSES':
return ListBoxAddresses(self,'ADDRESSES')
case 'EMAILS':
return ListBoxEmails(self,'ADDRESSES')
case 'TELEPHONES':
return ListBoxTelephones(self,'TELEPHONES')
case 'REFERRING_DOCTORS':
return ListBoxReferringDoctors(self,'REFERRING_DOCTORS')
case other:
print('No type found in getListBox')
return None
return None
def addPatientListBoxes(self):
# Add the patient listboxes to verticalLayoutLeft
lst=('ADDRESSES','TELEPHONES','EMAILS','REFERRING_DOCTORS')
for l in lst:
label=QLabel(self); label.setText(str.capitalize((l.replace('_',' '))+":"))
box=self.getListBox(l)
self.verticalLayoutLeft.addWidget(label)
self.verticalLayoutLeft.addWidget(box);self.childListBoxes.update({l:box})
def addPatientButtons(self):
# Letter buttons
self.button_newPatient = QPushButton(self);
self.button_newPatient.setText('NEW PATIENT')
self.button_Prescription = QPushButton(self);
self.button_Prescription.setText('PRESCRIPTION')
self.button_FollowUp = QPushButton(self);
self.button_FollowUp.setText('FOLLOW UP')
self.button_ShowFolder=QPushButton(self)
self.button_ShowFolder.setText('SHOW FOLDER')
self.HLayout = QHBoxLayout()
self.HLayout.addWidget(self.button_newPatient)
self.HLayout.addWidget(self.button_FollowUp)
self.HLayout.addWidget(self.button_Prescription)
self.HLayout.addWidget(self.button_ShowFolder)
self.verticalLayout_Top.addLayout(self.HLayout)
self.button_newPatient.clicked.connect(self.NewLetter)
self.button_FollowUp.clicked.connect(self.FollowUpLetter)
self.button_Prescription.clicked.connect(self.PrescriptionLetter)
self.button_ShowFolder.clicked.connect(self.showFolder)
def setPatientID(self, ID):
self.patientID = ID
def getPatientFolder(self):
if self.patientID == -1: return None
items = self.searchablePatientList.list.selectedItems()
if len(items) > 0:
name = items[0].data(0)
id = self.patientID
return os.path.join(getAppPath(), name + " {PID" + str(id).zfill(6) + "}")
def getTimeStamp(self):
t = datetime.now()
return t.strftime('"%y-%m-%d %H%M"').replace('\"', "")
def fillComboBoxLocations(self):
self.comboBoxLocation.clear()
result = RunScript('SQL/All Locations.sql')
if result:
for i in result:
self.comboBoxLocation.addItem(i[1], i[0])
self.comboBoxLocation.setCurrentIndex(0) # set to first in list
self.ComboBoxLocationsChanged()
def ComboBoxLocationsChanged(self):
index = self.comboBoxLocation.currentIndex()
if index > -1:
self.locationID = self.comboBoxLocation.itemData(index)
self.location_photo.ID=self.locationID
self.location_photo.fillPhoto()
def fillPatients(self):
self.listWidgetPatients.clear()
result = RunScript('SQL/Patients lists/Patients Containing.sql', (self.lineEditName.text(),))
if result:
for i in result:
item = QListWidgetItem(i[1])
item.value = i[0] # the patient id
self.listWidgetPatients.addItem(item)
self.refreshMain()
def openWord(self, filepath):
if platform.system() == 'Darwin': # macOS
subprocess.call(('open', filepath))
elif platform.system() == 'Windows': # Windows
os.startfile(filepath)
else: # linux variants
subprocess.call(('xdg-open', filepath))
def uploadFile(self, filepath, destpath):
path = Path(filepath)
dest = Path(destpath)
d = "".join('/' + d for d in dest.joinpath(path.name).parts if d != sep)
with path.open('rb') as f:
metadata = self.dbx.files_upload(f.read(), d, WriteMode('overwrite'))
print(metadata.id)
print(d)
def copyFile(self, filepath, destpath, counter=0):
path = Path(filepath)
dest = Path(destpath)
try:
shutil.copyfile(path, dest)
except shutil.Error:
counter += 1
self.copyFile(filepath, destpath + " " + str(counter))
def safeCopyFile(self, filepath, destpath, dst=None):
"""Safely copy a file to the specified directory. If a file with the same name already
exists, the copied file name is altered to preserve both.
:param str file_path: Path to the file to copy.
:param str out_dir: Directory to copy the file into.
:param str dst: New name for the copied file. If None, use the name of the original
file.
"""
path = Path(filepath)
dest = Path(destpath)
name = dst or os.path.basename(dest)
dest_dir = os.path.dirname(dest)
if not os.path.exists(dest):
shutil.copy(path, dest)
return dest
else:
base, extension = os.path.splitext(name)
i = 1
while os.path.exists(os.path.join(dest_dir, '{} v{}{}'.format(base, i, extension))):
i += 1
shutil.copy(path, os.path.join(dest_dir, '{} v{}{}'.format(base, i, extension)))
return os.path.join(dest_dir, '{} v{}{}'.format(base, i, extension))
def formatAddress(self, s):
x = s.split(",")
x=[y.strip() for y in x]
return '\n'.join(x)
def getBasicContext(self):
context = {}
# date
context.update({'date': 'Dated: '+ datetime.now().strftime('%d-%m-%Y')})
# locatiion
if self.locationID > -1:
result = RunScript('SQL/Locations.sql', (self.locationID,))
if result:
y = dict(result.fetchall()[0])
context.update({'location': y.get('Name')})
context.update({'location_address': y.get('Address')})
# patient details
if self.patientID > -1:
# patients id
context.update({'patient_id':str(self.patientID).zfill(6)})
# personal details
result = RunScript('SQL/Details New Letter.sql', (self.patientID,))
if result:
y = result.fetchall()[0]
context.update({"name": y['Name'], "full_details": y['FullName'] + ", " + y['DOB']})
if y['NHS_NO']: context["full_details"] += "; NHS No: " + y['NHS_NO']
# Addresses
result = RunScript('SQL/Addresses Patient Used.sql', (self.patientID,))
addresses = []
if result:
for i in result:
addresses.append(self.formatAddress(i['TXT']))
if len(addresses) > 0:
a = '\n\n'.join(addresses)
context.update({'address': a})
# Telephone
result = RunScript('SQL/Tel Patient Used.sql', (self.patientID,))
tels = []
if result:
for i in result:
tels.append("t: " + i['TXT'])
if len(tels) > 0:
t = '\n'.join(tels)
context.update({'tel': t})
# Referring doctors
result = RunScript('SQL/Referring Doctors Patient Used.sql', (self.patientID,))
drs = []
if result:
for i in result:
drs.append(i['TXT'])
if len(drs) > 0:
d = "Cc'd" + "\n" + '\n'.join(drs)
context.update({'referring_doctors': d})
# Emails
result = RunScript('SQL/Emails Patient Used.sql', (self.patientID,))
emails = []
if result:
for i in result:
emails.append(i['TXT'])
if len(emails) > 0:
e = "Also by email:" + "\n" + '\n'.join(emails)
context.update({'emails': e})
return context
def Letter(self, type):
if self.patientID == -1: return
f = None
g = 'generic'
PID = "{" + str(self.patientID).zfill(6) + "}"
context = self.getBasicContext()
match type:
case 'NEW':
f = os.path.join("Letters", "NEW PATIENT LETTER.docx")
g = "new"
case "FOLLOW_UP":
f = os.path.join("Letters", "FOLLOW UP PATIENT LETTER.docx")
g = "follow up"
case "PRESCRIPTION":
f = os.path.join("Letters", "PRESCRIPTION LETTER.docx")
g = "prescription"
case _:
return
Path(self.getPatientFolder()).mkdir(parents=True, exist_ok=True)
destpath = os.path.join(self.getPatientFolder(), self.getTimeStamp() + " " + g + " " + PID + '.docx')
print(destpath)
d = self.safeCopyFile(f, destpath)
doc = DocxTemplate(d)
doc.render(context)
doc.save(d)
self.openWord(d)
new_letter_patient(self.patientID,context)
def NewLetter(self):
self.Letter('NEW')
def FollowUpLetter(self):
self.Letter('FOLLOW_UP')
def PrescriptionLetter(self):
self.Letter("PRESCRIPTION")
def showFolder(self):
showFolder(self.patientID)
# Drag and drop
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
event.ignore()
def dropEvent(self, event):
# TODO: check the file is fully downloaded from Dropbox
if self.patientID == -1: return
PID = "{" + str(self.patientID).zfill(6) + "}"
files = [u.toLocalFile() for u in event.mimeData().urls()]
for f in files:
name = os.path.basename(f)
base, extension = os.path.splitext(name)
dest = os.path.join(self.getPatientFolder(), self.getTimeStamp() + " " + base + " " + PID + extension)
self.safeCopyFile(f, dest)
print(dest)
def find_dbx_path(path):
""" Try and open info.json to retreive Dropbox path """
try:
with open(os.path.expandvars(path), "r") as f:
data = json.load(f)
print(data.values)
return list(data.values())[0]["path"]
except:
pass
""" Look for file """
def findDBPath():
for path in INFO_PATHS:
dbx_path = find_dbx_path(path)
# if path found stop searching
if dbx_path:
break
if dbx_path is None: dbx_path = "/Users/William/Dropbox (Personal)"
return dbx_path
def getAppPath():
return findDBPath() + APP_PATH
if __name__ == '__main__':
print(getAppPath())
app = QApplication(sys.argv)
ui = MainUI()
ui.show()
app.exec()