Ejemplo n.º 1
0
 def get_analysis_spec(self, analysis):
     if hasattr(analysis, 'getResultsRange'):
         return analysis.getResultsRange()
     if hasattr(analysis.aq_parent, 'getResultsRange'):
         rr = dicts_to_dict(analysis.aq_parent.getResultsRange(), 'keyword')
         return rr.get(analysis.getKeyword(), None)
     if hasattr(analysis.aq_parent, 'getReferenceResults'):
         rr = dicts_to_dict(analysis.aq_parent.getReferenceResults(), 'uid')
         return rr.get(analysis.UID(), None)
     keyword = analysis.getService().getKeyword()
     uid = analysis.UID()
     return {'keyword':keyword, 'uid':uid, 'min':'', 'max':'', 'error':''}
Ejemplo n.º 2
0
 def __call__(self, result=None, specification=None):
     workflow = getToolByName(self.context, 'portal_workflow')
     astate = workflow.getInfoFor(self.context, 'review_state')
     if astate == 'retracted':
         return None
     result = result is not None and str(result) or self.context.getResult()
     if result == '':
         return None
     # if analysis result is not a number, then we assume in range:
     try:
         result = float(str(result))
     except ValueError:
         return None
     # The spec is found in the parent AR's ResultsRange field.
     if not specification:
         rr = dicts_to_dict(self.context.aq_parent.getResultsRange(), 'keyword')
         specification = rr.get(self.context.getKeyword(), None)
         # No specs available, assume in range:
         if not specification:
             return None
     outofrange, acceptable = \
         self.isOutOfRange(result,
                           specification.get('min', ''),
                           specification.get('max', ''),
                           specification.get('error', ''))
     return {
         'out_of_range': outofrange,
         'acceptable': acceptable,
         'spec_values': specification
     }
Ejemplo n.º 3
0
 def __call__(self, result=None, specification=None):
     workflow = getToolByName(self.context, 'portal_workflow')
     astate = workflow.getInfoFor(self.context, 'review_state')
     if astate == 'retracted':
         return None
     result = result is not None and str(result) or self.context.getResult()
     if result == '':
         return None
     # if analysis result is not a number, then we assume in range:
     try:
         result = float(str(result))
     except ValueError:
         return None
     # The spec is found in the parent AR's ResultsRange field.
     if not specification:
         rr = dicts_to_dict(self.context.aq_parent.getResultsRange(),
                            'keyword')
         specification = rr.get(self.context.getKeyword(), None)
         # No specs available, assume in range:
         if not specification:
             return None
     outofrange, acceptable = \
         self.isOutOfRange(result,
                           specification.get('min', ''),
                           specification.get('max', ''),
                           specification.get('error', ''))
     return {
         'out_of_range': outofrange,
         'acceptable': acceptable,
         'spec_values': specification
     }
Ejemplo n.º 4
0
    def get_specs_from_request(self, dicts_to_dict_rr=None):
        """Specifications for analyses are given on the request in *Spec

        >>> portal = layer['portal']
        >>> portal_url = portal.absolute_url()
        >>> from plone.app.testing import SITE_OWNER_NAME
        >>> from plone.app.testing import SITE_OWNER_PASSWORD

        >>> browser = layer['getBrowser'](portal, loggedIn=True, username=SITE_OWNER_NAME, password=SITE_OWNER_PASSWORD)
        >>> browser.open(portal_url+"/@@API/create", "&".join([
        ... "obj_type=AnalysisRequest",
        ... "Client=portal_type:Client|id:client-1",
        ... "SampleType=portal_type:SampleType|title:Apple Pulp",
        ... "Contact=portal_type:Contact|getFullname:Rita Mohale",
        ... "Services:list=portal_type:AnalysisService|title:Calcium",
        ... "Services:list=portal_type:AnalysisService|title:Copper",
        ... "Services:list=portal_type:AnalysisService|title:Magnesium",
        ... "SamplingDate=2013-09-29",
        ... "Specification=portal_type:AnalysisSpec|title:Apple Pulp",
        ... 'ResultsRange=[{"keyword":"Cu","min":5,"max":10,"error":10},{"keyword":"Mg","min":6,"max":11,"error":11}]',
        ... ]))
        >>> browser.contents
        '{..."success": true...}'

        """

        # valid output for ResultsRange goes here.
        specs = []

        context = self.context
        request = self.request
        brains = resolve_request_lookup(context, request, "Specification")
        spec_rr = brains[0].getObject().getResultsRange() if brains else {}
        spec_rr = dicts_to_dict(spec_rr, 'keyword')
        #
        bsc = getToolByName(context, "bika_setup_catalog")
        req_rr = request.get('ResultsRange', "[]")
        try:
            req_rr = json.loads(req_rr)
        except:
            raise BadRequest("Invalid value for ResultsRange (%s)"%req_rr)
        req_rr = dicts_to_dict(req_rr, 'keyword')
        #
        spec_rr.update(req_rr)

        return spec_rr.values()
Ejemplo n.º 5
0
 def get_analysis_spec(self, analysis):
     if hasattr(analysis, 'getResultsRange'):
         return analysis.getResultsRange()
     if hasattr(analysis.aq_parent, 'getResultsRange'):
         rr = dicts_to_dict(analysis.aq_parent.getResultsRange(), 'keyword')
         return rr.get(analysis.getKeyword(), None)
     if hasattr(analysis.aq_parent, 'getReferenceResults'):
         rr = dicts_to_dict(analysis.aq_parent.getReferenceResults(), 'uid')
         return rr.get(analysis.UID(), None)
     keyword = analysis.getService().getKeyword()
     uid = analysis.UID()
     return {
         'keyword': keyword,
         'uid': uid,
         'min': '',
         'max': '',
         'error': ''
     }
    def __call__(self):
        bsc = getToolByName(self.context, 'bika_setup_catalog')
        bac = getToolByName(self.context, 'bika_analysis_catalog')
        self.report_content = {}
        parms = []
        headings = {}
        headings['header'] = _("Analyses out of range")
        headings['subheader'] = _("Analyses results out of specified range")

        count_all = 0

        query = {"portal_type": "Analysis",
                 "sort_order": "reverse"}

        spec_uid = self.request.form.get("spec", False)
        spec_obj = None
        spec_title = ""
        if spec_uid:
            brains = bsc(UID=spec_uid)
            if brains:
                spec_obj = brains[0].getObject()
                spec_title = spec_obj.Title()
        parms.append(
            {"title": _("Range spec"),
             "value": spec_title,
             "type": "text"})

        date_query = formatDateQuery(self.context, 'Received')
        if date_query:
            query['getDateReceived'] = date_query
            received = formatDateParms(self.context, 'Received')
        else:
            received = 'Undefined'
        parms.append(
            {'title': _('Received'),
             'value': received,
             'type': 'text'})

        wf_tool = getToolByName(self.context, 'portal_workflow')
        if self.request.form.has_key('bika_analysis_workflow'):
            query['review_state'] = self.request.form['bika_analysis_workflow']
            review_state = wf_tool.getTitleForStateOnType(
                self.request.form['bika_analysis_workflow'], 'Analysis')
        else:
            review_state = 'Undefined'
        parms.append(
            {'title': _('Status'),
             'value': review_state,
             'type': 'text'})

        if self.request.form.has_key('bika_cancellation_workflow'):
            query['cancellation_state'] = self.request.form[
                'bika_cancellation_workflow']
            cancellation_state = wf_tool.getTitleForStateOnType(
                self.request.form['bika_cancellation_workflow'], 'Analysis')
        else:
            cancellation_state = 'Undefined'
        parms.append(
            {'title': _('Active'),
             'value': cancellation_state,
             'type': 'text'})

        if self.request.form.has_key('bika_worksheetanalysis_workflow'):
            query['worksheetanalysis_review_state'] = self.request.form[
                'bika_worksheetanalysis_workflow']
            ws_review_state = wf_tool.getTitleForStateOnType(
                self.request.form['bika_worksheetanalysis_workflow'], 'Analysis')
        else:
            ws_review_state = 'Undefined'
        parms.append(
            {'title': _('Assigned to worksheet'),
             'value': ws_review_state,
             'type': 'text'})

        # and now lets do the actual report lines
        col_heads = [_('Client'),
                     _('Request'),
                     _('Sample type'),
                     _('Sample point'),
                     _('Category'),
                     _('Analysis'),
                     _('Result'),
                     _('Min'),
                     _('Max'),
                     _('Status'),
        ]
        if isAttributeHidden('Sample', 'SamplePoint'):
            col_heads.remove(_('Sample point'))

        formats = {'columns': 10,
                   'col_heads': col_heads,
                   'class': '',
        }

        datalines = []

        for a_proxy in bac(query):
            analysis = a_proxy.getObject()
            if analysis.getResult():
                try:
                    result = float(analysis.getResult())
                except:
                    continue
            else:
                continue

            keyword = analysis.getKeyword()

            # determine which specs to use for this particular analysis
            # 1) if a spec is given in the query form, use it.
            # 2) if a spec is entered directly on the analysis, use it.
            # otherwise just continue to the next object.
            spec_dict = False
            if spec_obj:
                rr = spec_obj.getResultsRangeDict()
                if keyword in rr:
                    spec_dict = rr[keyword]
            else:
                ar = analysis.aq_parent
                rr = dicts_to_dict(ar.getResultsRange(), 'keyword')
                if keyword in rr:
                    spec_dict = rr[keyword]
                else:
                    continue
            if not spec_dict:
                continue
            try:
                spec_min = float(spec_dict['min'])
                spec_max = float(spec_dict['max'])
            except ValueError:
                continue
            if spec_min <= result <= spec_max:
                continue

            # check if in shoulder: out of range, but in acceptable
            # error percentage
            shoulder = False
            error = 0
            try:
                error = float(spec_dict.get('error', '0'))
            except:
                error = 0
                pass
            error_amount = (result / 100) * error
            error_min = result - error_amount
            error_max = result + error_amount
            if ((result < spec_min) and (error_max >= spec_min)) or \
                    ((result > spec_max) and (error_min <= spec_max)):
                shoulder = True

            dataline = []

            dataitem = {'value': analysis.getClientTitle()}
            dataline.append(dataitem)

            dataitem = {'value': analysis.getRequestID()}
            dataline.append(dataitem)

            dataitem = {'value': analysis.aq_parent.getSampleTypeTitle()}
            dataline.append(dataitem)

            if isAttributeHidden('Sample', 'SamplePoint'):
                dataitem = {'value': analysis.aq_parent.getSamplePointTitle()}
                dataline.append(dataitem)

            dataitem = {'value': analysis.getCategoryTitle()}
            dataline.append(dataitem)

            dataitem = {'value': analysis.getServiceTitle()}
            dataline.append(dataitem)

            if shoulder:
                dataitem = {'value': analysis.getResult(),
                            'img_after': '++resource++bika.lims.images/exclamation.png'}
            else:
                dataitem = {'value': analysis.getResult()}

            dataline.append(dataitem)

            dataitem = {'value': spec_dict['min']}
            dataline.append(dataitem)

            dataitem = {'value': spec_dict['max']}
            dataline.append(dataitem)

            state = wf_tool.getInfoFor(analysis, 'review_state', '')
            review_state = wf_tool.getTitleForStateOnType(
                state, 'Analysis')
            dataitem = {'value': review_state}
            dataline.append(dataitem)

            datalines.append(dataline)

            count_all += 1

        # table footer data
        footlines = []
        footline = []
        footitem = {'value': _('Number of analyses out of range for period'),
                    'colspan': 9,
                    'class': 'total_label'}
        footline.append(footitem)
        footitem = {'value': count_all}
        footline.append(footitem)
        footlines.append(footline)

        # report footer data
        footnotes = []
        footline = []
        footitem = {'value': _('Analysis result within error range'),
                    'img_before': '++resource++bika.lims.images/exclamation.png'
        }
        footline.append(footitem)
        footnotes.append(footline)

        self.report_content = {
            'headings': headings,
            'parms': parms,
            'formats': formats,
            'datalines': datalines,
            'footings': footlines,
            'footnotes': footnotes}

        title = t(headings['header'])

        return {'report_title': title,
                'report_data': self.template()}
 def get_analysis_spec(self, analysis):
     rr = dicts_to_dict(analysis.aq_parent.getResultsRange(), 'keyword')
     return rr.get(analysis.getKeyword(), None)
 def get_analysis_spec(self, analysis):
     rr = dicts_to_dict(analysis.aq_parent.getResultsRange(), 'keyword')
     return rr.get(analysis.getKeyword(), None)
Ejemplo n.º 9
0
 def get_spec_from_ar(self, ar, keyword):
     empty = {'min': '', 'max': '', 'error': '', 'keyword':keyword}
     spec = ar.getResultsRange()
     if spec:
         return dicts_to_dict(spec, 'keyword').get(keyword, empty)
     return empty
    def __call__(self):
        bsc = getToolByName(self.context, 'bika_setup_catalog')
        bac = getToolByName(self.context, 'bika_analysis_catalog')
        self.report_content = {}
        parms = []
        headings = {}
        headings['header'] = _("Analyses out of range")
        headings['subheader'] = _("Analyses results out of specified range")

        count_all = 0

        query = {"portal_type": "Analysis", "sort_order": "reverse"}

        spec_uid = self.request.form.get("spec", False)
        spec_obj = None
        spec_title = ""
        if spec_uid:
            brains = bsc(UID=spec_uid)
            if brains:
                spec_obj = brains[0].getObject()
                spec_title = spec_obj.Title()
        parms.append({
            "title": _("Range spec"),
            "value": spec_title,
            "type": "text"
        })

        date_query = formatDateQuery(self.context, 'Received')
        if date_query:
            query['getDateReceived'] = date_query
            received = formatDateParms(self.context, 'Received')
        else:
            received = 'Undefined'
        parms.append({
            'title': _('Received'),
            'value': received,
            'type': 'text'
        })

        wf_tool = getToolByName(self.context, 'portal_workflow')
        if self.request.form.has_key('bika_analysis_workflow'):
            query['review_state'] = self.request.form['bika_analysis_workflow']
            review_state = wf_tool.getTitleForStateOnType(
                self.request.form['bika_analysis_workflow'], 'Analysis')
        else:
            review_state = 'Undefined'
        parms.append({
            'title': _('Status'),
            'value': review_state,
            'type': 'text'
        })

        if self.request.form.has_key('bika_cancellation_workflow'):
            query['cancellation_state'] = self.request.form[
                'bika_cancellation_workflow']
            cancellation_state = wf_tool.getTitleForStateOnType(
                self.request.form['bika_cancellation_workflow'], 'Analysis')
        else:
            cancellation_state = 'Undefined'
        parms.append({
            'title': _('Active'),
            'value': cancellation_state,
            'type': 'text'
        })

        if self.request.form.has_key('bika_worksheetanalysis_workflow'):
            query['worksheetanalysis_review_state'] = self.request.form[
                'bika_worksheetanalysis_workflow']
            ws_review_state = wf_tool.getTitleForStateOnType(
                self.request.form['bika_worksheetanalysis_workflow'],
                'Analysis')
        else:
            ws_review_state = 'Undefined'
        parms.append({
            'title': _('Assigned to worksheet'),
            'value': ws_review_state,
            'type': 'text'
        })

        # and now lets do the actual report lines
        col_heads = [
            _('Client'),
            _('Request'),
            _('Sample type'),
            _('Sample point'),
            _('Category'),
            _('Analysis'),
            _('Result'),
            _('Min'),
            _('Max'),
            _('Status'),
        ]
        if isAttributeHidden('Sample', 'SamplePoint'):
            col_heads.remove(_('Sample point'))

        formats = {
            'columns': 10,
            'col_heads': col_heads,
            'class': '',
        }

        datalines = []

        for a_proxy in bac(query):
            analysis = a_proxy.getObject()
            if analysis.getResult():
                try:
                    result = float(analysis.getResult())
                except:
                    continue
            else:
                continue

            keyword = analysis.getKeyword()

            # determine which specs to use for this particular analysis
            # 1) if a spec is given in the query form, use it.
            # 2) if a spec is entered directly on the analysis, use it.
            # otherwise just continue to the next object.
            spec_dict = False
            if spec_obj:
                rr = spec_obj.getResultsRangeDict()
                if keyword in rr:
                    spec_dict = rr[keyword]
            else:
                ar = analysis.aq_parent
                rr = dicts_to_dict(ar.getResultsRange(), 'keyword')
                if keyword in rr:
                    spec_dict = rr[keyword]
                else:
                    continue
            if not spec_dict:
                continue
            try:
                spec_min = float(spec_dict['min'])
                spec_max = float(spec_dict['max'])
            except ValueError:
                continue
            if spec_min <= result <= spec_max:
                continue

            # check if in shoulder: out of range, but in acceptable
            # error percentage
            shoulder = False
            error = 0
            try:
                error = float(spec_dict.get('error', '0'))
            except:
                error = 0
                pass
            error_amount = (result / 100) * error
            error_min = result - error_amount
            error_max = result + error_amount
            if ((result < spec_min) and (error_max >= spec_min)) or \
                    ((result > spec_max) and (error_min <= spec_max)):
                shoulder = True

            dataline = []

            dataitem = {'value': analysis.getClientTitle()}
            dataline.append(dataitem)

            dataitem = {'value': analysis.getRequestID()}
            dataline.append(dataitem)

            dataitem = {'value': analysis.aq_parent.getSampleTypeTitle()}
            dataline.append(dataitem)

            if isAttributeHidden('Sample', 'SamplePoint'):
                dataitem = {'value': analysis.aq_parent.getSamplePointTitle()}
                dataline.append(dataitem)

            dataitem = {'value': analysis.getCategoryTitle()}
            dataline.append(dataitem)

            dataitem = {'value': analysis.getServiceTitle()}
            dataline.append(dataitem)

            if shoulder:
                dataitem = {
                    'value': analysis.getResult(),
                    'img_after': '++resource++bika.lims.images/exclamation.png'
                }
            else:
                dataitem = {'value': analysis.getResult()}

            dataline.append(dataitem)

            dataitem = {'value': spec_dict['min']}
            dataline.append(dataitem)

            dataitem = {'value': spec_dict['max']}
            dataline.append(dataitem)

            state = wf_tool.getInfoFor(analysis, 'review_state', '')
            review_state = wf_tool.getTitleForStateOnType(state, 'Analysis')
            dataitem = {'value': review_state}
            dataline.append(dataitem)

            datalines.append(dataline)

            count_all += 1

        # table footer data
        footlines = []
        footline = []
        footitem = {
            'value': _('Number of analyses out of range for period'),
            'colspan': 9,
            'class': 'total_label'
        }
        footline.append(footitem)
        footitem = {'value': count_all}
        footline.append(footitem)
        footlines.append(footline)

        # report footer data
        footnotes = []
        footline = []
        footitem = {
            'value': _('Analysis result within error range'),
            'img_before': '++resource++bika.lims.images/exclamation.png'
        }
        footline.append(footitem)
        footnotes.append(footline)

        self.report_content = {
            'headings': headings,
            'parms': parms,
            'formats': formats,
            'datalines': datalines,
            'footings': footlines,
            'footnotes': footnotes
        }

        title = t(headings['header'])

        return {'report_title': title, 'report_data': self.template()}
Ejemplo n.º 11
0
 def analysis_specification(self):
     ar = self.context.aq_parent
     rr = dicts_to_dict(ar.getResultsRange(),'keyword')
     
     return rr[self.context.getService().getKeyword()]
Ejemplo n.º 12
0
    def analysis_specification(self):
        ar = self.context.aq_parent
        rr = dicts_to_dict(ar.getResultsRange(), 'keyword')

        return rr[self.context.getService().getKeyword()]