Beispiel #1
0
    def folderitems(self):
        # Obtain the member and member's role.
        pm = getToolByName(self.context, "portal_membership")
        member = pm.getAuthenticatedMember()
        roles = member.getRoles()
        # Limit results to those patients that "belong" to the member's client
        if "Client" in roles:
            # It obtains the referrer institution which the current AuthenticatedMember belong.
            client = logged_in_client(self.context, member)
            self.contentFilter["getPrimaryReferrerUID"] = client.UID()
            # hide PrimaryReferrer column
            new_states = []
            for x in self.review_states:
                if "getPrimaryReferrer" in x["columns"]:
                    x["columns"].remove("getPrimaryReferrer")
                new_states.append(x)
            self.review_states = new_states

        items = BikaListingView.folderitems(self)
        for x in range(len(items)):
            if "obj" not in items[x]:
                continue
            obj = items[x]["obj"]
            items[x]["getPatientID"] = obj.getPatientID()
            items[x]["getBirthDate"] = self.ulocalized_time(obj.getBirthDate())
            items[x]["replace"]["getPatientID"] = "<a href='%s/analysisrequests'>%s</a>" % (
                items[x]["url"],
                items[x]["getPatientID"],
            )
            items[x]["replace"]["getClientPatientID"] = "<a href='%s'>%s</a>" % (
                items[x]["url"],
                items[x]["getClientPatientID"],
            )
            items[x]["replace"]["Title"] = "<a href='%s/analysisrequests'>%s</a>" % (items[x]["url"], items[x]["Title"])
            if "Client" not in roles:
                # All the patients don't belong to the same client.
                pr = obj.getPrimaryReferrer()
                if pr:
                    items[x]["getPrimaryReferrer"] = pr.Title()
                    items[x]["replace"]["getPrimaryReferrer"] = "<a href='%s/analysisrequests'>%s</a>" % (
                        pr.absolute_url(),
                        pr.Title(),
                    )
                else:
                    items[x]["getPrimaryReferrer"] = ""

        return items
Beispiel #2
0
    def __call__(self):
        this_client = logged_in_client(self.context)
        if this_client:
            self.contentFilter = {
                'portal_type': 'Report',
                'getClientUID': this_client.UID(),
                'sort_order': 'reverse'}
            self.columns = {
                'Title': {'title': _('Title')},
                'FileSize': {'title': _('Size')},
                'Created': {'title': _('Created')},
                'By': {'title': _('By')}, }
            self.review_states = [
                {'id': 'default',
                 'title': 'All',
                 'contentFilter': {},
                 'columns': ['Title',
                             'FileSize',
                             'Created',
                             'By']},
            ]
        else:
            self.contentFilter = {
                'portal_type': 'Report',
                'sort_order': 'reverse'}

            self.columns = {
                'Client': {'title': _('Client')},
                'Title': {'title': _('Report Type')},
                'FileSize': {'title': _('Size')},
                'Created': {'title': _('Created')},
                'By': {'title': _('By')},
            }
            self.review_states = [
                {'id': 'default',
                 'title': 'All',
                 'contentFilter': {},
                 'columns': ['Client',
                             'Title',
                             'FileSize',
                             'Created',
                             'By']},
            ]

        return super(ReportHistoryView, self).__call__()
Beispiel #3
0
    def __call__(self):
        self.columns = {
            'Title': {
                'title': _('Title'),
                'attr': 'Title',
                'index': 'title', },
            'file_size': {
                'title': _("Size"),
                'attr': 'getFileSize',
                'sortable': False, },
            'created': {
                'title': _("Created"),
                'attr': 'created',
                'index': 'created', },
            'creator': {
                'title': _("By"),
                'attr': 'getCreatorFullName',
                'index': 'Creator', }, }
        self.review_states = [
            {'id': 'default',
             'title': 'All',
             'contentFilter': {},
             'columns': ['Title',
                         'file_size',
                         'created',
                         'creator']},
        ]

        self.contentFilter = {
            'portal_type': 'Report',
            'sort_order': 'reverse'}

        this_client = logged_in_client(self.context)
        if this_client:
            self.contentFilter['getClientUID'] = this_client.UID()
        else:
            self.columns['client'] = {
                'title': _('Client'),
                'attr': 'getClientTitle',
                'replace_url': 'getClientURL', }

        return super(ReportHistoryView, self).__call__()
Beispiel #4
0
    def __call__(self):
        lab = self.context.bika_setup.laboratory
        self.lab_title = lab.getName()
        self.lab_address = lab.getPrintAddress()
        self.lab_email = lab.getEmailAddress()
        self.lab_url = lab.getLabURL()
        self.date = DateTime()
        client = logged_in_client(self.context)
        if client:
            self.client_title = client.Title()
            self.client_address = client.getPrintAddress()
        else:
            self.client_title = None
            self.client_address = None

        if client:
            clientuid = client.UID()
        else:
            clientuid = None
        username = self.context.portal_membership.getAuthenticatedMember().getUserName()
        self.querier = self.user_fullname(username)
        self.querier_email = self.user_email(username)
        query_id =  self.request.form['query_id']
        querytype = ''
        if query_id == 'analysisrequests':
            querytype = 'Analysis requests'
            self.queryout = QueryAnalysisRequests(self.context, self.request)()
        elif query_id == 'orders':
            querytype = 'Orders'
            self.queryout = QueryOrders(self.context, self.request)()
        elif query_id == 'invoices':
            querytype = 'Invoices'
            self.queryout = QueryInvoices(self.context, self.request)()
        else:
            self.queryout = "no query to out"


        return self.template()
Beispiel #5
0
    def __call__(self):
        this_client = logged_in_client(self.context)
        if this_client:
            self.contentFilter = {"portal_type": "Report", "getClientUID": this_client.UID(), "sort_order": "reverse"}
            self.columns = {
                "ReportType": {"title": _("Report Type")},
                "FileSize": {"title": _("Size")},
                "Created": {"title": _("Created")},
                "By": {"title": _("By")},
            }
            self.review_states = [
                {
                    "id": "default",
                    "title": "All",
                    "contentFilter": {},
                    "columns": ["ReportType", "FileSize", "Created", "By"],
                }
            ]
        else:
            self.contentFilter = {"portal_type": "Report", "sort_order": "reverse"}

            self.columns = {
                "Client": {"title": _("Client")},
                "ReportType": {"title": _("Report Type")},
                "FileSize": {"title": _("Size")},
                "Created": {"title": _("Created")},
                "By": {"title": _("By")},
            }
            self.review_states = [
                {
                    "id": "default",
                    "title": "All",
                    "contentFilter": {},
                    "columns": ["Client", "ReportType", "FileSize", "Created", "By"],
                }
            ]

        return super(ReportHistoryView, self).__call__()
Beispiel #6
0
    def __call__(self):
        lab = self.context.bika_setup.laboratory
        self.lab_title = lab.getName()
        self.lab_address = lab.getPrintAddress()
        self.lab_email = lab.getEmailAddress()
        self.lab_url = lab.getLabURL()
        self.date = DateTime()
        client = logged_in_client(self.context)
        if client:
            self.client_title = client.Title()
            self.client_address = client.getPrintAddress()
        else:
            self.client_title = None
            self.client_address = None

        if client:
            clientuid = client.UID()
        else:
            clientuid = None
        username = self.context.portal_membership.getAuthenticatedMember().getUserName()
        self.querier = pretty_user_name_or_id(self.context, username)
        self.querier_email = pretty_user_email(self.context, username)
        query_id = self.request.form["query_id"]
        querytype = ""
        if query_id == "analysisrequests":
            querytype = "Analysis requests"
            self.queryout = QueryAnalysisRequests(self.context, self.request)()
        elif query_id == "orders":
            querytype = "Orders"
            self.queryout = QueryOrders(self.context, self.request)()
        elif query_id == "invoices":
            querytype = "Invoices"
            self.queryout = QueryInvoices(self.context, self.request)()
        else:
            self.queryout = "no query to out"

        return self.template()
Beispiel #7
0
    def __call__(self):
        """Create and render selected report
        """

        # if there's an error, we return productivity.pt which requires these.
        self.selection_macros = SelectionMacrosView(self.context, self.request)

        report_id = self.request.get('report_id', '')
        if not report_id:
            message =  "No report specified in request"
            self.logger.error(message)
            self.context.plone_utils.addPortalMessage(message, 'error')
            return self.template()

        self.date = DateTime()
        username = self.context.portal_membership.getAuthenticatedMember().getUserName()
        self.reporter = self.user_fullname(username)
        self.reporter_email = self.user_email(username)

        # signature image
        self.reporter_signature = ""
        c = [x for x in self.bika_setup_catalog(portal_type='LabContact')
             if x.getObject().getUsername() == username]
        if c:
            sf = c[0].getObject().getSignature()
            if sf:
                self.reporter_signature = sf.absolute_url() + "/Signature"

        lab = self.context.bika_setup.laboratory
        self.laboratory = lab
        self.lab_title = lab.getName()
        self.lab_address = lab.getPrintAddress()
        self.lab_email = lab.getEmailAddress()
        self.lab_url = lab.getLabURL()

        client = logged_in_client(self.context)
        if client:
            clientuid = client.UID()
            self.client_title = client.Title()
            self.client_address = client.getPrintAddress()
        else:
            clientuid = None
            self.client_title = None
            self.client_address = None

        ## Render form output

        # the report can add file names to this list; they will be deleted
        # once the PDF has been generated.  temporary plot image files, etc.
        self.request['to_remove'] = []

        try:
            exec("from bika.lims.browser.reports.%s import Report" % report_id)
        except ImportError:
            message = "Report %s not found (shouldn't happen)" % report_id
            self.logger.error(message)
            self.context.plone_utils.addPortalMessage(message, 'error')
            return self.template()

        # Report must return dict with:
        # - report_title - title string for pdf/history listing
        # - report_data - rendered report
        output = Report(self.context, self.request)()

        if type(output) in (str, unicode, bytes):
            # remove temporary files
            for f in self.request['to_remove']:
                os.remove(f)
            return output

        ## The report output gets pulled through report_frame.pt
        self.reportout = output['report_data']
        framed_output = self.frame_template()

        # this is the good part
        pisa.showLogging()
        ramdisk = StringIO()
        pdf = pisa.CreatePDF(framed_output, ramdisk)
        result = ramdisk.getvalue()
        ramdisk.close()

        ## Create new report object
        reportid = self.aq_parent.generateUniqueId('Report')
        self.aq_parent.invokeFactory(id = reportid, type_name = "Report")
        report = self.aq_parent._getOb(reportid)
        report.edit(Client = clientuid)
        report.processForm()

        ## write pdf to report object
        report.edit(title = output['report_title'], ReportFile = result)
        report.reindexObject()

        fn = "%s - %s" % (self.date.strftime(self.date_format_short),
                          output['report_title'])

        # remove temporary files
        for f in self.request['to_remove']:
            os.remove(f)

        if not pdf.err:
            setheader = self.request.RESPONSE.setHeader
            setheader('Content-Type', 'application/pdf')
            setheader("Content-Disposition", "attachment;filename=\"%s\""%fn)
            self.request.RESPONSE.write(result)

        return
    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):
        # 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()}
Beispiel #10
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):
        # 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()
            }
Beispiel #12
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 get_logged_in_client(self):
     """Return the logged in client
     """
     return logged_in_client(self.context)
    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()
        }
Beispiel #15
0
    def __call__(self):
        this_client = logged_in_client(self.context)
        if this_client:
            self.contentFilter = {
                'portal_type': 'Report',
                'getClientUID': this_client.UID(),
                'sort_order': 'reverse'
            }
            self.columns = {
                'Title': {
                    'title': _('Title')
                },
                'FileSize': {
                    'title': _('Size')
                },
                'Created': {
                    'title': _('Created')
                },
                'By': {
                    'title': _('By')
                },
            }
            self.review_states = [
                {
                    'id': 'default',
                    'title': 'All',
                    'contentFilter': {},
                    'columns': ['Title', 'FileSize', 'Created', 'By']
                },
            ]
        else:
            self.contentFilter = {
                'portal_type': 'Report',
                'sort_order': 'reverse'
            }

            self.columns = {
                'Client': {
                    'title': _('Client')
                },
                'Title': {
                    'title': _('Report Type')
                },
                'FileSize': {
                    'title': _('Size')
                },
                'Created': {
                    'title': _('Created')
                },
                'By': {
                    'title': _('By')
                },
            }
            self.review_states = [
                {
                    'id': 'default',
                    'title': 'All',
                    'contentFilter': {},
                    'columns':
                    ['Client', 'Title', 'FileSize', 'Created', 'By']
                },
            ]

        return super(ReportHistoryView, self).__call__()
    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

        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
        
        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

        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()}
Beispiel #20
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 '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()}
Beispiel #22
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()
            }
    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()}
Beispiel #24
0
    def __call__(self):
        """Create and render selected report
        """

        # if there's an error, we return productivity.pt which requires these.
        self.selection_macros = SelectionMacrosView(self.context, self.request)
        self.additional_reports = []
        adapters = getAdapters((self.context, ), IProductivityReport)
        for name, adapter in adapters:
            report_dict = adapter(self.context, self.request)
            report_dict['id'] = name
            self.additional_reports.append(report_dict)

        report_id = self.request.get('report_id', '')
        if not report_id:
            message = _("No report specified in request")
            self.logger.error(message)
            self.context.plone_utils.addPortalMessage(message, 'error')
            return self.template()

        self.date = DateTime()
        username = self.context.portal_membership.getAuthenticatedMember(
        ).getUserName()
        self.reporter = self.user_fullname(username)
        self.reporter_email = self.user_email(username)

        # signature image
        self.reporter_signature = ""
        c = [
            x for x in self.bika_setup_catalog(portal_type='LabContact')
            if x.getObject().getUsername() == username
        ]
        if c:
            sf = c[0].getObject().getSignature()
            if sf:
                self.reporter_signature = sf.absolute_url() + "/Signature"

        lab = self.context.bika_setup.laboratory
        self.laboratory = lab
        self.lab_title = lab.getName()
        self.lab_address = lab.getPrintAddress()
        self.lab_email = lab.getEmailAddress()
        self.lab_url = lab.getLabURL()

        client = logged_in_client(self.context)
        if client:
            clientuid = client.UID()
            self.client_title = client.Title()
            self.client_address = client.getPrintAddress()
        else:
            clientuid = None
            self.client_title = None
            self.client_address = None

        # Render form output

        # the report can add file names to this list; they will be deleted
        # once the PDF has been generated.  temporary plot image files, etc.
        self.request['to_remove'] = []

        if "report_module" in self.request:
            module = self.request["report_module"]
        else:
            module = "bika.lims.browser.reports.%s" % report_id
        try:
            exec("from %s import Report" % module)
            # required during error redirect: the report must have a copy of
            # additional_reports, because it is used as a surrogate view.
            Report.additional_reports = self.additional_reports
        except ImportError:
            message = "Report %s.Report not found (shouldn't happen)" % module
            self.logger.error(message)
            self.context.plone_utils.addPortalMessage(message, 'error')
            return self.template()

        # Report must return dict with:
        # - report_title - title string for pdf/history listing
        # - report_data - rendered report
        output = Report(self.context, self.request)()

        # if CSV output is chosen, report returns None
        if not output:
            return

        if type(output) in (str, unicode, bytes):
            # remove temporary files
            for f in self.request['to_remove']:
                os.remove(f)
            return output

        # The report output gets pulled through report_frame.pt
        self.reportout = output['report_data']
        framed_output = self.frame_template()

        # this is the good part
        result = createPdf(framed_output)

        # remove temporary files
        for f in self.request['to_remove']:
            os.remove(f)

        if result:
            # Create new report object
            reportid = self.aq_parent.generateUniqueId('Report')
            report = _createObjectByType("Report", self.aq_parent, reportid)
            report.edit(Client=clientuid)
            report.processForm()

            # write pdf to report object
            report.edit(title=output['report_title'], ReportFile=result)
            report.reindexObject()

            fn = "%s - %s" % (self.date.strftime(
                self.date_format_short), _u(output['report_title']))

            setheader = self.request.RESPONSE.setHeader
            setheader('Content-Type', 'application/pdf')
            setheader("Content-Disposition",
                      "attachment;filename=\"%s\"" % _c(fn))
            self.request.RESPONSE.write(result)

        return
Beispiel #25
0
    def __call__(self):
        lab = self.context.bika_setup.laboratory
        self.lab_title = lab.getName()
        self.lab_address = lab.getPrintAddress()
        self.lab_email = lab.getEmailAddress()
        self.lab_url = lab.getLabURL()
        self.date = DateTime()
        client = logged_in_client(self.context)
        if client:
            self.client_title = client.Title()
            self.client_address = client.getPrintAddress()
        else:
            self.client_title = None
            self.client_address = None

        if client:
            clientuid = client.UID()
        else:
            clientuid = None
        username = self.context.portal_membership.getAuthenticatedMember().getUserName()
        self.reporter = pretty_user_name_or_id(self.context, username)
        self.reporter_email = pretty_user_email(self.context, username)
        report_id = self.request.form["report_id"]
        reporttype = ""
        if report_id == "analysesperservice":
            reporttype = "Analyses per service"
            self.reportout = AnalysesPerService(self.context, self.request)()
        elif report_id == "analysespersampletype":
            reporttype = "Analyses per sampletype"
            self.reportout = AnalysesPerSampleType(self.context, self.request)()
        elif report_id == "analysesperclient":
            reporttype = "Analyses per client"
            self.reportout = AnalysesPerClient(self.context, self.request)()
        elif report_id == "analysestats":
            reporttype = "Analyses TATs"
            self.reportout = AnalysesTats(self.context, self.request)()
        elif report_id == "analysestats_overtime":
            reporttype = "Analyses TATs over time"
            self.reportout = AnalysesTatsOverTime(self.context, self.request)()
        elif report_id == "analysesattachments":
            reporttype = "Analyses attachments"
            self.reportout = AnalysesAttachments(self.context, self.request)()
        elif report_id == "analysesoutofrange":
            reporttype = "Analyses out of range"
            self.reportout = AnalysesOutOfRange(self.context, self.request)()
        elif report_id == "analysesrepeated":
            reporttype = "Analyses repeated"
            self.reportout = AnalysesRepeated(self.context, self.request)()
        elif report_id == "arsnotinvoiced":
            reporttype = "ARs not invoiced"
            self.reportout = ARsNotInvoiced(self.context, self.request)()
        elif report_id == "resultspersamplepoint":
            reporttype = "Results per sample point"
            self.reportout = ResultsPerSamplePoint(self.context, self.request)()
        else:
            self.reportout = "no report to out"

        # this is the good part
        ramdisk = StringIO()
        pdf = pisa.CreatePDF(self.template(), ramdisk)
        result = ramdisk.getvalue()
        ramdisk.close()

        # write pdf to report object
        reportid = self.aq_parent.generateUniqueId("Report")
        self.aq_parent.invokeFactory(id=reportid, type_name="Report")
        report = self.aq_parent._getOb(reportid)
        report.edit(title=reporttype, ReportFile=result, ReportType=reporttype, Client=clientuid)
        report.processForm()
        report.reindexObject()

        if not pdf.err:
            setheader = self.request.RESPONSE.setHeader
            setheader("Content-Type", "application/pdf")
            self.request.RESPONSE.write(result)

        pisa.showLogging()

        return self.template()
Beispiel #26
0
    def __call__(self):
        """Create and render selected report
        """

        # if there's an error, we return productivity.pt which requires these.
        self.selection_macros = SelectionMacrosView(self.context, self.request)
        self.additional_reports = []
        adapters = getAdapters((self.context, ), IProductivityReport)
        for name, adapter in adapters:
            report_dict = adapter(self.context, self.request)
            report_dict['id'] = name
            self.additional_reports.append(report_dict)

        report_id = self.request.get('report_id', '')
        if not report_id:
            message = "No report specified in request"
            self.logger.error(message)
            self.context.plone_utils.addPortalMessage(message, 'error')
            return self.template()

        self.date = DateTime()
        username = self.context.portal_membership.getAuthenticatedMember().getUserName()
        self.reporter = self.user_fullname(username)
        self.reporter_email = self.user_email(username)

        # signature image
        self.reporter_signature = ""
        c = [x for x in self.bika_setup_catalog(portal_type='LabContact')
             if x.getObject().getUsername() == username]
        if c:
            sf = c[0].getObject().getSignature()
            if sf:
                self.reporter_signature = sf.absolute_url() + "/Signature"

        lab = self.context.bika_setup.laboratory
        self.laboratory = lab
        self.lab_title = lab.getName()
        self.lab_address = lab.getPrintAddress()
        self.lab_email = lab.getEmailAddress()
        self.lab_url = lab.getLabURL()

        client = logged_in_client(self.context)
        if client:
            clientuid = client.UID()
            self.client_title = client.Title()
            self.client_address = client.getPrintAddress()
        else:
            clientuid = None
            self.client_title = None
            self.client_address = None

        # Render form output

        # the report can add file names to this list; they will be deleted
        # once the PDF has been generated.  temporary plot image files, etc.
        self.request['to_remove'] = []

        if "report_module" in self.request:
            module = self.request["report_module"]
        else:
            module = "bika.lims.browser.reports.%s" % report_id
        try:
            exec("from %s import Report" % module)
            # required during error redirect: the report must have a copy of
            # additional_reports, because it is used as a surrogate view.
            Report.additional_reports = self.additional_reports
        except ImportError:
            message = "Report %s.Report not found (shouldn't happen)" % module
            self.logger.error(message)
            self.context.plone_utils.addPortalMessage(message, 'error')
            return self.template()

        # Report must return dict with:
        # - report_title - title string for pdf/history listing
        # - report_data - rendered report
        output = Report(self.context, self.request)()

        # if CSV output is chosen, report returns None
        if not output:
            return

        if type(output) in (str, unicode, bytes):
            # remove temporary files
            for f in self.request['to_remove']:
                os.remove(f)
            return output

        # The report output gets pulled through report_frame.pt
        self.reportout = output['report_data']
        framed_output = self.frame_template()

        # this is the good part
        result = createPdf(framed_output)

        # remove temporary files
        for f in self.request['to_remove']:
            os.remove(f)

        if result:
            # Create new report object
            reportid = self.aq_parent.generateUniqueId('Report')
            self.aq_parent.invokeFactory(id=reportid, type_name="Report")
            report = self.aq_parent._getOb(reportid)
            report.edit(Client=clientuid)
            report.processForm()

            # write pdf to report object
            report.edit(title=output['report_title'], ReportFile=result)
            report.reindexObject()

            fn = "%s - %s" % (self.date.strftime(self.date_format_short),
                              _u(output['report_title']))

            setheader = self.request.RESPONSE.setHeader
            setheader('Content-Type', 'application/pdf')
            setheader("Content-Disposition", "attachment;filename=\"%s\"" % _c(fn))
            self.request.RESPONSE.write(result)

        return
    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()}
    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()}
    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:
            # list of projects of this client
            query['getClientUID'] = [project.getObject().UID() for project in client.getObject().getProjects()]
            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 folderitems(self):
        self.categories = []

        analyses = self.context.getAnalyses(full_objects=True)
        self.analyses = dict([(a.getServiceUID(), a) for a in analyses])
        self.selected = self.analyses.keys()
        self.show_categories = \
            self.context.bika_setup.getCategoriseAnalysisServices()
        self.expand_all_categories = False

        wf = getToolByName(self.context, 'portal_workflow')
        mtool = getToolByName(self.context, 'portal_membership')

        self.allow_edit = mtool.checkPermission('Modify portal content',
                                                self.context)

        items = BikaListingView.folderitems(self)
        analyses = self.context.getAnalyses(full_objects=True)

        parts = self.context.getSample().objectValues('SamplePartition')
        partitions = [{'ResultValue': o.Title(),
                       'ResultText': o.getId()}
                      for o in parts
                      if wf.getInfoFor(o, 'cancellation_state', '') == 'active']
        for x in range(len(items)):
            if not 'obj' in items[x]:
                continue
            obj = items[x]['obj']

            cat = obj.getCategoryTitle()
            items[x]['category'] = cat
            if cat not in self.categories:
                self.categories.append(cat)

            items[x]['selected'] = items[x]['uid'] in self.selected

            items[x]['class']['Title'] = 'service_title'

            # js checks in row_data if an analysis may be removed.
            row_data = {}
            # keyword = obj.getKeyword()
            # if keyword in review_states.keys() \
            #    and review_states[keyword] not in ['sample_due',
            #                                       'to_be_sampled',
            #                                       'to_be_preserved',
            #                                       'sample_received',
            #                                       ]:
            #     row_data['disabled'] = True
            items[x]['row_data'] = json.dumps(row_data)

            calculation = obj.getCalculation()
            items[x]['Calculation'] = calculation and calculation.Title()

            locale = locales.getLocale('en')
            currency = self.context.bika_setup.getCurrency()
            symbol = locale.numbers.currencies[currency].symbol
            items[x]['before']['Price'] = symbol
            items[x]['Price'] = obj.getPrice()
            items[x]['class']['Price'] = 'nowrap'
            items[x]['Priority'] = ''

            if items[x]['selected']:
                items[x]['allow_edit'] = ['Partition', 'min', 'max', 'error']
                if not logged_in_client(self.context):
                    items[x]['allow_edit'].append('Price')

            items[x]['required'].append('Partition')
            items[x]['choices']['Partition'] = partitions

            if obj.UID() in self.analyses:
                analysis = self.analyses[obj.UID()]
                part = analysis.getSamplePartition()
                part = part and part or obj
                items[x]['Partition'] = part.Title()
                spec = self.get_spec_from_ar(self.context,
                                             analysis.getService().getKeyword())
                items[x]["min"] = spec["min"]
                items[x]["max"] = spec["max"]
                items[x]["error"] = spec["error"]
                # Add priority premium
                items[x]['Price'] = analysis.getPrice()
                priority = analysis.getPriority()
                items[x]['Priority'] = priority and priority.Title() or ''
            else:
                items[x]['Partition'] = ''
                items[x]["min"] = ''
                items[x]["max"] = ''
                items[x]["error"] = ''
                items[x]["Priority"] = ''

            after_icons = ''
            if obj.getAccredited():
                after_icons += "<img\
                src='%s/++resource++bika.lims.images/accredited.png'\
                title='%s'>" % (
                    self.portal_url,
                    t(_("Accredited"))
                )
            if obj.getReportDryMatter():
                after_icons += "<img\
                src='%s/++resource++bika.lims.images/dry.png'\
                title='%s'>" % (
                    self.portal_url,
                    t(_("Can be reported as dry matter"))
                )
            if obj.getAttachmentOption() == 'r':
                after_icons += "<img\
                src='%s/++resource++bika.lims.images/attach_reqd.png'\
                title='%s'>" % (
                    self.portal_url,
                    t(_("Attachment required"))
                )
            if obj.getAttachmentOption() == 'n':
                after_icons += "<img\
                src='%s/++resource++bika.lims.images/attach_no.png'\
                title='%s'>" % (
                    self.portal_url,
                    t(_('Attachment not permitted'))
                )
            if after_icons:
                items[x]['after']['Title'] = after_icons


            # Display analyses for this Analysis Service in results?
            ser = self.context.getAnalysisServiceSettings(obj.UID())
            items[x]['allow_edit'] = ['Hidden', ]
            items[x]['Hidden'] = ser.get('hidden', obj.getHidden())

        self.categories.sort()
        return items
    def folderitems(self, full_objects=False, classic=True):
        self.categories = []

        analyses = self.context.getAnalyses(full_objects=True)
        self.analyses = dict([(a.getServiceUID(), a) for a in analyses])
        self.selected = self.analyses.keys()
        self.show_categories = \
            self.context.bika_setup.getCategoriseAnalysisServices()
        self.expand_all_categories = False

        wf = getToolByName(self.context, 'portal_workflow')
        items = BikaListingView.folderitems(self)

        parts = self.context.getSample().objectValues('SamplePartition')
        partitions = [{
            'ResultValue': o.Title(),
            'ResultText': o.getId()
        } for o in parts
                      if wf.getInfoFor(o, 'cancellation_state', '') == 'active'
                      ]

        for item in items:
            if 'obj' not in item:
                continue
            obj = item['obj']

            cat = obj.getCategoryTitle()
            item['category'] = cat
            if cat not in self.categories:
                self.categories.append(cat)

            item['selected'] = item['uid'] in self.selected
            item['class']['Title'] = 'service_title'
            row_data = dict()
            calculation = obj.getCalculation()
            item['Calculation'] = calculation and calculation.Title()

            locale = locales.getLocale('en')
            currency = self.context.bika_setup.getCurrency()
            symbol = locale.numbers.currencies[currency].symbol
            item['before']['Price'] = symbol
            item['Price'] = obj.getPrice()
            item['class']['Price'] = 'nowrap'
            item['allow_edit'] = list()
            if item['selected']:
                item['allow_edit'] = [
                    'Partition', 'min', 'max', 'warn_min', 'warn_max'
                ]
                if not logged_in_client(self.context):
                    item['allow_edit'].append('Price')

            item['required'].append('Partition')
            item['choices']['Partition'] = partitions

            if obj.UID() in self.analyses:
                analysis = self.analyses[obj.UID()]

                row_data['disabled'] = wasTransitionPerformed(
                    analysis, 'submit')

                part = analysis.getSamplePartition()
                part = part and part or obj
                item['Partition'] = part.Title()
                spec = self.get_spec_from_ar(self.context,
                                             analysis.getKeyword())
                item["min"] = spec.get("min", '')
                item["max"] = spec.get("max", '')
                item["warn_min"] = spec.get("warn_min", "")
                item["warn_max"] = spec.get("warn_max", "")
                item['Price'] = analysis.getPrice()
            else:
                item['Partition'] = ''
                item["min"] = ''
                item["max"] = ''
                item["warn_min"] = ""
                item["warn_max"] = ""

            # js checks in row_data if an analysis may not be editable.
            item['row_data'] = json.dumps(row_data)
            after_icons = ''
            if obj.getAccredited():
                after_icons += "<img\
                src='%s/++resource++bika.lims.images/accredited.png'\
                title='%s'>" % (self.portal_url, t(_("Accredited")))
            if obj.getAttachmentOption() == 'r':
                after_icons += "<img\
                src='%s/++resource++bika.lims.images/attach_reqd.png'\
                title='%s'>" % (self.portal_url, t(_("Attachment required")))
            if obj.getAttachmentOption() == 'n':
                after_icons += "<img\
                src='%s/++resource++bika.lims.images/attach_no.png'\
                title='%s'>" % (self.portal_url,
                                t(_('Attachment not permitted')))
            if after_icons:
                item['after']['Title'] = after_icons

            # Display analyses for this Analysis Service in results?
            ser = self.context.getAnalysisServiceSettings(obj.UID())
            item['allow_edit'].append('Hidden')
            item['Hidden'] = ser.get('hidden', obj.getHidden())
            item['Unit'] = obj.getUnit()

        self.categories.sort()
        return items
Beispiel #32
0
    def __call__(self):

        # get all the data into datalines
        sc = getToolByName(self.context, 'bika_setup_catalog')
        bac = getToolByName(self.context, 'bika_analysis_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        headings['header'] = _("Analyses per sample type")
        headings['subheader'] = _(
            "Number of analyses requested per sample type")

        count_all = 0
        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'
            })

        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': [_('Sample type'),
                          _('Number of analyses')],
            'class': '',
        }

        datalines = []
        for sampletype in sc(portal_type="SampleType",
                             sort_on='sortable_title'):
            query['getSampleTypeUID'] = sampletype.UID
            analyses = bac(query)
            count_analyses = len(analyses)

            dataline = []
            dataitem = {'value': sampletype.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
        }

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

            fieldnames = [
                'Sample Type',
                '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({
                    'Sample Type': 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=\"analysespersampletype_%s.csv\"" % date)
            self.request.RESPONSE.write(report_data)
        else:
            return {
                'report_title': t(headings['header']),
                'report_data': self.template()
            }
Beispiel #33
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()
    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()}
Beispiel #35
0
    def folderitems(self):
        self.categories = []

        analyses = self.context.getAnalyses(full_objects=True)
        self.analyses = dict([(a.getServiceUID(), a) for a in analyses])
        self.selected = self.analyses.keys()
        self.show_categories = \
            self.context.bika_setup.getCategoriseAnalysisServices()
        self.expand_all_categories = False

        wf = getToolByName(self.context, 'portal_workflow')
        mtool = getToolByName(self.context, 'portal_membership')

        self.allow_edit = mtool.checkPermission('Modify portal content',
                                                self.context)

        items = BikaListingView.folderitems(self)
        analyses = self.context.getAnalyses(full_objects=True)

        parts = self.context.getSample().objectValues('SamplePartition')
        partitions = [{'ResultValue': o.Title(),
                       'ResultText': o.getId()}
                      for o in parts
                      if wf.getInfoFor(o, 'cancellation_state', '') == 'active']
        for x in range(len(items)):
            if not 'obj' in items[x]:
                continue
            obj = items[x]['obj']

            cat = obj.getCategoryTitle()
            items[x]['category'] = cat
            if cat not in self.categories:
                self.categories.append(cat)

            items[x]['selected'] = items[x]['uid'] in self.selected

            items[x]['class']['Title'] = 'service_title'

            # js checks in row_data if an analysis may be removed.
            row_data = {}
            # keyword = obj.getKeyword()
            # if keyword in review_states.keys() \
            #    and review_states[keyword] not in ['sample_due',
            #                                       'to_be_sampled',
            #                                       'to_be_preserved',
            #                                       'sample_received',
            #                                       ]:
            #     row_data['disabled'] = True
            items[x]['row_data'] = json.dumps(row_data)

            calculation = obj.getCalculation()
            items[x]['Calculation'] = calculation and calculation.Title()

            locale = locales.getLocale('en')
            currency = self.context.bika_setup.getCurrency()
            symbol = locale.numbers.currencies[currency].symbol
            items[x]['before']['Price'] = symbol
            items[x]['Price'] = obj.getPrice()
            items[x]['class']['Price'] = 'nowrap'
            items[x]['Priority'] = ''

            if items[x]['selected']:
                items[x]['allow_edit'] = ['Partition', 'min', 'max', 'error']
                if not logged_in_client(self.context):
                    items[x]['allow_edit'].append('Price')

            items[x]['required'].append('Partition')
            items[x]['choices']['Partition'] = partitions

            if obj.UID() in self.analyses:
                analysis = self.analyses[obj.UID()]
                part = analysis.getSamplePartition()
                part = part and part or obj
                items[x]['Partition'] = part.Title()
                spec = analysis.specification \
                    if hasattr(analysis, 'specification') \
                    else {"min": "", "max": "", "error": ""}
                items[x]["min"] = spec["min"]
                items[x]["max"] = spec["max"]
                items[x]["error"] = spec["error"]
                # Add priority premium
                items[x]['Price'] = analysis.getPrice()
                priority = analysis.getPriority()
                items[x]['Priority'] = priority and priority.Title() or ''
            else:
                items[x]['Partition'] = ''
                items[x]["min"] = ''
                items[x]["max"] = ''
                items[x]["error"] = ''
                items[x]["Priority"] = ''

            after_icons = ''
            if obj.getAccredited():
                after_icons += "<img\
                src='%s/++resource++bika.lims.images/accredited.png'\
                title='%s'>" % (
                    self.portal_url,
                    t(_("Accredited"))
                )
            if obj.getReportDryMatter():
                after_icons += "<img\
                src='%s/++resource++bika.lims.images/dry.png'\
                title='%s'>" % (
                    self.portal_url,
                    t(_("Can be reported as dry matter"))
                )
            if obj.getAttachmentOption() == 'r':
                after_icons += "<img\
                src='%s/++resource++bika.lims.images/attach_reqd.png'\
                title='%s'>" % (
                    self.portal_url,
                    t(_("Attachment required"))
                )
            if obj.getAttachmentOption() == 'n':
                after_icons += "<img\
                src='%s/++resource++bika.lims.images/attach_no.png'\
                title='%s'>" % (
                    self.portal_url,
                    t(_('Attachment not permitted'))
                )
            if after_icons:
                items[x]['after']['Title'] = after_icons

        self.categories.sort()
        return items
    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()}
Beispiel #37
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()}