コード例 #1
0
ファイル: gmStaffWidgets.py プロジェクト: ncqgm/gnumed
	def _on_save_button_pressed(self, event):
		pk_staff = self._LCTRL_staff.GetItemData(self._LCTRL_staff.GetFirstSelected())

		conn = gmAuthWidgets.get_dbowner_connection(procedure = _('Modifying GNUmed user.'))
		if conn is None:
			return False

		staff = gmStaff.cStaff(aPK_obj = pk_staff)
		staff['short_alias'] = self._TCTRL_alias.GetValue()
		staff['db_user'] = self._TCTRL_account.GetValue()
		staff['comment'] = self._TCTRL_comment.GetValue()
		success, data = staff.save_payload(conn = conn)
		if not success:
			conn.close()
			gmGuiHelpers.gm_show_error (
				aMessage = _('Failed to save changes to GNUmed database user.'),
				aTitle = _('Modifying GNUmed user')
			)
			return False

		target_role = self._PRW_user_role.GetData()
		if target_role is not None:
			if not staff.set_role(conn = conn, role = target_role):
				gmGuiHelpers.gm_show_error (
					aMessage = _('Failed to set role [%s] for GNUmed database user.') % self._PRW_user_role.GetValue().strip(),
					aTitle = _('Modifying GNUmed user')
				)

		conn.close()
		self.__init_ui_data()
		return True
コード例 #2
0
ファイル: gmProviderInboxWidgets.py プロジェクト: sk/gnumed
	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
コード例 #3
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
コード例 #4
0
def __handle_access_violation(t, v, tb):

	if t != gmExceptions.AccessDenied:
		return False

	_log.error('access permissions violation detected')
	wx.EndBusyCursor()
	gmLog2.flush()
	txt = ' ' + v.errmsg
	if v.source is not None:
		txt += _('\n Source: %s') % v.source
	if v.code is not None:
		txt += _('\n Code: %s') % v.code
	if v.details is not None:
		txt += _('\n Details (first 250 characters):\n%s\n%s\n%s') % (
			u_box_horiz_single * 50,
			v.details[:250],
			u_box_horiz_single * 50
		)
	gmGuiHelpers.gm_show_error (
		aTitle = _('Access violation'),
		aMessage = _(
			'You do not have access to this part of GNUmed.\n'
			'\n'
			'%s'
		) % txt
	)
	return True
コード例 #5
0
    def __get_lab_panel(self):
        # get panel to use
        dbcfg = gmCfg.cCfgSQL()
        pk_panel = dbcfg.get2(
            option=u'horstspace.top_panel.lab_panel',
            workplace=gmPraxis.gmCurrentPraxisBranch().active_workplace,
            bias='user')
        if pk_panel is None:
            return None

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

        _log.error(
            'Cannot load test panel [#%s] configured for patient pane (horstspace.top_panel.lab_panel).',
            pk_panel)
        gmGuiHelpers.gm_show_error(
            title=_('GNUmed startup'),
            error=_('Cannot load test panel [#%s] configured\n'
                    'for the top pane with option\n'
                    '\n'
                    ' <horstspace.top_panel.lab_panel>\n'
                    '\n'
                    'Please reconfigure.') % pk_panel)
        return None
コード例 #6
0
ファイル: gmNarrativeWidgets.py プロジェクト: weeksjm/gnumed
	def _on_problem_activated(self, event):
		"""Open progress note editor for this problem.
		"""
		problem = self._LCTRL_active_problems.get_selected_item_data(only_one = True)
		if problem is None:
			return True

		dbcfg = gmCfg.cCfgSQL()
		allow_duplicate_editors = bool(dbcfg.get2 (
			option = 'horstspace.soap_editor.allow_same_episode_multiple_times',
			workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
			bias = 'user',
			default = False
		))
		if self._PNL_editors.add_editor(problem = problem, allow_same_problem = allow_duplicate_editors):
			return True

		gmGuiHelpers.gm_show_error (
			aMessage = _(
				'Cannot open progress note editor for\n\n'
				'[%s].\n\n'
			) % problem['problem'],
			aTitle = _('opening progress note editor')
		)
		return False
コード例 #7
0
ファイル: gmProviderInboxWidgets.py プロジェクト: sk/gnumed
	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
コード例 #8
0
ファイル: gmProviderInboxWidgets.py プロジェクト: sk/gnumed
	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
コード例 #9
0
ファイル: gmXdtViewer.py プロジェクト: ncqgm/gnumed
		def OnInit (self):

			fname = ""
			# has the user manually supplied a config file on the command line ?
			fname = cfg.get(option = '--xdt-file', source_order = [('cli', 'return')])
			if fname is not None:
				_log.debug('XDT file is [%s]' % fname)
				# file valid ?
				if not os.access(fname, os.R_OK):
					title = _('Opening xDT file')
					msg = _('Cannot open xDT file.\n'
							'[%s]') % fname
					gmGuiHelpers.gm_show_error(msg, title)
					return False
			else:
				title = _('Opening xDT file')
				msg = _('You must provide an xDT file on the command line.\n'
						'Format: --xdt-file=<file>')
				gmGuiHelpers.gm_show_error(msg, title)
				return False

			frame = wx.Frame(
				parent = None,
				id = -1,
				title = _("XDT Viewer"),
				size = wx.Size(800,600)
			)
			pnl = gmXdtViewerPanel(frame, fname)
			pnl.Populate()
			frame.Show(1)
			return True
コード例 #10
0
	def __export_as_files(self, msg_title, base_dir=None, encrypt=False, with_metadata=False, items=None):
		# get password
		data_pwd = None
		if encrypt:
			data_pwd = self.__get_password(msg_title)
			if data_pwd is None:
				_log.debug('user aborted by not providing the same password twice')
				gmDispatcher.send(signal = 'statustext', msg = _('Password not provided twice. Aborting.'))
				return None
		# save
		wx.BeginBusyCursor()
		try:
			exp_area = gmPerson.gmCurrentPatient().export_area
			if with_metadata:
				export_dir = exp_area.export(base_dir = base_dir, items = items, passphrase = data_pwd)
			else:
				export_dir = exp_area.dump_items_to_disk(base_dir = base_dir, items = items, passphrase = data_pwd)
		finally:
			wx.EndBusyCursor()
		if export_dir is None:
			gmGuiHelpers.gm_show_error (
				aMessage = _('Error exporting entries.'),
				aTitle = msg_title
			)
			return None

		return export_dir
コード例 #11
0
	def _on_mail_items_button_pressed(self, event):
		event.Skip()

		_log.debug('gm-mail_doc(.bat) API: "MAIL-PROGRAM PRAXIS-VCF ZIP-ARCHIVE"')

		found, external_cmd = gmShellAPI.detect_external_binary('gm-mail_doc')
		if not found:
			gmDispatcher.send(signal = 'statustext', msg = _('Cannot send e-mail: <gm-mail_doc(.bat)> not found'))
			return False

		zip_file = self.__export_as_zip (
			_('Mailing documents as zip archive'),
			encrypt = True
		)
		if zip_file is None:
			gmDispatcher.send(signal = 'statustext', msg = _('Cannot send e-mail: no archive created.'))
			return False

		prax = gmPraxis.gmCurrentPraxisBranch()
		args = [external_cmd, prax.vcf, zip_file]
		success, ret_code, stdout = gmShellAPI.run_process(cmd_line = args, verbose = _cfg.get(option = 'debug'))
		if not success:
			gmGuiHelpers.gm_show_error (
				aMessage = _('Error mailing documents.'),
				aTitle = _('Mailing documents')
			)
			return False

		self.__save_soap_note(soap = _('Mailed:\n - %s') % '\n - '.join([ i['description'] for i in items ]))
		return True
コード例 #12
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
コード例 #13
0
ファイル: gmStaffWidgets.py プロジェクト: weeksjm/gnumed
    def _on_save_button_pressed(self, event):
        pk_staff = self._LCTRL_staff.GetItemData(
            self._LCTRL_staff.GetFirstSelected())

        conn = gmAuthWidgets.get_dbowner_connection(
            procedure=_('Modifying GNUmed user.'))
        if conn is None:
            return False

        staff = gmStaff.cStaff(aPK_obj=pk_staff)
        staff['short_alias'] = self._TCTRL_alias.GetValue()
        staff['db_user'] = self._TCTRL_account.GetValue()
        staff['comment'] = self._TCTRL_comment.GetValue()
        success, data = staff.save_payload(conn=conn)
        if not success:
            conn.close()
            gmGuiHelpers.gm_show_error(
                aMessage=_('Failed to save changes to GNUmed database user.'),
                aTitle=_('Modifying GNUmed user'))
            return False

        target_role = self._PRW_user_role.GetData()
        if target_role is not None:
            if not staff.set_role(conn=conn, role=target_role):
                gmGuiHelpers.gm_show_error(
                    aMessage=_(
                        'Failed to set role [%s] for GNUmed database user.') %
                    self._PRW_user_role.GetValue().strip(),
                    aTitle=_('Modifying GNUmed user'))

        conn.close()
        self.__init_ui_data()
        return True
コード例 #14
0
ファイル: gmNarrativeWidgets.py プロジェクト: ncqgm/gnumed
	def _on_problem_activated(self, event):
		"""Open progress note editor for this problem.
		"""
		problem = self._LCTRL_active_problems.get_selected_item_data(only_one = True)
		if problem is None:
			return True

		dbcfg = gmCfg.cCfgSQL()
		allow_duplicate_editors = bool(dbcfg.get2 (
			option = 'horstspace.soap_editor.allow_same_episode_multiple_times',
			workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
			bias = 'user',
			default = False
		))
		if self._PNL_editors.add_editor(problem = problem, allow_same_problem = allow_duplicate_editors):
			return True

		gmGuiHelpers.gm_show_error (
			aMessage = _(
				'Cannot open progress note editor for\n\n'
				'[%s].\n\n'
			) % problem['problem'],
			aTitle = _('opening progress note editor')
		)
		return False
コード例 #15
0
def __handle_import_error(t, v, tb):

	if t == OSError:
		if not hasattr(t, 'winerror'):
			return False
		if getattr(t, 'winerror') != 126:
			return False
	else:
		if t != ImportError:
			return False

	wx.EndBusyCursor()

	_log.error('module [%s] not installed', v)
	gmGuiHelpers.gm_show_error (
		aTitle = _('Missing GNUmed module'),
		aMessage = _(
			'GNUmed detected that parts of it are not\n'
			'properly installed. The following message\n'
			'names the missing part:\n'
			'\n'
			' "%s"\n'
			'\n'
			'Please make sure to get the missing\n'
			'parts installed. Otherwise some of the\n'
			'functionality will not be accessible.'
		) % v
	)
	return True
コード例 #16
0
def __handle_import_error(t, v, tb):

    if t == OSError:
        if not hasattr(t, 'winerror'):
            return False
        if getattr(t, 'winerror') != 126:
            return False
    else:
        if t != ImportError:
            return False

    wx.EndBusyCursor()

    _log.error('module [%s] not installed', v)
    gmGuiHelpers.gm_show_error(
        aTitle=_('Missing GNUmed module'),
        aMessage=_('GNUmed detected that parts of it are not\n'
                   'properly installed. The following message\n'
                   'names the missing part:\n'
                   '\n'
                   ' "%s"\n'
                   '\n'
                   'Please make sure to get the missing\n'
                   'parts installed. Otherwise some of the\n'
                   'functionality will not be accessible.') % v)
    return True
コード例 #17
0
ファイル: gmXdtViewer.py プロジェクト: jeromecc/gnumed
        def OnInit(self):

            fname = ""
            # has the user manually supplied a config file on the command line ?
            fname = cfg.get(option='--xdt-file',
                            source_order=[('cli', 'return')])
            if fname is not None:
                _log.debug('XDT file is [%s]' % fname)
                # file valid ?
                if not os.access(fname, os.R_OK):
                    title = _('Opening xDT file')
                    msg = _('Cannot open xDT file.\n' '[%s]') % fname
                    gmGuiHelpers.gm_show_error(msg, title)
                    return False
            else:
                title = _('Opening xDT file')
                msg = _('You must provide an xDT file on the command line.\n'
                        'Format: --xdt-file=<file>')
                gmGuiHelpers.gm_show_error(msg, title)
                return False

            frame = wx.Frame(parent=None,
                             id=-1,
                             title=_("XDT Viewer"),
                             size=wx.Size(800, 600))
            pnl = gmXdtViewerPanel(frame, fname)
            pnl.Populate()
            frame.Show(1)
            return True
コード例 #18
0
	def _drop_target_consume_filenames(self, filenames):
		pat = gmPerson.gmCurrentPatient()
		if not pat.connected:
			gmDispatcher.send(signal = 'statustext', msg = _('Cannot accept new documents. No active patient.'))
			return

		# dive into folders dropped onto us and extract files (one level deep only)
		real_filenames = []
		for pathname in filenames:
			try:
				files = os.listdir(pathname)
				gmDispatcher.send(signal='statustext', msg=_('Extracting files from folder [%s] ...') % pathname)
				for file in files:
					fullname = os.path.join(pathname, file)
					if not os.path.isfile(fullname):
						continue
					real_filenames.append(fullname)
			except OSError:
				real_filenames.append(pathname)

		if not pat.export_area.add_files(real_filenames, hint = _('Drag&Drop')):
			gmGuiHelpers.gm_show_error (
				title = _('Adding files to export area'),
				error = _('Cannot add (some of) the following files to the export area:\n%s ') % '\n '.join(real_filenames)
			)
コード例 #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 _on_AcquirePhoto(self, event):

        # get from image source
        from Gnumed.pycommon import gmScanBackend

        try:
            fnames = gmScanBackend.acquire_pages_into_files(
                delay=5, calling_window=self)
        except OSError:
            _log.exception('problem acquiring image from source')
            gmGuiHelpers.gm_show_error(aMessage=_(
                'No image could be acquired from the source.\n\n'
                'This may mean the scanner driver is not properly installed.\n\n'
                'On Windows you must install the TWAIN Python module\n'
                'while on Linux and MacOSX it is recommended to install\n'
                'the XSane package.'),
                                       aTitle=_('Acquiring photo'))
            return

        if fnames is False:
            gmGuiHelpers.gm_show_error(
                aMessage=_('Patient photo could not be acquired from source.'),
                aTitle=_('Acquiring photo'))
            return

        if len(fnames) == 0:  # no pages scanned
            return

        self.__import_pic_into_db(fname=fnames[0])
        self.__reload_photo()
コード例 #21
0
    def _on_mail_items_button_pressed(self, event):
        event.Skip()

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

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

        files2mail = []
        for item in items:
            files2mail.append(item.save_to_file())

        cmd = '%s %s' % (external_cmd, ' '.join(files2mail))
        if os.name == 'nt':
            blocking = True
        else:
            blocking = False
        success = gmShellAPI.run_command_in_shell(command=cmd,
                                                  blocking=blocking)
        if not success:
            gmGuiHelpers.gm_show_error(aMessage=_('Error mailing documents.'),
                                       aTitle=_('Mailing documents'))
            return False

        self.save_soap_note(soap=_('Mailed:\n - %s') %
                            '\n - '.join([i['description'] for i in items]))
        return True
コード例 #22
0
def __handle_access_violation(t, v, tb):

	if t != gmExceptions.AccessDenied:
		return False

	_log2.error('access permissions violation detected')
	wx.EndBusyCursor()
	gmLog2.flush()
	txt = u' ' + v.errmsg
	if v.source is not None:
		txt += _('\n Source: %s') % v.source
	if v.code is not None:
		txt += _('\n Code: %s') % v.code
	if v.details is not None:
		txt += _('\n Details (first 250 characters):\n%s\n%s\n%s') % (
			u_box_horiz_single * 50,
			v.details[:250],
			u_box_horiz_single * 50
		)
	gmGuiHelpers.gm_show_error (
		aTitle = _('Access violation'),
		aMessage = _(
			'You do not have access to this part of GNUmed.\n'
			'\n'
			'%s'
		) % txt
	)
	return True
コード例 #23
0
ファイル: gmFormWidgets.py プロジェクト: ncqgm/gnumed
def generate_form_from_template(parent=None, template_types=None, edit=None, template=None, excluded_template_types=None):
	"""If <edit> is None it will honor the template setting."""

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

	# 1) get template to use
	if template is None:
		template = manage_form_templates (
			parent = parent,
			active_only = True,
			template_types = template_types,
			excluded_types = excluded_template_types
		)
		if template is None:
			gmDispatcher.send(signal = 'statustext', msg = _('No document template selected.'), beep = False)
			return None

	if template['engine'] == 'O':
		return print_doc_from_ooo_template(template = template)

	wx.BeginBusyCursor()

	# 2) process template
	try:
		form = template.instantiate()
	except KeyError:
		_log.exception('cannot instantiate document template [%s]', template)
		gmGuiHelpers.gm_show_error (
			aMessage = _('Invalid document template [%s - %s (%s)]') % (name, ver, template['engine']),
			aTitle = _('Generating document from template')
		)
		wx.EndBusyCursor()
		return None
	ph = gmMacro.gmPlaceholderHandler()
	#ph.debug = True
	form.substitute_placeholders(data_source = ph)
	if edit is None:
		if form.template['edit_after_substitution']:
			edit = True
		else:
			edit = False
	if edit:
		wx.EndBusyCursor()
		form.edit()
		wx.BeginBusyCursor()

	# 3) generate output
	pdf_name = form.generate_output()
	wx.EndBusyCursor()
	if pdf_name is not None:
		return form

	gmGuiHelpers.gm_show_error (
		aMessage = _('Error generating document printout.'),
		aTitle = _('Generating document printout')
	)
	return None
コード例 #24
0
ファイル: gmPraxisWidgets.py プロジェクト: jeromecc/gnumed
    def edit_old(workplace=None):

        available_plugins = gmPlugin.get_installed_plugins(plugin_dir='gui')

        dbcfg = gmCfg.cCfgSQL()

        if workplace is None:
            dlg = wx.TextEntryDialog(
                parent=parent,
                message=_('Enter a descriptive name for the new workplace:'),
                caption=_('Configuring GNUmed workplaces ...'),
                defaultValue=u'',
                style=wx.OK | wx.CENTRE)
            dlg.ShowModal()
            workplace = dlg.GetValue().strip()
            if workplace == u'':
                gmGuiHelpers.gm_show_error(
                    _('Cannot save a new workplace without a name.'),
                    _('Configuring GNUmed workplaces ...'))
                return False
            curr_plugins = []
            choices = available_plugins
        else:
            curr_plugins = gmTools.coalesce(
                dbcfg.get2(option=u'horstspace.notebook.plugin_load_order',
                           workplace=workplace,
                           bias='workplace'), [])
            choices = curr_plugins[:]
            for p in available_plugins:
                if p not in choices:
                    choices.append(p)

        sels = range(len(curr_plugins))
        new_plugins = gmListWidgets.get_choices_from_list(
            parent=parent,
            msg=_('\n'
                  'Select the plugin(s) to be loaded the next time\n'
                  'the client is restarted under the workplace:\n'
                  '\n'
                  ' [%s]'
                  '\n') % workplace,
            caption=_('Configuring GNUmed workplaces ...'),
            choices=choices,
            selections=sels,
            columns=[_('Plugins')],
            single_selection=False)

        if new_plugins == curr_plugins:
            return True

        if new_plugins is None:
            return True

        dbcfg.set(option=u'horstspace.notebook.plugin_load_order',
                  value=new_plugins,
                  workplace=workplace)

        return True
コード例 #25
0
def generate_form_from_template(parent=None, template_types=None, edit=None, template=None, excluded_template_types=None):
	"""If <edit> is None it will honor the template setting."""

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

	# 1) get template to use
	if template is None:
		template = manage_form_templates (
			parent = parent,
			active_only = True,
			template_types = template_types,
			excluded_types = excluded_template_types
		)
		if template is None:
			gmDispatcher.send(signal = 'statustext', msg = _('No document template selected.'), beep = False)
			return None

	if template['engine'] == 'O':
		return print_doc_from_ooo_template(template = template)

	wx.BeginBusyCursor()

	# 2) process template
	try:
		form = template.instantiate()
	except KeyError:
		_log.exception('cannot instantiate document template [%s]', template)
		gmGuiHelpers.gm_show_error (
			aMessage = _('Invalid document template [%s - %s (%s)]') % (template['name_long'], template['external_version'], template['engine']),
			aTitle = _('Generating document from template')
		)
		wx.EndBusyCursor()
		return None
	ph = gmMacro.gmPlaceholderHandler()
	#ph.debug = True
	form.substitute_placeholders(data_source = ph)
	if edit is None:
		if form.template['edit_after_substitution']:
			edit = True
		else:
			edit = False
	if edit:
		wx.EndBusyCursor()
		form.edit()
		wx.BeginBusyCursor()

	# 3) generate output
	pdf_name = form.generate_output()
	wx.EndBusyCursor()
	if pdf_name is not None:
		return form

	gmGuiHelpers.gm_show_error (
		aMessage = _('Error generating document printout.'),
		aTitle = _('Generating document printout')
	)
	return None
コード例 #26
0
    def __address_valid_for_save(self, empty_address_is_valid=False):

        # existing address ? if so set other fields
        if self._PRW_address_searcher.GetData() is not None:
            wx.CallAfter(self.__set_fields_from_address_searcher)
            return True

        # must either all contain something or none of them
        fields_to_fill = (self._TCTRL_number, self._PRW_zip, self._PRW_street,
                          self._PRW_urb, self._PRW_type)
        no_of_filled_fields = 0

        for field in fields_to_fill:
            if field.GetValue().strip() != '':
                no_of_filled_fields += 1
                field.display_as_valid(True)

        # empty address ?
        if no_of_filled_fields == 0:
            if empty_address_is_valid:
                return True
            else:
                return None

        # incompletely filled address ?
        if no_of_filled_fields != len(fields_to_fill):
            for field in fields_to_fill:
                if field.GetValue().strip() == '':
                    field.display_as_valid(False)
                    field.SetFocus()
            msg = _(
                'To properly create an address, all the related fields must be filled in.'
            )
            gmGuiHelpers.gm_show_error(msg, _('Required fields'))
            return False

        # fields which must contain a selected item
        # FIXME: they must also contain an *acceptable combination* which
        # FIXME: can only be tested against the database itself ...
        strict_fields = (self._PRW_type, self._PRW_region, self._PRW_country)
        error = False
        for field in strict_fields:
            if field.GetData() is None:
                error = True
                field.display_as_valid(False)
                field.SetFocus()
            else:
                field.display_as_valid(True)

        if error:
            msg = _(
                'This field must contain an item selected from the dropdown list.'
            )
            gmGuiHelpers.gm_show_error(msg, _('Required fields'))
            return False

        return True
コード例 #27
0
	def __get_password(self, msg_title):
		while True:
			data_pwd = wx.GetPasswordFromUser (
				message = _(
					'Enter passphrase to protect the data with.\n'
					'\n'
					'(minimum length: 5, trailing blanks will be stripped)'
				),
				caption = msg_title
			)
			# minimal weakness check
			data_pwd = data_pwd.rstrip()
			if len(data_pwd) > 4:
				break
			retry = gmGuiHelpers.gm_show_question (
				title = msg_title,
				question = _(
					'Insufficient passphrase.\n'
					'\n'
					'(minimum length: 5, trailing blanks will be stripped)\n'
					'\n'
					'Enter another passphrase ?'
				)
			)
			if not retry:
				# user changed her mind
				return None
		# confidentiality
		gmLog2.add_word2hide(data_pwd)
		# reget password
		while True:
			data_pwd4comparison = wx.GetPasswordFromUser (
				message = _(
					'Once more enter passphrase to protect the data with.\n'
					'\n'
					'(this will protect you from typos)\n'
					'\n'
					'Abort by leaving empty.'
				),
				caption = msg_title
			)
			data_pwd4comparison = data_pwd4comparison.rstrip()
			if data_pwd4comparison == '':
				# user changed her mind ...
				return None
			if data_pwd == data_pwd4comparison:
				break
			gmGuiHelpers.gm_show_error (
				error = _(
					'Passphrases do not match.\n'
					'\n'
					'Retry, or abort with an empty passphrase.'
				),
				title = msg_title
			)
		return data_pwd
コード例 #28
0
def __handle_lost_db_connection(t, v, tb):

	if t not in [gmPG2.dbapi.OperationalError, gmPG2.dbapi.InterfaceError]:
		return False

	try:
		msg = gmPG2.extract_msg_from_pg_exception(exc = v)
	except:
		msg = u'cannot extract message from PostgreSQL exception'
		print msg
		print v
		return False

	conn_lost = False

	if t == gmPG2.dbapi.OperationalError:
		conn_lost = (
			('erver' in msg)
				and
			(
				('term' in msg)
					or
				('abnorm' in msg)
					or
				('end' in msg)
					or
				('oute' in msg)
			)
		)

	if t == gmPG2.dbapi.InterfaceError:
		conn_lost = (
			('onnect' in msg)
				and
			(('close' in msg) or ('end' in msg))
		)

	if not conn_lost:
		return False

	gmLog2.log_stack_trace('lost connection', t, v, tb)
	wx.EndBusyCursor()
	gmLog2.flush()
	gmGuiHelpers.gm_show_error (
		aTitle = _('Lost connection'),
		aMessage = _(
			'Since you were last working in GNUmed,\n'
			'your database connection timed out.\n'
			'\n'
			'This GNUmed session is now expired.\n'
			'\n'
			'You will have to close this client and\n'
			'restart a new GNUmed session.'
		)
	)
	return True
コード例 #29
0
	def _on_OK_button_pressed(self, event):
		event.Skip()
		pk_issue = self._PhWheel_issue.GetData(can_create=True)
		if pk_issue is None:
			gmGuiHelpers.gm_show_error (
				_('Cannot create new health issue:\n [%(issue)s]') % {'issue': self._PhWheel_issue.GetValue().strip()},
				_('Selecting health issue')
			)
			return False
		return True
コード例 #30
0
ファイル: gmEMRStructWidgets.py プロジェクト: ncqgm/gnumed
	def _on_OK_button_pressed(self, event):
		event.Skip()
		pk_issue = self._PhWheel_issue.GetData(can_create=True)
		if pk_issue is None:
			gmGuiHelpers.gm_show_error (
				_('Cannot create new health issue:\n [%(issue)s]') % {'issue': self._PhWheel_issue.GetValue().strip()},
				_('Selecting health issue')
			)
			return False
		return True
コード例 #31
0
    def _on_burn_items_button_pressed(self, event):
        event.Skip()

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

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

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

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

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

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

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

        return True
コード例 #32
0
ファイル: gmConfigRegistry.py プロジェクト: ncqgm/gnumed
	def SaveCurrParam(self):
		"""save parameter dialog"""
		# self.currSelParam is the name of the parameter with optional
		# cookie part appended, defParamName the name without cookie part !
		# you must use the latter to access config definitions !

		if not (self.currSelParam is None or self.currSelSubtree is None):

			# get new value
			val = self.paramTextCtrl.GetValue()
			
			currConfSource = self.mConfSources[self.currSelSubtree]
			newValue = currConfSource.castType(self.currSelParam,val)

			if newValue is None:
				gmGuiHelpers.gm_show_error (
					_('Type of entered value is not compatible with type expected.'),
					_('saving configuration')
				)

			# a particular config definition refers to a parameter name
			# without the cookie part. we have to strip the 
			# cookie off get the correct parameter
			defParamName = currConfSource.getRawName(self.currSelParam)

			# config definition object
			confDefinition = currConfSource.hasDefinition()

			# if there is no config definition, ask the user if the
			# new value should be stored unchecked

			if not confDefinition or not currConfSource.hasParameterDefinition(defParamName):
				if gmGuiHelpers.gm_show_question (
					_("There is no config definition for this parameter.\nThus it can't be checked for validity.\n\nSave anyway ?"),
					_('saving configuration')):
					currConfSource.setConfigData( self.currSelParam,newValue)
				
					# reshow new data to mark it non modified
					self.__show_parameter(self.currSelSubtree,self.currSelParam)
				return 

			# else check parameter for validity

			if currConfSource.isValid(defParamName,newValue):
				currConfSource.setConfigData(self.currSelParam,newValue)
				
				# reshow new data to mark it non modified
				self.__show_parameter(self.currSelSubtree,self.currSelParam)
			else:
				# TODO: display some hint on what could be wrong
				gmGuiHelpers.gm_show_error (
					_('Entered value is not valid.'),
					_('saving configuration')
				)
コード例 #33
0
	def SaveCurrParam(self):
		"""save parameter dialog"""
		# self.currSelParam is the name of the parameter with optional
		# cookie part appended, defParamName the name without cookie part !
		# you must use the latter to access config definitions !

		if not (self.currSelParam is None or self.currSelSubtree is None):

			# get new value
			val = self.paramTextCtrl.GetValue()
			
			currConfSource = self.mConfSources[self.currSelSubtree]
			newValue = currConfSource.castType(self.currSelParam,val)

			if newValue is None:
				gmGuiHelpers.gm_show_error (
					_('Type of entered value is not compatible with type expected.'),
					_('saving configuration')
				)

			# a particular config definition refers to a parameter name
			# without the cookie part. we have to strip the 
			# cookie off get the correct parameter
			defParamName = currConfSource.getRawName(self.currSelParam)

			# config definition object
			confDefinition = currConfSource.hasDefinition()

			# if there is no config definition, ask the user if the
			# new value should be stored unchecked

			if not confDefinition or not currConfSource.hasParameterDefinition(defParamName):
				if gmGuiHelpers.gm_show_question (
					_("There is no config definition for this parameter.\nThus it can't be checked for validity.\n\nSave anyway ?"),
					_('saving configuration')):
					currConfSource.setConfigData( self.currSelParam,newValue)
				
					# reshow new data to mark it non modified
					self.__show_parameter(self.currSelSubtree,self.currSelParam)
				return 

			# else check parameter for validity

			if currConfSource.isValid(defParamName,newValue):
				currConfSource.setConfigData(self.currSelParam,newValue)
				
				# reshow new data to mark it non modified
				self.__show_parameter(self.currSelSubtree,self.currSelParam)
			else:
				# TODO: display some hint on what could be wrong
				gmGuiHelpers.gm_show_error (
					_('Entered value is not valid.'),
					_('saving configuration')
				)
コード例 #34
0
ファイル: gmPraxisWidgets.py プロジェクト: jeromecc/gnumed
    def edit(workplace=None):

        dbcfg = gmCfg.cCfgSQL()

        if workplace is None:
            dlg = wx.TextEntryDialog(
                parent=parent,
                message=_('Enter a descriptive name for the new workplace:'),
                caption=_('Configuring GNUmed workplaces ...'),
                defaultValue=u'',
                style=wx.OK | wx.CENTRE)
            dlg.ShowModal()
            workplace = dlg.GetValue().strip()
            if workplace == u'':
                gmGuiHelpers.gm_show_error(
                    _('Cannot save a new workplace without a name.'),
                    _('Configuring GNUmed workplaces ...'))
                return False
            curr_plugins = []
        else:
            curr_plugins = gmTools.coalesce(
                dbcfg.get2(option=u'horstspace.notebook.plugin_load_order',
                           workplace=workplace,
                           bias='workplace'), [])

        msg = _(
            'Pick the plugin(s) to be loaded the next time the client is restarted under the workplace:\n'
            '\n'
            '    [%s]\n') % workplace

        picker = gmListWidgets.cItemPickerDlg(
            parent, -1, title=_('Configuring workplace plugins ...'), msg=msg)
        picker.set_columns(['Available plugins'], ['Active plugins'])
        available_plugins = gmPlugin.get_installed_plugins(plugin_dir='gui')
        picker.set_choices(available_plugins)
        picker.set_picks(picks=curr_plugins[:])
        btn_pressed = picker.ShowModal()
        if btn_pressed != wx.ID_OK:
            picker.Destroy()
            return False

        new_plugins = picker.get_picks()
        picker.Destroy()
        if new_plugins == curr_plugins:
            return True

        if new_plugins is None:
            return True

        dbcfg.set(option=u'horstspace.notebook.plugin_load_order',
                  value=new_plugins,
                  workplace=workplace)

        return True
コード例 #35
0
    def update(self):
        if self.__pat['pk'] is None:
            gmGuiHelpers.gm_show_error(aMessage=_(
                'Cannot load lab journal.\nYou first need to select a patient.'
            ),
                                       aTitle=_('loading lab journal'))
            return None

        if self.__populate_notebook() is None:
            return None
        return 1
コード例 #36
0
	def _on_scan_items_button_pressed(self, event):
		event.Skip()
		scans = gmDocumentWidgets.acquire_images_from_capture_device(calling_window = self)
		if scans is None:
			return

		if not gmPerson.gmCurrentPatient().export_area.add_files(scans, _('scan')):
			gmGuiHelpers.gm_show_error (
				title = _('Scanning files into export area'),
				error = _('Cannot add (some of) the following scans to the export area:\n%s ') % '\n '.join(fnames)
			)
コード例 #37
0
ファイル: gmLabWidgets.py プロジェクト: sk/gnumed
	def update(self):
		if self.__pat['pk'] is None:
			gmGuiHelpers.gm_show_error(
				aMessage = _('Cannot load lab journal.\nYou first need to select a patient.'),
				aTitle = _('loading lab journal')
			)
			return None

		if self.__populate_notebook() is None:
			return None
		return 1
コード例 #38
0
	def _on_clipboard_items_button_pressed(self, event):
		event.Skip()
		clip = gmGuiHelpers.clipboard2file(check_for_filename = True)
		if clip is None:
			return
		if clip is False:
			return
		if not gmPerson.gmCurrentPatient().export_area.add_file(filename = clip, hint = _('clipboard')):
			gmGuiHelpers.gm_show_error (
				title = _('Loading clipboard item (saved to file) into export area'),
				error = _('Cannot add the following clip to the export area:\n%s ') % clip
			)
コード例 #39
0
    def update(self):
        if self.__pat['pk'] is None:
            _log.Log(gmLog.lErr, 'need patient for update')
            gmGuiHelpers.gm_show_error(aMessage=_(
                'Cannot load lab data.\nYou first need to select a patient.'),
                                       aTitle=_('loading lab data'))
            return None

        if self.__populate_grid() is None:
            return None

        return 1
コード例 #40
0
ファイル: gmStaffWidgets.py プロジェクト: ncqgm/gnumed
	def _on_delete_button_pressed(self, event):
		pk_staff = self._LCTRL_staff.GetItemData(self._LCTRL_staff.GetFirstSelected())
		conn = gmAuthWidgets.get_dbowner_connection(procedure = _('Removing GNUmed user.'))
		if conn is None:
			return False
		success, msg = gmStaff.delete_staff(conn = conn, pk_staff = pk_staff)
		conn.close()
		self.__init_ui_data()
		if not success:
			gmGuiHelpers.gm_show_error(aMessage = msg, aTitle = _('Removing GNUmed user'))
			return False
		return True
コード例 #41
0
	def _on_fax_items_button_pressed(self, event):
		event.Skip()

		_log.debug('gm-fax_doc(.bat) API: "FAX-PROGRAM FAXNUMBER-OR-<EMPTY> LIST-OF-FILES-TO-FAX" (any file type !)')

		found, external_cmd = gmShellAPI.detect_external_binary('gm-fax_doc')
		if not found:
			gmDispatcher.send(signal = 'statustext', msg = _('Cannot send fax: <gm-fax_doc(.bat)> not found'))
			return False

		items = self._LCTRL_items.get_selected_item_data(only_one = False)
		if len(items) == 0:
			items = self._LCTRL_items.get_item_data()
			if len(items) == 0:
				gmDispatcher.send(signal = 'statustext', msg = _('Cannot send fax: no items'))
				return None
			if len(items) > 1:
				# ask, might be a lot
				process_all = gmGuiHelpers.gm_show_question (
					title = _('Faxing documents'),
					question = _('You have not selected any entries.\n\nSend fax with all %s entries ?') % len(items),
					cancel_button = False
				)
				if not process_all:
					return None

			return False

		files2fax = []
		for item in items:
			files2fax.append(item.save_to_file())
		fax_number = wx.GetTextFromUser (
			_('Please enter the fax number here !\n\n'
			  'It can be left empty if the external\n'
			  'fax software knows how to get the number.'),
			caption = _('Faxing documents'),
			parent = self,
			centre = True
		)
		if fax_number == '':
			fax_number = 'EMPTY'
		args = [external_cmd, fax_number, ' '.join(files2fax)]
		success, ret_code, stdout = gmShellAPI.run_process(cmd_line = args, verbose = _cfg.get(option = 'debug'))
		if not success:
			gmGuiHelpers.gm_show_error (
				aMessage = _('Error faxing documents to\n\n  %s') % fax_number,
				aTitle = _('Faxing documents')
			)
			return False

		self.__save_soap_note(soap = _('Faxed to [%s]:\n - %s') % (fax_number, '\n - '.join([ i['description'] for i in items ])))
		return True
コード例 #42
0
ファイル: gmLabWidgets.py プロジェクト: sk/gnumed
	def update(self):
		if self.__pat['pk'] is None:
			_log.Log(gmLog.lErr, 'need patient for update')
			gmGuiHelpers.gm_show_error(
				aMessage = _('Cannot load lab data.\nYou first need to select a patient.'),
				aTitle = _('loading lab data')
			)
			return None

		if self.__populate_grid() is None:
			return None

		return 1
コード例 #43
0
ファイル: gmAddressWidgets.py プロジェクト: ncqgm/gnumed
	def _valid_for_save(self):

		validity = True

		# if any field is filled, all must be filled, so track that
		is_any_field_filled = False

		# check by string
		required_fields = [
			self._PRW_urb,
			self._TCTRL_number,
			self._PRW_street,
			self._PRW_zip
		]
		if self.__type_is_editable:
			required_fields.insert(0, self._PRW_type)
		for field in required_fields:
			if len(field.GetValue().strip()) == 0:
				if is_any_field_filled:
					self.display_ctrl_as_valid(field, False)
					field.SetFocus()
					gmGuiHelpers.gm_show_error (
						_('Address details must be filled in completely or not at all.'),
						_('Saving contact data')
					)
					validity = False
			else:
				is_any_field_filled = True
				self.display_ctrl_as_valid(field, True)

		# check by data
		required_fields = (
			self._PRW_country,
			self._PRW_state
		)
		for field in required_fields:
			if field.GetData() is None:
				if is_any_field_filled:
					self.display_ctrl_as_valid(field, False)
					field.SetFocus()
					gmGuiHelpers.gm_show_error (
						_('Address details must be filled in completely or not at all.'),
						_('Saving contact data')
					)
					validity = False
			else:
				is_any_field_filled = True
				self.display_ctrl_as_valid(field, True)

		return validity
コード例 #44
0
ファイル: gmAuthWidgets.py プロジェクト: ncqgm/gnumed
def get_dbowner_connection(procedure=None, dbo_password=None, dbo_account='gm-dbo'):
	if procedure is None:
		procedure = _('<restricted procedure>')

	# 1) get password for gm-dbo
	if dbo_password is None:
		dbo_password = wx.GetPasswordFromUser (
			message = _("""
 [%s]

This is a restricted procedure. We need the
current password for the GNUmed database owner.

Please enter the current password for <%s>:""") % (
				procedure,
				dbo_account
			),
			caption = procedure
		)
		if dbo_password == '':
			return None

	gmLog2.add_word2hide(dbo_password)

	# 2) connect as gm-dbo
	login = gmPG2.get_default_login()
	dsn = gmPG2.make_psycopg2_dsn (
		database = login.database,
		host = login.host,
		port = login.port,
		user = dbo_account,
		password = dbo_password
	)
	try:
		conn = gmPG2.get_connection (
			dsn = dsn,
			readonly = False,
			verbose = True,
			pooled = False
		)
	except:
		_log.exception('cannot connect')
		gmGuiHelpers.gm_show_error (
			aMessage = _('Cannot connect as the GNUmed database owner <%s>.') % dbo_account,
			aTitle = procedure
		)
		gmPG2.log_database_access(action = 'failed to connect as database owner for [%s]' % procedure)
		return None

	return conn
コード例 #45
0
ファイル: gmAddressWidgets.py プロジェクト: rockdriven/gnumed
	def _valid_for_save(self):

		validity = True

		# if any field is filled, all must be filled, so track that
		is_any_field_filled = False

		# check by string
		required_fields = [
			self._PRW_urb,
			self._TCTRL_number,
			self._PRW_street,
			self._PRW_zip
		]
		if self.__type_is_editable:
			required_fields.insert(0, self._PRW_type)
		for field in required_fields:
			if len(field.GetValue().strip()) == 0:
				if is_any_field_filled:
					self.display_ctrl_as_valid(field, False)
					field.SetFocus()
					gmGuiHelpers.gm_show_error (
						_('Address details must be filled in completely or not at all.'),
						_('Saving contact data')
					)
					validity = False
			else:
				is_any_field_filled = True
				self.display_ctrl_as_valid(field, True)

		# check by data
		required_fields = (
			self._PRW_country,
			self._PRW_state
		)
		for field in required_fields:
			if field.GetData() is None:
				if is_any_field_filled:
					self.display_ctrl_as_valid(field, False)
					field.SetFocus()
					gmGuiHelpers.gm_show_error (
						_('Address details must be filled in completely or not at all.'),
						_('Saving contact data')
					)
					validity = False
			else:
				is_any_field_filled = True
				self.display_ctrl_as_valid(field, True)

		return validity
コード例 #46
0
ファイル: gmStaffWidgets.py プロジェクト: ncqgm/gnumed
	def _on_enlist_button_pressed(self, evt):
		# sanity checks
		if self._TXT_password.GetValue() != self._TXT_password_again.GetValue():
			gmGuiHelpers.gm_show_error (
				aMessage = _('Password entries do not match. Please type in the passwords again to rule out typos.'),
				aTitle = _('Adding GNUmed user')
			)
			self._TXT_password.SetValue('')
			self._TXT_password_again.SetValue('')
			return False

		if self._TXT_password.GetValue().strip() == '':
			really_wants_empty_password = gmGuiHelpers.gm_show_question (
				aMessage = _(
					'Are you positively sure you want to create\n'
					'a user with an empty password ?\n'
					'\n'
					'Think about the record access implications !'
				),
				aTitle = _('Adding GNUmed user')
			)
			if not really_wants_empty_password:
				return False

		# connect as "gm-dbo"
		conn = gmAuthWidgets.get_dbowner_connection (
			procedure = _('Enlisting person as user.'),
			dbo_password = gmTools.none_if(self._TXT_dbo_password.GetValue(), '')
		)
		if conn is None:
			return False

		# create new user
		success, msg = gmStaff.create_staff (
			conn = conn,
			db_account = self._TXT_account.GetValue(),
			password = self._TXT_password.GetValue(),
			identity = gmPerson.gmCurrentPatient().ID,
			short_alias = self._TXT_short_alias.GetValue().strip()
		)
		conn.close()
		if not success:
			gmGuiHelpers.gm_show_error(aMessage = msg, aTitle = _('Adding GNUmed user'))
			return False

		if self.IsModal():
			self.EndModal(wx.ID_OK)
		else:
			self.Close()
コード例 #47
0
    def __handle_keyword(self, kwd=None):
        try:
            create_widget = self.__popup_keywords[kwd]['widget_factory']
        except KeyError:
            gmDispatcher.send(signal='statustext',
                              msg=_('No action configured for keyword [%s].') %
                              kwd)
            return False

#		best_pos, best_size = self.__get_best_popup_geom()
        screen_pos = self.ClientToScreen(
            self.PointFromPosition(self.GetCurrentPos()))
        top_parent = wx.GetTopLevelParent(self)
        best_pos = top_parent.ScreenToClient(screen_pos)
        try:
            popup = create_widget(
                parent=top_parent,
                pos=best_pos,
                size=wx.Size(400, 300),
                style=wx.SUNKEN_BORDER,
                data_sink=self.__popup_keywords[kwd]['widget_data_sink'])
        except Exception:
            _log.exception(
                'cannot call [%s] on keyword [%s] to create widget' %
                (create_widget, kwd))
            gmGuiHelpers.gm_show_error(
                aMessage=_('Cannot invoke [%s] for keyword [%s].') %
                (create_widget, kwd),
                aTitle=_('showing keyword popup'))
            return False

        if not isinstance(popup, wx.Dialog):
            gmDispatcher.send(
                signal='statustext',
                msg=_('Action [%s] on keyword [%s] is invalid.') %
                (create_widget, kwd))
            _log.error('keyword [%s] triggered action [%s]' %
                       (kwd, create_widget))
            _log.error(
                'the result (%s) is not a wx.Dialog subclass instance, however'
                % str(popup))
            return False

        # display widget
        result = popup.ShowModal()
        if result == wx.ID_OK:
            summary = popup.get_summary()
            wx.CallAfter(self.Embed, summary)
        popup.DestroyLater()
コード例 #48
0
ファイル: gmLabWidgets.py プロジェクト: sk/gnumed
	def on_save_request_ID(self, event):
		req_id = self.fld_request_id.GetValue()
		if (req_id is None) or (req_id.strip() == ''):
			gmGuiHelpers.gm_show_error (
				_('You must type in a request ID !\n\nUsually you will find the request ID written on\nthe barcode sticker on your probe container.'),
				_('saving request id')
			)
			return None
		emr = self.__pat.get_emr()
		request = emr.add_lab_request(lab=int(self.lab), req_id = req_id)
		if request is None:
			gmDispatcher.send(signal = 'statustext', msg =_('Cannot save lab request.'))
			return None

		# FIXME: maybe populate request list only ?
		# btw, we can make the sub-notebook tabs load data on-demand just
		# like the main notebook tabs :-)
		self.__populate_notebook()
コード例 #49
0
ファイル: gmFormWidgets.py プロジェクト: sk/gnumed
	def print_forms():
		# anything to do ?
		files2print = []
		form_names = []
		for form in forms:
			files2print.extend(form.final_output_filenames)
			form_names.append(u'%s (%s)' % (form.template['name_long'], form.template['external_version']))
		if len(files2print) == 0:
			return True
		# print
		printed = gmPrinting.print_files(filenames = files2print, jobtype = jobtype)
		if not printed:
			gmGuiHelpers.gm_show_error (
				aMessage = _('Error printing documents.'),
				aTitle = _('Printing [%s]') % jobtype
			)
			return False
		soap_lines.append(_('Printed: %s') % u', '.join(form_names))
		return True
コード例 #50
0
ファイル: gmRequest.py プロジェクト: ncqgm/gnumed
 def _ok_pressed (self, event):
     form_id = self.wheel_form.getData ()
     print "Form id: %s" % form_id
     type_id = self.wheel_type.getData ()
     print "Type : %s" % type_id
     if form_id and type_id:
         try:
             form = gmForms.get_form (form_id)
             params = {}
             params['type'] = self.wheel_type.GetValue ()
             params['request'] = self.text_ctrl_request.GetValue ()
             params['clinical_notes'] = self.text_ctrl_clinical.GetValue ()
             params['instructions'] = self.text_ctrl_instructions.GetValue ()
             form.store (params)
             form.process (params)
             form.printout ()
         except gmForms.FormError, e:
             gmGuiHelpers.gm_show_error (str(e), _("Error processing form"))
         except:
コード例 #51
0
		def _func_decorated_with_required_role_checking(*args, **kwargs):
			if _known_roles.index(minimum_role) > _known_roles.index(_curr_staff['role']):
				_log.info('access denied: %s', activity)
				_log.debug('required role: %s', minimum_role)
				_log.debug('current role: %s (<%s>)', _curr_staff['l10n_role'], _curr_staff['role'])
				_log.debug('current user: %s (<%s>)', _curr_staff['short_alias'], _curr_staff['db_user'])
				wx.EndBusyCursor()
				if fail_silently:
					return return_value_on_failure
				gmGuiHelpers.gm_show_error (
					aTitle = _('Access denied'),
					aMessage = _(
						'Your account is not set up to access this part of GNUmed:\n'
						'\n'
						'  [%s]'
					) % activity
				)
				return return_value_on_failure
			return original_function(*args, **kwargs)
コード例 #52
0
ファイル: gmAddressWidgets.py プロジェクト: ncqgm/gnumed
	def _save_as_update(self):
		# do not update existing address, rather
		# create new one or get corresponding
		# address should it exist
		try:
			created_or_loaded_address = gmDemographicRecord.create_address (
				country_code = self._PRW_country.GetData(),
				region_code = self._PRW_state.GetData(),
				urb = self._PRW_urb.GetValue().strip(),
				suburb = gmTools.none_if(self._PRW_suburb.GetValue().strip(), ''),
				postcode = self._PRW_zip.GetValue().strip(),
				street = self._PRW_street.GetValue().strip(),
				number = self._TCTRL_number.GetValue().strip(),
				subunit = gmTools.none_if(self._TCTRL_subunit.GetValue().strip(), '')
			)
		except:
			_log.exception('cannot save address')
			gmGuiHelpers.gm_show_error (
				_('Cannot save address.\n\n'
				  'Does the region [%s]\n'
				  'exist in country [%s] ?'
				) % (
					self._PRW_state.GetValue().strip(),
					self._PRW_country.GetValue().strip()
				),
				_('Saving address')
			)
			return False

		# link address to holder (there better be one)
		linked_address = self.address_holder.link_address(id_type = self._PRW_type.GetData(), address = created_or_loaded_address)
		if linked_address['pk_address'] != created_or_loaded_address['pk_address']:
			raise ValueError('problem linking address to person or org')

		created_or_loaded_address['notes_street'] = gmTools.none_if(self._TCTRL_notes_street.GetValue().strip(), '')
		created_or_loaded_address['notes_subunit'] = gmTools.none_if(self._TCTRL_notes_subunit.GetValue().strip(), '')
		created_or_loaded_address.save_payload()
		linked_address.refetch_payload()
		self.data = linked_address

		return True
コード例 #53
0
ファイル: gmProviderInboxWidgets.py プロジェクト: sk/gnumed
	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
コード例 #54
0
def __handle_lost_db_connection(t, v, tb):

    if t not in [gmPG2.dbapi.OperationalError, gmPG2.dbapi.InterfaceError]:
        return False

    try:
        msg = gmPG2.extract_msg_from_pg_exception(exc=v)
    except:
        msg = u"cannot extract message from PostgreSQL exception"
        print msg
        print v
        return False

    conn_lost = False

    if t == gmPG2.dbapi.OperationalError:
        conn_lost = ("erver" in msg) and (("term" in msg) or ("abnorm" in msg) or ("end" in msg) or ("oute" in msg))

    if t == gmPG2.dbapi.InterfaceError:
        conn_lost = ("onnect" in msg) and (("close" in msg) or ("end" in msg))

    if not conn_lost:
        return False

    gmLog2.log_stack_trace("lost connection", t, v, tb)
    wx.EndBusyCursor()
    gmLog2.flush()
    gmGuiHelpers.gm_show_error(
        aTitle=_("Lost connection"),
        aMessage=_(
            "Since you were last working in GNUmed,\n"
            "your database connection timed out.\n"
            "\n"
            "This GNUmed session is now expired.\n"
            "\n"
            "You will have to close this client and\n"
            "restart a new GNUmed session."
        ),
    )
    return True
コード例 #55
0
ファイル: gmResizingWidgets.py プロジェクト: sk/gnumed
	def __handle_keyword(self, kwd=None):
		try:
			create_widget = self.__popup_keywords[kwd]['widget_factory']
		except KeyError:
			gmDispatcher.send(signal='statustext', msg=_('No action configured for keyword [%s].') % kwd)
			return False

#		best_pos, best_size = self.__get_best_popup_geom()
		screen_pos = self.ClientToScreen(self.PointFromPosition(self.GetCurrentPos()))
		top_parent = wx.GetTopLevelParent(self)
		best_pos = top_parent.ScreenToClient(screen_pos)
		try:
			popup = create_widget (
				parent = top_parent,
				pos = best_pos,
				size = wx.Size(400, 300),
				style = wx.SUNKEN_BORDER,
				data_sink = self.__popup_keywords[kwd]['widget_data_sink']
			)
		except Exception:
			_log.exception('cannot call [%s] on keyword [%s] to create widget' % (create_widget, kwd))
			gmGuiHelpers.gm_show_error (
				aMessage = _('Cannot invoke [%s] for keyword [%s].') % (create_widget, kwd),
				aTitle = _('showing keyword popup')
			)
			return False

		if not isinstance(popup, wx.Dialog):
			gmDispatcher.send(signal='statustext', msg=_('Action [%s] on keyword [%s] is invalid.') % (create_widget, kwd))
			_log.error('keyword [%s] triggered action [%s]' % (kwd, create_widget))
			_log.error('the result (%s) is not a wx.Dialog subclass instance, however' % str(popup))
			return False

		# display widget
		result = popup.ShowModal()
		if result == wx.ID_OK:
			summary = popup.get_summary()
			wx.CallAfter(self.Embed, summary)
		popup.Destroy()
コード例 #56
0
def __handle_lost_db_connection(t, v, tb):

	if not gmPG2.exception_is_connection_loss(v):
		return False

	gmPG2.log_pg_exception_details(v)
	gmLog2.log_stack_trace('lost connection', t, v, tb)
	wx.EndBusyCursor()
	gmLog2.flush()
	gmGuiHelpers.gm_show_error (
		aTitle = _('Lost connection'),
		aMessage = _(
			'Since you were last working in GNUmed,\n'
			'your database connection timed out.\n'
			'\n'
			'This GNUmed session is now expired.\n'
			'\n'
			'You will have to close this client and\n'
			'restart a new GNUmed session.'
		)
	)
	return True
コード例 #57
0
ファイル: gmLabWidgets.py プロジェクト: sk/gnumed
	def _on_mark_reviewed(self, event):
		reviewed_results = []
		for row in range(self.__grid_unreviewed_results.GetNumberRows()):
			if self.__grid_unreviewed_results.GetCellValue(row, 0) == '1':
				# look up associated request
				result = self.dict_unreviewed_results[row]
				reviewed_results.append(result)
				# update "relevant" status
				relevant = self.__grid_unreviewed_results.GetCellValue(row, 1)
				if relevant == '1':
					result['relevant'] = 'true'
				else:
					result['relevant'] = 'false'

		if len(reviewed_results) == 0:
			gmGuiHelpers.beep_status_text(_('No results marked as reviewed.'))
			event.Skip()
			return None

		for result in reviewed_results:
			result['reviewed'] = 'true'
			result['pk_reviewer'] = gmStaff.gmCurrentProvider()['pk_staff']
			if not result['abnormal']:
				result['abnormal'] = ''
			successfull, error = result.save_payload()
			# repopulate
			if successfull:
				self.__populate_notebook()
			else:
				_log.Log(gmLog.lErr, 'setting result status to reviewed failed %s' % error)
				gmGuiHelpers.gm_show_error (
					aMessage = _('Cannot mark results as "reviewed":\n%s') % error,
					aTitle = _('update result status')
				)
				return None

		event.Skip()
コード例 #58
0
ファイル: gmPatPicWidgets.py プロジェクト: sk/gnumed
	def _on_AcquirePhoto(self, event):

		# get from image source
		from Gnumed.pycommon import gmScanBackend

		try:
			fnames = gmScanBackend.acquire_pages_into_files (
				delay = 5,
				calling_window = self
			)
		except OSError:
			_log.exception('problem acquiring image from source')
			gmGuiHelpers.gm_show_error (
				aMessage = _(
					'No image could be acquired from the source.\n\n'
					'This may mean the scanner driver is not properly installed.\n\n'
					'On Windows you must install the TWAIN Python module\n'
					'while on Linux and MacOSX it is recommended to install\n'
					'the XSane package.'
				),
				aTitle = _('Acquiring photo')
			)
			return

		if fnames is False:
			gmGuiHelpers.gm_show_error (
				aMessage = _('Patient photo could not be acquired from source.'),
				aTitle = _('Acquiring photo')
			)
			return

		if len(fnames) == 0:		# no pages scanned
			return

		self.__import_pic_into_db(fname=fnames[0])
		self.__reload_photo()
コード例 #59
0
ファイル: gmSOAPWidgets.py プロジェクト: ncqgm/gnumed
	def __on_problem_activated(self, event):
		"""
		When the user changes health issue selection, update selected issue
		reference and update buttons according its input status.

		when the user selects a problem in the problem list:
			- check whether selection is issue or episode
			- if editor for episode exists: focus it
			- if no editor for episode exists: create one and focus it
		"""
		problem_idx = self.__LST_problems.GetSelection()
		problem = self.__LST_problems.GetClientData(problem_idx)

		if self.__soap_notebook.add_editor(problem = problem):
			return True

		gmGuiHelpers.gm_show_error (
			aMessage = _(
				'Cannot open progress note editor for\n\n'
				'[%s].\n\n'
			) % problem['problem'],
			aTitle = _('opening progress note editor')
		)
		return False
コード例 #60
0
def __handle_import_error(t, v, tb):

    if t != exceptions.ImportError:
        return False

    wx.EndBusyCursor()

    _log2.error("module [%s] not installed", v)
    gmGuiHelpers.gm_show_error(
        aTitle=_("Missing GNUmed module"),
        aMessage=_(
            "GNUmed detected that parts of it are not\n"
            "properly installed. The following message\n"
            "names the missing part:\n"
            "\n"
            ' "%s"\n'
            "\n"
            "Please make sure to get the missing\n"
            "parts installed. Otherwise some of the\n"
            "functionality will not be accessible."
        )
        % v,
    )
    return True