File: gmSOAPWidgets.py

package info (click to toggle)
gnumed-client 1.4.12%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 164,192 kB
  • ctags: 168,531
  • sloc: python: 88,281; sh: 765; makefile: 37
file content (1238 lines) | stat: -rw-r--r-- 41,341 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
"""GNUmed SOAP related widgets.
"""
#============================================================
__version__ = "$Revision: 1.114 $"
__author__ = "Carlos Moro <cfmoro1976@yahoo.es>, K.Hilbert <Karsten.Hilbert@gmx.net>"
__license__ = "GPL"

# std library
import types, logging


# 3rd party
import wx


# GNUmed
from Gnumed.pycommon import gmDispatcher, gmI18N, gmExceptions, gmMatchProvider, gmTools, gmCfg
from Gnumed.wxpython import gmResizingWidgets, gmPhraseWheel, gmEMRStructWidgets, gmGuiHelpers, gmRegetMixin, gmEditArea, gmPatSearchWidgets
from Gnumed.business import gmPerson, gmEMRStructItems, gmSOAPimporter, gmPraxis, gmPersonSearch, gmStaff

_log = logging.getLogger('gm.ui')
_log.info(__version__)

#============================================================
def create_issue_popup(parent, pos, size, style, data_sink):
	ea = gmEMRStructWidgets.cHealthIssueEditArea (
		parent,
		-1,
		wx.DefaultPosition,
		wx.DefaultSize,
		wx.NO_BORDER | wx.TAB_TRAVERSAL,
		data_sink = data_sink
	)
	popup = gmEditArea.cEditAreaPopup (
		parent = parent,
		id = -1,
		title = '',
		pos = pos,
		size = size,
		style = style,
		name = '',
		edit_area = ea
	)
	return popup
#============================================================
def create_vacc_popup(parent, pos, size, style, data_sink):
	ea = gmVaccWidgets.cVaccinationEditArea (
		parent = parent,
		id = -1,
      	pos = pos,
		size = size,
		style = style,
		data_sink = data_sink
	)
	popup = gmEditArea.cEditAreaPopup (
		parent = parent,
		id = -1,
		title = _('Enter vaccination given'),
		pos = pos,
		size = size,
		style = style,
		name = '',
		edit_area = ea
	)
	return popup
#============================================================
# FIXME: keywords hardcoded for now, load from cfg in backend instead
progress_note_keywords = {
	's': {
		'$missing_action': {},
		'phx$': {
			'widget_factory': create_issue_popup,
			'widget_data_sink': None
		},
		'ea$:': {
			'widget_factory': create_issue_popup,
			'widget_data_sink': None
		},
		'$vacc': {
			'widget_factory': create_vacc_popup,
			'widget_data_sink': None
		},
		'impf:': {
			'widget_factory': create_vacc_popup,
			'widget_data_sink': None
		},
		'icpc:': {},
		'icpc?': {}
	},
	'o': {
		'icpc:': {},
		'icpc?': {}
	},
	'a': {
		'icpc:': {},
		'icpc?': {}
	},
	'p': {
		'$vacc': {
			'widget_factory': create_vacc_popup,
			'widget_data_sink': None
		},
		'icpc:': {},
		'icpc?': {}
	}
}
#============================================================
class cProgressNoteInputNotebook(wx.Notebook, gmRegetMixin.cRegetOnPaintMixin):
	"""A notebook holding panels with progress note editors.

	There is one progress note editor panel for each episode being worked on.
	"""
	def __init__(self, parent, id, pos=wx.DefaultPosition, size=wx.DefaultSize):
		wx.Notebook.__init__ (
			self,
			parent = parent,
			id = id,
			pos = pos,
			size = size,
			style = wx.NB_TOP | wx.NB_MULTILINE | wx.NO_BORDER,
			name = self.__class__.__name__
		)
		gmRegetMixin.cRegetOnPaintMixin.__init__(self)
		self.__pat = gmPerson.gmCurrentPatient()
		self.__do_layout()
		self.__register_interests()
	#--------------------------------------------------------
	# public API
	#--------------------------------------------------------
	def add_editor(self, problem=None, allow_same_problem=False):
		"""Add a progress note editor page.

		The way <allow_same_problem> is currently used in callers
		it only applies to unassociated episodes.
		"""
		problem_to_add = problem

		# determine label
		if problem_to_add is None:
			label = _('new problem')
		else:
			# normalize problem type
			emr = self.__pat.get_emr()
			if isinstance(problem_to_add, gmEMRStructItems.cEpisode):
				problem_to_add = emr.episode2problem(episode = problem_to_add)
			elif isinstance(problem_to_add, gmEMRStructItems.cHealthIssue):
				problem_to_add = emr.health_issue2problem(issue = problem_to_add)
			if not isinstance(problem_to_add, gmEMRStructItems.cProblem):
				raise TypeError('cannot open progress note editor for [%s]' % problem_to_add)
			label = problem_to_add['problem']
			# FIXME: configure maximum length
			if len(label) > 23:
				label = label[:21] + gmTools.u_ellipsis

		if allow_same_problem:
			new_page = cResizingSoapPanel(parent = self, problem = problem_to_add)
			result = self.AddPage (
				page = new_page,
				text = label,
				select = True
			)
			return result

		# check for dupes
		# new unassociated problem
		if problem_to_add is None:
			# check for dupes
			for page_idx in range(self.GetPageCount()):
				page = self.GetPage(page_idx)
				# found
				if page.get_problem() is None:
					self.SetSelection(page_idx)
					return True
				continue
			# not found
			new_page = cResizingSoapPanel(parent = self, problem = problem_to_add)
			result = self.AddPage (
				page = new_page,
				text = label,
				select = True
			)
			return result

		# real problem
		# - raise existing editor ?
		for page_idx in range(self.GetPageCount()):
			page = self.GetPage(page_idx)
			problem_of_page = page.get_problem()
			# editor is for unassociated new problem
			if problem_of_page is None:
				continue
			# editor is for episode
			if problem_of_page['type'] == 'episode':
				if problem_to_add['type'] == 'issue':
					is_equal = (problem_of_page['pk_health_issue'] == problem_to_add['pk_health_issue'])
				else:
					is_equal = (problem_of_page['pk_episode'] == problem_to_add['pk_episode'])
				if is_equal:
					self.SetSelection(page_idx)
					return True
				continue
			# editor is for health issue
			if problem_of_page['type'] == 'issue':
				if problem_of_page['pk_health_issue'] == problem_to_add['pk_health_issue']:
					self.SetSelection(page_idx)
					return True
				continue

		# - add new editor
		new_page = cResizingSoapPanel(parent = self, problem = problem_to_add)
		result = self.AddPage (
			page = new_page,
			text = label,
			select = True
		)

		return result
	#--------------------------------------------------------
	def close_current_editor(self):

		page_idx = self.GetSelection()
		page = self.GetPage(page_idx)

		if not page.editor_empty():
			really_discard = gmGuiHelpers.gm_show_question (
				_('Are you sure you really want to\n'
				  'discard this progress note ?\n'
				),
				_('Discarding progress note')
			)
			if really_discard is False:
				return

		self.DeletePage(page_idx)

		# always keep one unassociated editor open
		if self.GetPageCount() == 0:
			self.add_editor()
	#--------------------------------------------------------
	def warn_on_unsaved_soap(self):

		for page_idx in range(self.GetPageCount()):
			page = self.GetPage(page_idx)
			if page.editor_empty():
				continue

			gmGuiHelpers.gm_show_warning (
				_('There are unsaved progress notes !\n'),
				_('Unsaved progress notes')
			)
			return False

		return True
	#--------------------------------------------------------
	def save_unsaved_soap(self):
		save_all = False
		dlg = None
		for page_idx in range(self.GetPageCount()):
			page = self.GetPage(page_idx)
			if page.editor_empty():
				continue

			if dlg is None:
				dlg = gmGuiHelpers.c3ButtonQuestionDlg (
					self, 
					-1,
					caption = _('Unsaved progress note'),
					question = _(
						'This progress note has not been saved yet.\n'
						'\n'
						'Do you want to save it or discard it ?\n\n'
					),
					button_defs = [
						{'label': _('&Save'), 'tooltip': _('Save this progress note'), 'default': True},
						{'label': _('&Discard'), 'tooltip': _('Discard this progress note'), 'default': False},
						{'label': _('Save &all'), 'tooltip': _('Save all remaining unsaved progress notes'), 'default': False}
					]
				)

			if not save_all:
				self.ChangeSelection(page_idx)
				decision = dlg.ShowModal()
				if decision == wx.ID_NO:
					_log.info('user requested discarding of unsaved progress note')
					continue
				if decision == wx.ID_CANCEL:
					save_all = True
			page.save()

		if dlg is not None:
			dlg.Destroy()
	#--------------------------------------------------------
	# internal API
	#--------------------------------------------------------
	def __do_layout(self):
		# add one empty unassociated progress note editor - which to
		# have (by all sensible accounts) seems to be the intent when
		# instantiating this class
		self.add_editor()
	#--------------------------------------------------------
	# reget mixin API
	#--------------------------------------------------------
	def _populate_with_data(self):
		print '[%s._populate_with_data] nothing to do, really...' % self.__class__.__name__
		return True
	#--------------------------------------------------------
	# event handling
	#--------------------------------------------------------
	def __register_interests(self):
		"""Configure enabled event signals
		"""
		# wxPython events

		# client internal signals
		gmDispatcher.connect(signal = u'post_patient_selection', receiver=self._on_post_patient_selection)
#		gmDispatcher.connect(signal = u'application_closing', receiver=self._on_application_closing)

		self.__pat.register_pre_selection_callback(callback = self._pre_selection_callback)

		gmDispatcher.send(signal = u'register_pre_exit_callback', callback = self._pre_exit_callback)
	#--------------------------------------------------------
	def _pre_selection_callback(self):
		"""Another patient is about to be activated.

		Patient change will not proceed before this returns True.
		"""
		return self.warn_on_unsaved_soap()
	#--------------------------------------------------------
	def _pre_exit_callback(self):
		"""The client is about to be shut down.

		Shutdown will not proceed before this returns.
		"""
		self.save_unsaved_soap()
	#--------------------------------------------------------
	def _on_post_patient_selection(self):
		"""Patient changed."""
		self.DeleteAllPages()
		self.add_editor()
		self._schedule_data_reget()
	#--------------------------------------------------------
#	def _on_application_closing(self):
#		"""GNUmed is shutting down."""
#		print "[%s]: the application is closing down" % self.__class__.__name__
#		print "************************************"
#		print "need to ask user about SOAP saving !"
#		print "************************************"
	#--------------------------------------------------------
#	def _on_episodes_modified(self):
#		print "[%s]: episode modified" % self.__class__.__name__
#		print "need code to deal with:"
#		print "- deleted episode that we show so we can notify the user"
#		print "- renamed episode so we can update our episode label"
#		self._schedule_data_reget()
#		pass
#============================================================
class cNotebookedProgressNoteInputPanel(wx.Panel):
	"""A panel for entering multiple progress notes in context.

	Expects to be used as a notebook page.

	Left hand side:
	- problem list (health issues and active episodes)

	Right hand side:
	- notebook with progress note editors

	Listens to patient change signals, thus acts on the current patient.
	"""
	#--------------------------------------------------------
	def __init__(self, parent, id):
		"""Contructs a new instance of SOAP input panel

		@param parent: Wx parent widget
		@param id: Wx widget id
		"""
		# Call parents constructors
		wx.Panel.__init__ (
			self,
			parent = parent,
			id = id,
			pos = wx.DefaultPosition,
			size = wx.DefaultSize,
			style = wx.NO_BORDER
		)
		self.__pat = gmPerson.gmCurrentPatient()

		# ui contruction and event handling set up
		self.__do_layout()
		self.__register_interests()
		self.reset_ui_content()
	#--------------------------------------------------------
	# public API
	#--------------------------------------------------------
	def reset_ui_content(self):
		"""
		Clear all information from input panel
		"""
		self.__LST_problems.Clear()
		self.__soap_notebook.DeleteAllPages()
		self.__soap_notebook.add_editor()
	#--------------------------------------------------------
	# internal helpers
	#--------------------------------------------------------
	def __do_layout(self):
		"""Arrange widgets.

		left: problem list (mix of issues and episodes)
		right: soap editors
		"""
		# SOAP input panel main splitter window
		self.__splitter = wx.SplitterWindow(self, -1)

		# left hand side
		PNL_list = wx.Panel(self.__splitter, -1)
		# - header
		list_header = wx.StaticText (
			parent = PNL_list,
			id = -1,
			label = _('Active problems'),
			style = wx.NO_BORDER | wx.ALIGN_CENTRE
		)
		# - problem list
		self.__LST_problems = wx.ListBox (
			PNL_list,
			-1,
			style= wx.NO_BORDER
		)
		# - arrange
		szr_left = wx.BoxSizer(wx.VERTICAL)
		szr_left.Add(list_header, 0)
		szr_left.Add(self.__LST_problems, 1, wx.EXPAND)
		PNL_list.SetSizerAndFit(szr_left)

		# right hand side
		# - soap inputs panel
		PNL_soap_editors = wx.Panel(self.__splitter, -1)
		# - progress note notebook
		self.__soap_notebook = cProgressNoteInputNotebook(PNL_soap_editors, -1)
		# - buttons
		self.__BTN_add_unassociated = wx.Button(PNL_soap_editors, -1, _('&New'))
		tt = _(
			'Add editor for a new unassociated progress note.\n\n'
			'There is a configuration option whether or not to\n'
			'allow several new unassociated progress notes at once.'
		)
		self.__BTN_add_unassociated.SetToolTipString(tt)

		self.__BTN_save = wx.Button(PNL_soap_editors, -1, _('&Save'))
		self.__BTN_save.SetToolTipString(_('Save progress note into medical record and close this editor.'))

		self.__BTN_clear = wx.Button(PNL_soap_editors, -1, _('&Clear'))
		self.__BTN_clear.SetToolTipString(_('Clear this progress note editor.'))

		self.__BTN_discard = wx.Button(PNL_soap_editors, -1, _('&Discard'))
		self.__BTN_discard.SetToolTipString(_('Discard progress note and close this editor. You will loose any data already typed into this editor !'))

		# - arrange
		szr_btns_right = wx.BoxSizer(wx.HORIZONTAL)
		szr_btns_right.Add(self.__BTN_add_unassociated, 0, wx.SHAPED)
		szr_btns_right.Add(self.__BTN_clear, 0, wx.SHAPED)
		szr_btns_right.Add(self.__BTN_save, 0, wx.SHAPED)
		szr_btns_right.Add(self.__BTN_discard, 0, wx.SHAPED)

		szr_right = wx.BoxSizer(wx.VERTICAL)
		szr_right.Add(self.__soap_notebook, 1, wx.EXPAND)
		szr_right.Add(szr_btns_right)
		PNL_soap_editors.SetSizerAndFit(szr_right)

		# arrange widgets
		self.__splitter.SetMinimumPaneSize(20)
		self.__splitter.SplitVertically(PNL_list, PNL_soap_editors)

		szr_main = wx.BoxSizer(wx.VERTICAL)
		szr_main.Add(self.__splitter, 1, wx.EXPAND, 0)
		self.SetSizerAndFit(szr_main)
	#--------------------------------------------------------
	def __refresh_problem_list(self):
		"""Update health problems list.
		"""
		self.__LST_problems.Clear()
		emr = self.__pat.get_emr()
		problems = emr.get_problems()
		for problem in problems:
			if not problem['problem_active']:
				continue
			if problem['type'] == 'issue':
				issue = emr.problem2issue(problem)
				last_encounter = emr.get_last_encounter(issue_id = issue['pk_health_issue'])
				if last_encounter is None:
					last = issue['modified_when'].strftime('%m/%Y')
				else:
					last = last_encounter['last_affirmed'].strftime('%m/%Y')
				label = u'%s: %s "%s"' % (last, problem['l10n_type'], problem['problem'])
			elif problem['type'] == 'episode':
				epi = emr.problem2episode(problem)
				last_encounter = emr.get_last_encounter(episode_id = epi['pk_episode'])
				if last_encounter is None:
					last = epi['episode_modified_when'].strftime('%m/%Y')
				else:
					last = last_encounter['last_affirmed'].strftime('%m/%Y')
				label = u'%s: %s "%s"%s' % (
					last,
					problem['l10n_type'],
					problem['problem'],
					gmTools.coalesce(initial = epi['health_issue'], instead = '', template_initial = ' (%s)')
				)
			self.__LST_problems.Append(label, problem)
		splitter_width = self.__splitter.GetSizeTuple()[0]
		self.__splitter.SetSashPosition((splitter_width / 2), True)
		self.Refresh()
		#self.Update()
		return True
	#--------------------------------------------------------
	# event handling
	#--------------------------------------------------------
	def __register_interests(self):
		"""Configure enabled event signals
		"""
		# wxPython events
		wx.EVT_LISTBOX_DCLICK(self.__LST_problems, self.__LST_problems.GetId(), self.__on_problem_activated)
		wx.EVT_BUTTON(self.__BTN_save, self.__BTN_save.GetId(), self.__on_save)
		wx.EVT_BUTTON(self.__BTN_clear, self.__BTN_clear.GetId(), self.__on_clear)
		wx.EVT_BUTTON(self.__BTN_discard, self.__BTN_discard.GetId(), self.__on_discard)
		wx.EVT_BUTTON(self.__BTN_add_unassociated, self.__BTN_add_unassociated.GetId(), self.__on_add_unassociated)

		# client internal signals
		gmDispatcher.connect(signal='post_patient_selection', receiver=self._on_post_patient_selection)
		gmDispatcher.connect(signal = 'clin.episode_mod_db', receiver = self._on_episode_issue_mod_db)
		gmDispatcher.connect(signal = 'clin.health_issue_mod_db', receiver = self._on_episode_issue_mod_db)
	#--------------------------------------------------------
	def _on_post_patient_selection(self):
		"""Patient changed."""
		if self.GetParent().GetCurrentPage() == self:
			self.reset_ui_content()
	#--------------------------------------------------------
	def _on_episode_issue_mod_db(self):
		if self.GetParent().GetCurrentPage() == self:
			self.__refresh_problem_list()
	#--------------------------------------------------------
	def __on_clear(self, event):
		"""Clear raised SOAP input widget.
		"""
		soap_nb_page = self.__soap_notebook.GetPage(self.__soap_notebook.GetSelection())
		soap_nb_page.Clear()
	#--------------------------------------------------------
	def __on_discard(self, event):
		"""Discard raised SOAP input widget.

		Will throw away data !
		"""
		self.__soap_notebook.close_current_editor()
	#--------------------------------------------------------
	def __on_add_unassociated(self, evt):
		"""Add new editor for as-yet unassociated progress note.

		Clinical logic as per discussion with Jim Busser:

		- if patient has no episodes:
			- new patient
			- always allow several NEWs
		- if patient has episodes:
			- allow several NEWs per configuration
		"""
		emr = self.__pat.get_emr()
		epis = emr.get_episodes()

		if len(epis) == 0:
			value = True
		else:
			dbcfg = gmCfg.cCfgSQL()
			value = bool(dbcfg.get2 (
				option = u'horstspace.soap_editor.allow_same_episode_multiple_times',
				workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
				bias = u'user',
				default = False
			))

		self.__soap_notebook.add_editor(allow_same_problem = value)
	#--------------------------------------------------------
	def __on_problem_activated(self, event):
		"""
		When the user changes health issue selection, update selected issue
		reference and update buttons according its input status.

		when the user selects a problem in the problem list:
			- check whether selection is issue or episode
			- if editor for episode exists: focus it
			- if no editor for episode exists: create one and focus it
		"""
		problem_idx = self.__LST_problems.GetSelection()
		problem = self.__LST_problems.GetClientData(problem_idx)

		if self.__soap_notebook.add_editor(problem = problem):
			return True

		gmGuiHelpers.gm_show_error (
			aMessage = _(
				'Cannot open progress note editor for\n\n'
				'[%s].\n\n'
			) % problem['problem'],
			aTitle = _('opening progress note editor')
		)
		return False
	#--------------------------------------------------------
	def __on_save(self, event):
		"""Save data to backend and close editor.
		"""
		page_idx = self.__soap_notebook.GetSelection()
		soap_nb_page = self.__soap_notebook.GetPage(page_idx)
		if not soap_nb_page.save():
			gmDispatcher.send(signal='statustext', msg=_('Problem saving progress note: duplicate information ?'))
			return False
		self.__soap_notebook.DeletePage(page_idx)
		# always keep one unassociated editor open
		self.__soap_notebook.add_editor()
		#self.__refresh_problem_list()
		return True
	#--------------------------------------------------------
	# notebook plugin API
	#--------------------------------------------------------
	def repopulate_ui(self):
		self.__refresh_problem_list()
#============================================================
class cSOAPLineDef:
	def __init__(self):
		self.label = _('label missing')
		self.text = ''
		self.soap_cat = _('soap cat missing')
		self.is_rfe = False		# later support via types
		self.data = None
#============================================================
# FIXME: this should be a more generic(ally named) class
# FIXME: living elsewhere
class cPopupDataHolder:

	_data_savers = {}

	def __init__(self):
		self.__data = {}
	#--------------------------------------------------------
	def store_data(self, popup_type=None, desc=None, data=None, old_desc=None):
		# FIXME: do fancy validations

		print "storing popup data:", desc
		print "type", popup_type
		print "data", data

		# verify structure
		try:
			self.__data[popup_type]
		except KeyError:
			self.__data[popup_type] = {}
		# store new data
		self.__data[popup_type][desc] = {
			'data': data
		}
		# remove old data if necessary
		try:
			del self.__data[popup_type][old_desc]
		except:
			pass
		return True
	#--------------------------------------------------------
	def save(self):
		for popup_type in self.__data.keys():
			try:
				saver_func = self.__data_savers[popup_type]
			except KeyError:
				_log.exception('no saver for popup data type [%s] configured', popup_type)
				return False
			for desc in self.__data[popup_type].keys():
				data = self.__data[popup_type][desc]['data']
				saver_func(data)
		return True
	#--------------------------------------------------------
	def clear(self):
		self.__data = {}
	#--------------------------------------------------------
#	def remove_data(self, popup_type=None, desc=None):
#		del self.__data[popup_type][desc]
	#--------------------------------------------------------
	# def get_descs(self, popup_type=None, origination_soap=None):
	# def get_data(self, desc=None):
	# def rename_data(self, old_desc=None, new_desc=None):
#============================================================
class cResizingSoapWin(gmResizingWidgets.cResizingWindow):

	def __init__(self, parent, size, input_defs=None, problem=None):
		"""Resizing SOAP note input editor.

		This is a wrapper around a few resizing STCs (the
		labels and categories are settable) which are
		customized to accept progress note input. It provides
		the unified resizing behaviour.

		Knows how to save it's data into the backend.

		@param input_defs: note's labels and categories
		@type input_defs: list of cSOAPLineDef instances
		"""
		if input_defs is None or len(input_defs) == 0:
			raise gmExceptions.ConstructorError, 'cannot generate note with field defs [%s]' % input_defs

		# FIXME: *actually* this should be a session-local
		# FIXME: holding store at the cClinicalRecord level
		self.__embedded_data_holder = cPopupDataHolder()

		self.__input_defs = input_defs

		gmResizingWidgets.cResizingWindow.__init__(self, parent, id=-1, size=size)

		self.__problem = problem
		if isinstance(problem, gmEMRStructItems.cEpisode):
			self.__problem = emr.episode2problem(episode = problem)
		elif isinstance(problem, gmEMRStructItems.cHealthIssue):
			self.__problem = emr.health_issue2problem(issue = problem)
		self.__pat = gmPerson.gmCurrentPatient()
	#--------------------------------------------------------
	# cResizingWindow API
	#--------------------------------------------------------
	def DoLayout(self):
		"""Visually display input note according to user defined labels.
		"""
		# configure keywords
		for soap_cat in progress_note_keywords.keys():
			category = progress_note_keywords[soap_cat]
			for kwd in category.keys():
				category[kwd]['widget_data_sink'] = self.__embedded_data_holder.store_data
		input_fields = []
		# add fields to edit widget
		# note: this may produce identically labelled lines
		for line_def in self.__input_defs:
			input_field = gmResizingWidgets.cResizingSTC(self, -1, data = line_def)
			input_field.SetText(line_def.text)
			kwds = progress_note_keywords[line_def.soap_cat]
			input_field.set_keywords(popup_keywords=kwds)
			# FIXME: pending matcher setup
			self.AddWidget(widget=input_field, label=line_def.label)
			self.Newline()
			input_fields.append(input_field)
		# setup tab navigation between input fields
		for field_idx in range(len(input_fields)):
			# previous
			try:
				input_fields[field_idx].prev_in_tab_order = input_fields[field_idx-1]
			except IndexError:
				input_fields[field_idx].prev_in_tab_order = None
			# next
			try:
				input_fields[field_idx].next_in_tab_order = input_fields[field_idx+1]
			except IndexError:
				input_fields[field_idx].next_in_tab_order = None
	#--------------------------------------------------------
	# public API
	#--------------------------------------------------------
	def save(self):
		"""Save data into backend."""

		# fill progress_note for import
		progress_note = []
		aoe = u''
		rfe = u''
		has_rfe = False
		soap_lines_contents = self.GetValue()
		for line_content in soap_lines_contents.values():
			if line_content.text.strip() == u'':
				continue
			progress_note.append ({
				gmSOAPimporter.soap_bundle_SOAP_CAT_KEY: line_content.data.soap_cat,
				gmSOAPimporter.soap_bundle_TYPES_KEY: [],		# these types need to come from the editor
				gmSOAPimporter.soap_bundle_TEXT_KEY: line_content.text.rstrip()
			})
			if line_content.data.is_rfe:
				has_rfe = True
				rfe += line_content.text.rstrip()
			if line_content.data.soap_cat == u'a':
				aoe += line_content.text.rstrip()

		emr = self.__pat.get_emr()

		# - new episode, must get name from narrative (or user)
		if (self.__problem is None) or (self.__problem['type'] == 'issue'):
			# work out episode name
			epi_name = u''
			if len(aoe) != 0:
				epi_name = aoe
			else:
				epi_name = rfe

			dlg = wx.TextEntryDialog (
				parent = self,
				message = _('Enter a descriptive name for this new problem:'),
				caption = _('Creating a problem (episode) to save the notelet under ...'),
				defaultValue = epi_name.replace('\r', '//').replace('\n', '//'),
				style = wx.OK | wx.CANCEL | wx.CENTRE
			)
			decision = dlg.ShowModal()
			if decision != wx.ID_OK:
				return False

			epi_name = dlg.GetValue().strip()
			if epi_name == u'':
				gmGuiHelpers.gm_show_error(_('Cannot save a new problem without a name.'), _('saving progress note'))
				return False

			# new unassociated episode
			new_episode = emr.add_episode(episode_name = epi_name[:45], pk_health_issue = None, is_open = True)

			if self.__problem is not None:
				issue = emr.problem2issue(self.__problem)
				if not gmEMRStructWidgets.move_episode_to_issue(episode = new_episode, target_issue = issue, save_to_backend = True):
					print "error moving episode to issue"

			epi_id = new_episode['pk_episode']
		else:
			epi_id = self.__problem['pk_episode']

		# set up clinical context in progress note
		encounter = emr.active_encounter
		staff_id = gmStaff.gmCurrentProvider()['pk_staff']
		clin_ctx = {
			gmSOAPimporter.soap_bundle_EPISODE_ID_KEY: epi_id,
			gmSOAPimporter.soap_bundle_ENCOUNTER_ID_KEY: encounter['pk_encounter'],
			gmSOAPimporter.soap_bundle_STAFF_ID_KEY: staff_id
		}
		for line in progress_note:
			line[gmSOAPimporter.soap_bundle_CLIN_CTX_KEY] = clin_ctx

		# dump progress note to backend
		importer = gmSOAPimporter.cSOAPImporter()
		if not importer.import_soap(progress_note):
			gmGuiHelpers.gm_show_error(_('Error saving progress note.'), _('saving progress note'))
			return False

		# dump embedded data to backend
		if not self.__embedded_data_holder.save():
			gmGuiHelpers.gm_show_error (
				_('Error saving embedded data.'),
				_('saving progress note')
			)
			return False
		self.__embedded_data_holder.clear()

		return True
	#--------------------------------------------------------
	def get_problem(self):
		return self.__problem
	#--------------------------------------------------------
	def is_empty(self):
		editor_content = self.GetValue()

		for field_content in editor_content.values():
			if field_content.text.strip() != u'':
				return False

		return True
#============================================================
class cResizingSoapPanel(wx.Panel):
	"""Basic progress note panel.

	It provides a gmResizingWindow based progress note editor
	with a header line. The header either displays the episode
	this progress note is associated with or it allows for
	entering an episode name. The episode name either names
	an existing episode or is the name for a new episode.

	This panel knows how to save it's data into the backend.

	Can work as:
		a) Progress note creation: displays an empty set of soap entries to
		create a new soap note for the given episode (or unassociated)
	"""
	#--------------------------------------------------------
	def __init__(self, parent, problem=None, input_defs=None):
		"""
		Construct a new SOAP input widget.

		@param parent: the parent widget

		@param episode: the episode to create the SOAP editor for.
		@type episode gmEMRStructItems.cEpisode instance or None (to create an
		unassociated progress note). A gmEMRStructItems.cProblem instance is 
		also allowed to be passed, as the widget will obtain the related cEpisode.

		@param input_defs: the display and associated data for each displayed narrative
		@type input_defs: a list of cSOAPLineDef instances
		"""
		if not isinstance(problem, (gmEMRStructItems.cHealthIssue, gmEMRStructItems.cEpisode, gmEMRStructItems.cProblem, types.NoneType)):
			raise gmExceptions.ConstructorError, 'problem [%s] is of type %s, must be issue, episode, problem or None' % (str(problem), type(problem))

		self.__is_saved = False
		# do layout
		wx.Panel.__init__(self, parent, -1, style = wx.NO_BORDER | wx.TAB_TRAVERSAL)
		# - editor
		if input_defs is None:
			soap_lines = []
			# make Richard the default ;-)
			# FIXME: actually, should be read from backend
			line = cSOAPLineDef()
			line.label = _('Visit Purpose')
			line.soap_cat = 's'
			line.is_rfe = True
			soap_lines.append(line)

			line = cSOAPLineDef()
			line.label = _('History Taken')
			line.soap_cat = 's'
			soap_lines.append(line)

			line = cSOAPLineDef()
			line.label = _('Findings')
			line.soap_cat = 'o'
			soap_lines.append(line)

			line = cSOAPLineDef()
			line.label = _('Assessment')
			line.soap_cat = 'a'
			soap_lines.append(line)

			line = cSOAPLineDef()
			line.label = _('Plan')
			line.soap_cat = 'p'
			soap_lines.append(line)
		else:
			soap_lines = input_defs
		self.__soap_editor = cResizingSoapWin (
			self,
			size = wx.DefaultSize,
			input_defs = soap_lines,
			problem = problem
		)
		# - arrange
		self.__szr_main = wx.BoxSizer(wx.VERTICAL)
		self.__szr_main.Add(self.__soap_editor, 1, wx.EXPAND)
		self.SetSizerAndFit(self.__szr_main)
	#--------------------------------------------------------
	# public API
	#--------------------------------------------------------
	def get_problem(self):
		"""Retrieve the related problem for this SOAP input widget.
		"""
		return self.__soap_editor.get_problem()
	#--------------------------------------------------------
	def is_unassociated_editor(self):
		"""
		Retrieves whether the current editor is not associated
		with any episode.
		"""
		return ((self.__problem is None) or (self.__problem['type'] == 'issue'))
	#--------------------------------------------------------
	def get_editor(self):
		"""Retrieves widget's SOAP text editor.
		"""
		return self.__soap_editor
	#--------------------------------------------------------
	def Clear(self):
		"""Clear any entries in widget's SOAP text editor
		"""
		self.__soap_editor.Clear()
	#--------------------------------------------------------
	def SetSaved(self, is_saved):
		"""
		Set SOAP input widget saved (dumped to backend) state

		@param is_saved: Flag indicating wether the SOAP has been dumped to
						 persistent backend
		@type is_saved: boolean
		"""
		self.__is_saved = is_saved
		self.Clear()
	#--------------------------------------------------------
	def IsSaved(self):
		"""
		Check SOAP input widget saved (dumped to backend) state
		"""
		return self.__is_saved
	#--------------------------------------------------------
	def save(self):
		return self.__soap_editor.save()
	#--------------------------------------------------------
	def editor_empty(self):
		return self.__soap_editor.is_empty()
#============================================================
class cSingleBoxSOAP(wx.TextCtrl):
	"""if we separate it out like this it can transparently gain features"""
	def __init__(self, *args, **kwargs):
		wx.TextCtrl.__init__(self, *args, **kwargs)
#============================================================
class cSingleBoxSOAPPanel(wx.Panel):
	"""Single Box free text SOAP input.

	This widget was suggested by David Guest on the mailing
	list. All it does is provide a single multi-line textbox
	for typing free-text clinical notes which are stored as
	Subjective.
	"""
	def __init__(self, *args, **kwargs):
		wx.Panel.__init__(self, *args, **kwargs)
		self.__do_layout()
		self.__pat = gmPerson.gmCurrentPatient()
		if not self.__register_events():
			raise gmExceptions.ConstructorError, 'cannot register interests'
	#--------------------------------------------------------
	def __do_layout(self):
		# large box for free-text clinical notes
		self.__soap_box = cSingleBoxSOAP (
			self,
			-1,
			'',
			style = wx.TE_MULTILINE
		)
		# buttons below that
		self.__BTN_save = wx.Button(self, wx.NewId(), _("save"))
		self.__BTN_save.SetToolTipString(_('save clinical note in EMR'))
		self.__BTN_discard = wx.Button(self, wx.NewId(), _("discard"))
		self.__BTN_discard.SetToolTipString(_('discard clinical note'))
		szr_btns = wx.BoxSizer(wx.HORIZONTAL)
		szr_btns.Add(self.__BTN_save, 1, wx.ALIGN_CENTER_HORIZONTAL, 0)
		szr_btns.Add(self.__BTN_discard, 1, wx.ALIGN_CENTER_HORIZONTAL, 0)
		# arrange widgets
		szr_outer = wx.StaticBoxSizer(wx.StaticBox(self, -1, _("clinical progress note")), wx.VERTICAL)
		szr_outer.Add(self.__soap_box, 1, wx.EXPAND, 0)
		szr_outer.Add(szr_btns, 0, wx.EXPAND, 0)
		# and do layout
		self.SetAutoLayout(1)
		self.SetSizer(szr_outer)
		szr_outer.Fit(self)
		szr_outer.SetSizeHints(self)
		self.Layout()
	#--------------------------------------------------------
	def __register_events(self):
		# wxPython events
		wx.EVT_BUTTON(self.__BTN_save, self.__BTN_save.GetId(), self._on_save_note)
		wx.EVT_BUTTON(self.__BTN_discard, self.__BTN_discard.GetId(), self._on_discard_note)

		# client internal signals
		gmDispatcher.connect(signal = 'pre_patient_selection', receiver = self._save_note)
		gmDispatcher.connect(signal = 'application_closing', receiver = self._save_note)

		return True
	#--------------------------------------------------------
	# event handlers
	#--------------------------------------------------------
	def _on_save_note(self, event):
		self.__save_note()
		#event.Skip()
	#--------------------------------------------------------
	def _on_discard_note(self, event):
		# FIXME: maybe ask for confirmation ?
		self.__soap_box.SetValue('')
		#event.Skip()
	#--------------------------------------------------------
	# internal helpers
	#--------------------------------------------------------
	def _save_note(self):
		wx.CallAfter(self.__save_note)
	#--------------------------------------------------------
	def __save_note(self):
		# sanity checks
		if self.__pat is None:
			return True
		if not self.__pat.connected:
			return True
		if not self.__soap_box.IsModified():
			return True
		note = self.__soap_box.GetValue()
		if note.strip() == '':
			return True
		# now save note
		emr = self.__pat.get_emr()
		if emr is None:
			_log.error('cannot access clinical record of patient')
			return False
		if not emr.add_clin_narrative(note, soap_cat='s'):
			_log.error('error saving clinical note')
			return False
		self.__soap_box.SetValue('')
		return True
#============================================================
# main
#------------------------------------------------------------
if __name__ == "__main__":

	import sys

	from Gnumed.pycommon import gmPG2
	#--------------------------------------------------------
	def get_narrative(pk_encounter=None, pk_health_issue = None, default_labels=None):
		"""
		Retrieve the soap editor input lines definitions built from
		all the narratives for the given issue along a specific
		encounter.

		@param pk_health_issue The id of the health issue to obtain the narratives for.
		@param pk_health_issue An integer instance

		@param pk_encounter The id of the encounter to obtain the narratives for.
		@type A gmEMRStructItems.cEncounter instance.

		@param default_labels: The user customized labels for each
		soap category.
		@type default_labels: A dictionary instance which keys are
		soap categories.
		"""
		# custom labels
		if default_labels is None:
			default_labels = {
				's': _('History Taken'),
				'o': _('Findings'),
				'a': _('Assessment'),
				'p': _('Plan')
		}

		pat = gmPerson.gmCurrentPatient()
		emr = pat.get_emr()
		soap_lines = []
		# for each soap cat
		for soap_cat in gmSOAPimporter.soap_bundle_SOAP_CATS:
			# retrieve narrative for given encounter
			narr_items =  emr.get_clin_narrative (
				encounters = [pk_encounter],
				issues = [pk_health_issue],
				soap_cats = [soap_cat]
			)
			for narrative in narr_items:
				try:
					# FIXME: add more data such as doctor sig
					label_txt = default_labels[narrative['soap_cat']]
				except:
					label_txt = narrative['soap_cat']
				line = cSOAPLineDef()
				line.label = label_txt
				line.text = narrative['narrative']
#				line.data['narrative instance'] = narrative
				soap_lines.append(line)
		return soap_lines
	#--------------------------------------------------------
	def create_widget_on_test_kwd1(*args, **kwargs):
		print "test keyword must have been typed..."
		print "actually this would have to return a suitable wx.Window subclass instance"
		print "args:", args
		print "kwd args:"
		for key in kwargs.keys():
			print key, "->", kwargs[key]
	#--------------------------------------------------------
	def create_widget_on_test_kwd2(*args, **kwargs):
		msg = (
			"test keyword must have been typed...\n"
			"actually this would have to return a suitable wx.Window subclass instance\n"
		)
		for arg in args:
			msg = msg + "\narg ==> %s" % arg
		for key in kwargs.keys():
			msg = msg + "\n%s ==> %s" % (key, kwargs[key])
		gmGuiHelpers.gm_show_info (
			aMessage = msg,
			aTitle = 'msg box on create_widget from test_keyword'
		)
	#--------------------------------------------------------
	def test_soap_notebook():
		print 'testing notebooked soap input...'
		application = wx.PyWidgetTester(size=(800,500))
		soap_input = cProgressNoteInputNotebook(application.frame, -1)
		application.frame.Show(True)
		application.MainLoop()
	#--------------------------------------------------------
	def test_soap_notebook_panel():
		print 'testing notebooked soap panel...'
		application = wx.PyWidgetTester(size=(800,500))
		soap_input = cNotebookedProgressNoteInputPanel(application.frame, -1)
		application.frame.Show(True)
		application.MainLoop()
	#--------------------------------------------------------

	try:
		# obtain patient
		patient = gmPersonSearch.ask_for_patient()
		if patient is None:
			print "No patient. Exiting gracefully..."
			sys.exit(0)
		gmPatSearchWidgets.set_active_patient(patient=patient)

		#test_soap_notebook()
		test_soap_notebook_panel()

#		# multisash soap
#		print 'testing multisashed soap input...'
#		application = wx.PyWidgetTester(size=(800,500))
#		soap_input = cMultiSashedProgressNoteInputPanel(application.frame, -1)
#		application.frame.Show(True)
#		application.MainLoop()

#		# soap widget displaying all narratives for an issue along an encounter
#		print 'testing soap editor for encounter narratives...'
#		episode = gmEMRStructItems.cEpisode(aPK_obj=1)
#		encounter = gmEMRStructItems.cEncounter(aPK_obj=1)
#		narrative = get_narrative(pk_encounter = encounter['pk_encounter'], pk_health_issue = episode['pk_health_issue'])
#		default_labels = {'s':'Subjective', 'o':'Objective', 'a':'Assesment', 'p':'Plan'}
#		app = wx.PyWidgetTester(size=(300,500))		
#		app.SetWidget(cResizingSoapPanel, episode, narrative)
#		app.MainLoop()
#		del app

#		# soap progress note for episode
#		print 'testing soap editor for episode...'
#		app = wx.PyWidgetTester(size=(300,300))
#		app.SetWidget(cResizingSoapPanel, episode)
#		app.MainLoop()
#		del app

#		# soap progress note for problem
#		print 'testing soap editor for problem...'
#		problem = gmEMRStructItems.cProblem(aPK_obj={'pk_patient': 12, 'pk_health_issue': 1, 'pk_episode': 1})		
#		app = wx.PyWidgetTester(size=(300,300))
#		app.SetWidget(cResizingSoapPanel, problem)
#		app.MainLoop()
#		del app

#		# unassociated soap progress note
#		print 'testing unassociated soap editor...'
#		app = wx.PyWidgetTester(size=(300,300))
#		app.SetWidget(cResizingSoapPanel, None)
#		app.MainLoop()
#		del app

#		# unstructured progress note
#		print 'testing unstructured progress note...'
#		app = wx.PyWidgetTester(size=(600,600))
#		app.SetWidget(cSingleBoxSOAPPanel, -1)
#		app.MainLoop()

	except StandardError:
		_log.exception("unhandled exception caught !")
		# but re-raise them
		raise

#============================================================