Ejemplo n.º 1
0
    def folderitems(self):
        items = BikaListingView.folderitems(self)
        for x in range(len(items)):
            if not items[x].has_key("obj"):
                continue
            obj = items[x]["obj"]
            obj_url = obj.absolute_url()
            file = obj.getReportFile()
            icon = file.getBestIcon()

            items[x]["Client"] = ""
            client = obj.getClient()
            if client:
                items[x]["replace"]["Client"] = "<a href='%s'>%s</a>" % (client.absolute_url(), client.Title())
            items[x]["FileSize"] = "%sKb" % (file.get_size() / 1024)
            items[x]["Created"] = TimeOrDate(self.context, obj.created())
            items[x]["By"] = pretty_user_name_or_id(self.context, obj.Creator())

            items[x]["replace"]["ReportType"] = "<a href='%s/at_download/ReportFile'>%s</a>" % (
                obj_url,
                items[x]["ReportType"],
            )
        return items
Ejemplo n.º 2
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()
Ejemplo n.º 3
0
    def folderitems(self, full_objects = False):
        workflow = getToolByName(self.context, "portal_workflow")
        items = BikaListingView.folderitems(self)
        mtool = getToolByName(self.context, 'portal_membership')
        member = mtool.getAuthenticatedMember()
        translate = self.context.translate

        for x in range(len(items)):
            if not items[x].has_key('obj'): continue
            obj = items[x]['obj']
            items[x]['replace']['getSampleID'] = "<a href='%s'>%s</a>" % \
                (items[x]['url'], obj.getSampleID())

            requests = ["<a href='%s'>%s</a>" % (o.absolute_url(), o.Title())
                        for o in obj.getAnalysisRequests()]
            items[x]['replace']['Requests'] = ",".join(requests)

            items[x]['Client'] = obj.aq_parent.Title()
            items[x]['replace']['Client'] = "<a href='%s'>%s</a>" % \
                (obj.aq_parent.absolute_url(), obj.aq_parent.Title())

            items[x]['Creator'] = pretty_user_name_or_id(self.context,
                                                         obj.Creator())

            items[x]['DateReceived'] = TimeOrDate(self.context,
                                                  obj.getDateReceived())

            samplingdate = obj.getSamplingDate()

            if not samplingdate > DateTime():
                datesampled = TimeOrDate(self.context, obj.getDateSampled())
                if not datesampled:
                    datesampled = TimeOrDate(self.context, DateTime(),
                                             long_format=1, with_time = False)
                    items[x]['class']['getDateSampled'] = 'provisional'
                sampler = obj.getSampler().strip()
                if sampler:
                    items[x]['replace']['getSampler'] = pretty_user_name_or_id(
                        self.context, sampler)
                if 'Sampler' in member.getRoles() and not sampler:
                    sampler = member.id
                    items[x]['class']['getSampler'] = 'provisional'
            else:
                datesampled = ''
                sampler = ''
            items[x]['getDateSampled'] = datesampled
            items[x]['getSampler'] = sampler

            items[x]['Created'] = TimeOrDate(self.context, obj.created())

            samplingdate = obj.getSamplingDate()
            items[x]['getSamplingDate'] = TimeOrDate(self.context, samplingdate)

            after_icons = ''
            if obj.getSampleType().getHazardous():
                after_icons += "<img title='%s' " \
                    "src='%s/++resource++bika.lims.images/hazardous.png'>" % \
                    (self.context.translate(_("Hazardous")),
                     self.portal_url)
            if obj.getSamplingDate() > DateTime():
                after_icons += "<img title='%s' " \
                    "src='%s/++resource++bika.lims.images/calendar.png' >" % \
                    (self.context.translate(_("Future dated sample")),
                     self.portal_url)
            if after_icons:
                items[x]['after']['getSampleID'] = after_icons

            # sampling workflow - inline edits for Sampler and Date Sampled
            checkPermission = self.context.portal_membership.checkPermission
            if checkPermission(SampleSample, obj) \
                and not samplingdate > DateTime():
                items[x]['required'] = ['getSampler', 'getDateSampled']
                items[x]['allow_edit'] = ['getSampler', 'getDateSampled']
                samplers = getUsers(obj, ['Sampler', 'LabManager', 'Manager'])
                getAuthenticatedMember = self.context.portal_membership.getAuthenticatedMember
                username = getAuthenticatedMember().getUserName()
                users = [({'ResultValue': u, 'ResultText': samplers.getValue(u)})
                         for u in samplers]
                items[x]['choices'] = {'getSampler': users}
                Sampler = sampler and sampler or \
                    (username in samplers.keys() and username) or ''
                items[x]['getSampler'] = Sampler

            # These don't exist on samples
            # the columns exist just to set "preserve" transition from lists.
            # XXX This should be a list of preservers...
            items[x]['getPreserver'] = ''
            items[x]['getDatePreserved'] = ''

            # inline edits for Preserver and Date Preserved
            checkPermission = self.context.portal_membership.checkPermission
            if checkPermission(PreserveSample, obj):
                items[x]['required'] = ['getPreserver', 'getDatePreserved']
                items[x]['allow_edit'] = ['getPreserver', 'getDatePreserved']
                preservers = getUsers(obj, ['Preserver', 'LabManager', 'Manager'])
                getAuthenticatedMember = self.context.portal_membership.getAuthenticatedMember
                username = getAuthenticatedMember().getUserName()
                users = [({'ResultValue': u, 'ResultText': preservers.getValue(u)})
                         for u in preservers]
                items[x]['choices'] = {'getPreserver': users}
                preserver = username in preservers.keys() and username or ''
                items[x]['getPreserver'] = preserver
                items[x]['getDatePreserved'] = TimeOrDate(
                    self.context, DateTime(), long_format=1, with_time=False)
                items[x]['class']['getPreserver'] = 'provisional'
                items[x]['class']['getDatePreserved'] = 'provisional'

        # Hide Preservation/Sampling workflow actions if the edit columns
        # are not displayed.
        toggle_cols = self.get_toggle_cols()
        new_states = []
        for i,state in enumerate(self.review_states):
            if state['id'] == self.review_state:
                if 'getSampler' not in toggle_cols \
                   or 'getDateSampled' not in toggle_cols:
                    if 'hide_transitions' in state:
                        state['hide_transitions'].append('sample')
                    else:
                        state['hide_transitions'] = ['sample',]
                if 'getPreserver' not in toggle_cols \
                   or 'getDatePreserved' not in toggle_cols:
                    if 'hide_transitions' in state:
                        state['hide_transitions'].append('preserve')
                    else:
                        state['hide_transitions'] = ['preserve',]
            new_states.append(state)
        self.review_states = new_states

        return items
Ejemplo n.º 4
0
    def __call__(self):
        form = self.request.form
        bc = getToolByName(self.context, 'bika_catalog')
        bsc = getToolByName(self.context, 'bika_setup_catalog')
        checkPermission = self.context.portal_membership.checkPermission
        getAuthenticatedMember = self.context.portal_membership.getAuthenticatedMember
        workflow = getToolByName(self.context, 'portal_workflow')
        ars = self.context.getAnalysisRequests()
        props = getToolByName(self.context, 'portal_properties').bika_properties
        datepicker_format = props.getProperty('datepicker_format')
        sample = self.context

        ## Create header_table data rows
        ar_links = ", ".join(
            ["<a href='%s'>%s</a>"%(ar.absolute_url(), ar.Title())
             for ar in ars])
        sp = self.context.getSamplePoint()
        st = self.context.getSampleType()
        if workflow.getInfoFor(self.context, 'cancellation_state') == "cancelled":
            allow_sample_edit = False
        else:
            edit_states = ['to_be_sampled', 'to_be_preserved', 'sample_due']
            allow_sample_edit = checkPermission(ManageSamples, self.context) \
                and workflow.getInfoFor(self.context, 'review_state') in edit_states

        SamplingWorkflowEnabled =\
            self.context.bika_setup.getSamplingWorkflowEnabled()
        samplers = getUsers(sample, ['Sampler', 'LabManager', 'Manager'])

        self.header_columns = 3
        self.header_rows = [
            {'id': 'ClientReference',
             'title': _('Client Reference'),
             'allow_edit': self.allow_edit,
             'value': self.context.getClientReference(),
             'condition':True,
             'type': 'text'},
            {'id': 'ClientSampleID',
             'title': _('Client SID'),
             'allow_edit': self.allow_edit,
             'value': self.context.getClientSampleID(),
             'condition':True,
             'type': 'text'},
            {'id': 'Requests',
             'title': _('Requests'),
             'allow_edit': False,
             'value': ar_links,
             'condition':True,
             'type': 'text'},
            {'id': 'SampleType',
             'title': _('Sample Type'),
             'allow_edit': self.allow_edit and allow_sample_edit,
             'value': st and st.Title() or '',
             'condition':True,
             'type': 'text',
             'required': True},
            {'id': 'SamplePoint',
             'title': _('Sample Point'),
             'allow_edit': self.allow_edit and allow_sample_edit,
             'value': sp and sp.Title() or '',
             'condition':True,
             'type': 'text'},
            {'id': 'Composite',
             'title': _('Composite'),
             'allow_edit': self.allow_edit and allow_sample_edit,
             'value': self.context.getComposite(),
             'condition':True,
             'type': 'boolean'},
            {'id': 'Creator',
             'title': PMF('Creator'),
             'allow_edit': False,
             'value': pretty_user_name_or_id(self.context, self.context.Creator()),
             'condition':True,
             'type': 'text'},
            {'id': 'DateCreated',
             'title': PMF('Date Created'),
             'allow_edit': False,
             'value': self.context.created(),
             'formatted_value': TimeOrDate(self.context, self.context.created()),
             'condition':True,
             'type': 'text'},
            {'id': 'SamplingDate',
             'title': _('Sampling Date'),
             'allow_edit': self.allow_edit and allow_sample_edit,
             'value': self.context.getSamplingDate().strftime(datepicker_format),
             'formatted_value': TimeOrDate(self.context, self.context.getSamplingDate()),
             'condition':True,
             'class': 'datepicker',
             'type': 'text'},
            {'id': 'DateSampled',
             'title': _('Date Sampled'),
             'allow_edit': self.allow_edit and allow_sample_edit,
             'value': sample.getDateSampled() and sample.getDateSampled().strftime(datepicker_format) or '',
             'formatted_value': sample.getDateSampled() and TimeOrDate(self.context, sample.getDateSampled()) or '',
             'condition':SamplingWorkflowEnabled,
             'class': 'datepicker',
             'type': 'text',
             'required': True},
            {'id': 'Sampler',
             'title': _('Sampler'),
             'allow_edit': self.allow_edit and allow_sample_edit,
             'value': sample.getSampler(),
             'formatted_value': sample.getSampler(),
             'condition':SamplingWorkflowEnabled,
             'vocabulary': samplers,
             'type': 'choices',
             'required': True},
            {'id': 'DateReceived',
             'title': _('Date Received'),
             'allow_edit': False,
             'value': self.context.getDateReceived(),
             'formatted_value': TimeOrDate(self.context, self.context.getDateReceived()),
             'condition':True,
             'type': 'text'},
            {'id': 'DateExpired',
             'title': _('Date Expired'),
             'allow_edit': False,
             'value': self.context.getDateExpired(),
             'formatted_value': TimeOrDate(self.context, self.context.getDateExpired()),
             'condition':True,
             'type': 'text'},
            {'id': 'DisposalDate',
             'title': _('Disposal Date'),
             'allow_edit': False,
             'value': self.context.getDisposalDate(),
             'formatted_value': TimeOrDate(self.context, self.context.getDisposalDate()),
             'condition':True,
             'type': 'text'},
            {'id': 'DateDisposed',
             'title': _('Date Disposed'),
             'allow_edit': False,
             'value': self.context.getDateDisposed(),
             'formatted_value': TimeOrDate(self.context, self.context.getDateDisposed()),
             'condition':True,
             'type': 'text'},
        ]
        if self.allow_edit:
            self.header_buttons = [{'name':'save_button', 'title':_('Save')}]
        else:
            self.header_buttons = []

        ## handle_header table submit
        if form.get('header_submitted', None):
            plone.protect.CheckAuthenticator(form)
            message = None
            values = {}
            for row in [r for r in self.header_rows if r['allow_edit']]:
                value = urllib.unquote_plus(form.get(row['id'], ''))

                if row['id'] == 'SampleType':
                    if not value:
                        message = PMF(
                            u'error_required',
                            default=u'${name} is required, please correct.',
                            mapping={'name': _('Sample Type')})
                        break
                    if not bsc(portal_type = 'SampleType', title = value):
                        message = _("${sampletype} is not a valid sample type",
                                    mapping={'sampletype':value})
                        break

                if row['id'] == 'SamplePoint':
                    if value and \
                       not bsc(portal_type = 'SamplePoint', title = value):
                        message = _("${samplepoint} is not a valid sample point",
                                    mapping={'sampletype':value})
                        break

                values[row['id']] = value

            # boolean - checkboxes are 'true' or 'false in form.
            for row in [r for r in self.header_rows if r.get('type', '') == 'boolean']:
                value = form.get(row['id'], 'false')
                values[row['id']] = value == 'true' and True or False

            if not message:
                self.context.edit(**values)
                self.context.reindexObject()
                ars = self.context.getAnalysisRequests()
                for ar in ars:
                    ar.reindexObject()
                message = PMF("Changes saved.")

            # If this sample was "To Be Sampled", and the
            # Sampler and DateSampled fields were completed,
            # do the Sampled transition.
            if workflow.getInfoFor(sample, "review_state") == "to_be_sampled" \
               and form.get("Sampler", None) \
               and form.get("DateSampled", None):
                workflow.doActionFor(sample, "sample")
                sample.reindexObject()

            self.context.plone_utils.addPortalMessage(message, 'info')
            url = self.context.absolute_url().split("?")[0]
            self.request.RESPONSE.redirect(url)
            return

        ## Create Sample Partitions table
        parts_table = None
        if not self.allow_edit:
            p = SamplePartitionsView(self.context, self.request)
            p.allow_edit = self.allow_edit
            p.show_select_column = self.allow_edit
            p.show_workflow_action_buttons = self.allow_edit
            p.show_column_toggles = False
            p.show_select_all_checkbox = False
            p.review_states[0]['transitions'] = [{'id': 'empty'},] # none
            parts_table = p.contents_table()
        self.parts = parts_table

        ## Create Field and Lab Analyses tables
        self.tables = {}
        if not self.allow_edit:
            for poc in POINTS_OF_CAPTURE:
                if not self.context.getAnalyses({'getPointOfCapture': poc}):
                    continue
                t = SampleAnalysesView(self.context,
                                 self.request,
                                 getPointOfCapture = poc,
                                 sort_on = 'getServiceTitle')
                t.form_id = "sample_%s_analyses" % poc
                if poc == 'field':
                    t.review_states[0]['columns'].remove('DueDate')
                t.show_column_toggles = False
                t.review_states[0]['transitions'] = [{'id':'submit'},
                                                     {'id':'retract'},
                                                     {'id':'verify'}]
                self.tables[POINTS_OF_CAPTURE.getValue(poc)] = t.contents_table()

        return self.template()
Ejemplo n.º 5
0
    def folderitems(self, full_objects = False):
        items = BikaListingView.folderitems(self)

        props = getToolByName(self.context, 'portal_properties').bika_properties
        datepicker_format = props.getProperty('datepicker_format')

        bsc = getToolByName(self.context, 'bika_setup_catalog')

        containers = [({'ResultValue':o.UID,
                        'ResultText':o.title})
                      for o in bsc(portal_type="Container",
                                   inactive_state="active")]
        preservations = [({'ResultValue':o.UID,
                           'ResultText':o.title})
                         for o in bsc(portal_type="Preservation",
                                      inactive_state="active")]

        for x in range(len(items)):
            if not items[x].has_key('obj'): continue
            obj = items[x]['obj']

            items[x]['PartTitle'] = obj.getId()

            container = obj.getContainer()
            if self.allow_edit:
                items[x]['getContainer'] = container and container.UID() or ''
            else:
                items[x]['getContainer'] = container and container.Title() or ''

            preservation = obj.getPreservation()
            if self.allow_edit:
                items[x]['getPreservation'] = preservation and preservation.UID() or ''
            else:
                items[x]['getPreservation'] = preservation and preservation.Title() or ''

##            sampler = obj.getSampler().strip()
##            items[x]['getSampler'] = \
##                sampler and pretty_user_name_or_id(self.context, sampler) or ''
##            datesampled = obj.getDateSampled()
##            items[x]['getDateSampled'] = \
##                datesampled and TimeOrDate(self.context, datesampled) or ''

            preserver = obj.getPreserver().strip()
            items[x]['getPreserver'] = \
                preserver and pretty_user_name_or_id(self.context, preserver) or ''
            datepreserved = obj.getDatePreserved()
            items[x]['getDatePreserved'] = \
                datepreserved and TimeOrDate(self.context, datepreserved) or ''

            disposaldate = obj.getDisposalDate()
            items[x]['getDisposalDate'] = \
                disposaldate and TimeOrDate(self.context, disposaldate) or ''

            samplingdate = obj.getSamplingDate()

            # inline edits for Container and Preservation
            items[x]['allow_edit'] = ['getContainer', 'getPreservation']
            items[x]['choices']['getPreservation'] = preservations
            items[x]['choices']['getContainer'] = containers

            # inline edits for Sampler and Date Sampled
##            checkPermission = self.context.portal_membership.checkPermission
##            if checkPermission(SampleSample, obj) \
##                and not samplingdate > DateTime():
##                items[x]['required'] += ['getSampler', 'getDateSampled']
##                items[x]['allow_edit'] += ['getSampler', 'getDateSampled']
##                samplers = getUsers(obj, ['Sampler', 'LabManager', 'Manager'])
##                getAuthenticatedMember = obj.portal_membership.getAuthenticatedMember
##                username = getAuthenticatedMember().getUserName()
##                users = [({'ResultValue': u, 'ResultText': samplers.getValue(u)})
##                         for u in samplers]
##                items[x]['choices']['getSampler'] = users
##                items[x]['getSampler'] = sampler and sampler or \
##                    (username in samplers.keys() and username) or ''
##                items[x]['getDateSampled'] = items[x]['getDateSampled'] \
##                    or DateTime().strftime(datepicker_format)
##                items[x]['class']['getSampler'] = 'provisional'
##                items[x]['class']['getDateSampled'] = 'provisional'

            # inline edits for Preserver and Date Preserved
            checkPermission = self.context.portal_membership.checkPermission
            if checkPermission(PreserveSample, obj):
                items[x]['required'] += ['getPreserver', 'getDatePreserved']
                items[x]['allow_edit'] += ['getPreserver', 'getDatePreserved']
                preservers = getUsers(obj, ['Preserver', 'LabManager', 'Manager'])
                getAuthenticatedMember = obj.portal_membership.getAuthenticatedMember
                username = getAuthenticatedMember().getUserName()
                users = [({'ResultValue': u, 'ResultText': preservers.getValue(u)})
                         for u in preservers]
                items[x]['choices']['getPreserver'] = users
                items[x]['getPreserver'] = preserver and preserver or \
                    (username in preservers.keys() and username) or ''
                items[x]['getDatePreserved'] = items[x]['getDatePreserved'] \
                    or DateTime().strftime(datepicker_format)
                items[x]['class']['getPreserver'] = 'provisional'
                items[x]['class']['getDatePreserved'] = 'provisional'

        return items
Ejemplo n.º 6
0
    def __call__(self):
        # get all the data into datalines
        
        sc = getToolByName(self.context, 'bika_setup_catalog')
        bc = getToolByName(self.context, 'bika_analysis_catalog')
        rc = getToolByName(self.context, 'reference_catalog')
        self.report_content = {}
        parm_lines = {}
        parms = []
        headings = {}
        headings['header'] = _("Analysis turnaround times over time")
        headings['subheader'] = \
               _("The turnaround time of analyses plotted over time")

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

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

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

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

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

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

        query['review_state'] = 'published'


        # query all the analyses and increment the counts

        periods = {}
        total_count = 0
        total_duration = 0

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

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

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


        datalines = []

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


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



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

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

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

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

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


        return self.template()
Ejemplo n.º 7
0
    def __call__(self):
        #import pdb
        #pdb.set_trace()
        lab = self.context.bika_setup.laboratory
        self.lab_title = lab.getName()
        self.address = lab.getPrintAddress()
        self.date = DateTime()
        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']
        if report_id == 'analysesperservice':
            self.reportout = AnalysesPerService(self.context, self.request)()
        elif report_id == 'analysespersampletype':
            self.reportout = AnalysesPerSampleType(self.context,
                                                   self.request)()
        elif report_id == 'analysesperclient':
            self.reportout = AnalysesPerClient(self.context, self.request)()
        elif report_id == 'analysestats':
            self.reportout = AnalysesTats(self.context, self.request)()
        elif report_id == 'analysesattachments':
            self.reportout = AnalysesAttachments(self.context, self.request)()
        else:
            self.reportout = "no report to out"

        # this works but the html is not rendered.
        #filename = "testing4.pdf"
        #ramdisk = StringIO()
        #pdf = pisa.CreatePDF(StringIO(self.reportout), ramdisk)
        #result = ramdisk.getvalue()
        #ramdisk.close()

        #if not pdf.err:
        #    #stream file to browser
        #    setheader = self.request.RESPONSE.setHeader
        #    #setheader('Content-Length',len(result))
        #    setheader('Content-Type', 'Application/pdf')
        #    setheader('Content-Disposition', 'inline; filename=%s' % filename)
        #    self.request.RESPONSE.write(result)

        #filename = "testing4.pdf"
        ramdisk = StringIO()
        pdf = pisa.CreatePDF(self.template(), ramdisk)
        result = ramdisk.getvalue()
        ramdisk.close()

        if not pdf.err:
            #stream file to browser
            setheader = self.request.RESPONSE.setHeader
            #setheader('Content-Length',len(result))
            setheader('Content-Type', 'application/pdf')
            #setheader('Content-Disposition', 'inline; filename=%s' % filename)
            #self.request.RESPONSE.write(result)
            thisid = self.context.invokeFactory("File", id="tmp")
            thisfile = self.context[thisid]
            from bika.lims.idserver import renameAfterCreation
            renameAfterCreation(thisfile)
            thisfile.setFile(result)
            self.request.RESPONSE.redirect(thisfile.absolute_url())

        pisa.showLogging()
        """pisa.CreatePDF(self.reportout, "testing.pdf")
Ejemplo n.º 8
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()
Ejemplo n.º 9
0
    def folderitems(self, full_objects = False):
        workflow = getToolByName(self.context, "portal_workflow")
        items = BikaListingView.folderitems(self)

        props = getToolByName(self.context, 'portal_properties').bika_properties
        datepicker_format = props.getProperty('datepicker_format')

        for x in range(len(items)):
            if not items[x].has_key('obj'): continue
            obj = items[x]['obj']

            container = obj.getContainer()
            items[x]['getContainer'] = container and container.Title() or ''

            preservation = obj.getPreservation()
            items[x]['getPreservation'] = \
                preservation and preservation.Title() or ''

            sampler = obj.getSampler().strip()
            items[x]['getSampler'] = \
                sampler and pretty_user_name_or_id(self.context, sampler) or ''
            datesampled = obj.getDateSampled()
            items[x]['getDateSampled'] = \
                datesampled and TimeOrDate(self.context, datesampled) or ''

            preserver = obj.getPreserver().strip()
            items[x]['getPreserver'] = \
                preserver and pretty_user_name_or_id(self.context, preserver) or ''
            datepreserved = obj.getDatePreserved()
            items[x]['getDatePreserved'] = \
                datepreserved and TimeOrDate(self.context, datepreserved) or ''

            disposaldate = obj.getDisposalDate()
            items[x]['getDisposalDate'] = \
                disposaldate and TimeOrDate(self.context, disposaldate) or ''

            samplingdate = obj.getSamplingDate()

            # inline edits for Sampler and Date Sampled
            checkPermission = self.context.portal_membership.checkPermission
            if checkPermission(SampleSample, obj) \
                and not samplingdate > DateTime():
                items[x]['required'] = ['getSampler', 'getDateSampled']
                items[x]['allow_edit'] = ['getSampler', 'getDateSampled']
                samplers = getUsers(obj, ['Sampler', 'LabManager', 'Manager'])
                getAuthenticatedMember = obj.portal_membership.getAuthenticatedMember
                username = getAuthenticatedMember().getUserName()
                users = [({'ResultValue': u, 'ResultText': samplers.getValue(u)})
                         for u in samplers]
                items[x]['choices'] = {'getSampler': users}
                items[x]['getSampler'] = sampler and sampler or \
                    (username in samplers.keys() and username) or ''
                items[x]['getDateSampled'] = items[x]['getDateSampled'] \
                    or DateTime().strftime(datepicker_format)
                items[x]['class']['getSampler'] = 'provisional'
                items[x]['class']['getDateSampled'] = 'provisional'

            # inline edits for Preserver and Date Preserved
            checkPermission = self.context.portal_membership.checkPermission
            if checkPermission(PreserveSample, obj):
                items[x]['required'] = ['getPreserver', 'getDatePreserved']
                items[x]['allow_edit'] = ['getPreserver', 'getDatePreserved']
                preservers = getUsers(obj, ['Preserver', 'LabManager', 'Manager'])
                getAuthenticatedMember = obj.portal_membership.getAuthenticatedMember
                username = getAuthenticatedMember().getUserName()
                users = [({'ResultValue': u, 'ResultText': preservers.getValue(u)})
                         for u in preservers]
                items[x]['choices'] = {'getPreserver': users}
                items[x]['getPreserver'] = preserver and preserver or \
                    (username in preservers.keys() and username) or ''
                items[x]['getDatePreserved'] = items[x]['getDatePreserved'] \
                    or DateTime().strftime(datepicker_format)
                items[x]['class']['getPreserver'] = 'provisional'
                items[x]['class']['getDatePreserved'] = 'provisional'

        return items
Ejemplo n.º 10
0
    def __call__(self):
        form = self.request.form
        bsc = getToolByName(self.context, 'bika_setup_catalog')
        pc = getToolByName(self.context, 'portal_catalog')
        checkPermission = self.context.portal_membership.checkPermission
        getAuthenticatedMember = self.context.portal_membership.getAuthenticatedMember
        workflow = getToolByName(self.context, 'portal_workflow')
        ars = self.context.getAnalysisRequests()

        props = getToolByName(self.context, 'portal_properties').bika_properties
        datepicker_format = props.getProperty('datepicker_format')

        ## Create header_table data rows
        ar_links = ", ".join(
            ["<a href='%s'>%s</a>"%(ar.absolute_url(), ar.Title())
             for ar in ars])
        sp = self.context.getSamplePoint()
        st = self.context.getSampleType()
        if workflow.getInfoFor(self.context, 'cancellation_state') == "cancelled":
            allow_sample_edit = False
        else:
            edit_states = ['to_be_sampled', 'to_be_preserved', 'sample_due']
            allow_sample_edit = checkPermission(ManageSamples, self.context) \
                and workflow.getInfoFor(self.context, 'review_state') in edit_states

        self.header_columns = 3
        self.header_rows = [
            {'id': 'ClientReference',
             'title': _('Client Reference'),
             'allow_edit': True,
             'value': self.context.getClientReference(),
             'condition':True,
             'type': 'text'},
            {'id': 'ClientSampleID',
             'title': _('Client SID'),
             'allow_edit': True,
             'value': self.context.getClientSampleID(),
             'condition':True,
             'type': 'text'},
            {'id': 'Requests',
             'title': _('Requests'),
             'allow_edit': False,
             'value': ar_links,
             'condition':True,
             'type': 'text'},
            {'id': 'SampleType',
             'title': _('Sample Type'),
             'allow_edit': allow_sample_edit,
             'value': st and st.Title() or '',
             'condition':True,
             'type': 'text',
             'required': True},
            {'id': 'SamplePoint',
             'title': _('Sample Point'),
             'allow_edit': allow_sample_edit,
             'value': sp and sp.Title() or '',
             'condition':True,
             'type': 'text'},
            {'id': 'Composite',
             'title': _('Composite'),
             'allow_edit': allow_sample_edit,
             'value': self.context.getComposite(),
             'condition':True,
             'type': 'boolean'},
            {'id': 'Creator',
             'title': PMF('Creator'),
             'allow_edit': False,
             'value': pretty_user_name_or_id(self.context, self.context.Creator()),
             'condition':True,
             'type': 'text'},
            {'id': 'DateCreated',
             'title': PMF('Date Created'),
             'allow_edit': False,
             'value': self.context.created(),
             'formatted_value': TimeOrDate(self.context, self.context.created()),
             'condition':True,
             'type': 'text'},
            {'id': 'SamplingDate',
             'title': _('Sampling Date'),
             'allow_edit': allow_sample_edit,
             'value': self.context.getSamplingDate().strftime(datepicker_format),
             'formatted_value': TimeOrDate(self.context, self.context.getSamplingDate()),
             'condition':True,
             'class': 'datepicker',
             'type': 'text'},
            {'id': 'DateReceived',
             'title': _('Date Received'),
             'allow_edit': False,
             'value': self.context.getDateReceived(),
             'formatted_value': TimeOrDate(self.context, self.context.getDateReceived()),
             'condition':True,
             'type': 'text'},
            {'id': 'DateExpired',
             'title': _('Date Expired'),
             'allow_edit': False,
             'value': self.context.getDateExpired(),
             'formatted_value': TimeOrDate(self.context, self.context.getDateExpired()),
             'condition':True,
             'type': 'text'},
            {'id': 'DisposalDate',
             'title': _('Disposal Date'),
             'allow_edit': False,
             'value': self.context.getDisposalDate(),
             'formatted_value': TimeOrDate(self.context, self.context.getDisposalDate()),
             'condition':True,
             'type': 'text'},
            {'id': 'DateDisposed',
             'title': _('Date Disposed'),
             'allow_edit': False,
             'value': self.context.getDateDisposed(),
             'formatted_value': TimeOrDate(self.context, self.context.getDateDisposed()),
             'condition':True,
             'type': 'text'},
        ]
        self.header_buttons = [{'name':'save_button', 'title':_('Save')}]

        ## handle_header table submit
        if 'save_button' in form:
            message = None
            values = {}
            for row in [r for r in self.header_rows if r['allow_edit']]:
                value = form.get(row['id'], '')

                if row['id'] == 'SampleType':
                    if not value:
                        message = _('Sample Type is required')
                        break
                    if not bsc(portal_type = 'SampleType', title = value):
                        message = _("${sampletype} is not a valid sample type",
                                    mapping={'sampletype':value})
                        break

                if row['id'] == 'SamplePoint':
                    if value and \
                       not bsc(portal_type = 'SamplePoint', title = value):
                        message = _("${samplepoint} is not a valid sample point",
                                    mapping={'sampletype':value})
                        break

                values[row['id']] = value

            # boolean - checkboxes are present, or not present in form.
            for row in [r for r in self.header_rows if r.get('type', '') == 'boolean']:
                values[row['id']] = row['id'] in form

            if not message:
                self.context.edit(**values)
                self.context.reindexObject()
                ars = self.context.getAnalysisRequests()
                for ar in ars:
                    ar.reindexObject()
                message = PMF("Changes saved.")

            self.context.plone_utils.addPortalMessage(message, 'info')
            # we need to start the request again, to regenerate header
            self.request.RESPONSE.redirect(self.context.absolute_url())
            return

        ## Create Sample Partitions table
        p = SamplePartitionsView(self.context, self.request)
        p.show_column_toggles = False
        self.parts = p.contents_table()

        ## Create Field and Lab Analyses tables
        self.tables = {}
        for poc in POINTS_OF_CAPTURE:
            if not self.context.getAnalyses({'getPointOfCapture': poc}):
                continue
            t = SampleAnalysesView(self.context,
                             self.request,
                             getPointOfCapture = poc,
                             sort_on = 'getServiceTitle')
            t.form_id = "sample_%s_analyses" % poc
            t.allow_edit = True
            if poc == 'field':
                t.review_states[0]['columns'].remove('DueDate')
            t.show_column_toggles = False
            t.review_states[0]['transitions'] = [{'id':'submit'},
                                                 {'id':'retract'},
                                                 {'id':'verify'}]
            t.show_select_column = True
            self.tables[POINTS_OF_CAPTURE.getValue(poc)] = t.contents_table()

        return self.template()