Example #1
0
def load_person_from_vcard_file():

	wildcards = '|'.join ([
		'%s (*.vcf)|*.vcf' % _('vcf files'),
		'%s (*.VCF)|*.VCF' % _('VCF files'),
		'%s (*)|*' % _('all files'),
		'%s (*.*)|*.*' % _('all files (Windows)')
	])

	dlg = wx.FileDialog (
		parent = wx.GetApp().GetTopWindow(),
		message = _('Choose a vCard file:'),
		defaultDir = os.path.join(gmTools.gmPaths().home_dir, 'gnumed'),
		wildcard = wildcards,
		style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST
	)
	result = dlg.ShowModal()
	fname = dlg.GetPath()
	dlg.DestroyLater()
	if result == wx.ID_CANCEL:
		return

	from Gnumed.business import gmVCard
	dto = gmVCard.parse_vcard2dto(filename = fname)
	if dto is None:
		gmDispatcher.send(signal='statustext', msg=_('[%s] does not seem to contain a vCard.') % fname)
		return

	idents = dto.get_candidate_identities(can_create = True)
	if len(idents) == 1:
		ident = idents[0]
		if not set_active_patient(patient = ident):
			gmGuiHelpers.gm_show_info (_(
				'Cannot activate patient:\n\n'
				'%s %s (%s)\n'
				'%s'
				) % (
					dto.firstnames, dto.lastnames, dto.gender, gmDateTime.pydt_strftime(dto.dob, '%Y %b %d')
				),
				_('Activating external patient')
			)
		return

	dlg = cSelectPersonFromListDlg(wx.GetApp().GetTopWindow(), -1)
	dlg.set_persons(persons = idents)
	result = dlg.ShowModal()
	ident = dlg.get_selected_person()
	dlg.DestroyLater()
	if result == wx.ID_CANCEL:
		return
	if not set_active_patient(patient = ident):
		gmGuiHelpers.gm_show_info (_(
			'Cannot activate patient:\n\n'
			'%s %s (%s)\n'
			'%s'
			) % (
				dto.firstnames, dto.lastnames, dto.gender, gmDateTime.pydt_strftime(dto.dob, '%Y %b %d')
			),
			_('Activating external patient')
		)
Example #2
0
def load_person_from_vcard_file():

	wildcards = '|'.join ([
		'%s (*.vcf)|*.vcf' % _('vcf files'),
		'%s (*.VCF)|*.VCF' % _('VCF files'),
		'%s (*)|*' % _('all files'),
		'%s (*.*)|*.*' % _('all files (Windows)')
	])

	dlg = wx.FileDialog (
		parent = wx.GetApp().GetTopWindow(),
		message = _('Choose a vCard file:'),
		defaultDir = os.path.join(gmTools.gmPaths().home_dir, 'gnumed'),
		wildcard = wildcards,
		style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST
	)
	result = dlg.ShowModal()
	fname = dlg.GetPath()
	dlg.DestroyLater()
	if result == wx.ID_CANCEL:
		return

	from Gnumed.business import gmVCard
	dto = gmVCard.parse_vcard2dto(filename = fname)
	if dto is None:
		gmDispatcher.send(signal='statustext', msg=_('[%s] does not seem to contain a vCard.') % fname)
		return

	idents = dto.get_candidate_identities(can_create = True)
	if len(idents) == 1:
		ident = idents[0]
		if not set_active_patient(patient = ident):
			gmGuiHelpers.gm_show_info (_(
				'Cannot activate patient:\n\n'
				'%s %s (%s)\n'
				'%s'
				) % (
					dto.firstnames, dto.lastnames, dto.gender, gmDateTime.pydt_strftime(dto.dob, '%Y %b %d')
				),
				_('Activating external patient')
			)
		return

	dlg = cSelectPersonFromListDlg(wx.GetApp().GetTopWindow(), -1)
	dlg.set_persons(persons = idents)
	result = dlg.ShowModal()
	ident = dlg.get_selected_person()
	dlg.DestroyLater()
	if result == wx.ID_CANCEL:
		return
	if not set_active_patient(patient = ident):
		gmGuiHelpers.gm_show_info (_(
			'Cannot activate patient:\n\n'
			'%s %s (%s)\n'
			'%s'
			) % (
				dto.firstnames, dto.lastnames, dto.gender, gmDateTime.pydt_strftime(dto.dob, '%Y %b %d')
			),
			_('Activating external patient')
		)
Example #3
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)
Example #4
0
    def _get_data_tooltip(self):
        if len(self._data) == 0:
            return ''

        date = self.GetData()
        # if match provider only provided completions
        # but not a full date with it
        if date is None:
            return ''

        now = gmDateTime.pydt_now_here()
        if date > now:
            intv = date - now
            template = _('%s\n (a %s in %s)')
        else:
            intv = now - date
            template = _('%s\n (a %s %s ago)')
        return template % (
            gmDateTime.pydt_strftime(
                date, format='%B %d %Y -- %c', accuracy=gmDateTime.acc_days),
            gmDateTime.pydt_strftime(
                date, format='%A', accuracy=gmDateTime.acc_days),
            gmDateTime.format_interval(interval=intv,
                                       accuracy_wanted=gmDateTime.acc_days,
                                       verbose=True))
Example #5
0
	def format(self, with_patient=True):
		tt = '%s: %s%s\n' % (
			gmDateTime.pydt_strftime (
				self._payload[self._idx['received_when']],
				format = '%A, %Y %b %d, %H:%M',
				accuracy = gmDateTime.acc_minutes
			),
			gmTools.bool2subst(self._payload[self._idx['is_virtual']], _('virtual message'), _('message')),
			gmTools.coalesce(self._payload[self._idx['pk_inbox_message']], '', ' #%s ')
		)

		tt += '%s: %s\n' % (
			self._payload[self._idx['l10n_category']],
			self._payload[self._idx['l10n_type']]
		)

		tt += '%s %s %s\n' % (
			self._payload[self._idx['modified_by']],
			gmTools.u_arrow2right,
			gmTools.coalesce(self._payload[self._idx['provider']], _('everyone'))
		)

		tt += '\n%s%s%s\n\n' % (
			gmTools.u_left_double_angle_quote,
			self._payload[self._idx['comment']],
			gmTools.u_right_double_angle_quote
		)

		if with_patient and (self._payload[self._idx['pk_patient']] is not None):
			tt += _('Patient: %s, %s%s %s   #%s\n' % (
				self._payload[self._idx['lastnames']],
				self._payload[self._idx['firstnames']],
				gmTools.coalesce(self._payload[self._idx['l10n_gender']], '', ' (%s)'),
				gmDateTime.pydt_strftime(self._payload[self._idx['dob']], '%Y %b %d', none_str = ''),
				self._payload[self._idx['pk_patient']]
			))

		if self._payload[self._idx['due_date']] is not None:
			if self._payload[self._idx['is_overdue']]:
				template = _('Due: %s (%s ago)\n')
			else:
				template = _('Due: %s (in %s)\n')
			tt += template % (
				gmDateTime.pydt_strftime(self._payload[self._idx['due_date']], '%Y %b %d'),
				gmDateTime.format_interval_medically(self._payload[self._idx['interval_due']])
			)

		if self._payload[self._idx['expiry_date']] is not None:
			if self._payload[self._idx['is_expired']]:
				template = _('Expired: %s\n')
			else:
				template = _('Expires: %s\n')
			tt += template % gmDateTime.pydt_strftime(self._payload[self._idx['expiry_date']], '%Y %b %d')

		if self._payload[self._idx['data']] is not None:
			tt += self._payload[self._idx['data']][:150]
			if len(self._payload[self._idx['data']]) > 150:
				tt += gmTools.u_ellipsis

		return tt
Example #6
0
	def _refresh_dupe_warning(self):
		lname = self._PRW_lastname.GetValue().strip()
		if lname == '':
			self._LBL_person_exists.SetLabel('')
			return

		dob = self._PRW_dob.GetData()
		if dob is None:
			self._LBL_person_exists.SetLabel('')
			return

		fname = gmTools.none_if(self._PRW_firstnames.GetValue().strip()[:1], '')

		no_of_dupes = gmPerson.get_potential_person_dupes(lastnames = lname, firstnames = fname, dob = dob)
		if no_of_dupes == 0:
			lbl = ''
		elif no_of_dupes == 1:
			lbl = _('One "%s, %s (%s)" already exists !') % (
				lname,
				gmTools.coalesce(fname, '?', '%s %%s. %s' % (gmTools.u_ellipsis, gmTools.u_ellipsis)),
				gmDateTime.pydt_strftime(dob, '%Y %b %d', 'utf8')
			)
		else:
			lbl = _('%s "%s, %s (%s)" already exist !') % (
				no_of_dupes,
				lname,
				gmTools.coalesce(fname, '?', '%s %%s. %s' % (gmTools.u_ellipsis, gmTools.u_ellipsis)),
				gmDateTime.pydt_strftime(dob, '%Y %b %d', 'utf8')
			)

		self._LBL_person_exists.SetLabel(lbl)
Example #7
0
    def _get_data_tooltip(self):
        if len(self._data) == 0:
            return ''

        date = self.GetData()
        # if match provider only provided completions
        # but not a full date with it
        if date is None:
            return ''

        if isinstance(date, pyDT.datetime):
            date = pyDT.date(date.year, date.month, date.day)
        today = pyDT.date.today()
        if date > today:
            intv = date - today
            return _('%s\n (a %s in %s)') % (
                date.strftime(format='%B %d %Y -- %x'),
                date.strftime(format='%A'),
                gmDateTime.format_interval(interval=intv,
                                           accuracy_wanted=gmDateTime.acc_days,
                                           verbose=True))

        if date < today:
            intv = today - date
            return _('%s\n (a %s %s ago)') % (
                gmDateTime.pydt_strftime(date, format='%B %d %Y -- %x'),
                gmDateTime.pydt_strftime(date, format='%A'),
                gmDateTime.format_interval(interval=intv,
                                           accuracy_wanted=gmDateTime.acc_days,
                                           verbose=True))

        return _('today (%s): %s') % (
            gmDateTime.pydt_strftime(date, format='%A'),
            gmDateTime.pydt_strftime(date, format='%B %d %Y -- %x'))
Example #8
0
    def _refresh_dupe_warning(self):
        lname = self._PRW_lastname.GetValue().strip()
        if lname == '':
            self._LBL_person_exists.SetLabel('')
            return

        dob = self._PRW_dob.GetData()
        if dob is None:
            self._LBL_person_exists.SetLabel('')
            return

        #fname = gmTools.none_if(self._PRW_firstnames.GetValue().strip()[:1], '')
        fname = gmTools.none_if(self._PRW_firstnames.GetValue().strip(), '')
        no_of_dupes = gmPerson.get_potential_person_dupes(lastnames=lname,
                                                          firstnames=fname,
                                                          dob=dob)
        if no_of_dupes == 0:
            lbl = ''
        elif no_of_dupes == 1:
            lbl = _('A (one) "%s, %s (%s)" already exists.') % (
                lname,
                gmTools.coalesce(
                    fname, '?', '%s %%s%s %s' %
                    (gmTools.u_ellipsis, gmTools.u_ellipsis,
                     gmTools.u_ellipsis)),
                gmDateTime.pydt_strftime(dob, '%Y %b %d', 'utf8'))
        else:
            lbl = _('%s "%s, %s (%s)" already exist.') % (
                no_of_dupes, lname,
                gmTools.coalesce(
                    fname, '?', '%s %%s%s %s' %
                    (gmTools.u_ellipsis, gmTools.u_ellipsis,
                     gmTools.u_ellipsis)),
                gmDateTime.pydt_strftime(dob, '%Y %b %d', 'utf8'))
        self._LBL_person_exists.SetLabel(lbl)
Example #9
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()
	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(at_date = patient.birthday_this_year).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)
Example #10
0
	def __refresh_meds(self, patient=None):

		emr = patient.get_emr()

		list_items = []
		data_items = []
		first_red = False

		# smoking
		ever, details = emr.smoking_status
		if ever is True:
			if details['quit_when'] is None:
				first_red = True
				list_items.append (
					_('active tobacco use (%s)') % gmDateTime.pydt_strftime(details['last_confirmed'], '%Y %b')
				)
				data_items.append (_(u'Last confirmed: %s%s') % (
					gmDateTime.pydt_strftime(details['last_confirmed'], '%Y %b %d'),
					gmTools.coalesce(details['comment'], u'', u'\n\n%s')
				))

		# list by brand or substance:
		intakes = emr.get_current_substance_intakes(include_inactive = False, include_unapproved = True, order_by = u'substance')
		multi_brands_already_seen = []
		for intake in intakes:
			brand = intake.containing_drug
			if brand is None or len(brand['pk_components']) == 1:
				list_items.append(_('%s %s %s%s') % (
					intake['substance'],
					intake['amount'],
					intake['unit'],
					gmTools.coalesce (
						intake['schedule'],
						u'',
						u': %s'
					)
				))
				data_items.append(intake)
			else:
				if intake['brand'] in multi_brands_already_seen:
					continue
				multi_brands_already_seen.append(intake['brand'])
				list_items.append(_('%s %s%s') % (
					intake['brand'],
					brand['preparation'],
					gmTools.coalesce (
						intake['schedule'],
						u'',
						u': %s'
					)
				))
				data_items.append(intake)

		self._LCTRL_meds.set_string_items(items = list_items)
		self._LCTRL_meds.set_data(data = data_items)

		if first_red:
			self._LCTRL_meds.SetItemTextColour(0, wx.NamedColour('RED'))
Example #11
0
    def format(self, with_patient=True):
        tt = '%s: %s%s\n' % (
            gmDateTime.pydt_strftime(self._payload[self._idx['received_when']],
                                     format='%A, %Y %b %d, %H:%M',
                                     accuracy=gmDateTime.acc_minutes),
            gmTools.bool2subst(self._payload[self._idx['is_virtual']],
                               _('virtual message'), _('message')),
            gmTools.coalesce(self._payload[self._idx['pk_inbox_message']], '',
                             ' #%s '))

        tt += '%s: %s\n' % (self._payload[self._idx['l10n_category']],
                            self._payload[self._idx['l10n_type']])

        tt += '%s %s %s\n' % (
            self._payload[self._idx['modified_by']], gmTools.u_arrow2right,
            gmTools.coalesce(self._payload[self._idx['provider']],
                             _('everyone')))

        tt += '\n%s%s%s\n\n' % (gmTools.u_left_double_angle_quote,
                                self._payload[self._idx['comment']],
                                gmTools.u_right_double_angle_quote)

        if with_patient and (self._payload[self._idx['pk_patient']]
                             is not None):
            tt += _(
                'Patient: %s, %s%s %s   #%s\n' %
                (self._payload[self._idx['lastnames']],
                 self._payload[self._idx['firstnames']],
                 gmTools.coalesce(self._payload[self._idx['l10n_gender']], '',
                                  ' (%s)'),
                 gmDateTime.pydt_strftime(
                     self._payload[self._idx['dob']], '%Y %b %d',
                     none_str=''), self._payload[self._idx['pk_patient']]))

        if self._payload[self._idx['due_date']] is not None:
            if self._payload[self._idx['is_overdue']]:
                template = _('Due: %s (%s ago)\n')
            else:
                template = _('Due: %s (in %s)\n')
            tt += template % (gmDateTime.pydt_strftime(
                self._payload[self._idx['due_date']], '%Y %b %d'),
                              gmDateTime.format_interval_medically(
                                  self._payload[self._idx['interval_due']]))

        if self._payload[self._idx['expiry_date']] is not None:
            if self._payload[self._idx['is_expired']]:
                template = _('Expired: %s\n')
            else:
                template = _('Expires: %s\n')
            tt += template % gmDateTime.pydt_strftime(
                self._payload[self._idx['expiry_date']], '%Y %b %d')

        if self._payload[self._idx['data']] is not None:
            tt += self._payload[self._idx['data']][:150]
            if len(self._payload[self._idx['data']]) > 150:
                tt += gmTools.u_ellipsis

        return tt
Example #12
0
	def __update_allergies(self, **kwargs):

		show_red = True

		emr = self.curr_pat.get_emr()
		state = emr.allergy_state

		# state in tooltip
		if state['last_confirmed'] is None:
			confirmed = _('never')
		else:
			confirmed = gmDateTime.pydt_strftime(state['last_confirmed'], '%Y %b %d')
		tt = (state.state_string + (90 * u' '))[:90] + u'\n'
		tt += _('last confirmed %s\n') % confirmed
		tt += gmTools.coalesce(state['comment'], u'', _('Comment (%s): %%s') % state['modified_by'])
		tt += u'\n'

		# allergies
		display = []
		for allergy in emr.get_allergies():
			# in field: "true" allergies only, not intolerances
			if allergy['type'] == u'allergy':
				display.append(allergy['descriptor'][:10].strip() + gmTools.u_ellipsis)
			# in tooltip
			if allergy['definite']:
				certainty = _('definite')
			else:
				certainty = _('suspected')
			reaction = gmTools.coalesce(allergy['reaction'], _('reaction not recorded'))
			if len(reaction) > 50:
				reaction = reaction[:50] + gmTools.u_ellipsis
			tt += u'%s (%s, %s): %s\n' % (
				allergy['descriptor'],
				allergy['l10n_type'],
				certainty,
				reaction
			)

		if len(display) == 0:
			display = state.state_symbol
			if display == gmTools.u_diameter:
				show_red = False
		else:
			display = ','.join(display)

		if state['last_confirmed'] is not None:
			display += gmDateTime.pydt_strftime(state['last_confirmed'], ' (%Y %b)')

		if show_red:
			self._LBL_allergies.SetForegroundColour('red')
			self._TCTRL_allergies.SetForegroundColour('red')
		else:
			self._LBL_allergies.SetForegroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT))
			self._TCTRL_allergies.SetForegroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT))

		self._TCTRL_allergies.SetValue(display)
		self._TCTRL_allergies.SetToolTipString(tt)
Example #13
0
	def __update_lab(self):

		if not self.curr_pat.connected:
			self._LBL_lab.SetLabel(u'')
			return

		tests2show = []

		rr = self.curr_pat.emr.get_most_recent_results(loinc = gmLOINC.LOINC_rr_quantity, no_of_results = 1)
		if rr is None:
			tests2show.append(_(u'RR ?'))
		else:
			#tests2show.append(_(u'%s%s') % (rr['unified_val'], rr['val_unit']))
			tests2show.append(rr['unified_val'])

		hr = self.curr_pat.emr.get_most_recent_results(loinc = gmLOINC.LOINC_heart_rate_quantity, no_of_results = 1)
		if hr is not None:
			tests2show.append(u'%s %s' % (hr['abbrev_tt'], hr['unified_val']))

		bmi = self.curr_pat.emr.bmi
		if bmi.numeric_value is not None:
			tests2show.append(_(u'BMI %s') % bmi.numeric_value.quantize(decimal.Decimal('1.')))
		else:
			weight = self.curr_pat.emr.get_most_recent_results(loinc = gmLOINC.LOINC_weight, no_of_results = 1)
			if weight is None:
				tests2show.append(_(u'BMI ?'))
			else:
				tests2show.append(u'%s%s' % (weight['unified_val'], weight['val_unit']))

		gfr_or_crea = self.curr_pat.emr.best_gfr_or_crea
		if gfr_or_crea is None:
			tests2show.append(_(u'GFR ?'))
		else:
			try:
				tests2show.append(_(u'GFR %s') % gfr_or_crea.numeric_value.quantize(decimal.Decimal('1.')))
			except AttributeError:
				tests2show.append(u'%s %s' % (gfr_or_crea['abbrev_tt'], gfr_or_crea['unified_val']))

		edc = self.curr_pat.emr.EDC
		if edc is not None:
			if self.curr_pat.emr.EDC_is_fishy:
				tests2show.append(_(u'?EDC %s') % gmDateTime.pydt_strftime(edc, '%Y-%b-%d', accuracy = gmDateTime.acc_days))
			else:
				tests2show.append(_(u'EDC %s') % gmDateTime.pydt_strftime(edc, '%Y-%b-%d', accuracy = gmDateTime.acc_days))

		inr = self.curr_pat.emr.get_most_recent_results(loinc = gmLOINC.LOINC_inr_quantity, no_of_results = 1)
		if inr is not None:
			tests2show.append(u'%s %s' % (hr['abbrev_tt'], hr['unified_val']))

		# include panel if configured, only show if exist
		if self.__lab_panel is not None:
			for result in self.__lab_panel.get_most_recent_results(pk_patient = self.curr_pat.ID, order_by = u'unified_abbrev', group_by_meta_type = True):
				tests2show.append(u'%s %s' % (result['abbrev_tt'], result['unified_val']))

		self._LBL_lab.SetLabel(u'; '.join(tests2show))
Example #14
0
	def __update_lab(self):

		if not self.curr_pat.connected:
			self._LBL_lab.SetLabel(u'')
			return

		tests2show = []

		rr = self.curr_pat.emr.get_most_recent_results(loinc = gmLOINC.LOINC_rr_quantity, no_of_results = 1)
		if rr is None:
			tests2show.append(_(u'RR ?'))
		else:
			#tests2show.append(_(u'%s%s') % (rr['unified_val'], rr['val_unit']))
			tests2show.append(rr['unified_val'])

		hr = self.curr_pat.emr.get_most_recent_results(loinc = gmLOINC.LOINC_heart_rate_quantity, no_of_results = 1)
		if hr is not None:
			tests2show.append(u'%s %s' % (hr['abbrev_tt'], hr['unified_val']))

		bmi = self.curr_pat.emr.bmi
		if bmi.numeric_value is not None:
			tests2show.append(_(u'BMI %s') % bmi.numeric_value.quantize(decimal.Decimal('1.')))
		else:
			weight = self.curr_pat.emr.get_most_recent_results(loinc = gmLOINC.LOINC_weight, no_of_results = 1)
			if weight is None:
				tests2show.append(_(u'BMI ?'))
			else:
				tests2show.append(u'%s%s' % (weight['unified_val'], weight['val_unit']))

		gfr_or_crea = self.curr_pat.emr.best_gfr_or_crea
		if gfr_or_crea is None:
			tests2show.append(_(u'GFR ?'))
		else:
			try:
				tests2show.append(_(u'GFR %s') % gfr_or_crea.numeric_value.quantize(decimal.Decimal('1.')))
			except AttributeError:
				tests2show.append(u'%s %s' % (gfr_or_crea['abbrev_tt'], gfr_or_crea['unified_val']))

		edc = self.curr_pat.emr.EDC
		if edc is not None:
			if self.curr_pat.emr.EDC_is_fishy:
				tests2show.append(_(u'?EDC %s') % gmDateTime.pydt_strftime(edc, '%Y-%b-%d', accuracy = gmDateTime.acc_days))
			else:
				tests2show.append(_(u'EDC %s') % gmDateTime.pydt_strftime(edc, '%Y-%b-%d', accuracy = gmDateTime.acc_days))

		inr = self.curr_pat.emr.get_most_recent_results(loinc = gmLOINC.LOINC_inr_quantity, no_of_results = 1)
		if inr is not None:
			tests2show.append(u'%s %s' % (inr['abbrev_tt'], inr['unified_val']))

		# include panel if configured, only show if exist
		if self.__lab_panel is not None:
			for result in self.__lab_panel.get_most_recent_results(pk_patient = self.curr_pat.ID, order_by = u'unified_abbrev', group_by_meta_type = True):
				tests2show.append(u'%s %s' % (result['abbrev_tt'], result['unified_val']))

		self._LBL_lab.SetLabel(u'; '.join(tests2show))
Example #15
0
def _display_clinical_reminders():

    pat = gmPerson.gmCurrentPatient()
    if not pat.connected:
        return

    # reminders
    for msg in pat.overdue_messages:
        if msg['expiry_date'] is None:
            exp = ''
        else:
            exp = _(' - expires %s') % gmDateTime.pydt_strftime(
                msg['expiry_date'], '%Y %b %d', accuracy=gmDateTime.acc_days)
        txt = _('Due for %s (since %s%s):\n'
                '%s'
                '%s'
                '\n'
                'Patient: %s\n'
                'Reminder by: %s') % (
                    gmDateTime.format_interval_medically(msg['interval_due']),
                    gmDateTime.pydt_strftime(msg['due_date'],
                                             '%Y %b %d',
                                             accuracy=gmDateTime.acc_days),
                    exp, gmTools.coalesce(msg['comment'], '', '\n%s\n'),
                    gmTools.coalesce(msg['data'], '', '\n%s\n'),
                    pat.description_gender, msg['modified_by'])
        gmGuiHelpers.gm_show_warning(aTitle=_('Clinical reminder'),
                                     aMessage=txt)

    # dynamic hints
    hints2aggregate = []
    emr = pat.emr
    hint_dlg = cDynamicHintDlg(wx.GetApp().GetTopWindow(), -1)
    # single-hint popups
    for hint in emr.dynamic_hints:
        if hint['popup_type'] == 0:
            continue
        if hint['popup_type'] == 2:
            hints2aggregate.append(hint)
            continue
        hint_dlg.hint = hint
        if hint_dlg.ShowModal() == wx.ID_APPLY:
            hint.suppress(rationale=hint_dlg.rationale.strip(),
                          pk_encounter=emr.current_encounter['pk_encounter'])
    hint_dlg.DestroyLater()
    # aggregate popup
    if len(hints2aggregate) > 0:
        hints_dlg = cDynamicHintListDlg(wx.GetApp().GetTopWindow(), -1)
        hints_dlg.pk_encounter = emr.current_encounter['pk_encounter']
        hints_dlg.hints = hints2aggregate
        hints_dlg.ShowModal()
        hints_dlg.DestroyLater()

    return
Example #16
0
	def __refresh_documents(self, patient=None):

		list_items = []
		list_data = []

		# export area items
		item_count = len(patient.export_area.items)
		if item_count == 1:
			list_items.append(_('Export area: 1 item'))
			list_data.append('')
		if item_count > 1:
			list_items.append(_('Export area: %s items') % item_count)
			list_data.append('')

		doc_folder = patient.get_document_folder()

		# unsigned docs first
		docs = doc_folder.get_unsigned_documents()
		no_of_unsigned = len(docs)
		for doc in docs:
			list_items.append('%s %s (%s)' % (
				gmDateTime.pydt_strftime(doc['clin_when'], format = '%m/%Y', accuracy = gmDateTime.acc_months),
				doc['l10n_type'],
				gmTools.u_writing_hand
			))
			list_data.append(doc)

		# other, signed docs second
		docs = doc_folder.get_documents(order_by = 'ORDER BY clin_when DESC', exclude_unsigned = True)
		for doc in docs[:5]:
			list_items.append('%s %s' % (
				gmDateTime.pydt_strftime(doc['clin_when'], format = '%m/%Y', accuracy = gmDateTime.acc_months),
				doc['l10n_type']
			))
			list_data.append(doc)
		if len(docs) > 5:
			list_items.append(_('%s %s more not shown %s') % (
				gmTools.u_ellipsis,
				len(docs) - 5,
				gmTools.u_ellipsis
			))
			list_data.append('')

		self._LCTRL_documents.set_string_items(items = list_items)
		self._LCTRL_documents.set_data(data = list_data)

		if no_of_unsigned > 0:
			start_idx = 0
			if item_count > 0:
				start_idx = 1
			end_idx = no_of_unsigned + start_idx
			for idx in range(start_idx, end_idx):
				self._LCTRL_documents.SetItemTextColour(idx, wx.Colour('RED'))
Example #17
0
	def __refresh_documents(self, patient=None):

		list_items = []
		list_data = []

		# export area items
		item_count = len(patient.export_area.items)
		if item_count == 1:
			list_items.append(_('Export area: 1 item'))
			list_data.append('')
		if item_count > 1:
			list_items.append(_('Export area: %s items') % item_count)
			list_data.append('')

		doc_folder = patient.get_document_folder()

		# unsigned docs first
		docs = doc_folder.get_unsigned_documents()
		no_of_unsigned = len(docs)
		for doc in docs:
			list_items.append('%s %s (%s)' % (
				gmDateTime.pydt_strftime(doc['clin_when'], format = '%m/%Y', accuracy = gmDateTime.acc_months),
				doc['l10n_type'],
				gmTools.u_writing_hand
			))
			list_data.append(doc)

		# other, signed docs second
		docs = doc_folder.get_documents(order_by = 'ORDER BY clin_when DESC', exclude_unsigned = True)
		for doc in docs[:5]:
			list_items.append('%s %s' % (
				gmDateTime.pydt_strftime(doc['clin_when'], format = '%m/%Y', accuracy = gmDateTime.acc_months),
				doc['l10n_type']
			))
			list_data.append(doc)
		if len(docs) > 5:
			list_items.append(_('%s %s more not shown %s') % (
				gmTools.u_ellipsis,
				len(docs) - 5,
				gmTools.u_ellipsis
			))
			list_data.append('')

		self._LCTRL_documents.set_string_items(items = list_items)
		self._LCTRL_documents.set_data(data = list_data)

		if no_of_unsigned > 0:
			start_idx = 0
			if item_count > 0:
				start_idx = 1
			end_idx = no_of_unsigned + start_idx
			for idx in range(start_idx, end_idx):
				self._LCTRL_documents.SetItemTextColour(idx, wx.Colour('RED'))
Example #18
0
	def get_useful_filename(self, patient=None, make_unique=False, directory=None, include_gnumed_tag=True, date_before_type=False, name_first=True):
		patient_part = ''
		if patient is not None:
			if name_first:
				patient_part = '%s-' % patient.subdir_name
			else:
				patient_part = '-%s' % patient.subdir_name

		# preserve original filename extension if available
		suffix = '.dat'
		if self._payload[self._idx['filename']] is not None:
			tmp, suffix = os.path.splitext (
				gmTools.fname_sanitize(self._payload[self._idx['filename']]).lower()
			)
			if suffix == '':
				suffix = '.dat'

		if include_gnumed_tag:
			fname_template = 'gm_doc-part_%s-%%s' % self._payload[self._idx['seq_idx']]
		else:
			fname_template = '%%s-part_%s' % self._payload[self._idx['seq_idx']]

		if date_before_type:
			date_type_part = '%s-%s' % (
				gmDateTime.pydt_strftime(self._payload[self._idx['date_generated']], '%Y-%m-%d', 'utf-8', gmDateTime.acc_days),
				self._payload[self._idx['l10n_type']].replace(' ', '_').replace('-', '_'),
			)
		else:
			date_type_part = '%s-%s' % (
				self._payload[self._idx['l10n_type']].replace(' ', '_').replace('-', '_'),
				gmDateTime.pydt_strftime(self._payload[self._idx['date_generated']], '%Y-%m-%d', 'utf-8', gmDateTime.acc_days)
			)

		if name_first:
			date_type_name_part = patient_part + date_type_part
		else:
			date_type_name_part = date_type_part + patient_part

		fname = fname_template % date_type_name_part

		if make_unique:
			fname = gmTools.get_unique_filename (
				prefix = '%s-' % gmTools.fname_sanitize(fname),
				suffix = suffix,
				tmp_dir = directory
			)
		else:
			fname = gmTools.fname_sanitize(os.path.join(gmTools.coalesce(directory, gmTools.gmPaths().tmp_dir), fname + suffix))

		return fname
Example #19
0
	def get_useful_filename(self, patient=None, make_unique=False, directory=None, include_gnumed_tag=True, date_before_type=False, name_first=True):
		patient_part = ''
		if patient is not None:
			if name_first:
				patient_part = '%s-' % patient.subdir_name
			else:
				patient_part = '-%s' % patient.subdir_name

		# preserve original filename extension if available
		suffix = '.dat'
		if self._payload[self._idx['filename']] is not None:
			tmp, suffix = os.path.splitext (
				gmTools.fname_sanitize(self._payload[self._idx['filename']]).lower()
			)
			if suffix == '':
				suffix = '.dat'

		if include_gnumed_tag:
			fname_template = 'gm_doc-part_%s-%%s' % self._payload[self._idx['seq_idx']]
		else:
			fname_template = '%%s-part_%s' % self._payload[self._idx['seq_idx']]

		if date_before_type:
			date_type_part = '%s-%s' % (
				gmDateTime.pydt_strftime(self._payload[self._idx['date_generated']], '%Y-%m-%d', 'utf-8', gmDateTime.acc_days),
				self._payload[self._idx['l10n_type']].replace(' ', '_').replace('-', '_'),
			)
		else:
			date_type_part = '%s-%s' % (
				self._payload[self._idx['l10n_type']].replace(' ', '_').replace('-', '_'),
				gmDateTime.pydt_strftime(self._payload[self._idx['date_generated']], '%Y-%m-%d', 'utf-8', gmDateTime.acc_days)
			)

		if name_first:
			date_type_name_part = patient_part + date_type_part
		else:
			date_type_name_part = date_type_part + patient_part

		fname = fname_template % date_type_name_part

		if make_unique:
			fname = gmTools.get_unique_filename (
				prefix = '%s-' % gmTools.fname_sanitize(fname),
				suffix = suffix,
				tmp_dir = directory
			)
		else:
			fname = gmTools.fname_sanitize(os.path.join(gmTools.coalesce(directory, gmTools.gmPaths().tmp_dir), fname + suffix))

		return fname
Example #20
0
def load_person_from_xml_linuxmednews_via_clipboard():

	fname = gmGuiHelpers.clipboard2file()
	if fname in [None, False]:
		gmGuiHelpers.gm_show_info (
			info = _('No patient in clipboard.'),
			title = _('Activating external patient')
		)
		return

	from Gnumed.business import gmLinuxMedNewsXML
	dto = gmLinuxMedNewsXML.parse_xml_linuxmednews(filename = fname)
	if dto is None:
		gmDispatcher.send(signal='statustext', msg=_('Clipboard does not seem to contain LinuxMedNews XML.'))
		return

	idents = dto.get_candidate_identities(can_create = True)
	if len(idents) == 1:
		ident = idents[0]
		if not set_active_patient(patient = ident):
			gmGuiHelpers.gm_show_info (_(
				'Cannot activate patient:\n\n'
				'%s %s (%s)\n'
				'%s'
				) % (
					dto.firstnames, dto.lastnames, dto.gender, gmDateTime.pydt_strftime(dto.dob, '%Y %b %d')
				),
				_('Activating external patient')
			)
		return

	dlg = cSelectPersonFromListDlg(wx.GetApp().GetTopWindow(), -1)
	dlg.set_persons(persons = idents)
	result = dlg.ShowModal()
	ident = dlg.get_selected_person()
	dlg.DestroyLater()
	if result == wx.ID_CANCEL:
		return None
	if not set_active_patient(patient = ident):
		gmGuiHelpers.gm_show_info (_(
			'Cannot activate patient:\n\n'
			'%s %s (%s)\n'
			'%s'
			) % (
				dto.firstnames, dto.lastnames, dto.gender, gmDateTime.pydt_strftime(dto.dob, '%Y %b %d')
			),
			_('Activating external patient')
		)
Example #21
0
def load_person_from_xml_linuxmednews_via_clipboard():

	fname = gmGuiHelpers.clipboard2file()
	if fname in [None, False]:
		gmGuiHelpers.gm_show_info (
			info = _('No patient in clipboard.'),
			title = _('Activating external patient')
		)
		return

	from Gnumed.business import gmLinuxMedNewsXML
	dto = gmLinuxMedNewsXML.parse_xml_linuxmednews(filename = fname)
	if dto is None:
		gmDispatcher.send(signal='statustext', msg=_('Clipboard does not seem to contain LinuxMedNews XML.'))
		return

	idents = dto.get_candidate_identities(can_create = True)
	if len(idents) == 1:
		ident = idents[0]
		if not set_active_patient(patient = ident):
			gmGuiHelpers.gm_show_info (_(
				'Cannot activate patient:\n\n'
				'%s %s (%s)\n'
				'%s'
				) % (
					dto.firstnames, dto.lastnames, dto.gender, gmDateTime.pydt_strftime(dto.dob, '%Y %b %d')
				),
				_('Activating external patient')
			)
		return

	dlg = cSelectPersonFromListDlg(wx.GetApp().GetTopWindow(), -1)
	dlg.set_persons(persons = idents)
	result = dlg.ShowModal()
	ident = dlg.get_selected_person()
	dlg.DestroyLater()
	if result == wx.ID_CANCEL:
		return None
	if not set_active_patient(patient = ident):
		gmGuiHelpers.gm_show_info (_(
			'Cannot activate patient:\n\n'
			'%s %s (%s)\n'
			'%s'
			) % (
				dto.firstnames, dto.lastnames, dto.gender, gmDateTime.pydt_strftime(dto.dob, '%Y %b %d')
			),
			_('Activating external patient')
		)
Example #22
0
	def is_valid_timestamp(self, empty_is_valid=True):
		if len(self._data) > 0:
			self.display_as_valid(True)
			return True

		if self.GetValue().strip() == '':
			if empty_is_valid:
				self.display_as_valid(True)
				return True
			else:
				self.display_as_valid(False)
				return False

		# skip showing calendar on '*' from here
		if self.GetValue().strip() == '*':
			self.display_as_valid(False)
			return False

		# try to auto-snap to first match
		self._set_data_to_first_match()
		if len(self._data) == 0:
			self.display_as_valid(False)
			return False

		date = self.GetData()
		self.SetValue(gmDateTime.pydt_strftime(date, format = '%Y-%m-%d', accuracy = gmDateTime.acc_days))#, none_str = u'')
		self.display_as_valid(True)
		return True
Example #23
0
 def _worker__export_doc_parts(self, docs=None, cookie=None):
     # this is used as the worker thread payload
     _log.debug('cookie [%s]', cookie)
     conn = gmPG2.get_connection(
         readonly=True,
         connection_name=threading.current_thread().name,
         pooled=False)
     parts_list = []
     for soap_doc in docs:
         parts = soap_doc.parts
         if len(parts) == 0:
             continue
         parts_counter = ''
         if len(parts) > 1:
             parts_counter = _(' [part 1 of %s]') % len(parts)
         part = parts[0]
         fname = part.save_to_file(conn=conn)
         if fname is None:
             continue
         tt_header = _('Created: %s%s') % (gmDateTime.pydt_strftime(
             part['date_generated'], '%Y %b %d'), parts_counter)
         tt_footer = gmTools.coalesce(part['doc_comment'], '').strip()
         parts_list.append([fname, part, tt_header, tt_footer])
     conn.close()
     _log.debug('worker finished')
     return (cookie, parts_list)
Example #24
0
	def _get_data_tooltip(self):
		if len(self._data) == 0:
			return ''

		date = self.GetData()
		# if match provider only provided completions
		# but not a full date with it
		if date is None:
			return ''
		ts = date.timestamp
		now = gmDateTime.pydt_now_here()
		if ts > now:
			intv = ts - now
			template = _('%s\n %s\n in %s')
		else:
			intv = now - ts
			template = _('%s\n%s\n%s ago')
		txt = template % (
			date.format_accurately(self.display_accuracy),
			gmDateTime.pydt_strftime (
				ts,
				format = '%A, %B-%d %Y (%c)',
			),
			gmDateTime.format_interval (
				interval = intv,
				accuracy_wanted = gmDateTime.acc_days,
				verbose = True
			)
		)
		return txt
Example #25
0
	def format(self):
		txt = u'%s               [#%s]\n' % (
			gmTools.bool2subst(self._payload[self._idx['is_active']], _('Suppressed active dynamic hint'), _('Suppressed inactive dynamic hint')),
			self._payload[self._idx['pk_suppressed_hint']]
		)
		txt += u'\n'
		txt += u'%s\n\n' % self._payload[self._idx['title']]
		txt += _('Suppressed by: %s\n') % self._payload[self._idx['suppressed_by']]
		txt += _('Suppressed at: %s\n') % gmDateTime.pydt_strftime(self._payload[self._idx['suppressed_when']], '%Y %b %d')
		txt += _('Hint #: %s\n') % self._payload[self._idx['pk_hint']]
		txt += _('Patient #: %s\n') % self._payload[self._idx['pk_identity']]
		txt += _('MD5 (currently): %s\n') % self._payload[self._idx['md5_hint']]
		txt += _('MD5 (at suppression): %s\n') % self._payload[self._idx['md5_suppressed']]
		txt += _('Source: %s\n') % self._payload[self._idx['source']]
		txt += _('Language: %s\n') % self._payload[self._idx['lang']]
		txt += u'\n'
		txt += u'%s\n' % gmTools.wrap(self._payload[self._idx['hint']], width = 50, initial_indent = u' ', subsequent_indent = u' ')
		txt += u'\n'
		if self._payload[self._idx['recommendation']] is not None:
			txt += u'\n'
			txt += u'%s\n' % gmTools.wrap(self._payload[self._idx['recommendation']], width = 50, initial_indent = u' ', subsequent_indent = u' ')
			txt += u'\n'
		txt += u'%s\n' % gmTools.wrap (
			gmTools.coalesce(self._payload[self._idx['url']], u''),
			width = 50,
			initial_indent = u' ',
			subsequent_indent = u' '
		)
		txt += u'\n'
		txt += u'%s\n' % gmTools.wrap(self._payload[self._idx['query']], width = 50, initial_indent = u' ', subsequent_indent = u' ')
		return txt
Example #26
0
	def set_dtos(self, dtos=None):
		self._LCTRL_persons.DeleteAllItems()

		pos = len(dtos) + 1
		if pos == 1:
			return False

		for rec in dtos:
			row_num = self._LCTRL_persons.InsertItem(pos, label = rec['source'])
			dto = rec['dto']
			self._LCTRL_persons.SetItem(index = row_num, column = 1, label = dto.lastnames)
			self._LCTRL_persons.SetItem(index = row_num, column = 2, label = dto.firstnames)
			if dto.dob is None:
				self._LCTRL_persons.SetItem(index = row_num, column = 3, label = '')
			else:
				if dto.dob_is_estimated:
					self._LCTRL_persons.SetItem(index = row_num, column = 3, label = gmTools.u_almost_equal_to + gmDateTime.pydt_strftime(dto.dob, '%Y %b %d'))
				else:
					self._LCTRL_persons.SetItem(index = row_num, column = 3, label = gmDateTime.pydt_strftime(dto.dob, '%Y %b %d'))
			self._LCTRL_persons.SetItem(index = row_num, column = 4, label = gmTools.coalesce(dto.gender, ''))

		for col in range(len(self.__cols)):
			self._LCTRL_persons.SetColumnWidth(col, wx.LIST_AUTOSIZE)

		self._BTN_select.Enable(False)
		self._LCTRL_persons.SetFocus()
		self._LCTRL_persons.Select(0)

		self._LCTRL_persons.set_data(data=dtos)
Example #27
0
    def get_useful_filename(self,
                            patient=None,
                            make_unique=False,
                            directory=None):
        patient_part = ''
        if patient is not None:
            patient_part = '-%s-' % patient['dirname']

        # preserve original filename extension if available
        suffix = '.dat'
        if self._payload[self._idx['filename']] is not None:
            tmp, suffix = os.path.splitext(
                self._payload[self._idx['filename']])
            suffix = suffix.strip().replace(' ', '-')
            if suffix == u'':
                suffix = '.dat'

        fname = 'gm_doc-part_%s-%s-%s-%s-' % (
            self._payload[self._idx['seq_idx']], patient_part,
            self._payload[self._idx['l10n_type']].replace(' ', '_'),
            gmDateTime.pydt_strftime(
                self._payload[self._idx['date_generated']], '%Y-%m-%d',
                'utf-8', gmDateTime.acc_days)
            #,gmTools.coalesce(self.__curr_node_data['ext_ref'], '', '-%s').replace(' ', '_')
        )

        if make_unique:
            fname = gmTools.get_unique_filename(prefix='%s-' % fname,
                                                suffix=suffix,
                                                tmp_dir=directory)
        else:
            fname = os.path.join(gmTools.coalesce(directory, u''),
                                 fname + suffix)

        return fname
Example #28
0
    def _get_data_tooltip(self):
        if len(self._data) == 0:
            return ''

        date = self.GetData()
        # if match provider only provided completions
        # but not a full date with it
        if date is None:
            return ''
        ts = date.timestamp
        now = gmDateTime.pydt_now_here()
        if ts > now:
            intv = ts - now
            template = _('%s\n %s\n in %s')
        else:
            intv = now - ts
            template = _('%s\n%s\n%s ago')
        txt = template % (date.format_accurately(self.display_accuracy),
                          gmDateTime.pydt_strftime(
                              ts,
                              format='%A, %B-%d %Y (%c)',
                          ),
                          gmDateTime.format_interval(
                              interval=intv,
                              accuracy_wanted=gmDateTime.acc_days,
                              verbose=True))
        return txt
Example #29
0
	def getMatchesByPhrase(self, aFragment):
		"""Return matches for aFragment at start of phrases."""
		matches = gmDateTime.str2pydt_matches(str2parse = aFragment.strip())

		if len(matches) == 0:
			return (False, [])

		items = []
		for match in matches:
			if match['data'] is None:
				items.append ({
					'data': None,
					'field_label': match['label'],
					'list_label': match['label']
				})
				continue

			data = match['data'].replace (
				hour = 11,
				minute = 11,
				second = 11,
				microsecond = 111111
			)
			list_label = gmDateTime.pydt_strftime (
				data,
				format = '%A, %d. %B %Y (%x)',
				accuracy = gmDateTime.acc_days
			)
			items.append ({
				'data': data,
				'field_label': match['label'],
				'list_label': list_label
			})

		return (True, items)
Example #30
0
	def format_single_line(self):

		part_count = len(self._payload[self._idx['seq_idx_list']])
		if part_count == 0:
			parts = _('no parts')
		elif part_count == 1:
			parts = _('1 part')
		else:
			parts = _('%s parts') % part_count

		detail = ''
		if self._payload[self._idx['ext_ref']] is not None:
			detail = self._payload[self._idx['ext_ref']]
		if self._payload[self._idx['unit']] is not None:
			template = _('%s of %s')
			if detail == '':
				detail = _('%s of %s') % (
					self._payload[self._idx['unit']],
					self._payload[self._idx['organization']]
				)
			else:
				detail += (' @ ' + template % (
					self._payload[self._idx['unit']],
					self._payload[self._idx['organization']]
				))
		if detail != '':
			detail = ' (%s)' % detail

		return '%s %s (%s):%s%s' % (
			gmDateTime.pydt_strftime(self._payload[self._idx['clin_when']], '%Y %b %d', accuracy = gmDateTime.acc_days),
			self._payload[self._idx['l10n_type']],
			parts,
			gmTools.coalesce(self._payload[self._idx['comment']], '', ' "%s"'),
			detail
		)
Example #31
0
    def format_single_line(self):

        part_count = len(self._payload[self._idx['seq_idx_list']])
        if part_count == 0:
            parts = _('no parts')
        elif part_count == 1:
            parts = _('1 part')
        else:
            parts = _('%s parts') % part_count

        detail = ''
        if self._payload[self._idx['ext_ref']] is not None:
            detail = self._payload[self._idx['ext_ref']]
        if self._payload[self._idx['unit']] is not None:
            template = _('%s of %s')
            if detail == '':
                detail = _('%s of %s') % (
                    self._payload[self._idx['unit']],
                    self._payload[self._idx['organization']])
            else:
                detail += (' @ ' + template %
                           (self._payload[self._idx['unit']],
                            self._payload[self._idx['organization']]))
        if detail != '':
            detail = ' (%s)' % detail

        return '%s %s (%s):%s%s' % (
            gmDateTime.pydt_strftime(self._payload[self._idx['clin_when']],
                                     '%Y %b %d',
                                     accuracy=gmDateTime.acc_days),
            self._payload[self._idx['l10n_type']], parts,
            gmTools.coalesce(self._payload[self._idx['comment']], '',
                             ' "%s"'), detail)
Example #32
0
	def format_maximum_information(self, patient=None):
		lines = []
		lines.append('%s%s: %s     [#%s]' % (
			self._payload[self._idx['l10n_type']],
			gmTools.bool2subst (
				self._payload[self._idx['definite']],
				' (%s)' % _('definite'),
				' (%s)' % _('indefinite'),
				''
			),
			self._payload[self._idx['descriptor']],
			self._payload[self._idx['pk_allergy']]
		))
		if self._payload[self._idx['reaction']] is not None:
			lines.append(' ' + _('Reaction:') + ' ' + self._payload[self._idx['reaction']])
		if self._payload[self._idx['date']] is not None:
			lines.append(' ' + _('Noted:') + ' ' + gmDateTime.pydt_strftime(self._payload[self._idx['date']], '%Y %b %d'))
		if self._payload[self._idx['allergene']] is not None:
			lines.append(' ' + _('Allergene:') + ' ' + self._payload[self._idx['allergene']])
		if self._payload[self._idx['substance']] is not None:
			lines.append(' ' + _('Substance:') + ' ' + self._payload[self._idx['substance']])
		if self._payload[self._idx['substance_code']] is not None:
			lines.append(' ' + _('Code:') + ' ' + self._payload[self._idx['substance_code']])
		if self._payload[self._idx['atc_code']] is not None:
			lines.append(' ' + _('ATC:') + ' ' + self._payload[self._idx['atc_code']])
		lines.append(' ' + _('Specific to:') + ' ' + gmTools.bool2subst (
			self._payload[self._idx['generic_specific']],
			_('this substance only'),
			_('drug class'),
			_('unknown')
		))
		if self._payload[self._idx['generics']] is not None:
			lines.append(' ' + _('Generics:') + ' ' + self._payload[self._idx['generics']])

		return lines
Example #33
0
 def _picklist_item2display_string(self, item=None):
     data = item['data']
     if data is not None:
         return gmDateTime.pydt_strftime(data,
                                         format='%Y-%m-%d',
                                         accuracy=gmDateTime.acc_days)
     return item['field_label']
Example #34
0
    def get_EDC(self, lmp=None, nullipara=True):

        result = cClinicalResult(_('unknown EDC'))
        result.formula_name = u'EDC (Mittendorf 1990)'
        result.formula_source = u'Mittendorf, R. et al., "The length of uncomplicated human gestation," OB/GYN, Vol. 75, No., 6 June, 1990, pp. 907-932.'

        if lmp is None:
            result.message = _('EDC: unknown LMP')
            return result

        result.variables['LMP'] = lmp
        result.variables['nullipara'] = nullipara
        if nullipara:
            result.variables['parity_offset'] = 15  # days
        else:
            result.variables['parity_offset'] = 10  # days

        now = gmDateTime.pydt_now_here()
        if lmp > now:
            result.warnings.append(_(u'LMP in the future'))

        if self.__patient is None:
            result.warnings.append(_(u'cannot run sanity checks, no patient'))
        else:
            if self.__patient['dob'] is None:
                result.warnings.append(_(u'cannot run sanity checks, no DOB'))
            else:
                years, months, days, hours, minutes, seconds = gmDateTime.calculate_apparent_age(
                    start=self.__patient['dob'])
                # 5 years -- Myth ?
                # http://www.mirror.co.uk/news/uk-news/top-10-crazy-amazing-and-world-789842
                if years < 10:
                    result.warnings.append(
                        _(u'patient less than 10 years old'))
            if self.__patient['gender'] in [None, u'm']:
                result.warnings.append(
                    _(u'atypical gender for pregnancy: %s') %
                    self.__patient.gender_string)
            if self.__patient['deceased'] is not None:
                result.warnings.append(_(u'patient already passed away'))

        if lmp.month > 3:
            edc_month = lmp.month - 3
            edc_year = lmp.year + 1
        else:
            edc_month = lmp.month + 9
            edc_year = lmp.year

        result.numeric_value = gmDateTime.pydt_replace(
            dt=lmp, year=edc_year, month=edc_month,
            strict=False) + pydt.timedelta(
                days=result.variables['parity_offset'])

        result.message = _('EDC: %s') % gmDateTime.pydt_strftime(
            result.numeric_value, format='%Y %b %d')
        result.date_valid = now

        _log.debug(u'%s' % result)

        return result
Example #35
0
	def __pick_from_calendar(self):
		dlg = cCalendarDatePickerDlg(self)
		# FIXME: show below parent
		dlg.CentreOnScreen()
		decision = dlg.ShowModal()
		date = dlg.cal.Date
		dlg.Destroy()

		if decision != wx.ID_OK:
			return

		if date is None:
			return

		if not date.IsValid():
			return

		date = gmDateTime.wxDate2py_dt(wxDate = date).replace (
			hour = 11,
			minute = 11,
			second = 11,
			microsecond = 111111
		)
		val = gmDateTime.pydt_strftime(date, format = '%Y-%m-%d', accuracy = gmDateTime.acc_days)
		self.SetText(value = val, data = date, suppress_smarts = True)
Example #36
0
	def __pick_from_calendar(self):
		dlg = cCalendarDatePickerDlg(self)
		# FIXME: show below parent
		dlg.CentreOnScreen()
		decision = dlg.ShowModal()
		date = dlg.cal.Date
		dlg.DestroyLater()

		if decision != wx.ID_OK:
			return

		if date is None:
			return

		if not date.IsValid():
			return

		date = gmDateTime.wxDate2py_dt(wxDate = date).replace (
			hour = 11,
			minute = 11,
			second = 11,
			microsecond = 111111
		)
		val = gmDateTime.pydt_strftime(date, format = '%Y-%m-%d', accuracy = gmDateTime.acc_days)
		self.SetText(value = val, data = date, suppress_smarts = True)
Example #37
0
    def _get_revision_history(self, query, args, title):
        rows, idx = gmPG2.run_ro_queries(queries=[{
            'cmd': query,
            'args': args
        }],
                                         get_col_idx=True)

        lines = []
        if rows == 0:
            lines.append('%s (no versions)' % title)
        else:
            lines.append('%s (%s versions)' %
                         (title, rows[0]['row_version'] + 1))
            headers = [
                'rev %s (%s)' % (r['row_version'],
                                 pydt_strftime(r['audit__action_when'],
                                               format='%Y %b %d %H:%M',
                                               none_str='live row'))
                for r in rows
            ]
            lines.extend(
                dicts2table(rows,
                            left_margin=1,
                            eol=None,
                            keys2ignore=[
                                'audit__action_when', 'row_version', 'pk_audit'
                            ],
                            show_only_changes=True,
                            headers=headers,
                            date_format='%Y %b %d %H:%M',
                            equality_value=u_left_arrow))
        return lines
Example #38
0
	def getMatchesByPhrase(self, aFragment):
		"""Return matches for aFragment at start of phrases."""
		matches = gmDateTime.str2pydt_matches(str2parse = aFragment.strip())

		if len(matches) == 0:
			return (False, [])

		items = []
		for match in matches:
			if match['data'] is None:
				items.append ({
					'data': None,
					'field_label': match['label'],
					'list_label': match['label']
				})
				continue

			data = match['data'].replace (
				hour = 11,
				minute = 11,
				second = 11,
				microsecond = 111111
			)
			list_label = gmDateTime.pydt_strftime (
				data,
				format = '%A, %d. %B %Y (%x)',
				accuracy = gmDateTime.acc_days
			)
			items.append ({
				'data': data,
				'field_label': match['label'],
				'list_label': list_label
			})

		return (True, items)
Example #39
0
	def format(self):
		txt = '%s               [#%s]\n' % (
			gmTools.bool2subst(self._payload[self._idx['is_active']], _('Suppressed active dynamic hint'), _('Suppressed inactive dynamic hint')),
			self._payload[self._idx['pk_suppressed_hint']]
		)
		txt += '\n'
		txt += '%s\n\n' % self._payload[self._idx['title']]
		txt += _('Suppressed by: %s\n') % self._payload[self._idx['suppressed_by']]
		txt += _('Suppressed at: %s\n') % gmDateTime.pydt_strftime(self._payload[self._idx['suppressed_when']], '%Y %b %d')
		txt += _('Hint #: %s\n') % self._payload[self._idx['pk_hint']]
		txt += _('Patient #: %s\n') % self._payload[self._idx['pk_identity']]
		txt += _('MD5 (currently): %s\n') % self._payload[self._idx['md5_hint']]
		txt += _('MD5 (at suppression): %s\n') % self._payload[self._idx['md5_suppressed']]
		txt += _('Source: %s\n') % self._payload[self._idx['source']]
		txt += _('Language: %s\n') % self._payload[self._idx['lang']]
		txt += '\n'
		txt += '%s\n' % gmTools.wrap(self._payload[self._idx['hint']], width = 50, initial_indent = ' ', subsequent_indent = ' ')
		txt += '\n'
		if self._payload[self._idx['recommendation']] is not None:
			txt += '\n'
			txt += '%s\n' % gmTools.wrap(self._payload[self._idx['recommendation']], width = 50, initial_indent = ' ', subsequent_indent = ' ')
			txt += '\n'
		txt += '%s\n' % gmTools.wrap (
			gmTools.coalesce(self._payload[self._idx['url']], ''),
			width = 50,
			initial_indent = ' ',
			subsequent_indent = ' '
		)
		txt += '\n'
		txt += '%s\n' % gmTools.wrap(self._payload[self._idx['query']], width = 50, initial_indent = ' ', subsequent_indent = ' ')
		return txt
Example #40
0
	def set_dtos(self, dtos=None):
		self._LCTRL_persons.DeleteAllItems()

		pos = len(dtos) + 1
		if pos == 1:
			return False

		for rec in dtos:
			row_num = self._LCTRL_persons.InsertItem(pos, label = rec['source'])
			dto = rec['dto']
			self._LCTRL_persons.SetItem(index = row_num, column = 1, label = dto.lastnames)
			self._LCTRL_persons.SetItem(index = row_num, column = 2, label = dto.firstnames)
			if dto.dob is None:
				self._LCTRL_persons.SetItem(index = row_num, column = 3, label = '')
			else:
				if dto.dob_is_estimated:
					self._LCTRL_persons.SetItem(index = row_num, column = 3, label = gmTools.u_almost_equal_to + gmDateTime.pydt_strftime(dto.dob, '%Y %b %d'))
				else:
					self._LCTRL_persons.SetItem(index = row_num, column = 3, label = gmDateTime.pydt_strftime(dto.dob, '%Y %b %d'))
			self._LCTRL_persons.SetItem(index = row_num, column = 4, label = gmTools.coalesce(dto.gender, ''))

		for col in range(len(self.__cols)):
			self._LCTRL_persons.SetColumnWidth(col, wx.LIST_AUTOSIZE)

		self._BTN_select.Enable(False)
		self._LCTRL_persons.SetFocus()
		self._LCTRL_persons.Select(0)

		self._LCTRL_persons.set_data(data=dtos)
Example #41
0
    def get_useful_filename(self, patient=None, make_unique=False, directory=None):
        patient_part = ""
        if patient is not None:
            patient_part = "-%s-" % patient["dirname"]

            # preserve original filename extension if available
        suffix = ".dat"
        if self._payload[self._idx["filename"]] is not None:
            tmp, suffix = os.path.splitext(self._payload[self._idx["filename"]])
            suffix = suffix.strip().replace(" ", "-")
            if suffix == u"":
                suffix = ".dat"

        fname = "gm-doc_part-%s-%s-%s--pg_%s" % (
            patient_part,
            self._payload[self._idx["l10n_type"]].replace(" ", "_"),
            gmDateTime.pydt_strftime(
                self._payload[self._idx["date_generated"]], "%Y-%b-%d", "utf-8", gmDateTime.acc_days
            ),
            self._payload[self._idx["seq_idx"]],
            # ,gmTools.coalesce(self.__curr_node_data['ext_ref'], '', '-%s').replace(' ', '_')
        )

        if make_unique:
            fname = gmTools.get_unique_filename(prefix="%s-" % fname, suffix=suffix, tmp_dir=directory)
        else:
            fname = os.path.join(gmTools.coalesce(directory, u""), fname + suffix)

        return fname
Example #42
0
	def is_valid_timestamp(self, allow_empty=True):
		if len(self._data) > 0:
			self.display_as_valid(True)
			return True

		if self.GetValue().strip() == u'':
			if allow_empty:
				self.display_as_valid(True)
				return True
			else:
				self.display_as_valid(False)
				return False

		# skip showing calendar on '*' from here
		if self.GetValue().strip() == u'*':
			self.display_as_valid(False)
			return False

		# try to auto-snap to first match
		self._set_data_to_first_match()
		if len(self._data) == 0:
			self.display_as_valid(False)
			return False

		date = self.GetData()
		self.SetValue(gmDateTime.pydt_strftime(date, format = '%Y-%m-%d', accuracy = gmDateTime.acc_days))#, none_str = u'')
		self.display_as_valid(True)
		return True
Example #43
0
	def format_maximum_information(self, patient=None):
		lines = []
		lines.append(u'%s%s: %s     [#%s]' % (
			self._payload[self._idx['l10n_type']],
			gmTools.bool2subst (
				self._payload[self._idx['definite']],
				u' (%s)' % _('definite'),
				u' (%s)' % _('indefinite'),
				u''
			),
			self._payload[self._idx['descriptor']],
			self._payload[self._idx['pk_allergy']]
		))
		if self._payload[self._idx['reaction']] is not None:
			lines.append(u' ' + _('Reaction:') + u' ' + self._payload[self._idx['reaction']])
		if self._payload[self._idx['date']] is not None:
			lines.append(u' ' + _('Noted:') + u' ' + gmDateTime.pydt_strftime(self._payload[self._idx['date']], '%Y %b %d'))
		if self._payload[self._idx['allergene']] is not None:
			lines.append(u' ' + _('Allergene:') + u' ' + self._payload[self._idx['allergene']])
		if self._payload[self._idx['substance']] is not None:
			lines.append(u' ' + _('Substance:') + u' ' + self._payload[self._idx['substance']])
		if self._payload[self._idx['substance_code']] is not None:
			lines.append(u' ' + _('Code:') + u' ' + self._payload[self._idx['substance_code']])
		if self._payload[self._idx['atc_code']] is not None:
			lines.append(u' ' + _('ATC:') + u' ' + self._payload[self._idx['atc_code']])
		lines.append(u' ' + _('Specific to:') + u' ' + gmTools.bool2subst (
			self._payload[self._idx['generic_specific']],
			_('this substance only'),
			_('drug class'),
			_('unknown')
		))
		if self._payload[self._idx['generics']] is not None:
			lines.append(u' ' + _('Generics:') + u' ' + self._payload[self._idx['generics']])

		return lines
	def refresh_summary(self):
		self._TCTRL_episode_summary.SetValue('')
		self._PRW_episode_codes.SetText('', self._PRW_episode_codes.list2data_dict([]))
		self._LBL_summary.SetLabel(_('Episode synopsis'))

		# new problem ?
		if self.problem is None:
			return

		# issue-level problem ?
		if self.problem['type'] == 'issue':
			return

		# episode-level problem
		caption = _('Synopsis (%s)') % (
			gmDateTime.pydt_strftime (
				self.problem['modified_when'],
				format = '%B %Y',
				accuracy = gmDateTime.acc_days
			)
		)
		self._LBL_summary.SetLabel(caption)

		if self.problem['summary'] is not None:
			self._TCTRL_episode_summary.SetValue(self.problem['summary'].strip())

		val, data = self._PRW_episode_codes.generic_linked_codes2item_dict(self.problem.generic_codes)
		self._PRW_episode_codes.SetText(val, data)
Example #45
0
def get_invoice_id(pk_patient=None):
	return 'GM%s / %s' % (
		pk_patient,
		gmDateTime.pydt_strftime (
			gmDateTime.pydt_now_here(),
			'%Y-%m-%d / %H%M%S'
		)
	)
Example #46
0
def get_invoice_id(pk_patient=None):
	return 'GM%s / %s' % (
		pk_patient,
		gmDateTime.pydt_strftime (
			gmDateTime.pydt_now_here(),
			'%Y-%m-%d / %H%M%S'
		)
	)
Example #47
0
 def __pick_from_weekday(self, weekday):
     self.is_valid_timestamp(empty_is_valid=True)
     target_date = gmDateTime.get_date_of_weekday_in_week_of_date(
         weekday, base_dt=self.date)
     val = gmDateTime.pydt_strftime(target_date,
                                    format='%Y-%m-%d',
                                    accuracy=gmDateTime.acc_days)
     self.SetText(value=val, data=target_date, suppress_smarts=True)
Example #48
0
File: gmHL7.py Project: sk/gnumed
	def _format_patient_identification(self):
		tmp = u'%s %s %s' % (
			gmTools.coalesce(self._payload[self._idx['lastnames']], u'', u'last=%s'),
			gmTools.coalesce(self._payload[self._idx['firstnames']], u'', u'first=%s'),
			gmTools.coalesce(self._payload[self._idx['gender']], u'', u'gender=%s')
		)
		if self._payload[self._idx['dob']] is not None:
			tmp += u' dob=%s' % gmDateTime.pydt_strftime(self._payload[self._idx['dob']], '%Y %b %d')
		return tmp
Example #49
0
	def format_maximum_information(self, patient=None):
		lines = []
		lines.append('%s (%s)' % (
			self.state_string,
			gmDateTime.pydt_strftime(self['last_confirmed'], '%Y %b %d', none_str = '?')
		))
		if self._payload[self._idx['comment']] is not None:
			lines.append(' %s' % self._payload[self._idx['comment']])
		return lines
Example #50
0
	def format(self):
		txt = '%s (%s %s%s)         [#%s]\n' % (
			gmTools.bool2subst(
				self._payload[self._idx['pk_bill']] is None,
				_('Open item'),
				_('Billed item'),
			),
			self._payload[self._idx['catalog_short']],
			self._payload[self._idx['catalog_version']],
			gmTools.coalesce(self._payload[self._idx['catalog_language']], '', ' - %s'),
			self._payload[self._idx['pk_bill_item']]
		)
		txt += ' %s: %s\n' % (
			self._payload[self._idx['billable_code']],
			self._payload[self._idx['billable_description']]
		)
		txt += gmTools.coalesce (
			self._payload[self._idx['billable_comment']],
			'',
			'  (%s)\n',
		)
		txt += gmTools.coalesce (
			self._payload[self._idx['item_detail']],
			'',
			_(' Details: %s\n'),
		)

		txt += '\n'
		txt += _(' %s of units: %s\n') % (
			gmTools.u_numero,
			self._payload[self._idx['unit_count']]
		)
		txt += _(' Amount per unit: %(curr)s%(val_p_unit)s (%(cat_curr)s%(cat_val)s per catalog)\n') % {
			'curr': self._payload[self._idx['currency']],
			'val_p_unit': self._payload[self._idx['net_amount_per_unit']],
			'cat_curr': self._payload[self._idx['billable_currency']],
			'cat_val': self._payload[self._idx['billable_amount']]
		}
		txt += _(' Amount multiplier: %s\n') % self._payload[self._idx['amount_multiplier']]
		txt += _(' VAT would be: %(perc_vat)s%% %(equals)s %(curr)s%(vat)s\n') % {
			'perc_vat': self._payload[self._idx['vat_multiplier']] * 100,
			'equals': gmTools.u_corresponds_to,
			'curr': self._payload[self._idx['currency']],
			'vat': self._payload[self._idx['vat']]
		}

		txt += '\n'
		txt += _(' Charge date: %s') % gmDateTime.pydt_strftime (
			self._payload[self._idx['date_to_bill']],
			'%Y %b %d',
			accuracy = gmDateTime.acc_days
		)
		bill = self.bill
		if bill is not None:
			txt += _('\n On bill: %s') % bill['invoice_id']

		return txt
Example #51
0
    def format(self, include_receiver=True, include_doc=True):
        txt = '%s                       [#%s]\n' % (gmTools.bool2subst(
            (self._payload[self._idx['close_date']] is None), _('Open bill'),
            _('Closed bill')), self._payload[self._idx['pk_bill']])
        txt += _(' Invoice ID: %s\n') % self._payload[self._idx['invoice_id']]

        if self._payload[self._idx['close_date']] is not None:
            txt += _(' Closed: %s\n') % gmDateTime.pydt_strftime(
                self._payload[self._idx['close_date']],
                '%Y %b %d',
                accuracy=gmDateTime.acc_days)

        if self._payload[self._idx['comment']] is not None:
            txt += _(' Comment: %s\n') % self._payload[self._idx['comment']]

        txt += _(' Bill value: %(curr)s%(val)s\n') % {
            'curr': self._payload[self._idx['currency']],
            'val': self._payload[self._idx['total_amount']]
        }

        if self._payload[self._idx['apply_vat']] is None:
            txt += _(' VAT: undecided\n')
        elif self._payload[self._idx['apply_vat']] is True:
            txt += _(' VAT: %(perc_vat)s%% %(equals)s %(curr)s%(vat)s\n') % {
                'perc_vat': self._payload[self._idx['percent_vat']],
                'equals': gmTools.u_corresponds_to,
                'curr': self._payload[self._idx['currency']],
                'vat': self._payload[self._idx['total_vat']]
            }
            txt += _(' Value + VAT: %(curr)s%(val)s\n') % {
                'curr': self._payload[self._idx['currency']],
                'val': self._payload[self._idx['total_amount_with_vat']]
            }
        else:
            txt += _(' VAT: does not apply\n')

        if self._payload[self._idx['pk_bill_items']] is None:
            txt += _(' Items billed: 0\n')
        else:
            txt += _(' Items billed: %s\n') % len(
                self._payload[self._idx['pk_bill_items']])
        if include_doc:
            txt += _(' Invoice: %s\n') % (gmTools.bool2subst(
                self._payload[self._idx['pk_doc']] is None, _('not available'),
                '#%s' % self._payload[self._idx['pk_doc']]))
        txt += _(' Patient: #%s\n') % self._payload[self._idx['pk_patient']]
        if include_receiver:
            txt += gmTools.coalesce(
                self._payload[self._idx['pk_receiver_identity']], '',
                _(' Receiver: #%s\n'))
            if self._payload[self._idx['pk_receiver_address']] is not None:
                txt += '\n '.join(
                    gmDemographicRecord.get_patient_address(
                        pk_patient_address=self._payload[
                            self._idx['pk_receiver_address']]).format())

        return txt
Example #52
0
	def format(self):
		txt = '%s (%s %s%s)         [#%s]\n' % (
			gmTools.bool2subst(
				self._payload[self._idx['pk_bill']] is None,
				_('Open item'),
				_('Billed item'),
			),
			self._payload[self._idx['catalog_short']],
			self._payload[self._idx['catalog_version']],
			gmTools.coalesce(self._payload[self._idx['catalog_language']], '', ' - %s'),
			self._payload[self._idx['pk_bill_item']]
		)
		txt += ' %s: %s\n' % (
			self._payload[self._idx['billable_code']],
			self._payload[self._idx['billable_description']]
		)
		txt += gmTools.coalesce (
			self._payload[self._idx['billable_comment']],
			'',
			'  (%s)\n',
		)
		txt += gmTools.coalesce (
			self._payload[self._idx['item_detail']],
			'',
			_(' Details: %s\n'),
		)

		txt += '\n'
		txt += _(' %s of units: %s\n') % (
			gmTools.u_numero,
			self._payload[self._idx['unit_count']]
		)
		txt += _(' Amount per unit: %(curr)s%(val_p_unit)s (%(cat_curr)s%(cat_val)s per catalog)\n') % {
			'curr': self._payload[self._idx['currency']],
			'val_p_unit': self._payload[self._idx['net_amount_per_unit']],
			'cat_curr': self._payload[self._idx['billable_currency']],
			'cat_val': self._payload[self._idx['billable_amount']]
		}
		txt += _(' Amount multiplier: %s\n') % self._payload[self._idx['amount_multiplier']]
		txt += _(' VAT would be: %(perc_vat)s%% %(equals)s %(curr)s%(vat)s\n') % {
			'perc_vat': self._payload[self._idx['vat_multiplier']] * 100,
			'equals': gmTools.u_corresponds_to,
			'curr': self._payload[self._idx['currency']],
			'vat': self._payload[self._idx['vat']]
		}

		txt += '\n'
		txt += _(' Charge date: %s') % gmDateTime.pydt_strftime (
			self._payload[self._idx['date_to_bill']],
			'%Y %b %d',
			accuracy = gmDateTime.acc_days
		)
		bill = self.bill
		if bill is not None:
			txt += _('\n On bill: %s') % bill['invoice_id']

		return txt
Example #53
0
 def refresh(lctrl):
     lctrl.secondary_sort_column = 0
     soap = emr.get_clin_narrative(soap_cats=soap_cats)
     lctrl.set_string_items([[
         gmDateTime.pydt_strftime(s['date'], '%Y %m %d'), s['modified_by'],
         gmSoapDefs.soap_cat2l10n[s['soap_cat']], s['narrative'],
         s['episode'], s['health_issue']
     ] for s in soap])
     lctrl.set_data(soap)
Example #54
0
	def _on_lose_focus(self, event):
		# no valid date yet ?
		if len(self._data) == 0:
			self._set_data_to_first_match()
			date = self.GetData()
			if date is not None:
				self.SetValue(gmDateTime.pydt_strftime(date, format = '%Y-%m-%d', accuracy = gmDateTime.acc_days))

		# let the base class do its thing
		super(cDateInputPhraseWheel, self)._on_lose_focus(event)
Example #55
0
	def format(self, single_line=False):
		if single_line:
			return self.format_single_line()

		part_count = len(self._payload[self._idx['seq_idx_list']])
		if part_count == 0:
			parts = _('no parts')
		elif part_count == 1:
			parts = _('1 part')
		else:
			parts = _('%s parts') % part_count
		org = ''
		if self._payload[self._idx['unit']] is not None:
			if self._payload[self._idx['unit_is_receiver']]:
				org = _(' Receiver: %s @ %s\n') % (
					self._payload[self._idx['unit']],
					self._payload[self._idx['organization']]
				)
			else:
				org = _(' Sender: %s @ %s\n') % (
					self._payload[self._idx['unit']],
					self._payload[self._idx['organization']]
				)
		stay = ''
		if self._payload[self._idx['pk_hospital_stay']] is not None:
			stay = _('Hospital stay') + ': %s\n' % self.hospital_stay.format (
				left_margin = 0,
				include_procedures = False,
				include_docs = False,
				include_episode = False
			)

		txt = _(
			'%s (%s)   #%s\n'
			' Created: %s\n'
			' Episode: %s\n'
			'%s'
			'%s'
			'%s'
			'%s'
			'%s'
		) % (
			self._payload[self._idx['l10n_type']],
			parts,
			self._payload[self._idx['pk_doc']],
			gmDateTime.pydt_strftime(self._payload[self._idx['clin_when']], format = '%Y %b %d', accuracy = gmDateTime.acc_days),
			self._payload[self._idx['episode']],
			gmTools.coalesce(self._payload[self._idx['health_issue']], '', _(' Health issue: %s\n')),
			gmTools.coalesce(self._payload[self._idx['ext_ref']], '', _(' External reference: %s\n')),
			org,
			stay,
			gmTools.coalesce(self._payload[self._idx['comment']], '', ' %s')
		)

		return txt
Example #56
0
	def get_EDC(self, lmp=None, nullipara=True):

		result = cClinicalResult(_('unknown EDC'))
		result.formula_name = 'EDC (Mittendorf 1990)'
		result.formula_source = 'Mittendorf, R. et al., "The length of uncomplicated human gestation," OB/GYN, Vol. 75, No., 6 June, 1990, pp. 907-932.'

		if lmp is None:
			result.message = _('EDC: unknown LMP')
			return result

		result.variables['LMP'] = lmp
		result.variables['nullipara'] = nullipara
		if nullipara:
			result.variables['parity_offset'] = 15		# days
		else:
			result.variables['parity_offset'] = 10		# days

		now = gmDateTime.pydt_now_here()
		if lmp > now:
			result.warnings.append(_('LMP in the future'))

		if self.__patient is None:
			result.warnings.append(_('cannot run sanity checks, no patient'))
		else:
			if self.__patient['dob'] is None:
				result.warnings.append(_('cannot run sanity checks, no DOB'))
			else:
				years, months, days, hours, minutes, seconds = gmDateTime.calculate_apparent_age(start = self.__patient['dob'])
				# 5 years -- Myth ?
				# http://www.mirror.co.uk/news/uk-news/top-10-crazy-amazing-and-world-789842
				if years < 10:
					result.warnings.append(_('patient less than 10 years old'))
			if self.__patient['gender'] in [None, 'm']:
				result.warnings.append(_('atypical gender for pregnancy: %s') % self.__patient.gender_string)
			if self.__patient['deceased'] is not None:
				result.warnings.append(_('patient already passed away'))

		if lmp.month > 3:
			edc_month = lmp.month - 3
			edc_year = lmp.year + 1
		else:
			edc_month = lmp.month + 9
			edc_year = lmp.year

		result.numeric_value = gmDateTime.pydt_replace(dt = lmp, year = edc_year, month = edc_month, strict = False) + pydt.timedelta(days = result.variables['parity_offset'])

		result.message = _('EDC: %s') % gmDateTime.pydt_strftime (
			result.numeric_value,
			format = '%Y %b %d'
		)
		result.date_valid = now

		_log.debug('%s' % result)

		return result
Example #57
0
	def refresh(lctrl):
		epis = emr.get_episodes(order_by = 'description')
		items = [
			[	e['description'],
				gmTools.bool2subst(e['episode_open'], _('ongoing'), _('closed'), '<unknown>'),
				gmDateTime.pydt_strftime(e.best_guess_clinical_start_date, '%Y %b %d'),
				gmTools.coalesce(e['health_issue'], '')
			] for e in epis
		]
		lctrl.set_string_items(items = items)
		lctrl.set_data(data = epis)
Example #58
0
	def refresh(lctrl):
		intakes = patient.emr.abused_substances
		items = []
		for i in intakes:
			items.append ([
				i['substance'],
				i.harmful_use_type_string,
				gmDateTime.pydt_strftime(i['last_checked_when'], '%b %Y', none_str = '')
			])
		lctrl.set_string_items(items)
		lctrl.set_data(intakes)
Example #59
0
	def refresh(lctrl):
		lctrl.secondary_sort_column = 0
		soap = emr.get_clin_narrative(soap_cats = soap_cats)
		lctrl.set_string_items ([ [
			gmDateTime.pydt_strftime(s['date'], '%Y %m %d'),
			s['modified_by'],
			gmSoapDefs.soap_cat2l10n[s['soap_cat']],
			s['narrative'],
			s['episode'],
			s['health_issue']
		] for s in soap ])
		lctrl.set_data(soap)