-
Notifications
You must be signed in to change notification settings - Fork 3
/
bp.py
executable file
·1540 lines (1376 loc) · 66.3 KB
/
bp.py
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# File: bp.py
# Copyright 2006-2017 Tibor Csernay
# This file is part of SuperPatient.
# SuperPatient is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# SuperPatient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with SuperPatient; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
from collections import OrderedDict
import datetime
import getpass
import logging
import mailcap
import os
import sys
import wx
from superpatient import BaseApp, DBMixin, HelpMenuMixin, CancelableMixin
from superpatient import bills, normalize_filename, gen_title
from superpatient.bvr import gen_bvr_ref
import superpatient.customization as custo
from superpatient.customization import DATE_FMT, DEFAULT_CANTON, FULL_ADDRESS
from superpatient.models import (Patient, Consultation, Bill, Position, round_cts,
STATUS_OPENED, STATUS_PAYED, STATUS_PRINTED,
SEX_ALL, SEX_FEMALE, SEX_MALE,
BILL_TYPE_CONSULTATION, BILL_TYPE_MANUAL,
CANTONS)
from superpatient.ui.common import askyesno, show_info, show_db_warning, show_warning, show_error
from superpatient.ui import core, bill
from superpatient.signature import sign
logger = logging.getLogger(__name__)
FIX_PATIENT_DELAY = 500 # milliseconds
def show_invalid_amount(logger):
show_warning(logger, "Montant invalide")
def ask_confirm_printed_bvr():
return askyesno("Impression effectuée ?", "Avez-vous imprimé le BVR ?")
def ask_really_cancel():
return askyesno("Confirmation d'annulation",
"Voulez-vous vraiment annuler ?\n"
"Les données de cette consultation ne seront pas enregistrées.")
class MainFrame(DBMixin, HelpMenuMixin, core.MainFrame):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def on_activate(self, event):
if not event.Active:
return
self.cursor.execute("SELECT count(*) FROM patients")
self.patients_count.LabelText = str(self.cursor.fetchone()[0])
self.cursor.execute("SELECT count(*) FROM consultations")
self.consultations_count.LabelText = str(self.cursor.fetchone()[0])
self.Fit()
def on_manage_collaborators(self, event):
ManageCollaboratorsDialog(self).ShowModal()
def on_manage_tarifs(self, event):
ManageCostsDialog(self).ShowModal()
def on_manual_bill(self, event):
ManualBillDialog(self).ShowModal()
def on_manage_addresses(self, event):
ManageAddressesDialog(self).ShowModal()
def on_delete_data(self, event):
ManagePatientsDialog(self, mode='delete').ShowModal()
def on_dump_database(self, event):
filename = wx.FileSelector("Sauvegarde de la base de donnée", default_extension="*.sql", wildcard="Database files (*.sql)|*.sql", flags=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT).strip()
if filename:
os.system("mysqldump -u root SuperPatient > %s" % filename)
def on_restore_database(self, event):
filename = wx.FileSelector("Restauration de la base de donnée", default_extension="*.sql", wildcard="Database files (*.sql)|*.sql", flags=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST).strip()
if filename:
os.system("mysql -u root SuperPatient < %s" % filename)
def on_new_patient(self, event):
PatientDialog(self).ShowModal()
def on_search_patient(self, event):
ManagePatientsDialog(self, mode='patient').ShowModal()
def on_new_consultation(self, event):
ManagePatientsDialog(self, mode='new_consultation').ShowModal()
def on_search_consultation(self, event):
ManagePatientsDialog(self, mode='consultation').ShowModal()
class ManualBillDialog(DBMixin, CancelableMixin, core.ManualBillDialog):
MANUAL_ADDRESS = "Adresse manuelle"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
default_therapeute = ''
self.therapeutes = {}
self.cursor.execute("SELECT therapeute, login, entete FROM therapeutes")
for therapeute, login, entete in self.cursor:
if not entete.strip():
continue
if 'RCC' in entete:
name, rcc = [line for i, line in enumerate(entete.splitlines()) if i == 0 or line.startswith('RCC')]
rcc = rcc.replace('RCC', '').strip()
else:
name = entete
rcc = ''
firstname, lastname = name.split(' ', 1)
self.therapeutes[therapeute] = firstname, lastname, rcc
if login == LOGIN:
default_therapeute = therapeute
self.therapeute.Set(sorted(self.therapeutes.keys()))
self.therapeute.StringSelection = default_therapeute
self.on_select_therapeute(None)
self.addresses = OrderedDict({self.MANUAL_ADDRESS: None})
self.cursor.execute("SELECT id, title, firstname, lastname, complement, street, zip, city FROM addresses ORDER BY id")
for row in self.cursor:
self.addresses[row[0]] = row[1:]
self.prefilled_address.Set(list(self.addresses.keys()))
self.Bind(wx.EVT_ACTIVATE, self.on_activate, self)
self.Bind(wx.EVT_CHAR_HOOK, self.on_tab, self.remark)
def on_activate(self, event):
self.Fit()
self.title.SetFocus()
def on_select_therapeute(self, event):
firstname, lastname, rcc = self.therapeutes[self.therapeute.StringSelection]
if rcc:
rcc = 'RCC ' + rcc
self.therapeute_address.Value = '{} {}\n{}\n\n{}'.format(firstname, lastname, rcc, FULL_ADDRESS)
def on_select_address(self, event):
if self.prefilled_address.StringSelection != self.MANUAL_ADDRESS:
title, firstname, lastname, complement, street, zip, city = self.addresses[self.prefilled_address.StringSelection]
self.title.Value = title or ''
self.firstname.Value = firstname
self.lastname.Value = lastname
self.complement.Value = complement or ''
self.street.Value = street
self.zip.Value = zip
self.city.Value = city
def on_generate(self, event):
therapeute = self.therapeute.StringSelection
t_firstname, t_lastname, t_rcc = self.therapeutes[therapeute]
title = self.title.Value.strip()
firstname = self.firstname.Value.strip()
lastname = self.lastname.Value.strip()
complement = self.complement.Value.strip()
street = self.street.Value.strip()
zip = self.zip.Value.strip()
city = self.city.Value.strip()
identifier = self.prefilled_address.StringSelection
if identifier == self.MANUAL_ADDRESS:
name = [firstname]
if lastname:
name.append(lastname)
identifier = '_'.join(name)
now = datetime.datetime.now()
ts = now.strftime('%Y-%m-%d_%H')
filename = normalize_filename('%s_%sh.pdf' % (identifier.replace(' ', '_'), ts))
reason = self.reason.Value.strip()
try:
amount = float(self.amount.Value.strip())
except ValueError:
show_invalid_amount(logger)
return
remark = self.remark.Value.strip()
try:
bv_ref = gen_bvr_ref(self.cursor, identifier[0], identifier[1], now)
bill = Bill(type=BILL_TYPE_MANUAL,
bv_ref=bv_ref,
payment_method='BVR',
status=STATUS_OPENED,
timestamp=datetime.datetime.now(),
author_id=therapeute,
author_lastname=t_lastname,
author_firstname=t_firstname,
author_rcc=t_rcc,
title=title,
lastname=lastname,
firstname=firstname,
complement=complement,
street=street,
zip=zip,
city=city,
comment=remark)
bill.save(self.cursor)
# and positions
price_cts = round_cts(int(amount * 100))
pos = Position(id_bill=bill.id, position_date=bill.timestamp.date(),
tarif_code='999', tarif_description=reason,
quantity=1, price_cts=price_cts, total_cts=price_cts)
pos.save(self.cursor)
bill.positions.append(pos)
except:
show_db_warning(logger, 'update')
return
bills.manuals(filename, [bill])
cmd, cap = mailcap.findmatch(mailcap.getcaps(), 'application/pdf', 'view', filename)
os.system(cmd)
if ask_confirm_printed_bvr():
bill.status = STATUS_PRINTED
bill.save(self.cursor)
class ManageCollaboratorsDialog(DBMixin, CancelableMixin, core.ManageCollaboratorsDialog):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.SetTitle("Gérer les collaborateurs")
try:
self.cursor.execute("""SELECT therapeute, login, entete FROM therapeutes ORDER BY therapeute""")
self.collaborators = list(self.cursor)
except:
show_db_warning(logger, 'read')
return
self.index = None
self.prev_index = None
self.populate()
def populate(self):
self.collaborators_list.DeleteAllItems()
for therapeute, login, entete in self.collaborators:
self.collaborators_list.Append((therapeute, login, entete))
for c in range(self.collaborators_list.ColumnCount):
self.collaborators_list.SetColumnWidth(c, wx.LIST_AUTOSIZE)
self.on_deselect_collaborator(None)
self.Layout()
self.Fit()
def on_deselect_collaborator(self, event):
self.prev_index = self.index
self.index = None
self.therapeute.Value = ''
self.login.Value = ''
self.address_header.Value = ''
self.add_btn.Show()
self.change_btn.Hide()
self.remove_btn.Disable()
self.Layout()
def on_select_collaborator(self, event):
selected = self.collaborators_list.GetFirstSelected()
self.therapeute.Value = ''
self.login.Value = ''
self.address_header.Value = ''
if selected != self.prev_index:
self.index = selected
therapeute, login, address_header = self.collaborators[self.index]
self.therapeute.Value = therapeute
self.login.Value = login
self.address_header.Value = address_header
self.add_btn.Hide()
self.change_btn.Show()
self.remove_btn.Enable()
self.Layout()
else:
self.collaborators_list.Select(selected, False)
def on_add_collaborator(self, event):
if self.index is not None:
return
therapeute = self.therapeute.Value.strip()
login = self.login.Value.strip()
address_header = self.address_header.Value.strip()
try:
self.cursor.execute("""INSERT INTO therapeutes (therapeute, login, entete) VALUES (%s, %s, %s)""",
[therapeute, login, address_header])
self.collaborators.append((therapeute, login, address_header))
except:
show_db_warning(logger, 'update')
self.populate()
def on_change_collaborator(self, event):
if self.index is None:
return
therapeute = self.therapeute.Value.strip()
login = self.login.Value.strip()
address_header = self.address_header.Value.strip()
try:
key, _, _ = self.collaborators[self.index]
self.cursor.execute("""UPDATE therapeutes SET therapeute = %s, login = %s, entete = %s WHERE therapeute = %s""",
[therapeute, login, address_header, key])
self.collaborators[self.index] = (therapeute, login, address_header)
except:
show_db_warning(logger, 'update')
self.populate()
def on_remove_collaborator(self, event):
if self.index is None:
return
try:
key, _, _ = self.collaborators[self.index]
self.cursor.execute("""DELETE FROM therapeutes WHERE therapeute = %s""", [key])
del self.collaborators[self.index]
except:
show_db_warning(logger, 'delete')
self.populate()
class ManageCostsDialog(DBMixin, CancelableMixin, core.ManageCostsDialog):
def __init__(self, parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.SetTitle("Gérer les tarifs")
try:
self.cursor.execute("""SELECT code, description, unit_price_cts FROM tarifs ORDER BY code, description""")
self.costs = list(self.cursor)
except:
show_db_warning(logger, 'read')
return
self.index = None
self.prev_index = None
self.populate()
def populate(self):
self.costs_list.DeleteAllItems()
for code, description, unit_price_cts in self.costs:
self.costs_list.Append((code, description or '', '%7.2f' % (unit_price_cts/100.) if unit_price_cts is not None else ''))
for c in range(self.costs_list.ColumnCount):
self.costs_list.SetColumnWidth(c, wx.LIST_AUTOSIZE if c == 1 else wx.LIST_AUTOSIZE_USEHEADER)
self.on_deselect_cost(None)
self.Layout()
self.Fit()
def on_deselect_cost(self, event):
self.prev_index = self.index
self.index = None
self.code.Value = ''
self.description.Value = ''
self.price.Value = ''
self.add_btn.Show()
self.change_btn.Hide()
self.remove_btn.Disable()
self.Layout()
def on_select_cost(self, event):
selected = self.costs_list.GetFirstSelected()
self.code.Value = ''
self.description.Value = ''
self.price.Value = ''
if selected != self.prev_index:
self.index = selected
code, description, unit_price_cts = self.costs[self.index]
self.code.Value = code
self.description.Value = description or ''
self.price.Value = '%0.2f' % (unit_price_cts/100.) if unit_price_cts is not None else ''
self.add_btn.Hide()
self.change_btn.Show()
self.remove_btn.Enable()
self.Layout()
else:
self.costs_list.Select(selected, False)
def _get_values(self):
code = self.code.Value.strip()
description = self.description.Value.strip() or None
unit_price_cts = self.price.Value.strip() or None
if unit_price_cts is not None:
try:
unit_price_cts = int(float(unit_price_cts) * 100)
except:
show_invalid_amount(logger)
return None
return [code, description, unit_price_cts]
def on_add_cost(self, event):
if self.index is not None:
return
values = self._get_values()
if values is None:
return
try:
self.cursor.execute("""INSERT INTO tarifs (code, description, unit_price_cts) VALUES (%s, %s, %s)""", values)
self.costs.append(values)
except:
show_db_warning(logger, 'update')
self.populate()
def on_change_cost(self, event):
if self.index is None:
return
values = self._get_values()
if values is None:
return
try:
old_value = self.costs[self.index]
self.cursor.execute("""UPDATE tarifs SET code = %s, description = %s, unit_price_cts = %s WHERE code = %s AND description = %s AND unit_price_cts = %s""",
values + list(old_value))
self.costs[self.index] = values
except:
show_db_warning(logger, 'update')
self.populate()
def on_remove_cost(self, event):
if self.index is None:
return
try:
old_value = self.costs[self.index]
self.cursor.execute("""DELETE FROM tarifs WHERE code = %s AND description = %s AND unit_price_cts = %s""", list(old_value))
del self.costs[self.index]
except:
show_db_warning(logger, 'delete')
self.populate()
class ManageAddressesDialog(DBMixin, CancelableMixin, core.ManageAddressesDialog):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.SetTitle("Gérer les adresses")
try:
self.cursor.execute("""SELECT id, title, firstname, lastname,
complement, street, zip, city
FROM addresses ORDER BY id""")
self.addresses = list(self.cursor)
except:
show_db_warning(logger, 'read')
return
self.index = None
self.prev_index = None
self.populate()
def populate(self):
self.addresses_list.DeleteAllItems()
for identifier, title, firstname, lastname, complement, street, zip, city in self.addresses:
self.addresses_list.Append((identifier, title or '', firstname, lastname,
(complement or '').replace('\n', ', '),
(street or '').replace('\n', ', '),
zip, city
))
size_key = wx.LIST_AUTOSIZE if self.addresses else wx.LIST_AUTOSIZE_USEHEADER
for c in range(self.addresses_list.ColumnCount):
self.addresses_list.SetColumnWidth(c, size_key)
self.on_deselect_address(None)
self.Layout()
self.Fit()
def on_deselect_address(self, event):
self.prev_index = self.index
self.index = None
self.reset_fields()
self.add_btn.Show()
self.change_btn.Hide()
self.remove_btn.Disable()
self.Layout()
def reset_fields(self):
self.identifier.Value = ''
self.title.Value = ''
self.firstname.Value = ''
self.lastname.Value = ''
self.complement.Value = ''
self.street.Value = ''
self.zip.Value = ''
self.city.Value = ''
def parse_fields(self):
return (self.identifier.Value.strip(),
self.title.Value.strip() or None,
self.firstname.Value.strip(),
self.lastname.Value.strip(),
self.complement.Value.strip() or None,
self.street.Value.strip(),
self.zip.Value.strip(),
self.city.Value.strip())
def on_select_address(self, event):
selected = self.addresses_list.GetFirstSelected()
self.reset_fields()
if selected != self.prev_index:
self.index = selected
identifier, title, firstname, lastname, complement, street, zip, city = self.addresses[self.index]
self.identifier.Value = identifier
self.title.Value = title or ''
self.firstname.Value = firstname
self.lastname.Value = lastname
self.complement.Value = complement or ''
self.street.Value = street
self.zip.Value = zip
self.city.Value = city
self.add_btn.Hide()
self.change_btn.Show()
self.remove_btn.Enable()
self.Layout()
else:
self.addresses_list.Select(selected, False)
def on_add_address(self, event):
if self.index is not None:
return
fields = self.parse_fields()
try:
self.cursor.execute("""INSERT INTO addresses
(id, title, firstname, lastname, complement, street, zip, city)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)""",
list(fields))
self.addresses.append(fields)
except:
show_db_warning(logger, 'update')
self.populate()
def on_change_address(self, event):
if self.index is None:
return
fields = self.parse_fields()
try:
key = self.addresses[self.index][0]
self.cursor.execute("""UPDATE addresses
SET id = %s, title = %s,
firstname = %s, lastname = %s,
complement = %s, street = %s,
zip = %s, city = %s
WHERE id = %s""",
list(fields) + [key])
self.addresses[self.index] = fields
except:
show_db_warning(logger, 'update')
self.populate()
def on_remove_address(self, event):
if self.index is None:
return
try:
key = self.addresses[self.index][0]
self.cursor.execute("""DELETE FROM addresses WHERE id = %s""", [key])
del self.addresses[self.index]
except:
show_db_warning(logger, 'delete')
self.populate()
class ManagePatientsDialog(DBMixin, CancelableMixin, core.ManagePatientsDialog):
def __init__(self, parent, mode, *args, **kwargs):
self.mode = mode
titles = dict(delete="Base de patients - Suppression de données",
patient="Voir ou modifier la fiche d'un patient",
consultation="Voir ou modifier les consultations d'un patient",
new_consultation="Base de patients")
assert self.mode in titles
super().__init__(parent, *args, **kwargs)
self.SetTitle(titles[self.mode])
self.show_patient_btn.Show(self.mode == 'patient')
self.modify_patient_btn.Show(self.mode == 'patient')
self.delete_patient_btn.Show(self.mode == 'delete')
self.show_consultations_btn.Show(self.mode in ('delete', 'consultation'))
self.new_consultation_btn.Show(self.mode == 'new_consultation')
self.display_consultations_btn.Show(self.mode == 'new_consultation')
self.Fit()
def get_selected_patient_id(self):
selected = self.patients.GetFirstSelected()
return self.results[selected] if selected != -1 else None
def open_patient(self, readonly):
id_patient = self.get_selected_patient_id()
if id_patient is not None:
PatientDialog(self, id_patient, readonly).ShowModal()
self.on_search_patient(None)
def on_search_patient(self, event):
try:
self.cursor.execute("""SELECT id, sex, nom, prenom, (SELECT count(*) FROM consultations WHERE id = patients.id)
FROM patients
WHERE nom LIKE %s AND prenom LIKE %s
ORDER BY nom""",
[self.lastname.Value.strip(), self.firstname.Value.strip()])
except:
show_db_warning(logger, 'search')
self.results = []
self.patients.DeleteAllItems()
for id, sex, nom, prenom, n_consult in self.cursor:
self.patients.Append((sex, nom, prenom))
self.results.append(id)
for c in range(self.patients.ColumnCount):
self.patients.SetColumnWidth(c, wx.LIST_AUTOSIZE)
def on_show_patient(self, event):
self.open_patient(True)
def on_modify_patient(self, event):
self.open_patient(False)
def on_new_consultation(self, event):
id_patient = self.get_selected_patient_id()
if id_patient is not None:
ConsultationDialog(self, id_patient, readonly=False).ShowModal()
def on_show_consultations(self, event):
id_patient = self.get_selected_patient_id()
if id_patient is not None:
ManageConsultationsDialog(self, id_patient, self.mode).ShowModal()
def on_delete_patient(self, event):
id_patient = self.get_selected_patient_id()
if id_patient is not None:
try:
self.cursor.execute("""SELECT sex, nom, prenom, date_naiss
FROM patients
WHERE id = %s""",
[id_patient])
sex, nom, prenom, date_naiss = self.cursor.fetchone()
except:
show_db_warning(logger, 'search')
return
if askyesno("Suppression",
"Supprimer définitivement\n"
"{} {} {}, né(e) le {}\n"
"ainsi que toutes ses consultations ?"
.format(sex, prenom, nom, date_naiss.strftime(DATE_FMT))):
try:
self.cursor.execute("DELETE FROM bills WHERE id_patient = %s", [id_patient])
self.cursor.execute("DELETE FROM consultations WHERE id = %s", [id_patient])
self.cursor.execute("DELETE FROM patients WHERE id = %s", [id_patient])
show_info(logger, "Patient(e) {} {} supprimé(e) de la base".format(prenom, nom))
except:
show_db_warning(logger, 'delete')
self.on_search_patient(None)
def on_display_consultations(self, event):
id_patient = self.get_selected_patient_id()
if id_patient is not None:
AllConsultationsDialog(self, id_patient).ShowModal()
class ManageConsultationsDialog(DBMixin, CancelableMixin, core.ManageConsultationsDialog):
def __init__(self, parent, id_patient, mode, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.id_patient = id_patient
self.mode = mode
assert self.mode in ('delete', 'consultation')
self.delete_consult_btn.Show(self.mode == 'delete')
self.delete_bill_btn.Show(self.mode == 'delete')
self.show_btn.Show(self.mode == 'consultation')
self.modify_btn.Show(self.mode == 'consultation')
self.show_all_btn.Show(self.mode == 'consultation')
try:
self.cursor.execute("""SELECT nom, prenom, sex, therapeute, date_naiss
FROM patients WHERE id = %s""", [self.id_patient])
nom, prenom, sex, therapeute, date_naiss = self.cursor.fetchone()
except:
show_db_warning(logger, 'read')
return
if self.mode == 'delete':
self.SetTitle("Supprimer une consultation de %s %s" % (sex, nom))
else:
self.SetTitle("Afficher une consultation de %s %s" % (sex, nom))
self.patient.LabelText = "{} {} {}\nNaissance: {}\nThérapeute: {}".format(sex, prenom, nom, date_naiss, therapeute)
self.update_list()
self.Layout()
self.Fit()
def update_list(self):
try:
self.cursor.execute("""SELECT consultations.id_consult, date_consult, therapeute, MC, bills.id, bills.payment_date
FROM consultations
LEFT OUTER JOIN bills ON consultations.id_consult = bills.id_consult
WHERE consultations.id=%s
ORDER BY date_consult DESC""",
[self.id_patient])
except:
show_db_warning(logger, 'show')
self.results = []
self.consultations.DeleteAllItems()
for id_consult, date_consult, therapeute, MC, bill_id, payment_date in self.cursor:
index = self.consultations.Append((date_consult, therapeute or '', MC))
if bill_id is None:
# No bill at all, usually the consultation was offered
self.consultations.SetItemTextColour(index, wx.Colour(0, 128, 0))
elif payment_date is None:
self.consultations.SetItemTextColour(index, wx.Colour(128, 0, 0))
self.results.append(id_consult)
self.consultations.SetColumnWidth(0, wx.LIST_AUTOSIZE)
self.consultations.SetColumnWidth(1, wx.LIST_AUTOSIZE_USEHEADER)
self.consultations.SetColumnWidth(2, wx.LIST_AUTOSIZE)
def get_selected_consult_id(self):
selected = self.consultations.GetFirstSelected()
return self.results[selected] if selected != -1 else None
def open_consultation(self, readonly):
id_consult = self.get_selected_consult_id()
if id_consult is not None:
ConsultationDialog(self, self.id_patient, id_consult, readonly=readonly).ShowModal()
def on_delete_consultation(self, event):
id_consult = self.get_selected_consult_id()
if id_consult is not None:
if askyesno("Suppression", "Supprimer définitivement cette consultation ?"):
try:
self.cursor.execute("DELETE FROM bills WHERE id_consult = %s", [id_consult])
self.cursor.execute("DELETE FROM consultations WHERE id_consult=%s", [id_consult])
show_info(logger, "Consultation supprimée de la base")
except:
show_db_warning(logger, 'delete')
self.update_list()
def on_delete_bill(self, event):
id_consult = self.get_selected_consult_id()
if id_consult is not None:
if askyesno("Suppression", "Supprimer définitivement la facture de cette consultation ?"):
try:
self.cursor.execute("DELETE FROM bills WHERE id_consult = %s", [id_consult])
show_info(logger, "Facture supprimée de la base")
except:
show_db_warning(logger, 'delete')
self.update_list()
def on_show_consultation(self, event):
self.open_consultation(True)
def on_modify_consultation(self, event):
self.open_consultation(False)
def on_show_all_consultations(self, event):
AllConsultationsDialog(self, self.id_patient).ShowModal()
class AllConsultationsDialog(DBMixin, CancelableMixin, core.AllConsultationsDialog):
def __init__(self, parent, id_patient, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.id_patient = id_patient
try:
patient = Patient.load(self.cursor, self.id_patient)
except:
logger.debug("id_patient: %r", self.id_patient)
show_db_warning(logger, 'show')
return
html = ["""
<html>
<head>
<style>
.date {{ color: red; }}
.unpaid {{ color: darkred; }}
.offered {{ color: darkgreen; }}
h3 {{ color: blue; }}
.important {{ color: darkblue; }}
body {{ font-family: sans-serif; font-size: small; line-height: 1.0; }}
h1, h2, h3 {{ margin-top: 1ex; margin-bottom: 1ex; }}
div {{ white-space: pre-line; }}
</style>
</head>
<body>
<h1>{sex} {prenom} {nom}, {date_naiss}</h1>
<h3>Antécédents personnels</h3>
<div>{ATCD_perso}</div>
<h3>Antécédents familiaux</h3>
<div>{ATCD_fam}</div>
<h2 class="important">Important</h2>
<div>{important}</div>
<h3>Assurance complémentaire</h3>
<div>{ass_compl}</div>
""".format(**patient.__dict__)]
for consult in Consultation.yield_all(self.cursor, where=dict(id=patient.id), order='-date_consult'):
html += filter(None, [
"<hr/><h2 class='date'>********** Consultation du {} **********</h2>".format(consult.date_consult),
("<h3 class='unpaid'>!!!!! Non-payé !!!!!</h3>" if consult.bill is not None and consult.bill.payment_date is None else
("<h3 class='offered'>----- Offerte -----</h3>" if consult.bill is None else None)),
"<h3>État général</h3><div>{}</div>".format(consult.EG) if consult.EG.strip() else None,
"<h3>Thérapeute</h3><div>{}</div>".format(consult.therapeute) if consult.therapeute else None,
"<h3>Motif : {}</h3><div>{}</div>".format(("accident" if consult.MC_accident else "maladie"), consult.MC),
"<h3>Thorax</h3><div>{}</div>".format(consult.APT_thorax) if consult.APT_thorax.strip() else None,
"<h3>Abdomen</h3><div>{}</div>".format(consult.APT_abdomen) if consult.APT_abdomen.strip() else None,
"<h3>Tête et cou</h3><div>{}</div>".format(consult.APT_tete) if consult.APT_tete.strip() else None,
"<h3>Membres supérieurs</h3><div>{}</div>".format(consult.APT_MS) if consult.APT_MS.strip() else None,
"<h3>Membres inférieurs</h3><div>{}</div>".format(consult.APT_MI) if consult.APT_MI.strip() else None,
"<h3>Neuro, vascul, dermato, endocrino, lymph</h3><div>{}</div>".format(consult.APT_system) if consult.APT_system.strip() else None,
"<h3>Anamnèse ostéopathique</h3><div>{}</div>".format(consult.A_osteo) if consult.A_osteo.strip() else None,
"<h3>Examen physique</h3><div>{}</div>".format(consult.exam_phys) if consult.exam_phys.strip() else None,
"<h3>Traitement</h3><div>{}</div>".format(consult.traitement) if consult.traitement.strip() else None,
"<h3>Examens paracliniques</h3><div>{}</div>".format(consult.exam_pclin) if consult.exam_pclin.strip() else None,
"<h3>Remarques</h3><div>{}</div>".format(consult.divers) if consult.divers.strip() else None,
])
html.append("</body></html>")
self.html.SetPage('\n'.join(html), "")
class FixPatientAddressDialog(CancelableMixin, wx.Dialog):
def __init__(self, parent, patient):
super().__init__(parent)
self.patient = patient
self.street = wx.TextCtrl(self, wx.ID_ANY, patient.street or '')
self.zip = wx.TextCtrl(self, wx.ID_ANY, patient.zip or '')
self.city = wx.TextCtrl(self, wx.ID_ANY, patient.city or '')
self.canton = wx.Choice(self, wx.ID_ANY, choices=CANTONS)
self.canton.StringSelection = patient.canton or DEFAULT_CANTON
self.ok_btn = wx.Button(self, wx.ID_ANY, "OK")
self.cancel_btn = wx.Button(self, wx.ID_ANY, "Annuler")
if self.patient.adresse is None:
address = '\n'.join((self.patient.street or '',
(self.patient.zip or '') + ' ' + (self.patient.city or ''),
self.patient.canton or ''))
else:
address = self.patient.adresse
if not address:
address = "\nAucune adresse\n"
sizer = wx.GridBagSizer(wx.VERTICAL)
sizer.Add(wx.StaticText(self, wx.ID_ANY, "Veuillez préciser l'adresse du patient.\n\nInformation existante:\n%s" % address), (0, 0), (1, 3), wx.CENTER | wx.ALL, 5)
sizer.Add(wx.StaticText(self, wx.ID_ANY, "Rue"), (1, 0), (1, 1), wx.LEFT, 5)
sizer.Add(self.street, (1, 1), (1, 2), wx.EXPAND | wx.RIGHT, 5)
sizer.Add(wx.StaticText(self, wx.ID_ANY, "NPA/Localité"), (2, 0), (1, 1), wx.LEFT, 5)
sizer.Add(self.zip, (2, 1), (1, 1), wx.EXPAND | wx.RIGHT, 5)
sizer.Add(self.city, (2, 2), (1, 1), wx.EXPAND | wx.RIGHT, 5)
sizer.Add(wx.StaticText(self, wx.ID_ANY, "Canton"), (3, 0), (1, 1), wx.LEFT, 5)
sizer.Add(self.canton, (3, 1), (1, 2), wx.EXPAND | wx.RIGHT, 5)
sizer.Add(self.ok_btn, (4, 0), (1, 1), wx.CENTER | wx.ALL, 5)
sizer.Add(self.cancel_btn, (4, 2), (1, 1), wx.ALIGN_RIGHT | wx.CENTER | wx.ALL, 5)
self.SetSizer(sizer)
sizer.SetSizeHints(self)
self.Layout()
self.Fit()
self.Bind(wx.EVT_BUTTON, self.on_validate, self.ok_btn)
self.Bind(wx.EVT_BUTTON, self.on_close, self.cancel_btn)
self.Bind(wx.EVT_CLOSE, self.on_close, self)
def on_validate(self, event):
if (self.street.Value.strip() and self.zip.Value.strip() and self.city.Value.strip() and self.canton.StringSelection):
self.EndModal(1)
def on_close(self, event):
self.EndModal(0)
class FixPatientSexDialog(CancelableMixin, wx.Dialog):
def __init__(self, parent, patient):
super().__init__(parent)
self.patient = patient
self.male = wx.RadioButton(self, wx.ID_ANY, SEX_MALE, style=wx.RB_GROUP)
self.female = wx.RadioButton(self, wx.ID_ANY, SEX_FEMALE)
self.ok_btn = wx.Button(self, wx.ID_ANY, "OK")
self.cancel_btn = wx.Button(self, wx.ID_ANY, "Annuler")
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(wx.StaticText(self, wx.ID_ANY, "Veuillez préciser le sexe du patient"), 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, 5)
sizer.Add(self.male, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, 5)
sizer.Add(self.female, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, 5)
btn_sizer = wx.BoxSizer(wx.HORIZONTAL)
btn_sizer.Add(self.ok_btn, 0, 0, 0)
btn_sizer.AddStretchSpacer()
btn_sizer.Add(self.cancel_btn, 0, 0, 0)
sizer.Add(btn_sizer, 0, wx.EXPAND | wx.ALL, 5)
self.SetSizer(sizer)
sizer.SetSizeHints(self)
self.Layout()
self.Fit()
self.Bind(wx.EVT_BUTTON, self.on_validate, self.ok_btn)
self.Bind(wx.EVT_BUTTON, self.on_close, self.cancel_btn)
self.Bind(wx.EVT_CLOSE, self.on_close, self)
def on_validate(self, event):
if self.male.Value:
self.EndModal(1)
elif self.female.Value:
self.EndModal(2)
def on_close(self, event):
self.EndModal(0)
class FixPatientMixin:
def fix_patient(self, update_ui=False):
changed = False
if self.patient.adresse is not None or not self.patient.canton:
with FixPatientAddressDialog(self, self.patient) as dlg:
if dlg.ShowModal():
self.patient.street = dlg.street.Value.strip()
self.patient.zip = dlg.zip.Value.strip()
self.patient.city = dlg.city.Value.strip()
self.patient.canton = dlg.canton.StringSelection
if update_ui:
self.street.Value = self.patient.street
self.zip.Value = self.patient.zip
self.city.Value = self.patient.city
self.canton.StringSelection = self.patient.canton
self.patient.adresse = None
changed = True
if self.patient.sex not in SEX_ALL:
with FixPatientSexDialog(self, self.patient) as dlg:
result_code = dlg.ShowModal()
if result_code == 1:
self.patient.sex = SEX_MALE
if update_ui:
self.male.SetValue(True)
elif result_code == 2:
self.patient.sex = SEX_FEMALE
if update_ui:
self.female.SetValue(True)
changed = changed or (result_code != 0)
if changed:
self.patient.save(self.cursor)
class PatientDialog(FixPatientMixin, DBMixin, CancelableMixin, core.PatientDialog):
def __init__(self, parent, id_patient=None, readonly=False):
super().__init__(parent)
patient = self.patient = Patient.load(self.cursor, id_patient) if id_patient is not None else Patient()
self.readonly = readonly and patient
self.new_consultation_btn.Show(not self.patient)
self.save_btn.Show(not self.patient)
self.update_btn.Show(bool(self.patient and not self.readonly))
if patient:
title = "Fiche patient"
else:
title = "Nouveau patient"
self.SetTitle(title)
if patient.date_ouverture is None:
patient.date_ouverture = datetime.date.today()
# Setup fields value
self.patient_id.Value = str(patient.id) if patient else ''
if patient.sex in SEX_ALL:
{SEX_FEMALE: self.female, SEX_MALE: self.male}[patient.sex].SetValue(True)
self.lastname.Value = patient.nom or ''
self.firstname.Value = patient.prenom or ''
try:
self.cursor.execute("""SELECT therapeute, login FROM therapeutes ORDER BY therapeute""")
except:
show_db_warning(logger, 'read')
return
therapeutes = []
for t, login in self.cursor:
therapeutes.append(t)
if login == LOGIN and patient.therapeute is None:
patient.therapeute = t
self.therapeute.Set(therapeutes)
try:
self.therapeute.SetSelection(therapeutes.index(patient.therapeute))
except ValueError:
self.therapeute.SetSelection(wx.NOT_FOUND)
if patient.date_naiss:
self.birthdate.Value = patient.date_naiss.strftime(DATE_FMT)
else:
self.birthdate.Value = 'JJ.MM.AAAA'
self.birthdate.SelectAll()
self.opening_date.Value = patient.date_ouverture.strftime(DATE_FMT)
self.fixed_phone.Value = patient.phone or ''
self.mobile_phone.Value = patient.portable or ''
self.professional_phone.Value = patient.profes_phone or ''
self.email.Value = patient.mail or ''
if patient.adresse is None:
self.street.Value = patient.street or ''
self.zip.Value = patient.zip or ''
self.city.Value = patient.city or ''
self.canton.StringSelection = patient.canton or DEFAULT_CANTON
self.important.Value = patient.important or ''
self.main_doctor.Value = patient.medecin or ''
self.other_doctors.Value = patient.autre_medecin or ''
self.complementary_insurance.Value = patient.ass_compl or ''
self.profession.Value = patient.profes or ''
self.civil_status.Value = patient.etat or ''
self.sent_by.Value = patient.envoye or ''
self.remarks.Value = patient.divers or ''
self.highlight_missing_fields()
if self.readonly:
for widget in (self.female, self.male, self.firstname, self.lastname, self.therapeute, self.birthdate,
self.opening_date, self.fixed_phone, self.mobile_phone, self.professional_phone, self.email,
self.street, self.zip, self.city, self.canton, self.important,
self.main_doctor, self.other_doctors, self.complementary_insurance,
self.profession, self.civil_status, self.sent_by, self.remarks):
widget.Disable()