File: gmTopPanel.py

package info (click to toggle)
gnumed-client 1.8.5%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 37,672 kB
  • sloc: python: 126,459; javascript: 6,113; sh: 1,192; xml: 36; makefile: 33
file content (415 lines) | stat: -rw-r--r-- 14,171 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
# GNUmed

#===========================================================
__author__  = "R.Terry <rterry@gnumed.net>, I.Haywood <i.haywood@ugrad.unimelb.edu.au>, K.Hilbert <Karsten.Hilbert@gmx.net>"
__license__ = "GPL v2 or later"


import sys
import os.path
import datetime as pyDT
import logging
import decimal


import wx


from Gnumed.pycommon import gmGuiBroker
from Gnumed.pycommon import gmDispatcher
from Gnumed.pycommon import gmTools
from Gnumed.pycommon import gmCfg
from Gnumed.pycommon import gmCfg2
from Gnumed.pycommon import gmDateTime
from Gnumed.pycommon import gmI18N
from Gnumed.pycommon import gmExceptions

from Gnumed.business import gmPerson
from Gnumed.business import gmEMRStructItems
from Gnumed.business import gmAllergy
from Gnumed.business import gmLOINC
from Gnumed.business import gmClinicalCalculator
from Gnumed.business import gmPathLab
from Gnumed.business import gmPraxis

from Gnumed.wxpython import gmGuiHelpers
from Gnumed.wxpython import gmDemographicsWidgets
from Gnumed.wxpython import gmAllergyWidgets
from Gnumed.wxpython import gmPatSearchWidgets
from Gnumed.wxpython import gmEMRStructWidgets
from Gnumed.wxpython import gmPatPicWidgets


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

#===========================================================
from Gnumed.wxGladeWidgets import wxgTopPnl

class cTopPnl(wxgTopPnl.wxgTopPnl):

	def __init__(self, *args, **kwargs):

		wxgTopPnl.wxgTopPnl.__init__(self, *args, **kwargs)

		self.__gb = gmGuiBroker.GuiBroker()

		self.curr_pat = gmPerson.gmCurrentPatient()

		self.__init_ui()
		self.__register_interests()

	#-------------------------------------------------------
	def __init_ui(self):
		cfg = gmCfg2.gmCfgData()
		if cfg.get(option = 'slave'):
			self._TCTRL_patient_selector.SetEditable(0)
			self._TCTRL_patient_selector.SetToolTip(None)

		if sys.platform == 'darwin':
			_log.debug('adjusting font size on Mac for top panel parts')
			for ctrl in [self._TCTRL_patient_selector, self._LBL_age, self._LBL_allergies, self._TCTRL_allergies]:
				curr_font = ctrl.GetFont()
				mac_font = wx.Font(curr_font.GetNativeFontInfo())
				mac_font.SetPointSize(pointSize = int(curr_font.GetPointSize() / 0.8))
				ctrl.SetFont(mac_font)

		self.__lab_panel = self.__get_lab_panel()

	#-------------------------------------------------------
	def __register_interests(self):
		# events
		self._TCTRL_allergies.Bind(wx.EVT_LEFT_DCLICK, self._on_allergies_dclicked)

		# client internal signals
		gmDispatcher.connect(signal = 'post_patient_selection', receiver = self._on_post_patient_selection)
		gmDispatcher.connect(signal = 'focus_patient_search', receiver = self._on_focus_patient_search)

		gmDispatcher.connect(signal = 'gm_table_mod', receiver = self._on_database_signal)

	#----------------------------------------------
	# event handling
	#----------------------------------------------
	def _on_allergies_dclicked(self, evt):
		if not self.curr_pat.connected:
			gmDispatcher.send('statustext', msg = _('Cannot activate Allergy Manager. No active patient.'))
			return
		dlg = gmAllergyWidgets.cAllergyManagerDlg(parent=self, id=-1)
		dlg.ShowModal()
		return

	#----------------------------------------------
	def _on_database_signal(self, **kwds):

		if kwds['table'] not in ['dem.identity', 'dem.names', 'dem.identity_tag', 'clin.allergy', 'clin.allergy_state', 'clin.test_result', 'clin.patient']:
			return True

		if self.curr_pat.connected:
			# signal is not about our patient: ignore signal
			if kwds['pk_identity'] != self.curr_pat.ID:
				return True

		if kwds['table'] == 'dem.identity':
			# we don't care about newly INSERTed or DELETEd patients
			if kwds['operation'] != 'UPDATE':
				return True
			self.__update_age_label()
			return True

		if kwds['table'] == 'dem.names':
			self.__update_age_label()
			return True

		if kwds['table'] == 'dem.identity_tag':
			self.__update_tags()
			return True

		if kwds['table'] in ['clin.allergy', 'clin.allergy_state']:
			self.__update_allergies()
			return True

		if kwds['table'] in ['clin.test_result', 'clin.patient']:
			self.__update_lab()
			return True

		return True

	#----------------------------------------------
	def _on_post_patient_selection(self, **kwargs):
		wx.CallAfter(self.__on_post_patient_selection)

	#-------------------------------------------------------
	def __on_post_patient_selection(self):
		self.__update_age_label()
		self.__update_allergies()
		self.__update_tags()
		self.__update_lab()
		self.Layout()

	#-------------------------------------------------------
	def _on_focus_patient_search(self, **kwargs):
		wx.CallAfter(self._TCTRL_patient_selector.SetFocus)

	#-------------------------------------------------------
	# internal API
	#-------------------------------------------------------
	def __get_lab_panel(self):
		# get panel to use
		dbcfg = gmCfg.cCfgSQL()
		pk_panel = dbcfg.get2 (
			option = u'horstspace.top_panel.lab_panel',
			workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
			bias = 'user'
		)
		if pk_panel is None:
			return None

		try:
			panel = gmPathLab.cTestPanel(aPK_obj = pk_panel)
		except gmExceptions.ConstructorError:
			_log.exception('cannot load configured test panel')
			panel = None
		if panel is not None:
			return panel

		_log.error('Cannot load test panel [#%s] configured for patient pane (horstspace.top_panel.lab_panel).', pk_panel)
		gmGuiHelpers.gm_show_error (
			title = _('GNUmed startup'),
			error = _(
				'Cannot load test panel [#%s] configured\n'
				'for the top pane with option\n'
				'\n'
				' <horstspace.top_panel.lab_panel>\n'
				'\n'
				'Please reconfigure.'
			) % pk_panel
		)
		return None

	#-------------------------------------------------------
	def __update_tags(self):
		self._PNL_tags.refresh(patient = self.curr_pat)

	#-------------------------------------------------------
	def __update_lab(self):

		if not self.curr_pat.connected:
			self._LBL_lab.SetLabel('')
			return

		tests2show = []

		rrs = self.curr_pat.emr.get_most_recent_results_in_loinc_group(loincs = gmLOINC.LOINC_rr_quantity, max_no_of_results = 1)
		if len(rrs) == 0:
			tests2show.append(_('RR ?'))
		else:
			tests2show.append(rrs[0]['unified_val'])

		hrs = self.curr_pat.emr.get_most_recent_results_in_loinc_group(loincs = gmLOINC.LOINC_heart_rate_quantity, max_no_of_results = 1)
		if len(hrs) > 0:
			tests2show.append('%s %s' % (hrs[0]['abbrev_tt'], hrs[0]['unified_val']))

		bmi = self.curr_pat.emr.bmi
		if bmi.numeric_value is not None:
			tests2show.append(_('BMI %s') % bmi.numeric_value.quantize(decimal.Decimal('1.')))
		else:
			weights = self.curr_pat.emr.get_most_recent_results_in_loinc_group(loincs = gmLOINC.LOINC_weight, max_no_of_results = 1)
			if len(weights) == 0:
				tests2show.append(_('BMI ?'))
			else:
				tests2show.append('%s%s' % (weights[0]['unified_val'], weights[0]['val_unit']))

		gfr_or_crea = self.curr_pat.emr.best_gfr_or_crea
		if gfr_or_crea is None:
			tests2show.append(_('GFR ?'))
		else:
			try:
				tests2show.append(_('GFR %s') % gfr_or_crea.numeric_value.quantize(decimal.Decimal('1.')))
			except AttributeError:
				tests2show.append('%s %s' % (gfr_or_crea['abbrev_tt'], gfr_or_crea['unified_val']))

		edc = self.curr_pat.emr.EDC
		if edc is not None:
			if self.curr_pat.emr.EDC_is_fishy:
				tests2show.append(_('?EDC %s') % gmDateTime.pydt_strftime(edc, '%Y-%b-%d', accuracy = gmDateTime.acc_days))
			else:
				tests2show.append(_('EDC %s') % gmDateTime.pydt_strftime(edc, '%Y-%b-%d', accuracy = gmDateTime.acc_days))

		inrs = self.curr_pat.emr.get_most_recent_results_in_loinc_group(loincs = gmLOINC.LOINC_inr_quantity, max_no_of_results = 1)
		if len(inrs) > 0:
			tests2show.append('%s %s' % (inrs[0]['abbrev_tt'], inrs[0]['unified_val']))

		# include panel if configured, only show if exist
		if self.__lab_panel is not None:
			for result in self.__lab_panel.get_most_recent_results(pk_patient = self.curr_pat.ID, order_by = 'unified_abbrev', group_by_meta_type = True):
				tests2show.append('%s %s' % (result['abbrev_tt'], result['unified_val']))

		self._LBL_lab.SetLabel('; '.join(tests2show))

	#-------------------------------------------------------
	def __update_age_label(self):

		# no patient
		if not self.curr_pat.connected:
			self._LBL_age.SetLabel(_('<Age>'))
			self._LBL_age.SetToolTip(_('no patient selected'))
			return

		# gender is always known
		tt = _('Gender: %s (%s) - %s\n') % (
			self.curr_pat.gender_symbol,
			gmTools.coalesce(self.curr_pat['gender'], '?'),
			self.curr_pat.gender_string
		)

		# dob is not known
		if self.curr_pat['dob'] is None:
			age = '%s  %s' % (
				self.curr_pat.gender_symbol,
				self.curr_pat.get_formatted_dob()
			)
			self._LBL_age.SetLabel(age)
			self._LBL_age.SetToolTip(tt)
			return

		tt += _('Born: %s\n') % self.curr_pat.get_formatted_dob(format = '%d %b %Y')

		# patient is dead
		if self.curr_pat['deceased'] is not None:
			tt += _('Died: %s\n') % gmDateTime.pydt_strftime(self.curr_pat['deceased'], '%d %b %Y')
			tt += _('At age: %s\n') % self.curr_pat['medical_age']
			age = '%s  %s - %s (%s)' % (
				self.curr_pat.gender_symbol,
				self.curr_pat.get_formatted_dob(format = '%d %b %Y'),
				gmDateTime.pydt_strftime(self.curr_pat['deceased'], '%d %b %Y'),
				self.curr_pat['medical_age']
			)
			if self.curr_pat['dob_is_estimated']:
				tt += _(' (date of birth and age are estimated)\n')
			self._LBL_age.SetLabel(age)
			self._LBL_age.SetToolTip(tt)
			return

		# patient alive
		now = gmDateTime.pydt_now_here()

		# patient birthday ?
		if self.curr_pat.get_formatted_dob(format = '%m-%d', honor_estimation = False) == now.strftime('%m-%d'):
			template = _('%(sex)s  %(dob)s (%(age)s today !)')
			tt += _("\nToday is the patient's birthday !\n\n")
			tt += _('Age: %s\n') % self.curr_pat['medical_age']
		else:
			tt += _('Age: %s, birthday:\n') % self.curr_pat['medical_age']
			if self.curr_pat.current_birthday_passed is True:
				template = '%(sex)s  %(dob)s%(l_arr)s (%(age)s)'
				tt += ' ' + _('last: %s ago (this year)') % gmDateTime.format_apparent_age_medically (
					age = gmDateTime.calculate_apparent_age(start = self.curr_pat.birthday_this_year, end = now)
				) + '\n'
				tt += ' ' + _('next: in %s (next year)') % gmDateTime.format_apparent_age_medically (
					age = gmDateTime.calculate_apparent_age(start = now, end = self.curr_pat.birthday_next_year)
				) + '\n'
			elif self.curr_pat.current_birthday_passed is False:
				template = '%(sex)s  %(r_arr)s%(dob)s (%(age)s)'
				tt += ' ' + _('next: in %s (this year)') % gmDateTime.format_apparent_age_medically (
					age = gmDateTime.calculate_apparent_age(start = now, end = self.curr_pat.birthday_this_year)
				) + '\n'
				tt += ' ' + _('last: %s ago (last year)') % gmDateTime.format_apparent_age_medically (
					age = gmDateTime.calculate_apparent_age(start = self.curr_pat.birthday_last_year, end = now)
				) + '\n'
			else:	# None, unknown
				template = '%(sex)s  %(dob)s (%(age)s)'

		# FIXME: if the age is below, say, 2 hours we should fire
		# a timer here that updates the age in increments of 1 minute ... :-)
		age = template % {
			'sex': self.curr_pat.gender_symbol,
			'dob': self.curr_pat.get_formatted_dob(format = '%d %b %Y'),
			'age': self.curr_pat['medical_age'],
			'r_arr': gmTools.u_arrow2right,
			'l_arr': gmTools.u_left_arrow
		}

		# Easter Egg ;-)
		if self.curr_pat['lastnames'] == 'Leibner':
			if self.curr_pat['firstnames'] == 'Steffi':
				if self.curr_pat['preferred'] == 'Wildfang':
					age = '%s %s' % (gmTools.u_black_heart, age)

		if self.curr_pat['dob_is_estimated']:
			tt += _(' (date of birth and age are estimated)\n')

		self._LBL_age.SetLabel(age)
		self._LBL_age.SetToolTip(tt)

	#-------------------------------------------------------
	def __update_allergies(self, **kwargs):

		if not self.curr_pat.connected:
			self._LBL_allergies.SetForegroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT))
			self._TCTRL_allergies.SetForegroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT))
			self._TCTRL_allergies.SetValue('')
			self._TCTRL_allergies.SetToolTip('')
			return

		show_red = True

		emr = self.curr_pat.emr
		state = emr.allergy_state

		# state in tooltip
		if state['last_confirmed'] is None:
			confirmed = _('never')
		else:
			confirmed = gmDateTime.pydt_strftime(state['last_confirmed'], '%Y %b %d')
		tt = (state.state_string + (90 * ' '))[:90] + '\n'
		tt += _('last confirmed %s\n') % confirmed
		tt += gmTools.coalesce(state['comment'], '', _('Comment (%s): %%s') % state['modified_by'])
		tt += '\n'

		# allergies
		display = []
		for allergy in emr.get_allergies():
			# in field: "true" allergies only, not intolerances
			if allergy['type'] == 'allergy':
				display.append(allergy['descriptor'][:10].strip() + gmTools.u_ellipsis)
			# in tooltip
			if allergy['definite']:
				certainty = _('definite')
			else:
				certainty = _('suspected')
			reaction = gmTools.coalesce(allergy['reaction'], _('reaction not recorded'))
			if len(reaction) > 50:
				reaction = reaction[:50] + gmTools.u_ellipsis
			tt += '%s (%s, %s): %s\n' % (
				allergy['descriptor'],
				allergy['l10n_type'],
				certainty,
				reaction
			)

		if len(display) == 0:
			display = state.state_symbol
			if display == gmTools.u_diameter:
				show_red = False
		else:
			display = ','.join(display)

		if state['last_confirmed'] is not None:
			display += gmDateTime.pydt_strftime(state['last_confirmed'], ' (%Y %b)')

		if show_red:
			self._LBL_allergies.SetForegroundColour('red')
			self._TCTRL_allergies.SetForegroundColour('red')
		else:
			self._LBL_allergies.SetForegroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT))
			self._TCTRL_allergies.SetForegroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT))

		self._TCTRL_allergies.SetValue(display)
		self._TCTRL_allergies.SetToolTip(tt)

#===========================================================	
if __name__ == "__main__":
	app = wxPyWidgetTester(size = (400, 200))
	app.SetWidget(cMainTopPanel, -1)
	app.SetWidget(cTopPanel, -1)
	app.MainLoop()
#===========================================================