Exemple #1
0
    def activating_node(self, event): # wxGlade: cAU_VaccV01Panel.<event_handler>
        print "Event handler `activating_node' not implemented"
	n = event.GetItem()

        event.Skip(1)
	t = self.tree_ctrl_1
	#import pdb
	#pdb.set_trace()
	
	if n in self._rec_nodes:
		recommender = t.GetItemData( n).GetData()
		active = True
		for v in self._vreg[0][recommender]:
			if not v['pk_regime'] in self._active_recs:
				active = False
				break

		if active:
			msg = " unenrolling in the selected recommenders' regimes ( will fail if any vaccinations linked to regime)"
		else:
			msg = "enroll in regime of recommender " + str( recommender) 
			
		answ = wx.MessageDialog(self, _("Proceed with " + msg + "?")).ShowModal()
		failures = []
		success = []
		#import pdb
		#pdb.set_trace()
		if answ == wx.ID_OK and not active:
			for v in self._vreg[0][recommender]:
				result = False
				id = gmPerson.gmCurrentPatient().ID
				if v['pk_regime'] in success:
					continue
				if id:
					result,msg = gmVaccination.put_patient_on_schedule(id, v['pk_regime'])
				if not result:
					failures.append(v)
				else:
					success.append(v['pk_regime'])
			if len(failures):
				wx.MessageDialog(self, _("Failed to enrol patient in %s") % ',  '.join( [ f['regime'] for f in failures] ) , style = wx.OK  ).ShowModal()
				
		if answ == wx.ID_OK and active:
			for v in self._vreg[0][recommender]:
				result = False
				id = gmPerson.gmCurrentPatient().ID
				if v['pk_regime'] in success:
					continue
				if id:
					result,msg = gmVaccination.remove_patient_from_schedule(id, v['pk_regime'])
				if not result:
					failures.append(v)
				else:
					success.append(v['pk_regime'])
			if len(failures):
				wx.MessageDialog(self, _("Failed to  delist patient from %s") % ',  '.join( [ f['regime'] for f in failures] ) , style = wx.OK  ).ShowModal()
	
	self._on_post_patient_selection()
Exemple #2
0
	def _calc_documents_list_item_tooltip(self, data):
		emr = gmPerson.gmCurrentPatient().emr

		if isinstance(data, gmDocuments.cDocument):
			return data.format()

		return None
Exemple #3
0
	def _save_as_new(self):

		pat = gmPerson.gmCurrentPatient()
		emr = pat.emr

		epi = emr.add_episode(episode_name = self._PRW_description.GetValue().strip())
		epi['summary'] = self._TCTRL_status.GetValue().strip()
		epi['episode_open'] = not self._CHBOX_closed.IsChecked()
		epi['diagnostic_certainty_classification'] = self._PRW_certainty.GetData()

		issue_name = self._PRW_issue.GetValue().strip()
		if len(issue_name) != 0:
			epi['pk_health_issue'] = self._PRW_issue.GetData(can_create = True)
			issue = gmEMRStructItems.cHealthIssue(aPK_obj = epi['pk_health_issue'])

			if not move_episode_to_issue(episode = epi, target_issue = issue, save_to_backend = False):
				gmDispatcher.send (
					signal = 'statustext',
					msg = _('Cannot attach episode [%s] to health issue [%s] because it already has a running episode.') % (
						epi['description'],
						issue['description']
					)
				)
				gmEMRStructItems.delete_episode(episode = epi)
				return False

		epi.save()

		epi.generic_codes = [ c['data'] for c in self._PRW_codes.GetData() ]

		self.data = epi
		return True
Exemple #4
0
			def OnInit (self):
				"""
				Create test application UI
				"""
				frame = wx.Frame (
							None,
							-4,
							'Testing EMR struct widgets',
							size=wx.Size(600, 400),
							style=wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE
						)
				filemenu = wx.Menu()
				filemenu.AppendSeparator()
				item = filemenu.Append(ID_EXIT, "E&xit"," Terminate test application")
				self.Bind(wx.EVT_MENU, self.OnCloseWindow, item)

				# Creating the menubar.
				menuBar = wx.MenuBar()
				menuBar.Append(filemenu,"&File")

				frame.SetMenuBar(menuBar)

				txt = wx.StaticText( frame, -1, _("Select desired test option from the 'File' menu"),
				wx.DefaultPosition, wx.DefaultSize, 0 )

				# patient EMR
				self.__pat = gmPerson.gmCurrentPatient()

				frame.Show(1)
				return 1
Exemple #5
0
	def _on_leave_year_noted(self, *args, **kwargs):

		if not self._PRW_year_noted.IsModified():
			return True

		year_noted = self._PRW_year_noted.GetData()

		if year_noted is None:
			if self._PRW_year_noted.GetValue().strip() == '':
				self._PRW_year_noted.display_as_valid(True)
				return True
			self._PRW_year_noted.display_as_valid(False)
			return True

		year_noted = year_noted.get_pydt()

		if year_noted >= pydt.datetime.now(tz = year_noted.tzinfo):
			self.status_message = _('Condition diagnosed in the future.')
			self._PRW_year_noted.display_as_valid(False)
			return True

		self._PRW_year_noted.display_as_valid(True)

		pat = gmPerson.gmCurrentPatient()
		if pat['dob'] is not None:
			issue_age = year_noted - pat['dob']
			age_str = gmDateTime.format_interval_medically(interval = issue_age)
			self._PRW_age_noted.SetText(age_str, issue_age, True)

		return True
Exemple #6
0
	def _save_as_new(self):
		pat = gmPerson.gmCurrentPatient()
		emr = pat.emr

		issue = emr.add_health_issue(issue_name = self._PRW_condition.GetValue().strip())

		side = ''
		if self._ChBOX_left.GetValue():
			side += 's'
		if self._ChBOX_right.GetValue():
			side += 'd'
		issue['laterality'] = side

		issue['summary'] = self._TCTRL_status.GetValue().strip()
		issue['diagnostic_certainty_classification'] = self._PRW_certainty.GetData()
		issue['grouping'] = self._PRW_grouping.GetValue().strip()
		issue['is_active'] = self._ChBOX_active.GetValue()
		issue['clinically_relevant'] = self._ChBOX_relevant.GetValue()
		issue['is_confidential'] = self._ChBOX_confidential.GetValue()
		issue['is_cause_of_death'] = self._ChBOX_caused_death.GetValue()

		age_noted = self._PRW_age_noted.GetData()
		if age_noted is not None:
			issue['age_noted'] = age_noted

		issue.save()

		issue.generic_codes = [ c['data'] for c in self._PRW_codes.GetData() ]

		self.data = issue
		return True
Exemple #7
0
	def _on_identity_item_activated(self, event):
		data = self._LCTRL_identity.get_selected_item_data(only_one = True)
		if data is None:
			gmDispatcher.send(signal = 'display_widget', name = 'gmNotebookedPatientEditionPlugin')

		# <ctrl> down ?
		if not wx.GetKeyState(wx.WXK_CONTROL):
			gmDispatcher.send(signal = 'display_widget', name = 'gmNotebookedPatientEditionPlugin')

		# <ctrl> down !
		if isinstance(data, gmPerson.cPersonName):
			ea = gmDemographicsWidgets.cPersonNameEAPnl(self, -1, name = data)
			dlg = gmEditArea.cGenericEditAreaDlg2(self, -1, edit_area = ea, single_entry = True)
			dlg.SetTitle(_('Cloning name'))
			dlg.ShowModal()
			return

		if isinstance(data, dict):
			key = list(data.keys())[0]
			val = data[key]
			if key == 'id':
				ea = gmDemographicsWidgets.cExternalIDEditAreaPnl(self, -1, external_id = val)
				ea.id_holder = gmPerson.gmCurrentPatient()
				dlg = gmEditArea.cGenericEditAreaDlg2(self, -1, edit_area = ea, single_entry = True)
				dlg.SetTitle(_('Editing external ID'))
				dlg.ShowModal()
				return
			if key == 'job':
				gmDemographicsWidgets.edit_occupation()
				return
Exemple #8
0
    def _populate_vacc_regime_tree(self):
	# populate vacc regime choice tree
	p = gmPerson.gmCurrentPatient()	
	self._vreg, self._active_recs = gmVaccination.get_vacc_regimes_by_recommender_ordered( int ( p.ID ) )
	vreg = self._vreg
	t = self.tree_ctrl_1
	t.DeleteAllItems()
	root = t.AddRoot( _('Vaccinations by Recommender (X = patient on regime, O = patient not on regime) ') )
	
	self._rec_nodes = []
	for recommender in vreg[1]:
		
		
		rec_node = t.AppendItem( root, str(recommender) , data = wx.TreeItemData(recommender) )	
		self._rec_nodes .append(rec_node)
		
		last_min_age = -1
		age_node = None

		on_rec = False
		
		for v in vreg[0][recommender]:
			t, v, age_node, last_min_age, def_node = self._update_age_ordered_vacc_tree( t, v, rec_node, age_node, last_min_age)
		
			if int(v['pk_regime']) in self._active_recs:		
		
				marker = ' - x'
				colour = wx.GREEN
			else:
				marker = ' - O'
				colour = wx.RED
				
			t.SetItemText( def_node, t.GetItemText(def_node) + marker)
			t.SetItemTextColour( def_node, colour)
	expand_tree(t, root , 2)
Exemple #9
0
	def _display_name(self):

		curr_pat = gmPerson.gmCurrentPatient()
		if curr_pat.connected:
			name = curr_pat['description']
			if curr_pat.locked:
				name = _('%(name)s (locked)') % {'name': name}
		else:
			if curr_pat.locked:
				name = _('<patient search locked>')
			else:
				name = _('<type here to search patient>')

		self.SetValue(name)

		# adjust tooltip
		if self.person is None:
			self.SetToolTip(self._tt_search_hints)
			return

		if (self.person['emergency_contact'] is None) and (self.person['comment'] is None):
			separator = ''
		else:
			separator = '%s\n' % (gmTools.u_box_horiz_single * 40)

		tt = '%s%s%s%s' % (
			gmTools.coalesce(self.person['emergency_contact'], '', '%s\n %%s\n' % _('In case of emergency contact:')),
			gmTools.coalesce(self.person['comment'], '', '\n%s\n'),
			separator,
			self._tt_search_hints
		)
		self.SetToolTip(tt)
Exemple #10
0
	def __add_new_health_issue_to_record(self):
		print "add new health issue to record"
		pat = gmPerson.gmCurrentPatient()
		rec = pat.get_clinical_record()
		issue = rec.add_health_issue( self.get_emr_tree().GetItemText(self.edit_node).strip() )
		if not issue is None and isinstance(issue, gmEMRStructItems.cHealthIssue):
			self.get_emr_tree().SetPyData( self.edit_node, issue)
Exemple #11
0
    def _populate_vaccination_history_list(self):
    	# populate vaccination history
    	print self, "got on patient selected"
	p = gmPerson.gmCurrentPatient()	
	emr = p.get_emr()
	vv = emr.get_vaccinations()
	l = self.list_ctrl_1
	l.ClearAll()
	cols =  [ _('Date'), _('Vaccine'), _('Sequence'), _('Batch'), _('Site'), _('Narrative'), _('Vaccinator') ]
	for c, i in zip(cols, range(len(cols)) ):
		l.InsertColumn( i, c)
	
	fields = [ 'date', 'vaccine', 'seq_no', 'batch_no', 'site', 'narrative', 'pk_provider' ]
	for v, i  in zip( vv, range(len(vv))):
		for f, j in zip(fields,range(len(fields)) ):	
			if j == 0:
				l.InsertStringItem( i,  str(v[f])) 
			else:
				l.SetStringItem(i, j, str(v[f]) )
	
	for i in range(len(cols)):
		l.SetColumnWidth( i, wx.LIST_AUTOSIZE)
		w1 = l.GetColumnWidth(i)
		l.SetColumnWidth( i, wx.LIST_AUTOSIZE_USEHEADER)
		w2 = l.GetColumnWidth(i)
		if w1 > w2:
			l.SetColumnWidth(i, w1)
Exemple #12
0
	def _save_as_new(self):

		pat = gmPerson.gmCurrentPatient()
		emr = pat.emr

		stay = self._PRW_hospital_stay.GetData()
		if stay is None:
			epi = self._PRW_episode.GetData(can_create = True)
		else:
			epi = gmEMRStructItems.cHospitalStay(aPK_obj = stay)['pk_episode']

		proc = emr.add_performed_procedure (
			episode = epi,
			location = self._PRW_location.GetData(),
			hospital_stay = stay,
			procedure = self._PRW_procedure.GetValue().strip()
		)

		proc['clin_when'] = self._DPRW_date.GetData().get_pydt()
		if self._DPRW_end.GetData() is None:
			proc['clin_end'] = None
		else:
			proc['clin_end'] = self._DPRW_end.GetData().get_pydt()
		proc['is_ongoing'] = self._CHBOX_ongoing.IsChecked()
		proc['comment'] = self._TCTRL_comment.GetValue()
		proc['pk_doc'] = self._PRW_document.GetData()
		proc.save()

		proc.generic_codes = [ c['data'] for c in self._PRW_codes.GetData() ]

		self.data = proc

		return True
Exemple #13
0
	def archive_forms(episode_name=None, comment=None):
		if episode_name is None:
			epi = None				# will ask for episode further down
		else:
			pat = gmPerson.gmCurrentPatient()
			emr = pat.emr
			epi = emr.add_episode(episode_name = episode_name, is_open = False)

		for form in forms:
			files2import = []
			files2import.extend(form.final_output_filenames)
			files2import.extend(form.re_editable_filenames)
			if len(files2import) == 0:
				continue
			save_files_as_new_document (
				parent = parent,
				filenames = files2import,
				document_type = form.template['instance_type'],
				unlock_patient = False,
				episode = epi,
				review_as_normal = review_copy_as_normal,
				reference = None,
				pk_org_unit = gmPraxis.gmCurrentPraxisBranch()['pk_org_unit'],
				comment = comment
			)

		return True
Exemple #14
0
	def _check_RFE(self):
		"""
		This gets called when a patient has been activated, but
		only when the waiting list is actually in use (that is,
		the plugin is loaded)
		"""
		pat = gmPerson.gmCurrentPatient()
		enc = pat.emr.active_encounter
		if gmTools.coalesce(enc['reason_for_encounter'], '').strip() != '':
			return
		entries = pat.waiting_list_entries
		if len(entries) == 0:
			if self.__id_most_recently_activated_patient is None:
				return
			if self.__id_most_recently_activated_patient != pat.ID:
				return
			rfe = self.__comment_most_recently_activated_patient
		else:
			entry = entries[0]
			if gmTools.coalesce(entry['comment'], '').strip() == '':
				return
			rfe = entry['comment'].strip()
		enc['reason_for_encounter'] = rfe
		enc.save()
		self.__id_most_recently_activated_patient = None
Exemple #15
0
	def __init__(self, parent, id=-1):
		wx.Panel.__init__(self, parent, id, wx.DefaultPosition, wx.DefaultSize, wx.RAISED_BORDER)
		gmRegetMixin.cRegetOnPaintMixin.__init__(self)
		self.__do_layout()
		self.__pat = gmPerson.gmCurrentPatient()
		self.__register_interests()
		self.__reset_ui_content()
Exemple #16
0
	def _save_as_update(self):

		self.data['comment'] = self._TCTRL_subject.GetValue().strip()
		self.data['pk_type'] = self._PRW_type.GetData(can_create = True)

		if self._CHBOX_send_to_me.IsChecked():
			self.data['pk_staff'] = gmStaff.gmCurrentProvider()['pk_staff']
		else:
			self.data['pk_staff'] = self._PRW_receiver.GetData()

		self.data['data'] = self._TCTRL_message.GetValue().strip()

		if self._CHBOX_active_patient.GetValue() is True:
			self.data['pk_patient'] = gmPerson.gmCurrentPatient().ID
		else:
			if self._PRW_patient.person is None:
				self.data['pk_patient'] = None
			else:
				self.data['pk_patient'] = self._PRW_patient.person.ID

		if self._PRW_due.is_valid_timestamp():
			self.data['due_date'] = self._PRW_due.date

		if self._PRW_expiry.is_valid_timestamp():
			self.data['expiry_date'] = self._PRW_expiry.date

		if self._RBTN_normal.GetValue() is True:
			self.data['importance'] = 0
		elif self._RBTN_high.GetValue() is True:
			self.data['importance'] = 1
		else:
			self.data['importance'] = -1

		self.data.save()
		return True
Exemple #17
0
	def _refresh_as_new(self):
		self._TCTRL_subject.SetValue(u'')
		self._PRW_type.SetText(value = u'', data = None)
		self._CHBOX_send_to_me.SetValue(True)
		self._PRW_receiver.Enable(False)
		self._PRW_receiver.SetData(data = gmStaff.gmCurrentProvider()['pk_staff'])
		self._TCTRL_message.SetValue(u'')
		self._PRW_due.SetText(data = None)
		self._PRW_expiry.SetText(data = None)
		self._RBTN_normal.SetValue(True)
		self._RBTN_high.SetValue(False)
		self._RBTN_low.SetValue(False)

		self._PRW_patient.person = None

		if gmPerson.gmCurrentPatient().connected:
			self._CHBOX_active_patient.Enable(True)
			self._CHBOX_active_patient.SetValue(True)
			self._PRW_patient.Enable(False)
		else:
			self._CHBOX_active_patient.Enable(False)
			self._CHBOX_active_patient.SetValue(False)
			self._PRW_patient.Enable(True)

		self._TCTRL_subject.SetFocus()
Exemple #18
0
	def __init__(self, parent, id):
		"""
		Contructs a new instance of EMR browser panel

		parent - Wx parent widget
		id - Wx widget id
		"""
		# Call parents constructors
		wx.wxPanel.__init__ (
			self,
			parent,
			id,
			wx.wxPyDefaultPosition,
			wx.wxPyDefaultSize,
			wx.wxNO_BORDER
		)
		gmRegetMixin.cRegetOnPaintMixin.__init__(self)

		self.__pat = gmPerson.gmCurrentPatient()
		self.__exporter = gmPatientExporter.cEmrExport(patient = self.__pat)

		self.__do_layout()
		self.__register_interests()
		self.__reset_ui_content()
		
		self.__init_popup()
Exemple #19
0
	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 c_ClinicalRecord 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()
Exemple #20
0
	def _on_add_patient_button_pressed(self, evt):
		self.__id_most_recently_activated_patient = None
		curr_pat = gmPerson.gmCurrentPatient()
		if not curr_pat.connected:
			gmDispatcher.send(signal = 'statustext', msg = _('Cannot add waiting list entry: No patient selected.'), beep = True)
			return
		edit_waiting_list_entry(parent = self, patient = curr_pat)
Exemple #21
0
	def refresh(self):
		pat = gmPerson.gmCurrentPatient()
		if not pat.connected:
			self.clear()
			return

		enc = pat.get_emr().active_encounter
		self._TCTRL_encounter.SetValue(enc.format (
			with_docs = False,
			with_tests = False,
			fancy_header = False,
			with_vaccinations = False,
			with_family_history = False).strip('\n')
		)
		self._TCTRL_encounter.SetToolTipString (
			_('The active encounter of the current patient:\n\n%s') % enc.format(
				with_docs = False,
				with_tests = False,
				fancy_header = True,
				with_vaccinations = False,
				with_rfe_aoe = True,
				with_family_history = False).strip('\n')
		)
		self._BTN_new.Enable(True)
		self._BTN_list.Enable(True)
Exemple #22
0
def manage_external_care(parent=None):

	pat = gmPerson.gmCurrentPatient()
	emr = pat.get_emr()

	if parent is None:
		parent = wx.GetApp().GetTopWindow()

	#-----------------------------------------
	def edit(external_care_item=None):
		return edit_external_care_item(parent = parent, external_care_item = external_care_item)
	#-----------------------------------------
	def delete(external_care_item=None):
		if gmExternalCare.delete_external_care_item(pk_external_care = external_care_item['pk_external_care']):
			return True

		gmDispatcher.send (
			signal = u'statustext',
			msg = _('Cannot delete external care item.'),
			beep = True
		)
		return False
	#------------------------------------------------------------
	def get_tooltip(data):
		if data is None:
			return None
		return u'\n'.join(data.format(with_health_issue = True))
	#------------------------------------------------------------
	def refresh(lctrl):
		care = emr.get_external_care_items(order_by = u'issue, provider, unit, organization')
		items = [ [
			u'%s @ %s' % (
				c['unit'],
				c['organization']
			),
			gmTools.coalesce(c['provider'], u''),
			c['issue'],
			gmTools.coalesce(c['comment'], u'')
		] for c in care ]
		lctrl.set_string_items(items)
		lctrl.set_data(care)
	#------------------------------------------------------------
	return gmListWidgets.get_choices_from_list (
		parent = parent,
		msg = _('External care of this patient.'),
		caption = _('Showing external care network.'),
		columns = [ _('Location'), _('Provider'), _('Care issue'), _('Comment') ],
		single_selection = False,
		can_return_empty = True,
		ignore_OK_button = False,
		refresh_callback = refresh,
		edit_callback = edit,
		new_callback = edit,
		delete_callback = delete,
		list_tooltip_callback = get_tooltip
#		left_extra_button=None,		# manage orgs
#		middle_extra_button=None,	# manage issues
#		right_extra_button=None
	)
Exemple #23
0
	def __init__(self, *args, **kwargs):
		wxgMergePatientsDlg.wxgMergePatientsDlg.__init__(self, *args, **kwargs)

		curr_pat = gmPerson.gmCurrentPatient()
		if curr_pat.connected:
			self._TCTRL_patient1.person = curr_pat
			self._TCTRL_patient1._display_name()
			self._RBTN_patient1.SetValue(True)
Exemple #24
0
	def _on_save_results_button_pressed(self, event):
		event.Skip()

		user_query = self._TCTRL_query.GetValue().strip().strip(';')
		if user_query == '':
			return

		pat = None
		curr_pat = gmPerson.gmCurrentPatient()
		if curr_pat.connected:
			pat = curr_pat.ID
		success, hint, cols, rows = gmDataMining.run_report_query (
			query = user_query,
			limit = None,
			pk_identity = pat
		)

		if not success:
			return

		if len(rows) == 0:
			return

		dlg = wx.FileDialog (
			parent = self,
			message = _("Save SQL report query results as CSV in..."),
			defaultDir = os.path.abspath(os.path.expanduser(os.path.join('~', 'gnumed'))),
			defaultFile = 'gm-query_results.csv',
			wildcard = '%s (*.csv)|*.csv|%s (*)|*' % (_("CSV files"), _("all files")),
			style = wx.FD_SAVE
		)
		choice = dlg.ShowModal()
		csv_name = dlg.GetPath()
		dlg.DestroyLater()
		if choice != wx.ID_OK:
			return

		csv_file = io.open(csv_name, mode = 'wt', encoding = 'utf8')
		csv_file.write('#-------------------------------------------------------------------------------------\n')
		csv_file.write('# GNUmed SQL report results\n')
		csv_file.write('#\n')
		csv_file.write('# Report: "%s"\n' % self._PRW_report_name.GetValue().strip())
		csv_file.write('#\n')
		csv_file.write('# SQL:\n')
		for line in user_query.split('\n'):
			csv_file.write('# %s\n' % line)
		csv_file.write('#\n')
		csv_file.write('# ID of active patient: %s\n' % pat)
		csv_file.write('#\n')
		csv_file.write('# hits found: %s\n' % len(rows))
		csv_file.write('#-------------------------------------------------------------------------------------\n')

		csv_writer = csv.writer(csv_file)
		csv_writer.writerow(cols)
		for row in rows:
			csv_writer.writerow(row)

		csv_file.close()
Exemple #25
0
def manage_hospital_stays(parent=None):

	pat = gmPerson.gmCurrentPatient()
	emr = pat.emr

	if parent is None:
		parent = wx.GetApp().GetTopWindow()

	#-----------------------------------------
	def get_tooltip(stay=None):
		if stay is None:
			return None
		return stay.format (
			include_procedures = True,
			include_docs = True
		)

	#-----------------------------------------
	def edit(stay=None):
		return edit_hospital_stay(parent = parent, hospital_stay = stay)

	#-----------------------------------------
	def delete(stay=None):
		if gmEMRStructItems.delete_hospital_stay(stay = stay['pk_hospital_stay']):
			return True
		gmDispatcher.send (
			signal = 'statustext',
			msg = _('Cannot delete hospitalization.'),
			beep = True
		)
		return False

	#-----------------------------------------
	def refresh(lctrl):
		stays = emr.get_hospital_stays()
		items = [
			[
				s['admission'].strftime('%Y-%m-%d'),
				gmTools.coalesce(s['discharge'], '', function_initial = ('strftime', '%Y-%m-%d')),
				s['episode'],
				'%s @ %s' % (s['ward'], s['hospital'])
			] for s in stays
		]
		lctrl.set_string_items(items = items)
		lctrl.set_data(data = stays)
	#-----------------------------------------
	gmListWidgets.get_choices_from_list (
		parent = parent,
		msg = _("The patient's hospitalizations:\n"),
		caption = _('Editing hospitalizations ...'),
		columns = [_('Admission'), _('Discharge'), _('Reason'), _('Hospital')],
		single_selection = True,
		edit_callback = edit,
		new_callback = edit,
		delete_callback = delete,
		refresh_callback = refresh,
		list_tooltip_callback = get_tooltip
	)
Exemple #26
0
	def _save_as_update(self):
		self.data['pk_encounter'] = gmPerson.gmCurrentPatient().emr.current_encounter['pk_encounter']
		self.data['pk_health_issue'] = self._PRW_issue.GetData()
		self.data['issue'] = self._PRW_issue.GetValue().strip()
		self.data['pk_org_unit'] = self._PRW_care_location.GetData()
		self.data['provider'] = self._TCTRL_provider.GetValue().strip()
		self.data['comment'] = self._TCTRL_comment.GetValue().strip()
		self.data.save()
		return True
Exemple #27
0
	def _on_export_area_button_pressed(self, event):
		if self.__tl_file is None:
			return
		pat = gmPerson.gmCurrentPatient()
		if not pat.connected:
			return
		pat.export_area.add_file(filename = self._PNL_timeline.export_as_png(), hint = _('timeline image (png)'))
		pat.export_area.add_file(filename = self._PNL_timeline.export_as_svg(), hint = _('timeline image (svg)'))
		pat.export_area.add_file(filename = self.__tl_file, hint = _('timeline data (xml)'))
Exemple #28
0
	def __init__(self, *args, **kwargs):

		wxgSimpleSoapPluginPnl.wxgSimpleSoapPluginPnl.__init__(self, *args, **kwargs)
		gmRegetMixin.cRegetOnPaintMixin.__init__(self)

		self.__curr_pat = gmPerson.gmCurrentPatient()
		self.__problem = None
		self.__init_ui()
		self.__register_interests()
def manage_hospital_stays(parent=None):

    pat = gmPerson.gmCurrentPatient()
    emr = pat.emr

    if parent is None:
        parent = wx.GetApp().GetTopWindow()

    #-----------------------------------------
    def get_tooltip(stay=None):
        if stay is None:
            return None
        return stay.format(include_procedures=True, include_docs=True)

    #-----------------------------------------
    def edit(stay=None):
        return edit_hospital_stay(parent=parent, hospital_stay=stay)

    #-----------------------------------------
    def delete(stay=None):
        if gmEMRStructItems.delete_hospital_stay(
                stay=stay['pk_hospital_stay']):
            return True
        gmDispatcher.send(signal='statustext',
                          msg=_('Cannot delete hospitalization.'),
                          beep=True)
        return False

    #-----------------------------------------
    def refresh(lctrl):
        stays = emr.get_hospital_stays()
        items = [[
            s['admission'].strftime('%Y-%m-%d'),
            gmTools.coalesce(s['discharge'],
                             '',
                             function4value=('strftime', '%Y-%m-%d')),
            s['episode'],
            '%s @ %s' % (s['ward'], s['hospital'])
        ] for s in stays]
        lctrl.set_string_items(items=items)
        lctrl.set_data(data=stays)

    #-----------------------------------------
    gmListWidgets.get_choices_from_list(
        parent=parent,
        msg=_("The patient's hospitalizations:\n"),
        caption=_('Editing hospitalizations ...'),
        columns=[_('Admission'),
                 _('Discharge'),
                 _('Reason'),
                 _('Hospital')],
        single_selection=True,
        edit_callback=edit,
        new_callback=edit,
        delete_callback=delete,
        refresh_callback=refresh,
        list_tooltip_callback=get_tooltip)
Exemple #30
0
 def save_soap(soap=None):
     if episode_name is None:
         return
     if soap.strip() == '':
         return
     pat = gmPerson.gmCurrentPatient()
     emr = pat.emr
     epi = emr.add_episode(episode_name=episode_name, is_open=False)
     emr.add_clin_narrative(soap_cat=None, note=soap, episode=epi)
Exemple #31
0
def manage_family_history(parent=None):

	pat = gmPerson.gmCurrentPatient()
	emr = pat.get_emr()

	if parent is None:
		parent = wx.GetApp().GetTopWindow()

	#-----------------------------------------
	def edit(family_history=None):
		return edit_family_history(parent = parent, family_history = family_history)
	#-----------------------------------------
	def delete(family_history=None):
		if gmFamilyHistory.delete_family_history(pk_family_history = family_history['pk_family_history']):
			return True

		gmDispatcher.send (
			signal = u'statustext',
			msg = _('Cannot delete family history item.'),
			beep = True
		)
		return False
	#------------------------------------------------------------
	def refresh(lctrl):
		fhx = emr.get_family_history()
		items = [ [
			f['l10n_relation'],
			f['condition'],
			gmTools.bool2subst(f['contributed_to_death'], _('yes'), _('no'), u'?'),
			gmTools.coalesce(f['age_noted'], u''),
			gmDateTime.format_interval (
				interval = f['age_of_death'],
				accuracy_wanted = gmDateTime.acc_years,
				none_string = u''
			),
			gmTools.coalesce(f['name_relative'], u''),
			gmTools.coalesce(f['dob_relative'], u'', function_initial = ('strftime', '%Y-%m-%d'))
		] for f in fhx ]
		lctrl.set_string_items(items)
		lctrl.set_data(fhx)
	#------------------------------------------------------------
	gmListWidgets.get_choices_from_list (
		parent = parent,
		msg = _('Family history of this patient.'),
		caption = _('Showing family history.'),
		columns = [ _('Relationship'), _('Condition'), _('Fatal'), _('Noted'), _('Died'), _('Name'), _('Born') ],
		single_selection = True,
		can_return_empty = True,
		ignore_OK_button = True,
		refresh_callback = refresh,
		edit_callback = edit,
		new_callback = edit,
		delete_callback = delete
#		left_extra_button=None,
#		middle_extra_button=None,
#		right_extra_button=None
	)
Exemple #32
0
	def __init__(self, *args, **kwargs):

		wxgSimpleSoapPluginPnl.wxgSimpleSoapPluginPnl.__init__(self, *args, **kwargs)
		gmRegetMixin.cRegetOnPaintMixin.__init__(self)

		self.__curr_pat = gmPerson.gmCurrentPatient()
		self.__problem = None
		self.__init_ui()
		self.__register_interests()
Exemple #33
0
 def __add_new_health_issue_to_record(self):
     print "add new health issue to record"
     pat = gmPerson.gmCurrentPatient()
     rec = pat.get_clinical_record()
     issue = rec.add_health_issue(self.get_emr_tree().GetItemText(
         self.edit_node).strip())
     if not issue is None and isinstance(issue,
                                         gmEMRStructItems.cHealthIssue):
         self.get_emr_tree().SetPyData(self.edit_node, issue)
Exemple #34
0
def run_importer():

	# map data from commandline
	try:
		date = sys.argv[idx_date]
		gsm = sys.argv[idx_gsm]
		sms = sys.argv[idx_sms]
		pk_patient, weight = sms.split(':::')
	except:
		return False

	# find patient by gsm
#	cmd1 = u"select dem.add_external_id_type(%(desc)s, %(org)s)"
#	args1 = {'desc': external_id_type, 'org': u'gmSMSImporter.py'}
#	cmd2 = u'select pk from dem.enum_ext_id_types where name = %(desc)s'
#	rows, idx = gmPG2.run_rw_queries (
#		queries = [
#			{'cmd': cmd1, 'args': args1},
#			{'cmd': cmd2, 'args': args1}
#		],
#		return_data = True
#	)
#	ext_id_pk = rows[0][0]

#	cmd = u"""
#select li2id.id_identity
#from dem.lnk_identity2ext_id li2id
#where
#	li2id.external_id = %(id)s and
#	fk_origin = %(src)s"""
#	args = {'id': gsm, 'src': ext_id_pk}

#	rows, idx = gmPG2.run_ro_queries (
#		queries = [{'cmd': cmd, 'args': args}],
#		return_data = True
#	)
#	if len(rows) == 0:
#		print "patient with GSM [%s] not found" % gsm
#		return False
#	pk_patient = rows[0][0]

	gmPerson.set_active_patient(patient = gmPerson.cPerson(aPK_obj = pk_patient))

	# ensure structure of EMR
	curr_pat = gmPerson.gmCurrentPatient()
	emr = curr_pat.get_emr()
	epi = emr.add_episode(episode_name = u'Gewichtsmonitoring', is_open = False)

	# and import our stuff
	narr = emr.add_clin_narrative (
		note = weight_template % (dt.datetime.now().strftime('%X'), weight),
		soap_cat = soap_cat,
		episode = epi
	)

	return True
Exemple #35
0
	def __init_ui(self):

		# FIXME: include more sources: coding systems/other database columns
		mp = gmMatchProvider.cMatchProvider_SQL2 (
			queries = ["SELECT DISTINCT ON (description) description, description FROM clin.health_issue WHERE description %(fragment_condition)s LIMIT 50"]
		)
		mp.setThresholds(1, 3, 5)
		self._PRW_condition.matcher = mp

		mp = gmMatchProvider.cMatchProvider_SQL2 (
			queries = ["""
SELECT DISTINCT ON (grouping) grouping, grouping from (

	SELECT rank, grouping from ((

		SELECT
			grouping,
			1 as rank
		from
			clin.health_issue
		where
			grouping %%(fragment_condition)s
				and
			(SELECT True from clin.encounter where fk_patient = %s and pk = clin.health_issue.fk_encounter)

	) union (

		SELECT
			grouping,
			2 as rank
		from
			clin.health_issue
		where
			grouping %%(fragment_condition)s

	)) as union_result

	order by rank

) as order_result

limit 50""" % gmPerson.gmCurrentPatient().ID
			]
		)
		mp.setThresholds(1, 3, 5)
		self._PRW_grouping.matcher = mp

		self._PRW_age_noted.add_callback_on_lose_focus(self._on_leave_age_noted)
		self._PRW_year_noted.add_callback_on_lose_focus(self._on_leave_year_noted)

#		self._PRW_age_noted.add_callback_on_modified(self._on_modified_age_noted)
#		self._PRW_year_noted.add_callback_on_modified(self._on_modified_year_noted)

		self._PRW_year_noted.Enable(True)

		self._PRW_codes.add_callback_on_lose_focus(self._on_leave_codes)
 def _on_add_patient_button_pressed(self, evt):
     self.__id_most_recently_activated_patient = None
     curr_pat = gmPerson.gmCurrentPatient()
     if not curr_pat.connected:
         gmDispatcher.send(
             signal='statustext',
             msg=_('Cannot add waiting list entry: No patient selected.'),
             beep=True)
         return
     edit_waiting_list_entry(parent=self, patient=curr_pat)
Exemple #37
0
    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()
Exemple #38
0
	def __save_soap_note(self, soap=None):
		if soap.strip() == '':
			return
		emr = gmPerson.gmCurrentPatient().emr
		epi = emr.add_episode(episode_name = 'administrative', is_open = False)
		emr.add_clin_narrative (
			soap_cat = None,
			note = soap,
			episode = epi
		)
Exemple #39
0
    def _on_burn_items_button_pressed(self, event):
        event.Skip()

        found, external_cmd = gmShellAPI.detect_external_binary('gm-burn_doc')
        if not found:
            return False

        items = self._LCTRL_items.get_selected_item_data(only_one=False)
        if len(items) == 0:
            items = self._LCTRL_items.get_item_data()

        base_dir = None
        dlg = wx.DirDialog(
            self,
            message=_(
                'If you wish to include an existing directory select it here:'
            ),
            defaultPath=os.path.join(gmTools.gmPaths().home_dir, 'gnumed'),
            style=wx.DD_DEFAULT_STYLE | wx.DD_DIR_MUST_EXIST)
        choice = dlg.ShowModal()
        path2include = dlg.GetPath()
        if choice == wx.ID_OK:
            if not gmTools.dir_is_empty(path2include):
                base_dir = path2include

        export_dir = gmPerson.gmCurrentPatient().export_area.export(
            base_dir=base_dir, items=items, with_metadata=True)
        if export_dir is None:
            return False

        cmd = u'%s %s' % (external_cmd, export_dir)
        if os.name == 'nt':
            blocking = True
        else:
            blocking = False
        success = gmShellAPI.run_command_in_shell(command=cmd,
                                                  blocking=blocking)
        if not success:
            gmGuiHelpers.gm_show_error(
                aMessage=_('Error burning documents to CD/DVD.'),
                aTitle=_('Burning documents'))
            return False

        self.save_soap_note(soap=_('Burned onto CD/DVD:\n - %s') %
                            u'\n - '.join([i['description'] for i in items]))

        browse_index = gmGuiHelpers.gm_show_question(
            title=title,
            question=_('Browse patient data pack ?'),
            cancel_button=False)
        if browse_index:
            gmNetworkTools.open_url_in_browser(
                url=u'file://%s' % os.path.join(export_dir, u'index.html'))

        return True
Exemple #40
0
def run_importer():

    # map data from commandline
    try:
        date = sys.argv[idx_date]
        gsm = sys.argv[idx_gsm]
        sms = sys.argv[idx_sms]
        pk_patient, weight = sms.split(':::')
    except:
        return False

    # find patient by gsm
#	cmd1 = u"select dem.add_external_id_type(%(desc)s, %(org)s)"
#	args1 = {'desc': external_id_type, 'org': u'gmSMSImporter.py'}
#	cmd2 = u'select pk from dem.enum_ext_id_types where name = %(desc)s'
#	rows, idx = gmPG2.run_rw_queries (
#		queries = [
#			{'cmd': cmd1, 'args': args1},
#			{'cmd': cmd2, 'args': args1}
#		],
#		return_data = True
#	)
#	ext_id_pk = rows[0][0]

#	cmd = u"""
#select li2id.id_identity
#from dem.lnk_identity2ext_id li2id
#where
#	li2id.external_id = %(id)s and
#	fk_origin = %(src)s"""
#	args = {'id': gsm, 'src': ext_id_pk}

#	rows, idx = gmPG2.run_ro_queries (
#		queries = [{'cmd': cmd, 'args': args}],
#		return_data = True
#	)
#	if len(rows) == 0:
#		print "patient with GSM [%s] not found" % gsm
#		return False
#	pk_patient = rows[0][0]

    gmPerson.set_active_patient(patient=gmPerson.cPerson(aPK_obj=pk_patient))

    # ensure structure of EMR
    curr_pat = gmPerson.gmCurrentPatient()
    emr = curr_pat.emr
    epi = emr.add_episode(episode_name='Gewichtsmonitoring', is_open=False)

    # and import our stuff
    narr = emr.add_clin_narrative(note=weight_template %
                                  (dt.datetime.now().strftime('%X'), weight),
                                  soap_cat=soap_cat,
                                  episode=epi)

    return True
Exemple #41
0
   def __init_ui_data(self):
       pat = gmPerson.gmCurrentPatient()
       name = pat.get_active_name()
       txt = _("""
 %s "%s" %s
 born: %s""") % (name['firstnames'], name['preferred'], name['lastnames'],
                 pat.get_formatted_dob(format='%Y %b %d'))
       self._TXT_person.SetValue(txt)
       txt = name['firstnames'][:2] + name['lastnames'][:2]
       self._TXT_short_alias.SetValue(txt)
       self._TXT_account.SetValue(txt.lower())
Exemple #42
0
 def _save_as_update(self):
     self.data['pk_encounter'] = gmPerson.gmCurrentPatient(
     ).emr.current_encounter['pk_encounter']
     self.data['pk_health_issue'] = self._PRW_issue.GetData()
     self.data['issue'] = self._PRW_issue.GetValue().strip()
     self.data['pk_org_unit'] = self._PRW_care_location.GetData()
     self.data['provider'] = self._TCTRL_provider.GetValue().strip()
     self.data['comment'] = self._TCTRL_comment.GetValue().strip()
     self.data['inactive'] = self._CHBOX_inactive.IsChecked()
     self.data.save()
     return True
	def _on_new_patient_button_pressed(self, event):
		event.Skip()
		success = create_new_person(activate = True)
		if success:
			self.person = gmPerson.gmCurrentPatient()
		else:
			self.person = None
		if self.IsModal():
			self.EndModal(wx.ID_CANCEL)
		else:
			self.Close()
Exemple #44
0
	def __add_new_episode_to_record(self):
		print "add new episode to record"
		pat = gmPerson.gmCurrentPatient()
		rec = pat.get_clinical_record()
		print "health_issue pk = ", self.get_browser().get_parent_EMR_item(self.edit_node).pk_obj
		print "text = ", self.get_emr_tree().GetItemText(self.edit_node).strip()
		
		episode = rec.add_episode( self.get_emr_tree().GetItemText(self.edit_node).strip(), self.get_browser().get_parent_EMR_item(self.edit_node).pk_obj )
		 
		if not episode is None and isinstance(episode, gmEMRStructItems.cEpisode):
			self.get_emr_tree().SetPyData( self.edit_node, episode)	
Exemple #45
0
	def _on_scan_items_button_pressed(self, event):
		event.Skip()
		scans = gmDocumentWidgets.acquire_images_from_capture_device(calling_window = self)
		if scans is None:
			return

		if not gmPerson.gmCurrentPatient().export_area.add_files(scans, _('scan')):
			gmGuiHelpers.gm_show_error (
				title = _('Scanning files into export area'),
				error = _('Cannot add (some of) the following scans to the export area:\n%s ') % '\n '.join(fnames)
			)
Exemple #46
0
def _display_clinical_reminders():

    pat = gmPerson.gmCurrentPatient()
    if not pat.connected:
        return

    # reminders
    for msg in pat.overdue_messages:
        if msg['expiry_date'] is None:
            exp = ''
        else:
            exp = _(' - expires %s') % gmDateTime.pydt_strftime(
                msg['expiry_date'], '%Y %b %d', accuracy=gmDateTime.acc_days)
        txt = _('Due for %s (since %s%s):\n'
                '%s'
                '%s'
                '\n'
                'Patient: %s\n'
                'Reminder by: %s') % (
                    gmDateTime.format_interval_medically(msg['interval_due']),
                    gmDateTime.pydt_strftime(msg['due_date'],
                                             '%Y %b %d',
                                             accuracy=gmDateTime.acc_days),
                    exp, gmTools.coalesce(msg['comment'], '', '\n%s\n'),
                    gmTools.coalesce(msg['data'], '', '\n%s\n'),
                    pat.description_gender, msg['modified_by'])
        gmGuiHelpers.gm_show_warning(aTitle=_('Clinical reminder'),
                                     aMessage=txt)

    # dynamic hints
    hints2aggregate = []
    emr = pat.emr
    hint_dlg = cDynamicHintDlg(wx.GetApp().GetTopWindow(), -1)
    # single-hint popups
    for hint in emr.dynamic_hints:
        if hint['popup_type'] == 0:
            continue
        if hint['popup_type'] == 2:
            hints2aggregate.append(hint)
            continue
        hint_dlg.hint = hint
        if hint_dlg.ShowModal() == wx.ID_APPLY:
            hint.suppress(rationale=hint_dlg.rationale.strip(),
                          pk_encounter=emr.current_encounter['pk_encounter'])
    hint_dlg.DestroyLater()
    # aggregate popup
    if len(hints2aggregate) > 0:
        hints_dlg = cDynamicHintListDlg(wx.GetApp().GetTopWindow(), -1)
        hints_dlg.pk_encounter = emr.current_encounter['pk_encounter']
        hints_dlg.hints = hints2aggregate
        hints_dlg.ShowModal()
        hints_dlg.DestroyLater()

    return
Exemple #47
0
	def _calc_problem_list_item_tooltip(self, data):

		if isinstance(data, gmExternalCare.cExternalCareItem):
			return '\n'.join(data.format (
				with_health_issue = True,
				with_address = True,
				with_comms = True
			))

		emr = gmPerson.gmCurrentPatient().emr

		if data['type'] == 'issue':
			issue = emr.problem2issue(data)
			tt = issue.format (
				patient = gmPerson.gmCurrentPatient(),
				with_medications = False,
				with_hospital_stays = False,
				with_procedures = False,
				with_family_history = False,
				with_documents = False,
				with_tests = False,
				with_vaccinations = False
			).strip('\n')
			return tt

		if data['type'] == 'episode':
			epi = emr.problem2episode(data)
			tt = epi.format (
				patient = gmPerson.gmCurrentPatient(),
				with_encounters = False,
				with_hospital_stays = False,
				with_procedures = False,
				with_family_history = False,
				with_documents = False,
				with_tests = False,
				with_vaccinations = False,
				with_health_issue = True
			).strip('\n')
			return tt

		return None
Exemple #48
0
	def _on_clipboard_items_button_pressed(self, event):
		event.Skip()
		clip = gmGuiHelpers.clipboard2file(check_for_filename = True)
		if clip is None:
			return
		if clip is False:
			return
		if not gmPerson.gmCurrentPatient().export_area.add_file(filename = clip, hint = _('clipboard')):
			gmGuiHelpers.gm_show_error (
				title = _('Loading clipboard item (saved to file) into export area'),
				error = _('Cannot add the following clip to the export area:\n%s ') % clip
			)
Exemple #49
0
    def _on_confirm_button_pressed(self, evt):
        pat = gmPerson.gmCurrentPatient()
        emr = pat.emr
        allergies = emr.get_allergies()
        state = emr.allergy_state

        cmt = self._TCTRL_state_comment.GetValue().strip()

        if self._RBTN_unknown.GetValue():
            if len(allergies) > 0:
                gmDispatcher.send(
                    signal=u'statustext',
                    msg=
                    _('Cannot set allergy state to <unknown> because there are allergies stored for this patient.'
                      ),
                    beep=True)
                self._RBTN_some.SetValue(True)
                state['has_allergy'] = 1
                return False
            else:
                state['has_allergy'] = None

        elif self._RBTN_none.GetValue():
            if len(allergies) > 0:
                gmDispatcher.send(
                    signal=u'statustext',
                    msg=
                    _('Cannot set allergy state to <None> because there are allergies stored for this patient.'
                      ),
                    beep=True)
                self._RBTN_some.SetValue(True)
                state['has_allergy'] = 1
                return False
            else:
                state['has_allergy'] = 0

        elif self._RBTN_some.GetValue():
            if (len(allergies) == 0) and (cmt == u''):
                gmDispatcher.send(
                    signal=u'statustext',
                    msg=
                    _('Cannot set allergy state to <some> because there are neither allergies nor a comment available for this patient.'
                      ),
                    beep=True)
                return False
            else:
                state['has_allergy'] = 1

        state['comment'] = cmt
        state['last_confirmed'] = u'now'

        state.save_payload()
        self.__refresh_state_ui()
Exemple #50
0
	def _refresh_from_existing(self):

		self._TCTRL_subject.SetValue(gmTools.coalesce(self.data['comment'], ''))
		self._PRW_type.SetData(data = self.data['pk_type'])

		curr_prov = gmStaff.gmCurrentProvider()
		curr_pat = gmPerson.gmCurrentPatient()

		if curr_prov['pk_staff'] == self.data['pk_staff']:
			self._CHBOX_send_to_me.SetValue(True)
			self._PRW_receiver.Enable(False)
			self._PRW_receiver.SetData(data = gmStaff.gmCurrentProvider()['pk_staff'])
		else:
			self._CHBOX_send_to_me.SetValue(False)
			self._PRW_receiver.Enable(True)
			self._PRW_receiver.SetData(data = self.data['pk_staff'])

		self._TCTRL_message.SetValue(gmTools.coalesce(self.data['data'], ''))

		if curr_pat.connected:
			self._CHBOX_active_patient.Enable(True)
			if curr_pat.ID == self.data['pk_patient']:
				self._CHBOX_active_patient.SetValue(True)
				self._PRW_patient.Enable(False)
				self._PRW_patient.person = None
			else:
				self._CHBOX_active_patient.SetValue(False)
				self._PRW_patient.Enable(True)
				if self.data['pk_patient'] is None:
					self._PRW_patient.person = None
				else:
					self._PRW_patient.person = gmPerson.cPerson(aPK_obj = self.data['pk_patient'])
		else:
			self._CHBOX_active_patient.Enable(False)
			self._CHBOX_active_patient.SetValue(False)
			self._PRW_patient.Enable(True)
			if self.data['pk_patient'] is None:
				self._PRW_patient.person = None
			else:
				self._PRW_patient.person = gmPerson.cPerson(aPK_obj = self.data['pk_patient'])

		self._PRW_due.SetText(data = self.data['due_date'])
		self._PRW_expiry.SetText(data = self.data['expiry_date'])

		self._RBTN_normal.SetValue(False)
		self._RBTN_high.SetValue(False)
		self._RBTN_low.SetValue(False)
		{	-1: self._RBTN_low,
			0: self._RBTN_normal,
			1: self._RBTN_high
		}[self.data['importance']].SetValue(True)

		self._TCTRL_subject.SetFocus()
Exemple #51
0
	def __init_ui(self):
		self._LCTRL_provider_inbox.debug = 'provider inbox list'

		self._LCTRL_provider_inbox.set_columns(['', _('Generated'), _('Status'), _('Patient'), _('Message'), _('Category - Type')])
		self._LCTRL_provider_inbox.searchable_columns = [2, 3, 4, 5]
		self._LCTRL_provider_inbox.item_tooltip_callback = self._get_msg_tooltip
		self._LCTRL_provider_inbox.extend_popup_menu_callback = self._extend_popup_menu

		self.__update_greeting()

		if gmPerson.gmCurrentPatient().connected:
			self._CHBOX_active_patient.Enable()
Exemple #52
0
	def _on_table_mod(self, *args, **kwargs):
		if kwargs['table'] != 'clin.export_item':
			return
		if self._RBTN_all_patients.Value is True:
			self._schedule_data_reget()
			return
		pat = gmPerson.gmCurrentPatient()
		if not pat.connected:
			return
		if kwargs['pk_identity'] != pat.ID:
			return
		self._schedule_data_reget()
Exemple #53
0
	def __init__(self, *args, **kwargs):

		wx.StaticBitmap.__init__(self, *args, **kwargs)

		paths = gmTools.gmPaths(app_name = 'gnumed', wx = wx)
		self.__fallback_pic_name = os.path.join(paths.system_app_data_dir, 'bitmaps', 'empty-face-in-bust.png')
		self.__desired_width = 50
		self.__desired_height = 54
		self.__pat = gmPerson.gmCurrentPatient()

		self.__init_ui()
		self.__register_events()
Exemple #54
0
 def _on_export_area_button_pressed(self, event):
     if self.__tl_file is None:
         return
     pat = gmPerson.gmCurrentPatient()
     if not pat.connected:
         return
     pat.export_area.add_file(filename=self.__tl_file,
                              hint=_('timeline data (xml)'))
     pat.export_area.add_file(filename=self._PNL_timeline.export_as_png(),
                              hint=_('timeline image (png)'))
     pat.export_area.add_file(filename=self._PNL_timeline.export_as_svg(),
                              hint=_('timeline image (svg)'))
Exemple #55
0
	def __init__(self, parent, id):
		wx.Panel.__init__(self, parent, id, wx.DefaultPosition, wx.DefaultSize, wx.RAISED_BORDER)
		gmRegetMixin.cRegetOnPaintMixin.__init__(self)
		self.__pat = gmPerson.gmCurrentPatient()
		# do this here so "import cImmunisationsPanel from gmVaccWidgets" works
		self.ID_VaccinatedIndicationsList = wx.NewId()
		self.ID_VaccinationsPerRegimeList = wx.NewId()
		self.ID_MissingShots = wx.NewId()
		self.ID_ActiveSchedules = wx.NewId()
		self.__do_layout()
		self.__register_interests()
		self.__reset_ui_content()
Exemple #56
0
    def __init__(self, *args, **kwargs):

        gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)

        ctxt = {
            'ctxt_pat': {
                'where_part': u'(pk_patient = %(pat)s) AND',
                'placeholder': u'pat'
            }
        }

        mp = gmMatchProvider.cMatchProvider_SQL2(queries=[
            u"""
SELECT
	pk_hospital_stay,
	descr
FROM (
	SELECT DISTINCT ON (pk_hospital_stay)
		pk_hospital_stay,
		descr
	FROM
		(SELECT
			pk_hospital_stay,
			(
				to_char(admission, 'YYYY-Mon-DD')
				|| ' (' || ward || ' @ ' || hospital || '):'
				|| episode
				|| coalesce((' (' || health_issue || ')'), '')
			) AS descr
		 FROM
		 	clin.v_hospital_stays
		 WHERE
			%(ctxt_pat)s (
				hospital %(fragment_condition)s
					OR
				ward %(fragment_condition)s
					OR
				episode %(fragment_condition)s
					OR
				health_issue %(fragment_condition)s
			)
		) AS the_stays
) AS distinct_stays
ORDER BY descr
LIMIT 25
"""
        ],
                                                 context=ctxt)
        mp.setThresholds(3, 4, 6)
        mp.set_context('pat', gmPerson.gmCurrentPatient().ID)

        self.matcher = mp
        self.selection_only = True
Exemple #57
0
    def __refresh_state_ui(self):

        pat = gmPerson.gmCurrentPatient()
        emr = pat.emr
        state = emr.allergy_state

        self._TXT_current_state.SetLabel(state.state_string)

        if state['last_confirmed'] is None:
            self._TXT_last_confirmed.SetLabel(_('<allergy state unasked>'))
        else:
            self._TXT_last_confirmed.SetLabel(
                state['last_confirmed'].strftime('%x %H:%M'))

        if state['has_allergy'] is None:
            self._RBTN_unknown.SetValue(True)
            self._RBTN_none.SetValue(False)
            self._RBTN_some.SetValue(False)

            self._RBTN_unknown.Enable(True)
            self._RBTN_none.Enable(True)

        elif state['has_allergy'] == 0:
            self._RBTN_unknown.SetValue(False)
            self._RBTN_none.SetValue(True)
            self._RBTN_some.SetValue(False)

            self._RBTN_unknown.Enable(True)
            self._RBTN_none.Enable(True)

        elif state['has_allergy'] == 1:
            self._RBTN_unknown.SetValue(False)
            self._RBTN_none.SetValue(False)
            self._RBTN_some.SetValue(True)

            self._RBTN_unknown.Enable(True)
            self._RBTN_none.Enable(False)

        else:
            self._RBTN_unknown.SetValue(True)
            self._RBTN_none.SetValue(False)
            self._RBTN_some.SetValue(False)

            self._RBTN_unknown.Enable(True)
            self._RBTN_none.Enable(True)

            gmDispatcher.send(signal=u'statustext',
                              msg=_('invalid allergy state [%s]') % state,
                              beep=True)

        if state['comment'] is not None:
            self._TCTRL_state_comment.SetValue(state['comment'])
Exemple #58
0
	def _on_export_items_button_pressed(self, event):
		event.Skip()

		items = self.__get_items_to_work_on(_('Exporting entries'))
		if items is None:
			return

		# export dialog
		pat = gmPerson.gmCurrentPatient()
		dlg = cExportAreaExportToMediaDlg(self, -1, patient = pat, item_count = len(items))
		choice = dlg.ShowModal()
		media = dlg._LCTRL_removable_media.get_selected_item_data(only_one = True)
		use_subdir = dlg._CHBOX_use_subdirectory.IsChecked()
		encrypt = dlg._CHBOX_encrypt.IsChecked()
		dlg.DestroyLater()
		if choice == wx.ID_CANCEL:
			return

		# export the files
		if media['type'] == 'cd':
			base_dir = gmTools.mk_sandbox_dir(prefix = 'iso-')
		else:
			base_dir = media['mountpoint']
		if use_subdir:
			dir2save2 = os.path.join(base_dir, pat.subdir_name)
		else:
			dir2save2 = base_dir
		export_dir = self.__export_as_files (
			gmTools.coalesce(encrypt, _('Exporting encrypted entries'), _('Exporting entries')),
			base_dir = dir2save2,
			items = items,
			encrypt = encrypt,
			with_metadata = True
		)
		if export_dir is None:
			gmDispatcher.send(signal = 'statustext', msg = _('Cannot export: aborted or error.'))
			return

		if media['type'] == 'cd':
			if not self.__burn_dir_to_disk(base_dir = base_dir):
				return
			gmDispatcher.send(signal = 'statustext', msg = _('Entries successfully burned to disk.'))
			self.__save_soap_note(soap = _('Burned onto CD/DVD:\n - %s') % '\n - '.join([ i['description'] for i in items ]))
		else:
			gmDispatcher.send(signal = 'statustext', msg = _('Exported entries into [%s]') % export_dir)
			self.__save_soap_note(soap = _('Exported onto removable media:\n - %s') % '\n - '.join([ i['description'] for i in items ]))

		self.__browse_patient_data(dir2save2, encrypted = encrypt, archive = False, has_metadata = True)

		# remove_entries ?

		return True
Exemple #59
0
 def _save_as_new(self):
     data = gmExternalCare.create_external_care_item(
         pk_encounter=gmPerson.gmCurrentPatient(
         ).emr.current_encounter['pk_encounter'],
         pk_health_issue=self._PRW_issue.GetData(),
         issue=self._PRW_issue.GetValue().strip(),
         pk_org_unit=self._PRW_care_location.GetData())
     data['provider'] = self._TCTRL_provider.GetValue().strip()
     data['comment'] = self._TCTRL_comment.GetValue().strip()
     data['inactive'] = self._CHBOX_inactive.IsChecked()
     data.save()
     self.data = data
     return True
Exemple #60
0
    def _on_save_details_button_pressed(self, evt):

        if not self._PNL_edit_area.save():
            return False

        pat = gmPerson.gmCurrentPatient()
        emr = pat.emr
        state = emr.allergy_state
        state['last_confirmed'] = u'now'
        state.save_payload()

        self.__refresh_state_ui()
        self.__refresh_details_ui()