Exemplo n.º 1
0
def _check_birthday(patient=None):

	if patient['dob'] is None:
		return

	dbcfg = gmCfg.cCfgSQL()
	dob_distance = dbcfg.get2 (
		option = 'patient_search.dob_warn_interval',
		workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
		bias = 'user',
		default = '1 week'
	)

	if not patient.dob_in_range(dob_distance, dob_distance):
		return

	now = gmDateTime.pydt_now_here()
	enc = gmI18N.get_encoding()
	msg = _('%(pat)s turns %(age)s on %(month)s %(day)s ! (today is %(month_now)s %(day_now)s)') % {
		'pat': patient.get_description_gender(),
		'age': patient.get_medical_age().strip('y'),
		'month': patient.get_formatted_dob(format = '%B'),
		'day': patient.get_formatted_dob(format = '%d'),
		'month_now': gmDateTime.pydt_strftime(now, '%B', gmDateTime.acc_months),
		'day_now': gmDateTime.pydt_strftime(now, '%d', gmDateTime.acc_days)
	}
	gmDispatcher.send(signal = 'statustext', msg = msg)
Exemplo n.º 2
0
	def contribute_translations(item=None):

		do_it = gmGuiHelpers.gm_show_question (
			aTitle = _('Contributing translations'),
			aMessage = _('Do you want to contribute your translations to the GNUmed project ?')
		)
		if not do_it:
			return False

		fname = gmTools.get_unique_filename(prefix = 'gm-db-translations-', suffix = '.sql')
		gmPG2.export_translations_from_database(filename = fname)

		msg = (
			u'These are database string translations contributed by a GNUmed user.\n'
			'\n'
			'\tThe GNUmed "%s" Client'
		) % gmI18N.system_locale

		if not gmNetworkTools.send_mail (
			auth = {'user': gmNetworkTools.default_mail_sender, 'password': u'gnumed-at-gmx-net'},
			sender = u'GNUmed Client <*****@*****.**>',
			receiver = [u'*****@*****.**'],
			subject = u'<contribution>: database translation',
			message = msg,
			encoding = gmI18N.get_encoding(),
			attachments = [[fname, u'text/plain', u'quoted-printable']]
		):
			gmDispatcher.send(signal = 'statustext', msg = _('Unable to send mail. Cannot contribute translations to GNUmed community.') % report, beep = True)
			return False

		gmDispatcher.send(signal = 'statustext', msg = _('Thank you for your contribution to the GNUmed community!'), beep = True)
		return True
Exemplo n.º 3
0
 def _on_remove_button_pressed(self, evt):
     self.__id_most_recently_activated_patient = None
     item = self._LCTRL_patients.get_selected_item_data(only_one=True)
     if item is None:
         return
     cmt = gmTools.coalesce(item['comment'], '').split('\n')[0].strip()[:40]
     if cmt != '':
         cmt += '\n'
     question = _(
         'Are you sure you want to remove\n'
         '\n'
         ' %s, %s (%s)\n'
         ' born: %s\n'
         ' %s'
         '\n'
         'from the waiting list ?') % (
             item['lastnames'], item['firstnames'], item['l10n_gender'],
             gmTools.coalesce(gmTools.coalesce(
                 item['dob'], '', function4value=('strftime', '%d %b %Y')),
                              '',
                              function4value=('decode',
                                              gmI18N.get_encoding())), cmt)
     do_delete = gmGuiHelpers.gm_show_question(
         title=_('Delete waiting list entry'), question=question)
     if not do_delete:
         return
     gmPraxis.gmCurrentPraxisBranch().remove_from_waiting_list(
         pk=item['pk_waiting_list'])
Exemplo n.º 4
0
    def _on_get_list_tooltip(self, entry):

        dob = gmTools.coalesce(gmTools.coalesce(entry['dob'],
                                                u'',
                                                function_initial=('strftime',
                                                                  '%d %b %Y')),
                               u'',
                               u' (%s)',
                               function_initial=('decode',
                                                 gmI18N.get_encoding()))

        tt = _('%s patients are waiting.\n'
               '\n'
               'Doubleclick to activate (entry will stay in list).'
               ) % self._LCTRL_patients.GetItemCount()

        tt += _('\n'
                '%s\n'
                'Patient: %s%s\n'
                '%s'
                'Urgency: %s\n'
                'Time: %s\n'
                '%s') % (gmTools.u_box_horiz_single * 50, u'%s, %s (%s)' %
                         (entry['lastnames'], entry['firstnames'],
                          entry['l10n_gender']), dob,
                         gmTools.coalesce(entry['waiting_zone'], u'',
                                          _('Zone: %s\n')), entry['urgency'],
                         gmDateTime.format_interval_medically(
                             entry['waiting_time']),
                         gmTools.coalesce(entry['comment'], u'', u'\n%s'))

        return tt
Exemplo n.º 5
0
    def format(self,
               with_indications=False,
               with_comment=False,
               with_reaction=False,
               date_format='%Y-%m-%d'):

        lines = []

        lines.append(u' %s: %s [%s]%s' % (
            self._payload[self._idx['date_given']].strftime(date_format).
            decode(gmI18N.get_encoding()), self._payload[self._idx['vaccine']],
            self._payload[self._idx['batch_no']],
            gmTools.coalesce(self._payload[self._idx['site']], u'', u' (%s)')))

        if with_comment:
            if self._payload[self._idx['comment']] is not None:
                lines.append(u'   %s' % self._payload[self._idx['comment']])

        if with_reaction:
            if self._payload[self._idx['reaction']] is not None:
                lines.append(u'   %s' % self._payload[self._idx['reaction']])

        if with_indications:
            lines.append(u'   %s' % u' / '.join([
                i['l10n_indication']
                for i in self._payload[self._idx['indications']]
            ]))

        return lines
Exemplo n.º 6
0
	def _on_contribute_button_pressed(self, evt):
		report = self._PRW_report_name.GetValue().strip()
		if report == u'':
			gmDispatcher.send(signal = 'statustext', msg = _('Report must have a name for contribution.'), beep = False)
			return

		query = self._TCTRL_query.GetValue().strip()
		if query == u'':
			gmDispatcher.send(signal = 'statustext', msg = _('Report must have a query for contribution.'), beep = False)
			return

		do_it = gmGuiHelpers.gm_show_question (
			_(	'Be careful that your contribution (the query itself) does\n'
				'not contain any person-identifiable search parameters.\n'
				'\n'
				'Note, however, that no query result data whatsoever\n'
				'is included in the contribution that will be sent.\n'
				'\n'
				'Are you sure you wish to send this query to\n'
				'the gnumed community mailing list?\n'
			),
			_('Contributing custom report')
		)
		if not do_it:
			return

		auth = {'user': gmNetworkTools.default_mail_sender, 'password': u'gnumed-at-gmx-net'}
		msg = u"""--- This is a report definition contributed by a GNUmed user.

--- Save it as a text file and drop it onto the Report Generator
--- inside GNUmed in order to take advantage of the contribution.

----------------------------------------

--- %s

%s

----------------------------------------

--- The GNUmed client.
""" % (report, query)

		if not gmNetworkTools.send_mail (
			sender = u'GNUmed Report Generator <*****@*****.**>',
			receiver = [u'*****@*****.**'],
			subject = u'user contributed report',
			message = msg,
			encoding = gmI18N.get_encoding(),
			server = gmNetworkTools.default_mail_server,
			auth = auth
		):
			gmDispatcher.send(signal = 'statustext', msg = _('Unable to send mail. Cannot contribute report [%s] to GNUmed community.') % report, beep = True)
			return False

		gmDispatcher.send(signal = 'statustext', msg = _('Thank you for your contribution to the GNUmed community!'), beep = False)
		return True
Exemplo n.º 7
0
	def _on_contribute_button_pressed(self, evt):
		report = self._PRW_report_name.GetValue().strip()
		if report == u'':
			gmDispatcher.send(signal = 'statustext', msg = _('Report must have a name for contribution.'), beep = False)
			return

		query = self._TCTRL_query.GetValue().strip()
		if query == u'':
			gmDispatcher.send(signal = 'statustext', msg = _('Report must have a query for contribution.'), beep = False)
			return

		do_it = gmGuiHelpers.gm_show_question (
			_(	'Be careful that your contribution (the query itself) does\n'
				'not contain any person-identifiable search parameters.\n'
				'\n'
				'Note, however, that no query result data whatsoever\n'
				'is included in the contribution that will be sent.\n'
				'\n'
				'Are you sure you wish to send this query to\n'
				'the gnumed community mailing list?\n'
			),
			_('Contributing custom report')
		)
		if not do_it:
			return

		auth = {'user': gmNetworkTools.default_mail_sender, 'password': u'gnumed-at-gmx-net'}
		msg = u"""--- This is a report definition contributed by a GNUmed user.

--- Save it as a text file and drop it onto the Report Generator
--- inside GNUmed in order to take advantage of the contribution.

----------------------------------------

--- %s

%s

----------------------------------------

--- The GNUmed client.
""" % (report, query)

		if not gmNetworkTools.send_mail (
			sender = u'GNUmed Report Generator <*****@*****.**>',
			receiver = [u'*****@*****.**'],
			subject = u'user contributed report',
			message = msg,
			encoding = gmI18N.get_encoding(),
			server = gmNetworkTools.default_mail_server,
			auth = auth
		):
			gmDispatcher.send(signal = 'statustext', msg = _('Unable to send mail. Cannot contribute report [%s] to GNUmed community.') % report, beep = True)
			return False

		gmDispatcher.send(signal = 'statustext', msg = _('Thank you for your contribution to the GNUmed community!'), beep = False)
		return True
Exemplo n.º 8
0
   def __init_ui_data(self):
       pat = gmPerson.gmCurrentPatient()
       name = pat.get_active_name()
       txt = _("""
 %s "%s" %s
 born: %s""") % (name['firstnames'], name['preferred'], name['lastnames'],
                 pat.get_formatted_dob(format='%Y %b %d',
                                       encoding=gmI18N.get_encoding()))
       self._TXT_person.SetValue(txt)
       txt = name['firstnames'][:2] + name['lastnames'][:2]
       self._TXT_short_alias.SetValue(txt)
       self._TXT_account.SetValue(txt.lower())
Exemplo n.º 9
0
	def __get_session_xsanerc(self):

		# create an xsanerc for this session
		session_xsanerc = gmTools.get_unique_filename (
			prefix = 'gm-session_xsanerc-',
			suffix = '.conf'
		)
		_log.debug('GNUmed -> XSane session xsanerc: %s', session_xsanerc)

		# our closest bet, might contain umlauts
		enc = gmI18N.get_encoding()
		fread = io.open(self._gm_custom_xsanerc, mode = "rt", encoding = enc)
		fwrite = io.open(session_xsanerc, mode = "wt", encoding = enc)

		paths = gmTools.gmPaths()
		val_dict = {
			'tmp-path': paths.tmp_dir,
			'working-directory': paths.tmp_dir,
			'filename': '<--force-filename>',
			'filetype': cXSaneScanner._FILETYPE,
			'skip-existing-numbers': '1',
			'filename-counter-step': '1',
			'filename-counter-len': '3'
		}

		for idx, line in enumerate(fread):
			line = line.replace('\n', '')
			line = line.replace('\r', '')

			if idx % 2 == 0:			# even lines are keys
				curr_key = line.strip('"')
				fwrite.write('"%s"\n' % curr_key)
			else: 						# odd lines are corresponding values
				try:
					value = val_dict[curr_key]
					_log.debug('replaced [%s] with [%s]', curr_key, val_dict[curr_key])
				except KeyError:
					value = line
				fwrite.write('%s\n' % value)

		fwrite.flush()
		fwrite.close()
		fread.close()

		return session_xsanerc
Exemplo n.º 10
0
    def contribute_translations(item=None):

        do_it = gmGuiHelpers.gm_show_question(
            aTitle=_('Contributing translations'),
            aMessage=
            _('Do you want to contribute your translations to the GNUmed project ?'
              ))
        if not do_it:
            return False

        fname = gmTools.get_unique_filename(prefix='gm-db-translations-',
                                            suffix='.sql')
        gmPG2.export_translations_from_database(filename=fname)

        msg = (
            u'These are database string translations contributed by a GNUmed user.\n'
            '\n'
            '\tThe GNUmed "%s" Client') % gmI18N.system_locale

        if not gmNetworkTools.send_mail(
                auth={
                    'user': gmNetworkTools.default_mail_sender,
                    'password': u'gnumed-at-gmx-net'
                },
                sender=u'GNUmed Client <*****@*****.**>',
                receiver=[u'*****@*****.**'],
                subject=u'<contribution>: database translation',
                message=msg,
                encoding=gmI18N.get_encoding(),
                attachments=[[fname, u'text/plain', u'quoted-printable']]):
            gmDispatcher.send(
                signal='statustext',
                msg=
                _('Unable to send mail. Cannot contribute translations to GNUmed community.'
                  ) % report,
                beep=True)
            return False

        gmDispatcher.send(
            signal='statustext',
            msg=_('Thank you for your contribution to the GNUmed community!'),
            beep=True)
        return True
Exemplo n.º 11
0
   def __init_ui_data(self):
       pat = gmPerson.gmCurrentPatient()
       name = pat.get_active_name()
       txt = (
           _(
               """
 %s "%s" %s
 born: %s"""
           )
           % (
               name["firstnames"],
               name["preferred"],
               name["lastnames"],
               pat.get_formatted_dob(format="%Y %b %d", encoding=gmI18N.get_encoding()),
           )
       )
       self._TXT_person.SetValue(txt)
       txt = name["firstnames"][:2] + name["lastnames"][:2]
       self._TXT_short_alias.SetValue(txt)
       self._TXT_account.SetValue(txt.lower())
Exemplo n.º 12
0
	def _on_remove_button_pressed(self, evt):
		self.__id_most_recently_activated_patient = None
		item = self._LCTRL_patients.get_selected_item_data(only_one = True)
		if item is None:
			return
		cmt = gmTools.coalesce(item['comment'], '').split('\n')[0].strip()[:40]
		if cmt != '':
			cmt += '\n'
		question = _(
			'Are you sure you want to remove\n'
			'\n'
			' %s, %s (%s)\n'
			' born: %s\n'
			' %s'
			'\n'
			'from the waiting list ?'
		) % (
			item['lastnames'],
			item['firstnames'],
			item['l10n_gender'],
			gmTools.coalesce (
				gmTools.coalesce (
					item['dob'],
					'',
					function_initial = ('strftime', '%d %b %Y')
				),
				'',
				function_initial = ('decode', gmI18N.get_encoding())
			),
			cmt
		)
		do_delete = gmGuiHelpers.gm_show_question (
			title = _('Delete waiting list entry'),
			question = question
		)
		if not do_delete:
			return
		gmPraxis.gmCurrentPraxisBranch().remove_from_waiting_list(pk = item['pk_waiting_list'])
Exemplo n.º 13
0
	def _on_get_list_tooltip(self, entry):

		dob = gmTools.coalesce (
				gmTools.coalesce (
					entry['dob'],
					u'',
					function_initial = ('strftime', '%d %b %Y')
				),
				u'',
				u' (%s)',
				function_initial = ('decode', gmI18N.get_encoding())
		)

		tt = _(
			'%s patients are waiting.\n'
			'\n'
			'Doubleclick to activate (entry will stay in list).'
		) % self._LCTRL_patients.GetItemCount()

		tt += _(
			'\n'
			'%s\n'
			'Patient: %s%s\n'
			'%s'
			'Urgency: %s\n'
			'Time: %s\n'
			'%s'
		) % (
			gmTools.u_box_horiz_single * 50,
			u'%s, %s (%s)' % (entry['lastnames'], entry['firstnames'], entry['l10n_gender']),
			dob,
			gmTools.coalesce(entry['waiting_zone'], u'', _('Zone: %s\n')),
			entry['urgency'],
			gmDateTime.format_interval_medically(entry['waiting_time']),
			gmTools.coalesce(entry['comment'], u'', u'\n%s')
		)

		return tt
Exemplo n.º 14
0
def run_report_query(query=None, limit=None, pk_identity=None):
    """Returns (status, hint, cols, rows)"""

    PATIENT_ID_TOKEN = '$<ID_ACTIVE_PATIENT>$'
    if limit is None:
        limit = ''
    else:
        limit = 'LIMIT %s' % limit

    # does user want to insert current patient ID ?
    if query.find(PATIENT_ID_TOKEN) == -1:
        wrapper_query = """
			SELECT * FROM (
				%%s
			) AS user_query
			%s
		""" % limit
    else:
        # she does, but is it possible ?
        if pk_identity is None:
            gmDispatcher.send('statustext',
                              msg=_('Query needs active patient.'),
                              beep=True)
            cols = [_('Error')]
            rows = [[_('Active patient query')], [
                ''
            ], [
                _('This query requires a patient to be active in the client.')
            ], [''], [_('Please activate the patient you are interested')],
                    [_('in and re-run the query.')]]
            return (False, 'pk_identity', cols, rows)

        query = query.replace(PATIENT_ID_TOKEN, str(pk_identity))
        wrapper_query = """
			SELECT %s AS pk_patient, * FROM (
				%%s
			) AS user_query
			%s
		""" % (pk_identity, limit)

    wrapped_query = wrapper_query % query
    _log.debug('running report query:')
    _log.debug(wrapped_query)

    try:
        # read-only for safety reasons
        rows, idx = gmPG2.run_ro_queries(queries=[{
            'cmd': wrapped_query
        }],
                                         get_col_idx=True)
    except Exception:
        _log.exception('report query failed')
        gmDispatcher.send('statustext', msg=_('The query failed.'), beep=True)
        cols = [_('Error')]
        t, v = sys.exc_info()[:2]
        rows = [[_('The query failed.')], [''], [str(t)]]
        for line in str(v).decode(gmI18N.get_encoding()).split('\n'):
            rows.append([line])
        rows.append([''])
        for line in query.split('\n'):
            rows.append([line])
        return (False, 'query failed', cols, rows)

    # swap (col_name, col_idx) to (col_idx, col_name)
    # and sort them according to position-in-query
    cols = [(value, key) for key, value in idx.items()]
    cols.sort()
    cols = [pair[1] for pair in cols]

    return (True, None, cols, rows)
Exemplo n.º 15
0
	def __refresh_waiting_list(self):
		self.__id_most_recently_activated_patient = None
		col, ascending = self._LCTRL_patients.GetSortState()	# preserve sorting order

		praxis = gmPraxis.gmCurrentPraxisBranch()
		pats = praxis.waiting_list_patients

		# set matcher to all zones currently in use
		zones = {}
		zones.update([ [p['waiting_zone'], None] for p in pats if p['waiting_zone'] is not None ])
		self._PRW_zone.update_matcher(items = zones.keys())

		# filter patient list by zone and set waiting list
		self.__current_zone = self._PRW_zone.GetValue().strip()
		if self.__current_zone == u'':
			pats = [ p for p in pats ]
		else:
			pats = [ p for p in pats if p['waiting_zone'] == self.__current_zone ]

		# filter by "active patient only"
		curr_pat = gmPerson.gmCurrentPatient()
		if curr_pat.connected:
			if self._CHBOX_active_patient_only.IsChecked():
				pats = [ p for p in pats if p['pk_identity'] == curr_pat.ID ]

		old_pks = [ d['pk_waiting_list'] for d in self._LCTRL_patients.get_selected_item_data() ]
		self._LCTRL_patients.set_string_items (
			[ [
				gmTools.coalesce(p['waiting_zone'], u''),
				p['urgency'],
				gmDateTime.pydt_strftime(p['registered'], format='%Y %b %d %H:%M'),
				gmDateTime.format_interval_medically(p['waiting_time']),
				u'%s, %s (%s)' % (p['lastnames'], p['firstnames'], p['l10n_gender']),
				gmTools.coalesce (
					gmTools.coalesce (
						p['dob'],
						u'',
						function_initial = ('strftime', '%d %b %Y')
					),
					u'',
					function_initial = ('decode', gmI18N.get_encoding())
				),
				gmTools.coalesce(p['comment'], u'').split('\n')[0]
			] for p in pats ]
		)
		self._LCTRL_patients.set_column_widths()
		self._LCTRL_patients.set_data(pats)
		new_selections = []
		new_pks = [ p['pk_waiting_list'] for p in pats ]
		for old_pk in old_pks:
			if old_pk in new_pks:
				new_selections.append(new_pks.index(old_pk))
		self._LCTRL_patients.selections = new_selections
		self._LCTRL_patients.Refresh()
		self._LCTRL_patients.SortListItems(col, ascending) # re-sort

		self._LBL_no_of_patients.SetLabel(_('(%s patients)') % len(pats))

		if len(pats) == 0:
			self._BTN_activate.Enable(False)
			self._BTN_activateplus.Enable(False)
			self._BTN_remove.Enable(False)
			self._BTN_edit.Enable(False)
			self._BTN_up.Enable(False)
			self._BTN_down.Enable(False)
		else:
			self._BTN_activate.Enable(True)
			self._BTN_activateplus.Enable(True)
			self._BTN_remove.Enable(True)
			self._BTN_edit.Enable(True)
		if len(pats) > 1:
			self._BTN_up.Enable(True)
			self._BTN_down.Enable(True)
Exemplo n.º 16
0
	def __update_age_label(self):

		# no patient
		if not self.curr_pat.connected:
			self._LBL_age.SetLabel(_('<Age>'))
			self._LBL_age.SetToolTipString(_('no patient selected'))
			return

		# gender is always known
		tt = _(u'Gender: %s (%s) - %s\n') % (
			self.curr_pat.gender_symbol,
			gmTools.coalesce(self.curr_pat[u'gender'], u'?'),
			self.curr_pat.gender_string
		)

		# dob is not known
		if self.curr_pat['dob'] is None:
			age = u'%s  %s' % (
				self.curr_pat.gender_symbol,
				self.curr_pat.get_formatted_dob()
			)
			self._LBL_age.SetLabel(age)
			self._LBL_age.SetToolTipString(tt)
			return

		tt += _('Born: %s\n') % self.curr_pat.get_formatted_dob(format = '%d %b %Y', encoding = gmI18N.get_encoding())

		# patient is dead
		if self.curr_pat['deceased'] is not None:
			tt += _('Died: %s\n') % gmDateTime.pydt_strftime(self.curr_pat['deceased'], '%d %b %Y')
			tt += _('At age: %s\n') % self.curr_pat['medical_age']
			age = u'%s  %s - %s (%s)' % (
				self.curr_pat.gender_symbol,
				self.curr_pat.get_formatted_dob(format = '%d %b %Y', encoding = gmI18N.get_encoding()),
				gmDateTime.pydt_strftime(self.curr_pat['deceased'], '%d %b %Y'),
				self.curr_pat['medical_age']
			)
			if self.curr_pat['dob_is_estimated']:
				tt += _(' (date of birth and age are estimated)\n')
			self._LBL_age.SetLabel(age)
			self._LBL_age.SetToolTipString(tt)
			return

		# patient alive
		now = gmDateTime.pydt_now_here()

		# patient birthday ?
		if self.curr_pat.get_formatted_dob(format = '%m-%d', honor_estimation = False) == now.strftime('%m-%d'):
			template = _('%(sex)s  %(dob)s (%(age)s today !)')
			tt += _("\nToday is the patient's birthday !\n\n")
		else:
			if self.curr_pat.current_birthday_passed is True:
				template = u'%(sex)s  %(dob)s%(l_arr)s (%(age)s)'
				tt += _(u'Birthday: %s ago\n') % gmDateTime.format_apparent_age_medically (
					age = gmDateTime.calculate_apparent_age(start = self.curr_pat.birthday_this_year, end = now)
				)
			elif self.curr_pat.current_birthday_passed is False:
				template = u'%(sex)s  %(r_arr)s%(dob)s (%(age)s)'
				tt += _(u'Birthday: in %s\n') % gmDateTime.format_apparent_age_medically (
					age = gmDateTime.calculate_apparent_age(start = now, end = self.curr_pat.birthday_this_year)
				)
			else:	# None, unknown
				template = u'%(sex)s  %(dob)s (%(age)s)'

		tt += _('Age: %s\n') % self.curr_pat['medical_age']

		# FIXME: if the age is below, say, 2 hours we should fire
		# a timer here that updates the age in increments of 1 minute ... :-)
		age = template % {
			u'sex': self.curr_pat.gender_symbol,
			u'dob': self.curr_pat.get_formatted_dob(format = '%d %b %Y', encoding = gmI18N.get_encoding()),
			u'age': self.curr_pat['medical_age'],
			u'r_arr': gmTools.u_arrow2right,
			u'l_arr': gmTools.u_left_arrow
		}

		# Easter Egg ;-)
		if self.curr_pat['lastnames'] == u'Leibner':
			if self.curr_pat['firstnames'] == u'Steffi':
				if self.curr_pat['preferred'] == u'Wildfang':
					age = u'%s %s' % (gmTools.u_black_heart, age)

		if self.curr_pat['dob_is_estimated']:
			tt += _(' (date of birth and age are estimated)\n')

		self._LBL_age.SetLabel(age)
		self._LBL_age.SetToolTipString(tt)
Exemplo n.º 17
0
def mail_log(parent=None, comment=None, helpdesk=None, sender=None):

    if (comment is None) or (comment.strip() == u""):
        comment = wx.GetTextFromUser(
            message=_("Please enter a short note on what you\n" "were about to do in GNUmed:"),
            caption=_("Sending bug report"),
            parent=parent,
        )
        if comment.strip() == u"":
            comment = u"<user did not comment on bug report>"

    receivers = []
    if helpdesk is not None:
        receivers = regex.findall("[\S]+@[\S]+", helpdesk.strip(), flags=regex.UNICODE | regex.LOCALE)
    if len(receivers) == 0:
        if _is_public_database:
            receivers = [u"*****@*****.**"]

    receiver_string = wx.GetTextFromUser(
        message=_(
            "Edit the list of email addresses to send the\n"
            "bug report to (separate addresses by spaces).\n"
            "\n"
            "Note that <*****@*****.**> refers to\n"
            "the public (!) GNUmed bugs mailing list."
        ),
        caption=_("Sending bug report"),
        default_value=",".join(receivers),
        parent=parent,
    )
    if receiver_string.strip() == u"":
        return

    receivers = regex.findall("[\S]+@[\S]+", receiver_string, flags=regex.UNICODE | regex.LOCALE)

    dlg = gmGuiHelpers.c2ButtonQuestionDlg(
        parent,
        -1,
        caption=_("Sending bug report"),
        question=_(
            "Your bug report will be sent to:\n"
            "\n"
            "%s\n"
            "\n"
            "Make sure you have reviewed the log file for potentially\n"
            "sensitive information before sending out the bug report.\n"
            "\n"
            "Note that emailing the report may take a while depending\n"
            "on the speed of your internet connection.\n"
        )
        % u"\n".join(receivers),
        button_defs=[
            {"label": _("Send report"), "tooltip": _("Yes, send the bug report.")},
            {"label": _("Cancel"), "tooltip": _("No, do not send the bug report.")},
        ],
        show_checkbox=True,
        checkbox_msg=_("include log file in bug report"),
    )
    dlg._CHBOX_dont_ask_again.SetValue(_is_public_database)
    go_ahead = dlg.ShowModal()
    if go_ahead == wx.ID_NO:
        dlg.Destroy()
        return

    include_log = dlg._CHBOX_dont_ask_again.GetValue()
    if not _is_public_database:
        if include_log:
            result = gmGuiHelpers.gm_show_question(
                _(
                    "The database you are connected to is marked as\n"
                    '"in-production with controlled access".\n'
                    "\n"
                    "You indicated that you want to include the log\n"
                    "file in your bug report. While this is often\n"
                    "useful for debugging the log file might contain\n"
                    "bits of patient data which must not be sent out\n"
                    "without de-identification.\n"
                    "\n"
                    "Please confirm that you want to include the log !"
                ),
                _("Sending bug report"),
            )
            include_log = result is True

    if sender is None:
        sender = _("<not supplied>")
    else:
        if sender.strip() == u"":
            sender = _("<not supplied>")

    msg = u"""\
Report sent via GNUmed's handler for unexpected exceptions.

user comment  : %s

client version: %s

system account: %s
staff member  : %s
sender email  : %s

 # enable Launchpad bug tracking
 affects gnumed
 tag automatic-report
 importance medium

""" % (
        comment,
        _client_version,
        _local_account,
        _staff_name,
        sender,
    )
    if include_log:
        _log2.error(comment)
        _log2.warning("syncing log file for emailing")
        gmLog2.flush()
        attachments = [[_logfile_name, "text/plain", "quoted-printable"]]
    else:
        attachments = None

    dlg.Destroy()

    wx.BeginBusyCursor()
    try:
        gmNetworkTools.send_mail(
            sender="%s <%s>" % (_staff_name, gmNetworkTools.default_mail_sender),
            receiver=receivers,
            subject=u"<bug>: %s" % comment,
            message=msg,
            encoding=gmI18N.get_encoding(),
            server=gmNetworkTools.default_mail_server,
            auth={"user": gmNetworkTools.default_mail_sender, "password": u"gnumed-at-gmx-net"},
            attachments=attachments,
        )
        gmDispatcher.send(signal="statustext", msg=_("Bug report has been emailed."))
    except:
        _log2.exception("cannot send bug report")
        gmDispatcher.send(signal="statustext", msg=_("Bug report COULD NOT be emailed."))
    wx.EndBusyCursor()
Exemplo n.º 18
0
def run_report_query(query=None, limit=None, pk_identity=None):
	"""Returns (status, hint, cols, rows)"""

	PATIENT_ID_TOKEN = '$<ID_ACTIVE_PATIENT>$'
	if limit is None:
		limit = ''
	else:
		limit = 'LIMIT %s' % limit

	# does user want to insert current patient ID ?
	if query.find(PATIENT_ID_TOKEN) == -1:
		wrapper_query = """
			SELECT * FROM (
				%%s
			) AS user_query
			%s
		""" % limit
	else:
		# she does, but is it possible ?
		if pk_identity is None:
			gmDispatcher.send('statustext', msg = _('Query needs active patient.'), beep = True)
			cols = [_('Error')]
			rows = [
				[_('Active patient query')],
				[''],
				[_('This query requires a patient to be active in the client.')],
				[''],
				[_('Please activate the patient you are interested')],
				[_('in and re-run the query.')]
			]
			return (False, 'pk_identity', cols, rows)

		query = query.replace(PATIENT_ID_TOKEN, str(pk_identity))
		wrapper_query = """
			SELECT %s AS pk_patient, * FROM (
				%%s
			) AS user_query
			%s
		""" % (pk_identity, limit)

	wrapped_query = wrapper_query % query
	_log.debug('running report query:')
	_log.debug(wrapped_query)

	try:
		# read-only for safety reasons
		rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': wrapped_query}], get_col_idx = True)
	except Exception:
		_log.exception('report query failed')
		gmDispatcher.send('statustext', msg = _('The query failed.'), beep = True)
		cols = [_('Error')]
		t, v = sys.exc_info()[:2]
		rows = [
			[_('The query failed.')],
			[''],
			[str(t)]
		]
		for line in str(v).decode(gmI18N.get_encoding()).split('\n'):
			rows.append([line])
		rows.append([''])
		for line in query.split('\n'):
			rows.append([line])
		return (False, 'query failed', cols, rows)

	# swap (col_name, col_idx) to (col_idx, col_name)
	# and sort them according to position-in-query
	cols = [ (value, key) for key, value in idx.items() ]
	cols.sort()
	cols = [ pair[1] for pair in cols ]

	return (True, None, cols, rows)
Exemplo n.º 19
0
#==================================================================
if __name__ == '__main__':

	_cfg = gmCfg2.gmCfgData()

	_cfg.add_cli(long_options = ['text-domain=', 'lang-gettext=', 'conf-file='])
	td = _cfg.get(option = '--text-domain', source_order = [('cli', 'return')])
	l = _cfg.get(option = '--lang-gettext', source_order = [('cli', 'return')])
	gmI18N.activate_locale()
	gmI18N.install_domain(domain = td, language = l)

	_cfg.add_file_source (
		source = 'explicit',
		file = _cfg.get(option = '--conf-file', source = [('cli', 'return')]),
		encoding = gmI18N.get_encoding()
	)

	connector = cBaseConnector()
	if not connector.connect():
		sys.exit('connect() error')
	if not connector.setup():
		connector.cleanup()
		sys.exit('setup() error')
	if not connector.run_script():
		connector.cleanup()
		sys.exit('run_script() error')
	connector.cleanup()

#==================================================================
Exemplo n.º 20
0
def mail_log(parent=None, comment=None, helpdesk=None, sender=None):

		if (comment is None) or (comment.strip() == u''):
			comment = wx.GetTextFromUser (
				message = _(
					'Please enter a short note on what you\n'
					'were about to do in GNUmed:'
				),
				caption = _('Sending bug report'),
				parent = parent
			)
			if comment.strip() == u'':
				comment = u'<user did not comment on bug report>'

		receivers = []
		if helpdesk is not None:
			receivers = regex.findall (
				'[\S]+@[\S]+',
				helpdesk.strip(),
				flags = regex.UNICODE | regex.LOCALE
			)
		if len(receivers) == 0:
			if _is_public_database:
				receivers = [u'*****@*****.**']

		receiver_string = wx.GetTextFromUser (
			message = _(
				'Edit the list of email addresses to send the\n'
				'bug report to (separate addresses by spaces).\n'
				'\n'
				'Note that <*****@*****.**> refers to\n'
				'the public (!) GNUmed bugs mailing list.'
			),
			caption = _('Sending bug report'),
			default_value = ','.join(receivers),
			parent = parent
		)
		if receiver_string.strip() == u'':
			return

		receivers = regex.findall (
			'[\S]+@[\S]+',
			receiver_string,
			flags = regex.UNICODE | regex.LOCALE
		)

		dlg = gmGuiHelpers.c2ButtonQuestionDlg (
			parent,
			-1,
			caption = _('Sending bug report'),
			question = _(
				'Your bug report will be sent to:\n'
				'\n'
				'%s\n'
				'\n'
				'Make sure you have reviewed the log file for potentially\n'
				'sensitive information before sending out the bug report.\n'
				'\n'
				'Note that emailing the report may take a while depending\n'
				'on the speed of your internet connection.\n'
			) % u'\n'.join(receivers),
			button_defs = [
				{'label': _('Send report'), 'tooltip': _('Yes, send the bug report.')},
				{'label': _('Cancel'), 'tooltip': _('No, do not send the bug report.')}
			],
			show_checkbox = True,
			checkbox_msg = _('include log file in bug report')
		)
		dlg._CHBOX_dont_ask_again.SetValue(_is_public_database)
		go_ahead = dlg.ShowModal()
		if go_ahead == wx.ID_NO:
			dlg.Destroy()
			return

		include_log = dlg._CHBOX_dont_ask_again.GetValue()
		if not _is_public_database:
			if include_log:
				result = gmGuiHelpers.gm_show_question (
					_(
						'The database you are connected to is marked as\n'
						'"in-production with controlled access".\n'
						'\n'
						'You indicated that you want to include the log\n'
						'file in your bug report. While this is often\n'
						'useful for debugging the log file might contain\n'
						'bits of patient data which must not be sent out\n'
						'without de-identification.\n'
						'\n'
						'Please confirm that you want to include the log !'
					),
					_('Sending bug report')
				)
				include_log = (result is True)

		if sender is None:
			sender = _('<not supplied>')
		else:
			if sender.strip() == u'':
				sender = _('<not supplied>')

		msg = u"""\
Report sent via GNUmed's handler for unexpected exceptions.

user comment  : %s

client version: %s

system account: %s
staff member  : %s
sender email  : %s

 # enable Launchpad bug tracking
 affects gnumed
 tag automatic-report
 importance medium

""" % (comment, _client_version, _local_account, _staff_name, sender)
		if include_log:
			_log2.error(comment)
			_log2.warning('syncing log file for emailing')
			gmLog2.flush()
			attachments = [ [_logfile_name, 'text/plain', 'quoted-printable'] ]
		else:
			attachments = None

		dlg.Destroy()

		wx.BeginBusyCursor()
		try:
			gmNetworkTools.send_mail (
				sender = '%s <%s>' % (_staff_name, gmNetworkTools.default_mail_sender),
				receiver = receivers,
				subject = u'<bug>: %s' % comment,
				message = msg,
				encoding = gmI18N.get_encoding(),
				server = gmNetworkTools.default_mail_server,
				auth = {'user': gmNetworkTools.default_mail_sender, 'password': u'gnumed-at-gmx-net'},
				attachments = attachments
			)
			gmDispatcher.send(signal='statustext', msg = _('Bug report has been emailed.'))
		except:
			_log2.exception('cannot send bug report')
			gmDispatcher.send(signal='statustext', msg = _('Bug report COULD NOT be emailed.'))
		wx.EndBusyCursor()
Exemplo n.º 21
0

#==================================================================
if __name__ == '__main__':

    _cfg = gmCfg2.gmCfgData()

    _cfg.add_cli(long_options=['text-domain=', 'lang-gettext=', 'conf-file='])
    td = _cfg.get(option='--text-domain', source_order=[('cli', 'return')])
    l = _cfg.get(option='--lang-gettext', source_order=[('cli', 'return')])
    gmI18N.activate_locale()
    gmI18N.install_domain(domain=td, language=l)

    _cfg.add_file_source(source='explicit',
                         file=_cfg.get(option='--conf-file',
                                       source=[('cli', 'return')]),
                         encoding=gmI18N.get_encoding())

    connector = cBaseConnector()
    if not connector.connect():
        sys.exit('connect() error')
    if not connector.setup():
        connector.cleanup()
        sys.exit('setup() error')
    if not connector.run_script():
        connector.cleanup()
        sys.exit('run_script() error')
    connector.cleanup()

#==================================================================
Exemplo n.º 22
0
    def __refresh_waiting_list(self):
        self.__id_most_recently_activated_patient = None
        col, ascending = self._LCTRL_patients.GetSortState(
        )  # preserve sorting order

        praxis = gmPraxis.gmCurrentPraxisBranch()
        pats = praxis.waiting_list_patients

        # set matcher to all zones currently in use
        zones = {}
        zones.update([[p['waiting_zone'], None] for p in pats
                      if p['waiting_zone'] is not None])
        self._PRW_zone.update_matcher(items=zones.keys())

        # filter patient list by zone and set waiting list
        self.__current_zone = self._PRW_zone.GetValue().strip()
        if self.__current_zone == u'':
            pats = [p for p in pats]
        else:
            pats = [
                p for p in pats if p['waiting_zone'] == self.__current_zone
            ]

        # filter by "active patient only"
        curr_pat = gmPerson.gmCurrentPatient()
        if curr_pat.connected:
            if self._CHBOX_active_patient_only.IsChecked():
                pats = [p for p in pats if p['pk_identity'] == curr_pat.ID]

        old_pks = [
            d['pk_waiting_list']
            for d in self._LCTRL_patients.get_selected_item_data()
        ]
        self._LCTRL_patients.set_string_items([[
            gmTools.coalesce(p['waiting_zone'], u''), p['urgency'],
            gmDateTime.pydt_strftime(p['registered'], format='%Y %b %d %H:%M'),
            gmDateTime.format_interval_medically(p['waiting_time']),
            u'%s, %s (%s)' %
            (p['lastnames'], p['firstnames'], p['l10n_gender']),
            gmTools.coalesce(gmTools.coalesce(p['dob'],
                                              u'',
                                              function_initial=('strftime',
                                                                '%d %b %Y')),
                             u'',
                             function_initial=('decode',
                                               gmI18N.get_encoding())),
            gmTools.coalesce(p['comment'], u'').split('\n')[0]
        ] for p in pats])
        self._LCTRL_patients.set_column_widths()
        self._LCTRL_patients.set_data(pats)
        new_selections = []
        new_pks = [p['pk_waiting_list'] for p in pats]
        for old_pk in old_pks:
            if old_pk in new_pks:
                new_selections.append(new_pks.index(old_pk))
        self._LCTRL_patients.selections = new_selections
        self._LCTRL_patients.Refresh()
        self._LCTRL_patients.SortListItems(col, ascending)  # re-sort

        self._LBL_no_of_patients.SetLabel(_('(%s patients)') % len(pats))

        if len(pats) == 0:
            self._BTN_activate.Enable(False)
            self._BTN_activateplus.Enable(False)
            self._BTN_remove.Enable(False)
            self._BTN_edit.Enable(False)
            self._BTN_up.Enable(False)
            self._BTN_down.Enable(False)
        else:
            self._BTN_activate.Enable(True)
            self._BTN_activateplus.Enable(True)
            self._BTN_remove.Enable(True)
            self._BTN_edit.Enable(True)
        if len(pats) > 1:
            self._BTN_up.Enable(True)
            self._BTN_down.Enable(True)
Exemplo n.º 23
0
	def __update_age_label(self):

		# no patient
		if not self.curr_pat.connected:
			self._LBL_age.SetLabel(_('<Age>'))
			self._LBL_age.SetToolTipString(_('no patient selected'))
			return

		# gender is always known
		tt = _(u'Gender: %s (%s) - %s\n') % (
			self.curr_pat.gender_symbol,
			gmTools.coalesce(self.curr_pat[u'gender'], u'?'),
			self.curr_pat.gender_string
		)

		# dob is not known
		if self.curr_pat['dob'] is None:
			age = u'%s  %s' % (
				self.curr_pat.gender_symbol,
				self.curr_pat.get_formatted_dob()
			)
			self._LBL_age.SetLabel(age)
			self._LBL_age.SetToolTipString(tt)
			return

		tt += _('Born: %s\n') % self.curr_pat.get_formatted_dob(format = '%d %b %Y', encoding = gmI18N.get_encoding())

		# patient is dead
		if self.curr_pat['deceased'] is not None:
			tt += _('Died: %s\n') % gmDateTime.pydt_strftime(self.curr_pat['deceased'], '%d %b %Y')
			tt += _('At age: %s\n') % self.curr_pat['medical_age']
			age = u'%s  %s - %s (%s)' % (
				self.curr_pat.gender_symbol,
				self.curr_pat.get_formatted_dob(format = '%d %b %Y', encoding = gmI18N.get_encoding()),
				gmDateTime.pydt_strftime(self.curr_pat['deceased'], '%d %b %Y'),
				self.curr_pat['medical_age']
			)
			if self.curr_pat['dob_is_estimated']:
				tt += _(' (date of birth and age are estimated)\n')
			self._LBL_age.SetLabel(age)
			self._LBL_age.SetToolTipString(tt)
			return

		# patient alive
		now = gmDateTime.pydt_now_here()

		# patient birthday ?
		if self.curr_pat.get_formatted_dob(format = '%m-%d') == now.strftime('%m-%d'):
			template = _('%(sex)s  %(dob)s (%(age)s today !)')
			tt += _("\nToday is the patient's birthday !\n\n")
		else:
			if self.curr_pat.current_birthday_passed():
				template = u'%(sex)s  %(dob)s%(l_arr)s (%(age)s)'
				tt += _(u'Birthday: %s ago\n') % gmDateTime.format_apparent_age_medically (
					age = gmDateTime.calculate_apparent_age(start = self.curr_pat.birthday_this_year, end = now)
				)
			else:
				template = u'%(sex)s  %(r_arr)s%(dob)s (%(age)s)'
				tt += _(u'Birthday: in %s\n') % gmDateTime.format_apparent_age_medically (
					age = gmDateTime.calculate_apparent_age(start = now, end = self.curr_pat.birthday_this_year)
				)

		tt += _('Age: %s\n') % self.curr_pat['medical_age']

		# FIXME: if the age is below, say, 2 hours we should fire
		# a timer here that updates the age in increments of 1 minute ... :-)
		age = template % {
			u'sex': self.curr_pat.gender_symbol,
			u'dob': self.curr_pat.get_formatted_dob(format = '%d %b %Y', encoding = gmI18N.get_encoding()),
			u'age': self.curr_pat['medical_age'],
			u'r_arr': gmTools.u_right_arrow,
			u'l_arr': gmTools.u_left_arrow
		}

		# Easter Egg ;-)
		if self.curr_pat['lastnames'] == u'Leibner':
			if self.curr_pat['firstnames'] == u'Steffi':
				if self.curr_pat['preferred'] == u'Wildfang':
					age = u'%s %s' % (gmTools.u_black_heart, age)

		if self.curr_pat['dob_is_estimated']:
			tt += _(' (date of birth and age are estimated)\n')

		self._LBL_age.SetLabel(age)
		self._LBL_age.SetToolTipString(tt)