Пример #1
0
    def _refresh_from_existing(self):

        self._TCTRL_subject.SetValue(
            gmTools.coalesce(self.data['comment'], u''))
        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'], u''))

        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()
Пример #2
0
	def _refresh_from_existing(self):

		self._TCTRL_subject.SetValue(gmTools.coalesce(self.data['comment'], u''))
		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'], u''))

		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()
Пример #3
0
def search_narrative_across_emrs(parent=None):

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

	search_term_dlg = wx.TextEntryDialog (
		parent,
		_('Enter (regex) term to search for across all EMRs:'),
		caption = _('Text search across all EMRs'),
		style = wx.OK | wx.CANCEL | wx.CENTRE
	)
	result = search_term_dlg.ShowModal()

	if result != wx.ID_OK:
		return

	wx.BeginBusyCursor()
	search_term = search_term_dlg.GetValue()
	search_term_dlg.DestroyLater()
	results = gmClinNarrative.search_text_across_emrs(search_term = search_term)
	wx.EndBusyCursor()

	if len(results) == 0:
		gmGuiHelpers.gm_show_info (
			_(
			'Nothing found for search term:\n'
			' "%s"'
			) % search_term,
			_('Search results')
		)
		return

	items = [ [
		gmPerson.cPerson(aPK_obj = r['pk_patient']).description_gender,
		r['narrative'],
		r['src_table']
	] for r in results ]

	selected_patient = gmListWidgets.get_choices_from_list (
		parent = parent,
		caption = _('Search results for [%s]') % search_term,
		choices = items,
		columns = [_('Patient'), _('Match'), _('Match location')],
		data = [ r['pk_patient'] for r in results ],
		single_selection = True,
		can_return_empty = False
	)

	if selected_patient is None:
		return

	wx.CallAfter(set_active_patient, patient = gmPerson.cPerson(aPK_obj = selected_patient))
Пример #4
0
def search_narrative_across_emrs(parent=None):

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

	search_term_dlg = wx.TextEntryDialog (
		parent,
		_('Enter (regex) term to search for across all EMRs:'),
		caption = _('Text search across all EMRs'),
		style = wx.OK | wx.CANCEL | wx.CENTRE
	)
	result = search_term_dlg.ShowModal()

	if result != wx.ID_OK:
		return

	wx.BeginBusyCursor()
	search_term = search_term_dlg.GetValue()
	search_term_dlg.DestroyLater()
	results = gmClinNarrative.search_text_across_emrs(search_term = search_term)
	wx.EndBusyCursor()

	if len(results) == 0:
		gmGuiHelpers.gm_show_info (
			_(
			'Nothing found for search term:\n'
			' "%s"'
			) % search_term,
			_('Search results')
		)
		return

	items = [ [
		gmPerson.cPerson(aPK_obj = r['pk_patient'])['description_gender'],
		r['narrative'],
		r['src_table']
	] for r in results ]

	selected_patient = gmListWidgets.get_choices_from_list (
		parent = parent,
		caption = _('Search results for [%s]') % search_term,
		choices = items,
		columns = [_('Patient'), _('Match'), _('Match location')],
		data = [ r['pk_patient'] for r in results ],
		single_selection = True,
		can_return_empty = False
	)

	if selected_patient is None:
		return

	wx.CallAfter(set_active_patient, patient = gmPerson.cPerson(aPK_obj = selected_patient))
Пример #5
0
	def _goto_measurements_review(self, pk_context=None, pk_patient=None):

		msg = _('Supposedly there are unreviewed results\n'
			'for patient [%s]. However, I cannot find\n'
			'that patient in the GNUmed database.'
		) % pk_patient

		wx.BeginBusyCursor()

		try:
			pat = gmPerson.cPerson(aPK_obj = pk_patient)
		except gmExceptions.ConstructorError:
			wx.EndBusyCursor()
			_log.exception('patient [%s] not found', pk_patient)
			gmGuiHelpers.gm_show_error(msg, _('handling provider inbox item'))
			return False

		success = set_active_patient(patient = pat)

		wx.EndBusyCursor()

		if not success:
			gmGuiHelpers.gm_show_error(msg, _('handling provider inbox item'))
			return False

		gmDispatcher.send(signal = 'display_widget', name = 'gmMeasurementsGridPlugin')
		return True
Пример #6
0
	def _goto_patient(self, pk_context=None, pk_patient=None):

		wx.BeginBusyCursor()

		msg = _('There is a message about patient [%s].\n\n'
			'However, I cannot find that\n'
			'patient in the GNUmed database.'
		) % pk_patient

		try:
			pat = gmPerson.cPerson(aPK_obj = pk_patient)
		except gmExceptions.ConstructorError:
			wx.EndBusyCursor()
			_log.exception('patient [%s] not found', pk_patient)
			gmGuiHelpers.gm_show_error(msg, _('handling provider inbox item'))
			return False
		except:
			wx.EndBusyCursor()
			raise

		success = set_active_patient(patient = pat)

		wx.EndBusyCursor()

		if not success:
			gmGuiHelpers.gm_show_error(msg, _('handling provider inbox item'))
			return False

		return True
Пример #7
0
	def _on_delete_focussed_msg(self, evt):
		if self.__focussed_msg['is_virtual']:
			gmDispatcher.send(signal = 'statustext', msg = _('You must deal with the reason for this message to remove it from your inbox.'), beep = True)
			return False

		# if not "to" current provider, then don't delete
		if self.__focussed_msg['pk_staff'] != gmStaff.gmCurrentProvider()['pk_staff']:
			gmDispatcher.send(signal = 'statustext', msg = _('This message can only be deleted by [%s].') % self.__focussed_msg['provider'], beep = True)
			return False

		pk_patient = self.__focussed_msg['pk_patient']
		if pk_patient is not None:
			#emr = gmClinicalRecord.cClinicalRecord(aPKey = pk_patient, allow_user_interaction = False)
			from Gnumed.wxpython import gmChartPullingWidgets
			emr = gmChartPullingWidgets.pull_chart(gmPerson.cPerson(pk_patient))
			if emr is None:
				return False
			epi = emr.add_episode(episode_name = 'administrative', is_open = False)
			soap_cat = gmTools.bool2subst (
				(self.__focussed_msg['category'] == u'clinical'),
				u'U',
				None
			)
			narr = _('Deleted inbox message:\n%s') % self.__focussed_msg.format(with_patient = False)
			emr.add_clin_narrative(note = narr, soap_cat = soap_cat, episode = epi)
			gmDispatcher.send(signal = 'statustext', msg = _('Recorded deletion of inbox message in EMR.'), beep = False)

		if not self.provider.inbox.delete_message(self.__focussed_msg['pk_inbox_message']):
			gmDispatcher.send(signal='statustext', msg=_('Problem removing message from Inbox.'))
			return False

		return True
Пример #8
0
def export_patients_as_xdt(base_path=None):

	path = gmTools.get_unique_filename (
		prefix = u'gm-export-',
		suffix = u'',
		tmp_dir = base_path
	)
	path = os.path.splitext(path)[0]
	gmTools.mkdir(path)

	for ID in gmPerson.get_person_IDs():
		_log.info(u'exporting patient #%s', ID)
		identity = gmPerson.cPerson(aPK_obj = ID)
		_log.info(u'identity: %s', identity)
		filename = gmTools.get_unique_filename (
			prefix = u'gm_exp-%s-' % identity.dirname,
			suffix = u'.xdt',
			tmp_dir = path
		)
		_log.info(u'file: %s', filename)
		identity.export_as_gdt (
			filename = filename,
			encoding = u'utf8'
			#encoding = u'iso-8859-15'
		)
Пример #9
0
	def _on_list_item_activated(self, evt):
		data = self.get_selected_item_data(only_one = True)
		pk_pat_col = self.__get_patient_pk_data_key(data = data)

		if pk_pat_col is None:
			gmDispatcher.send(signal = 'statustext', msg = _('List not known to be patient-related.'))
			return

		pat_data = data[pk_pat_col]
		try:
			pat_pk = int(pat_data)
			pat = gmPerson.cPerson(aPK_obj = pat_pk)
		except (ValueError, TypeError):
			searcher = gmPersonSearch.cPatientSearcher_SQL()
			idents = searcher.get_identities(pat_data)
			if len(idents) == 0:
				gmDispatcher.send(signal = 'statustext', msg = _('No matching patient found.'))
				return
			if len(idents) == 1:
				pat = idents[0]
			else:
				from Gnumed.wxpython import gmPatSearchWidgets
				dlg = gmPatSearchWidgets.cSelectPersonFromListDlg(parent=wx.GetTopLevelParent(self), id=-1)
				dlg.set_persons(persons=idents)
				result = dlg.ShowModal()
				if result == wx.ID_CANCEL:
					dlg.Destroy()
					return
				pat = dlg.get_selected_person()
				dlg.Destroy()

		from Gnumed.wxpython import gmPatSearchWidgets
		gmPatSearchWidgets.set_active_patient(patient = pat)
Пример #10
0
	def _goto_vaccination_review(self, pk_context=None, pk_patient=None):

		msg = _('Supposedly there are conflicting vaccinations\n'
			'for patient [%s]. However, I cannot find\n'
			'that patient in the GNUmed database.'
		) % pk_patient

		wx.BeginBusyCursor()

		try:
			pat = gmPerson.cPerson(aPK_obj = pk_patient)
		except gmExceptions.ConstructorError:
			wx.EndBusyCursor()
			_log.exception('patient [%s] not found', pk_patient)
			gmGuiHelpers.gm_show_error(msg,	_('handling provider inbox item'))
			return False

		success = set_active_patient(patient = pat)

		wx.EndBusyCursor()

		if not success:
			gmGuiHelpers.gm_show_error(msg, _('handling provider inbox item'))
			return False

		wx.CallAfter(gmVaccWidgets.manage_vaccinations)

		return True
Пример #11
0
	def get_candidate_identities(self, can_create = False):
		old_idents = gmPerson.cDTO_person.get_candidate_identities(self, can_create = can_create)

		# look for candidates based on their Insuree Number
		if not self.card_is_rejected:
			cmd = """
				SELECT pk_identity FROM dem.v_external_ids4identity WHERE
					value = %(val)s AND
					name = %(name)s AND
					issuer = %(kk)s
				"""
			args = {
				'val': self.insuree_number,
				'name': '%s (%s)' % (
					EXTERNAL_ID_TYPE_VK_INSUREE_NUMBER,
					self.raw_data['Karte']
				),
				'kk': EXTERNAL_ID_ISSUER_TEMPLATE % (self.raw_data['KostentraegerName'], self.raw_data['Kostentraegerkennung'])
			}
			rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = None)

			# weed out duplicates
			name_candidate_ids = [ o.ID for o in old_idents ]
			for r in rows:
				if r[0] not in name_candidate_ids:
					old_idents.append(gmPerson.cPerson(aPK_obj = r[0]))

		return old_idents
Пример #12
0
	def _on_waiting_list_button_pressed(self, event):
		event.Skip()

		pat_pk_key = self._LCTRL_result.patient_pk_data_key
		if pat_pk_key is None:
			gmGuiHelpers.gm_show_info (
				info = _('These report results do not seem to contain per-patient data.'),
				title = _('Using report results')
			)
			return

		zone = wx.GetTextFromUser (
			_('Enter a waiting zone to put patients in:'),
			caption = _('Using report results'),
			default_value = _('search results')
		)
		if zone.strip() == '':
			return

		data = self._LCTRL_result.get_selected_item_data(only_one = False)
		if data is None:
			use_all = gmGuiHelpers.gm_show_question (
				title = _('Using report results'),
				question = _('No results selected.\n\nTransfer ALL patients from results to waiting list ?'),
				cancel_button = True
			)
			if not use_all:
				return
			data = self._LCTRL_result.data

		comment = self._PRW_report_name.GetValue().strip()
		for item in data:
			pat = gmPerson.cPerson(aPK_obj = item[pat_pk_key])
			pat.put_on_waiting_list (comment = comment, zone = zone)
Пример #13
0
	def get_candidate_identities(self, can_create = False):
		old_idents = gmPerson.cDTO_person.get_candidate_identities(self, can_create = can_create)

		cmd = """
select pk_identity from dem.v_external_ids4identity where
	value = %(val)s and
	name = %(name)s and
	issuer = %(kk)s
"""
		args = {
			'val': self.insuree_number,
			'name': EXTERNAL_ID_TYPE_VK_INSUREE_NUMBER,
			'kk': EXTERNAL_ID_ISSUER_TEMPLATE % (self.insurance_company, self.insurance_number)
		}
		rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}])

		# weed out duplicates
		new_idents = []
		for r in rows:
			for oid in old_idents:
				if r[0] == oid.ID:
					break
			new_idents.append(gmPerson.cPerson(aPK_obj = r['pk_identity']))

		old_idents.extend(new_idents)

		return old_idents
Пример #14
0
	def _refresh_from_existing(self):
		ident = gmPerson.cPerson(aPK_obj = self.data['pk_patient'])
		self._TCTRL_patient.SetValue(ident.get_description_gender())

		if self.data['pk_health_issue'] is not None:
			self._PRW_issue.SetText (
				self.data['health_issue'],
				data = self.data['pk_health_issue']
			)

		self._PRW_description.SetText (
			self.data['description'],
			data = self.data['description']
		)

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

		if self.data['diagnostic_certainty_classification'] is not None:
			self._PRW_certainty.SetData(data = self.data['diagnostic_certainty_classification'])

		self._CHBOX_closed.SetValue(not self.data['episode_open'])

		val, data = self._PRW_codes.generic_linked_codes2item_dict(self.data.generic_codes)
		self._PRW_codes.SetText(val, data)

		if self.data['pk_health_issue'] is None:
			self._PRW_issue.SetFocus()
		else:
			self._PRW_description.SetFocus()
Пример #15
0
    def _on_waiting_list_button_pressed(self, event):
        event.Skip()

        pat_pk_key = self._LCTRL_result.patient_pk_data_key
        if pat_pk_key is None:
            gmGuiHelpers.gm_show_info(info=_(
                'These report results do not seem to contain per-patient data.'
            ),
                                      title=_('Using report results'))
            return

        zone = wx.GetTextFromUser(
            _('Enter a waiting zone to put patients in:'),
            caption=_('Using report results'),
            default_value=_('search results'))
        if zone.strip() == '':
            return

        data = self._LCTRL_result.get_selected_item_data(only_one=False)
        if data is None:
            use_all = gmGuiHelpers.gm_show_question(
                title=_('Using report results'),
                question=
                _('No results selected.\n\nTransfer ALL patients from results to waiting list ?'
                  ),
                cancel_button=True)
            if not use_all:
                return
            data = self._LCTRL_result.data

        comment = self._PRW_report_name.GetValue().strip()
        for item in data:
            pat = gmPerson.cPerson(aPK_obj=item[pat_pk_key])
            pat.put_on_waiting_list(comment=comment, zone=zone)
Пример #16
0
	def _refresh_from_existing(self):
		ident = gmPerson.cPerson(aPK_obj = self.data['pk_patient'])
		self._TCTRL_patient.SetValue(ident.get_description_gender())

		if self.data['pk_health_issue'] is not None:
			self._PRW_issue.SetText (
				self.data['health_issue'],
				data = self.data['pk_health_issue']
			)

		self._PRW_description.SetText (
			self.data['description'],
			data = self.data['description']
		)

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

		if self.data['diagnostic_certainty_classification'] is not None:
			self._PRW_certainty.SetData(data = self.data['diagnostic_certainty_classification'])

		self._CHBOX_closed.SetValue(not self.data['episode_open'])

		val, data = self._PRW_codes.generic_linked_codes2item_dict(self.data.generic_codes)
		self._PRW_codes.SetText(val, data)

		if self.data['pk_health_issue'] is None:
			self._PRW_issue.SetFocus()
		else:
			self._PRW_description.SetFocus()
Пример #17
0
    def _goto_measurements_review(self, pk_context=None, pk_patient=None):

        msg = _('Supposedly there are unreviewed results\n'
                'for patient [%s]. However, I cannot find\n'
                'that patient in the GNUmed database.') % pk_patient

        wx.BeginBusyCursor()

        try:
            pat = gmPerson.cPerson(aPK_obj=pk_patient)
        except gmExceptions.ConstructorError:
            wx.EndBusyCursor()
            _log.exception('patient [%s] not found', pk_patient)
            gmGuiHelpers.gm_show_error(msg, _('handling provider inbox item'))
            return False

        success = set_active_patient(patient=pat)

        wx.EndBusyCursor()

        if not success:
            gmGuiHelpers.gm_show_error(msg, _('handling provider inbox item'))
            return False

        gmDispatcher.send(signal='display_widget',
                          name='gmMeasurementsGridPlugin')
        return True
Пример #18
0
    def _goto_patient(self, pk_context=None, pk_patient=None):

        wx.BeginBusyCursor()

        msg = _('There is a message about patient [%s].\n\n'
                'However, I cannot find that\n'
                'patient in the GNUmed database.') % pk_patient

        try:
            pat = gmPerson.cPerson(aPK_obj=pk_patient)
        except gmExceptions.ConstructorError:
            wx.EndBusyCursor()
            _log.exception('patient [%s] not found', pk_patient)
            gmGuiHelpers.gm_show_error(msg, _('handling provider inbox item'))
            return False
        except:
            wx.EndBusyCursor()
            raise

        success = set_active_patient(patient=pat)

        wx.EndBusyCursor()

        if not success:
            gmGuiHelpers.gm_show_error(msg, _('handling provider inbox item'))
            return False

        return True
Пример #19
0
    def _goto_vaccination_review(self, pk_context=None, pk_patient=None):

        msg = _('Supposedly there are conflicting vaccinations\n'
                'for patient [%s]. However, I cannot find\n'
                'that patient in the GNUmed database.') % pk_patient

        wx.BeginBusyCursor()

        try:
            pat = gmPerson.cPerson(aPK_obj=pk_patient)
        except gmExceptions.ConstructorError:
            wx.EndBusyCursor()
            _log.exception('patient [%s] not found', pk_patient)
            gmGuiHelpers.gm_show_error(msg, _('handling provider inbox item'))
            return False

        success = set_active_patient(patient=pat)

        wx.EndBusyCursor()

        if not success:
            gmGuiHelpers.gm_show_error(msg, _('handling provider inbox item'))
            return False

        wx.CallAfter(gmVaccWidgets.manage_vaccinations)

        return True
Пример #20
0
    def get_candidate_identities(self, can_create=False):
        old_idents = gmPerson.cDTO_person.get_candidate_identities(
            self, can_create=can_create)

        cmd = """
select pk_identity from dem.v_external_ids4identity where
	value = %(val)s and
	name = %(name)s and
	issuer = %(kk)s
"""
        args = {
            'val':
            self.insuree_number,
            'name':
            EXTERNAL_ID_TYPE_VK_INSUREE_NUMBER,
            'kk':
            EXTERNAL_ID_ISSUER_TEMPLATE %
            (self.insurance_company, self.insurance_number)
        }
        rows, idx = gmPG2.run_ro_queries(queries=[{'cmd': cmd, 'args': args}])

        # weed out duplicates
        new_idents = []
        for r in rows:
            for oid in old_idents:
                if r[0] == oid.ID:
                    break
            new_idents.append(gmPerson.cPerson(aPK_obj=r['pk_identity']))

        old_idents.extend(new_idents)

        return old_idents
Пример #21
0
	def get_identities(self, search_term = None, a_locale = None, dto = None):
		"""Get patient identity objects for given parameters.

		- either search term or search dict
		- dto contains structured data that doesn't need to be parsed (cDTO_person)
		- dto takes precedence over search_term
		"""
		parse_search_term = (dto is None)

		if not parse_search_term:
			queries = self._generate_queries_from_dto(dto)
			if queries is None:
				parse_search_term = True
			if len(queries) == 0:
				parse_search_term = True

		if parse_search_term:
			# temporary change of locale for selecting query generator
			if a_locale is not None:
				print "temporary change of locale on patient search not implemented"
				_log.warning("temporary change of locale on patient search not implemented")
			# generate queries
			if search_term is None:
				raise ValueError('need search term (dto AND search_term are None)')

			queries = self._generate_queries(search_term)

		# anything to do ?
		if len(queries) == 0:
			_log.error('query tree empty')
			_log.error('[%s] [%s] [%s]' % (search_term, a_locale, str(dto)))
			return None

		# collect IDs here
		identities = []
		# cycle through query list
		for query in queries:
			_log.debug("running %s" % query)
			try:
				rows, idx = gmPG2.run_ro_queries(queries = [query], get_col_idx=True)
			except:
				_log.exception('error running query')
				continue
			if len(rows) == 0:
				continue
			identities.extend (
				[ gmPerson.cPerson(row = {'pk_field': 'pk_identity', 'data': row, 'idx': idx}) for row in rows ]
			)

		pks = []
		unique_identities = []
		for identity in identities:
			if identity['pk_identity'] in pks:
				continue
			pks.append(identity['pk_identity'])
			unique_identities.append(identity)

		return unique_identities
Пример #22
0
	def get_identities(self, search_term = None, a_locale = None, dto = None):
		"""Get patient identity objects for given parameters.

		- either search term or search dict
		- dto contains structured data that doesn't need to be parsed (cDTO_person)
		- dto takes precedence over search_term
		"""
		parse_search_term = (dto is None)

		if not parse_search_term:
			queries = self._generate_queries_from_dto(dto)
			if queries is None:
				parse_search_term = True
			if len(queries) == 0:
				parse_search_term = True

		if parse_search_term:
			# temporary change of locale for selecting query generator
			if a_locale is not None:
				print("temporary change of locale on patient search not implemented")
				_log.warning("temporary change of locale on patient search not implemented")
			# generate queries
			if search_term is None:
				raise ValueError('need search term (dto AND search_term are None)')

			queries = self._generate_queries(search_term)

		# anything to do ?
		if len(queries) == 0:
			_log.error('query tree empty')
			_log.error('[%s] [%s] [%s]' % (search_term, a_locale, str(dto)))
			return None

		# collect IDs here
		identities = []
		# cycle through query list
		for query in queries:
			_log.debug("running %s" % query)
			try:
				rows, idx = gmPG2.run_ro_queries(queries = [query], get_col_idx=True)
			except Exception:
				_log.exception('error running query')
				continue
			if len(rows) == 0:
				continue
			identities.extend (
				[ gmPerson.cPerson(row = {'pk_field': 'pk_identity', 'data': row, 'idx': idx}) for row in rows ]
			)

		pks = []
		unique_identities = []
		for identity in identities:
			if identity['pk_identity'] in pks:
				continue
			pks.append(identity['pk_identity'])
			unique_identities.append(identity)

		return unique_identities
Пример #23
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
Пример #24
0
	def _refresh_from_existing(self):
		self._PRW_patient.person = gmPerson.cPerson(aPK_obj = self.data['pk_identity'])
		self._PRW_patient.Enable(False)
		self._PRW_patient._display_name()

		self._TCTRL_comment.SetValue(gmTools.coalesce(self.data['comment'], ''))
		self._PRW_zone.SetValue(gmTools.coalesce(self.data['waiting_zone'], ''))
		self._SPCTRL_urgency.SetValue(self.data['urgency'])

		self._TCTRL_comment.SetFocus()
Пример #25
0
	def _refresh_from_existing(self):
		self._PRW_patient.person = gmPerson.cPerson(aPK_obj = self.data['pk_identity'])
		self._PRW_patient.Enable(False)
		self._PRW_patient._display_name()

		self._TCTRL_comment.SetValue(gmTools.coalesce(self.data['comment'], ''))
		self._PRW_zone.SetValue(gmTools.coalesce(self.data['waiting_zone'], ''))
		self._SPCTRL_urgency.SetValue(self.data['urgency'])

		self._TCTRL_comment.SetFocus()
Пример #26
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
Пример #27
0
	def _refresh_as_new(self):
		if self.data is None:
			ident = gmPerson.gmCurrentPatient()
		else:
			ident = gmPerson.cPerson(aPK_obj = self.data['pk_patient'])
		self._TCTRL_patient.SetValue(ident.get_description_gender())
		self._PRW_issue.SetText()
		self._PRW_description.SetText()
		self._TCTRL_status.SetValue('')
		self._PRW_certainty.SetText()
		self._CHBOX_closed.SetValue(False)
		self._PRW_codes.SetText()

		self._PRW_issue.SetFocus()
Пример #28
0
	def _refresh_as_new(self):
		if self.data is None:
			ident = gmPerson.gmCurrentPatient()
		else:
			ident = gmPerson.cPerson(aPK_obj = self.data['pk_patient'])
		self._TCTRL_patient.SetValue(ident.get_description_gender())
		self._PRW_issue.SetText()
		self._PRW_description.SetText()
		self._TCTRL_status.SetValue('')
		self._PRW_certainty.SetText()
		self._CHBOX_closed.SetValue(False)
		self._PRW_codes.SetText()

		self._PRW_issue.SetFocus()
Пример #29
0
	def _on_activate_button_pressed(self, evt):
		self.__id_most_recently_activated_patient = None
		item = self._LCTRL_patients.get_selected_item_data(only_one=True)
		if item is None:
			return
		try:
			pat = gmPerson.cPerson(aPK_obj = item['pk_identity'])
		except gmExceptions.ConstructorError:
			gmGuiHelpers.gm_show_info (
				aTitle = _('Waiting list'),
				aMessage = _('Cannot activate patient.\n\nIt has probably been disabled.')
			)
			return
		curr_pat = gmPerson.gmCurrentPatient()
		if curr_pat.connected:
			if curr_pat.ID == item['pk_identity']:
				return
		wx.CallAfter(gmPatSearchWidgets.set_active_patient, patient = pat)
Пример #30
0
	def _on_activate_button_pressed(self, evt):
		self.__id_most_recently_activated_patient = None
		item = self._LCTRL_patients.get_selected_item_data(only_one=True)
		if item is None:
			return
		try:
			pat = gmPerson.cPerson(aPK_obj = item['pk_identity'])
		except gmExceptions.ConstructorError:
			gmGuiHelpers.gm_show_info (
				aTitle = _('Waiting list'),
				aMessage = _('Cannot activate patient.\n\nIt has probably been disabled.')
			)
			return
		curr_pat = gmPerson.gmCurrentPatient()
		if curr_pat.connected:
			if curr_pat.ID == item['pk_identity']:
				return
		wx.CallAfter(gmPatSearchWidgets.set_active_patient, patient = pat)
Пример #31
0
	def _on_activateplus_button_pressed(self, evt):
		item = self._LCTRL_patients.get_selected_item_data(only_one=True)
		if item is None:
			return
		try:
			pat = gmPerson.cPerson(aPK_obj = item['pk_identity'])
		except gmExceptions.ConstructorError:
			gmGuiHelpers.gm_show_info (
				aTitle = _('Waiting list'),
				aMessage = _('Cannot activate patient.\n\nIt has probably been disabled.')
			)
			return
		self.__id_most_recently_activated_patient = item['pk_identity']
		self.__comment_most_recently_activated_patient = gmTools.coalesce(item['comment'], '').strip()
		gmPraxis.gmCurrentPraxisBranch().remove_from_waiting_list(pk = item['pk_waiting_list'])
		curr_pat = gmPerson.gmCurrentPatient()
		if curr_pat.connected:
			if curr_pat.ID == item['pk_identity']:
				return
		wx.CallAfter(gmPatSearchWidgets.set_active_patient, patient = pat)
Пример #32
0
	def _on_activateplus_button_pressed(self, evt):
		item = self._LCTRL_patients.get_selected_item_data(only_one=True)
		if item is None:
			return
		try:
			pat = gmPerson.cPerson(aPK_obj = item['pk_identity'])
		except gmExceptions.ConstructorError:
			gmGuiHelpers.gm_show_info (
				aTitle = _('Waiting list'),
				aMessage = _('Cannot activate patient.\n\nIt has probably been disabled.')
			)
			return
		self.__id_most_recently_activated_patient = item['pk_identity']
		self.__comment_most_recently_activated_patient = gmTools.coalesce(item['comment'], '').strip()
		gmPraxis.gmCurrentPraxisBranch().remove_from_waiting_list(pk = item['pk_waiting_list'])
		curr_pat = gmPerson.gmCurrentPatient()
		if curr_pat.connected:
			if curr_pat.ID == item['pk_identity']:
				return
		wx.CallAfter(gmPatSearchWidgets.set_active_patient, patient = pat)
Пример #33
0
def export_patients_as_xdt(base_path=None):

    path = gmTools.get_unique_filename(prefix='gm-export-',
                                       suffix='',
                                       tmp_dir=base_path)
    path = os.path.splitext(path)[0]
    gmTools.mkdir(path)

    for ID in gmPerson.get_person_IDs():
        _log.info('exporting patient #%s', ID)
        identity = gmPerson.cPerson(aPK_obj=ID)
        _log.info('identity: %s', identity)
        filename = gmTools.get_unique_filename(prefix='gm_exp-%s-' %
                                               identity.subdir_name,
                                               suffix='.xdt',
                                               tmp_dir=path)
        _log.info('file: %s', filename)
        identity.export_as_gdt(filename=filename,
                               encoding='utf8'
                               #encoding = u'iso-8859-15'
                               )
Пример #34
0
    def _on_list_item_activated(self, evt):
        data = self.get_selected_item_data(only_one=True)
        pk_pat_col = self.__get_patient_pk_data_key(data=data)

        if pk_pat_col is None:
            gmDispatcher.send(signal='statustext',
                              msg=_('List not known to be patient-related.'))
            return

        pat_data = data[pk_pat_col]
        try:
            pat_pk = int(pat_data)
            pat = gmPerson.cPerson(aPK_obj=pat_pk)
        except (ValueError, TypeError):
            searcher = gmPersonSearch.cPatientSearcher_SQL()
            idents = searcher.get_identities(pat_data)
            if len(idents) == 0:
                gmDispatcher.send(signal='statustext',
                                  msg=_('No matching patient found.'))
                return
            if len(idents) == 1:
                pat = idents[0]
            else:
                from Gnumed.wxpython import gmPatSearchWidgets
                dlg = gmPatSearchWidgets.cSelectPersonFromListDlg(
                    parent=wx.GetTopLevelParent(self), id=-1)
                dlg.set_persons(persons=idents)
                result = dlg.ShowModal()
                if result == wx.ID_CANCEL:
                    dlg.Destroy()
                    return
                pat = dlg.get_selected_person()
                dlg.Destroy()
        except ConstructorError:
            gmDispatcher.send(signal='statustext',
                              msg=_('No matching patient found.'))
            return

        from Gnumed.wxpython import gmPatSearchWidgets
        gmPatSearchWidgets.set_active_patient(patient=pat)
Пример #35
0
    def get_candidate_identities(self, can_create=False):
        old_idents = gmPerson.cDTO_person.get_candidate_identities(
            self, can_create=can_create)

        # look for candidates based on their Insuree Number
        if not self.card_is_rejected:
            cmd = """
				SELECT pk_identity FROM dem.v_external_ids4identity WHERE
					value = %(val)s AND
					name = %(name)s AND
					issuer = %(kk)s
				"""
            args = {
                'val':
                self.insuree_number,
                'name':
                '%s (%s)' %
                (EXTERNAL_ID_TYPE_VK_INSUREE_NUMBER, self.raw_data['Karte']),
                'kk':
                EXTERNAL_ID_ISSUER_TEMPLATE %
                (self.raw_data['KostentraegerName'],
                 self.raw_data['Kostentraegerkennung'])
            }
            rows, idx = gmPG2.run_ro_queries(queries=[{
                'cmd': cmd,
                'args': args
            }],
                                             get_col_idx=None)

            # weed out duplicates
            name_candidate_ids = [o.ID for o in old_idents]
            for r in rows:
                if r[0] not in name_candidate_ids:
                    old_idents.append(gmPerson.cPerson(aPK_obj=r[0]))

        return old_idents
Пример #36
0
	def _get_identity(self):
		from Gnumed.business.gmPerson import cPerson
		return cPerson(self._payload[self._idx['pk_identity']])
Пример #37
0
                              beep=False)
            return False

        return True


#============================================================
# main
#------------------------------------------------------------
if __name__ == "__main__":

    if len(sys.argv) < 2:
        sys.exit()

    if sys.argv[1] != 'test':
        sys.exit()

    from Gnumed.pycommon import gmI18N
    from Gnumed.pycommon import gmDateTime
    gmI18N.activate_locale()
    gmI18N.install_domain()
    gmDateTime.init()

    from Gnumed.business import gmPerson

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

    arriba = cArriba()
    print(arriba)
    arriba.run(patient=gmPerson.gmCurrentPatient(), debug=True)
Пример #38
0
	def _get_identity(self):
		from Gnumed.business import gmPerson
		return gmPerson.cPerson(aPK_obj = self._payload[self._idx['pk_identity']])
Пример #39
0
	def test_fd_switch_to():
		gmPerson.set_active_patient(patient = gmPerson.cPerson(aPK_obj = 12))
		fd = cFreeDiamsInterface()
		fd.patient = gmPerson.gmCurrentPatient()
#		fd.switch_to_frontend(blocking = True)
		fd.import_fd2gm_file_as_drugs(filename = sys.argv[2])
Пример #40
0
	def test_fd_show_interactions():
		gmPerson.set_active_patient(patient = gmPerson.cPerson(aPK_obj = 12))
		fd = cFreeDiamsInterface()
		fd.patient = gmPerson.gmCurrentPatient()
		fd.check_interactions(substances = fd.patient.emr.get_current_medications(include_unapproved = True))
Пример #41
0
		except:
			_log.exception('error accessing [%s]', self.pdf_result)
			gmDispatcher.send(signal = u'statustext', msg = _('No [arriba] result found in [%s].') % self.pdf_result, beep = False)
			return False

		return True
#============================================================
# main
#------------------------------------------------------------
if __name__ == "__main__":

	if len(sys.argv) < 2:
		sys.exit()

	if sys.argv[1] != 'test':
		sys.exit()

	from Gnumed.pycommon import gmI18N
	from Gnumed.pycommon import gmDateTime
	gmI18N.activate_locale()
	gmI18N.install_domain()
	gmDateTime.init()

	from Gnumed.business import gmPerson

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

	arriba = cArriba()
	print arriba
	arriba.run(patient = gmPerson.gmCurrentPatient(), debug = True)
Пример #42
0
	def test_fd_switch_to():
		gmPerson.set_active_patient(patient = gmPerson.cPerson(aPK_obj = 12))
		fd = cFreeDiamsInterface()
		fd.patient = gmPerson.gmCurrentPatient()
#		fd.switch_to_frontend(blocking = True)
		fd.import_fd2gm_file_as_drugs(filename = sys.argv[2])
Пример #43
0
	def test_fd_show_interactions():
		gmPerson.set_active_patient(patient = gmPerson.cPerson(aPK_obj = 12))
		fd = cFreeDiamsInterface()
		fd.patient = gmPerson.gmCurrentPatient()
		fd.check_interactions(substances = fd.patient.emr.get_current_medications())