def add_filter_by_date(self, query, out_params):
     """Applies the filter by Requested date to the search query
     """
     date_query = formatDateQuery(self.context, 'Requested')
     if date_query:
         query['created'] = date_query
         requested = formatDateParms(self.context, 'Requested')
         out_params.append({'title': _('Requested'),
                            'value': requested,
                            'type': 'text'})
Exemplo n.º 2
0
 def add_filter_by_date_range(self, query, out_params):
     date_query = formatDateQuery(self.context, "tats_DateReceived")
     if not date_query:
         return
     query["getDateReceived"] = date_query
     out_params.append({
         "title":
         _("Received"),
         "value":
         formatDateParms(self.context, "Tats_DateReceived"),
         "type":
         "text"
     })
Exemplo n.º 3
0
    def __call__(self):
        # get all the data into datalines

        pc = getToolByName(self.context, 'portal_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.report_content = {}
        parms = []
        headings = {}
        headings['header'] = _("Attachments")
        headings['subheader'] = _(
            "The attachments linked to analysis requests and analyses")

        count_all = 0
        query = {'portal_type': 'Attachment'}
        if 'ClientUID' in self.request.form:
            client_uid = self.request.form['ClientUID']
            query['getClientUID'] = client_uid
            client = rc.lookupObject(client_uid)
            client_title = client.Title()
        else:
            client = logged_in_client(self.context)
            if client:
                client_title = client.Title()
                query['getClientUID'] = client.UID()
            else:
                client_title = 'All'
        parms.append({
            'title': _('Client'),
            'value': client_title,
            'type': 'text'
        })

        date_query = formatDateQuery(self.context, 'Loaded')
        if date_query:
            query['getDateLoaded'] = date_query
            loaded = formatDateParms(self.context, 'Loaded')
            parms.append({
                'title': _('Loaded'),
                'value': loaded,
                'type': 'text'
            })

        # and now lets do the actual report lines
        formats = {
            'columns':
            6,
            'col_heads': [
                _('Request'),
                _('File'),
                _('Attachment type'),
                _('Content type'),
                _('Size'),
                _('Loaded'),
            ],
            'class':
            '',
        }

        datalines = []
        attachments = pc(query)
        for a_proxy in attachments:
            attachment = a_proxy.getObject()
            attachment_file = attachment.getAttachmentFile()
            icon = attachment_file.icon
            filename = attachment_file.filename
            filesize = attachment_file.get_size()
            filesize = filesize / 1024
            sizeunit = "Kb"
            if filesize > 1024:
                filesize = filesize / 1024
                sizeunit = "Mb"
            dateloaded = attachment.getDateLoaded()
            dataline = []
            dataitem = {'value': attachment.Title()}
            dataline.append(dataitem)
            dataitem = {'value': filename, 'img_before': icon}
            dataline.append(dataitem)
            dataitem = {
                'value':
                attachment.getAttachmentType().Title()
                if attachment.getAttachmentType() else ''
            }
            dataline.append(dataitem)
            dataitem = {
                'value':
                self.context.lookupMime(attachment_file.getContentType())
            }
            dataline.append(dataitem)
            dataitem = {'value': '%s%s' % (filesize, sizeunit)}
            dataline.append(dataitem)
            dataitem = {'value': self.ulocalized_time(dateloaded)}
            dataline.append(dataitem)

            datalines.append(dataline)

            count_all += 1

        # footer data
        footlines = []
        footline = []
        footitem = {'value': _('Total'), 'colspan': 5, 'class': 'total_label'}
        footline.append(footitem)
        footitem = {'value': count_all}
        footline.append(footitem)
        footlines.append(footline)

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

        if self.request.get('output_format', '') == 'CSV':
            import csv
            import StringIO
            import datetime

            fieldnames = [
                _('Request'),
                _('File'),
                _('Attachment type'),
                _('Content type'),
                _('Size'),
                _('Loaded'),
            ]
            output = StringIO.StringIO()
            dw = csv.DictWriter(output, fieldnames=fieldnames)
            dw.writerow(dict((fn, fn) for fn in fieldnames))
            for row in datalines:
                dw.writerow(row)
            report_data = output.getvalue()
            output.close()
            date = datetime.datetime.now().strftime("%Y%m%d%H%M")
            setheader = self.request.RESPONSE.setHeader
            setheader('Content-Type', 'text/csv')
            setheader(
                "Content-Disposition",
                "attachment;filename=\"analysesattachments_%s.csv\"" % date)
            self.request.RESPONSE.write(report_data)
        else:
            return {
                'report_title': t(headings['header']),
                'report_data': self.template()
            }
Exemplo n.º 4
0
    def __call__(self):
        # get all the data into datalines

        sc = getToolByName(self.context, 'bika_setup_catalog')
        bc = getToolByName(self.context, 'bika_analysis_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        headings['header'] = _("Analyses per analysis service")
        headings['subheader'] = _(
            "Number of analyses requested per analysis service")

        query = {'portal_type': 'Analysis'}
        if self.request.form.has_key('ClientUID'):
            client_uid = self.request.form['ClientUID']
            query['getClientUID'] = client_uid
            client = rc.lookupObject(client_uid)
            client_title = client.Title()
        else:
            client = logged_in_client(self.context)
            if client:
                client_title = client.Title()
                query['getClientUID'] = client.UID()
            else:
                client_title = _('All')
        parms.append({
            'title': _('Client'),
            'value': client_title,
            'type': 'text'
        })

        date_query = formatDateQuery(self.context, 'Requested')
        if date_query:
            query['created'] = date_query
            requested = formatDateParms(self.context, 'Requested')
            parms.append({
                'title': _('Requested'),
                'value': requested,
                'type': 'text'
            })

        date_query = formatDateQuery(self.context, 'Published')
        if date_query:
            query['getDatePublished'] = date_query
            published = formatDateParms(self.context, 'Published')
            parms.append({
                'title': _('Published'),
                'value': published,
                'type': 'text'
            })

        workflow = 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 = workflow.getTitleForStateOnType(
                self.request.form['bika_analysis_workflow'], 'Analysis')
            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 = workflow.getTitleForStateOnType(
                self.request.form['bika_cancellation_workflow'], 'Analysis')
            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 = workflow.getTitleForStateOnType(
                self.request.form['bika_worksheetanalysis_workflow'],
                'Analysis')
            parms.append({
                'title': _('Assigned to worksheet'),
                'value': ws_review_state,
                'type': 'text'
            })

        # and now lets do the actual report lines
        formats = {
            'columns': 2,
            'col_heads': [_('Analysis service'),
                          _('Number of analyses')],
            'class': '',
        }

        datalines = []
        count_all = 0
        for cat in sc(portal_type="AnalysisCategory",
                      sort_on='sortable_title'):
            dataline = [
                {
                    'value': cat.Title,
                    'class': 'category_heading',
                    'colspan': 2
                },
            ]
            datalines.append(dataline)
            for service in sc(portal_type="AnalysisService",
                              getCategoryUID=cat.UID,
                              sort_on='sortable_title'):
                query['getServiceUID'] = service.UID
                analyses = bc(query)
                count_analyses = len(analyses)

                dataline = []
                dataitem = {'value': service.Title}
                dataline.append(dataitem)
                dataitem = {'value': count_analyses}

                dataline.append(dataitem)

                datalines.append(dataline)

                count_all += count_analyses

        # footer data
        footlines = []
        footline = []
        footitem = {'value': _('Total'), 'class': 'total_label'}
        footline.append(footitem)
        footitem = {'value': count_all}
        footline.append(footitem)
        footlines.append(footline)

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

        title = self.context.translate(headings['header'])
        return {'report_title': title, 'report_data': self.template()}
    def __call__(self):
        # get all the data into datalines

        pc = getToolByName(self.context, 'portal_catalog')
        bac = getToolByName(self.context, 'bika_analysis_catalog')
        bc = getToolByName(self.context, 'bika_catalog')
        rc = getToolByName(self.context, 'reference_catalog')

        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}        
        count_all_ars = 0
        count_all_analyses = 0
        query = {}

        this_client = logged_in_client(self.context)

        if not this_client and self.request.form.has_key('ClientUID'):
            client_uid = self.request.form['ClientUID']
            this_client = rc.lookupObject(client_uid)
            parms.append(
                { 'title': _('Client'),
                 'value': this_client.Title(),
                 'type': 'text'})

        if this_client:
            headings['header'] = _("Analysis requests and analyses")
            headings['subheader'] = _("Number of Analysis requests and analyses")
        else:
            headings['header'] = _("Analysis requests and analyses per client")
            headings['subheader'] = _("Number of Analysis requests and analyses per client")

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

        workflow = 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 = workflow.getTitleForStateOnType(self.request.form['bika_analysis_workflow'], 'Analysis')
            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 = workflow.getTitleForStateOnType(
                        self.request.form['bika_cancellation_workflow'], 'Analysis')
            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 = workflow.getTitleForStateOnType(
                        self.request.form['bika_worksheetanalysis_workflow'], 'Analysis')
            parms.append({'title': _('Assigned to worksheet'), 'value': ws_review_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 = workflow.getTitleForStateOnType(
                        self.request.form['bika_worksheetanalysis_workflow'], 'Analysis')
            parms.append({'title': _('Assigned to worksheet'), 'value': ws_review_state, 'type': 'text'})
        
        # and now lets do the actual report lines
        formats = {'columns': 3,
                   'col_heads': [ _('Client'),
                                  _('Number of requests'),
                                  _('Number of analyses')],
                   'class': ''}

        datalines = []

        if this_client:
            c_proxies = pc(portal_type="Client", UID=this_client.UID())
        else:
            c_proxies = pc(portal_type="Client", sort_on='sortable_title')

        for client in c_proxies:
            query['getClientUID'] = client.UID
            dataline = [{'value': client.Title },]
            query['portal_type'] = 'AnalysisRequest'
            ars = bc(query)
            count_ars = len(ars)
            dataitem = {'value': count_ars}
            dataline.append(dataitem)

            query['portal_type'] = 'Analysis'
            analyses = bac(query)
            count_analyses = len(analyses)
            dataitem = {'value': count_analyses }
            dataline.append(dataitem)


            datalines.append(dataline)

            count_all_analyses += count_analyses
            count_all_ars += count_ars

        # footer data
        footlines = []
        if not this_client:
            footline = []
            footitem = {'value': _('Total'),
                        'class': 'total_label'}
            footline.append(footitem)

            footitem = {'value': count_all_ars}
            footline.append(footitem)
            footitem = {'value': count_all_analyses}
            footline.append(footitem)

            footlines.append(footline)


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


        return {'report_title': self.context.translate(headings['header']),
                'report_data': self.template()}
    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
                ar_spec_obj = ar.getSpecification()
                if ar_spec_obj:
                    rr = ar_spec_obj.getResultsRangeDict()
                    if keyword in rr:
                        spec_dict = rr[keyword]
                else:
                    if hasattr(analysis, "specification") \
                            and analysis.specification:
                        spec_dict = analysis.specification
                    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 __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"}

        if self.request.form.get("spec", ""):
            spec_uid = self.request.form["spec"]
            spec_obj = bsc(UID=spec_uid).getObject()
            spec_title = spec_obj.Title()
        else:
            spec_uid = ""
            spec_obj = None
            spec_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
        formats = {
            "columns": 10,
            "col_heads": [
                _("Client"),
                _("Request"),
                _("Sample type"),
                _("Sample point"),
                _("Category"),
                _("Analysis"),
                _("Result"),
                _("Min"),
                _("Max"),
                _("Status"),
            ],
            "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.
            if spec_obj:
                rr = spec_obj.getResultsRangeDict()
                if keyword in rr:
                    spec_dict = rr[keyword]
            else:
                ar = analysis.aq_parent
                ar_spec_obj = ar.getSpecification()
                if ar_spec_obj:
                    rr = ar_spec_obj.getResultsRangeDict()
                    if keyword in rr:
                        spec_dict = rr[keyword]
                else:
                    if hasattr(analysis, "specification") and analysis.specification:
                        spec_dict = analysis.specification
                    else:
                        continue

            spec_min = float(spec_dict["min"])
            spec_max = float(spec_dict["max"])
            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)

            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 = self.context.translate(headings["header"])

        return {"report_title": title, "report_data": self.template()}
    def __call__(self):
        # get all the data into datalines

        bc = getToolByName(self.context, 'bika_analysis_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.report_content = {}
        parms = []
        headings = {}
        headings['header'] = _("Analysis turnaround times over time")
        headings['subheader'] = \
               _("The turnaround time of analyses plotted over time")

        query = {'portal_type': 'Analysis'}

        if 'ServiceUID' in self.request.form:
            service_uid = self.request.form['ServiceUID']
            query['ServiceUID'] = service_uid
            service = rc.lookupObject(service_uid)
            service_title = service.Title()
            parms.append(
                {'title': _('Analysis Service'),
                 'value': service_title,
                 'type': 'text'})

        if 'Analyst' in self.request.form:
            analyst = self.request.form['Analyst']
            query['getAnalyst'] = analyst
            analyst_title = self.user_fullname(analyst)
            parms.append(
                {'title': _('Analyst'),
                 'value': analyst_title,
                 'type': 'text'})

        if 'getInstrumentUID' in self.request.form:
            instrument_uid = self.request.form['getInstrumentUID']
            query['getInstrument'] = instrument_uid
            instrument = rc.lookupObject(instrument_uid)
            instrument_title = instrument.Title()
            parms.append(
                {'title': _('Instrument'),
                 'value': instrument_title,
                 'type': 'text'})

        if 'Period' in self.request.form:
            period = self.request.form['Period']
        else:
            period = 'Day'

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

        query['review_state'] = 'published'

        # query all the analyses and increment the counts

        periods = {}
        total_count = 0
        total_duration = 0

        analyses = bc(query)
        for a in analyses:
            analysis = a.getObject()
            received = analysis.created()
            if period == 'Day':
                datekey = received.strftime('%d %b %Y')
            elif period == 'Week':
                # key period on Monday
                dayofweek = received.strftime('%w')  # Sunday = 0
                if dayofweek == 0:
                    firstday = received - 6
                else:
                    firstday = received - (int(dayofweek) - 1)
                datekey = firstday.strftime(self.date_format_short)
            elif period == 'Month':
                datekey = received.strftime('%m-%d')
            if datekey not in periods:
                periods[datekey] = {'count': 0,
                                    'duration': 0,
                                   }
            count = periods[datekey]['count']
            duration = periods[datekey]['duration']
            count += 1
            duration += analysis.getDuration()
            periods[datekey]['duration'] = duration
            periods[datekey]['count'] = count
            total_count += 1
            total_duration += duration

        # calculate averages
        for datekey in periods.keys():
            count = periods[datekey]['count']
            duration = periods[datekey]['duration']
            ave_duration = (duration) / count
            periods[datekey]['duration'] = \
                formatDuration(self.context, ave_duration)

        # and now lets do the actual report lines
        formats = {'columns': 2,
                   'col_heads': [_('Date'),
                                  _('Turnaround time (h)'),
                                  ],
                   'class': '',
                  }

        datalines = []

        period_keys = periods.keys()
        for period in period_keys:
            dataline = [{'value': period,
                        'class': ''}, ]
            dataline.append({'value': periods[period]['duration'],
                             'class': 'number'})
            datalines.append(dataline)

        if total_count > 0:
            ave_total_duration = total_duration / total_count
        else:
            ave_total_duration = 0
        ave_total_duration = formatDuration(self.context, ave_total_duration)

        # footer data
        footlines = []
        footline = []
        footline = [{'value': _('Total data points'),
                     'class': 'total'}, ]

        footline.append({'value': total_count,
                         'class': 'total number'})
        footlines.append(footline)

        footline = [{'value': _('Average TAT'),
                     'class': 'total'}, ]

        footline.append({'value': ave_total_duration,
                         'class': 'total number'})
        footlines.append(footline)

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

        if self.request.get('output_format', '') == 'CSV':
            import csv
            import StringIO
            import datetime
            fieldnames = [
                'Date',
                'Turnaround time (h)',
            ]
            output = StringIO.StringIO()
            dw = csv.DictWriter(output, extrasaction='ignore', fieldnames=fieldnames)
            dw.writerow(dict((fn, fn) for fn in fieldnames))
            for row in datalines:
                dw.writerow({
                    'Date': row[0]['value'],
                    'Turnaround time (h)': row[1]['value'],
                })
            report_data = output.getvalue()
            output.close()
            date = datetime.datetime.now().strftime("%Y%m%d%H%M")
            setheader = self.request.RESPONSE.setHeader
            setheader('Content-Type', 'text/csv')
            setheader("Content-Disposition",
                "attachment;filename=\"analysesperservice_%s.csv\"" % date)
            self.request.RESPONSE.write(report_data)
        else:
            return {'report_title': self.context.translate(headings['header']),
                    'report_data': self.template()}
    def __call__(self):
        # get all the data into datalines

        sc = getToolByName(self.context, 'bika_setup_catalog')
        bc = getToolByName(self.context, 'bika_analysis_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.report_content = {}
        parms = []
        headings = {}
        headings['header'] = _("Analyses per analysis service")
        headings['subheader'] = _(
            "Number of analyses requested per analysis service")

        query = {'portal_type': 'Analysis'}
        client_title = None
        if 'ClientUID' in self.request.form:
            client_uid = self.request.form['ClientUID']
            query['getClientUID'] = client_uid
            client = rc.lookupObject(client_uid)
            client_title = client.Title()
        else:
            client = logged_in_client(self.context)
            if client:
                client_title = client.Title()
                query['getClientUID'] = client.UID()
        if client_title:
            parms.append(
                {'title': _('Client'), 'value': client_title, 'type': 'text'})

        date_query = formatDateQuery(self.context, 'Requested')
        if date_query:
            query['created'] = date_query
            requested = formatDateParms(self.context, 'Requested')
            parms.append(
                {'title': _('Requested'), 'value': requested, 'type': 'text'})

        date_query = formatDateQuery(self.context, 'Published')
        if date_query:
            query['getDatePublished'] = date_query
            published = formatDateParms(self.context, 'Published')
            parms.append(
                {'title': _('Published'), 'value': published, 'type': 'text'})

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

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

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

        # and now lets do the actual report lines
        formats = {'columns': 2,
                   'col_heads': [_('Analysis service'), _('Number of analyses')],
                   'class': '',
        }

        datalines = []
        count_all = 0
        for cat in sc(portal_type="AnalysisCategory",
                      sort_on='sortable_title'):
            dataline = [{'value': cat.Title,
                         'class': 'category_heading',
                         'colspan': 2}, ]
            datalines.append(dataline)
            for service in sc(portal_type="AnalysisService",
                              getCategoryUID=cat.UID,
                              sort_on='sortable_title'):
                query['getServiceUID'] = service.UID
                analyses = bc(query)
                count_analyses = len(analyses)

                dataline = []
                dataitem = {'value': service.Title}
                dataline.append(dataitem)
                dataitem = {'value': count_analyses}

                dataline.append(dataitem)

                datalines.append(dataline)

                count_all += count_analyses

        # footer data
        footlines = []
        footline = []
        footitem = {'value': _('Total'),
                    'class': 'total_label'}
        footline.append(footitem)
        footitem = {'value': count_all}
        footline.append(footitem)
        footlines.append(footline)

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

        title = t(headings['header'])

        if self.request.get('output_format', '') == 'CSV':
            import csv
            import StringIO
            import datetime

            fieldnames = [
                'Analysis Service',
                'Analyses',
            ]
            output = StringIO.StringIO()
            dw = csv.DictWriter(output, extrasaction='ignore',
                                fieldnames=fieldnames)
            dw.writerow(dict((fn, fn) for fn in fieldnames))
            for row in datalines:
                if len(row) == 1:
                    # category heading thingy
                    continue
                dw.writerow({
                    'Analysis Service': row[0]['value'],
                    'Analyses': row[1]['value'],
                })
            report_data = output.getvalue()
            output.close()
            date = datetime.datetime.now().strftime("%Y%m%d%H%M")
            setheader = self.request.RESPONSE.setHeader
            setheader('Content-Type', 'text/csv')
            setheader("Content-Disposition",
                      "attachment;filename=\"analysesperservice_%s.csv\"" % date)
            self.request.RESPONSE.write(report_data)
        else:
            return {'report_title': title,
                    'report_data': self.template()}
Exemplo n.º 10
0
    def __call__(self):
        # get all the data into datalines
        
        bsc = getToolByName(self.context, 'bika_setup_catalog')
        bac = getToolByName(self.context, 'bika_analysis_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        localTimeFormat = self.context.portal_properties.site_properties.getProperty('localTimeFormat')
        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        headings['header'] = _("Results per sample point")
        headings['subheader'] = _("Analysis results per sample point and analysis service")

        count_all = 0

        query = {'portal_type' : "Analysis",
                 'review_state': 'published',
                 'sort_on'     : 'getDateAnalysisPublished'}
                 
        if self.request.form.has_key('getSamplePointUID'):
            sp_uid = self.request.form['getSamplePointUID']
            query['getSamplePointUID'] = sp_uid
            sp = rc.lookupObject(sp_uid)
            sp_title = sp.Title()
        else:
            sp_title = 'Undefined'
        parms.append(
            { 'title': _('Sample point'),
             'value': sp_title,
             'type': 'text'})

        if self.request.form.has_key('getSampleTypeUID'):
            st_uid = self.request.form['getSampleTypeUID']
            query['getSampleTypeUID'] = st_uid
            st = rc.lookupObject(st_uid)
            st_title = st.Title()
        else:
            st_title = 'Undefined'
        parms.append(
            { 'title': _('Sample type'),
             'value': st_title,
             'type': 'text'})

        service_uids = []
        if self.request.form.has_key('getServiceUID'):
            service_uid = self.request.form['getServiceUID']
            query['getServiceUID'] = service_uid
        if type(service_uid) == str:
            # a single service was selected
            service_uids.append(service_uid)
            no_services = 1
        else:
            # multiple services were selected
            service_uids = list(service_uid)
            no_services = len(service_uids)
        
        service_titles = []
        service_values = {}
        service_counts = {}
        service_oor = {}            # out of range
        service_joor = {}           # just out of range
        service_keys = {}
        for service_uid in service_uids:
            service = rc.lookupObject(service_uid)
            service_titles.append('%s  (%s)' \
                %(service.Title(), service.getUnit()))
            service_values[service_uid] = []
            service_counts[service_uid] = 0
            service_oor[service_uid] = 0
            service_joor[service_uid] = 0
            service_keys[service_uid] = service.getKeyword()
         
        
        date_query = formatDateQuery(self.context, 'DateAnalysisPublished')
        if date_query:
            query['getDateAnalysisPublished'] = date_query
            published = formatDateParms(self.context, 'DateAnalysisPublished') 
        else:
            published = 'Undefined'
        parms.append(
            { 'title': _('Published'),
             'value': published,
             'type': 'text'})

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



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

        # get the lab specs for these services
        specs = {}
        owner_uid = self.context.bika_setup.bika_analysisspecs.UID()
        proxies = bsc(portal_type = 'AnalysisSpec',
                      getSampleTypeUID = st_uid,
                      getClientUID = owner_uid)
        if len(proxies) > 0:
            spec_object = proxies[0].getObject()
            results_range = spec_object.getResultsRangeDict()
            for service_uid in service_uids:
                keyword = service_keys[service_uid]
                if results_range.has_key(keyword):
                    specs[service_uid] = results_range[keyword]


        # and now lets do the actual report lines
        formats = {'columns': no_services + 1,
                   'col_heads': [' ',] + service_titles,
                   'class': '',
                  }

        datalines = []
        dataline = []

        dataline = [{'value':'Specification minimum',
                    'class':'colhead'}, ]
        for service_uid in service_uids:
            dataline.append({'value': specs[service_uid]['min'],
                             'class':'colhead number'})
        datalines.append(dataline)

        dataline = [{'value':'Specification maximum',
                    'class':'colhead'}, ]
        for service_uid in service_uids:
            dataline.append({'value': specs[service_uid]['max'],
                             'class':'colhead number'})
        datalines.append(dataline)

        current = None
        first = True
        def loadlines():
            more = True
            while more:
                thisline = [{'value': current},]
                more = False
                for service_uid in service_uids:
                    if service_values[service_uid]:
                        item = service_values[service_uid].pop(0)
                        if service_values[service_uid]:
                            more = True
                        thisline.append(item)
                    else:
                        thisline.append({'value': '-'})
                datalines.append(thisline)

        joor_img = '++resource++bika.lims.images/warning.png'
        oor_img  = '++resource++bika.lims.images/exclamation.png'
        for a_proxy in bac(query):
            analysis = a_proxy.getObject()
            this_service = analysis.getServiceUID()
            pubdate = analysis.getDateAnalysisPublished()
            published = pubdate.strftime('%d %b %Y')
            if first:
                current = published
                first = False
            if published != current:
                # print the previous date
                loadlines()
                current = published
 
            if analysis.getResult():
                try:
                    result = float(analysis.getResult())
                except:
                    continue

            dataitem = {'value': analysis.getResult(),
                        'class': 'number'}

            # check if in range
            if specs.has_key(this_service):
                spec_min = float(specs[this_service]['min'])
                spec_max = float(specs[this_service]['max'])
                spec_error = float(specs[this_service]['error'])
                if spec_min < result < spec_max:
                    pass
                else:
                    # check if in shoulder: out of range, 
                    # but in acceptable error percentage
                    error_amount = (result / 100) * spec_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)):
                        dataitem['img_before'] = joor_img
                        service_joor[this_service] += 1
                    else:
                        dataitem['img_before'] = oor_img
                        service_oor[this_service] += 1

            service_values[this_service].append(dataitem)
            service_counts[this_service] += 1

        # include the last one
        loadlines()

        # footer data
        footlines = []
        footline = []
        footitem = {'value': _('Total analyses out of range'),
                    'colspan': 1,
                    'class': 'total_label'} 
        footline.append(footitem)
        for service_uid in service_uids:
            footitem = {'value': service_oor[service_uid],
                        'class': 'number'} 
            footline.append(footitem)

        footlines.append(footline)

        footline = []
        footitem = {'value': _('Total analyses within error range'),
                    'colspan': 1,
                    'class': 'total_label'} 
        footline.append(footitem)
        for service_uid in service_uids:
            footitem = {'value': service_joor[service_uid], 
                        'class': 'number'} 
            footline.append(footitem)
        footlines.append(footline)

        footline = []
        footitem = {'value': _('Total number of analyses'),
                    'colspan': 1,
                    'class': 'total_label'} 
        footline.append(footitem)
        for service_uid in service_uids:
            footitem = {'value': service_counts[service_uid],
                        'class': 'number'} 
            footline.append(footitem)
        footlines.append(footline)

        

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


        return self.template()
    def __call__(self):
        # get all the data into datalines

        pc = getToolByName(self.context, 'portal_catalog')
        sc = getToolByName(self.context, 'bika_setup_catalog')
        bc = getToolByName(self.context, 'bika_analysis_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        headings['header'] = _("Attachments")
        headings['subheader'] = _("The attachments linked to analysis requests and analyses")

        count_all = 0
        query = {'portal_type': 'Attachment'}
        if self.request.form.has_key('ClientUID'):
            client_uid = self.request.form['ClientUID']
            query['getClientUID'] = client_uid
            client = rc.lookupObject(client_uid)
            client_title = client.Title()
        else:
            client = logged_in_client(self.context)
            if client:
                client_title = client.Title()
                query['getClientUID'] = client.UID()
            else:
                client_title = 'Undefined'
        parms.append(
            { 'title': _('Client'),
             'value': client_title,
             'type': 'text'})

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


        # and now lets do the actual report lines
        formats = {'columns': 6,
                   'col_heads': [ _('Request'), \
                                  _('File'), \
                                  _('Attachment type'), \
                                  _('Content type'), \
                                  _('Size'), \
                                  _('Loaded'), \
                                  ],
                   'class': '',
                  }

        datalines = []
        attachments = pc(query)
        for a_proxy in attachments:
            attachment = a_proxy.getObject()
            attachment_file = attachment.getAttachmentFile()
            icon = attachment_file.getBestIcon()
            filename = attachment_file.filename
            filesize = attachment_file.get_size()
            filesize = filesize / 1024
            sizeunit = "Kb"
            if filesize > 1024:
                filesize = filesize / 1024
                sizeunit = "Mb"
            dateloaded = attachment.getDateLoaded()
            dataline = []
            dataitem = {'value': attachment.getTextTitle()}
            dataline.append(dataitem)
            dataitem = {'value': filename,
                        'img_before': icon}
            dataline.append(dataitem)
            dataitem = {'value': attachment.getAttachmentType().Title()}
            dataline.append(dataitem)
            dataitem = {'value': self.context.lookupMime(attachment_file.getContentType())}
            dataline.append(dataitem)
            dataitem = {'value': '%s%s' %(filesize, sizeunit)}
            dataline.append(dataitem)
            dataitem = {'value': self.ulocalized_time(dateloaded)}
            dataline.append(dataitem)


            datalines.append(dataline)

            count_all += 1

        # footer data
        footlines = []
        footline = []
        footitem = {'value': _('Total'),
                    'colspan': 5,
                    'class': 'total_label'}
        footline.append(footitem)
        footitem = {'value': count_all}
        footline.append(footitem)
        footlines.append(footline)


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


        return {'report_title': self.context.translate(headings['header']),
                'report_data': self.template()}
    def __call__(self):
        # get all the data into datalines

        bc = getToolByName(self.context, "bika_analysis_catalog")
        rc = getToolByName(self.context, "reference_catalog")
        self.report_content = {}
        parms = []
        headings = {}
        headings["header"] = _("Analysis turnaround times over time")
        headings["subheader"] = _("The turnaround time of analyses plotted over time")

        query = {"portal_type": "Analysis"}

        if "ServiceUID" in self.request.form:
            service_uid = self.request.form["ServiceUID"]
            query["ServiceUID"] = service_uid
            service = rc.lookupObject(service_uid)
            service_title = service.Title()
            parms.append({"title": _("Analysis Service"), "value": service_title, "type": "text"})

        if "Analyst" in self.request.form:
            analyst = self.request.form["Analyst"]
            query["getAnalyst"] = analyst
            analyst_title = self.user_fullname(analyst)
            parms.append({"title": _("Analyst"), "value": analyst_title, "type": "text"})

        if "getInstrumentUID" in self.request.form:
            instrument_uid = self.request.form["getInstrumentUID"]
            query["getInstrument"] = instrument_uid
            instrument = rc.lookupObject(instrument_uid)
            instrument_title = instrument.Title()
            parms.append({"title": _("Instrument"), "value": instrument_title, "type": "text"})

        if "Period" in self.request.form:
            period = self.request.form["Period"]
        else:
            period = "Day"

        date_query = formatDateQuery(self.context, "tats_DateReceived")
        if date_query:
            query["created"] = date_query
            received = formatDateParms(self.context, "tats_DateReceived")
            parms.append({"title": _("Received"), "value": received, "type": "text"})

        query["review_state"] = "published"

        # query all the analyses and increment the counts

        periods = {}
        total_count = 0
        total_duration = 0

        analyses = bc(query)
        for a in analyses:
            analysis = a.getObject()
            received = analysis.created()
            if period == "Day":
                datekey = received.strftime("%d %b %Y")
            elif period == "Week":
                # key period on Monday
                dayofweek = received.strftime("%w")  # Sunday = 0
                if dayofweek == 0:
                    firstday = received - 6
                else:
                    firstday = received - (int(dayofweek) - 1)
                datekey = firstday.strftime(self.date_format_short)
            elif period == "Month":
                datekey = received.strftime("%m-%d")
            if datekey not in periods:
                periods[datekey] = {"count": 0, "duration": 0}
            count = periods[datekey]["count"]
            duration = periods[datekey]["duration"]
            count += 1
            duration += analysis.getDuration()
            periods[datekey]["duration"] = duration
            periods[datekey]["count"] = count
            total_count += 1
            total_duration += duration

        # calculate averages
        for datekey in periods.keys():
            count = periods[datekey]["count"]
            duration = periods[datekey]["duration"]
            ave_duration = (duration) / count
            periods[datekey]["duration"] = formatDuration(self.context, ave_duration)

        # and now lets do the actual report lines
        formats = {"columns": 2, "col_heads": [_("Date"), _("Turnaround time (h)")], "class": ""}

        datalines = []

        period_keys = periods.keys()
        for period in period_keys:
            dataline = [{"value": period, "class": ""}]
            dataline.append({"value": periods[period]["duration"], "class": "number"})
            datalines.append(dataline)

        if total_count > 0:
            ave_total_duration = total_duration / total_count
        else:
            ave_total_duration = 0
        ave_total_duration = formatDuration(self.context, ave_total_duration)

        # footer data
        footlines = []
        footline = []
        footline = [{"value": _("Total data points"), "class": "total"}]

        footline.append({"value": total_count, "class": "total number"})
        footlines.append(footline)

        footline = [{"value": _("Average TAT"), "class": "total"}]

        footline.append({"value": ave_total_duration, "class": "total number"})
        footlines.append(footline)

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

        if self.request.get("output_format", "") == "CSV":
            import csv
            import StringIO
            import datetime

            fieldnames = ["Date", "Turnaround time (h)"]
            output = StringIO.StringIO()
            dw = csv.DictWriter(output, extrasaction="ignore", fieldnames=fieldnames)
            dw.writerow(dict((fn, fn) for fn in fieldnames))
            for row in datalines:
                dw.writerow({"Date": row[0]["value"], "Turnaround time (h)": row[1]["value"]})
            report_data = output.getvalue()
            output.close()
            date = datetime.datetime.now().strftime("%Y%m%d%H%M")
            setheader = self.request.RESPONSE.setHeader
            setheader("Content-Type", "text/csv")
            setheader("Content-Disposition", 'attachment;filename="analysesperservice_%s.csv"' % date)
            self.request.RESPONSE.write(report_data)
        else:
            return {"report_title": t(headings["header"]), "report_data": self.template()}
    def __call__(self):
        # get all the data into datalines

        sc = getToolByName(self.context, "bika_setup_catalog")
        bc = getToolByName(self.context, "bika_analysis_catalog")
        rc = getToolByName(self.context, "reference_catalog")
        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        headings["header"] = _("Analysis turnaround times")
        headings["subheader"] = _("The turnaround time of analyses")

        count_all = 0
        query = {"portal_type": "Analysis"}
        if self.request.form.has_key("ClientUID"):
            client_uid = self.request.form["ClientUID"]
            query["getClientUID"] = client_uid
            client = rc.lookupObject(client_uid)
            client_title = client.Title()
        else:
            client = logged_in_client(self.context)
            if client:
                client_title = client.Title()
                query["getClientUID"] = client.UID()
            else:
                client_title = "Undefined"
        parms.append({"title": _("Client"), "value": client_title, "type": "text"})

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

        query["review_state"] = "published"

        workflow = getToolByName(self.context, "portal_workflow")
        if self.request.form.has_key("bika_worksheetanalysis_workflow"):
            query["worksheetanalysis_review_state"] = self.request.form["bika_worksheetanalysis_workflow"]
            ws_review_state = workflow.getTitleForStateOnType(
                self.request.form["bika_worksheetanalysis_workflow"], "Analysis"
            )
            parms.append({"title": _("Assigned to worksheet"), "value": ws_review_state, "type": "text"})

        # query all the analyses and increment the counts

        count_early = 0
        mins_early = 0
        count_late = 0
        mins_late = 0
        count_undefined = 0
        services = {}

        analyses = bc(query)
        for a in analyses:
            analysis = a.getObject()
            service_uid = analysis.getServiceUID()
            if not services.has_key(service_uid):
                services[service_uid] = {
                    "count_early": 0,
                    "count_late": 0,
                    "mins_early": 0,
                    "mins_late": 0,
                    "count_undefined": 0,
                }
            earliness = analysis.getEarliness()
            if earliness < 0:
                count_late = services[service_uid]["count_late"]
                mins_late = services[service_uid]["mins_late"]
                count_late += 1
                mins_late -= earliness
                services[service_uid]["count_late"] = count_late
                services[service_uid]["mins_late"] = mins_late
            if earliness > 0:
                count_early = services[service_uid]["count_early"]
                mins_early = services[service_uid]["mins_early"]
                count_early += 1
                mins_early += earliness
                services[service_uid]["count_early"] = count_early
                services[service_uid]["mins_early"] = mins_early
            if earliness == 0:
                count_undefined = services[service_uid]["count_undefined"]
                count_undefined += 1
                services[service_uid]["count_undefined"] = count_undefined

        # calculate averages
        for service_uid in services.keys():
            count_early = services[service_uid]["count_early"]
            mins_early = services[service_uid]["mins_early"]
            if count_early == 0:
                services[service_uid]["ave_early"] = ""
            else:
                avemins = (mins_early) / count_early
                services[service_uid]["ave_early"] = formatDuration(self.context, avemins)
            count_late = services[service_uid]["count_late"]
            mins_late = services[service_uid]["mins_late"]
            if count_late == 0:
                services[service_uid]["ave_late"] = ""
            else:
                avemins = mins_late / count_late
                services[service_uid]["ave_late"] = formatDuration(self.context, avemins)

        # and now lets do the actual report lines
        formats = {
            "columns": 7,
            "col_heads": [
                _("Analysis"),
                _("Count"),
                _("Undefined"),
                _("Late"),
                _("Average late"),
                _("Early"),
                _("Average early"),
            ],
            "class": "",
        }

        total_count_early = 0
        total_count_late = 0
        total_mins_early = 0
        total_mins_late = 0
        total_count_undefined = 0
        datalines = []

        for cat in sc(portal_type="AnalysisCategory", sort_on="sortable_title"):
            catline = [{"value": cat.Title, "class": "category_heading", "colspan": 7}]
            first_time = True
            cat_count_early = 0
            cat_count_late = 0
            cat_count_undefined = 0
            cat_mins_early = 0
            cat_mins_late = 0
            for service in sc(portal_type="AnalysisService", getCategoryUID=cat.UID, sort_on="sortable_title"):

                dataline = [{"value": service.Title, "class": "testgreen"}]
                if not services.has_key(service.UID):
                    continue

                if first_time:
                    datalines.append(catline)
                    first_time = False

                # analyses found
                cat_count_early += services[service.UID]["count_early"]
                cat_count_late += services[service.UID]["count_late"]
                cat_count_undefined += services[service.UID]["count_undefined"]
                cat_mins_early += services[service.UID]["mins_early"]
                cat_mins_late += services[service.UID]["mins_late"]

                count = (
                    services[service.UID]["count_early"]
                    + services[service.UID]["count_late"]
                    + services[service.UID]["count_undefined"]
                )

                dataline.append({"value": count, "class": "number"})
                dataline.append({"value": services[service.UID]["count_undefined"], "class": "number"})
                dataline.append({"value": services[service.UID]["count_late"], "class": "number"})
                dataline.append({"value": services[service.UID]["ave_late"], "class": "number"})
                dataline.append({"value": services[service.UID]["count_early"], "class": "number"})
                dataline.append({"value": services[service.UID]["ave_early"], "class": "number"})

                datalines.append(dataline)

            # category totals
            dataline = [{"value": "%s - total" % (cat.Title), "class": "subtotal_label"}]

            dataline.append(
                {"value": cat_count_early + cat_count_late + cat_count_undefined, "class": "subtotal_number"}
            )

            dataline.append({"value": cat_count_undefined, "class": "subtotal_number"})

            dataline.append({"value": cat_count_late, "class": "subtotal_number"})

            if cat_count_late:
                dataitem = {"value": cat_mins_late / cat_count_late, "class": "subtotal_number"}
            else:
                dataitem = {"value": 0, "class": "subtotal_number"}

            dataline.append(dataitem)

            dataline.append({"value": cat_count_early, "class": "subtotal_number"})

            if cat_count_early:
                dataitem = {"value": cat_mins_early / cat_count_early, "class": "subtotal_number"}
            else:
                dataitem = {"value": 0, "class": "subtotal_number"}

            dataline.append(dataitem)

            total_count_early += cat_count_early
            total_count_late += cat_count_late
            total_count_undefined += cat_count_undefined
            total_mins_early += cat_mins_early
            total_mins_late += cat_mins_late

        # footer data
        footlines = []
        footline = []
        footline = [{"value": _("Total"), "class": "total"}]

        footline.append(
            {"value": total_count_early + total_count_late + total_count_undefined, "class": "total number"}
        )

        footline.append({"value": total_count_undefined, "class": "total number"})

        footline.append({"value": total_count_late, "class": "total number"})

        if total_count_late:
            ave_mins = total_mins_late / total_count_late
            footline.append({"value": formatDuration(self.context, ave_mins), "class": "total number"})
        else:
            footline.append({"value": ""})

        footline.append({"value": total_count_early, "class": "total number"})

        if total_count_early:
            ave_mins = total_mins_early / total_count_early
            footline.append({"value": formatDuration(self.context, ave_mins), "class": "total number"})
        else:
            footline.append({"value": "", "class": "total number"})

        footlines.append(footline)

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

        title = self.context.translate(headings["header"])

        return {"report_title": title, "report_data": self.template()}
    def __call__(self):
        # get all the data into datalines

        bc = getToolByName(self.context, 'bika_analysis_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.report_content = {}
        parms = []
        headings = {}
        headings['header'] = _("Analysis turnaround times over time")
        headings['subheader'] = \
            _("The turnaround time of analyses plotted over time")

        query = {'portal_type': 'Analysis'}

        if 'ServiceUID' in self.request.form:
            service_uid = self.request.form['ServiceUID']
            query['getServiceUID'] = service_uid
            service = rc.lookupObject(service_uid)
            service_title = service.Title()
            parms.append({
                'title': _('Analysis Service'),
                'value': service_title,
                'type': 'text'
            })

        if 'Analyst' in self.request.form:
            analyst = self.request.form['Analyst']
            query['getAnalyst'] = analyst
            analyst_title = self.user_fullname(analyst)
            parms.append({
                'title': _('Analyst'),
                'value': analyst_title,
                'type': 'text'
            })

        if 'getInstrumentUID' in self.request.form:
            instrument_uid = self.request.form['getInstrumentUID']
            query['getInstrument'] = instrument_uid
            instrument = rc.lookupObject(instrument_uid)
            instrument_title = instrument.Title()
            parms.append({
                'title': _('Instrument'),
                'value': instrument_title,
                'type': 'text'
            })

        if 'Period' in self.request.form:
            period = self.request.form['Period']
        else:
            period = 'Day'

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

        query['review_state'] = 'published'

        # query all the analyses and increment the counts

        analysis_list = []
        analyses = bc(query)

        import datetime
        for a in analyses:
            analysis = a.getObject()
            analysis_list.append(
                {'analysis_id': analysis.id,
                 'duration': str(datetime.timedelta(seconds=analysis.getDuration())),
                 'overtime': self.formatOvertime(int(round((DT2dt(DateTime.DateTime(analysis.getDueDate())) - \
                       DT2dt(DateTime.DateTime(analysis.getDateAnalysisPublished()))) \
                      .total_seconds())))
                 }
            )

        # and now lets do the actual report lines
        formats = {
            'columns': 3,
            'col_heads': [
                _('Analysis'),
                _('Duration'),
                _('Overtime'),
            ],
            'class': ''
        }

        datalines = []

        for al in analysis_list:
            dataline = [{'value': al['analysis_id'], 'class': ''}]
            dataline.append({'value': al['duration'], 'class': 'number'})
            dataline.append({'value': al['overtime'], 'class': 'number'})
            datalines.append(dataline)

        # footer data
        footlines = []
        footline = []
        footline = [
            {
                'value': _('Total number of analysis'),
                'class': 'total'
            },
        ]

        footline.append({
            'value': len(analysis_list),
            'colspan': 2,
            'class': 'total number'
        })
        footlines.append(footline)

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

        if self.request.get('output_format', '') == 'CSV':
            import csv
            import StringIO
            import datetime

            fieldnames = [
                'Analysis',
                'Duration',
                'Overtime',
            ]
            output = StringIO.StringIO()
            dw = csv.DictWriter(output,
                                extrasaction='ignore',
                                fieldnames=fieldnames)
            dw.writerow(dict((fn, fn) for fn in fieldnames))
            for row in datalines:
                dw.writerow({
                    'Analysis': row[0]['value'],
                    'Duration': row[1]['value'],
                    'Overtime': row[2]['value'],
                })
            report_data = output.getvalue()
            output.close()
            date = datetime.datetime.now().strftime("%Y%m%d%H%M")
            setheader = self.request.RESPONSE.setHeader
            setheader('Content-Type', 'text/csv')
            setheader("Content-Disposition",
                      "attachment;filename=\"analysestats_%s.csv\"" % date)
            self.request.RESPONSE.write(report_data)
        else:
            return {
                'report_title': t(headings['header']),
                'report_data': self.template()
            }
Exemplo n.º 15
0
    def __call__(self):
        self.datalines = []
        workflow = getToolByName(self, 'portal_workflow')

        # check for batch size
        if self.request.form.has_key('size'):
            batch_size = self.request.form['size']
        else:
            batch_size = 6

        # check for batch start
        if self.request.form.has_key('b_start'):
            batch_start = self.request.form['b_start']
        else:
            batch_start = 0

        sc = getToolByName(self.context, 'bika_setup_catalog')
        bc = getToolByName(self.context, 'bika_catalog')
        bac = getToolByName(self.context, 'bika_analysis_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.query_content = {}
        parm_lines = {}
        self.parms = []
        self.headings = {}
        self.headings['header'] = _("Analysis Requests")
        self.headings['head_parms'] = _("Selected on the following criteria")
        self.headings['head_undefined'] = _("Parameters undefined")

        count_all = 0
        query = {'portal_type': 'AnalysisRequest'}

        undefined = []

        # Client
        client_title = None
        if self.request.form.has_key('ClientUID'):
            client_uid = self.request.form['ClientUID']
            query['getClientUID'] = client_uid
            client = rc.lookupObject(client_uid)
            client_title = client.Title()
        else:
            client = logged_in_client(self.context)
            if client:
                client_title = client.Title()
                query['getClientUID'] = client.UID()
        if client_title:
            self.parms.append({
                'title': _('Client'),
                'fieldid': 'ClientUID',
                'value': client_title,
                'type': 'text'
            })
        else:
            undefined.append('Client')

        # Contact
        if self.request.form.has_key('ContactUID'):
            contact_uid = self.request.form['ContactUID']
            query['getContactUID'] = contact_uid
            contact = rc.lookupObject(contact_uid)
            contact_name = contact.getFullname()
            self.parms.append({
                'title': _('Contact'),
                'fieldid': 'ContactUID',
                'value': contact_name,
                'type': 'text'
            })
        else:
            undefined.append('Contact')

        # Profile
        if self.request.form.has_key('ProfileUID'):
            profile_uid = self.request.form['ProfileUID']
            query['getAnalysisProfileUID'] = profile_uid
            profile = rc.lookupObject(profile_uid)
            profile_title = profile.Title()
            self.parms.append({
                'title': _('Profile'),
                'value': profile_title,
                'type': 'text'
            })
        else:
            undefined.append('Profile')

        # Request ID
        if self.request.form.has_key('RequestID'):
            request_id = self.request.form['RequestID']
            query['getRequestID'] = request_id
            self.parms.append({
                'title': _('AR'),
                'value': request_id,
                'type': 'text'
            })
        else:
            undefined.append('AR')

        # Client order number
        if self.request.form.has_key('ClientOrderNumber'):
            clientoid = self.request.form['ClientOrderNumber']
            query['getClientOrderNumber'] = clientoid
            self.parms.append({
                'title': _('Client order number'),
                'value': clientoid,
                'type': 'text'
            })
        else:
            undefined.append('Client order number')

        # Client reference
        if self.request.form.has_key('ClientReference'):
            clientref = self.request.form['ClientReference']
            query['getClientReference'] = clientref
            self.parms.append({
                'title': _('Client reference'),
                'value': clientref,
                'type': 'text'
            })
        else:
            undefined.append('Client reference')

        # Client sample ID
        if self.request.form.has_key('ClientSampleID'):
            clientsid = self.request.form['ClientSampleID']
            query['getClientSampleID'] = clientsid
            self.parms.append({
                'title': _('Client sample ID'),
                'value': clientsid,
                'type': 'text'
            })
        else:
            undefined.append('Client sample ID')

        # Sample type
        if self.request.form.has_key('SampleTypeUID'):
            st_uid = self.request.form['SampleTypeUID']
            query['getSampleTypeUID'] = st_uid
            st = rc.lookupObject(st_uid)
            st_title = st.Title()
            self.parms.append({
                'title': _('Sample type'),
                'value': st_title,
                'type': 'text'
            })
        else:
            undefined.append('Sample type')

        # Sample point
        if self.request.form.has_key('SamplePointUID'):
            sp_uid = self.request.form['SamplePointUID']
            query['getSamplePointUID'] = sp_uid
            sp = rc.lookupObject(sp_uid)
            sp_title = sp.Title()
            self.parms.append({
                'title': _('Sample point'),
                'value': sp_title,
                'type': 'text'
            })
        else:
            undefined.append('Sample point')

        # Date sampled
        date_query = formatDateQuery(self.context, 'DateSampled')
        if date_query:
            query['created'] = date_query
            sampled = formatDateParms(self.context, 'DateSampled')
            self.parms.append({
                'title': _('Sampled'),
                'value': sampled,
                'type': 'text'
            })
        else:
            undefined.append('Sampled')

        # Date requested
        date_query = formatDateQuery(self.context, 'DateRequested')
        if date_query:
            query['created'] = date_query
            requested = formatDateParms(self.context, 'DateRequested')
            self.parms.append({
                'title': _('Requested'),
                'value': requested,
                'type': 'text'
            })
        else:
            undefined.append('Requested')

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

        # Date published
        date_query = formatDateQuery(self.context, 'DatePublished')
        if date_query:
            query['getDatePublished'] = date_query
            published = formatDateParms(self.context, 'DatePublished')
            self.parms.append({
                'title': _('Published'),
                'value': published,
                'type': 'text'
            })
        else:
            undefined.append('Published')

        # Category
        if self.request.form.has_key('CategoryUID'):
            category_uid = self.request.form['CategoryUID']
            query['getCategoryUID'] = category_uid
            category = rc.lookupObject(category_uid)
            category_title = category.Title()
            self.parms.append({
                'title': _('Category'),
                'value': category_title,
                'type': 'text'
            })
        else:
            undefined.append('Category')

        # Analysis service
        if self.request.form.has_key('ServiceUID'):
            service_uid = self.request.form['ServiceUID']
            query['getServiceUID'] = service_uid
            service = rc.lookupObject(service_uid)
            service_title = service.Title()
            self.parms.append({
                'title': _('Analysis service'),
                'value': service_title,
                'type': 'text'
            })
        else:
            undefined.append('Analysis service')

        # Analyst
        if self.request.form.has_key('Analyst'):
            analyst = self.request.form['Analyst']
            query['getAnalyst'] = analyst
            analyst_name = self.user_fullname(analyst)
            self.parms.append({
                'title': _('Analyst'),
                'value': analyst_name,
                'type': 'text'
            })
        else:
            undefined.append('Analyst')

        # Status
        if self.request.form.has_key('review_state'):
            query['review_state'] = self.request.form['review_state']
            review_state = workflow.getTitleForStateOnType(
                self.request.form['review_state'], 'Analysis')
            self.parms.append({
                'title': _('Status'),
                'value': review_state,
                'type': 'text'
            })
        else:
            undefined.append('Status')

        # Cancellation state
        if self.request.form.has_key('cancellation_state'):
            query['cancellation_state'] = self.request.form[
                'cancellation_state']
            cancellation_state = workflow.getTitleForStateOnType(
                self.request.form['cancellation_state'], 'Analysis')
            self.parms.append({
                'title': _('Active'),
                'value': cancellation_state,
                'type': 'text'
            })
        else:
            undefined.append('Active')

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

        # set up the undefined parameters in pretty format
        undefined_string = ', '.join(undefined)
        self.parms_undefined = [{
            'title': _('Parameters not defined'),
            'value': undefined_string
        }]

        self.columns = batch_size + 1
        # and now lets do the actual query lines
        self.formats = {
            'columns': self.columns,
            'col_heads': [],
            'class': '',
        }

        labels = [
            "Client order ID", "Client reference", "Client sample ID",
            "Client", "Contact", "Request ID", "Sample ID", "Profile",
            "Sample type", "Sample point", "Sampled", "Requested", "Received",
            "Published", "Status", "Submitted by", "Verified by"
        ]
        for label in labels:
            self.datalines.append([{
                'value': _(label),
                'class': 'header',
            }])

        details = []
        for i in range(len(self.datalines)):
            details.append([])

        ars = bc(query)
        self.url = self.request.URL
        self.show_all = False

        self.batch = Batch(ars, batch_size, batch_start)

        analyses = []
        analysis_dict = {}
        service_dict = {}
        ar_ids = []
        for arp in self.batch:
            ar = arp.getObject()
            ar_ids.append(ar.getRequestID())
            details[0].append({'value': ar.getClientOrderNumber()})
            details[1].append({'value': ar.getClientReference()})
            details[2].append({'value': ar.getClientSampleID()})
            details[3].append({'value': ar.aq_parent.Title()})
            details[4].append({'value': ar.getContact().Title()})
            details[5].append({'value': ar.getRequestID()})
            details[6].append({'value': ar.getSample().getSampleID()})
            details[7].append(
                {'value': ar.getProfile() and ar.getProfile().Title() or ' '})
            details[8].append({'value': ar.getSampleTypeTitle()})

            details[10].append({
                'value':
                self.ulocalized_time(ar.getSample().getDateSampled())
            })
            details[11].append({'value': self.ulocalized_time(ar.created())})
            details[12].append(
                {'value': self.ulocalized_time(ar.getDateReceived())})
            details[13].append(
                {'value': self.ulocalized_time(ar.getDatePublished())})
            details[14].append(
                {'value': workflow.getInfoFor(ar, 'review_state')})
            #details[15].append({'value': ar.getSubmittedBy().Title()})
            details[15].append({'value': ' '})

            #details[16].append({'value': ar.get_verifier().Title()})
            details[16].append({'value': ' '})

            #analyses
            for analysis in ar.getAnalyses(full_objects=True):
                service_uid = analysis.getServiceUID()
                if not analysis_dict.has_key(service_uid):
                    service_dict[analysis.Title()] = service_uid
                    analysis_dict[service_uid] = {}
                analysis_dict[service_uid][
                    ar.getRequestID()] = analysis.getResult()

            if len(details[0]) == batch_size:
                break

        # load the detail lines
        for i in range(len(self.datalines)):
            self.datalines[i].extend(details[i])

        # load the analysis lines
        service_titles = service_dict.keys()
        service_titles.sort()

        for service_title in service_titles:
            service_uid = service_dict[service_title]
            analysis_line = [
                {
                    'value': service_title
                },
            ]
            for ar_id in ar_ids:
                if analysis_dict[service_uid].has_key(ar_id):
                    analysis_line.append(
                        {'value': analysis_dict[service_uid][ar_id]})
                else:
                    analysis_line.append({})
            self.datalines.append(analysis_line)

        # footer data
        self.footlines = []
        footline = []
        footitem = {'value': _('Total'), 'class': 'total_label'}
        footline.append(footitem)
        footitem = {'value': count_all}
        footline.append(footitem)
        self.footlines.append(footline)

        return self.template()
Exemplo n.º 16
0
    def __call__(self):
        # get all the data into datalines

        sc = getToolByName(self.context, 'bika_setup_catalog')
        pc = getToolByName(self.context, 'portal_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        headings['header'] = _("Analyses per analysis service")
        headings['subheader'] = _(
            "Number of analyses requested per analysis service")

        count_all = 0
        query = {'portal_type': 'Analysis'}
        if self.request.form.has_key('getClientUID'):
            client_uid = self.request.form['getClientUID']
            query['getClientUID'] = client_uid
            client = rc.lookupObject(client_uid)
            client_title = client.Title()
        else:
            client_title = 'Undefined'
        parms.append({
            'title': _('Client'),
            'value': client_title,
            'type': 'text'
        })

        date_query = formatDateQuery(self.context, 'DateRequested')
        if date_query:
            query['created'] = date_query
            requested = formatDateParms(self.context, 'DateRequested')
        else:
            requested = 'Undefined'
        parms.append({
            'title': _('Requested'),
            'value': requested,
            'type': 'text'
        })

        date_query = formatDateQuery(self.context, 'DatePublished')
        if date_query:
            query['getDatePublished'] = date_query
            published = formatDateParms(self.context, 'DatePublished')
        else:
            published = 'Undefined'
        parms.append({
            'title': _('Published'),
            'value': published,
            'type': 'text'
        })

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

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

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

        datalines = []
        for cat in sc(portal_type="AnalysisCategory",
                      sort_on='sortable_title'):
            service_data = []
            for service in sc(portal_type="AnalysisService",
                              getCategoryUID=cat.UID,
                              sort_on='sortable_title'):
                query['getServiceUID'] = service.UID
                analyses = pc(query)
                count_analyses = len(analyses)
                service_data.append([service.Title, count_analyses])
                count_all += count_analyses

            datalines.append([cat.Title, service_data])

        self.report_content = {
            'headings': headings,
            'parms': parms,
            'datalines': datalines,
            'total': count_all
        }

        return self.template()
    def __call__(self):
        # get all the data into datalines

        sc = getToolByName(self.context, 'bika_setup_catalog')
        bc = getToolByName(self.context, 'bika_analysis_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.report_content = {}
        parms = []
        headings = {}
        headings['header'] = _("Analysis turnaround times")
        headings['subheader'] = _("The turnaround time of analyses")

        query = {'portal_type': 'Analysis'}
        client_title = None
        if 'ClientUID' in self.request.form:
            client_uid = self.request.form['ClientUID']
            query['getClientUID'] = client_uid
            client = rc.lookupObject(client_uid)
            client_title = client.Title()
        else:
            client = logged_in_client(self.context)
            if client:
                client_title = client.Title()
                query['getClientUID'] = client.UID()
        if client_title:
            parms.append({
                'title': _('Client'),
                'value': client_title,
                'type': 'text'
            })

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

        query['review_state'] = 'published'

        workflow = getToolByName(self.context, 'portal_workflow')
        if 'bika_worksheetanalysis_workflow' in self.request.form:
            query['worksheetanalysis_review_state'] = self.request.form[
                'bika_worksheetanalysis_workflow']
            ws_review_state = workflow.getTitleForStateOnType(
                self.request.form['bika_worksheetanalysis_workflow'],
                'Analysis')
            parms.append({
                'title': _('Assigned to worksheet'),
                'value': ws_review_state,
                'type': 'text'
            })

        # query all the analyses and increment the counts
        count_early = 0
        mins_early = 0
        count_late = 0
        mins_late = 0
        count_undefined = 0
        services = {}

        analyses = bc(query)
        for a in analyses:
            analysis = a.getObject()
            service_uid = analysis.getServiceUID()
            if service_uid not in services:
                services[service_uid] = {
                    'count_early': 0,
                    'count_late': 0,
                    'mins_early': 0,
                    'mins_late': 0,
                    'count_undefined': 0,
                }
            earliness = analysis.getEarliness()
            if earliness < 0:
                count_late = services[service_uid]['count_late']
                mins_late = services[service_uid]['mins_late']
                count_late += 1
                mins_late -= earliness
                services[service_uid]['count_late'] = count_late
                services[service_uid]['mins_late'] = mins_late
            if earliness > 0:
                count_early = services[service_uid]['count_early']
                mins_early = services[service_uid]['mins_early']
                count_early += 1
                mins_early += earliness
                services[service_uid]['count_early'] = count_early
                services[service_uid]['mins_early'] = mins_early
            if earliness == 0:
                count_undefined = services[service_uid]['count_undefined']
                count_undefined += 1
                services[service_uid]['count_undefined'] = count_undefined

        # calculate averages
        for service_uid in services.keys():
            count_early = services[service_uid]['count_early']
            mins_early = services[service_uid]['mins_early']
            if count_early == 0:
                services[service_uid]['ave_early'] = ''
            else:
                avemins = (mins_early) / count_early
                services[service_uid]['ave_early'] = formatDuration(
                    self.context, avemins)
            count_late = services[service_uid]['count_late']
            mins_late = services[service_uid]['mins_late']
            if count_late == 0:
                services[service_uid]['ave_late'] = ''
            else:
                avemins = mins_late / count_late
                services[service_uid]['ave_late'] = formatDuration(
                    self.context, avemins)

        # and now lets do the actual report lines
        formats = {
            'columns':
            7,
            'col_heads': [
                _('Analysis'),
                _('Count'),
                _('Undefined'),
                _('Late'),
                _('Average late'),
                _('Early'),
                _('Average early'),
            ],
            'class':
            '',
        }

        total_count_early = 0
        total_count_late = 0
        total_mins_early = 0
        total_mins_late = 0
        total_count_undefined = 0
        datalines = []

        for cat in sc(portal_type='AnalysisCategory',
                      sort_on='sortable_title'):
            catline = [
                {
                    'value': cat.Title,
                    'class': 'category_heading',
                    'colspan': 7
                },
            ]
            first_time = True
            cat_count_early = 0
            cat_count_late = 0
            cat_count_undefined = 0
            cat_mins_early = 0
            cat_mins_late = 0
            for service in sc(portal_type="AnalysisService",
                              getCategoryUID=cat.UID,
                              sort_on='sortable_title'):

                dataline = [
                    {
                        'value': service.Title,
                        'class': 'testgreen'
                    },
                ]
                if service.UID not in services:
                    continue

                if first_time:
                    datalines.append(catline)
                    first_time = False

                # analyses found
                cat_count_early += services[service.UID]['count_early']
                cat_count_late += services[service.UID]['count_late']
                cat_count_undefined += services[service.UID]['count_undefined']
                cat_mins_early += services[service.UID]['mins_early']
                cat_mins_late += services[service.UID]['mins_late']

                count = services[service.UID]['count_early'] + \
                        services[service.UID]['count_late'] + \
                        services[service.UID]['count_undefined']

                dataline.append({'value': count, 'class': 'number'})
                dataline.append({
                    'value':
                    services[service.UID]['count_undefined'],
                    'class':
                    'number'
                })
                dataline.append({
                    'value': services[service.UID]['count_late'],
                    'class': 'number'
                })
                dataline.append({
                    'value': services[service.UID]['ave_late'],
                    'class': 'number'
                })
                dataline.append({
                    'value': services[service.UID]['count_early'],
                    'class': 'number'
                })
                dataline.append({
                    'value': services[service.UID]['ave_early'],
                    'class': 'number'
                })

                datalines.append(dataline)

            # category totals
            dataline = [
                {
                    'value': '%s - total' % (cat.Title),
                    'class': 'subtotal_label'
                },
            ]

            dataline.append({
                'value':
                cat_count_early + cat_count_late + cat_count_undefined,
                'class': 'subtotal_number'
            })

            dataline.append({
                'value': cat_count_undefined,
                'class': 'subtotal_number'
            })

            dataline.append({
                'value': cat_count_late,
                'class': 'subtotal_number'
            })

            if cat_count_late:
                dataitem = {
                    'value': cat_mins_late / cat_count_late,
                    'class': 'subtotal_number'
                }
            else:
                dataitem = {'value': 0, 'class': 'subtotal_number'}

            dataline.append(dataitem)

            dataline.append({
                'value': cat_count_early,
                'class': 'subtotal_number'
            })

            if cat_count_early:
                dataitem = {
                    'value': cat_mins_early / cat_count_early,
                    'class': 'subtotal_number'
                }
            else:
                dataitem = {'value': 0, 'class': 'subtotal_number'}

            dataline.append(dataitem)

            total_count_early += cat_count_early
            total_count_late += cat_count_late
            total_count_undefined += cat_count_undefined
            total_mins_early += cat_mins_early
            total_mins_late += cat_mins_late

        # footer data
        footlines = []
        footline = []
        footline = [
            {
                'value': _('Total'),
                'class': 'total'
            },
        ]

        footline.append({
            'value':
            total_count_early + total_count_late + total_count_undefined,
            'class': 'total number'
        })

        footline.append({
            'value': total_count_undefined,
            'class': 'total number'
        })

        footline.append({'value': total_count_late, 'class': 'total number'})

        if total_count_late:
            ave_mins = total_mins_late / total_count_late
            footline.append({
                'value': formatDuration(self.context, ave_mins),
                'class': 'total number'
            })
        else:
            footline.append({'value': ''})

        footline.append({'value': total_count_early, 'class': 'total number'})

        if total_count_early:
            ave_mins = total_mins_early / total_count_early
            footline.append({
                'value': formatDuration(self.context, ave_mins),
                'class': 'total number'
            })
        else:
            footline.append({'value': '', 'class': 'total number'})

        footlines.append(footline)

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

        if self.request.get('output_format', '') == 'CSV':
            import csv
            import StringIO
            import datetime
            fieldnames = [
                'Analysis',
                'Count',
                'Undefined',
                'Late',
                'Average late',
                'Early',
                'Average early',
            ]
            output = StringIO.StringIO()
            dw = csv.DictWriter(output,
                                extrasaction='ignore',
                                fieldnames=fieldnames)
            dw.writerow(dict((fn, fn) for fn in fieldnames))
            for row in datalines:
                if len(row) == 1:
                    # category heading thingy
                    continue
                dw.writerow({
                    'Analysis': row[0]['value'],
                    'Count': row[1]['value'],
                    'Undefined': row[2]['value'],
                    'Late': row[3]['value'],
                    'Average late': row[4]['value'],
                    'Early': row[5]['value'],
                    'Average early': row[6]['value'],
                })
            report_data = output.getvalue()
            output.close()
            date = datetime.datetime.now().strftime("%Y%m%d%H%M")
            setheader = self.request.RESPONSE.setHeader
            setheader('Content-Type', 'text/csv')
            setheader("Content-Disposition",
                      "attachment;filename=\"analysestats_%s.csv\"" % date)
            self.request.RESPONSE.write(report_data)
        else:
            return {
                'report_title': self.context.translate(headings['header']),
                'report_data': self.template()
            }
Exemplo n.º 18
0
    def __call__(self):
        # get all the data into datalines
        
        sc = getToolByName(self.context, 'bika_setup_catalog')
        bc = getToolByName(self.context, 'bika_catalog')
        bac = getToolByName(self.context, 'bika_analysis_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.query_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        headings['header'] = _("Analysis Requests")
        headings['subheader'] = _("Selected on the following criteria")

        count_all = 0
        query = {'portal_type': 'AnalysisRequest'}

        if self.request.form.has_key('getClientUID'):
            client_uid = self.request.form['getClientUID']
            query['getClientUID'] = client_uid
            client = rc.lookupObject(client_uid)
            client_title = client.Title()
        else:
            client = logged_in_client(self.context)
            if client:
                client_title = client.Title()
                query['getClientUID'] = client.UID()
            else:
                client_title = 'Undefined'
        parms.append(
            { 'title': _('Client'),
             'value': client_title,
             'type': 'text'})

        if self.request.form.has_key('getContactUID'):
            contact_uid = self.request.form['getContactUID']
            query['getContactUID'] = contact_uid
            contact = rc.lookupObject(contact_uid)
            contact_name = contact.getFullname()
        else:
            contact_name = 'Undefined'
        parms.append(
            { 'title': _('Contact'),
             'value': contact_name,
             'type': 'text'})

        if self.request.form.has_key('getARProfileUID'):
            profile_uid = self.request.form['getARProfileUID']
            query['getARProfileUID'] = profile_uid
            profile = rc.lookupObject(profile_uid)
            profile_title = profile.Title()
        else:
            profile_title = 'Undefined'
        parms.append(
            { 'title': _('Profile'),
             'value': profile_title,
             'type': 'text'})

        if self.request.form.has_key('RequestID'):
            request_id = self.request.form['RequestID']
            query['getRequestID'] = request_id
        else:
            request_id = 'Undefined'
        parms.append(
            { 'title': _('AR'),
             'value': request_id,
             'type': 'text'})

        if self.request.form.has_key('ClientOrderNumber'):
            clientordernumber = self.request.form['ClientOrderNumber']
            query['getClientOrderNumber'] = clientordernumber
        else:
            clientordernumber = 'Undefined'
        parms.append(
            { 'title': _('Client order number'),
             'value': clientordernumber,
             'type': 'text'})

        if self.request.form.has_key('ClientReference'):
            clientref = self.request.form['ClientReference']
            query['getClientReference'] = clientref
        else:
            clientref = 'Undefined'
        parms.append(
            { 'title': _('Client reference'),
             'value': clientref,
             'type': 'text'})

        if self.request.form.has_key('ClientSampleID'):
            clientsid = self.request.form['ClientSampleID']
            query['getClientSampleID'] = clientsid
        else:
            clientsid = 'Undefined'
        parms.append(
            { 'title': _('Client sample ID'),
             'value': clientsid,
             'type': 'text'})

        if self.request.form.has_key('SampleTypeUID'):
            st_uid = self.request.form['SampleTypeUID']
            query['getSampleTypeUID'] = st_uid
            st = rc.lookupObject(st_uid)
            st_title = st.Title()
        else:
            st_title = 'Undefined'
        parms.append(
            { 'title': _('Sample type'),
             'value': st_title,
             'type': 'text'})

        if self.request.form.has_key('SamplePointUID'):
            sp_uid = self.request.form['SamplePointUID']
            query['getSamplePointUID'] = sp_uid
            sp = rc.lookupObject(sp_uid)
            sp_title = sp.Title()
        else:
            sp_title = 'Undefined'
        parms.append(
            { 'title': _('Sample point'),
             'value': sp_title,
             'type': 'text'})

        date_query = formatDateQuery(self.context, 'DateSampled')
        if date_query:
            query['created'] = date_query
            sampled = formatDateParms(self.context, 'DateSampled') 
        else:
            sampled = 'Undefined'
        parms.append(
            { 'title': _('Sampled'),
             'value': sampled,
             'type': 'text'})

        date_query = formatDateQuery(self.context, 'DateRequested')
        if date_query:
            query['created'] = date_query
            requested = formatDateParms(self.context, 'DateRequested') 
        else:
            requested = 'Undefined'
        parms.append(
            { 'title': _('Requested'),
             'value': requested,
             'type': 'text'})

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

        date_query = formatDateQuery(self.context, 'DatePublished')
        if date_query:
            query['getDatePublished'] = date_query
            published = formatDateParms(self.context, 'DatePublished') 
        else:
            published = 'Undefined'
        parms.append(
            { 'title': _('Published'),
             'value': published,
             'type': 'text'})

        if self.request.form.has_key('CategoryUID'):
            category_uid = self.request.form['CategoryUID']
            query['getCategoryUID'] = category_uid
            category = rc.lookupObject(category_uid)
            category_title = category.Title()
        else:
            category_title = 'Undefined'
        parms.append(
            { 'title': _('Category'),
             'value': category_title,
             'type': 'text'})

        if self.request.form.has_key('ServiceUID'):
            service_uid = self.request.form['ServiceUID']
            query['getServiceUID'] = service_uid
            service = rc.lookupObject(service_uid)
            service_title = service.Title()
        else:
            service_title = 'Undefined'
        parms.append(
            { 'title': _('Analysis service'),
             'value': service_title,
             'type': 'text'})

        if self.request.form.has_key('SubmittedByUID'):
            submittedby_uid = self.request.form['SubmittedByUID']
            query['getSubmittedByUID'] = submittedby_uid
            submittedby = rc.lookupObject(submittedby_uid)
            submittedby_name = submittedby.prettyNameOrTitle()
        else:
            submittedby_name = 'Undefined'
        parms.append(
            { 'title': _('Submitted by'),
             'value': submittedby_name,
             'type': 'text'})

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

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



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


        # and now lets do the actual query lines
        formats = {'columns': 7,
                   'col_heads': [], 
                   'class': '',
                  }

        columns = 6
        
        datalines = []
        clientoid_label =   [{'value': _("Client order ID"),
                              'class': 'header',}]
        clientref_label =   [{'value': _("Client reference"),
                              'class': 'header',}]
        clientsid_label =   [{'value': _("Client sample ID"),
                              'class': 'header',}]
        client_label =      [{'value': _("Client"),
                              'class': 'header',}]
        contact_label =     [{'value': _("Contact"),
                              'class': 'header',}]
        requestid_label =   [{'value': _("Request ID"),
                              'class': 'header',}]
        sampleid_label =    [{'value': _("Sample ID"),
                              'class': 'header',}]
        profile_label =     [{'value': _("Profile"),
                              'class': 'header',}]
        sampletype_label =  [{'value': _("Sample type"),
                              'class': 'header',}]
        samplepoint_label = [{'value': _("Sample point"),
                              'class': 'header',}]
        sampled_label =     [{'value': _("Sampled"),
                              'class': 'header',}]
        requested_label =   [{'value': _("Requested"),
                              'class': 'header',}]
        received_label =    [{'value': _("Received"),
                              'class': 'header',}]
        published_label =   [{'value': _("Published"),
                              'class': 'header',}]
        status_label =      [{'value': _("Status"),
                              'class': 'header',}]
        submittedby_label = [{'value': _("Submitted by"),
                              'class': 'header',}]
        verifiedby_label =  [{'value': _("Verified by"),
                              'class': 'header',}]
        i = 0
        for arp in bc(query):
            ar = arp.getObject()
            clientoid.append({'value': ar.getClientOrderNumber()})
            clientref.append({'value': ar.getClientReference()})
            clientsid.append({'value': ar.getClientSampleID()})
            client.append({'value': ar.aq_parent.Title()})
            contact.append({'value': ar.getContact().Title()})
            requestid.append({'value': ar.getRequestID()})
            sampleid.append({'value': ar.getSample().getSampleID()})
            profile.append({'value': ar.getProfile() and ar.getProfile().Title() or ' '})
            sampletype.append({'value': ar.getSampleTypeTitle()})
            samplepoint.append({'value': ar.getSamplePointTitle()})
            sampled.append({'value': TimeOrDate(self.context, ar.getSample().getDateSampled())})
            requested.append({'value': ' '})
            #requested.append({'value': TimeOrDate(self.context, ar.created())})
            received.append({'value': TimeOrDate(self.context, ar.getDateReceived())})
            published.append({'value': TimeOrDate(self.context, ar.getDatePublished())})
            status.append({'value': ' '})
            #status.append({'value': ar.review_state()})
            submittedby.append({'value': ' '})
            #submittedby.append({'value': ar.getSubmittedBy().Title()})
            verifiedby.append({'value': ' '})
            #verifiedby.append({'value': ar.get_verifier().Title()})
            if len(clientoid) > columns:
                datalines.append(clientoid)
                datalines.append(clientref)
                datalines.append(clientsid)
                datalines.append(client)
                datalines.append(contact)
                datalines.append(requestid)
                datalines.append(sampleid)
                datalines.append(profile)
                datalines.append(sampletype)
                datalines.append(samplepoint)
                datalines.append(sampled)
                datalines.append(requested)
                datalines.append(received)
                datalines.append(published)
                datalines.append(status)
                datalines.append(submittedby)
                datalines.append(verifiedby)
                     

        # footer data
        footlines = []
        footline = []
        footitem = {'value': _('Total'),
                    'class': 'total_label'} 
        footline.append(footitem)
        footitem = {'value': count_all} 
        footline.append(footitem)
        footlines.append(footline)
        

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


        return self.template()
    def __call__(self):
        # get all the data into datalines

        pc = getToolByName(self.context, 'portal_catalog')
        sc = getToolByName(self.context, 'bika_setup_catalog')
        bc = getToolByName(self.context, 'bika_analysis_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        headings['header'] = _("Attachments")
        headings['subheader'] = _("The attachments linked to analysis requests and analyses")

        count_all = 0
        query = {'portal_type': 'Attachment'}
        if self.request.form.has_key('getClientUID'):
            client_uid = self.request.form['getClientUID']
            query['getClientUID'] = client_uid
            client = rc.lookupObject(client_uid)
            client_title = client.Title()
        else:
            client = logged_in_client(self.context)
            if client:
                client_title = client.Title()
                query['getClientUID'] = client.UID()
            else:
                client_title = 'Undefined'
        parms.append(
            { 'title': _('Client'),
             'value': client_title,
             'type': 'text'})

        date_query = formatDateQuery(self.context, 'DateLoaded')
        if date_query:
            query['getDateLoaded'] = date_query
            loaded = formatDateParms(self.context, 'DateLoaded')
        else:
            loaded = 'Undefined'
        parms.append(
            { 'title': _('Loaded'),
             'value': loaded,
             'type': 'text'})


        # and now lets do the actual report lines
        formats = {'columns': 6,
                   'col_heads': [ _('Request'), \
                                  _('File'), \
                                  _('Attachment type'), \
                                  _('Content type'), \
                                  _('Size'), \
                                  _('Loaded'), \
                                  ],
                   'class': '',
                  }

        datalines = []
        attachments = pc(query)
        for a_proxy in attachments:
            attachment = a_proxy.getObject()
            attachment_file = attachment.getAttachmentFile()
            icon = attachment_file.getBestIcon()
            filename = attachment_file.filename
            filesize = attachment_file.get_size()
            filesize = filesize / 1024
            sizeunit = "Kb"
            if filesize > 1024:
                filesize = filesize / 1024
                sizeunit = "Mb"
            dateloaded = attachment.getDateLoaded()
            dataline = []
            dataitem = {'value': attachment.getTextTitle()}
            dataline.append(dataitem)
            dataitem = {'value': filename,
                        'img_before': icon}
            dataline.append(dataitem)
            dataitem = {'value': attachment.getAttachmentType().Title()}
            dataline.append(dataitem)
            dataitem = {'value': self.context.lookupMime(attachment_file.getContentType())}
            dataline.append(dataitem)
            dataitem = {'value': '%s%s' %(filesize, sizeunit)}
            dataline.append(dataitem)
            dataitem = {'value': self.ulocalized_time(dateloaded)}
            dataline.append(dataitem)


            datalines.append(dataline)

            count_all += 1

        # footer data
        footlines = []
        footline = []
        footitem = {'value': _('Total'),
                    'colspan': 5,
                    'class': 'total_label'}
        footline.append(footitem)
        footitem = {'value': count_all}
        footline.append(footitem)
        footlines.append(footline)


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


        return {'report_title': self.context.translate(headings['header']),
                'report_data': self.template()}
    def __call__(self):
        # get all the data into datalines

        pc = getToolByName(self.context, "portal_catalog")
        sc = getToolByName(self.context, "bika_setup_catalog")
        bc = getToolByName(self.context, "bika_analysis_catalog")
        rc = getToolByName(self.context, "reference_catalog")
        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        headings["header"] = _("Attachments")
        headings["subheader"] = _("The attachments linked to analysis requests and analyses")

        count_all = 0
        query = {"portal_type": "Attachment"}
        if self.request.form.has_key("ClientUID"):
            client_uid = self.request.form["ClientUID"]
            query["getClientUID"] = client_uid
            client = rc.lookupObject(client_uid)
            client_title = client.Title()
        else:
            client = logged_in_client(self.context)
            if client:
                client_title = client.Title()
                query["getClientUID"] = client.UID()
            else:
                client_title = "Undefined"
        parms.append({"title": _("Client"), "value": client_title, "type": "text"})

        date_query = formatDateQuery(self.context, "Loaded")
        if date_query:
            query["getDateLoaded"] = date_query
            loaded = formatDateParms(self.context, "Loaded")
        else:
            loaded = "Undefined"
        parms.append({"title": _("Loaded"), "value": loaded, "type": "text"})

        # and now lets do the actual report lines
        formats = {
            "columns": 6,
            "col_heads": [_("Request"), _("File"), _("Attachment type"), _("Content type"), _("Size"), _("Loaded")],
            "class": "",
        }

        datalines = []
        attachments = pc(query)
        for a_proxy in attachments:
            attachment = a_proxy.getObject()
            attachment_file = attachment.getAttachmentFile()
            icon = attachment_file.getBestIcon()
            filename = attachment_file.filename
            filesize = attachment_file.get_size()
            filesize = filesize / 1024
            sizeunit = "Kb"
            if filesize > 1024:
                filesize = filesize / 1024
                sizeunit = "Mb"
            dateloaded = attachment.getDateLoaded()
            dataline = []
            dataitem = {"value": attachment.getTextTitle()}
            dataline.append(dataitem)
            dataitem = {"value": filename, "img_before": icon}
            dataline.append(dataitem)
            dataitem = {"value": attachment.getAttachmentType().Title()}
            dataline.append(dataitem)
            dataitem = {"value": self.context.lookupMime(attachment_file.getContentType())}
            dataline.append(dataitem)
            dataitem = {"value": "%s%s" % (filesize, sizeunit)}
            dataline.append(dataitem)
            dataitem = {"value": self.ulocalized_time(dateloaded)}
            dataline.append(dataitem)

            datalines.append(dataline)

            count_all += 1

        # footer data
        footlines = []
        footline = []
        footitem = {"value": _("Total"), "colspan": 5, "class": "total_label"}
        footline.append(footitem)
        footitem = {"value": count_all}
        footline.append(footitem)
        footlines.append(footline)

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

        return {"report_title": self.context.translate(headings["header"]), "report_data": self.template()}
Exemplo n.º 21
0
    def __call__(self):
        bsc = getToolByName(self.context, 'bika_setup_catalog')
        bac = getToolByName(self.context, 'bika_analysis_catalog')
        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        headings['header'] = _("Analyses out of range")
        headings['subheader'] = _("Analyses results out of client or lab specified range")

        count_all = 0

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

        if self.request.form.has_key('spec'):
            spec = self.request.form['spec']
        else:
            spec = 'lab'
        if spec == 'lab':
            lab_spec = True
        else:
            lab_spec = False

        parms.append(
            { 'title': _('Range spec'),
             'value': spec,
             'type': 'text'})

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

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

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


        if self.request.form.has_key('ws_review_state'):
            query['worksheetanalysis_review_state'] = self.request.form['ws_review_state']
            ws_review_state = wf_tool.getTitleForStateOnType(
                        self.request.form['ws_review_state'], '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
        formats = {'columns': 10,
                   'col_heads': [ _('Client'), \
                                  _('Request'), \
                                  _('Sample type'), \
                                  _('Sample point'), \
                                  _('Category'), \
                                  _('Analysis'), \
                                  _('Result'), \
                                  _('Min'), \
                                  _('Max'), \
                                  _('Status'), \
                                  ],
                   'class': '',
                  }

        datalines = []
        clients = {}
        sampletypes = {}
        samplepoints = {}
        categories = {}
        services = {}
        specs = {}

        if lab_spec:
            owner_uid = self.context.bika_setup.bika_analysisspecs.UID()

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

            sampletypeuid = analysis.getSampleTypeUID()

            # determine which specs to use, and load if not yet found
            if not lab_spec:
                owner_uid = analysis.getClientUID()
            if not specs.has_key(owner_uid):
                specs[owner_uid] = {}
            if not specs[owner_uid].has_key(sampletypeuid):
                proxies = bsc(portal_type = 'AnalysisSpec',
                              getSampleTypeUID = sampletypeuid,
                              getClientUID = owner_uid)
                if len(proxies) == 0:
                    continue
                spec_object = proxies[0].getObject()
                specs[owner_uid][sampletypeuid] = spec_object.getResultsRangeDict()
            spec = specs[owner_uid][sampletypeuid]

            keyword = analysis.getKeyword()
            if spec.has_key(keyword):
                spec_min = float(spec[keyword]['min'])
                spec_max = float(spec[keyword]['max'])
                if spec_min <= result <= spec_max:
                    continue
            else:
                continue

            # check if in shoulder: out of range, but in acceptable
            #     error percentage
            shoulder = False
            error_amount = (result / 100) * float(spec[keyword]['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)

            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[keyword]['min']}
            dataline.append(dataitem)

            dataitem = {'value': spec[keyword]['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 = self.context.translate(headings['header'])

        return {'report_title': title,
                'report_data': self.template()}
    def __call__(self):
        # get all the data into datalines

        pc = getToolByName(self.context, 'portal_catalog')
        bac = getToolByName(self.context, 'bika_analysis_catalog')
        bc = getToolByName(self.context, 'bika_catalog')

        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        this_client = logged_in_client(self.context)

        if this_client:
            headings['header'] = _("Analysis requests and analyses")
            headings['subheader'] = _(
                "Number of Analysis requests and analyses")
        else:
            headings['header'] = _("Analysis requests and analyses per client")
            headings['subheader'] = _(
                "Number of Analysis requests and analyses per client")

        count_all_ars = 0
        count_all_analyses = 0
        query = {}

        date_query = formatDateQuery(self.context, 'c_DateRequested')
        if date_query:
            query['created'] = date_query
            requested = formatDateParms(self.context, 'c_DateRequested')
        else:
            requested = 'Undefined'
        parms.append({
            'title': _('Requested'),
            'value': requested,
            'type': 'text'
        })

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

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

        if self.request.form.has_key('ws_review_state'):
            query['worksheetanalysis_review_state'] = self.request.form[
                'ws_review_state']
            ws_review_state = workflow.getTitleForStateOnType(
                self.request.form['ws_review_state'], '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
        formats = {'columns': 3,
                   'col_heads': [ _('Client'), \
                                  _('Number of requests'), \
                                  _('Number of analyses')],
                   'class': '',
                  }

        datalines = []

        if this_client:
            c_proxies = pc(portal_type="Client", UID=this_client.UID())
        else:
            c_proxies = pc(portal_type="Client", sort_on='sortable_title')

        for client in c_proxies:
            query['getClientUID'] = client.UID
            dataline = [
                {
                    'value': client.Title
                },
            ]
            query['portal_type'] = 'AnalysisRequest'
            ars = bc(query)
            count_ars = len(ars)
            dataitem = {'value': count_ars}
            dataline.append(dataitem)

            query['portal_type'] = 'Analysis'
            analyses = bac(query)
            count_analyses = len(analyses)
            dataitem = {'value': count_analyses}
            dataline.append(dataitem)

            datalines.append(dataline)

            count_all_analyses += count_analyses
            count_all_ars += count_ars

        # footer data
        footlines = []
        if not this_client:
            footline = []
            footitem = {'value': _('Total'), 'class': 'total_label'}
            footline.append(footitem)

            footitem = {'value': count_all_ars}
            footline.append(footitem)
            footitem = {'value': count_all_analyses}
            footline.append(footitem)

            footlines.append(footline)

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

        return {
            'report_title': self.context.translate(headings['header']),
            'report_data': self.template()
        }
    def __call__(self):
        # get all the data into datalines

        sc = getToolByName(self.context, "bika_setup_catalog")
        bc = getToolByName(self.context, "bika_analysis_catalog")
        rc = getToolByName(self.context, "reference_catalog")
        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        headings["header"] = _("Analyses per analysis service")
        headings["subheader"] = _("Number of analyses requested per analysis service")

        query = {"portal_type": "Analysis"}
        if self.request.form.has_key("ClientUID"):
            client_uid = self.request.form["ClientUID"]
            query["getClientUID"] = client_uid
            client = rc.lookupObject(client_uid)
            client_title = client.Title()
        else:
            client = logged_in_client(self.context)
            if client:
                client_title = client.Title()
                query["getClientUID"] = client.UID()
            else:
                client_title = _("All")
        parms.append({"title": _("Client"), "value": client_title, "type": "text"})

        date_query = formatDateQuery(self.context, "Requested")
        if date_query:
            query["created"] = date_query
            requested = formatDateParms(self.context, "Requested")
            parms.append({"title": _("Requested"), "value": requested, "type": "text"})

        date_query = formatDateQuery(self.context, "Published")
        if date_query:
            query["getDatePublished"] = date_query
            published = formatDateParms(self.context, "Published")
            parms.append({"title": _("Published"), "value": published, "type": "text"})

        workflow = 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 = workflow.getTitleForStateOnType(self.request.form["bika_analysis_workflow"], "Analysis")
            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 = workflow.getTitleForStateOnType(
                self.request.form["bika_cancellation_workflow"], "Analysis"
            )
            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 = workflow.getTitleForStateOnType(
                self.request.form["bika_worksheetanalysis_workflow"], "Analysis"
            )
            parms.append({"title": _("Assigned to worksheet"), "value": ws_review_state, "type": "text"})

        # and now lets do the actual report lines
        formats = {"columns": 2, "col_heads": [_("Analysis service"), _("Number of analyses")], "class": ""}

        datalines = []
        count_all = 0
        for cat in sc(portal_type="AnalysisCategory", sort_on="sortable_title"):
            dataline = [{"value": cat.Title, "class": "category_heading", "colspan": 2}]
            datalines.append(dataline)
            for service in sc(portal_type="AnalysisService", getCategoryUID=cat.UID, sort_on="sortable_title"):
                query["getServiceUID"] = service.UID
                analyses = bc(query)
                count_analyses = len(analyses)

                dataline = []
                dataitem = {"value": service.Title}
                dataline.append(dataitem)
                dataitem = {"value": count_analyses}

                dataline.append(dataitem)

                datalines.append(dataline)

                count_all += count_analyses

        # footer data
        footlines = []
        footline = []
        footitem = {"value": _("Total"), "class": "total_label"}
        footline.append(footitem)
        footitem = {"value": count_all}
        footline.append(footitem)
        footlines.append(footline)

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

        title = self.context.translate(headings["header"])
        return {"report_title": title, "report_data": self.template()}
    def __call__(self):
        bc = getToolByName(self.context, "bika_catalog")
        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        headings["header"] = _("Analysis requests not invoiced")
        headings["subheader"] = _("Published Analysis Requests which have not been invoiced")

        count_all = 0

        query = {
            "portal_type": "AnalysisRequest",
            "getInvoiced": False,
            "review_state": "published",
            "sort_order": "reverse",
        }

        date_query = formatDateQuery(self.context, "c_DatePublished")
        if date_query:
            query["getDatePublished"] = date_query
            pubished = formatDateParms(self.context, "c_DatePublished")
        else:
            pubished = "Undefined"
        parms.append({"title": _("Published"), "value": pubished, "type": "text"})

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

        # and now lets do the actual report lines
        formats = {
            "columns": 6,
            "col_heads": [_("Client"), _("Request"), _("Sample type"), _("Sample point"), _("Published"), _("Amount")],
            "class": "",
        }

        datalines = []
        clients = {}
        sampletypes = {}
        samplepoints = {}
        categories = {}
        services = {}

        for ar_proxy in bc(query):
            ar = ar_proxy.getObject()

            dataline = []

            dataitem = {"value": ar.aq_parent.Title()}
            dataline.append(dataitem)

            dataitem = {"value": ar.getRequestID()}
            dataline.append(dataitem)

            dataitem = {"value": ar.getSampleTypeTitle()}
            dataline.append(dataitem)

            dataitem = {"value": ar.getSamplePointTitle()}
            dataline.append(dataitem)

            dataitem = {"value": self.ulocalized_time(getTransitionDate(ar, "publish"), long_format=True)}
            dataline.append(dataitem)

            dataitem = {"value": ar.getTotalPrice()}
            dataline.append(dataitem)

            datalines.append(dataline)

            count_all += 1

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

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

        return {"report_title": t(headings["header"]), "report_data": self.template()}
    def __call__(self):
        bac = getToolByName(self.context, 'bika_analysis_catalog')
        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        headings['header'] = _("Analyses retested")
        headings['subheader'] = _("Analyses which have been retested")

        count_all = 0

        query = {'portal_type': 'Analysis',
                 'getRetested': True,
                 'sort_order': 'reverse'}

        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
        formats = {'columns': 8,
                   'col_heads': [ _('Client'),
                                  _('Request'),
                                  _('Sample type'),
                                  _('Sample point'),
                                  _('Category'),
                                  _('Analysis'),
                                  _('Received'),
                                  _('Status'),
                                  ],
                   'class': '',
                  }

        datalines = []
        clients = {}
        sampletypes = {}
        samplepoints = {}
        categories = {}
        services = {}

        for a_proxy in bac(query):
            analysis = a_proxy.getObject()

            dataline = []

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

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

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

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

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

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

            dataitem = {'value': self.ulocalized_time(analysis.getDateReceived())}
            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 retested for period'),
                    'colspan': 7,
                    'class': 'total_label'}
        footline.append(footitem)
        footitem = {'value': count_all}
        footline.append(footitem)
        footlines.append(footline)


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

        title = self.context.translate(headings['header'])

        return {'report_title': title,
                'report_data': self.template()}
    def __call__(self):
        # get all the data into datalines

        pc = getToolByName(self.context, 'portal_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.report_content = {}
        parms = []
        headings = {}
        headings['header'] = _("Attachments")
        headings['subheader'] = _("The attachments linked to analysis requests and analyses")

        count_all = 0
        query = {'portal_type': 'Attachment'}
        if 'ClientUID' in self.request.form:
            client_uid = self.request.form['ClientUID']
            query['getClientUID'] = client_uid
            client = rc.lookupObject(client_uid)
            client_title = client.Title()
        else:
            client = logged_in_client(self.context)
            if client:
                client_title = client.Title()
                query['getClientUID'] = client.UID()
            else:
                client_title = 'All'
        parms.append(
            {'title': _('Client'),
             'value': client_title,
             'type': 'text'})

        date_query = formatDateQuery(self.context, 'Loaded')
        if date_query:
            query['getDateLoaded'] = date_query
            loaded = formatDateParms(self.context, 'Loaded')
            parms.append(
                {'title': _('Loaded'),
                 'value': loaded,
                 'type': 'text'})

        # and now lets do the actual report lines
        formats = {'columns': 6,
                   'col_heads': [_('Request'),
                                  _('File'),
                                  _('Attachment type'),
                                  _('Content type'),
                                  _('Size'),
                                  _('Loaded'),
                                  ],
                   'class': '',
                  }

        datalines = []
        attachments = pc(query)
        for a_proxy in attachments:
            attachment = a_proxy.getObject()
            attachment_file = attachment.getAttachmentFile()
            icon = attachment_file.getBestIcon()
            filename = attachment_file.filename
            filesize = attachment_file.get_size()
            filesize = filesize / 1024
            sizeunit = "Kb"
            if filesize > 1024:
                filesize = filesize / 1024
                sizeunit = "Mb"
            dateloaded = attachment.getDateLoaded()
            dataline = []
            dataitem = {'value': attachment.getTextTitle()}
            dataline.append(dataitem)
            dataitem = {'value': filename,
                        'img_before': icon}
            dataline.append(dataitem)
            dataitem = {'value': attachment.getAttachmentType().Title() if attachment.getAttachmentType() else ''}
            dataline.append(dataitem)
            dataitem = {'value': self.context.lookupMime(attachment_file.getContentType())}
            dataline.append(dataitem)
            dataitem = {'value': '%s%s' % (filesize, sizeunit)}
            dataline.append(dataitem)
            dataitem = {'value': self.ulocalized_time(dateloaded)}
            dataline.append(dataitem)

            datalines.append(dataline)

            count_all += 1

        # footer data
        footlines = []
        footline = []
        footitem = {'value': _('Total'),
                    'colspan': 5,
                    'class': 'total_label'}
        footline.append(footitem)
        footitem = {'value': count_all}
        footline.append(footitem)
        footlines.append(footline)

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

        if self.request.get('output_format', '') == 'CSV':
            import csv
            import StringIO
            import datetime
            fieldnames = [
                _('Request'),
                _('File'),
                _('Attachment type'),
                _('Content type'),
                _('Size'),
                _('Loaded'),
            ]
            output = StringIO.StringIO()
            dw = csv.DictWriter(output, fieldnames=fieldnames)
            dw.writerow(dict((fn, fn) for fn in fieldnames))
            for row in datalines:
                dw.writerow(row)
            report_data = output.getvalue()
            output.close()
            date = datetime.datetime.now().strftime("%Y%m%d%H%M")
            setheader = self.request.RESPONSE.setHeader
            setheader('Content-Type', 'text/csv')
            setheader("Content-Disposition",
                "attachment;filename=\"analysesattachments_%s.csv\"" % date)
            self.request.RESPONSE.write(report_data)
        else:
            return {'report_title': self.context.translate(headings['header']),
                    'report_data': self.template()}
Exemplo n.º 27
0
    def __call__(self):
        bc = getToolByName(self.context, 'bika_catalog')
        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        headings['header'] = _("Samples not invoiced")
        headings['subheader'] = _(
            "Published Samples which have not been invoiced")

        count_all = 0

        query = {'portal_type': 'AnalysisRequest',
                 'getInvoiced': False,
                 'review_state': 'published',
                 'sort_order': 'reverse'}

        date_query = formatDateQuery(self.context, 'c_DatePublished')
        if date_query:
            query['getDatePublished'] = date_query
            pubished = formatDateParms(self.context, 'c_DatePublished')
        else:
            pubished = 'Undefined'
        parms.append(
            {'title': _('Published'),
             'value': pubished,
             'type': 'text'})

        parms.append(
            {'title': _('Active'),
             'value': 'Undefined',
             'type': 'text'})



        # and now lets do the actual report lines
        formats = {'columns': 6,
                   'col_heads': [_('Client'), \
                                 _('Request'), \
                                 _('Sample type'), \
                                 _('Sample point'), \
                                 _('Published'), \
                                 _('Amount'), \
                       ],
                   'class': '',
        }

        datalines = []
        clients = {}
        sampletypes = {}
        samplepoints = {}
        categories = {}
        services = {}

        for ar_proxy in bc(query):
            ar = ar_proxy.getObject()

            dataline = []

            dataitem = {'value': ar.aq_parent.Title()}
            dataline.append(dataitem)

            dataitem = {'value': ar.getId()}
            dataline.append(dataitem)

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

            dataitem = {'value': ar.getSamplePointTitle()}
            dataline.append(dataitem)

            dataitem = {'value':
                        self.ulocalized_time(getTransitionDate(ar, 'publish'),
                                             long_format=True)}
            dataline.append(dataitem)

            dataitem = {'value': ar.getTotalPrice()}
            dataline.append(dataitem)

            datalines.append(dataline)

            count_all += 1

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

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

        return {'report_title': t(headings['header']),
                'report_data': self.template()}
    def __call__(self):
        # get all the data into datalines

        bc = getToolByName(self.context, 'bika_analysis_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.report_content = {}
        parms = []
        headings = {}
        headings['header'] = _("Analysis turnaround times over time")
        headings['subheader'] = \
            _("The turnaround time of analyses plotted over time")

        query = {'portal_type': 'Analysis'}

        if 'ServiceUID' in self.request.form:
            service_uid = self.request.form['ServiceUID']
            query['ServiceUID'] = service_uid
            service = rc.lookupObject(service_uid)
            service_title = service.Title()
            parms.append({
                'title': _('Analysis Service'),
                'value': service_title,
                'type': 'text'
            })

        if 'Analyst' in self.request.form:
            analyst = self.request.form['Analyst']
            query['getAnalyst'] = analyst
            analyst_title = self.user_fullname(analyst)
            parms.append({
                'title': _('Analyst'),
                'value': analyst_title,
                'type': 'text'
            })

        if 'getInstrumentUID' in self.request.form:
            instrument_uid = self.request.form['getInstrumentUID']
            query['getInstrument'] = instrument_uid
            instrument = rc.lookupObject(instrument_uid)
            instrument_title = instrument.Title()
            parms.append({
                'title': _('Instrument'),
                'value': instrument_title,
                'type': 'text'
            })

        if 'Period' in self.request.form:
            period = self.request.form['Period']
        else:
            period = 'Day'

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

        query['review_state'] = 'published'

        # query all the analyses and increment the counts

        periods = {}
        total_count = 0
        total_duration = 0

        analyses = bc(query)
        for a in analyses:
            analysis = a.getObject()
            received = analysis.created()
            if period == 'Day':
                datekey = received.strftime('%d %b %Y')
            elif period == 'Week':
                # key period on Monday
                dayofweek = received.strftime('%w')  # Sunday = 0
                if dayofweek == 0:
                    firstday = received - 6
                else:
                    firstday = received - (int(dayofweek) - 1)
                datekey = firstday.strftime(self.date_format_short)
            elif period == 'Month':
                datekey = received.strftime('%m-%d')
            if datekey not in periods:
                periods[datekey] = {
                    'count': 0,
                    'duration': 0,
                }
            count = periods[datekey]['count']
            duration = periods[datekey]['duration']
            count += 1
            duration += analysis.getDuration()
            periods[datekey]['duration'] = duration
            periods[datekey]['count'] = count
            total_count += 1
            total_duration += duration

        # calculate averages
        for datekey in periods.keys():
            count = periods[datekey]['count']
            duration = periods[datekey]['duration']
            ave_duration = (duration) / count
            periods[datekey]['duration'] = \
                formatDuration(self.context, ave_duration)

        # and now lets do the actual report lines
        formats = {
            'columns': 2,
            'col_heads': [
                _('Date'),
                _('Turnaround time (h)'),
            ],
            'class': '',
        }

        datalines = []

        period_keys = periods.keys()
        for period in period_keys:
            dataline = [
                {
                    'value': period,
                    'class': ''
                },
            ]
            dataline.append({
                'value': periods[period]['duration'],
                'class': 'number'
            })
            datalines.append(dataline)

        if total_count > 0:
            ave_total_duration = total_duration / total_count
        else:
            ave_total_duration = 0
        ave_total_duration = formatDuration(self.context, ave_total_duration)

        # footer data
        footlines = []
        footline = []
        footline = [
            {
                'value': _('Total data points'),
                'class': 'total'
            },
        ]

        footline.append({'value': total_count, 'class': 'total number'})
        footlines.append(footline)

        footline = [
            {
                'value': _('Average TAT'),
                'class': 'total'
            },
        ]

        footline.append({'value': ave_total_duration, 'class': 'total number'})
        footlines.append(footline)

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

        if self.request.get('output_format', '') == 'CSV':
            import csv
            import StringIO
            import datetime

            fieldnames = [
                'Date',
                'Turnaround time (h)',
            ]
            output = StringIO.StringIO()
            dw = csv.DictWriter(output,
                                extrasaction='ignore',
                                fieldnames=fieldnames)
            dw.writerow(dict((fn, fn) for fn in fieldnames))
            for row in datalines:
                dw.writerow({
                    'Date': row[0]['value'],
                    'Turnaround time (h)': row[1]['value'],
                })
            report_data = output.getvalue()
            output.close()
            date = datetime.datetime.now().strftime("%Y%m%d%H%M")
            setheader = self.request.RESPONSE.setHeader
            setheader('Content-Type', 'text/csv')
            setheader(
                "Content-Disposition",
                "attachment;filename=\"analysesperservice_%s.csv\"" % date)
            self.request.RESPONSE.write(report_data)
        else:
            return {
                'report_title': t(headings['header']),
                'report_data': self.template()
            }
    def __call__(self):
        # get all the data into datalines

        pc = getToolByName(self.context, 'portal_catalog')
        bac = getToolByName(self.context, 'bika_analysis_catalog')
        bc = getToolByName(self.context, 'bika_catalog')
        rc = getToolByName(self.context, 'reference_catalog')

        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        count_all_ars = 0
        count_all_analyses = 0
        query = {}

        this_client = logged_in_client(self.context)

        if not this_client and 'ClientUID' in self.request.form:
            client_uid = self.request.form['ClientUID']
            this_client = rc.lookupObject(client_uid)
            parms.append({
                'title': _('Client'),
                'value': this_client.Title(),
                'type': 'text'
            })

        if this_client:
            headings['header'] = _("Analysis requests and analyses")
            headings['subheader'] = _(
                "Number of Analysis requests and analyses")
        else:
            headings['header'] = _("Analysis requests and analyses per client")
            headings['subheader'] = _(
                "Number of Analysis requests and analyses per client")

        date_query = formatDateQuery(self.context, 'Requested')
        if date_query:
            query['created'] = date_query
            requested = formatDateParms(self.context, 'Requested')
            parms.append({
                'title': _('Requested'),
                'value': requested,
                'type': 'text'
            })

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

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

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

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

        # and now lets do the actual report lines
        formats = {
            'columns':
            3,
            'col_heads':
            [_('Client'),
             _('Number of requests'),
             _('Number of analyses')],
            'class':
            ''
        }

        datalines = []

        if this_client:
            c_proxies = pc(portal_type="Client", UID=this_client.UID())
        else:
            c_proxies = pc(portal_type="Client", sort_on='sortable_title')

        for client in c_proxies:
            query['getClientUID'] = client.UID
            dataline = [
                {
                    'value': client.Title
                },
            ]
            query['portal_type'] = 'AnalysisRequest'
            ars = bc(query)
            count_ars = len(ars)
            dataitem = {'value': count_ars}
            dataline.append(dataitem)

            query['portal_type'] = 'Analysis'
            analyses = bac(query)
            count_analyses = len(analyses)
            dataitem = {'value': count_analyses}
            dataline.append(dataitem)

            datalines.append(dataline)

            count_all_analyses += count_analyses
            count_all_ars += count_ars

        # footer data
        footlines = []
        if not this_client:
            footline = []
            footitem = {'value': _('Total'), 'class': 'total_label'}
            footline.append(footitem)

            footitem = {'value': count_all_ars}
            footline.append(footitem)
            footitem = {'value': count_all_analyses}
            footline.append(footitem)

            footlines.append(footline)

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

        if self.request.get('output_format', '') == 'CSV':
            import csv
            import StringIO
            import datetime

            fieldnames = [
                'Client',
                'Analysis Requests',
                'Analyses',
            ]
            output = StringIO.StringIO()
            dw = csv.DictWriter(output,
                                extrasaction='ignore',
                                fieldnames=fieldnames)
            dw.writerow(dict((fn, fn) for fn in fieldnames))
            for row in datalines:
                dw.writerow({
                    'Client': row[0]['value'],
                    'Analysis Requests': row[1]['value'],
                    'Analyses': row[2]['value'],
                })
            report_data = output.getvalue()
            output.close()
            date = datetime.datetime.now().strftime("%Y%m%d%H%M")
            setheader = self.request.RESPONSE.setHeader
            setheader('Content-Type', 'text/csv')
            setheader(
                "Content-Disposition",
                "attachment;filename=\"analysesperclient_%s.csv\"" % date)
            self.request.RESPONSE.write(report_data)
        else:
            return {
                'report_title': t(headings['header']),
                'report_data': self.template()
            }
Exemplo n.º 30
0
    def __call__(self):
        # get all the data into datalines
        
        sc = getToolByName(self.context, 'bika_setup_catalog')
        bc = getToolByName(self.context, 'bika_analysis_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        headings['header'] = _("Analysis turnaround times over time")
        headings['subheader'] = \
               _("The turnaround time of analyses plotted over time")

        count_all = 0
        query = {'portal_type': 'Analysis'}

        if self.request.form.has_key('getServiceUID'):
            service_uid = self.request.form['getServiceUID']
            query['getServiceUID'] = service_uid
            service = rc.lookupObject(service_uid)
            service_title = service.Title()
        else:
            service_title = 'Undefined'
        parms.append(
            { 'title': _('Analysis Service'),
             'value': service_title,
             'type': 'text'})

        if self.request.form.has_key('Analyst'):
            analyst = self.request.form['Analyst']
            query['getAnalyst'] = analyst
            analyst_title = pretty_user_name_or_id(self.context, analyst)
        else:
            analyst_title = 'Undefined'
        parms.append(
            { 'title': _('Analyst'),
             'value': analyst_title,
             'type': 'text'})

        if self.request.form.has_key('getInstrumentUID'):
            instrument_uid = self.request.form['getInstrumentUID']
            query['getInstrument'] = instrument_uid
            instrument = rc.lookupObject(instrument_uid)
            instrument_title = instrument.Title()
        else:
            instrument_title = 'Undefined'
        parms.append(
            { 'title': _('Instrument'),
             'value': instrument_title,
             'type': 'text'})

        if self.request.form.has_key('Period'):
            period = self.request.form['Period']
        else:
            period = 'Day'

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

        query['review_state'] = 'published'


        # query all the analyses and increment the counts

        periods = {}
        total_count = 0
        total_duration = 0

        analyses = bc(query)
        for a in analyses:
            analysis = a.getObject()
            received = analysis.created()
            if period == 'Day':
                datekey = received.strftime('%d %b %Y')
            elif period == 'Week':
                # key period on Monday 
                dayofweek = received.strftime('%w') # Sunday = 0
                if dayofweek == 0:
                    firstday = received - 6
                else:
                    firstday = received - (int(dayofweek) - 1)
                datekey = firstday.strftime('%d %b %Y')
            elif period == 'Month':
                datekey = received.strftime('%b %Y')
            if not periods.has_key(datekey):
                periods[datekey] = {'count': 0,
                                    'duration': 0,
                                   }
            count = periods[datekey]['count']
            duration = periods[datekey]['duration']
            count += 1
            duration += analysis.getDuration()
            periods[datekey]['duration'] = duration
            periods[datekey]['count'] = count
            total_count += 1
            total_duration += duration

        # calculate averages
        for datekey in periods.keys():
            count = periods[datekey]['count']
            duration = periods[datekey]['duration']
            ave_duration = (duration) / count
            periods[datekey]['duration'] = \
                formatDuration(self.context, ave_duration)

        # and now lets do the actual report lines
        formats = {'columns': 2,
                   'col_heads': [ _('Date'), \
                                  _('Turnaround time (h)'), \
                                  ],
                   'class': '',
                  }


        datalines = []

        period_keys = periods.keys()
        for period in period_keys: 
            dataline = [{'value': period,
                        'class' : ''},]
            dataline.append({'value': periods[period]['duration'],
                             'class' : 'number'})
            datalines.append(dataline)


        ave_total_duration = total_duration / total_count
        ave_total_duration = formatDuration(self.context, ave_total_duration)



        # footer data
        footlines = []
        footline = []
        footline = [{'value': _('Total data points'),
                     'class': 'total'}, ]

        footline.append({'value' : total_count,
                         'class' : 'total number'})
        footlines.append(footline)

        footline = [{'value': _('Average TAT'),
                     'class': 'total'}, ]

        footline.append({'value' : ave_total_duration,
                         'class' : 'total number'})
        footlines.append(footline)

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


        return self.template()
    def __call__(self):
        # get all the data into datalines

        sc = getToolByName(self.context, 'bika_setup_catalog')
        bc = getToolByName(self.context, 'bika_analysis_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        headings['header'] = _("Analyses per analysis service")
        headings['subheader'] = _("Number of analyses requested per analysis service")

        count_all = 0
        query = {'portal_type': 'Analysis'}
        if self.request.form.has_key('getClientUID'):
            client_uid = self.request.form['getClientUID']
            query['getClientUID'] = client_uid
            client = rc.lookupObject(client_uid)
            client_title = client.Title()
        else:
            client = logged_in_client(self.context)
            if client:
                client_title = client.Title()
                query['getClientUID'] = client.UID()
            else:
                client_title = _('All')
        parms.append(
            { 'title': _('Client'),
             'value': client_title,
             'type': 'text'})

        date_query = formatDateQuery(self.context, 'DateRequested')
        if date_query:
            query['created'] = date_query
            requested = formatDateParms(self.context, 'DateRequested')
            parms.append(
                { 'title': _('Requested'),
                  'value': requested,
                  'type': 'text'})

        date_query = formatDateQuery(self.context, 'DatePublished')
        if date_query:
            query['getDatePublished'] = date_query
            published = formatDateParms(self.context, 'DatePublished')
        else:
            published = 'Undefined'
        parms.append(
            { 'title': _('Published'),
             'value': published,
             'type': 'text'})


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

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



        if self.request.form.has_key('ws_review_state'):
            query['worksheetanalysis_review_state'] = self.request.form['ws_review_state']
            ws_review_state = workflow.getTitleForStateOnType(
                        self.request.form['ws_review_state'], '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
        formats = {'columns': 2,
                   'col_heads': [ _('Analysis service'), _('Number of analyses')],
                   'class': '',
                  }

        datalines = []
        for cat in sc(portal_type="AnalysisCategory",
                        sort_on='sortable_title'):
            dataline = [{'value': cat.Title,
                        'class': 'category_heading',
                        'colspan': 2},]
            datalines.append(dataline)
            for service in sc(portal_type="AnalysisService",
                            getCategoryUID = cat.UID,
                            sort_on='sortable_title'):
                query['getServiceUID'] = service.UID
                analyses = bc(query)
                count_analyses = len(analyses)

                dataline = []
                dataitem = {'value': service.Title}
                dataline.append(dataitem)
                dataitem = {'value': count_analyses }

                dataline.append(dataitem)


                datalines.append(dataline)

                count_all += count_analyses

        # footer data
        footlines = []
        footline = []
        footitem = {'value': _('Total'),
                    'class': 'total_label'}
        footline.append(footitem)
        footitem = {'value': count_all}
        footline.append(footitem)
        footlines.append(footline)


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


        title = self.context.translate(headings['header'])
        return {'report_title': title,
                'report_data': self.template()}
Exemplo n.º 32
0
    def __call__(self):
        # get all the data into datalines

        sc = getToolByName(self.context, 'bika_setup_catalog')
        bc = getToolByName(self.context, 'bika_analysis_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        headings['header'] = _("Analysis turnaround times over time")
        headings['subheader'] = \
               _("The turnaround time of analyses plotted over time")

        count_all = 0
        query = {'portal_type': 'Analysis'}

        if self.request.form.has_key('getServiceUID'):
            service_uid = self.request.form['getServiceUID']
            query['getServiceUID'] = service_uid
            service = rc.lookupObject(service_uid)
            service_title = service.Title()
        else:
            service_title = 'Undefined'
        parms.append({
            'title': _('Analysis Service'),
            'value': service_title,
            'type': 'text'
        })

        if self.request.form.has_key('Analyst'):
            analyst = self.request.form['Analyst']
            query['getAnalyst'] = analyst
            analyst_title = self.user_fullname(analyst)
        else:
            analyst_title = 'Undefined'
        parms.append({
            'title': _('Analyst'),
            'value': analyst_title,
            'type': 'text'
        })

        if self.request.form.has_key('getInstrumentUID'):
            instrument_uid = self.request.form['getInstrumentUID']
            query['getInstrument'] = instrument_uid
            instrument = rc.lookupObject(instrument_uid)
            instrument_title = instrument.Title()
        else:
            instrument_title = 'Undefined'
        parms.append({
            'title': _('Instrument'),
            'value': instrument_title,
            'type': 'text'
        })

        if self.request.form.has_key('Period'):
            period = self.request.form['Period']
        else:
            period = 'Day'

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

        query['review_state'] = 'published'

        # query all the analyses and increment the counts

        periods = {}
        total_count = 0
        total_duration = 0

        analyses = bc(query)
        for a in analyses:
            analysis = a.getObject()
            received = analysis.created()
            if period == 'Day':
                datekey = received.strftime('%d %b %Y')
            elif period == 'Week':
                # key period on Monday
                dayofweek = received.strftime('%w')  # Sunday = 0
                if dayofweek == 0:
                    firstday = received - 6
                else:
                    firstday = received - (int(dayofweek) - 1)
                datekey = firstday.strftime(self.date_format_short)
            elif period == 'Month':
                datekey = received.strftime('%m-%d')
            if not periods.has_key(datekey):
                periods[datekey] = {
                    'count': 0,
                    'duration': 0,
                }
            count = periods[datekey]['count']
            duration = periods[datekey]['duration']
            count += 1
            duration += analysis.getDuration()
            periods[datekey]['duration'] = duration
            periods[datekey]['count'] = count
            total_count += 1
            total_duration += duration

        # calculate averages
        for datekey in periods.keys():
            count = periods[datekey]['count']
            duration = periods[datekey]['duration']
            ave_duration = (duration) / count
            periods[datekey]['duration'] = \
                formatDuration(self.context, ave_duration)

        # and now lets do the actual report lines
        formats = {
            'columns': 2,
            'col_heads': [
                _('Date'),
                _('Turnaround time (h)'),
            ],
            'class': '',
        }

        datalines = []

        period_keys = periods.keys()
        for period in period_keys:
            dataline = [
                {
                    'value': period,
                    'class': ''
                },
            ]
            dataline.append({
                'value': periods[period]['duration'],
                'class': 'number'
            })
            datalines.append(dataline)

        if total_count > 0:
            ave_total_duration = total_duration / total_count
        else:
            ave_total_duration = 0
        ave_total_duration = formatDuration(self.context, ave_total_duration)

        # footer data
        footlines = []
        footline = []
        footline = [
            {
                'value': _('Total data points'),
                'class': 'total'
            },
        ]

        footline.append({'value': total_count, 'class': 'total number'})
        footlines.append(footline)

        footline = [
            {
                'value': _('Average TAT'),
                'class': 'total'
            },
        ]

        footline.append({'value': ave_total_duration, 'class': 'total number'})
        footlines.append(footline)

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

        title = self.context.translate(headings['header'])

        return {'report_title': title, 'report_data': self.template()}
    def __call__(self):
        # get all the data into datalines

        pc = getToolByName(self.context, 'portal_catalog')
        bac = getToolByName(self.context, 'bika_analysis_catalog')
        bc = getToolByName(self.context, 'bika_catalog')
        rc = getToolByName(self.context, 'reference_catalog')

        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        count_all_ars = 0
        count_all_analyses = 0
        query = {}

        this_client = logged_in_client(self.context)

        if not this_client and 'ClientUID' in self.request.form:
            client_uid = self.request.form['ClientUID']
            this_client = rc.lookupObject(client_uid)
            parms.append(
                {'title': _('Client'),
                 'value': this_client.Title(),
                 'type': 'text'})

        if this_client:
            headings['header'] = _("Analysis requests and analyses")
            headings['subheader'] = _("Number of Analysis requests and analyses")
        else:
            headings['header'] = _("Analysis requests and analyses per client")
            headings['subheader'] = _(
                "Number of Analysis requests and analyses per client")

        date_query = formatDateQuery(self.context, 'Requested')
        if date_query:
            query['created'] = date_query
            requested = formatDateParms(self.context, 'Requested')
            parms.append(
                {'title': _('Requested'),
                 'value': requested,
                 'type': 'text'})

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

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

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

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

        # and now lets do the actual report lines
        formats = {'columns': 3,
                   'col_heads': [_('Client'),
                                 _('Number of requests'),
                                 _('Number of analyses')],
                   'class': ''}

        datalines = []

        if this_client:
            c_proxies = pc(portal_type="Client", UID=this_client.UID())
        else:
            c_proxies = pc(portal_type="Client", sort_on='sortable_title')

        for client in c_proxies:
            query['getClientUID'] = client.UID
            dataline = [{'value': client.Title}, ]
            query['portal_type'] = 'AnalysisRequest'
            ars = bc(query)
            count_ars = len(ars)
            dataitem = {'value': count_ars}
            dataline.append(dataitem)

            query['portal_type'] = 'Analysis'
            analyses = bac(query)
            count_analyses = len(analyses)
            dataitem = {'value': count_analyses}
            dataline.append(dataitem)

            datalines.append(dataline)

            count_all_analyses += count_analyses
            count_all_ars += count_ars

        # footer data
        footlines = []
        if not this_client:
            footline = []
            footitem = {'value': _('Total'),
                        'class': 'total_label'}
            footline.append(footitem)

            footitem = {'value': count_all_ars}
            footline.append(footitem)
            footitem = {'value': count_all_analyses}
            footline.append(footitem)

            footlines.append(footline)

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

        if self.request.get('output_format', '') == 'CSV':
            import csv
            import StringIO
            import datetime

            fieldnames = [
                'Client',
                'Analysis Requests',
                'Analyses',
            ]
            output = StringIO.StringIO()
            dw = csv.DictWriter(output, extrasaction='ignore',
                                fieldnames=fieldnames)
            dw.writerow(dict((fn, fn) for fn in fieldnames))
            for row in datalines:
                dw.writerow({
                    'Client': row[0]['value'],
                    'Analysis Requests': row[1]['value'],
                    'Analyses': row[2]['value'],
                })
            report_data = output.getvalue()
            output.close()
            date = datetime.datetime.now().strftime("%Y%m%d%H%M")
            setheader = self.request.RESPONSE.setHeader
            setheader('Content-Type', 'text/csv')
            setheader("Content-Disposition",
                      "attachment;filename=\"analysesperclient_%s.csv\"" % date)
            self.request.RESPONSE.write(report_data)
        else:
            return {'report_title': t(headings['header']),
                    'report_data': self.template()}
    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
                ar_spec_obj = ar.getSpecification()
                if ar_spec_obj:
                    rr = ar_spec_obj.getResultsRangeDict()
                    if keyword in rr:
                        spec_dict = rr[keyword]
                else:
                    if hasattr(analysis, "specification") \
                            and analysis.specification:
                        spec_dict = analysis.specification
                    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()}
Exemplo n.º 35
0
    def __call__(self):
        self.datalines = []
        workflow = getToolByName(self, 'portal_workflow')

        # check for batch size
        if self.request.form.has_key('size'):
            batch_size = self.request.form['size']
        else:
            batch_size = 6

        # check for batch start
        if self.request.form.has_key('b_start'):
            batch_start = self.request.form['b_start']
        else:
            batch_start = 0

        sc = getToolByName(self.context, 'bika_setup_catalog')
        bc = getToolByName(self.context, 'bika_catalog')
        bac = getToolByName(self.context, 'bika_analysis_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.query_content = {}
        parm_lines = {}
        self.parms = []
        self.headings = {}
        self.headings['header'] = _("Analysis Requests")
        self.headings['head_parms'] = _("Selected on the following criteria")
        self.headings['head_undefined'] = _("Parameters undefined")

        count_all = 0
        query = {'portal_type': 'AnalysisRequest'}

        undefined = []

        # Client
        client_title = None
        if self.request.form.has_key('ClientUID'):
            client_uid = self.request.form['ClientUID']
            query['getClientUID'] = client_uid
            client = rc.lookupObject(client_uid)
            client_title = client.Title()
        else:
            client = logged_in_client(self.context)
            if client:
                client_title = client.Title()
                query['getClientUID'] = client.UID()
        if client_title:
            self.parms.append(
                { 'title': _('Client'),
                  'fieldid': 'ClientUID',
                  'value': client_title,
                  'type': 'text'})
        else:
            undefined.append('Client')

        # Contact
        if self.request.form.has_key('ContactUID'):
            contact_uid = self.request.form['ContactUID']
            query['getContactUID'] = contact_uid
            contact = rc.lookupObject(contact_uid)
            contact_name = contact.getFullname()
            self.parms.append(
                { 'title': _('Contact'),
                  'fieldid': 'ContactUID',
                  'value': contact_name,
                  'type': 'text'})
        else:
            undefined.append('Contact')

        # Profile
        if self.request.form.has_key('ProfileUID'):
            profile_uid = self.request.form['ProfileUID']
            query['getAnalysisProfileUID'] = profile_uid
            profile = rc.lookupObject(profile_uid)
            profile_title = profile.Title()
            self.parms.append(
                { 'title': _('Profile'),
                 'value': profile_title,
                 'type': 'text'})
        else:
            undefined.append('Profile')

        # Request ID
        if self.request.form.has_key('RequestID'):
            request_id = self.request.form['RequestID']
            query['getRequestID'] = request_id
            self.parms.append(
                { 'title': _('AR'),
                 'value': request_id,
                 'type': 'text'})
        else:
            undefined.append('AR')

        # Client order number
        if self.request.form.has_key('ClientOrderNumber'):
            clientoid = self.request.form['ClientOrderNumber']
            query['getClientOrderNumber'] = clientoid
            self.parms.append(
                { 'title': _('Client order number'),
                 'value': clientoid,
                 'type': 'text'})
        else:
            undefined.append('Client order number')

        # Client reference
        if self.request.form.has_key('ClientReference'):
            clientref = self.request.form['ClientReference']
            query['getClientReference'] = clientref
            self.parms.append(
                { 'title': _('Client reference'),
                 'value': clientref,
                 'type': 'text'})
        else:
            undefined.append('Client reference')

        # Client sample ID
        if self.request.form.has_key('ClientSampleID'):
            clientsid = self.request.form['ClientSampleID']
            query['getClientSampleID'] = clientsid
            self.parms.append(
                { 'title': _('Client sample ID'),
                 'value': clientsid,
                 'type': 'text'})
        else:
            undefined.append('Client sample ID')

        # Sample type
        if self.request.form.has_key('SampleTypeUID'):
            st_uid = self.request.form['SampleTypeUID']
            query['getSampleTypeUID'] = st_uid
            st = rc.lookupObject(st_uid)
            st_title = st.Title()
            self.parms.append(
                { 'title': _('Sample type'),
                  'value': st_title,
                  'type': 'text'})
        else:
            undefined.append('Sample type')

        # Sample point
        if self.request.form.has_key('SamplePointUID'):
            sp_uid = self.request.form['SamplePointUID']
            query['getSamplePointUID'] = sp_uid
            sp = rc.lookupObject(sp_uid)
            sp_title = sp.Title()
            self.parms.append(
               { 'title': _('Sample point'),
                 'value': sp_title,
                 'type': 'text'})
        else:
            undefined.append('Sample point')

        # Date sampled
        date_query = formatDateQuery(self.context, 'DateSampled')
        if date_query:
            query['created'] = date_query
            sampled = formatDateParms(self.context, 'DateSampled')
            self.parms.append(
                { 'title': _('Sampled'),
                 'value': sampled,
                 'type': 'text'})
        else:
            undefined.append('Sampled')

        # Date requested
        date_query = formatDateQuery(self.context, 'DateRequested')
        if date_query:
            query['created'] = date_query
            requested = formatDateParms(self.context, 'DateRequested')
            self.parms.append(
                { 'title': _('Requested'),
                 'value': requested,
                 'type': 'text'})
        else:
            undefined.append('Requested')

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

        # Date published
        date_query = formatDateQuery(self.context, 'DatePublished')
        if date_query:
            query['getDatePublished'] = date_query
            published = formatDateParms(self.context, 'DatePublished')
            self.parms.append(
                { 'title': _('Published'),
                 'value': published,
                 'type': 'text'})
        else:
            undefined.append('Published')

        # Category
        if self.request.form.has_key('CategoryUID'):
            category_uid = self.request.form['CategoryUID']
            query['getCategoryUID'] = category_uid
            category = rc.lookupObject(category_uid)
            category_title = category.Title()
            self.parms.append(
                { 'title': _('Category'),
                 'value': category_title,
                 'type': 'text'})
        else:
            undefined.append('Category')

        # Analysis service
        if self.request.form.has_key('ServiceUID'):
            service_uid = self.request.form['ServiceUID']
            query['getServiceUID'] = service_uid
            service = rc.lookupObject(service_uid)
            service_title = service.Title()
            self.parms.append(
                {'title': _('Analysis service'),
                 'value': service_title,
                 'type': 'text'})
        else:
            undefined.append('Analysis service')

        # Analyst
        if self.request.form.has_key('Analyst'):
            analyst = self.request.form['Analyst']
            query['getAnalyst'] = analyst
            analyst_name = self.user_fullname(analyst)
            self.parms.append(
                {'title': _('Analyst'),
                 'value': analyst_name,
                 'type': 'text'})
        else:
            undefined.append('Analyst')

        # Status
        if self.request.form.has_key('review_state'):
            query['review_state'] = self.request.form['review_state']
            review_state = workflow.getTitleForStateOnType(
                        self.request.form['review_state'], 'Analysis')
            self.parms.append(
                {'title': _('Status'),
                 'value': review_state,
                 'type': 'text'})
        else:
            undefined.append('Status')

        # Cancellation state
        if self.request.form.has_key('cancellation_state'):
            query['cancellation_state'] = self.request.form['cancellation_state']
            cancellation_state = workflow.getTitleForStateOnType(
                        self.request.form['cancellation_state'], 'Analysis')
            self.parms.append(
                {'title': _('Active'),
                 'value': cancellation_state,
                 'type': 'text'})
        else:
            undefined.append('Active')



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


        # set up the undefined parameters in pretty format
        undefined_string = ', '.join(undefined)
        self.parms_undefined = [{'title': _('Parameters not defined'),
                                 'value': undefined_string}]

        self.columns = batch_size + 1
        # and now lets do the actual query lines
        self.formats = {'columns': self.columns,
                   'col_heads': [],
                   'class': '',
                  }


        labels = ["Client order ID",
                  "Client reference",
                  "Client sample ID",
                  "Client",
                  "Contact",
                  "Request ID",
                  "Sample ID",
                  "Profile",
                  "Sample type",
                  "Sample point",
                  "Sampled",
                  "Requested",
                  "Received",
                  "Published",
                  "Status",
                  "Submitted by",
                  "Verified by"]
        for label in labels:
            self.datalines.append([{'value': _(label),
                                    'class': 'header',}])

        details = []
        for i in range(len(self.datalines)):
            details.append([])

        ars = bc(query)
        self.url = self.request.URL
        self.show_all = False

        self.batch = Batch(ars, batch_size, batch_start)

        analyses = []
        analysis_dict = {}
        service_dict = {}
        ar_ids = []
        for arp in self.batch:
            ar = arp.getObject()
            ar_ids.append(ar.getRequestID())
            details[0].append({'value': ar.getClientOrderNumber()})
            details[1].append({'value': ar.getClientReference()})
            details[2].append({'value': ar.getClientSampleID()})
            details[3].append({'value': ar.aq_parent.Title()})
            details[4].append({'value': ar.getContact().Title()})
            details[5].append({'value': ar.getRequestID()})
            details[6].append({'value': ar.getSample().getSampleID()})
            details[7].append({'value': ar.getProfile() and ar.getProfile().Title() or ' '})
            details[8].append({'value': ar.getSampleTypeTitle()})

            details[10].append({'value': self.ulocalized_time(ar.getSample().getDateSampled())})
            details[11].append({'value': self.ulocalized_time(ar.created())})
            details[12].append({'value': self.ulocalized_time(ar.getDateReceived())})
            details[13].append({'value': self.ulocalized_time(ar.getDatePublished())})
            details[14].append({'value': workflow.getInfoFor(ar, 'review_state')})
            #details[15].append({'value': ar.getSubmittedBy().Title()})
            details[15].append({'value': ' '})

            #details[16].append({'value': ar.get_verifier().Title()})
            details[16].append({'value': ' '})

            #analyses
            for analysis in ar.getAnalyses(full_objects=True):
                service_uid = analysis.getServiceUID()
                if not analysis_dict.has_key(service_uid):
                    service_dict[analysis.Title()] = service_uid
                    analysis_dict[service_uid] = {}
                analysis_dict[service_uid][ar.getRequestID()] = analysis.getResult()

            if len(details[0]) == batch_size:
                break


        # load the detail lines
        for i in range(len(self.datalines)):
            self.datalines[i].extend(details[i])

        # load the analysis lines
        service_titles = service_dict.keys()
        service_titles.sort()

        for service_title in service_titles:
            service_uid = service_dict[service_title]
            analysis_line = [{'value': service_title},]
            for ar_id in ar_ids:
                if analysis_dict[service_uid].has_key(ar_id):
                    analysis_line.append({'value': analysis_dict[service_uid][ar_id]})
                else:
                    analysis_line.append({})
            self.datalines.append(analysis_line)



        # footer data
        self.footlines = []
        footline = []
        footitem = {'value': _('Total'),
                    'class': 'total_label'}
        footline.append(footitem)
        footitem = {'value': count_all}
        footline.append(footitem)
        self.footlines.append(footline)

        return self.template()
    def __call__(self):
        bc = getToolByName(self.context, 'bika_catalog')
        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        headings['header'] = _("Analysis requests not invoiced")
        headings['subheader'] = _(
            "Published Analysis Requests which have not been invoiced")

        count_all = 0

        query = {'portal_type': 'AnalysisRequest',
                 'getInvoiced': False,
                 'review_state': 'published',
                 'sort_order': 'reverse'}

        date_query = formatDateQuery(self.context, 'c_DatePublished')
        if date_query:
            query['getDatePublished'] = date_query
            pubished = formatDateParms(self.context, 'c_DatePublished')
        else:
            pubished = 'Undefined'
        parms.append(
            {'title': _('Published'),
             'value': pubished,
             'type': 'text'})

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



        # and now lets do the actual report lines
        formats = {'columns': 6,
                   'col_heads': [_('Client'), \
                                 _('Request'), \
                                 _('Sample type'), \
                                 _('Sample point'), \
                                 _('Published'), \
                                 _('Amount'), \
                       ],
                   'class': '',
        }

        datalines = []
        clients = {}
        sampletypes = {}
        samplepoints = {}
        categories = {}
        services = {}

        for ar_proxy in bc(query):
            ar = ar_proxy.getObject()

            dataline = []

            dataitem = {'value': ar.aq_parent.Title()}
            dataline.append(dataitem)

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

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

            dataitem = {'value': ar.getSamplePointTitle()}
            dataline.append(dataitem)

            dataitem = {'value': self.ulocalized_time(ar.getDatePublished())}
            dataline.append(dataitem)

            dataitem = {'value': ar.getTotalPrice()}
            dataline.append(dataitem)

            datalines.append(dataline)

            count_all += 1

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

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

        return {'report_title': t(headings['header']),
                'report_data': self.template()}
    def __call__(self):
        # get all the data into datalines

        sc = getToolByName(self.context, 'bika_setup_catalog')
        bc = getToolByName(self.context, 'bika_analysis_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.report_content = {}
        parms = []
        headings = {}
        headings['header'] = _("Analyses per analysis service")
        headings['subheader'] = _(
            "Number of analyses requested per analysis service")

        query = {'portal_type': 'Analysis'}
        client_title = None
        if 'ClientUID' in self.request.form:
            client_uid = self.request.form['ClientUID']
            query['getClientUID'] = client_uid
            client = rc.lookupObject(client_uid)
            client_title = client.Title()
        else:
            client = logged_in_client(self.context)
            if client:
                client_title = client.Title()
                query['getClientUID'] = client.UID()
        if client_title:
            parms.append({
                'title': _('Client'),
                'value': client_title,
                'type': 'text'
            })

        date_query = formatDateQuery(self.context, 'Requested')
        if date_query:
            query['created'] = date_query
            requested = formatDateParms(self.context, 'Requested')
            parms.append({
                'title': _('Requested'),
                'value': requested,
                'type': 'text'
            })

        date_query = formatDateQuery(self.context, 'Published')
        if date_query:
            query['getDatePublished'] = date_query
            published = formatDateParms(self.context, 'Published')
            parms.append({
                'title': _('Published'),
                'value': published,
                'type': 'text'
            })

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

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

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

        # and now lets do the actual report lines
        formats = {
            'columns': 2,
            'col_heads': [_('Analysis service'),
                          _('Number of analyses')],
            'class': '',
        }

        datalines = []
        count_all = 0
        for cat in sc(portal_type="AnalysisCategory",
                      sort_on='sortable_title'):
            dataline = [
                {
                    'value': cat.Title,
                    'class': 'category_heading',
                    'colspan': 2
                },
            ]
            datalines.append(dataline)
            for service in sc(portal_type="AnalysisService",
                              getCategoryUID=cat.UID,
                              sort_on='sortable_title'):
                query['getServiceUID'] = service.UID
                analyses = bc(query)
                count_analyses = len(analyses)

                dataline = []
                dataitem = {'value': service.Title}
                dataline.append(dataitem)
                dataitem = {'value': count_analyses}

                dataline.append(dataitem)

                datalines.append(dataline)

                count_all += count_analyses

        # footer data
        footlines = []
        footline = []
        footitem = {'value': _('Total'), 'class': 'total_label'}
        footline.append(footitem)
        footitem = {'value': count_all}
        footline.append(footitem)
        footlines.append(footline)

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

        title = t(headings['header'])

        if self.request.get('output_format', '') == 'CSV':
            import csv
            import StringIO
            import datetime

            fieldnames = [
                'Analysis Service',
                'Analyses',
            ]
            output = StringIO.StringIO()
            dw = csv.DictWriter(output,
                                extrasaction='ignore',
                                fieldnames=fieldnames)
            dw.writerow(dict((fn, fn) for fn in fieldnames))
            for row in datalines:
                if len(row) == 1:
                    # category heading thingy
                    continue
                dw.writerow({
                    'Analysis Service': row[0]['value'],
                    'Analyses': row[1]['value'],
                })
            report_data = output.getvalue()
            output.close()
            date = datetime.datetime.now().strftime("%Y%m%d%H%M")
            setheader = self.request.RESPONSE.setHeader
            setheader('Content-Type', 'text/csv')
            setheader(
                "Content-Disposition",
                "attachment;filename=\"analysesperservice_%s.csv\"" % date)
            self.request.RESPONSE.write(report_data)
        else:
            return {'report_title': title, 'report_data': self.template()}
Exemplo n.º 38
0
    def __call__(self):
        # get all the data into datalines
        
        sc = getToolByName(self.context, 'bika_setup_catalog')
        bc = getToolByName(self.context, 'bika_analysis_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        headings['header'] = _("Analysis turnaround times")
        headings['subheader'] = _("The turnaround time of analyses")

        count_all = 0
        query = {'portal_type': 'Analysis'}
        if self.request.form.has_key('getClientUID'):
            client_uid = self.request.form['getClientUID']
            query['getClientUID'] = client_uid
            client = rc.lookupObject(client_uid)
            client_title = client.Title()
        else:
            client = logged_in_client(self.context)
            if client:
                client_title = client.Title()
                query['getClientUID'] = client.UID()
            else:
                client_title = 'Undefined'
        parms.append(
            { 'title': _('Client'),
             'value': client_title,
             'type': 'text'})

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

        query['review_state'] = 'published'

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


        # query all the analyses and increment the counts

        count_early = 0
        mins_early = 0
        count_late = 0
        mins_late = 0
        count_undefined = 0
        services = {}

        analyses = bc(query)
        for a in analyses:
            analysis = a.getObject()
            service_uid = analysis.getServiceUID()
            if not services.has_key(service_uid):
                services[service_uid] = {'count_early': 0,
                                         'count_late': 0,
                                         'mins_early': 0,
                                         'mins_late': 0,
                                         'count_undefined': 0,
                                        }
            earliness = analysis.getEarliness()
            if earliness < 0:
                count_late = services[service_uid]['count_late']
                mins_late = services[service_uid]['mins_late']
                count_late += 1
                mins_late -= earliness
                services[service_uid]['count_late'] = count_late
                services[service_uid]['mins_late'] = mins_late
            if earliness > 0:
                count_early = services[service_uid]['count_early']
                mins_early = services[service_uid]['mins_early']
                count_early += 1
                mins_early += earliness
                services[service_uid]['count_early'] = count_early
                services[service_uid]['mins_early'] = mins_early
            if earliness == 0:
                count_undefined = services[service_uid]['count_undefined']
                count_undefined += 1
                services[service_uid]['count_undefined'] = count_undefined

        # calculate averages
        for service_uid in services.keys():
            count_early = services[service_uid]['count_early']
            mins_early = services[service_uid]['mins_early']
            if count_early == 0:
                services[service_uid]['ave_early'] = ''
            else:
                avemins = (mins_early) / count_early
                services[service_uid]['ave_early'] = formatDuration(self.context, avemins)
            count_late = services[service_uid]['count_late']
            mins_late = services[service_uid]['mins_late']
            if count_late == 0:
                services[service_uid]['ave_late'] = ''
            else:
                avemins = mins_late / count_late
                services[service_uid]['ave_late'] = formatDuration(self.context, avemins)

        # and now lets do the actual report lines
        formats = {'columns': 7,
                   'col_heads': [ _('Analysis'), \
                                  _('Count'), \
                                  _('Undefined'), \
                                  _('Late'), \
                                  _('Average late'), \
                                  _('Early'), \
                                  _('Average early'), \
                                  ],
                   'class': '',
                  }


        total_count_early = 0
        total_count_late = 0
        total_mins_early = 0
        total_mins_late = 0
        total_count_undefined = 0
        datalines = []

        for cat in sc(portal_type='AnalysisCategory',
                        sort_on='sortable_title'):
            catline = [{'value': cat.Title, 
                        'class': 'category',
                        'colspan': 7},]
            first_time = True
            cat_count_early = 0
            cat_count_late = 0
            cat_count_undefined = 0
            cat_mins_early = 0
            cat_mins_late = 0
            for service in sc(portal_type="AnalysisService",
                            getCategoryUID = cat.UID,
                            sort_on='sortable_title'):

                dataline = [{'value': service.Title,
                             'class': 'testgreen'},]
                if not services.has_key(service.UID):
                    continue

                if first_time:
                    datalines.append(catline)
                    first_time = False

                # analyses found
                cat_count_early += services[service.UID]['count_early']
                cat_count_late += services[service.UID]['count_late']
                cat_count_undefined += services[service.UID]['count_undefined']
                cat_mins_early += services[service.UID]['mins_early']
                cat_mins_late += services[service.UID]['mins_late']

                count = services[service.UID]['count_early'] + \
                        services[service.UID]['count_late'] + \
                        services[service.UID]['count_undefined'] 

                dataline.append({'value': count,
                                 'class' : 'number'})
                dataline.append({'value': services[service.UID]['count_undefined'],
                                 'class' : 'number'})
                dataline.append({'value': services[service.UID]['count_late'],
                                 'class' : 'number'})
                dataline.append({'value': services[service.UID]['ave_late'],
                                 'class' : 'number'})
                dataline.append({'value': services[service.UID]['count_early'],
                                 'class' : 'number'})
                dataline.append({'value': services[service.UID]['ave_early'],
                                 'class' : 'number'})

                datalines.append(dataline)



            # category totals
            dataline = [{'value': '%s - total' %(cat.Title),
                        'class': 'subtotal_label'}, ]

            dataline.append({'value' : cat_count_early + \
                                       cat_count_late + \
                                       cat_count_undefined,
                             'class' : 'subtotal_number'})

            dataline.append({'value' : cat_count_undefined,
                             'class' : 'subtotal_number'})

            dataline.append({'value' : cat_count_late,
                             'class' : 'subtotal_number'})

            if cat_count_late:
                dataitem = {'value' : cat_mins_late / cat_count_late,
                            'class' : 'subtotal_number'}
            else:
                dataitem = {'value' : 0,
                            'class' : 'subtotal_number'}

            dataline.append(dataitem)

            dataline.append({'value' : cat_count_early,
                             'class' : 'subtotal_number'})

            if cat_count_early:
                dataitem = {'value' : cat_mins_early / cat_count_early,
                             'class' : 'subtotal_number'}
            else:
                dataitem = {'value' : 0,
                            'class' : 'subtotal_number'}

            dataline.append(dataitem)

            total_count_early += cat_count_early
            total_count_late += cat_count_late
            total_count_undefined += cat_count_undefined
            total_mins_early += cat_mins_early
            total_mins_late += cat_mins_late

        # footer data
        footlines = []
        footline = []
        footline = [{'value': _('Total'),
                     'class': 'total'}, ]

        footline.append({'value' : total_count_early + \
                                   total_count_late + \
                                   total_count_undefined,
                         'class' : 'total number'})

        footline.append({'value' : total_count_undefined,
                         'class' : 'total number'})

        footline.append({'value' : total_count_late,
                         'class' : 'total number'})

        if total_count_late:
            ave_mins = total_mins_late / total_count_late
            footline.append({'value' : formatDuration(self.context, ave_mins),
                             'class' : 'total number'})
        else:
            footline.append({'value' : ''})

        footline.append({'value' : total_count_early,
                         'class' : 'total number'})


        if total_count_early:
            ave_mins = total_mins_early / total_count_early
            footline.append({'value' : formatDuration(self.context, ave_mins),
                             'class' : 'total number'})
        else:
            footline.append({'value' : '',
                             'class' : 'total number'})

        
        footlines.append(footline)

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


        return self.template()
Exemplo n.º 39
0
    def __call__(self):
        # get all the data into datalines

        sc = getToolByName(self.context, 'bika_setup_catalog')
        bc = getToolByName(self.context, 'bika_analysis_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.report_content = {}
        parms = []
        headings = {}
        headings['header'] = _("Analysis turnaround times")
        headings['subheader'] = _("The turnaround time of analyses")

        query = {'portal_type': 'Analysis'}
        client_title = None
        if 'ClientUID' in self.request.form:
            client_uid = self.request.form['ClientUID']
            query['getClientUID'] = client_uid
            client = rc.lookupObject(client_uid)
            client_title = client.Title()
        else:
            client = logged_in_client(self.context)
            if client:
                client_title = client.Title()
                query['getClientUID'] = client.UID()
        if client_title:
            parms.append(
                {'title': _('Client'),
                 'value': client_title,
                 'type': 'text'})

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

        query['review_state'] = 'published'

        workflow = getToolByName(self.context, 'portal_workflow')
        if 'bika_worksheetanalysis_workflow' in self.request.form:
            query['worksheetanalysis_review_state'] = self.request.form[
                'bika_worksheetanalysis_workflow']
            ws_review_state = workflow.getTitleForStateOnType(
                self.request.form['bika_worksheetanalysis_workflow'], 'Analysis')
            parms.append(
                {'title': _('Assigned to worksheet'), 'value': ws_review_state,
                 'type': 'text'})

        # query all the analyses and increment the counts
        count_early = 0
        mins_early = 0
        count_late = 0
        mins_late = 0
        count_undefined = 0
        services = {}

        analyses = bc(query)
        for a in analyses:
            analysis = a.getObject()
            service_uid = analysis.getServiceUID()
            if service_uid not in services:
                services[service_uid] = {'count_early': 0,
                                         'count_late': 0,
                                         'mins_early': 0,
                                         'mins_late': 0,
                                         'count_undefined': 0,
                }
            earliness = analysis.getEarliness()
            if earliness < 0:
                count_late = services[service_uid]['count_late']
                mins_late = services[service_uid]['mins_late']
                count_late += 1
                mins_late -= earliness
                services[service_uid]['count_late'] = count_late
                services[service_uid]['mins_late'] = mins_late
            if earliness > 0:
                count_early = services[service_uid]['count_early']
                mins_early = services[service_uid]['mins_early']
                count_early += 1
                mins_early += earliness
                services[service_uid]['count_early'] = count_early
                services[service_uid]['mins_early'] = mins_early
            if earliness == 0:
                count_undefined = services[service_uid]['count_undefined']
                count_undefined += 1
                services[service_uid]['count_undefined'] = count_undefined

        # calculate averages
        for service_uid in services.keys():
            count_early = services[service_uid]['count_early']
            mins_early = services[service_uid]['mins_early']
            if count_early == 0:
                services[service_uid]['ave_early'] = ''
            else:
                avemins = (mins_early) / count_early
                services[service_uid]['ave_early'] = formatDuration(self.context,
                                                                    avemins)
            count_late = services[service_uid]['count_late']
            mins_late = services[service_uid]['mins_late']
            if count_late == 0:
                services[service_uid]['ave_late'] = ''
            else:
                avemins = mins_late / count_late
                services[service_uid]['ave_late'] = formatDuration(self.context,
                                                                   avemins)

        # and now lets do the actual report lines
        formats = {'columns': 7,
                   'col_heads': [_('Analysis'),
                                 _('Count'),
                                 _('Undefined'),
                                 _('Late'),
                                 _('Average late'),
                                 _('Early'),
                                 _('Average early'),
                   ],
                   'class': '',
        }

        total_count_early = 0
        total_count_late = 0
        total_mins_early = 0
        total_mins_late = 0
        total_count_undefined = 0
        datalines = []

        for cat in sc(portal_type='AnalysisCategory',
                      sort_on='sortable_title'):
            catline = [{'value': cat.Title,
                        'class': 'category_heading',
                        'colspan': 7}, ]
            first_time = True
            cat_count_early = 0
            cat_count_late = 0
            cat_count_undefined = 0
            cat_mins_early = 0
            cat_mins_late = 0
            for service in sc(portal_type="AnalysisService",
                              getCategoryUID=cat.UID,
                              sort_on='sortable_title'):

                dataline = [{'value': service.Title,
                             'class': 'testgreen'}, ]
                if service.UID not in services:
                    continue

                if first_time:
                    datalines.append(catline)
                    first_time = False

                # analyses found
                cat_count_early += services[service.UID]['count_early']
                cat_count_late += services[service.UID]['count_late']
                cat_count_undefined += services[service.UID]['count_undefined']
                cat_mins_early += services[service.UID]['mins_early']
                cat_mins_late += services[service.UID]['mins_late']

                count = services[service.UID]['count_early'] + \
                        services[service.UID]['count_late'] + \
                        services[service.UID]['count_undefined']

                dataline.append({'value': count,
                                 'class': 'number'})
                dataline.append(
                    {'value': services[service.UID]['count_undefined'],
                     'class': 'number'})
                dataline.append({'value': services[service.UID]['count_late'],
                                 'class': 'number'})
                dataline.append({'value': services[service.UID]['ave_late'],
                                 'class': 'number'})
                dataline.append({'value': services[service.UID]['count_early'],
                                 'class': 'number'})
                dataline.append({'value': services[service.UID]['ave_early'],
                                 'class': 'number'})

                datalines.append(dataline)

            # category totals
            dataline = [{'value': '%s - total' % (cat.Title),
                         'class': 'subtotal_label'}, ]

            dataline.append({'value': cat_count_early +
                                      cat_count_late +
                                      cat_count_undefined,
                             'class': 'subtotal_number'})

            dataline.append({'value': cat_count_undefined,
                             'class': 'subtotal_number'})

            dataline.append({'value': cat_count_late,
                             'class': 'subtotal_number'})

            if cat_count_late:
                dataitem = {'value': cat_mins_late / cat_count_late,
                            'class': 'subtotal_number'}
            else:
                dataitem = {'value': 0,
                            'class': 'subtotal_number'}

            dataline.append(dataitem)

            dataline.append({'value': cat_count_early,
                             'class': 'subtotal_number'})

            if cat_count_early:
                dataitem = {'value': cat_mins_early / cat_count_early,
                            'class': 'subtotal_number'}
            else:
                dataitem = {'value': 0,
                            'class': 'subtotal_number'}

            dataline.append(dataitem)

            total_count_early += cat_count_early
            total_count_late += cat_count_late
            total_count_undefined += cat_count_undefined
            total_mins_early += cat_mins_early
            total_mins_late += cat_mins_late

        # footer data
        footlines = []
        footline = []
        footline = [{'value': _('Total'),
                     'class': 'total'}, ]

        footline.append({'value': total_count_early +
                                  total_count_late +
                                  total_count_undefined,
                         'class': 'total number'})

        footline.append({'value': total_count_undefined,
                         'class': 'total number'})

        footline.append({'value': total_count_late,
                         'class': 'total number'})

        if total_count_late:
            ave_mins = total_mins_late / total_count_late
            footline.append({'value': formatDuration(self.context, ave_mins),
                             'class': 'total number'})
        else:
            footline.append({'value': ''})

        footline.append({'value': total_count_early,
                         'class': 'total number'})

        if total_count_early:
            ave_mins = total_mins_early / total_count_early
            footline.append({'value': formatDuration(self.context, ave_mins),
                             'class': 'total number'})
        else:
            footline.append({'value': '',
                             'class': 'total number'})

        footlines.append(footline)

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

        if self.request.get('output_format', '') == 'CSV':
            import csv
            import StringIO
            import datetime

            fieldnames = [
                'Analysis',
                'Count',
                'Undefined',
                'Late',
                'Average late',
                'Early',
                'Average early',
            ]
            output = StringIO.StringIO()
            dw = csv.DictWriter(output, extrasaction='ignore',
                                fieldnames=fieldnames)
            dw.writerow(dict((fn, fn) for fn in fieldnames))
            for row in datalines:
                if len(row) == 1:
                    # category heading thingy
                    continue
                dw.writerow({
                    'Analysis': row[0]['value'],
                    'Count': row[1]['value'],
                    'Undefined': row[2]['value'],
                    'Late': row[3]['value'],
                    'Average late': row[4]['value'],
                    'Early': row[5]['value'],
                    'Average early': row[6]['value'],
                })
            report_data = output.getvalue()
            output.close()
            date = datetime.datetime.now().strftime("%Y%m%d%H%M")
            setheader = self.request.RESPONSE.setHeader
            setheader('Content-Type', 'text/csv')
            setheader("Content-Disposition",
                      "attachment;filename=\"analysestats_%s.csv\"" % date)
            self.request.RESPONSE.write(report_data)
        else:
            return {'report_title': t(headings['header']),
                    'report_data': self.template()}
Exemplo n.º 40
0
    def __call__(self):
        # get all the data into datalines

        sc = getToolByName(self.context, 'bika_setup_catalog')
        bc = getToolByName(self.context, 'bika_analysis_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        headings['header'] = _("Analysis turnaround times")
        headings['subheader'] = _("The turnaround time of analyses")

        count_all = 0
        query = {'portal_type': 'Analysis'}
        if self.request.form.has_key('ClientUID'):
            client_uid = self.request.form['ClientUID']
            query['getClientUID'] = client_uid
            client = rc.lookupObject(client_uid)
            client_title = client.Title()
        else:
            client = logged_in_client(self.context)
            if client:
                client_title = client.Title()
                query['getClientUID'] = client.UID()
            else:
                client_title = 'Undefined'
        parms.append({
            'title': _('Client'),
            'value': client_title,
            'type': 'text'
        })

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

        query['review_state'] = 'published'

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

        # query all the analyses and increment the counts

        count_early = 0
        mins_early = 0
        count_late = 0
        mins_late = 0
        count_undefined = 0
        services = {}

        analyses = bc(query)
        for a in analyses:
            analysis = a.getObject()
            service_uid = analysis.getServiceUID()
            if not services.has_key(service_uid):
                services[service_uid] = {
                    'count_early': 0,
                    'count_late': 0,
                    'mins_early': 0,
                    'mins_late': 0,
                    'count_undefined': 0,
                }
            earliness = analysis.getEarliness()
            if earliness < 0:
                count_late = services[service_uid]['count_late']
                mins_late = services[service_uid]['mins_late']
                count_late += 1
                mins_late -= earliness
                services[service_uid]['count_late'] = count_late
                services[service_uid]['mins_late'] = mins_late
            if earliness > 0:
                count_early = services[service_uid]['count_early']
                mins_early = services[service_uid]['mins_early']
                count_early += 1
                mins_early += earliness
                services[service_uid]['count_early'] = count_early
                services[service_uid]['mins_early'] = mins_early
            if earliness == 0:
                count_undefined = services[service_uid]['count_undefined']
                count_undefined += 1
                services[service_uid]['count_undefined'] = count_undefined

        # calculate averages
        for service_uid in services.keys():
            count_early = services[service_uid]['count_early']
            mins_early = services[service_uid]['mins_early']
            if count_early == 0:
                services[service_uid]['ave_early'] = ''
            else:
                avemins = (mins_early) / count_early
                services[service_uid]['ave_early'] = formatDuration(
                    self.context, avemins)
            count_late = services[service_uid]['count_late']
            mins_late = services[service_uid]['mins_late']
            if count_late == 0:
                services[service_uid]['ave_late'] = ''
            else:
                avemins = mins_late / count_late
                services[service_uid]['ave_late'] = formatDuration(
                    self.context, avemins)

        # and now lets do the actual report lines
        formats = {'columns': 7,
                   'col_heads': [ _('Analysis'), \
                                  _('Count'), \
                                  _('Undefined'), \
                                  _('Late'), \
                                  _('Average late'), \
                                  _('Early'), \
                                  _('Average early'), \
                                  ],
                   'class': '',
                  }

        total_count_early = 0
        total_count_late = 0
        total_mins_early = 0
        total_mins_late = 0
        total_count_undefined = 0
        datalines = []

        for cat in sc(portal_type='AnalysisCategory',
                      sort_on='sortable_title'):
            catline = [
                {
                    'value': cat.Title,
                    'class': 'category_heading',
                    'colspan': 7
                },
            ]
            first_time = True
            cat_count_early = 0
            cat_count_late = 0
            cat_count_undefined = 0
            cat_mins_early = 0
            cat_mins_late = 0
            for service in sc(portal_type="AnalysisService",
                              getCategoryUID=cat.UID,
                              sort_on='sortable_title'):

                dataline = [
                    {
                        'value': service.Title,
                        'class': 'testgreen'
                    },
                ]
                if not services.has_key(service.UID):
                    continue

                if first_time:
                    datalines.append(catline)
                    first_time = False

                # analyses found
                cat_count_early += services[service.UID]['count_early']
                cat_count_late += services[service.UID]['count_late']
                cat_count_undefined += services[service.UID]['count_undefined']
                cat_mins_early += services[service.UID]['mins_early']
                cat_mins_late += services[service.UID]['mins_late']

                count = services[service.UID]['count_early'] + \
                        services[service.UID]['count_late'] + \
                        services[service.UID]['count_undefined']

                dataline.append({'value': count, 'class': 'number'})
                dataline.append({
                    'value':
                    services[service.UID]['count_undefined'],
                    'class':
                    'number'
                })
                dataline.append({
                    'value': services[service.UID]['count_late'],
                    'class': 'number'
                })
                dataline.append({
                    'value': services[service.UID]['ave_late'],
                    'class': 'number'
                })
                dataline.append({
                    'value': services[service.UID]['count_early'],
                    'class': 'number'
                })
                dataline.append({
                    'value': services[service.UID]['ave_early'],
                    'class': 'number'
                })

                datalines.append(dataline)

            # category totals
            dataline = [
                {
                    'value': '%s - total' % (cat.Title),
                    'class': 'subtotal_label'
                },
            ]

            dataline.append({'value' : cat_count_early + \
                                       cat_count_late + \
                                       cat_count_undefined,
                             'class' : 'subtotal_number'})

            dataline.append({
                'value': cat_count_undefined,
                'class': 'subtotal_number'
            })

            dataline.append({
                'value': cat_count_late,
                'class': 'subtotal_number'
            })

            if cat_count_late:
                dataitem = {
                    'value': cat_mins_late / cat_count_late,
                    'class': 'subtotal_number'
                }
            else:
                dataitem = {'value': 0, 'class': 'subtotal_number'}

            dataline.append(dataitem)

            dataline.append({
                'value': cat_count_early,
                'class': 'subtotal_number'
            })

            if cat_count_early:
                dataitem = {
                    'value': cat_mins_early / cat_count_early,
                    'class': 'subtotal_number'
                }
            else:
                dataitem = {'value': 0, 'class': 'subtotal_number'}

            dataline.append(dataitem)

            total_count_early += cat_count_early
            total_count_late += cat_count_late
            total_count_undefined += cat_count_undefined
            total_mins_early += cat_mins_early
            total_mins_late += cat_mins_late

        # footer data
        footlines = []
        footline = []
        footline = [
            {
                'value': _('Total'),
                'class': 'total'
            },
        ]

        footline.append({'value' : total_count_early + \
                                   total_count_late + \
                                   total_count_undefined,
                         'class' : 'total number'})

        footline.append({
            'value': total_count_undefined,
            'class': 'total number'
        })

        footline.append({'value': total_count_late, 'class': 'total number'})

        if total_count_late:
            ave_mins = total_mins_late / total_count_late
            footline.append({
                'value': formatDuration(self.context, ave_mins),
                'class': 'total number'
            })
        else:
            footline.append({'value': ''})

        footline.append({'value': total_count_early, 'class': 'total number'})

        if total_count_early:
            ave_mins = total_mins_early / total_count_early
            footline.append({
                'value': formatDuration(self.context, ave_mins),
                'class': 'total number'
            })
        else:
            footline.append({'value': '', 'class': 'total number'})

        footlines.append(footline)

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

        title = self.context.translate(headings['header'])

        return {'report_title': title, 'report_data': self.template()}