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
47
49 wxgMergePatientsDlg.wxgMergePatientsDlg.__init__(self, *args, **kwargs)
50
51 curr_pat = gmPerson.gmCurrentPatient()
52 if curr_pat.connected:
53 self._TCTRL_patient1.person = curr_pat
54 self._TCTRL_patient1._display_name()
55 self._RBTN_patient1.SetValue(True)
56
155
157
159 wxgSelectPersonFromListDlg.wxgSelectPersonFromListDlg.__init__(self, *args, **kwargs)
160
161 self.__cols = [
162 _('Title'),
163 _('Lastname'),
164 _('Firstname'),
165 _('Nickname'),
166 _('DOB'),
167 _('Gender'),
168 _('last visit'),
169 _('found via')
170 ]
171 self.__init_ui()
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
230 wxgSelectPersonDTOFromListDlg.wxgSelectPersonDTOFromListDlg.__init__(self, *args, **kwargs)
231
232 self.__cols = [
233 _('Source'),
234 _('Lastname'),
235 _('Firstname'),
236 _('DOB'),
237 _('Gender')
238 ]
239 self.__init_ui()
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
801
802
803
804
805 success = gmDemographicsWidgets.create_new_person(parent = self, activate = True)
806 if success:
807 self.person = gmPerson.gmCurrentPatient()
808 else:
809 self.person = None
810 self._display_name()
811 return None
812
813
814 if len(idents) == 1:
815 self.person = idents[0]
816 self._display_name()
817 wx.EndBusyCursor()
818 return None
819
820
821 dlg = cSelectPersonFromListDlg(parent=wx.GetTopLevelParent(self), id=-1)
822 dlg.set_persons(persons=idents)
823 wx.EndBusyCursor()
824 result = dlg.ShowModal()
825 if result == wx.ID_CANCEL:
826 dlg.Destroy()
827 return None
828
829 wx.BeginBusyCursor()
830 self.person = dlg.get_selected_person()
831 dlg.Destroy()
832 self._display_name()
833 wx.EndBusyCursor()
834
835 return None
836
838
839
840 try:
841 patient['dob']
842 check_dob = True
843 except TypeError:
844 check_dob = False
845
846 if check_dob:
847 if patient['dob'] is None:
848 gmGuiHelpers.gm_show_warning (
849 aTitle = _('Checking date of birth'),
850 aMessage = _(
851 '\n'
852 ' %s\n'
853 '\n'
854 'The date of birth for this patient is not known !\n'
855 '\n'
856 'You can proceed to work on the patient but\n'
857 'GNUmed will be unable to assist you with\n'
858 'age-related decisions.\n'
859 ) % patient['description_gender']
860 )
861
862 return gmPerson.set_active_patient(patient = patient, forced_reload = forced_reload)
863
865
867
868 cPersonSearchCtrl.__init__(self, *args, **kwargs)
869
870 selector_tooltip = _(
871 'Patient search field. \n'
872 '\n'
873 'To search, type any of:\n'
874 ' - fragment of last or first name\n'
875 " - date of birth (can start with '$' or '*')\n"
876 " - patient ID (can start with '#')\n"
877 'and hit <ENTER>.\n'
878 '\n'
879 '<CURSOR-UP>\n'
880 ' - recall most recently used search term\n'
881 '<CURSOR-DOWN>\n'
882 ' - list 10 most recently activated patients\n'
883 '<F2>\n'
884 ' - scan external sources for patients to import and activate\n'
885 )
886 self.SetToolTip(wx.ToolTip(selector_tooltip))
887
888
889 cfg = gmCfg.cCfgSQL()
890
891 self.__always_dismiss_on_search = bool (
892 cfg.get2 (
893 option = 'patient_search.always_dismiss_previous_patient',
894 workplace = gmSurgery.gmCurrentPractice().active_workplace,
895 bias = 'user',
896 default = 0
897 )
898 )
899
900 self.__always_reload_after_search = bool (
901 cfg.get2 (
902 option = 'patient_search.always_reload_new_patient',
903 workplace = gmSurgery.gmCurrentPractice().active_workplace,
904 bias = 'user',
905 default = 0
906 )
907 )
908
909 self.__register_events()
910
911
912
924
926 if not set_active_patient(patient=pat, forced_reload = self.__always_reload_after_search):
927 _log.error('cannot change active patient')
928 return None
929
930 self._remember_ident(pat)
931
932 dbcfg = gmCfg.cCfgSQL()
933 dob_distance = dbcfg.get2 (
934 option = u'patient_search.dob_warn_interval',
935 workplace = gmSurgery.gmCurrentPractice().active_workplace,
936 bias = u'user',
937 default = u'1 week'
938 )
939
940 if pat.dob_in_range(dob_distance, dob_distance):
941 now = pyDT.datetime.now(tz = gmDateTime.gmCurrentLocalTimezone)
942 enc = gmI18N.get_encoding()
943 gmDispatcher.send(signal = 'statustext', msg = _(
944 '%(pat)s turns %(age)s on %(month)s %(day)s ! (today is %(month_now)s %(day_now)s)') % {
945 'pat': pat.get_description_gender(),
946 'age': pat.get_medical_age().strip('y'),
947 'month': pat.get_formatted_dob(format = '%B', encoding = enc),
948 'day': pat.get_formatted_dob(format = '%d', encoding = enc),
949 'month_now': now.strftime('%B').decode(enc),
950 'day_now': now.strftime('%d')
951 }
952 )
953
954 return True
955
956
957
959
960 gmDispatcher.connect(signal = u'post_patient_selection', receiver = self._on_post_patient_selection)
961 gmDispatcher.connect(signal = u'name_mod_db', receiver = self._on_name_identity_change)
962 gmDispatcher.connect(signal = u'identity_mod_db', receiver = self._on_name_identity_change)
963
964 gmDispatcher.connect(signal = 'patient_locked', receiver = self._on_post_patient_selection)
965 gmDispatcher.connect(signal = 'patient_unlocked', receiver = self._on_post_patient_selection)
966
968 wx.CallAfter(self._display_name)
969
971 if gmPerson.gmCurrentPatient().connected:
972 self.person = gmPerson.gmCurrentPatient().patient
973 else:
974 self.person = None
975 wx.CallAfter(self._display_name)
976
978
979 if self.__always_dismiss_on_search:
980 _log.warning("dismissing patient before patient search")
981 self._set_person_as_active_patient(-1)
982
983 super(self.__class__, self)._on_enter(search_term=search_term)
984
985 if self.person is None:
986 return
987
988 self._set_person_as_active_patient(self.person)
989 self._display_name()
990
992
993 success = super(self.__class__, self)._on_char(evt)
994 if success:
995 self._set_person_as_active_patient(self.person)
996
997
998
1000
1009
1010
1012 self.matcher.set_items([ {'data': i, 'label': i, 'weight': 1} for i in items ])
1013
1014
1015 from Gnumed.wxGladeWidgets import wxgWaitingListEntryEditAreaPnl
1016
1017 -class cWaitingListEntryEditAreaPnl(wxgWaitingListEntryEditAreaPnl.wxgWaitingListEntryEditAreaPnl, gmEditArea.cGenericEditAreaMixin):
1018
1019 - def __init__ (self, *args, **kwargs):
1020
1021 try:
1022 self.patient = kwargs['patient']
1023 del kwargs['patient']
1024 except KeyError:
1025 self.patient = None
1026
1027 try:
1028 data = kwargs['entry']
1029 del kwargs['entry']
1030 except KeyError:
1031 data = None
1032
1033 wxgWaitingListEntryEditAreaPnl.wxgWaitingListEntryEditAreaPnl.__init__(self, *args, **kwargs)
1034 gmEditArea.cGenericEditAreaMixin.__init__(self)
1035
1036 if data is None:
1037 self.mode = 'new'
1038 else:
1039 self.data = data
1040 self.mode = 'edit'
1041
1042 praxis = gmSurgery.gmCurrentPractice()
1043 pats = praxis.waiting_list_patients
1044 zones = {}
1045 zones.update([ [p['waiting_zone'], None] for p in pats if p['waiting_zone'] is not None ])
1046 self._PRW_zone.update_matcher(items = zones.keys())
1047
1048
1049
1050 - def _refresh_as_new(self):
1051 if self.patient is None:
1052 self._PRW_patient.person = None
1053 self._PRW_patient.Enable(True)
1054 self._PRW_patient.SetFocus()
1055 else:
1056 self._PRW_patient.person = self.patient
1057 self._PRW_patient.Enable(False)
1058 self._PRW_comment.SetFocus()
1059 self._PRW_patient._display_name()
1060
1061 self._PRW_comment.SetValue(u'')
1062 self._PRW_zone.SetValue(u'')
1063 self._SPCTRL_urgency.SetValue(0)
1064
1066 self._PRW_patient.person = gmPerson.cIdentity(aPK_obj = self.data['pk_identity'])
1067 self._PRW_patient.Enable(False)
1068 self._PRW_patient._display_name()
1069
1070 self._PRW_comment.SetValue(gmTools.coalesce(self.data['comment'], u''))
1071 self._PRW_zone.SetValue(gmTools.coalesce(self.data['waiting_zone'], u''))
1072 self._SPCTRL_urgency.SetValue(self.data['urgency'])
1073
1074 self._PRW_comment.SetFocus()
1075
1076 - def _valid_for_save(self):
1077 validity = True
1078
1079 self.display_tctrl_as_valid(tctrl = self._PRW_patient, valid = (self._PRW_patient.person is not None))
1080 validity = (self._PRW_patient.person is not None)
1081
1082 if validity is False:
1083 gmDispatcher.send(signal = 'statustext', msg = _('Cannot add to waiting list. Missing essential input.'))
1084
1085 return validity
1086
1087 - def _save_as_new(self):
1088
1089 self._PRW_patient.person.put_on_waiting_list (
1090 urgency = self._SPCTRL_urgency.GetValue(),
1091 comment = gmTools.none_if(self._PRW_comment.GetValue().strip(), u''),
1092 zone = gmTools.none_if(self._PRW_zone.GetValue().strip(), u'')
1093 )
1094
1095 self.data = {'pk_identity': None, 'comment': None, 'waiting_zone': None, 'urgency': 0}
1096 return True
1097
1098 - def _save_as_update(self):
1099 gmSurgery.gmCurrentPractice().update_in_waiting_list (
1100 pk = self.data['pk_waiting_list'],
1101 urgency = self._SPCTRL_urgency.GetValue(),
1102 comment = self._PRW_comment.GetValue().strip(),
1103 zone = self._PRW_zone.GetValue().strip()
1104 )
1105 return True
1106
1107 from Gnumed.wxGladeWidgets import wxgWaitingListPnl
1108
1109 -class cWaitingListPnl(wxgWaitingListPnl.wxgWaitingListPnl, gmRegetMixin.cRegetOnPaintMixin):
1110
1120
1121
1122
1124 self._LCTRL_patients.set_columns ([
1125 _('Zone'),
1126 _('Urgency'),
1127
1128 _('Waiting time'),
1129 _('Patient'),
1130 _('Born'),
1131 _('Comment')
1132 ])
1133 self._LCTRL_patients.set_column_widths(widths = [wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE_USEHEADER, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE])
1134 self._PRW_zone.add_callback_on_selection(callback = self._on_zone_selected)
1135 self._PRW_zone.add_callback_on_lose_focus(callback = self._on_zone_selected)
1136
1138 gmDispatcher.connect(signal = u'waiting_list_generic_mod_db', receiver = self._on_waiting_list_modified)
1139
1141
1142 praxis = gmSurgery.gmCurrentPractice()
1143 pats = praxis.waiting_list_patients
1144
1145
1146 zones = {}
1147 zones.update([ [p['waiting_zone'], None] for p in pats if p['waiting_zone'] is not None ])
1148 self._PRW_zone.update_matcher(items = zones.keys())
1149 del zones
1150
1151
1152 self.__current_zone = self._PRW_zone.GetValue().strip()
1153 if self.__current_zone == u'':
1154 pats = [ p for p in pats ]
1155 else:
1156 pats = [ p for p in pats if p['waiting_zone'] == self.__current_zone ]
1157
1158 self._LCTRL_patients.set_string_items (
1159 [ [
1160 gmTools.coalesce(p['waiting_zone'], u''),
1161 p['urgency'],
1162 p['waiting_time_formatted'].replace(u'00 ', u'', 1).replace('00:', u'').lstrip('0'),
1163 u'%s, %s (%s)' % (p['lastnames'], p['firstnames'], p['l10n_gender']),
1164 p['dob'].strftime('%x').decode(gmI18N.get_encoding()),
1165 gmTools.coalesce(p['comment'], u'')
1166 ] for p in pats
1167 ]
1168 )
1169 self._LCTRL_patients.set_column_widths()
1170 self._LCTRL_patients.set_data(pats)
1171 self._LCTRL_patients.Refresh()
1172 self._LCTRL_patients.SetToolTipString ( _(
1173 '%s patients are waiting.\n'
1174 '\n'
1175 'Doubleclick to activate (entry will stay in list).'
1176 ) % len(pats))
1177
1178 self._LBL_no_of_patients.SetLabel(_('(%s patients)') % len(pats))
1179
1180 if len(pats) == 0:
1181 self._BTN_activate.Enable(False)
1182 self._BTN_activateplus.Enable(False)
1183 self._BTN_remove.Enable(False)
1184 self._BTN_edit.Enable(False)
1185 self._BTN_up.Enable(False)
1186 self._BTN_down.Enable(False)
1187 else:
1188 self._BTN_activate.Enable(True)
1189 self._BTN_activateplus.Enable(True)
1190 self._BTN_remove.Enable(True)
1191 self._BTN_edit.Enable(True)
1192 if len(pats) > 1:
1193 self._BTN_up.Enable(True)
1194 self._BTN_down.Enable(True)
1195
1196
1197
1199 if self.__current_zone == self._PRW_zone.GetValue().strip():
1200 return True
1201 wx.CallAfter(self.__refresh_waiting_list)
1202 return True
1203
1205 wx.CallAfter(self._schedule_data_reget)
1206
1213
1220
1228
1240
1249
1255
1261
1267
1268
1269
1270
1271
1273 self.__refresh_waiting_list()
1274 return True
1275
1276
1277
1278 if __name__ == "__main__":
1279
1280 if len(sys.argv) > 1:
1281 if sys.argv[1] == 'test':
1282 gmI18N.activate_locale()
1283 gmI18N.install_domain()
1284
1285 app = wx.PyWidgetTester(size = (200, 40))
1286
1287
1288
1289 app.SetWidget(cWaitingListPnl, -1)
1290 app.MainLoop()
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
1995
1996
1997
1998
1999