Beispiel #1
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
Beispiel #2
0
	def warn_on_unsaved_soap(self):
		for page_idx in range(self.GetPageCount()):
			page = self.GetPage(page_idx)
			if page.empty:
				continue

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

		return True
Beispiel #3
0
	def warn_on_unsaved_soap(self):
		for page_idx in range(self.GetPageCount()):
			page = self.GetPage(page_idx)
			if page.empty:
				continue

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

		return True
Beispiel #4
0
def update_loinc_reference_data():

    wx.BeginBusyCursor()

    gmDispatcher.send(signal='statustext',
                      msg=_('Updating LOINC data can take quite a while...'),
                      beep=True)

    # download
    loinc_zip = gmNetworkTools.download_file(
        url='http://www.gnumed.de/downloads/data/loinc/loinctab.zip',
        suffix='.zip')
    if loinc_zip is None:
        wx.EndBusyCursor()
        gmGuiHelpers.gm_show_warning(
            aTitle=_('Downloading LOINC'),
            aMessage=_('Error downloading the latest LOINC data.\n'))
        return False

    _log.debug('downloaded zipped LOINC data into [%s]', loinc_zip)

    loinc_dir = gmNetworkTools.unzip_data_pack(filename=loinc_zip)

    # split master data file
    data_fname, license_fname = gmLOINC.split_LOINCDBTXT(
        input_fname=os.path.join(loinc_dir, 'LOINCDB.TXT'))

    wx.EndBusyCursor()

    conn = gmAuthWidgets.get_dbowner_connection(
        procedure=_('importing LOINC reference data'))
    if conn is None:
        return False

    wx.BeginBusyCursor()

    # import data
    if gmLOINC.loinc_import(data_fname=data_fname,
                            license_fname=license_fname,
                            conn=conn):
        gmDispatcher.send(signal='statustext',
                          msg=_('Successfully imported LOINC reference data.'))
    else:
        gmDispatcher.send(signal='statustext',
                          msg=_('Importing LOINC reference data failed.'),
                          beep=True)

    wx.EndBusyCursor()
    return True
Beispiel #5
0
def __database_is_acceptable_for_use(require_version: bool = True,
                                     expected_version: int = None,
                                     login=None) -> bool:
    if not gmPG2.schema_exists(schema='gm'):
        _log.error('schema [gm] does not exist - database not bootstrapped ?')
        gmGuiHelpers.gm_show_error(msg_not_bootstrapped,
                                   _('Verifying database'))
        return False

    if not gmPG2.database_schema_compatible(version=expected_version):
        client_version = _cfg.get(option='client_version')
        connected_db_version = gmPG2.get_schema_version()
        msg = msg_generic % (client_version, connected_db_version,
                             expected_version,
                             gmTools.coalesce(login.host, '<localhost>'),
                             login.database, login.user)
        if require_version:
            gmGuiHelpers.gm_show_error(msg + '\n\n' + msg_fail,
                                       _('Verifying database version'))
            return False

        gmGuiHelpers.gm_show_info(msg + '\n\n' + msg_override,
                                  _('Verifying database version'))

    max_skew = 10 if _cfg.get(option='debug') else 1  # in minutes
    if not gmPG2.sanity_check_time_skew(tolerance=(max_skew * 60)):
        if not _cfg.get(option='debug'):
            gmGuiHelpers.gm_show_error(msg_time_skew_fail % max_skew,
                                       _('Verifying database settings'))
            return False

        gmGuiHelpers.gm_show_warning(msg_time_skew_warn % max_skew,
                                     _('Verifying database settings'))

    sanity_level, message = gmPG2.sanity_check_database_settings()
    if sanity_level != 0:
        gmGuiHelpers.gm_show_error((msg_insanity % message),
                                   _('Verifying database settings'))
        if sanity_level == 2:
            return False

    gmLog2.log_multiline(logging.DEBUG,
                         message='DB seems suitable to use, fingerprint:',
                         text=gmPG2.get_db_fingerprint(eol='\n'))

    return True
Beispiel #6
0
def _check_has_dob(patient=None):

	if patient is None:
		return

	if patient['dob'] is None:
		gmGuiHelpers.gm_show_warning (
			aTitle = _('Checking date of birth'),
			aMessage = _(
				'\n'
				' %s\n'
				'\n'
				'The date of birth for this patient is not known !\n'
				'\n'
				'You can proceed to work on the patient but\n'
				'GNUmed will be unable to assist you with\n'
				'age-related decisions.\n'
			) % patient['description_gender']
		)
def _check_has_dob(patient=None):

	if patient is None:
		return

	if patient['dob'] is None:
		gmGuiHelpers.gm_show_warning (
			aTitle = _('Checking date of birth'),
			aMessage = _(
				'\n'
				' %s\n'
				'\n'
				'The date of birth for this patient is not known !\n'
				'\n'
				'You can proceed to work on the patient but\n'
				'GNUmed will be unable to assist you with\n'
				'age-related decisions.\n'
			) % patient['description_gender']
		)
Beispiel #8
0
	def _lst_item_activated(self, evt):

		try:
			msg = self._LCTRL_provider_inbox.get_selected_item_data(only_one = True)
		except IndexError:
			_log.exception('problem with provider inbox item data access')
			gmGuiHelpers.gm_show_error (
				aTitle = _('handling provider inbox item'),
				aMessage = _('There was a problem accessing the message data.')
			)
			_log.debug('effecting inbox reload')
			wx.CallAfter(self.__populate_inbox)
			return False

		if msg is None:
			return

		handler_key = '%s.%s' % (msg['category'], msg['type'])
		try:
			handle_item = cProviderInboxPnl._item_handlers[handler_key]
		except KeyError:
			if msg['pk_patient'] is None:
				gmGuiHelpers.gm_show_warning (
					_('No double-click action pre-programmed into\n'
					'GNUmed for message category and type:\n'
					'\n'
					' [%s]\n'
					) % handler_key,
					_('handling provider inbox item')
				)
				return False
			handle_item = self._goto_patient

		if not handle_item(pk_context = msg['pk_context'], pk_patient = msg['pk_patient']):
			_log.error('item handler returned <False>')
			_log.error('handler key: [%s]', handler_key)
			_log.error('message: %s', str(msg))
			return False

		return True
Beispiel #9
0
	def _lst_item_activated(self, evt):

		try:
			msg = self._LCTRL_provider_inbox.get_selected_item_data(only_one = True)
		except IndexError:
			_log.exception('problem with provider inbox item data access')
			gmGuiHelpers.gm_show_error (
				aTitle = _('handling provider inbox item'),
				aMessage = _('There was a problem accessing the message data.')
			)
			_log.debug('effecting inbox reload')
			wx.CallAfter(self.__populate_inbox)
			return False

		if msg is None:
			return

		handler_key = '%s.%s' % (msg['category'], msg['type'])
		try:
			handle_item = cProviderInboxPnl._item_handlers[handler_key]
		except KeyError:
			if msg['pk_patient'] is None:
				gmGuiHelpers.gm_show_warning (
					_('No double-click action pre-programmed into\n'
					'GNUmed for message category and type:\n'
					'\n'
					' [%s]\n'
					) % handler_key,
					_('handling provider inbox item')
				)
				return False
			handle_item = self._goto_patient

		if not handle_item(pk_context = msg['pk_context'], pk_patient = msg['pk_patient']):
			_log.error('item handler returned <False>')
			_log.error('handler key: [%s]', handler_key)
			_log.error('message: %s', str(msg))
			return False

		return True
Beispiel #10
0
def update_loinc_reference_data():

	wx.BeginBusyCursor()

	gmDispatcher.send(signal = 'statustext', msg = _('Updating LOINC data can take quite a while...'), beep = True)

	# download
	loinc_zip = gmNetworkTools.download_file(url = 'http://www.gnumed.de/downloads/data/loinc/loinctab.zip', suffix = '.zip')
	if loinc_zip is None:
		wx.EndBusyCursor()
		gmGuiHelpers.gm_show_warning (
			aTitle = _('Downloading LOINC'),
			aMessage = _('Error downloading the latest LOINC data.\n')
		)
		return False

	_log.debug('downloaded zipped LOINC data into [%s]', loinc_zip)

	loinc_dir = gmNetworkTools.unzip_data_pack(filename = loinc_zip)

	# split master data file
	data_fname, license_fname = gmLOINC.split_LOINCDBTXT(input_fname = os.path.join(loinc_dir, 'LOINCDB.TXT'))

	wx.EndBusyCursor()

	conn = gmAuthWidgets.get_dbowner_connection(procedure = _('importing LOINC reference data'))
	if conn is None:
		return False

	wx.BeginBusyCursor()

	# import data
	if gmLOINC.loinc_import(data_fname = data_fname, license_fname = license_fname, conn = conn):
		gmDispatcher.send(signal = 'statustext', msg = _('Successfully imported LOINC reference data.'))
	else:
		gmDispatcher.send(signal = 'statustext', msg = _('Importing LOINC reference data failed.'), beep = True)

	wx.EndBusyCursor()
	return True
Beispiel #11
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 = u""
        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"], u"", u"\n%s\n"),
            gmTools.coalesce(msg["data"], u"", u"\n%s\n"),
            pat["description_gender"],
            msg["modified_by"],
        )
        gmGuiHelpers.gm_show_warning(aTitle=_("Clinical reminder"), aMessage=txt)

        # dynamic hints
    hint_dlg = cDynamicHintDlg(wx.GetApp().GetTopWindow(), -1)
    for hint in pat._get_dynamic_hints(include_suppressed_needing_invalidation=True):
        if hint["rationale4suppression"] == u"magic_tag::please_invalidate_suppression":
            _log.debug("database asks for invalidation of suppression of hint [%s]", hint)
            hint.invalidate_suppression(pk_encounter=pat.emr.current_encounter["pk_encounter"])
            continue
        hint_dlg.hint = hint
        if hint_dlg.ShowModal() == wx.ID_APPLY:
            hint.suppress(rationale=hint_dlg.rationale.strip(), pk_encounter=pat.emr.current_encounter["pk_encounter"])
    hint_dlg.Destroy()

    return
Beispiel #12
0
def regenerate_generic_vaccines():

	dbo_conn = gmAuthWidgets.get_dbowner_connection(procedure = _('Regenerating generic vaccines'))
	if dbo_conn is None:
		return False

	wx.BeginBusyCursor()
	_cfg = gmCfg2.gmCfgData()
	sql_script = gmVaccination.write_generic_vaccine_sql (
		'client-%s' % _cfg.get(option = 'client_version'),
		include_indications_mapping = False
	)
	_log.debug('regenerating generic vaccines, SQL script: %s', sql_script)
	if not gmPG2.run_sql_script(sql_script, conn = dbo_conn):
		wx.EndBusyCursor()
		gmGuiHelpers.gm_show_warning (
			aMessage = _('Error regenerating generic vaccines.\n\nSee [%s]') % sql_script,
			aTitle = _('Regenerating generic vaccines')
		)
		return False

	gmDispatcher.send(signal = 'statustext', msg = _('Successfully regenerated generic vaccines ...'), beep = False)
	wx.EndBusyCursor()
	return True
Beispiel #13
0
def regenerate_generic_vaccines():

	dbo_conn = gmAuthWidgets.get_dbowner_connection(procedure = _('Regenerating generic vaccines'))
	if dbo_conn is None:
		return False

	wx.BeginBusyCursor()
	_cfg = gmCfg2.gmCfgData()
	sql_script = gmVaccination.write_generic_vaccine_sql (
		'client-%s' % _cfg.get(option = 'client_version'),
		include_indications_mapping = False
	)
	_log.debug('regenerating generic vaccines, SQL script: %s', sql_script)
	if not gmPG2.run_sql_script(sql_script, conn = dbo_conn):
		wx.EndBusyCursor()
		gmGuiHelpers.gm_show_warning (
			aMessage = _('Error regenerating generic vaccines.\n\nSee [%s]') % sql_script,
			aTitle = _('Regenerating generic vaccines')
		)
		return False

	gmDispatcher.send(signal = 'statustext', msg = _('Successfully regenerated generic vaccines ...'), beep = False)
	wx.EndBusyCursor()
	return True
Beispiel #14
0
def connect_to_database(max_attempts=3,
                        expected_version=None,
                        require_version=True):
    """Display the login dialog and try to log into the backend.

	- up to max_attempts times
	- returns True/False
	"""
    # force programmer to set a valid expected_version
    expected_hash = gmPG2.known_schema_hashes[expected_version]
    client_version = _cfg.get(option='client_version')
    global current_db_name
    current_db_name = 'gnumed_v%s' % expected_version

    attempt = 0

    dlg = cLoginDialog(None, -1, client_version=client_version)
    dlg.Centre(wx.BOTH)

    while attempt < max_attempts:

        _log.debug('login attempt %s of %s', (attempt + 1), max_attempts)

        connected = False

        dlg.ShowModal()
        login = dlg.panel.GetLoginInfo()
        if login is None:
            _log.info("user cancelled login dialog")
            break

        gmLog2.add_word2hide(login.password)

        # try getting a connection to verify the DSN works
        dsn = gmPG2.make_psycopg2_dsn(database=login.database,
                                      host=login.host,
                                      port=login.port,
                                      user=login.user,
                                      password=login.password)
        try:
            conn = gmPG2.get_raw_connection(dsn=dsn,
                                            verbose=True,
                                            readonly=True)
            connected = True

        except gmPG2.cAuthenticationError as e:
            attempt += 1
            _log.error("login attempt failed: %s", e)
            if attempt < max_attempts:
                if ('host=127.0.0.1' in ('%s' % e)) or ('host='
                                                        not in ('%s' % e)):
                    msg = _(
                        'Unable to connect to database:\n\n'
                        '%s\n\n'
                        "Are you sure you have got a local database installed ?\n"
                        '\n'
                        "Please retry with proper credentials or cancel.\n"
                        '\n'
                        ' (for the public and any new GNUmed data-\n'
                        '  bases the default user name and password\n'
                        '  are {any-doc, any-doc})\n'
                        '\n'
                        'You may also need to check the PostgreSQL client\n'
                        'authentication configuration in pg_hba.conf. For\n'
                        'details see:\n'
                        '\n'
                        'wiki.gnumed.de/bin/view/Gnumed/ConfigurePostgreSQL')
                else:
                    msg = _(
                        "Unable to connect to database:\n\n"
                        "%s\n\n"
                        "Please retry with proper credentials or cancel.\n"
                        "\n"
                        "For the public and any new GNUmed databases the\n"
                        "default user name and password are {any-doc, any-doc}.\n"
                        "\n"
                        'You may also need to check the PostgreSQL client\n'
                        'authentication configuration in pg_hba.conf. For\n'
                        'details see:\n'
                        '\n'
                        'wiki.gnumed.de/bin/view/Gnumed/ConfigurePostgreSQL')
                msg = msg % e
                msg = regex.sub(
                    r'password=[^\s]+',
                    'password=%s' % gmTools.u_replacement_character, msg)
                gmGuiHelpers.gm_show_error(msg, _('Connecting to backend'))
            del e
            continue

        except gmPG2.dbapi.OperationalError as exc:
            _log.exception('login attempt failed')
            gmPG2.log_pg_exception_details(exc)
            msg = _(
                "Unable to connect to database:\n\n"
                "%s\n\n"
                "Please retry another backend / user / password combination !\n"
                "\n"
                " (for the public and any new GNUmed databases\n"
                "  the default user name and password are\n"
                "  {any-doc, any-doc})\n"
                "\n") % exc
            msg = regex.sub(r'password=[^\s]+',
                            'password=%s' % gmTools.u_replacement_character,
                            msg)
            gmGuiHelpers.gm_show_error(msg, _('Connecting to backend'))
            del exc
            continue

        conn.close()

        # connect was successful
        gmPG2.set_default_login(login=login)
        gmPG2.set_default_client_encoding(
            encoding=dlg.panel.backend_profile.encoding)

        seems_bootstrapped = gmPG2.schema_exists(schema='gm')
        if not seems_bootstrapped:
            _log.error(
                'schema [gm] does not exist - database not bootstrapped ?')
            msg = _('The database you connected to does not seem\n'
                    'to have been boostrapped properly.\n'
                    '\n'
                    'Make sure you have run the GNUmed database\n'
                    'bootstrapper tool to create a new database.\n'
                    '\n'
                    'Further help can be found on the website at\n'
                    '\n'
                    '  http://wiki.gnumed.de\n'
                    '\n'
                    'or on the GNUmed mailing list.')
            gmGuiHelpers.gm_show_error(msg, _('Verifying database'))
            connected = False
            break

        compatible = gmPG2.database_schema_compatible(version=expected_version)
        if compatible or not require_version:
            dlg.panel.save_state()

        if not compatible:
            connected_db_version = gmPG2.get_schema_version()
            msg = msg_generic % (client_version, connected_db_version,
                                 expected_version,
                                 gmTools.coalesce(login.host, '<localhost>'),
                                 login.database, login.user)
            if require_version:
                gmGuiHelpers.gm_show_error(msg + msg_fail,
                                           _('Verifying database version'))
                connected = False
                continue
            gmGuiHelpers.gm_show_info(msg + msg_override,
                                      _('Verifying database version'))

        # FIXME: make configurable
        max_skew = 1  # minutes
        if _cfg.get(option='debug'):
            max_skew = 10
        if not gmPG2.sanity_check_time_skew(tolerance=(max_skew * 60)):
            if _cfg.get(option='debug'):
                gmGuiHelpers.gm_show_warning(msg_time_skew_warn % max_skew,
                                             _('Verifying database settings'))
            else:
                gmGuiHelpers.gm_show_error(msg_time_skew_fail % max_skew,
                                           _('Verifying database settings'))
                connected = False
                continue

        sanity_level, message = gmPG2.sanity_check_database_settings()
        if sanity_level != 0:
            gmGuiHelpers.gm_show_error((msg_insanity % message),
                                       _('Verifying database settings'))
            if sanity_level == 2:
                connected = False
                continue

        gmExceptionHandlingWidgets.set_is_public_database(login.public_db)
        gmExceptionHandlingWidgets.set_helpdesk(login.helpdesk)

        conn = gmPG2.get_connection(
            verbose=True,
            connection_name='GNUmed-[DbListenerThread]',
            pooled=False)
        listener = gmBackendListener.gmBackendListener(conn=conn)
        break

    dlg.DestroyLater()

    return connected
Beispiel #15
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
Beispiel #16
0
def connect_to_database(max_attempts=3, expected_version=None, require_version=True):
	"""Display the login dialog and try to log into the backend.

	- up to max_attempts times
	- returns True/False
	"""
	# force programmer to set a valid expected_version
	expected_hash = gmPG2.known_schema_hashes[expected_version]
	client_version = _cfg.get(option = 'client_version')
	global current_db_name
	current_db_name = 'gnumed_v%s' % expected_version

	attempt = 0

	dlg = cLoginDialog(None, -1, client_version = client_version)
	dlg.Centre(wx.BOTH)

	while attempt < max_attempts:

		_log.debug('login attempt %s of %s', (attempt+1), max_attempts)

		connected = False

		dlg.ShowModal()
		login = dlg.panel.GetLoginInfo()
		if login is None:
			_log.info("user cancelled login dialog")
			break

		gmLog2.add_word2hide(login.password)

		# try getting a connection to verify the DSN works
		dsn = gmPG2.make_psycopg2_dsn (
			database = login.database,
			host = login.host,
			port = login.port,
			user = login.user,
			password = login.password
		)
		try:
			conn = gmPG2.get_raw_connection(dsn = dsn, verbose = True, readonly = True)
			connected = True

		except gmPG2.cAuthenticationError as e:
			attempt += 1
			_log.error("login attempt failed: %s", e)
			if attempt < max_attempts:
				if ('host=127.0.0.1' in ('%s' % e)) or ('host=' not in ('%s' % e)):
					msg = _(
						'Unable to connect to database:\n\n'
						'%s\n\n'
						"Are you sure you have got a local database installed ?\n"
						'\n'
						"Please retry with proper credentials or cancel.\n"
						'\n'
						' (for the public and any new GNUmed data-\n'
						'  bases the default user name and password\n'
						'  are {any-doc, any-doc})\n'
						'\n'
						'You may also need to check the PostgreSQL client\n'
						'authentication configuration in pg_hba.conf. For\n'
						'details see:\n'
						'\n'
						'wiki.gnumed.de/bin/view/Gnumed/ConfigurePostgreSQL'
					)
				else:
					msg = _(
						"Unable to connect to database:\n\n"
						"%s\n\n"
						"Please retry with proper credentials or cancel.\n"
						"\n"
						"For the public and any new GNUmed databases the\n"
						"default user name and password are {any-doc, any-doc}.\n"
						"\n"
						'You may also need to check the PostgreSQL client\n'
						'authentication configuration in pg_hba.conf. For\n'
						'details see:\n'
						'\n'
						'wiki.gnumed.de/bin/view/Gnumed/ConfigurePostgreSQL'
					)
				msg = msg % e
				msg = regex.sub(r'password=[^\s]+', 'password=%s' % gmTools.u_replacement_character, msg)
				gmGuiHelpers.gm_show_error (
					msg,
					_('Connecting to backend')
				)
			del e
			continue

		except gmPG2.dbapi.OperationalError as exc:
			_log.exception('login attempt failed')
			gmPG2.log_pg_exception_details(exc)
			msg = _(
				"Unable to connect to database:\n\n"
				"%s\n\n"
				"Please retry another backend / user / password combination !\n"
				"\n"
				" (for the public and any new GNUmed databases\n"
				"  the default user name and password are\n"
				"  {any-doc, any-doc})\n"
				"\n"
			) % exc
			msg = regex.sub(r'password=[^\s]+', 'password=%s' % gmTools.u_replacement_character, msg)
			gmGuiHelpers.gm_show_error(msg, _('Connecting to backend'))
			del exc
			continue

		conn.close()

		# connect was successful
		gmPG2.set_default_login(login = login)
		gmPG2.set_default_client_encoding(encoding = dlg.panel.backend_profile.encoding)

		seems_bootstrapped = gmPG2.schema_exists(schema = 'gm')
		if not seems_bootstrapped:
			_log.error('schema [gm] does not exist - database not bootstrapped ?')
			msg = _(
				'The database you connected to does not seem\n'
				'to have been boostrapped properly.\n'
				'\n'
				'Make sure you have run the GNUmed database\n'
				'bootstrapper tool to create a new database.\n'
				'\n'
				'Further help can be found on the website at\n'
				'\n'
				'  http://wiki.gnumed.de\n'
				'\n'
				'or on the GNUmed mailing list.'
			)
			gmGuiHelpers.gm_show_error(msg, _('Verifying database'))
			connected = False
			break

		compatible = gmPG2.database_schema_compatible(version = expected_version)
		if compatible or not require_version:
			dlg.panel.save_state()

		if not compatible:
			connected_db_version = gmPG2.get_schema_version()
			msg = msg_generic % (
				client_version,
				connected_db_version,
				expected_version,
				gmTools.coalesce(login.host, '<localhost>'),
				login.database,
				login.user
			)
			if require_version:
				gmGuiHelpers.gm_show_error(msg + msg_fail, _('Verifying database version'))
				connected = False
				continue
			gmGuiHelpers.gm_show_info(msg + msg_override, _('Verifying database version'))

		# FIXME: make configurable
		max_skew = 1		# minutes
		if _cfg.get(option = 'debug'):
			max_skew = 10
		if not gmPG2.sanity_check_time_skew(tolerance = (max_skew * 60)):
			if _cfg.get(option = 'debug'):
				gmGuiHelpers.gm_show_warning(msg_time_skew_warn % max_skew, _('Verifying database settings'))
			else:
				gmGuiHelpers.gm_show_error(msg_time_skew_fail % max_skew, _('Verifying database settings'))
				connected = False
				continue

		sanity_level, message = gmPG2.sanity_check_database_settings()
		if sanity_level != 0:
			gmGuiHelpers.gm_show_error((msg_insanity % message), _('Verifying database settings'))
			if sanity_level == 2:
				connected = False
				continue

		gmExceptionHandlingWidgets.set_is_public_database(login.public_db)
		gmExceptionHandlingWidgets.set_helpdesk(login.helpdesk)

		conn = gmPG2.get_connection(verbose = True, connection_name = 'GNUmed-[DbListenerThread]', pooled = False)
		listener = gmBackendListener.gmBackendListener(conn = conn)
		break

	dlg.DestroyLater()

	return connected
	def __create_new_episode(self, emr=None, episode_name_candidates=None):

		episode_name_candidates.append(self._TCTRL_episode_summary.GetValue().strip())
		for candidate in episode_name_candidates:
			if candidate is None:
				continue
			epi_name = candidate.strip().replace('\r', '//').replace('\n', '//')
			break

		if self.problem is None:
			msg = _(
				'Enter a short working name for this new problem\n'
				'(which will become a new, unassociated episode):\n'
			)
		else:
			issue = emr.problem2issue(self.problem)
			msg = _(
				'Enter a short working name for this new\n'
				'episode under the existing health issue\n'
				'\n'
				'"%s":\n'
			) % issue['description']

		dlg = wx.TextEntryDialog (
			self, msg,
			caption = _('Creating problem (episode) to save notelet under ...'),
			value = epi_name,
			style = wx.OK | wx.CANCEL | wx.CENTRE
		)
		decision = dlg.ShowModal()
		if decision != wx.ID_OK:
			return None

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

		# create episode
		new_episode = emr.add_episode (
			episode_name = epi_name[:45],
			pk_health_issue = None,
			is_open = True,
			allow_dupes = True		# this ensures we get a new episode even if a same-name one already exists
		)
		new_episode['summary'] = self._TCTRL_episode_summary.GetValue().strip()
		new_episode.save()

		if self.problem is not None:
			issue = emr.problem2issue(self.problem)
			if not gmEMRStructWidgets.move_episode_to_issue(episode = new_episode, target_issue = issue, save_to_backend = True):
				gmGuiHelpers.gm_show_warning (
					_(
						'The new episode:\n'
						'\n'
						' "%s"\n'
						'\n'
						'will remain unassociated despite the editor\n'
						'having been invoked from the health issue:\n'
						'\n'
						' "%s"'
					) % (
						new_episode['description'],
						issue['description']
					),
					_('saving progress note')
				)

		return new_episode
Beispiel #18
0
                login.database,
                login.user,
            )
            if require_version:
                gmGuiHelpers.gm_show_error(msg + msg_fail, _("Verifying database version"))
                connected = False
                continue
            gmGuiHelpers.gm_show_info(msg + msg_override, _("Verifying database version"))

            # FIXME: make configurable
        max_skew = 1  # minutes
        if _cfg.get(option="debug"):
            max_skew = 10
        if not gmPG2.sanity_check_time_skew(tolerance=(max_skew * 60)):
            if _cfg.get(option="debug"):
                gmGuiHelpers.gm_show_warning(msg_time_skew_warn % max_skew, _("Verifying database settings"))
            else:
                gmGuiHelpers.gm_show_error(msg_time_skew_fail % max_skew, _("Verifying database settings"))
                connected = False
                continue

        sanity_level, message = gmPG2.sanity_check_database_settings()
        if sanity_level != 0:
            gmGuiHelpers.gm_show_error((msg_insanity % message), _("Verifying database settings"))
            if sanity_level == 2:
                connected = False
                continue

        gmExceptionHandlingWidgets.set_is_public_database(login.public_db)
        gmExceptionHandlingWidgets.set_helpdesk(login.helpdesk)