Example #1
0
def select_praxis_branch(parent=None):

	branches = gmPraxis.get_praxis_branches()

	if len(branches) == 0:
		if not set_active_praxis_branch(parent = parent, no_parent = False):
			return None
Example #2
0
def select_praxis_branch(parent=None):

    branches = gmPraxis.get_praxis_branches()

    if len(branches) == 0:
        if not set_active_praxis_branch(parent=parent, no_parent=False):
            return None
Example #3
0
 def refresh(lctrl):
     branches = gmPraxis.get_praxis_branches()
     items = [[b['branch'],
               gmTools.coalesce(b['l10n_unit_category'], u'')]
              for b in branches]
     lctrl.set_string_items(items=items)
     lctrl.set_data(data=branches)
Example #4
0
 def test_get_scan2pay_data():
     prax = gmPraxis.get_praxis_branches()[0]
     bills = get_bills(pk_patient=12)
     print(
         get_scan2pay_data(prax,
                           bills[0],
                           provider=None,
                           comment='GNUmed test harness' + ('x' * 400)))
Example #5
0
	def refresh(lctrl):
		branches = gmPraxis.get_praxis_branches()
		items = [
			[	b['branch'],
				gmTools.coalesce(b['l10n_unit_category'], u'')
			] for b in branches
		]
		lctrl.set_string_items(items = items)
		lctrl.set_data(data = branches)
Example #6
0
	def test_get_scan2pay_data():
		prax = gmPraxis.get_praxis_branches()[0]
		bills = get_bills(pk_patient = 12)
		print(get_scan2pay_data (
			prax,
			bills[0],
			provider=None,
			comment = 'GNUmed test harness' + ('x' * 400)
		))
Example #7
0
 def refresh(lctrl):
     branches = gmPraxis.get_praxis_branches()
     items = [[b['branch'],
               gmTools.coalesce(b['l10n_unit_category'], '')]
              for b in branches]
     lctrl.set_string_items(items=items)
     lctrl.set_data(data=branches)
     if most_recent_branch is not None:
         for idx in range(len(branches)):
             if branches[idx].format(one_line=True) == most_recent_branch:
                 lctrl.selections = [idx]
                 break
Example #8
0
	def test_clin_calc():
		from Gnumed.business import gmPraxis
		branches = gmPraxis.get_praxis_branches()
		praxis = gmPraxis.gmCurrentPraxisBranch(branches[0])

		from Gnumed.business.gmPerson import cPatient
		pat = cPatient(aPK_obj = 201)

		calc = cClinicalCalculator(patient = pat)
		#result = calc.eGFR_MDRD_short
		#result = calc.eGFR_Schwartz
		result = calc.eGFR
		#result = calc.body_surface_area
		#result = calc.get_EDC(lmp = gmDateTime.pydt_now_here())
		#result = calc.body_mass_index
		#result = calc.eGFRs
		print('%s' % result.format(with_formula = True, with_warnings = True, with_variables = True, with_sub_results = True))
Example #9
0
	def __populate_candidates_list(self):

		list_items = [[_('Patient'), self.__patient['description_gender'].strip()]]
		list_data = [(self.__patient['description'].strip(), self.__patient.get_addresses(), '', None)]

		candidate_type = _('Emergency contact')
		if self.__patient['emergency_contact'] is not None:
			name = self.__patient['emergency_contact'].strip()
			list_items.append([candidate_type, name])
			list_data.append((name, [], '', None))
		contact = self.__patient.emergency_contact_in_database
		if contact is not None:
			list_items.append([candidate_type, contact['description_gender']])
			list_data.append((contact['description'].strip(), contact.get_addresses(), '', None))

		candidate_type = _('Primary doctor')
		prov = self.__patient.primary_provider
		if prov is not None:
			ident = prov.identity
			list_items.append([candidate_type, '%s: %s' % (prov['short_alias'], ident['description_gender'])])
			list_data.append((ident['description'].strip(), ident.get_addresses(), _('in-praxis primary provider'), None))

		candidate_type = _('This praxis')
		branches = gmPraxis.get_praxis_branches(order_by = 'branch')
		for branch in branches:
			adr = branch.address
			if adr is None:
				continue
			list_items.append([candidate_type, '%s @ %s' % (branch['branch'], branch['praxis'])])
			list_data.append(('%s @ %s' % (branch['branch'], branch['praxis']), [adr], branch.format(), None))
		del branches

		candidate_type = _('External care')
		cares = gmExternalCare.get_external_care_items(pk_identity = self.__patient.ID)
		for care in cares:
			details = '%s%s@%s (%s)' % (
				gmTools.coalesce(care['provider'], '', '%s: '),
				care['unit'],
				care['organization'],
				care['issue']
			)
			name = ('%s%s' % (
				gmTools.coalesce(care['provider'], '', '%s, '),
				'%s @ %s' % (care['unit'], care['organization'])
			)).strip()
			org_unit = care.org_unit
			adr = org_unit.address
			if adr is None:
				addresses = []
			else:
				addresses = [adr]
			list_items.append([candidate_type, details])
			tt = '\n'.join(care.format(with_health_issue = True, with_address = True, with_comms = True))
			list_data.append((name, addresses, tt, org_unit))
		del cares

		emr = self.__patient.emr

		candidate_type = _('Hospital stay')
		depts = emr.get_attended_hospitals_as_org_units()
		for dept in depts:
			adr = dept.address
			if adr is None:
				continue
			list_items.append([candidate_type, '%s @ %s' % (dept['unit'], dept['organization'])])
			list_data.append(('%s @ %s' % (dept['unit'], dept['organization']), [adr], '\n'.join(dept.format(with_comms = True)), dept))
		del depts

		candidate_type = _('Procedure')
		proc_locs = emr.get_procedure_locations_as_org_units()
		for proc_loc in proc_locs:
			adr = proc_loc.address
			if adr is None:
				continue
			list_items.append([candidate_type, '%s @ %s' % (proc_loc['unit'], proc_loc['organization'])])
			list_data.append(('%s @ %s' % (proc_loc['unit'], proc_loc['organization']), [adr], '\n'.join(proc_loc.format(with_comms = True)), proc_loc))
		del proc_locs

		candidate_type = _('Lab')
		labs = emr.get_labs_as_org_units()
		for lab in labs:
			adr = lab.address
			if adr is None:
				continue
			list_items.append([candidate_type, '%s @ %s' % (lab['unit'], lab['organization'])])
			list_data.append(('%s @ %s' % (lab['unit'], lab['organization']), [adr], '\n'.join(lab.format(with_comms = True)), lab))
		del labs

		candidate_type = _('Bill receiver')
		bills = self.__patient.bills
		adrs_seen = []
		for bill in bills:
			if bill['pk_receiver_address'] in adrs_seen:
				continue
			adr = bill.address
			if adr is None:
				continue
			adrs_seen.append(bill['pk_receiver_address'])
			details = '%s%s' % (bill['invoice_id'], gmDateTime.pydt_strftime(dt = bill['close_date'], format = ' (%Y %b %d)', none_str = ''))
			list_items.append([candidate_type, details])
			list_data.append(('', [adr], '\n'.join(adr.format()), None))

		candidate_type = _('Document')
		doc_folder = self.__patient.document_folder
		doc_units = doc_folder.all_document_org_units
		for doc_unit in doc_units:
			adr = doc_unit.address
			if adr is None:
				continue
			list_items.append([candidate_type, '%s @ %s' % (doc_unit['unit'], doc_unit['organization'])])
			list_data.append(('%s @ %s' % (doc_unit['unit'], doc_unit['organization']), [adr], '\n'.join(doc_unit.format(with_comms = True)), doc_unit))
		del doc_units

		self._LCTRL_candidates.set_string_items(list_items)
		self._LCTRL_candidates.set_column_widths()
		self._LCTRL_candidates.set_data(list_data)
Example #10
0
	def __populate_candidates_list(self):

		list_items = [[_('Patient'), self.__patient.description_gender.strip()]]
		list_data = [(self.__patient.description.strip(), self.__patient.get_addresses(), '', None)]

		candidate_type = _('Emergency contact')
		if self.__patient['emergency_contact'] is not None:
			name = self.__patient['emergency_contact'].strip()
			list_items.append([candidate_type, name])
			list_data.append((name, [], '', None))
		contact = self.__patient.emergency_contact_in_database
		if contact is not None:
			list_items.append([candidate_type, contact.description_gender])
			list_data.append((contact.description.strip(), contact.get_addresses(), '', None))

		candidate_type = _('Primary doctor')
		prov = self.__patient.primary_provider
		if prov is not None:
			ident = prov.identity
			list_items.append([candidate_type, '%s: %s' % (prov['short_alias'], ident.description_gender)])
			list_data.append((ident.description.strip(), ident.get_addresses(), _('in-praxis primary provider'), None))

		candidate_type = _('This praxis')
		branches = gmPraxis.get_praxis_branches(order_by = 'branch')
		for branch in branches:
			adr = branch.address
			if adr is None:
				continue
			list_items.append([candidate_type, '%s @ %s' % (branch['branch'], branch['praxis'])])
			list_data.append(('%s @ %s' % (branch['branch'], branch['praxis']), [adr], branch.format(), None))
		del branches

		candidate_type = _('External care')
		cares = gmExternalCare.get_external_care_items(pk_identity = self.__patient.ID)
		for care in cares:
			details = '%s%s@%s (%s)' % (
				gmTools.coalesce(care['provider'], '', '%s: '),
				care['unit'],
				care['organization'],
				care['issue']
			)
			name = ('%s%s' % (
				gmTools.coalesce(care['provider'], '', '%s, '),
				'%s @ %s' % (care['unit'], care['organization'])
			)).strip()
			org_unit = care.org_unit
			adr = org_unit.address
			if adr is None:
				addresses = []
			else:
				addresses = [adr]
			list_items.append([candidate_type, details])
			tt = '\n'.join(care.format(with_health_issue = True, with_address = True, with_comms = True))
			list_data.append((name, addresses, tt, org_unit))
		del cares

		emr = self.__patient.emr

		candidate_type = _('Hospital stay')
		depts = emr.get_attended_hospitals_as_org_units()
		for dept in depts:
			adr = dept.address
			if adr is None:
				continue
			list_items.append([candidate_type, '%s @ %s' % (dept['unit'], dept['organization'])])
			list_data.append(('%s @ %s' % (dept['unit'], dept['organization']), [adr], '\n'.join(dept.format(with_comms = True)), dept))
		del depts

		candidate_type = _('Procedure')
		proc_locs = emr.get_procedure_locations_as_org_units()
		for proc_loc in proc_locs:
			adr = proc_loc.address
			if adr is None:
				continue
			list_items.append([candidate_type, '%s @ %s' % (proc_loc['unit'], proc_loc['organization'])])
			list_data.append(('%s @ %s' % (proc_loc['unit'], proc_loc['organization']), [adr], '\n'.join(proc_loc.format(with_comms = True)), proc_loc))
		del proc_locs

		candidate_type = _('Lab')
		labs = emr.get_labs_as_org_units()
		for lab in labs:
			adr = lab.address
			if adr is None:
				continue
			list_items.append([candidate_type, '%s @ %s' % (lab['unit'], lab['organization'])])
			list_data.append(('%s @ %s' % (lab['unit'], lab['organization']), [adr], '\n'.join(lab.format(with_comms = True)), lab))
		del labs

		candidate_type = _('Bill receiver')
		bills = self.__patient.bills
		adrs_seen = []
		for bill in bills:
			if bill['pk_receiver_address'] in adrs_seen:
				continue
			adr = bill.address
			if adr is None:
				continue
			adrs_seen.append(bill['pk_receiver_address'])
			details = '%s%s' % (bill['invoice_id'], gmDateTime.pydt_strftime(dt = bill['close_date'], format = ' (%Y %b %d)', none_str = ''))
			list_items.append([candidate_type, details])
			list_data.append(('', [adr], '\n'.join(adr.format()), None))

		candidate_type = _('Document')
		doc_folder = self.__patient.document_folder
		doc_units = doc_folder.all_document_org_units
		for doc_unit in doc_units:
			adr = doc_unit.address
			if adr is None:
				continue
			list_items.append([candidate_type, '%s @ %s' % (doc_unit['unit'], doc_unit['organization'])])
			list_data.append(('%s @ %s' % (doc_unit['unit'], doc_unit['organization']), [adr], '\n'.join(doc_unit.format(with_comms = True)), doc_unit))
		del doc_units

		self._LCTRL_candidates.set_string_items(list_items)
		self._LCTRL_candidates.set_column_widths()
		self._LCTRL_candidates.set_data(list_data)
Example #11
0
def run_tool():
    tool = _cfg.get(option='--tool', source_order=[('cli', 'return')])
    if tool is None:
        # not running a tool
        return None

    if tool not in _known_tools:
        _log.error('unknown tool requested: %s', tool)
        print('GNUmed startup: Unknown tool [%s] requested.' % tool)
        print('GNUmed startup: Known tools: %s' % _known_tools)
        return -1

    print('')
    print('==============================================')
    print('Running tool: %s' % tool)
    print('----------------------------------------------')
    print('')

    if tool == 'check_enc_epi_xref':
        from Gnumed.business import gmEMRStructItems
        return gmEMRStructItems.check_fk_encounter_fk_episode_x_ref()

    if tool == 'export_pat_emr_structure':
        # setup praxis
        from Gnumed.business import gmPraxis
        praxis = gmPraxis.gmCurrentPraxisBranch(
            branch=gmPraxis.get_praxis_branches()[0])
        # get patient
        from Gnumed.business import gmPersonSearch
        pat = gmPersonSearch.ask_for_patient()
        # setup exporters
        from Gnumed.business import gmEMRStructItems
        from Gnumed.exporters import gmTimelineExporter
        from Gnumed.exporters import gmPatientExporter
        while pat is not None:
            print('patient:', pat['description_gender'])
            # as EMR structure
            fname = os.path.expanduser('~/gnumed/gm-emr_structure-%s.txt' %
                                       pat.subdir_name)
            print(
                'EMR structure:',
                gmEMRStructItems.export_emr_structure(patient=pat,
                                                      filename=fname))
            # as timeline
            fname = os.path.expanduser('~/gnumed/gm-emr-%s.timeline' %
                                       pat.subdir_name)
            try:
                print(
                    'EMR timeline:',
                    gmTimelineExporter.create_timeline_file(
                        patient=pat,
                        filename=fname,
                        include_documents=True,
                        include_vaccinations=True,
                        include_encounters=True))
            finally:
                pass
            # as journal by encounter
            exporter = gmPatientExporter.cEMRJournalExporter()
            fname = os.path.expanduser(
                '~/gnumed/gm-emr-journal_by_encounter-%s.txt' %
                pat.subdir_name)
            print(
                'EMR journal (by encounter):',
                exporter.save_to_file_by_encounter(patient=pat,
                                                   filename=fname))
            # as journal by mod time
            fname = os.path.expanduser(
                '~/gnumed/gm-emr-journal_by_mod_time-%s.txt' % pat.subdir_name)
            print(
                'EMR journal (by mod time):',
                exporter.save_to_file_by_mod_time(patient=pat, filename=fname))
            # as statistical summary
            fname = os.path.expanduser('~/gnumed/gm-emr-statistics-%s.txt' %
                                       pat.subdir_name)
            output_file = io.open(fname,
                                  mode='wt',
                                  encoding='utf8',
                                  errors='replace')
            emr = pat.emr
            output_file.write(emr.format_statistics())
            output_file.close()
            print('EMR statistics:', fname)
            # as text file
            exporter = gmPatientExporter.cEmrExport(patient=pat)
            fname = os.path.expanduser('~/gnumed/gm-emr-text_export-%s.txt' %
                                       pat.subdir_name)
            output_file = io.open(fname,
                                  mode='wt',
                                  encoding='utf8',
                                  errors='replace')
            exporter.set_output_file(output_file)
            exporter.dump_constraints()
            exporter.dump_demographic_record(True)
            exporter.dump_clinical_record()
            exporter.dump_med_docs()
            output_file.close()
            print('EMR text file:', fname)
            # another patient ?
            pat = gmPersonSearch.ask_for_patient()

        return 0

    # tool export_patient_as (vcf, gdt, ...)
    #if tool == 'export_pat_demographics':

    # should not happen (because checked against _known_tools)
    return -1
Example #12
0
File: gmHL7.py Project: sk/gnumed
	def test_import_HL7(filename):
		# would normally be set by external configuration:
		from Gnumed.business import gmPraxis
		gmPraxis.gmCurrentPraxisBranch(branch = gmPraxis.get_praxis_branches()[0])
		if not import_hl7_file(filename):
			print "error with", filename
Example #13
0
#============================================================
# main
#------------------------------------------------------------
if __name__ == '__main__':

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

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

	gmI18N.activate_locale()
	gmI18N.install_domain('gnumed')

	from Gnumed.business import gmPraxis
	praxis = gmPraxis.gmCurrentPraxisBranch(branch = gmPraxis.get_praxis_branches()[0])

	from Gnumed.business import gmPerson
	# 14 / 20 / 138 / 58 / 20 / 5
	pat = gmPerson.gmCurrentPatient(gmPerson.cPatient(aPK_obj = 14))
	fname = '~/gnumed/gm2tl-%s.timeline' % pat.subdir_name

	print (create_timeline_file (
		patient = pat,
		filename = os.path.expanduser(fname),
		include_documents = True,
		include_vaccinations = True,
		include_encounters = True
	))
Example #14
0
def run_tool():
    """Run a console tool.

	Exit codes as per man page:
		   0: normal termination of the client
		 < 0: some error occurred while trying to run a console tool
			  -1: an unknown console tool was requested
			< -1: an error occurred while a console tool was run
		-999: hard abort of the client

	One of these needs to be returned from this function (and,
	by extension from the tool having been run, if any).
	"""
    tool = _cfg.get(option='--tool', source_order=[('cli', 'return')])
    if tool is None:
        # not running a tool
        return None

    if tool not in _known_tools:
        _log.error('unknown tool requested: %s', tool)
        print('GNUmed startup: Unknown tool [%s] requested.' % tool)
        print('GNUmed startup: Known tools: %s' % _known_tools)
        return -1

    print('')
    print('==============================================')
    print('Running tool: %s' % tool)
    print('----------------------------------------------')
    print('')

    if tool == 'generate_man_page':
        man_page_fname = os.path.abspath(os.path.join('.', 'gnumed.1'))
        man_page_file = open(man_page_fname, mode='wt', encoding='utf8')
        man_page_file.write(__doc__ % datetime.date.today().strftime('%x'))
        man_page_file.close()
        print('MAN page saved as:', man_page_fname)
        return 0

    login, creds = gmPG2.request_login_params()
    pool = gmConnectionPool.gmConnectionPool()
    pool.credentials = creds
    print('')

    if tool == 'read_all_rows_of_table':
        result = gmPG2.read_all_rows_of_table()
        if result in [None, True]:
            print('Success.')
            return 0
        print('Failed. Check the log for details.')
        return -2

    if tool == 'check_mimetypes_in_archive':
        from Gnumed.business import gmDocuments
        return gmDocuments.check_mimetypes_in_archive()

    if tool == 'check_enc_epi_xref':
        from Gnumed.business import gmEMRStructItems
        return gmEMRStructItems.check_fk_encounter_fk_episode_x_ref()

    if tool == 'fingerprint_db':
        fname = 'db-fingerprint.txt'
        result = gmPG2.get_db_fingerprint(fname=fname, with_dump=True)
        if result == fname:
            print('Success: %s' % fname)
            return 0
        print('Failed. Check the log for details.')
        return -2

    if tool == 'export_pat_emr_structure':
        # setup praxis
        from Gnumed.business import gmPraxis
        praxis = gmPraxis.gmCurrentPraxisBranch(
            branch=gmPraxis.get_praxis_branches()[0])
        # get patient
        from Gnumed.business import gmPersonSearch
        pat = gmPersonSearch.ask_for_patient()
        # setup exporters
        from Gnumed.business import gmEMRStructItems
        from Gnumed.exporters import gmTimelineExporter
        from Gnumed.exporters import gmPatientExporter
        while pat is not None:
            print('patient:', pat.description_gender)
            # as EMR structure
            fname = os.path.expanduser('~/gnumed/gm-emr_structure-%s.txt' %
                                       pat.subdir_name)
            print(
                'EMR structure:',
                gmEMRStructItems.export_emr_structure(patient=pat,
                                                      filename=fname))
            # as timeline
            fname = os.path.expanduser('~/gnumed/gm-emr-%s.timeline' %
                                       pat.subdir_name)
            try:
                print(
                    'EMR timeline:',
                    gmTimelineExporter.create_timeline_file(
                        patient=pat,
                        filename=fname,
                        include_documents=True,
                        include_vaccinations=True,
                        include_encounters=True))
            finally:
                pass
            # as journal by encounter
            exporter = gmPatientExporter.cEMRJournalExporter()
            fname = os.path.expanduser(
                '~/gnumed/gm-emr-journal_by_encounter-%s.txt' %
                pat.subdir_name)
            print(
                'EMR journal (by encounter):',
                exporter.save_to_file_by_encounter(patient=pat,
                                                   filename=fname))
            # as journal by mod time
            fname = os.path.expanduser(
                '~/gnumed/gm-emr-journal_by_mod_time-%s.txt' % pat.subdir_name)
            print(
                'EMR journal (by mod time):',
                exporter.save_to_file_by_mod_time(patient=pat, filename=fname))
            # as statistical summary
            fname = os.path.expanduser('~/gnumed/gm-emr-statistics-%s.txt' %
                                       pat.subdir_name)
            output_file = open(fname,
                               mode='wt',
                               encoding='utf8',
                               errors='replace')
            emr = pat.emr
            output_file.write(emr.format_statistics())
            output_file.close()
            print('EMR statistics:', fname)
            # as text file
            exporter = gmPatientExporter.cEmrExport(patient=pat)
            fname = os.path.expanduser('~/gnumed/gm-emr-text_export-%s.txt' %
                                       pat.subdir_name)
            output_file = open(fname,
                               mode='wt',
                               encoding='utf8',
                               errors='replace')
            exporter.set_output_file(output_file)
            exporter.dump_constraints()
            exporter.dump_demographic_record(True)
            exporter.dump_clinical_record()
            exporter.dump_med_docs()
            output_file.close()
            print('EMR text file:', fname)
            # another patient ?
            pat = gmPersonSearch.ask_for_patient()
        return 0

    # tool export_patient_as (vcf, gdt, ...)
    #if tool == 'export_pat_demographics':

    # should not happen (because checked against _known_tools)
    return -1
Example #15
0
def set_active_praxis_branch(parent=None, no_parent=False):

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

	branches = gmPraxis.get_praxis_branches()

	if len(branches) == 1:
		_log.debug('only one praxis branch configured')
		gmPraxis.gmCurrentPraxisBranch(branches[0])
		return True

	if len(branches) == 0:
		orgs = gmOrganization.get_orgs()
		if len(orgs) == 0:
			pk_cat = gmOrganization.create_org_category(category = u'Praxis')
			org = gmOrganization.create_org(_('Your praxis'), pk_cat)
			unit = org.add_unit(_('Your branch'))
			branch = gmPraxis.create_praxis_branch(pk_org_unit = unit['pk_org_unit'])
			_log.debug('auto-created praxis branch because no organizations existed: %s', branch)
			gmPraxis.gmCurrentPraxisBranch(branch)
			gmGuiHelpers.gm_show_info (
				title = _('Praxis configuration ...'),
				info = _(
					'GNUmed has auto-created the following\n'
					'praxis branch for you (which you can\n'
					'later configure as needed):\n'
					'\n'
					'%s'
				) % branch.format()
			)
			return True

		if len(orgs) == 1:
			units = orgs[0].units
			if len(units) == 1:
				branch = gmPraxis.create_praxis_branch(pk_org_unit = units[0]['pk_org_unit'])
				_log.debug('auto-selected praxis branch because only one organization with only one unit existed: %s', branch)
				gmPraxis.gmCurrentPraxisBranch(branch)
				gmGuiHelpers.gm_show_info (
					title = _('Praxis configuration ...'),
					info = _(
						'GNUmed has auto-selected the following\n'
						'praxis branch for you (which you can\n'
						'later configure as needed):\n'
						'\n'
						'%s'
					) % branch.format()
				)
				return True

		_log.debug('no praxis branches configured, selecting from organization units')
		msg = _(
				'No praxis branches configured currently.\n'
				'\n'
				'You MUST select one unit of an organization to be the initial\n'
				'branch (site, office) which you are logging in from.'
		)
		unit = gmOrganizationWidgets.select_org_unit(msg = msg, no_parent = True)
		if unit is None:
			_log.warning('no organization unit selected, aborting')
			return False
		_log.debug('org unit selected as praxis branch: %s', unit)
		branch = gmPraxis.create_praxis_branch(pk_org_unit = unit['pk_org_unit'])
		_log.debug('created praxis branch: %s', branch)
		gmPraxis.gmCurrentPraxisBranch(branch)
		return True

	#--------------------
	def refresh(lctrl):
		branches = gmPraxis.get_praxis_branches()
		items = [
			[	b['branch'],
				gmTools.coalesce(b['l10n_unit_category'], u'')
			] for b in branches
		]
		lctrl.set_string_items(items = items)
		lctrl.set_data(data = branches)
	#--------------------
	branch = gmListWidgets.get_choices_from_list (
		parent = parent,
		msg = _("Select branch (of praxis [%s]) which you are logging in from.\n") % branches[0]['praxis'],
		caption = _('Praxis branch selection ...'),
		columns = [_('Branch'), _('Branch type')],
		can_return_empty = False,
		single_selection = True,
		refresh_callback = refresh
	)
	if branch is None:
		_log.warning('no praxis branch selected, aborting')
		return False
	gmPraxis.gmCurrentPraxisBranch(branch)
	return True
Example #16
0
def manage_praxis_branches(parent=None):

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

    #---------------------------
    def get_unit_tooltip(unit):
        if unit is None:
            return None
        return u'\n'.join(
            unit.format(with_address=True, with_org=True, with_comms=True))

    #---------------------------
    def manage_orgs():
        gmOrganizationWidgets.manage_orgs(parent=parent)

    #---------------------------

    branches = gmPraxis.get_praxis_branches()
    org = branches[0].organization
    praxis = branches[0]['praxis']

    msg = _('Pick those units of "%s" which are branches of your praxis !\n'
            '\n'
            'Note that no other client should be connected at this time.\n'
            '\n'
            'If you want to select another organization entirely\n'
            'first remove all existing branches.\n') % praxis

    picker = gmListWidgets.cItemPickerDlg(parent, -1, msg=msg)
    picker.extra_button = (_('Manage units'),
                           _('Manage organizations and their units'),
                           manage_orgs)
    picker.left_item_tooltip_callback = get_unit_tooltip
    picker.right_item_tooltip_callback = get_unit_tooltip
    picker.set_columns(columns=[_('Units of "%s"') % praxis],
                       columns_right=[_('Branches of your praxis')])
    units = org.units
    branch_unit_pks = [b['pk_org_unit'] for b in branches]
    branch_units = []
    for unit in units:
        if unit['pk_org_unit'] in branch_unit_pks:
            branch_units.append(unit)
    items = [
        u'%s%s' %
        (u['unit'], gmTools.coalesce(u['l10n_unit_category'], u'', u' (%s)'))
        for u in units
    ]
    picker.set_choices(choices=items, data=units)
    items = [
        u'%s%s' %
        (u['unit'], gmTools.coalesce(u['l10n_unit_category'], u'', u' (%s)'))
        for u in branch_units
    ]
    picker.set_picks(picks=items, data=branch_units)
    del units
    del branch_unit_pks
    del branch_units
    del items

    result = picker.ShowModal()

    if result == wx.ID_CANCEL:
        picker.Destroy()
        return None

    picks = picker.picks
    picker.Destroy()

    failed_delete_msg = _('Cannot delete praxis branch(es).\n'
                          '\n'
                          'There are probably clients logged in\n'
                          'from other locations. You need to log out\n'
                          'all but this client before the praxis can\n'
                          'be reconfigured.')

    if len(picks) == 0:
        if not gmPraxis.delete_praxis_branches():
            gmGuiHelpers.gm_show_error(error=failed_delete_msg,
                                       title=_('Configuring praxis ...'))
            return False
        while not set_active_praxis_branch(parent=parent):
            pass
        return

    pk_picked_units = [p['pk_org_unit'] for p in picks]
    pk_branches_to_keep = [
        b['pk_praxis_branch'] for b in gmPraxis.get_praxis_branches()
        if b['pk_org_unit'] in pk_picked_units
    ]
    if len(pk_branches_to_keep) == 0:
        if not gmPraxis.delete_praxis_branches():
            gmGuiHelpers.gm_show_error(error=failed_delete_msg,
                                       title=_('Configuring praxis ...'))
            return False
    else:
        if not gmPraxis.delete_praxis_branches(
                except_pk_praxis_branches=pk_branches_to_keep):
            gmGuiHelpers.gm_show_error(error=failed_delete_msg,
                                       title=_('Configuring praxis ...'))
            return False
    gmPraxis.create_praxis_branches(pk_org_units=pk_picked_units)

    # detect whether active branch in kept branches
    if gmPraxis.gmCurrentPraxisBranch(
    )['pk_praxis_branch'] in pk_branches_to_keep:
        return

    while not set_active_praxis_branch(parent=parent):
        pass
Example #17
0
def set_active_praxis_branch(parent=None, no_parent=False):

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

    branches = gmPraxis.get_praxis_branches()

    if len(branches) == 1:
        _log.debug('only one praxis branch configured, activating')
        gmPraxis.gmCurrentPraxisBranch(branches[0])
        return True

    if len(branches) == 0:
        orgs = gmOrganization.get_orgs()
        if len(orgs) == 0:
            new_branch_of_new_praxis = __create_praxis_and_branch()
            gmPraxis.gmCurrentPraxisBranch(new_branch_of_new_praxis)
            return True

        if len(orgs) == 1:
            units = orgs[0].units
            if len(units) == 1:
                branch = __create_branch_for_praxis(units[0]['pk_org_unit'])
                gmPraxis.gmCurrentPraxisBranch(branch)
                return True

        branch = __select_org_unit_as_branch()
        if branch is None:
            return False

        gmPraxis.gmCurrentPraxisBranch(branch)
        return True

    most_recent_branch = __get_most_recently_selected_branch()

    #--------------------
    def refresh(lctrl):
        branches = gmPraxis.get_praxis_branches()
        items = [[b['branch'],
                  gmTools.coalesce(b['l10n_unit_category'], '')]
                 for b in branches]
        lctrl.set_string_items(items=items)
        lctrl.set_data(data=branches)
        if most_recent_branch is not None:
            for idx in range(len(branches)):
                if branches[idx].format(one_line=True) == most_recent_branch:
                    lctrl.selections = [idx]
                    break

    #--------------------

    branch = gmListWidgets.get_choices_from_list(
        parent=parent,
        msg=_(
            "Select the branch of praxis [%s] which you are logging in from.\n"
        ) % branches[0]['praxis'],
        caption=_('Praxis branch selection ...'),
        columns=[_('Branch'), _('Branch type')],
        can_return_empty=False,
        single_selection=True,
        refresh_callback=refresh)
    if branch is None:
        _log.warning('no praxis branch selected, aborting')
        return False

    __update_most_recently_selected_branch(branch)
    gmPraxis.gmCurrentPraxisBranch(branch)
    return True
Example #18
0
def manage_praxis_branches(parent=None):

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

	#---------------------------
	def get_unit_tooltip(unit):
		if unit is None:
			return None
		return u'\n'.join(unit.format(with_address = True, with_org = True, with_comms = True))
	#---------------------------
	def manage_orgs():
		gmOrganizationWidgets.manage_orgs(parent = parent)
	#---------------------------

	branches = gmPraxis.get_praxis_branches()
	org = branches[0].organization
	praxis = branches[0]['praxis']

	msg = _(
		'Pick those units of "%s" which are branches of your praxis !\n'
		'\n'
		'Note that no other client should be connected at this time.\n'
		'\n'
		'If you want to select another organization entirely\n'
		'first remove all existing branches.\n'
	) % praxis

	picker = gmListWidgets.cItemPickerDlg(parent, -1, msg = msg)
	picker.extra_button = (
		_('Manage units'),
		_('Manage organizations and their units'),
		manage_orgs
	)
	picker.left_item_tooltip_callback = get_unit_tooltip
	picker.right_item_tooltip_callback = get_unit_tooltip
	picker.set_columns(columns = [_('Units of "%s"') % praxis], columns_right = [_('Branches of your praxis')])
	units = org.units
	branch_unit_pks = [b['pk_org_unit'] for b in branches]
	branch_units = []
	for unit in units:
		if unit['pk_org_unit'] in branch_unit_pks:
			branch_units.append(unit)
	items = [ u'%s%s' % (u['unit'], gmTools.coalesce(u['l10n_unit_category'], u'', u' (%s)')) for u in units ]
	picker.set_choices(choices = items, data = units)
	items = [ u'%s%s' % (u['unit'], gmTools.coalesce(u['l10n_unit_category'], u'', u' (%s)')) for u in branch_units ]
	picker.set_picks(picks = items, data = branch_units)
	del units
	del branch_unit_pks
	del branch_units
	del items

	result = picker.ShowModal()

	if result == wx.ID_CANCEL:
		picker.Destroy()
		return None

	picks = picker.picks
	picker.Destroy()

	failed_delete_msg = _(
		'Cannot delete praxis branch(es).\n'
		'\n'
		'There are probably clients logged in\n'
		'from other locations. You need to log out\n'
		'all but this client before the praxis can\n'
		'be reconfigured.'
	)

	if len(picks) == 0:
		if not gmPraxis.delete_praxis_branches():
			gmGuiHelpers.gm_show_error (
				error = failed_delete_msg,
				title = _('Configuring praxis ...')
			)
			return False
		while not set_active_praxis_branch(parent = parent):
			pass
		return

	pk_picked_units = [p['pk_org_unit'] for p in picks]
	pk_branches_to_keep = [
		b['pk_praxis_branch'] for b in gmPraxis.get_praxis_branches()
		if b['pk_org_unit'] in pk_picked_units
	]
	if len(pk_branches_to_keep) == 0:
		if not gmPraxis.delete_praxis_branches():
			gmGuiHelpers.gm_show_error (
				error = failed_delete_msg,
				title = _('Configuring praxis ...')
			)
			return False
	else:
		if not gmPraxis.delete_praxis_branches(except_pk_praxis_branches = pk_branches_to_keep):
			gmGuiHelpers.gm_show_error (
				error = failed_delete_msg,
				title = _('Configuring praxis ...')
			)
			return False
	gmPraxis.create_praxis_branches(pk_org_units = pk_picked_units)

	# detect whether active branch in kept branches
	if gmPraxis.gmCurrentPraxisBranch()['pk_praxis_branch'] in pk_branches_to_keep:
		return

	while not set_active_praxis_branch(parent = parent):
		pass
Example #19
0
def set_active_praxis_branch(parent=None, no_parent=False):

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

    branches = gmPraxis.get_praxis_branches()

    if len(branches) == 1:
        _log.debug('only one praxis branch configured')
        gmPraxis.gmCurrentPraxisBranch(branches[0])
        return True

    if len(branches) == 0:
        orgs = gmOrganization.get_orgs()
        if len(orgs) == 0:
            pk_cat = gmOrganization.create_org_category(category=u'Praxis')
            org = gmOrganization.create_org(_('Your praxis'), pk_cat)
            unit = org.add_unit(_('Your branch'))
            branch = gmPraxis.create_praxis_branch(
                pk_org_unit=unit['pk_org_unit'])
            _log.debug(
                'auto-created praxis branch because no organizations existed: %s',
                branch)
            gmPraxis.gmCurrentPraxisBranch(branch)
            gmGuiHelpers.gm_show_info(
                title=_('Praxis configuration ...'),
                info=_('GNUmed has auto-created the following\n'
                       'praxis branch for you (which you can\n'
                       'later configure as needed):\n'
                       '\n'
                       '%s') % branch.format())
            return True

        if len(orgs) == 1:
            units = orgs[0].units
            if len(units) == 1:
                branch = gmPraxis.create_praxis_branch(
                    pk_org_unit=units[0]['pk_org_unit'])
                _log.debug(
                    'auto-selected praxis branch because only one organization with only one unit existed: %s',
                    branch)
                gmPraxis.gmCurrentPraxisBranch(branch)
                gmGuiHelpers.gm_show_info(
                    title=_('Praxis configuration ...'),
                    info=_('GNUmed has auto-selected the following\n'
                           'praxis branch for you (which you can\n'
                           'later configure as needed):\n'
                           '\n'
                           '%s') % branch.format())
                return True

        _log.debug(
            'no praxis branches configured, selecting from organization units')
        msg = _(
            'No praxis branches configured currently.\n'
            '\n'
            'You MUST select one unit of an organization to be the initial\n'
            'branch (site, office) which you are logging in from.')
        unit = gmOrganizationWidgets.select_org_unit(msg=msg, no_parent=True)
        if unit is None:
            _log.warning('no organization unit selected, aborting')
            return False
        _log.debug('org unit selected as praxis branch: %s', unit)
        branch = gmPraxis.create_praxis_branch(pk_org_unit=unit['pk_org_unit'])
        _log.debug('created praxis branch: %s', branch)
        gmPraxis.gmCurrentPraxisBranch(branch)
        return True

    #--------------------
    def refresh(lctrl):
        branches = gmPraxis.get_praxis_branches()
        items = [[b['branch'],
                  gmTools.coalesce(b['l10n_unit_category'], u'')]
                 for b in branches]
        lctrl.set_string_items(items=items)
        lctrl.set_data(data=branches)

    #--------------------
    branch = gmListWidgets.get_choices_from_list(
        parent=parent,
        msg=_(
            "Select the branch of praxis [%s] which you are logging in from.\n"
        ) % branches[0]['praxis'],
        caption=_('Praxis branch selection ...'),
        columns=[_('Branch'), _('Branch type')],
        can_return_empty=False,
        single_selection=True,
        refresh_callback=refresh)
    if branch is None:
        _log.warning('no praxis branch selected, aborting')
        return False
    gmPraxis.gmCurrentPraxisBranch(branch)
    return True
Example #20
0
	def test_import_HL7(filename):
		# would normally be set by external configuration:
		from Gnumed.business import gmPraxis
		gmPraxis.gmCurrentPraxisBranch(branch = gmPraxis.get_praxis_branches()[0])
		if not import_hl7_file(filename):
			print("error with", filename)
Example #21
0
def run_tool():
	tool = _cfg.get(option = '--tool', source_order = [('cli', 'return')])
	if tool is None:
		# not running a tool
		return None

	if tool not in _known_tools:
		_log.error('unknown tool requested: %s', tool)
		print('GNUmed startup: Unknown tool [%s] requested.' % tool)
		print('GNUmed startup: Known tools: %s' % _known_tools)
		return -1

	print('')
	print('==============================================')
	print('Running tool: %s' % tool)
	print('----------------------------------------------')
	print('')

	if tool == 'check_enc_epi_xref':
		from Gnumed.business import gmEMRStructItems
		return gmEMRStructItems.check_fk_encounter_fk_episode_x_ref()

	if tool == 'export_pat_emr_structure':
		# setup praxis
		from Gnumed.business import gmPraxis
		praxis = gmPraxis.gmCurrentPraxisBranch(branch = gmPraxis.get_praxis_branches()[0])
		# get patient
		from Gnumed.business import gmPersonSearch
		pat = gmPersonSearch.ask_for_patient()
		# setup exporters
		from Gnumed.business import gmEMRStructItems
		from Gnumed.exporters import gmTimelineExporter
		from Gnumed.exporters import gmPatientExporter
		while pat is not None:
			print('patient:', pat['description_gender'])
			# as EMR structure
			fname = os.path.expanduser('~/gnumed/gm-emr_structure-%s.txt' % pat.subdir_name)
			print('EMR structure:', gmEMRStructItems.export_emr_structure(patient = pat, filename = fname))
			# as timeline
			fname = os.path.expanduser('~/gnumed/gm-emr-%s.timeline' % pat.subdir_name)
			try:
				print('EMR timeline:', gmTimelineExporter.create_timeline_file (
					patient = pat,
					filename = fname,
					include_documents = True,
					include_vaccinations = True,
					include_encounters = True
				))
			finally:
				pass
			# as journal by encounter
			exporter = gmPatientExporter.cEMRJournalExporter()
			fname = os.path.expanduser('~/gnumed/gm-emr-journal_by_encounter-%s.txt' % pat.subdir_name)
			print('EMR journal (by encounter):', exporter.save_to_file_by_encounter(patient = pat, filename = fname))
			# as journal by mod time
			fname = os.path.expanduser('~/gnumed/gm-emr-journal_by_mod_time-%s.txt' % pat.subdir_name)
			print('EMR journal (by mod time):', exporter.save_to_file_by_mod_time(patient = pat, filename = fname))
			# as statistical summary
			fname = os.path.expanduser('~/gnumed/gm-emr-statistics-%s.txt' % pat.subdir_name)
			output_file = io.open(fname, mode = 'wt', encoding = 'utf8', errors = 'replace')
			emr = pat.emr
			output_file.write(emr.format_statistics())
			output_file.close()
			print('EMR statistics:', fname)
			# as text file
			exporter = gmPatientExporter.cEmrExport(patient = pat)
			fname = os.path.expanduser('~/gnumed/gm-emr-text_export-%s.txt' % pat.subdir_name)
			output_file = io.open(fname, mode = 'wt', encoding = 'utf8', errors = 'replace')
			exporter.set_output_file(output_file)
			exporter.dump_constraints()
			exporter.dump_demographic_record(True)
			exporter.dump_clinical_record()
			exporter.dump_med_docs()
			output_file.close()
			print('EMR text file:', fname)
			# another patient ?
			pat = gmPersonSearch.ask_for_patient()

		return 0

	# tool export_patient_as (vcf, gdt, ...)
	#if tool == 'export_pat_demographics':

	# should not happen (because checked against _known_tools)
	return -1
Example #22
0
#============================================================
# main
#------------------------------------------------------------
if __name__ == '__main__':

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

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

	gmI18N.activate_locale()
	gmI18N.install_domain('gnumed')

	from Gnumed.business import gmPraxis
	praxis = gmPraxis.gmCurrentPraxisBranch(branch = gmPraxis.get_praxis_branches()[0])

	from Gnumed.business import gmPerson
	# 14 / 20 / 138 / 58 / 20 / 5
	pat = gmPerson.gmCurrentPatient(gmPerson.cPatient(aPK_obj = 14))
	fname = '~/gnumed/gm2tl-%s.timeline' % pat.subdir_name

	print (create_timeline_file (
		patient = pat,
		filename = os.path.expanduser(fname),
		include_documents = True,
		include_vaccinations = True,
		include_encounters = True
	))
Example #23
0
#============================================================
# main
#------------------------------------------------------------
if __name__ == '__main__':

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

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

    gmI18N.activate_locale()
    gmI18N.install_domain('gnumed')

    from Gnumed.business import gmPraxis
    praxis = gmPraxis.gmCurrentPraxisBranch(
        branch=gmPraxis.get_praxis_branches()[0])

    from Gnumed.business import gmPerson
    # 14 / 20 / 138 / 58 / 20 / 5
    pat = gmPerson.gmCurrentPatient(gmPerson.cPatient(aPK_obj=14))
    fname = '~/gnumed/gm2tl-%s.timeline' % pat.subdir_name

    print(
        create_timeline_file(patient=pat,
                             filename=os.path.expanduser(fname),
                             include_documents=True,
                             include_vaccinations=True,
                             include_encounters=True))
Example #24
0
		wx.GetApp().MainLoop()

	#----------------------------------------------------------------
	def test_health_issue_edit_area_dlg():
		app = wx.PyWidgetTester(size = (200, 300))
		edit_health_issue(parent=app.frame, issue=None)

	#----------------------------------------------------------------
	def test_health_issue_edit_area_pnl():
		app = wx.PyWidgetTester(size = (200, 300))
		app.SetWidget(cHealthIssueEditAreaPnl, id=-1, size = (400,400))
		app.MainLoop()

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

	branch = gmPraxis.get_praxis_branches()[0]
	prax = gmPraxis.gmCurrentPraxisBranch(branch)
	print(prax)

	#app = wx.PyWidgetTester(size = (400, 40))
	app = wx.App()#size = (400, 40))

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

#	try:
		# lauch emr dialogs test application