1
2 """GNUmed quick person search widgets.
3
4 This widget allows to search for persons based on the
5 critera name, date of birth and person ID. It goes to
6 considerable lengths to understand the user's intent from
7 her input. For that to work well we need per-culture
8 query generators. However, there's always the fallback
9 generator.
10 """
11
12
13
14 __version__ = "$Revision: 1.132 $"
15 __author__ = "K.Hilbert <Karsten.Hilbert@gmx.net>"
16 __license__ = 'GPL (for details see http://www.gnu.org/)'
17
18 import sys, os.path, glob, datetime as pyDT, re as regex, logging, webbrowser
19
20
21 import wx
22
23
24 if __name__ == '__main__':
25 sys.path.insert(0, '../../')
26 from Gnumed.pycommon import gmLog2
27 from Gnumed.pycommon import gmDispatcher, gmPG2, gmI18N, gmCfg, gmTools, gmDateTime, gmMatchProvider, gmCfg2
28 from Gnumed.business import gmPerson, gmKVK, gmSurgery
29 from Gnumed.wxpython import gmGuiHelpers, gmDemographicsWidgets, gmAuthWidgets, gmRegetMixin, gmPhraseWheel, gmEditArea
30 from Gnumed.wxGladeWidgets import wxgSelectPersonFromListDlg, wxgSelectPersonDTOFromListDlg, wxgMergePatientsDlg
31
32
33 _log = logging.getLogger('gm.person')
34 _log.info(__version__)
35
36 _cfg = gmCfg2.gmCfgData()
37
38 ID_PatPickList = wx.NewId()
39 ID_BTN_AddNew = wx.NewId()
40
41
45
155
157
172
174 for col in range(len(self.__cols)):
175 self._LCTRL_persons.InsertColumn(col, self.__cols[col])
176
178 self._LCTRL_persons.DeleteAllItems()
179
180 pos = len(persons) + 1
181 if pos == 1:
182 return False
183
184 for person in persons:
185 row_num = self._LCTRL_persons.InsertStringItem(pos, label = gmTools.coalesce(person['title'], ''))
186 self._LCTRL_persons.SetStringItem(index = row_num, col = 1, label = person['lastnames'])
187 self._LCTRL_persons.SetStringItem(index = row_num, col = 2, label = person['firstnames'])
188 self._LCTRL_persons.SetStringItem(index = row_num, col = 3, label = gmTools.coalesce(person['preferred'], ''))
189 self._LCTRL_persons.SetStringItem(index = row_num, col = 4, label = person.get_formatted_dob(format = '%x', encoding = gmI18N.get_encoding()))
190 self._LCTRL_persons.SetStringItem(index = row_num, col = 5, label = gmTools.coalesce(person['l10n_gender'], '?'))
191 label = u''
192 if person.is_patient:
193 enc = person.get_last_encounter()
194 if enc is not None:
195 label = u'%s (%s)' % (enc['started'].strftime('%x').decode(gmI18N.get_encoding()), enc['l10n_type'])
196 self._LCTRL_persons.SetStringItem(index = row_num, col = 6, label = label)
197 try: self._LCTRL_persons.SetStringItem(index = row_num, col = 7, label = person['match_type'])
198 except:
199 _log.exception('cannot set match_type field')
200 self._LCTRL_persons.SetStringItem(index = row_num, col = 7, label = u'??')
201
202 for col in range(len(self.__cols)):
203 self._LCTRL_persons.SetColumnWidth(col=col, width=wx.LIST_AUTOSIZE)
204
205 self._BTN_select.Enable(False)
206 self._LCTRL_persons.SetFocus()
207 self._LCTRL_persons.Select(0)
208
209 self._LCTRL_persons.set_data(data=persons)
210
212 return self._LCTRL_persons.get_item_data(self._LCTRL_persons.GetFirstSelected())
213
214
215
217 self._BTN_select.Enable(True)
218 return
219
221 self._BTN_select.Enable(True)
222 if self.IsModal():
223 self.EndModal(wx.ID_OK)
224 else:
225 self.Close()
226
228
240
242 for col in range(len(self.__cols)):
243 self._LCTRL_persons.InsertColumn(col, self.__cols[col])
244
246 self._LCTRL_persons.DeleteAllItems()
247
248 pos = len(dtos) + 1
249 if pos == 1:
250 return False
251
252 for rec in dtos:
253 row_num = self._LCTRL_persons.InsertStringItem(pos, label = rec['source'])
254 dto = rec['dto']
255 self._LCTRL_persons.SetStringItem(index = row_num, col = 1, label = dto.lastnames)
256 self._LCTRL_persons.SetStringItem(index = row_num, col = 2, label = dto.firstnames)
257 if dto.dob is None:
258 self._LCTRL_persons.SetStringItem(index = row_num, col = 3, label = u'')
259 else:
260 self._LCTRL_persons.SetStringItem(index = row_num, col = 3, label = dto.dob.strftime('%x').decode(gmI18N.get_encoding()))
261 self._LCTRL_persons.SetStringItem(index = row_num, col = 4, label = gmTools.coalesce(dto.gender, ''))
262
263 for col in range(len(self.__cols)):
264 self._LCTRL_persons.SetColumnWidth(col=col, width=wx.LIST_AUTOSIZE)
265
266 self._BTN_select.Enable(False)
267 self._LCTRL_persons.SetFocus()
268 self._LCTRL_persons.Select(0)
269
270 self._LCTRL_persons.set_data(data=dtos)
271
273 return self._LCTRL_persons.get_item_data(self._LCTRL_persons.GetFirstSelected())
274
275
276
278 self._BTN_select.Enable(True)
279 return
280
282 self._BTN_select.Enable(True)
283 if self.IsModal():
284 self.EndModal(wx.ID_OK)
285 else:
286 self.Close()
287
289
290 bdt_files = []
291
292
293
294 candidates = []
295 drives = 'cdefghijklmnopqrstuvwxyz'
296 for drive in drives:
297 candidate = drive + ':\Winacs\TEMP\BDT*.tmp'
298 candidates.extend(glob.glob(candidate))
299 for candidate in candidates:
300 path, filename = os.path.split(candidate)
301
302 bdt_files.append({'file': candidate, 'source': 'MCS/Isynet %s' % filename[-6:-4]})
303
304
305
306 src_order = [
307 ('explicit', 'return'),
308 ('workbase', 'append'),
309 ('local', 'append'),
310 ('user', 'append'),
311 ('system', 'append')
312 ]
313 xdt_profiles = _cfg.get (
314 group = 'workplace',
315 option = 'XDT profiles',
316 source_order = src_order
317 )
318 if xdt_profiles is None:
319 return []
320
321
322 src_order = [
323 ('explicit', 'return'),
324 ('workbase', 'return'),
325 ('local', 'return'),
326 ('user', 'return'),
327 ('system', 'return')
328 ]
329 for profile in xdt_profiles:
330 name = _cfg.get (
331 group = 'XDT profile %s' % profile,
332 option = 'filename',
333 source_order = src_order
334 )
335 if name is None:
336 _log.error('XDT profile [%s] does not define a <filename>' % profile)
337 continue
338 encoding = _cfg.get (
339 group = 'XDT profile %s' % profile,
340 option = 'encoding',
341 source_order = src_order
342 )
343 if encoding is None:
344 _log.warning('xDT source profile [%s] does not specify an <encoding> for BDT file [%s]' % (profile, name))
345 source = _cfg.get (
346 group = 'XDT profile %s' % profile,
347 option = 'source',
348 source_order = src_order
349 )
350 dob_format = _cfg.get (
351 group = 'XDT profile %s' % profile,
352 option = 'DOB format',
353 source_order = src_order
354 )
355 if dob_format is None:
356 _log.warning('XDT profile [%s] does not define a date of birth format in <DOB format>' % profile)
357 bdt_files.append({'file': name, 'source': source, 'encoding': encoding, 'dob_format': dob_format})
358
359 dtos = []
360 for bdt_file in bdt_files:
361 try:
362
363 dto = gmPerson.get_person_from_xdt (
364 filename = bdt_file['file'],
365 encoding = bdt_file['encoding'],
366 dob_format = bdt_file['dob_format']
367 )
368
369 except IOError:
370 gmGuiHelpers.gm_show_info (
371 _(
372 'Cannot access BDT file\n\n'
373 ' [%s]\n\n'
374 'to import patient.\n\n'
375 'Please check your configuration.'
376 ) % bdt_file,
377 _('Activating xDT patient')
378 )
379 _log.exception('cannot access xDT file [%s]' % bdt_file['file'])
380 continue
381 except:
382 gmGuiHelpers.gm_show_error (
383 _(
384 'Cannot load patient from BDT file\n\n'
385 ' [%s]'
386 ) % bdt_file,
387 _('Activating xDT patient')
388 )
389 _log.exception('cannot read patient from xDT file [%s]' % bdt_file['file'])
390 continue
391
392 dtos.append({'dto': dto, 'source': gmTools.coalesce(bdt_file['source'], dto.source)})
393
394 return dtos
395
397
398 pracsoft_files = []
399
400
401 candidates = []
402 drives = 'cdefghijklmnopqrstuvwxyz'
403 for drive in drives:
404 candidate = drive + ':\MDW2\PATIENTS.IN'
405 candidates.extend(glob.glob(candidate))
406 for candidate in candidates:
407 drive, filename = os.path.splitdrive(candidate)
408 pracsoft_files.append({'file': candidate, 'source': 'PracSoft (AU): drive %s' % drive})
409
410
411 src_order = [
412 ('explicit', 'append'),
413 ('workbase', 'append'),
414 ('local', 'append'),
415 ('user', 'append'),
416 ('system', 'append')
417 ]
418 fnames = _cfg.get (
419 group = 'AU PracSoft PATIENTS.IN',
420 option = 'filename',
421 source_order = src_order
422 )
423
424 src_order = [
425 ('explicit', 'return'),
426 ('user', 'return'),
427 ('system', 'return'),
428 ('local', 'return'),
429 ('workbase', 'return')
430 ]
431 source = _cfg.get (
432 group = 'AU PracSoft PATIENTS.IN',
433 option = 'source',
434 source_order = src_order
435 )
436
437 if source is not None:
438 for fname in fnames:
439 fname = os.path.abspath(os.path.expanduser(fname))
440 if os.access(fname, os.R_OK):
441 pracsoft_files.append({'file': os.path.expanduser(fname), 'source': source})
442 else:
443 _log.error('cannot read [%s] in AU PracSoft profile' % fname)
444
445
446 dtos = []
447 for pracsoft_file in pracsoft_files:
448 try:
449 tmp = gmPerson.get_persons_from_pracsoft_file(filename = pracsoft_file['file'])
450 except:
451 _log.exception('cannot parse PracSoft file [%s]' % pracsoft_file['file'])
452 continue
453 for dto in tmp:
454 dtos.append({'dto': dto, 'source': pracsoft_file['source']})
455
456 return dtos
457
472
474 """Load patient from external source.
475
476 - scan external sources for candidates
477 - let user select source
478 - if > 1 available: always
479 - if only 1 available: depending on search_immediately
480 - search for patients matching info from external source
481 - if more than one match:
482 - let user select patient
483 - if no match:
484 - create patient
485 - activate patient
486 """
487
488 dtos = []
489 dtos.extend(load_persons_from_xdt())
490 dtos.extend(load_persons_from_pracsoft_au())
491 dtos.extend(load_persons_from_kvks())
492
493
494 if len(dtos) == 0:
495 gmDispatcher.send(signal='statustext', msg=_('No patients found in external sources.'))
496 return None
497
498
499 if (len(dtos) == 1) and (dtos[0]['dto'].dob is not None):
500 dto = dtos[0]['dto']
501
502 curr_pat = gmPerson.gmCurrentPatient()
503 if curr_pat.connected:
504 key_dto = dto.firstnames + dto.lastnames + dto.dob.strftime('%Y-%m-%d') + dto.gender
505 names = curr_pat.get_active_name()
506 key_pat = names['firstnames'] + names['lastnames'] + curr_pat.get_formatted_dob(format = '%Y-%m-%d') + curr_pat['gender']
507 _log.debug('current patient: %s' % key_pat)
508 _log.debug('dto patient : %s' % key_dto)
509 if key_dto == key_pat:
510 gmDispatcher.send(signal='statustext', msg=_('The only external patient is already active in GNUmed.'), beep=False)
511 return None
512
513
514 if (len(dtos) == 1) and search_immediately:
515 dto = dtos[0]['dto']
516
517
518 else:
519 if parent is None:
520 parent = wx.GetApp().GetTopWindow()
521 dlg = cSelectPersonDTOFromListDlg(parent=parent, id=-1)
522 dlg.set_dtos(dtos=dtos)
523 result = dlg.ShowModal()
524 if result == wx.ID_CANCEL:
525 return None
526 dto = dlg.get_selected_dto()['dto']
527 dlg.Destroy()
528
529
530 idents = dto.get_candidate_identities(can_create=True)
531 if idents is None:
532 gmGuiHelpers.gm_show_info (_(
533 'Cannot create new patient:\n\n'
534 ' [%s %s (%s), %s]'
535 ) % (dto.firstnames, dto.lastnames, dto.gender, dto.dob.strftime('%x').decode(gmI18N.get_encoding())),
536 _('Activating external patient')
537 )
538 return None
539
540 if len(idents) == 1:
541 ident = idents[0]
542
543 if len(idents) > 1:
544 if parent is None:
545 parent = wx.GetApp().GetTopWindow()
546 dlg = cSelectPersonFromListDlg(parent=parent, id=-1)
547 dlg.set_persons(persons=idents)
548 result = dlg.ShowModal()
549 if result == wx.ID_CANCEL:
550 return None
551 ident = dlg.get_selected_person()
552 dlg.Destroy()
553
554 if activate_immediately:
555 if not set_active_patient(patient = ident):
556 gmGuiHelpers.gm_show_info (
557 _(
558 'Cannot activate patient:\n\n'
559 '%s %s (%s)\n'
560 '%s'
561 ) % (dto.firstnames, dto.lastnames, dto.gender, dto.dob.strftime('%x').decode(gmI18N.get_encoding())),
562 _('Activating external patient')
563 )
564 return None
565
566 dto.import_extra_data(identity = ident)
567 dto.delete_from_source()
568
569 return ident
570
572 """Widget for smart search for persons."""
573
575
576 try:
577 kwargs['style'] = kwargs['style'] | wx.TE_PROCESS_ENTER
578 except KeyError:
579 kwargs['style'] = wx.TE_PROCESS_ENTER
580
581
582
583 wx.TextCtrl.__init__(self, *args, **kwargs)
584
585 self.person = None
586
587 self.SetToolTipString (_(
588 'To search for a person type any of: \n'
589 '\n'
590 ' - fragment of last or first name\n'
591 " - date of birth (can start with '$' or '*')\n"
592 " - GNUmed ID of person (can start with '#')\n"
593 ' - exterenal ID of person\n'
594 '\n'
595 'and hit <ENTER>.\n'
596 '\n'
597 'Shortcuts:\n'
598 ' <F2>\n'
599 ' - scan external sources for persons\n'
600 ' <CURSOR-UP>\n'
601 ' - recall most recently used search term\n'
602 ' <CURSOR-DOWN>\n'
603 ' - list 10 most recently found persons\n'
604 ))
605
606
607 self.__person_searcher = gmPerson.cPatientSearcher_SQL()
608
609 self._prev_search_term = None
610 self.__prev_idents = []
611 self._lclick_count = 0
612
613 self._display_name()
614
615 self.__register_events()
616
617
618
620 name = u''
621
622 if self.person is not None:
623 name = self.person['description']
624
625 self.SetValue(name)
626
628
629 if not isinstance(ident, gmPerson.cIdentity):
630 return False
631
632
633 for known_ident in self.__prev_idents:
634 if known_ident['pk_identity'] == ident['pk_identity']:
635 return True
636
637 self.__prev_idents.append(ident)
638
639
640 if len(self.__prev_idents) > 10:
641 self.__prev_idents.pop(0)
642
643 return True
644
645
646
648 wx.EVT_CHAR(self, self.__on_char)
649 wx.EVT_SET_FOCUS(self, self._on_get_focus)
650 wx.EVT_KILL_FOCUS (self, self._on_loose_focus)
651 wx.EVT_TEXT_ENTER (self, self.GetId(), self.__on_enter)
652
654 """upon tabbing in
655
656 - select all text in the field so that the next
657 character typed will delete it
658 """
659 wx.CallAfter(self.SetSelection, -1, -1)
660 evt.Skip()
661
663
664
665
666
667
668
669
670
671
672 wx.CallAfter(self.SetSelection, 0, 0)
673
674 self._display_name()
675 self._remember_ident(self.person)
676
677 evt.Skip()
678
681
683 """True: patient was selected.
684 False: no patient was selected.
685 """
686 keycode = evt.GetKeyCode()
687
688
689 if keycode == wx.WXK_DOWN:
690 evt.Skip()
691 if len(self.__prev_idents) == 0:
692 return False
693
694 dlg = cSelectPersonFromListDlg(parent = wx.GetTopLevelParent(self), id = -1)
695 dlg.set_persons(persons = self.__prev_idents)
696 result = dlg.ShowModal()
697 if result == wx.ID_OK:
698 wx.BeginBusyCursor()
699 self.person = dlg.get_selected_person()
700 self._display_name()
701 dlg.Destroy()
702 wx.EndBusyCursor()
703 return True
704
705 dlg.Destroy()
706 return False
707
708
709 if keycode == wx.WXK_UP:
710 evt.Skip()
711
712 if self._prev_search_term is not None:
713 self.SetValue(self._prev_search_term)
714 return False
715
716
717 if keycode == wx.WXK_F2:
718 evt.Skip()
719 dbcfg = gmCfg.cCfgSQL()
720 search_immediately = bool(dbcfg.get2 (
721 option = 'patient_search.external_sources.immediately_search_if_single_source',
722 workplace = gmSurgery.gmCurrentPractice().active_workplace,
723 bias = 'user',
724 default = 0
725 ))
726 p = get_person_from_external_sources (
727 parent = wx.GetTopLevelParent(self),
728 search_immediately = search_immediately
729 )
730 if p is not None:
731 self.person = p
732 self._display_name()
733 return True
734 return False
735
736
737
738
739 evt.Skip()
740
742 """This is called from the ENTER handler."""
743
744
745 curr_search_term = self.GetValue().strip()
746 if curr_search_term == '':
747 return None
748
749
750 if self.person is not None:
751 if curr_search_term == self.person['description']:
752 return None
753
754
755 if self.IsModified():
756 self._prev_search_term = curr_search_term
757
758 self._on_enter(search_term = curr_search_term)
759
761 """This can be overridden in child classes."""
762
763 wx.BeginBusyCursor()
764
765
766 idents = self.__person_searcher.get_identities(search_term)
767
768 if idents is None:
769 wx.EndBusyCursor()
770 gmGuiHelpers.gm_show_info (
771 _('Error searching for matching persons.\n\n'
772 'Search term: "%s"'
773 ) % search_term,
774 _('selecting person')
775 )
776 return None
777
778 _log.info("%s matching person(s) found", len(idents))
779
780 if len(idents) == 0:
781 wx.EndBusyCursor()
782
783 dlg = gmGuiHelpers.c2ButtonQuestionDlg (
784 wx.GetTopLevelParent(self),
785 -1,
786 caption = _('Selecting patient'),
787 question = _(
788 'Cannot find any matching patients for the search term\n\n'
789 ' "%s"\n\n'
790 'You may want to try a shorter search term.\n'
791 ) % search_term,
792 button_defs = [
793 {'label': _('Go back'), 'tooltip': _('Go back and search again.'), 'default': True},
794 {'label': _('Create new'), 'tooltip': _('Create new patient.')}
795 ]
796 )
797 if dlg.ShowModal() != wx.ID_NO:
798 return
799
800 success = gmDemographicsWidgets.create_new_person(activate = True)
801 if success:
802 self.person = gmPerson.gmCurrentPatient()
803 else:
804 self.person = None
805 self._display_name()
806 return None
807
808
809 if len(idents) == 1:
810 self.person = idents[0]
811 self._display_name()
812 wx.EndBusyCursor()
813 return None
814
815
816 dlg = cSelectPersonFromListDlg(parent=wx.GetTopLevelParent(self), id=-1)
817 dlg.set_persons(persons=idents)
818 wx.EndBusyCursor()
819 result = dlg.ShowModal()
820 if result == wx.ID_CANCEL:
821 dlg.Destroy()
822 return None
823
824 wx.BeginBusyCursor()
825 self.person = dlg.get_selected_person()
826 dlg.Destroy()
827 self._display_name()
828 wx.EndBusyCursor()
829
830 return None
831
833
834
835 try:
836 patient['dob']
837 check_dob = True
838 except TypeError:
839 check_dob = False
840
841 if check_dob:
842 if patient['dob'] is None:
843 gmGuiHelpers.gm_show_warning (
844 aTitle = _('Checking date of birth'),
845 aMessage = _(
846 '\n'
847 ' %s\n'
848 '\n'
849 'The date of birth for this patient is not known !\n'
850 '\n'
851 'You can proceed to work on the patient but\n'
852 'GNUmed will be unable to assist you with\n'
853 'age-related decisions.\n'
854 ) % patient['description_gender']
855 )
856
857 return gmPerson.set_active_patient(patient = patient, forced_reload = forced_reload)
858
860
862
863 cPersonSearchCtrl.__init__(self, *args, **kwargs)
864
865 selector_tooltip = _(
866 'Patient search field. \n'
867 '\n'
868 'To search, type any of:\n'
869 ' - fragment of last or first name\n'
870 " - date of birth (can start with '$' or '*')\n"
871 " - patient ID (can start with '#')\n"
872 'and hit <ENTER>.\n'
873 '\n'
874 '<CURSOR-UP>\n'
875 ' - recall most recently used search term\n'
876 '<CURSOR-DOWN>\n'
877 ' - list 10 most recently activated patients\n'
878 '<F2>\n'
879 ' - scan external sources for patients to import and activate\n'
880 )
881 self.SetToolTip(wx.ToolTip(selector_tooltip))
882
883
884 cfg = gmCfg.cCfgSQL()
885
886 self.__always_dismiss_on_search = bool (
887 cfg.get2 (
888 option = 'patient_search.always_dismiss_previous_patient',
889 workplace = gmSurgery.gmCurrentPractice().active_workplace,
890 bias = 'user',
891 default = 0
892 )
893 )
894
895 self.__always_reload_after_search = bool (
896 cfg.get2 (
897 option = 'patient_search.always_reload_new_patient',
898 workplace = gmSurgery.gmCurrentPractice().active_workplace,
899 bias = 'user',
900 default = 0
901 )
902 )
903
904 self.__register_events()
905
906
907
919
921 if not set_active_patient(patient=pat, forced_reload = self.__always_reload_after_search):
922 _log.error('cannot change active patient')
923 return None
924
925 self._remember_ident(pat)
926
927 dbcfg = gmCfg.cCfgSQL()
928 dob_distance = dbcfg.get2 (
929 option = u'patient_search.dob_warn_interval',
930 workplace = gmSurgery.gmCurrentPractice().active_workplace,
931 bias = u'user',
932 default = u'1 week'
933 )
934
935 if pat.dob_in_range(dob_distance, dob_distance):
936 now = pyDT.datetime.now(tz = gmDateTime.gmCurrentLocalTimezone)
937 enc = gmI18N.get_encoding()
938 gmDispatcher.send(signal = 'statustext', msg = _(
939 '%(pat)s turns %(age)s on %(month)s %(day)s ! (today is %(month_now)s %(day_now)s)') % {
940 'pat': pat.get_description_gender(),
941 'age': pat.get_medical_age().strip('y'),
942 'month': pat.get_formatted_dob(format = '%B', encoding = enc),
943 'day': pat.get_formatted_dob(format = '%d', encoding = enc),
944 'month_now': now.strftime('%B').decode(enc),
945 'day_now': now.strftime('%d')
946 }
947 )
948
949 return True
950
951
952
954
955 gmDispatcher.connect(signal = u'post_patient_selection', receiver = self._on_post_patient_selection)
956 gmDispatcher.connect(signal = u'name_mod_db', receiver = self._on_name_identity_change)
957 gmDispatcher.connect(signal = u'identity_mod_db', receiver = self._on_name_identity_change)
958
959 gmDispatcher.connect(signal = 'patient_locked', receiver = self._on_post_patient_selection)
960 gmDispatcher.connect(signal = 'patient_unlocked', receiver = self._on_post_patient_selection)
961
963 wx.CallAfter(self._display_name)
964
966 if gmPerson.gmCurrentPatient().connected:
967 self.person = gmPerson.gmCurrentPatient().patient
968 else:
969 self.person = None
970 wx.CallAfter(self._display_name)
971
973
974 if self.__always_dismiss_on_search:
975 _log.warning("dismissing patient before patient search")
976 self._set_person_as_active_patient(-1)
977
978 super(self.__class__, self)._on_enter(search_term=search_term)
979
980 if self.person is None:
981 return
982
983 self._set_person_as_active_patient(self.person)
984 self._display_name()
985
987
988 success = super(self.__class__, self)._on_char(evt)
989 if success:
990 self._set_person_as_active_patient(self.person)
991
992
993
995
1004
1005
1007 self.matcher.set_items([ {'data': i, 'label': i, 'weight': 1} for i in items ])
1008
1009
1010 from Gnumed.wxGladeWidgets import wxgWaitingListEntryEditAreaPnl
1011
1012 -class cWaitingListEntryEditAreaPnl(wxgWaitingListEntryEditAreaPnl.wxgWaitingListEntryEditAreaPnl, gmEditArea.cGenericEditAreaMixin):
1013
1014 - def __init__ (self, *args, **kwargs):
1015
1016 try:
1017 self.patient = kwargs['patient']
1018 del kwargs['patient']
1019 except KeyError:
1020 self.patient = None
1021
1022 try:
1023 data = kwargs['entry']
1024 del kwargs['entry']
1025 except KeyError:
1026 data = None
1027
1028 wxgWaitingListEntryEditAreaPnl.wxgWaitingListEntryEditAreaPnl.__init__(self, *args, **kwargs)
1029 gmEditArea.cGenericEditAreaMixin.__init__(self)
1030
1031 if data is None:
1032 self.mode = 'new'
1033 else:
1034 self.data = data
1035 self.mode = 'edit'
1036
1037 praxis = gmSurgery.gmCurrentPractice()
1038 pats = praxis.waiting_list_patients
1039 zones = {}
1040 zones.update([ [p['waiting_zone'], None] for p in pats if p['waiting_zone'] is not None ])
1041 self._PRW_zone.update_matcher(items = zones.keys())
1042
1043
1044
1045 - def _refresh_as_new(self):
1046 if self.patient is None:
1047 self._PRW_patient.person = None
1048 self._PRW_patient.Enable(True)
1049 self._PRW_patient.SetFocus()
1050 else:
1051 self._PRW_patient.person = self.patient
1052 self._PRW_patient.Enable(False)
1053 self._PRW_comment.SetFocus()
1054 self._PRW_patient._display_name()
1055
1056 self._PRW_comment.SetValue(u'')
1057 self._PRW_zone.SetValue(u'')
1058 self._SPCTRL_urgency.SetValue(0)
1059
1061 self._PRW_patient.person = gmPerson.cIdentity(aPK_obj = self.data['pk_identity'])
1062 self._PRW_patient.Enable(False)
1063 self._PRW_patient._display_name()
1064
1065 self._PRW_comment.SetValue(gmTools.coalesce(self.data['comment'], u''))
1066 self._PRW_zone.SetValue(gmTools.coalesce(self.data['waiting_zone'], u''))
1067 self._SPCTRL_urgency.SetValue(self.data['urgency'])
1068
1069 self._PRW_comment.SetFocus()
1070
1071 - def _valid_for_save(self):
1072 validity = True
1073
1074 self.display_tctrl_as_valid(tctrl = self._PRW_patient, valid = (self._PRW_patient.person is not None))
1075 validity = (self._PRW_patient.person is not None)
1076
1077 if validity is False:
1078 gmDispatcher.send(signal = 'statustext', msg = _('Cannot add to waiting list. Missing essential input.'))
1079
1080 return validity
1081
1082 - def _save_as_new(self):
1083
1084 self._PRW_patient.person.put_on_waiting_list (
1085 urgency = self._SPCTRL_urgency.GetValue(),
1086 comment = gmTools.none_if(self._PRW_comment.GetValue().strip(), u''),
1087 zone = gmTools.none_if(self._PRW_zone.GetValue().strip(), u'')
1088 )
1089
1090 self.data = {'pk_identity': None, 'comment': None, 'waiting_zone': None, 'urgency': 0}
1091 return True
1092
1093 - def _save_as_update(self):
1094 gmSurgery.gmCurrentPractice().update_in_waiting_list (
1095 pk = self.data['pk_waiting_list'],
1096 urgency = self._SPCTRL_urgency.GetValue(),
1097 comment = self._PRW_comment.GetValue().strip(),
1098 zone = self._PRW_zone.GetValue().strip()
1099 )
1100 return True
1101
1102 from Gnumed.wxGladeWidgets import wxgWaitingListPnl
1103
1104 -class cWaitingListPnl(wxgWaitingListPnl.wxgWaitingListPnl, gmRegetMixin.cRegetOnPaintMixin):
1105
1115
1116
1117
1119 self._LCTRL_patients.set_columns ([
1120 _('Zone'),
1121 _('Urgency'),
1122
1123 _('Waiting time'),
1124 _('Patient'),
1125 _('Born'),
1126 _('Comment')
1127 ])
1128 self._LCTRL_patients.set_column_widths(widths = [wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE_USEHEADER, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE])
1129 self._PRW_zone.add_callback_on_selection(callback = self._on_zone_selected)
1130 self._PRW_zone.add_callback_on_lose_focus(callback = self._on_zone_selected)
1131
1133 gmDispatcher.connect(signal = u'waiting_list_generic_mod_db', receiver = self._on_waiting_list_modified)
1134
1136
1137 praxis = gmSurgery.gmCurrentPractice()
1138 pats = praxis.waiting_list_patients
1139
1140
1141 zones = {}
1142 zones.update([ [p['waiting_zone'], None] for p in pats if p['waiting_zone'] is not None ])
1143 self._PRW_zone.update_matcher(items = zones.keys())
1144 del zones
1145
1146
1147 self.__current_zone = self._PRW_zone.GetValue().strip()
1148 if self.__current_zone == u'':
1149 pats = [ p for p in pats ]
1150 else:
1151 pats = [ p for p in pats if p['waiting_zone'] == self.__current_zone ]
1152
1153 self._LCTRL_patients.set_string_items (
1154 [ [
1155 gmTools.coalesce(p['waiting_zone'], u''),
1156 p['urgency'],
1157 p['waiting_time_formatted'].replace(u'00 ', u'', 1).replace('00:', u'').lstrip('0'),
1158 u'%s, %s (%s)' % (p['lastnames'], p['firstnames'], p['l10n_gender']),
1159 p['dob'],
1160 gmTools.coalesce(p['comment'], u'')
1161 ] for p in pats
1162 ]
1163 )
1164 self._LCTRL_patients.set_column_widths()
1165 self._LCTRL_patients.set_data(pats)
1166 self._LCTRL_patients.Refresh()
1167 self._LCTRL_patients.SetToolTipString ( _(
1168 '%s patients are waiting.\n'
1169 '\n'
1170 'Doubleclick to activate (entry will stay in list).'
1171 ) % len(pats))
1172
1173 self._LBL_no_of_patients.SetLabel(_('(%s patients)') % len(pats))
1174
1175 if len(pats) == 0:
1176 self._BTN_activate.Enable(False)
1177 self._BTN_activateplus.Enable(False)
1178 self._BTN_remove.Enable(False)
1179 self._BTN_edit.Enable(False)
1180 self._BTN_up.Enable(False)
1181 self._BTN_down.Enable(False)
1182 else:
1183 self._BTN_activate.Enable(True)
1184 self._BTN_activateplus.Enable(True)
1185 self._BTN_remove.Enable(True)
1186 self._BTN_edit.Enable(True)
1187 if len(pats) > 1:
1188 self._BTN_up.Enable(True)
1189 self._BTN_down.Enable(True)
1190
1191
1192
1194 if self.__current_zone == self._PRW_zone.GetValue().strip():
1195 return True
1196 wx.CallAfter(self.__refresh_waiting_list)
1197 return True
1198
1200 wx.CallAfter(self._schedule_data_reget)
1201
1208
1215
1223
1235
1244
1250
1256
1262
1263
1264
1265
1266
1268 self.__refresh_waiting_list()
1269 return True
1270
1271
1272
1273 if __name__ == "__main__":
1274
1275 if len(sys.argv) > 1:
1276 if sys.argv[1] == 'test':
1277 gmI18N.activate_locale()
1278 gmI18N.install_domain()
1279
1280 app = wx.PyWidgetTester(size = (200, 40))
1281
1282
1283
1284 app.SetWidget(cWaitingListPnl, -1)
1285 app.MainLoop()
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994