Ejemplo n.º 1
0
def get_age(datetime_from, datetime_to=None):
    """Returns the elapsed time in years, months and days between the two
    dates passed in."""
    if not datetime_to:
        datetime_to = DateTime()

    if not bapi.is_date(datetime_from) or not bapi.is_date(datetime_to):
        bapi.fail("Only DateTime and datetype types are supported")

    dfrom = DT2dt(bapi.to_date(datetime_from)).replace(tzinfo=None)
    dto = DT2dt(bapi.to_date(datetime_to)).replace(tzinfo=None)

    diff = relativedelta(dto, dfrom)
    return (diff.years, diff.months, diff.days)
Ejemplo n.º 2
0
    def get_current_age(self, dob):
        """Returns a dict with keys "years", "months", "days"
        """
        if not api.is_date(dob):
            return {}

        delta = patient_api.get_relative_delta(dob)
        return {
            "years": delta.years,
            "months": delta.months,
            "days": delta.days,
        }
Ejemplo n.º 3
0
    def process_form(self, instance, field, form, empty_marker=None,
                     emptyReturnsMarker=False, validating=True):

        value = form.get(field.getName())

        # Not interested in the hidden field, but in the age + dob specific
        if isinstance(value, (list, tuple)):
            value = value[0] or None

        # Allow non-required fields
        if not value:
            return None, {}

        # handle DateTime object when creating partitions
        if api.is_date(value):
            self.set_age_selected(instance, False)
            return value, {}

        # Grab the input for DoB first
        dob = value.get("dob", "")
        dob = patient_api.to_datetime(dob)
        age_selected = value.get("selector") == "age"

        # remember what was slected
        self.set_age_selected(instance, age_selected)

        # Maybe user entered age instead of DoB
        if age_selected:
            # Validate the age entered
            ymd = map(lambda p: value.get(p), ["years", "months", "days"])
            if not any(ymd):
                # No values set
                return None

            # Age in ymd format
            ymd = filter(lambda p: p[0], zip(ymd, 'ymd'))
            ymd = "".join(map(lambda p: "".join(p), ymd))

            # Calculate the DoB
            dob = patient_api.get_birth_date(ymd)

        return dob, {}
Ejemplo n.º 4
0
 def addToJSON(self, analysis, service_uid, item):
     """ Adds an analysis item to the self.anjson dict that will be used
         after the page is rendered to generate a QC Chart
     """
     parent = api.get_parent(analysis)
     qcid = parent.id
     serviceref = "%s (%s)" % (item['Service'], item['Keyword'])
     trows = self.anjson.get(serviceref, {})
     anrows = trows.get(qcid, [])
     rr = parent.getResultsRangeDict()
     cap_date = item['obj'].getResultCaptureDate
     cap_date = api.is_date(cap_date) and \
                cap_date.strftime('%Y-%m-%d %I:%M %p') or ''
     if service_uid in rr:
         specs = rr.get(service_uid, None)
         try:
             smin = float(specs.get('min', 0))
             smax = float(specs.get('max', 0))
             error = float(specs.get('error', 0))
             target = float(specs.get('result', 0))
             result = float(item['Result'])
             error_amount = ((target / 100) * error) if target > 0 else 0
             upper = smax + error_amount
             lower = smin - error_amount
             anrow = {
                 'date': cap_date,
                 'min': smin,
                 'max': smax,
                 'target': target,
                 'error': error,
                 'erroramount': error_amount,
                 'upper': upper,
                 'lower': lower,
                 'result': result,
                 'unit': item['Unit'],
                 'id': item['uid']
             }
             anrows.append(anrow)
             trows[qcid] = anrows
             self.anjson[serviceref] = trows
         except:
             pass
Ejemplo n.º 5
0
    def add_analysis(self, analysis):
        """Adds an analysis to be consumed by the Analyses Chart machinery (js)

        :param analysis_object: analysis to be rendered in the chart
        """
        analysis_object = api.get_object(analysis)
        result = analysis_object.getResult()
        results_range = analysis_object.getResultsRange()
        range_result = results_range.get('result', None)
        range_min = results_range.get('min', None)
        range_max = results_range.get('max', None)
        # All them must be floatable
        for value in [result, range_result, range_min, range_max]:
            if not api.is_floatable(value):
                return
        cap_date = analysis_object.getResultCaptureDate()
        cap_date = api.is_date(cap_date) and \
                   cap_date.strftime('%Y-%m-%d %I:%M %p') or ''
        if not cap_date:
            return

        # Create json
        ref_sample_id = analysis_object.getSample().getId()
        as_keyword = analysis_object.getKeyword()
        as_name = analysis_object.Title()
        as_ref = '{} ({})'.format(as_name, as_keyword)
        as_rows = self.analyses_dict.get(as_ref, {})
        an_rows = as_rows.get(ref_sample_id, [])
        an_rows.append({
            'date': cap_date,
            'target': api.to_float(range_result),
            'upper': api.to_float(range_max),
            'lower': api.to_float(range_min),
            'result': api.to_float(result),
            'unit': analysis_object.getUnit(),
            'id': api.get_uid(analysis_object)
        })
        as_rows[ref_sample_id] = an_rows
        self.analyses_dict[as_ref] = as_rows
Ejemplo n.º 6
0
    def folderitems(self):
        items = AnalysesView.folderitems(self)
        items.sort(key=itemgetter('CaptureDate'), reverse=True)
        for item in items:
            obj = item['obj']
            # TODO-performance: getting an object
            # Note here the object in items[i]['obj'] is a brain, cause the
            # base class (AnalysesView), calls folderitems(.., classic=False).
            obj = obj.getObject()
            imgtype = ""
            if obj.portal_type == 'ReferenceAnalysis':
                antype = QCANALYSIS_TYPES.getValue(obj.getReferenceType())
                if obj.getReferenceType() == 'c':
                    imgtype = "<img title='%s' src='%s/++resource++bika.lims.images/control.png'/>&nbsp;" % (
                        antype, self.context.absolute_url())
                if obj.getReferenceType() == 'b':
                    imgtype = "<img title='%s' src='%s/++resource++bika.lims.images/blank.png'/>&nbsp;" % (
                        antype, self.context.absolute_url())
                item['replace']['Partition'] = "<a href='%s'>%s</a>" % (
                    obj.aq_parent.absolute_url(), obj.aq_parent.id)
            elif obj.portal_type == 'DuplicateAnalysis':
                antype = QCANALYSIS_TYPES.getValue('d')
                imgtype = "<img title='%s' src='%s/++resource++bika.lims.images/duplicate.png'/>&nbsp;" % (
                    antype, self.context.absolute_url())
                item['sortcode'] = '%s_%s' % (obj.getSample().id,
                                              obj.getKeyword())
            else:
                item['sortcode'] = '%s_%s' % (obj.getSample().id,
                                              obj.getKeyword())

            item['before']['Service'] = imgtype

            # Get retractions field
            pdf = obj.getRetractedAnalysesPdfReport()
            title = ''
            anchor = ''
            try:
                if pdf:
                    filesize = 0
                    title = _('Retractions')
                    anchor = "<a class='pdf' target='_blank' href='%s/at_download/RetractedAnalysesPdfReport'>%s</a>" % \
                             (obj.absolute_url(), _("Retractions"))
                    filesize = pdf.get_size()
                    filesize = filesize / 1024 if filesize > 0 else 0
            except:
                # POSKeyError: 'No blob file'
                # Show the record, but not the link
                title = _('Retraction report unavailable')
                anchor = title
            item['Retractions'] = title
            item['replace']['Retractions'] = anchor

            # Create json
            qcid = obj.aq_parent.getId()
            serviceref = "%s (%s)" % (item['Service'], item['Keyword'])
            trows = self.anjson.get(serviceref, {})
            anrows = trows.get(qcid, [])
            # anid = '%s.%s' % (item['getReferenceAnalysesGroupID'],
            #                   item['id'])

            rr = obj.aq_parent.getResultsRangeDict()
            uid = obj.getServiceUID()
            if uid in rr:
                specs = rr[uid]
                try:
                    smin = float(specs.get('min', 0))
                    smax = float(specs.get('max', 0))
                    error = float(specs.get('error', 0))
                    target = float(specs.get('result', 0))
                    result = float(item['Result'])
                    error_amount = ((target / 100) *
                                    error) if target > 0 else 0
                    upper = smax + error_amount
                    lower = smin - error_amount
                    cap_date = obj.getResultCaptureDate()
                    cap_date = api.is_date(cap_date) and \
                               cap_date.strftime('%Y-%m-%d %I:%M %p') or ''
                    anrow = {
                        'date': cap_date,
                        'min': smin,
                        'max': smax,
                        'target': target,
                        'error': error,
                        'erroramount': error_amount,
                        'upper': upper,
                        'lower': lower,
                        'result': result,
                        'unit': item['Unit'],
                        'id': item['uid']
                    }
                    anrows.append(anrow)
                    trows[qcid] = anrows
                    self.anjson[serviceref] = trows
                except:
                    pass

        return items