コード例 #1
0
ファイル: validators.py プロジェクト: nafwa03/olims
    def __call__(self, value, *args, **kwargs):
        instance = kwargs['instance']
        translate = getToolByName(instance, 'translation_service').translate

        # remove spaces from formatted
        IBAN = ''.join(c for c in value if c.isalnum())

        IBAN = IBAN[4:] + IBAN[:4]
        country = IBAN[-4:-2]

        if country not in country_dic:
            msg = _('Unknown IBAN country %s' % country)
            return to_utf8(translate(msg))

        length_c, name_c = country_dic[country]

        if len(IBAN) != length_c:
            diff = len(IBAN) - length_c
            msg = _('Wrong IBAN length by %s: %s' % (('short by %i' % -diff) if diff < 0 else
            ('too long by %i' % diff), value))
            return to_utf8(translate(msg))
        # Validating procedure
        elif int("".join(str(letter_dic[x]) for x in IBAN)) % 97 != 1:
            msg = _('Incorrect IBAN number: %s' % value)
            return to_utf8(translate(msg))

        else:
            # Accepted:
            return True
コード例 #2
0
ファイル: __init__.py プロジェクト: nafwa03/olims
    def parse_daterange(self, request, field_id, field_title):
        from_date = request.get('%s_fromdate' % field_id, None)
        from_date = from_date and from_date + ' 00:00' or None
        to_date = request.get('%s_todate' % field_id, None)
        to_date = to_date and to_date + ' 23:59' or None
        if from_date and to_date:
            query = {'query': [from_date, to_date], 'range': 'min:max'}
        elif from_date or to_date:
            query = {'query': from_date or to_date,
                     'range': from_date and 'min' or 'max'}
        else:
            return None

        if from_date and to_date:
            parms = translate(_("From ${start_date} to ${end_date}",
                               mapping={"start_date":from_date, "end_date":to_date}))
        elif from_date:
            parms = translate(_("Before ${start_date}",
                               mapping={"start_date":from_date}))
        elif to_date:
            parms = translate(_("After ${end_date}",
                               mapping={"end_date":to_date}))

        res = {}
        res['contentFilter'] = (field_id, query)
        res['parms'] = {'title': field_title, 'value': parms}
        res['titles'] = parms
        return res
コード例 #3
0
    def __call__(self, value, *args, **kwargs):
        instance = kwargs['instance']
        fieldname = kwargs['field'].getName()
        request = kwargs.get('REQUEST', {})
        form = request.form
        form_value = form.get(fieldname)

        translate = getToolByName(instance, 'translation_service').translate
        # bsc = getToolByName(instance, 'bika_setup_catalog')

        # ResultValue must always be a number
        for field in form_value:
            try:
                float(field['ResultValue'])
            except:
                return to_utf8(
                    translate(
                        _("Validation failed: "
                          "Result Values must be numbers")))
            if 'ResultText' not in field:
                return to_utf8(
                    translate(
                        _("Validation failed: Result Text cannot be blank")))

        return True
コード例 #4
0
 def getMaintenanceTypes(self):
     """ Return the current list of maintenance types
     """
     types = [('Preventive',safe_unicode(_('Preventive')).encode('utf-8')),
              ('Repair', safe_unicode(_('Repair')).encode('utf-8')),
              ('Enhancement', safe_unicode(_('Enhancement')).encode('utf-8'))]
     return DisplayList(types)
コード例 #5
0
    def __call__(self, value, *args, **kwargs):
        instance = kwargs['instance']
        translate = getToolByName(instance, 'translation_service').translate

        # remove spaces from formatted
        IBAN = ''.join(c for c in value if c.isalnum())

        IBAN = IBAN[4:] + IBAN[:4]
        country = IBAN[-4:-2]

        if country not in country_dic:
            msg = _('Unknown IBAN country %s' % country)
            return to_utf8(translate(msg))

        length_c, name_c = country_dic[country]

        if len(IBAN) != length_c:
            diff = len(IBAN) - length_c
            msg = _('Wrong IBAN length by %s: %s' %
                    (('short by %i' % -diff) if diff < 0 else
                     ('too long by %i' % diff), value))
            return to_utf8(translate(msg))
        # Validating procedure
        elif int("".join(str(letter_dic[x]) for x in IBAN)) % 97 != 1:
            msg = _('Incorrect IBAN number: %s' % value)
            return to_utf8(translate(msg))

        else:
            # Accepted:
            return True
コード例 #6
0
ファイル: referenceanalysis.py プロジェクト: pureboy8/OLiMS
 def __call__(self, result=None, specification=None, **kwargs):
     translate = self.context.translate
     path = '++resource++bika.lims.images'
     alerts = {}
     # We look for IResultOutOfRange adapters for this object
     for name, adapter in getAdapters((self.context, ), IResultOutOfRange):
         ret = adapter(result)
         if not ret:
             continue
         spec = ret["spec_values"]
         if spec:
             rngstr = " ({0} {1}, {2}, {3})".format(t(_("min")),
                                                    str(spec['min']),
                                                    t(_("max")),
                                                    str(spec['max']))
         else:
             rngstr = ""
         if ret["out_of_range"]:
             if ret["acceptable"]:
                 message = "{0}{1}".format(t(_('Result in shoulder range')),
                                           rngstr)
                 icon = path + '/warning.png'
             else:
                 message = "{0}{1}".format(t(_('Result out of range')),
                                           rngstr)
                 icon = path + '/exclamation.png'
             alerts[self.context.UID()] = [
                 {
                     'icon': icon,
                     'msg': message,
                     'field': 'Result',
                 },
             ]
         break
     return alerts
コード例 #7
0
ファイル: bika_attachmenttypes.py プロジェクト: nafwa03/olims
    def __init__(self, context, request):
        super(AttachmentTypesView, self).__init__(context, request)
        self.catalog = 'bika_setup_catalog'
        self.contentFilter = {'portal_type': 'AttachmentType',
                              'sort_on': 'sortable_title'}
        self.context_actions = {_('Add'):
                                {'url':'createObject?type_name=AttachmentType',
                                 'icon': '++resource++bika.lims.images/add.png'}}
        self.icon = self.portal_url + "/++resource++bika.lims.images/attachment_big.png"
        self.title = self.context.translate(_("Attachment Types"))
        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_column = True
        self.pagesize = 25

        self.columns = {
            'Title': {'title': _('Attachment Type'),
                      'index': 'sortable_title'},
            'Description': {'title': _('Description'),
                            'index': 'description',
                            'toggle': True},
        }
        self.review_states = [
            {'id':'default',
             'title': _('All'),
             'contentFilter':{},
             'columns': ['Title',
                         'Description']},
        ]
コード例 #8
0
ファイル: bika_samplematrices.py プロジェクト: nafwa03/olims
    def folderitems(self):
        mtool = getToolByName(self.context, 'portal_membership')
        if mtool.checkPermission(ManageBika, self.context):
            del self.review_states[0]['transitions']
            self.show_select_column = True
            self.review_states.append(
                {'id':'active',
                 'title': _('Active'),
                 'contentFilter': {'inactive_state': 'active'},
                 'transitions': [{'id':'deactivate'}, ],
                 'columns': ['Title', 'Description']})
            self.review_states.append(
                {'id':'inactive',
                 'title': _('Dormant'),
                 'contentFilter': {'inactive_state': 'inactive'},
                 'transitions': [{'id':'activate'}, ],
                 'columns': ['Title', 'Description']})

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

        return items
コード例 #9
0
    def __call__(self):
        ar = self.context
        workflow = getToolByName(ar, 'portal_workflow')

        # If is a retracted AR, show the link to child AR and show a warn msg
        if workflow.getInfoFor(ar, 'review_state') == 'invalid':
            childar = hasattr(ar, 'getChildAnalysisRequest') \
                        and ar.getChildAnalysisRequest() or None
            childid = childar and childar.getRequestID() or None
            message = _('This Analysis Request has been withdrawn and is shown '
                        'for trace-ability purposes only. Retest: ${retest_child_id}.',
                        mapping={"retest_child_id":childid if childid else ''})
            self.context.plone_utils.addPortalMessage(message, 'warning')

        # If is an AR automatically generated due to a Retraction, show it's
        # parent AR information
        if hasattr(ar, 'getParentAnalysisRequest') \
            and ar.getParentAnalysisRequest():
            par = ar.getParentAnalysisRequest()
            message = _(
                'This Analysis Request has been generated automatically due to '
                'the retraction of the Analysis Request ${retracted_request_id}.',
                mapping={"retracted_request_id": par.getRequestID()})
            self.context.plone_utils.addPortalMessage(message, 'info')

        can_do = getSecurityManager().checkPermission(ResultsNotRequested, ar)
        if workflow.getInfoFor(ar, 'cancellation_state') == "cancelled":
            self.request.response.redirect(ar.absolute_url())
        elif not(can_do):
            self.request.response.redirect(ar.absolute_url())
        else:
            return self.template()
コード例 #10
0
ファイル: analyses.py プロジェクト: nafwa03/olims
    def __init__(self, context, request, **kwargs):
        AnalysesView.__init__(self, context, request, **kwargs)
        self.columns['getReferenceAnalysesGroupID'] = {'title': _('QC Sample ID'),
                                                       'sortable': False}
        self.columns['Worksheet'] = {'title': _('Worksheet'),
                                                'sortable': False}
        self.review_states[0]['columns'] = ['Service',
                                            'Worksheet',
                                            'getReferenceAnalysesGroupID',
                                            'Partition',
                                            'Method',
                                            'Instrument',
                                            'Result',
                                            'Uncertainty',
                                            'CaptureDate',
                                            'DueDate',
                                            'state_title']

        qcanalyses = context.getQCAnalyses()
        asuids = [an.UID() for an in qcanalyses]
        self.catalog = 'bika_analysis_catalog'
        self.contentFilter = {'UID': asuids,
                              'sort_on': 'sortable_title'}
        self.icon = self.portal_url + \
                    "/++resource++bika.lims.images/referencesample.png"
コード例 #11
0
ファイル: serviceswidget.py プロジェクト: nafwa03/olims
    def __init__(self, context, request, field):
        BikaListingView.__init__(self, context, request)
        self.selected = [o.UID() for o in getattr(field, field.accessor)()]
        self.context_actions = {}
        self.catalog = "bika_setup_catalog"
        self.contentFilter = {'review_state': 'impossible_state'}
        self.base_url = self.context.absolute_url()
        self.view_url = self.base_url
        self.show_categories = True
        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_all_checkbox = False
        self.show_select_column = True
        self.pagesize = 999999
        self.form_id = 'serviceswidget'

        self.columns = {
            'Service': {'title': _('Service')},
            'Keyword': {'title': _('Keyword'),
                        'index': 'getKeyword'},
            'Method': {'title': _('Method')},
            'Calculation': {'title': _('Calculation')},
        }
        self.review_states = [
            {'id':'default',
             'title': _('All'),
             'contentFilter':{},
             'transitions': [],
             'columns':['Service',
                        'Keyword',
                        'Method',
                        'Calculation', ]
            },
        ]
コード例 #12
0
 def get_custom_fields(self):
     """ Returns a dictionary with custom fields to be rendered after
         header_table with this structure:
         {<fieldid>:{title:<title>, value:<html>}
     """
     custom = {}
     ar = self.context
     workflow = getToolByName(self.context, 'portal_workflow')
     # If is a retracted AR, show the link to child AR and show a warn msg
     if workflow.getInfoFor(ar, 'review_state') == 'invalid':
         childar = hasattr(ar, 'getChildAnalysisRequest') \
                     and ar.getChildAnalysisRequest() or None
         anchor = childar and (
             "<a href='%s'>%s</a>" %
             (childar.absolute_url(), childar.getRequestID())) or None
         if anchor:
             custom['ChildAR'] = {
                 'title': t(_("AR for retested results")),
                 'value': anchor
             }
     # If is an AR automatically generated due to a Retraction, show it's
     # parent AR information
     if hasattr(ar, 'getParentAnalysisRequest') \
         and ar.getParentAnalysisRequest():
         par = ar.getParentAnalysisRequest()
         anchor = "<a href='%s'>%s</a>" % (par.absolute_url(),
                                           par.getRequestID())
         custom['ParentAR'] = {
             'title': t(_("Invalid AR retested")),
             'value': anchor
         }
     return custom
コード例 #13
0
class CoordinateField(RecordField):
    """ Stores angle in deg, min, sec, bearing """
    security = ClassSecurityInfo()
    _properties = RecordField._properties.copy()
    _properties.update({
        'type':
        'angle',
        'subfields': ('degrees', 'minutes', 'seconds', 'bearing'),
        ##        'required_subfields' : ('degrees', 'minutes', 'seconds', 'bearing'),
        'subfield_labels': {
            'degrees': _('Degrees'),
            'minutes': _('Minutes'),
            'seconds': _('Seconds'),
            'bearing': _('Bearing')
        },
        'subfield_sizes': {
            'degrees': 3,
            'minutes': 2,
            'seconds': 2,
            'bearing': 1
        },
        'subfield_validators': {
            'degrees': 'coordinatevalidator',
            'minutes': 'coordinatevalidator',
            'seconds': 'coordinatevalidator',
            'bearing': 'coordinatevalidator',
        },
    })
コード例 #14
0
    def __init__(self, context, request, fieldvalue=[], allow_edit=False):
        super(AnalysisProfileAnalysesView, self).__init__(context, request)
        self.catalog = "bika_setup_catalog"
        self.contentFilter = {'portal_type': 'AnalysisService',
                              'sort_on': 'sortable_title',
                              'inactive_state': 'active',}
        self.context_actions = {}
        self.base_url = self.context.absolute_url()
        self.view_url = self.base_url
        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_all_checkbox = False
        self.show_column_toggles = False
        self.show_select_column = True
        self.allow_edit = allow_edit
        self.form_id = "analyses"
        self.profile = None

        self.categories = []
        self.do_cats = self.context.bika_setup.getCategoriseAnalysisServices()
        if self.do_cats:
            self.pagesize = 999999  # hide batching controls
            self.show_categories = True
            self.expand_all_categories = False
            self.ajax_categories = True
            self.ajax_categories_url = self.context.absolute_url() + \
                                       "/analysisprofile_analysesview"
            self.category_index = 'getCategoryTitle'

        self.columns = {
            'Title': {'title': _('Service'),
                      'index': 'sortable_title',
                      'sortable': False,},
            'Price': {'title': _('Price'),
                      'sortable': False,},
        }

        self.review_states = [
            {'id':'default',
             'title': _('All'),
             'contentFilter':{},
             'columns': ['Title',
                         'Price',
                         ],
             'transitions': [{'id':'empty'}, ], # none
             },
        ]

        self.fieldvalue = fieldvalue
        self.selected = [x.UID() for x in fieldvalue]

        if self.aq_parent.portal_type == 'AnalysisProfile':
            # Custom settings for the Analysis Services assigned to
            # the Analysis Profile
            # https://jira.bikalabs.com/browse/LIMS-1324
            self.profile = self.aq_parent
            self.columns['Hidden'] = {'title': _('Hidden'),
                                      'sortable': False,
                                      'type': 'boolean'}
            self.review_states[0]['columns'].insert(1, 'Hidden')
コード例 #15
0
ファイル: analysis.py プロジェクト: nafwa03/olims
 def __call__(self, result=None, **kwargs):
     translate = self.context.translate
     path = '++resource++bika.lims.images'
     alerts = {}
     # We look for IResultOutOfRange adapters for this object
     for name, adapter in getAdapters((self.context, ), IResultOutOfRange):
         ret = adapter(result)
         if not ret:
             continue
         spec = ret["spec_values"]
         rngstr = "{0} {1}, {2} {3}".format(
             t(_("min")), str(spec['min']),
             t(_("max")), str(spec['max']))
         if ret["out_of_range"]:
             if ret["acceptable"]:
                 message = "{0} ({1})".format(
                     t(_('Result in shoulder range')),
                     rngstr
                 )
                 icon = path + '/warning.png'
             else:
                 message = "{0} ({1})".format(
                     t(_('Result out of range')),
                     rngstr
                 )
                 icon = path + '/exclamation.png'
             alerts[self.context.UID()] = [
                 {
                     'icon': icon,
                     'msg': message,
                     'field': 'Result',
                 },
             ]
             break
     return alerts
コード例 #16
0
ファイル: __init__.py プロジェクト: pureboy8/OLiMS
    def parse_daterange(self, request, field_id, field_title):
        from_date = request.get('%s_fromdate' % field_id, None)
        from_date = from_date and from_date + ' 00:00' or None
        to_date = request.get('%s_todate' % field_id, None)
        to_date = to_date and to_date + ' 23:59' or None
        if from_date and to_date:
            query = {'query': [from_date, to_date], 'range': 'min:max'}
        elif from_date or to_date:
            query = {
                'query': from_date or to_date,
                'range': from_date and 'min' or 'max'
            }
        else:
            return None

        if from_date and to_date:
            parms = translate(
                _("From ${start_date} to ${end_date}",
                  mapping={
                      "start_date": from_date,
                      "end_date": to_date
                  }))
        elif from_date:
            parms = translate(
                _("Before ${start_date}", mapping={"start_date": from_date}))
        elif to_date:
            parms = translate(
                _("After ${end_date}", mapping={"end_date": to_date}))

        res = {}
        res['contentFilter'] = (field_id, query)
        res['parms'] = {'title': field_title, 'value': parms}
        res['titles'] = parms
        return res
コード例 #17
0
    def __init__(self, context, request):
        super(SamplingDeviationsView, self).__init__(context, request)
        self.catalog = 'bika_setup_catalog'
        self.contentFilter = {'portal_type': 'SamplingDeviation',
                              'sort_on': 'sortable_title'}
        self.context_actions = {_('Add'): {
            'url': 'createObject?type_name=SamplingDeviation',
            'icon': '++resource++bika.lims.images/add.png'
        }}
        self.title = self.context.translate(_("Sampling Deviations"))
        self.icon = self.portal_url + "/++resource++bika.lims.images/samplingdeviation_big.png"
        self.description = ""
        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_column = False
        self.pagesize = 25

        self.columns = {
            'Title': {'title': _('Sampling Deviation'),
                      'index': 'sortable_title'},
            'Description': {'title': _('Description'),
                            'index': 'description',
                            'toggle': True},
        }

        self.review_states = [
            {'id':'default',
             'title': _('All'),
             'contentFilter':{},
             'transitions':[{'id':'empty'},],
             'columns': ['Title', 'Description']},
        ]
コード例 #18
0
    def folderitems(self):
        mtool = getToolByName(self.context, 'portal_membership')
        if mtool.checkPermission(ManageBika, self.context):
            del self.review_states[0]['transitions']
            self.show_select_column = True
            self.review_states.append(
                {'id':'active',
                 'title': _('Active'),
                 'contentFilter': {'inactive_state': 'active'},
                 'transitions': [{'id':'deactivate'}, ],
                 'columns': ['Title', 'Description']})
            self.review_states.append(
                {'id':'inactive',
                 'title': _('Dormant'),
                 'contentFilter': {'inactive_state': 'inactive'},
                 'transitions': [{'id':'activate'}, ],
                 'columns': ['Title', 'Description']})

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

        return items
コード例 #19
0
ファイル: log.py プロジェクト: nafwa03/olims
 def __call__(self):
     ar = self.context
     workflow = getToolByName(ar, 'portal_workflow')
     # If is a retracted AR, show the link to child AR and show a warn msg
     if workflow.getInfoFor(ar, 'review_state') == 'invalid':
         childar = hasattr(ar, 'getChildAnalysisRequest') \
                     and ar.getChildAnalysisRequest() or None
         childid = childar and childar.getRequestID() or None
         message = _('This Analysis Request has been withdrawn and is shown '
                       'for trace-ability purposes only. Retest: '
                       '${retest_child_id}.',
                       mapping={'retest_child_id': safe_unicode(childid) or ''})
         self.context.plone_utils.addPortalMessage(message, 'warning')
     # If is an AR automatically generated due to a Retraction, show it's
     # parent AR information
     if hasattr(ar, 'getParentAnalysisRequest') \
         and ar.getParentAnalysisRequest():
         par = ar.getParentAnalysisRequest()
         message = _('This Analysis Request has been '
                     'generated automatically due to '
                     'the retraction of the Analysis '
                     'Request ${retracted_request_id}.',
                     mapping={'retracted_request_id': safe_unicode(par.getRequestID())})
         self.context.plone_utils.addPortalMessage(
             t(message), 'info')
     template = LogView.__call__(self)
     return template
コード例 #20
0
 def __call__(self):
     ar = self.context
     workflow = getToolByName(ar, 'portal_workflow')
     # If is a retracted AR, show the link to child AR and show a warn msg
     if workflow.getInfoFor(ar, 'review_state') == 'invalid':
         childar = hasattr(ar, 'getChildAnalysisRequest') \
                     and ar.getChildAnalysisRequest() or None
         childid = childar and childar.getRequestID() or None
         message = _(
             'This Analysis Request has been withdrawn and is shown '
             'for trace-ability purposes only. Retest: '
             '${retest_child_id}.',
             mapping={'retest_child_id': safe_unicode(childid) or ''})
         self.context.plone_utils.addPortalMessage(message, 'warning')
     # If is an AR automatically generated due to a Retraction, show it's
     # parent AR information
     if hasattr(ar, 'getParentAnalysisRequest') \
         and ar.getParentAnalysisRequest():
         par = ar.getParentAnalysisRequest()
         message = _(
             'This Analysis Request has been '
             'generated automatically due to '
             'the retraction of the Analysis '
             'Request ${retracted_request_id}.',
             mapping={
                 'retracted_request_id': safe_unicode(par.getRequestID())
             })
         self.context.plone_utils.addPortalMessage(t(message), 'info')
     template = LogView.__call__(self)
     return template
コード例 #21
0
    def __call__(self):
        ar = self.context
        workflow = getToolByName(ar, 'portal_workflow')

        # If is a retracted AR, show the link to child AR and show a warn msg
        if workflow.getInfoFor(ar, 'review_state') == 'invalid':
            childar = hasattr(ar, 'getChildAnalysisRequest') \
                        and ar.getChildAnalysisRequest() or None
            childid = childar and childar.getRequestID() or None
            message = _(
                'This Analysis Request has been withdrawn and is shown '
                'for trace-ability purposes only. Retest: ${retest_child_id}.',
                mapping={"retest_child_id": childid if childid else ''})
            self.context.plone_utils.addPortalMessage(message, 'warning')

        # If is an AR automatically generated due to a Retraction, show it's
        # parent AR information
        if hasattr(ar, 'getParentAnalysisRequest') \
            and ar.getParentAnalysisRequest():
            par = ar.getParentAnalysisRequest()
            message = _(
                'This Analysis Request has been generated automatically due to '
                'the retraction of the Analysis Request ${retracted_request_id}.',
                mapping={"retracted_request_id": par.getRequestID()})
            self.context.plone_utils.addPortalMessage(message, 'info')

        can_do = getSecurityManager().checkPermission(ResultsNotRequested, ar)
        if workflow.getInfoFor(ar, 'cancellation_state') == "cancelled":
            self.request.response.redirect(ar.absolute_url())
        elif not (can_do):
            self.request.response.redirect(ar.absolute_url())
        else:
            return self.template()
コード例 #22
0
ファイル: view.py プロジェクト: nafwa03/olims
 def get_custom_fields(self):
     """ Returns a dictionary with custom fields to be rendered after
         header_table with this structure:
         {<fieldid>:{title:<title>, value:<html>}
     """
     custom = {}
     ar = self.context
     workflow = getToolByName(self.context, 'portal_workflow')
     # If is a retracted AR, show the link to child AR and show a warn msg
     if workflow.getInfoFor(ar, 'review_state') == 'invalid':
         childar = hasattr(ar, 'getChildAnalysisRequest') \
                     and ar.getChildAnalysisRequest() or None
         anchor = childar and ("<a href='%s'>%s</a>" % (childar.absolute_url(), childar.getRequestID())) or None
         if anchor:
             custom['ChildAR'] = {
                 'title': t(_("AR for retested results")),
                 'value': anchor
             }
     # If is an AR automatically generated due to a Retraction, show it's
     # parent AR information
     if hasattr(ar, 'getParentAnalysisRequest') \
         and ar.getParentAnalysisRequest():
         par = ar.getParentAnalysisRequest()
         anchor = "<a href='%s'>%s</a>" % (par.absolute_url(), par.getRequestID())
         custom['ParentAR'] = {
             'title': t(_("Invalid AR retested")),
             'value': anchor
         }
     return custom
コード例 #23
0
    def __init__(self, context, request):
        super(SampleConditionsView, self).__init__(context, request)
        self.catalog = "bika_setup_catalog"
        self.contentFilter = {"portal_type": "SampleCondition", "sort_on": "sortable_title"}
        self.context_actions = {
            _("Add"): {"url": "createObject?type_name=SampleCondition", "icon": "++resource++bika.lims.images/add.png"}
        }
        self.title = self.context.translate(_("Sample Conditions"))
        self.icon = self.portal_url + "/++resource++bika.lims.images/samplecondition_big.png"
        self.description = ""
        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_column = False
        self.pagesize = 25

        self.columns = {
            "Title": {"title": _("Sample Condition"), "index": "sortable_title"},
            "Description": {"title": _("Description"), "index": "description", "toggle": True},
        }

        self.review_states = [
            {
                "id": "default",
                "title": _("All"),
                "contentFilter": {},
                "transitions": [{"id": "empty"}],
                "columns": ["Title", "Description"],
            }
        ]
コード例 #24
0
    def folderitems(self):
        mtool = getToolByName(self.context, "portal_membership")
        if mtool.checkPermission(ManageBika, self.context):
            del self.review_states[0]["transitions"]
            self.show_select_column = True
            self.review_states.append(
                {
                    "id": "active",
                    "title": _("Active"),
                    "contentFilter": {"inactive_state": "active"},
                    "transitions": [{"id": "deactivate"}],
                    "columns": ["Title", "Description"],
                }
            )
            self.review_states.append(
                {
                    "id": "inactive",
                    "title": _("Dormant"),
                    "contentFilter": {"inactive_state": "inactive"},
                    "transitions": [{"id": "activate"}],
                    "columns": ["Title", "Description"],
                }
            )

        items = BikaListingView.folderitems(self)
        for x in range(len(items)):
            if "obj" in items[x]:
                items[x]["replace"]["Title"] = "<a href='%s'>%s</a>" % (items[x]["url"], items[x]["Title"])

        return items
コード例 #25
0
    def __init__(self, context, request):
        super(ClientContactsView, self).__init__(context, request)
        self.catalog = "portal_catalog"
        self.contentFilter = {
            'portal_type': 'Contact',
            'sort_on':'sortable_title',
            'path': {
                "query": "/".join(context.getPhysicalPath()),
                "level" : 0
            }
        }
        self.context_actions = {_('Add'):
                                {'url': 'createObject?type_name=Contact',
                                 'icon': '++resource++bika.lims.images/add.png'}}
        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_column = True
        self.pagesize = 50
        self.form_id = "contacts"

        self.icon = self.portal_url + "/++resource++bika.lims.images/client_contact_big.png"
        self.title = self.context.translate(_("Contacts"))
        self.description = ""

        self.columns = {
            'getFullname': {'title': _('Full Name'),
                            'index': 'getFullname'},
            'Username': {'title': _('User Name')},
            'getEmailAddress': {'title': _('Email Address')},
            'getBusinessPhone': {'title': _('Business Phone')},
            'getMobilePhone': {'title': _('Mobile Phone')},
        }
        self.review_states = [
            {'id':'default',
             'title': _('Active'),
             'contentFilter': {'inactive_state': 'active'},
             'transitions': [{'id':'deactivate'}, ],
             'columns': ['getFullname',
                         'Username',
                         'getEmailAddress',
                         'getBusinessPhone',
                         'getMobilePhone']},
            {'id':'inactive',
             'title': _('Dormant'),
             'contentFilter': {'inactive_state': 'inactive'},
             'transitions': [{'id':'activate'}, ],
             'columns': ['getFullname',
                         'Username',
                         'getEmailAddress',
                         'getBusinessPhone',
                         'getMobilePhone']},
            {'id':'all',
             'title': _('All'),
             'contentFilter':{},
             'columns': ['getFullname',
                         'Username',
                         'getEmailAddress',
                         'getBusinessPhone',
                         'getMobilePhone']},
        ]
コード例 #26
0
ファイル: arimports.py プロジェクト: pureboy8/OLiMS
    def __call__(self):
        request = self.request
        response = request.response
        form = request.form
        CheckAuthenticator(form)
        if form.get('submitted'):
            csvfile = form.get('csvfile')
            option = form.get('ImportOption')
            client_id = form.get('ClientID')
            valid = False
            if option in ('c', 'p'):
                arimport, msg = self._import_file(option, csvfile, client_id)
            else:
                msg = "Import Option not yet available"
                IStatusMessage(request).addStatusMessage(_(msg), "warn")
                request.response.redirect('%s/arimports' % (
                    self.context.absolute_url()))
                return

            if arimport:
                msg = "AR Import complete"
                IStatusMessage(request).addStatusMessage(_(msg), "info")
                request.response.write(
                    '<script>document.location.href="%s"</script>' % (
                        arimport.absolute_url()))
                return
            else:
                IStatusMessage(request).addStatusMessage(_(msg), "error")
                request.response.write(
                    '<script>document.location.href="%s/arimport_add"</script>' % (self.context.absolute_url()))
                return
        return self.template()
コード例 #27
0
ファイル: bika_containers.py プロジェクト: nafwa03/olims
    def __init__(self, context, request):
        super(ContainersView, self).__init__(context, request)
        self.catalog = 'bika_setup_catalog'
        self.contentFilter = {'portal_type': 'Container',
                              'sort_on': 'sortable_title'}
        self.context_actions = {_('Add'):
                                {'url': 'createObject?type_name=Container',
                                 'icon': '++resource++bika.lims.images/add.png'}}
        self.title = self.context.translate(_("Containers"))
        self.icon = self.portal_url + "/++resource++bika.lims.images/container_big.png"
        self.description = ""
        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_column = True
        self.pagesize = 25

        self.columns = {
            'Title': {'title': _('Container'),
                      'index':'sortable_title'},
            'Description': {'title': _('Description'),
                            'index': 'description',
                            'toggle': True},
            'ContainerType': {'title': _('Container Type'),
                              'toggle': True},
            'Capacity': {'title': _('Capacity'),
                         'toggle': True},
            'Pre-preserved': {'title': _('Pre-preserved'),
                             'toggle': True},
        }

        self.review_states = [ # leave these titles and ids alone
            {'id':'default',
             'contentFilter': {'inactive_state':'active'},
             'title': _('Active'),
             'transitions': [{'id':'deactivate'}, ],
             'columns': ['Title',
                         'Description',
                         'ContainerType',
                         'Capacity',
                         'Pre-preserved']},
            {'id':'inactive',
             'title': _('Dormant'),
             'contentFilter': {'inactive_state': 'inactive'},
             'transitions': [{'id':'activate'}, ],
             'columns': ['Title',
                         'Description',
                         'ContainerType',
                         'Capacity',
                         'Pre-preserved']},
            {'id':'all',
             'title': _('All'),
             'contentFilter':{},
             'transitions': [],
             'columns': ['Title',
                         'Description',
                         'ContainerType',
                         'Capacity',
                         'Pre-preserved']},
        ]
コード例 #28
0
ファイル: workflow.py プロジェクト: nafwa03/olims
    def workflow_action_preserve(self):
        form = self.request.form
        workflow = getToolByName(self.context, 'portal_workflow')
        action, came_from = WorkflowAction._get_form_workflow_action(self)
        checkPermission = self.context.portal_membership.checkPermission
        # Partition Preservation
        # the partition table shown in AR and Sample views sends it's
        # action button submits here.
        objects = WorkflowAction._get_selected_items(self)
        transitioned = []
        incomplete = []
        for obj_uid, obj in objects.items():
            part = obj
            # can't transition inactive items
            if workflow.getInfoFor(part, 'inactive_state', '') == 'inactive':
                continue
            if not checkPermission(PreserveSample, part):
                continue
            # grab this object's Preserver and DatePreserved from the form
            Preserver = form['getPreserver'][0][obj_uid].strip()
            Preserver = Preserver and Preserver or ''
            DatePreserved = form['getDatePreserved'][0][obj_uid].strip()
            DatePreserved = DatePreserved and DateTime(DatePreserved) or ''
            # write them to the sample
            part.setPreserver(Preserver)
            part.setDatePreserved(DatePreserved)
            # transition the object if both values are present
            if Preserver and DatePreserved:
                workflow.doActionFor(part, action)
                transitioned.append(part.id)
            else:
                incomplete.append(part.id)
            part.reindexObject()
            part.aq_parent.reindexObject()
        message = None
        if len(transitioned) > 1:
            message = _('${items} are waiting to be received.',
                        mapping={'items': safe_unicode(', '.join(transitioned))})
            self.context.plone_utils.addPortalMessage(message, 'info')
        elif len(transitioned) == 1:
            message = _('${item} is waiting to be received.',
                        mapping={'item': safe_unicode(', '.join(transitioned))})
            self.context.plone_utils.addPortalMessage(message, 'info')
        if not message:
            message = _('No changes made.')
            self.context.plone_utils.addPortalMessage(message, 'info')

        if len(incomplete) > 1:
            message = _('${items} are missing Preserver or Date Preserved',
                        mapping={'items': safe_unicode(', '.join(incomplete))})
            self.context.plone_utils.addPortalMessage(message, 'error')
        elif len(incomplete) == 1:
            message = _('${item} is missing Preserver or Preservation Date',
                        mapping={'item': safe_unicode(', '.join(incomplete))})
            self.context.plone_utils.addPortalMessage(message, 'error')

        self.destination_url = self.request.get_header("referer",
                               self.context.absolute_url())
        self.request.response.redirect(self.destination_url)
コード例 #29
0
 def getMaintenanceTypes(self):
     """ Return the current list of maintenance types
     """
     types = [('Preventive', safe_unicode(_('Preventive')).encode('utf-8')),
              ('Repair', safe_unicode(_('Repair')).encode('utf-8')),
              ('Enhancement',
               safe_unicode(_('Enhancement')).encode('utf-8'))]
     return DisplayList(types)
コード例 #30
0
ファイル: dataimport.py プロジェクト: pureboy8/OLiMS
    def __init__(self, context, request):
        super(ImportView, self).__init__(context, request)

        self.icon = ""
        self.title = self.context.translate(_("Import"))
        self.description = self.context.translate(_("Select a data interface"))

        request.set('disable_border', 1)
コード例 #31
0
ファイル: dataimport.py プロジェクト: nafwa03/olims
    def __init__(self, context, request):
        super(ImportView, self).__init__(context, request)

        self.icon = ""
        self.title = self.context.translate(_("Import"))
        self.description = self.context.translate(_("Select a data interface"))

        request.set('disable_border', 1)
コード例 #32
0
ファイル: bika_arpriorities.py プロジェクト: nafwa03/olims
    def __init__(self, context, request):
        super(ARPrioritiesView, self).__init__(context, request)
        request.set('disable_plone.rightcolumn', 1)

        self.catalog = 'bika_setup_catalog'
        self.contentFilter = {
                'portal_type': 'ARPriority',
                'path': {'query': '/'.join(context.getPhysicalPath())},
                'sort_on': 'sortKey',
                }
        self.context_actions[_('Add')] = \
                {'url': 'createObject?type_name=ARPriority',
                 'icon': self.portal.absolute_url() +
                         '/++resource++bika.lims.images/add.png'}
        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_column = True
        self.pagesize = 50
        self.form_id = "arpriorities"

        self.icon = \
            self.portal_url + "/++resource++bika.lims.images/arpriority_big.png"
        self.title = self.context.translate(_("Analysis Request Priorities"))
        self.description = ""

        self.columns = {
            'title': {'title': _('Priority')},
            'sortKey': {'title': _('Sort Key')},
            'pricePremium': {'title': _('Premium')},
            'isDefault': {'title': _('Default')},
            'inactive_state': {'title': _('State')},
        }
        self.review_states = [
            {'id': 'default',
             'title': _('All'),
             'contentFilter': {},
             'columns': ['title',
                         'sortKey',
                         'pricePremium',
                         'isDefault',
                         'inactive_state']},
            {'id': 'draft',
             'title': _('Active'),
             'contentFilter': {'inactive_state': 'active'},
             'columns': ['title',
                         'sortKey',
                         'pricePremium',
                         'isDefault',
                         ]},
            {'id': 'inactive',
             'title': _('Inactive'),
             'contentFilter': {'inactive_state': 'inactive'},
             'columns': ['title',
                         'sortKey',
                         'pricePremium',
                         'isDefault',
                         ]},
        ]
コード例 #33
0
ファイル: header_table.py プロジェクト: nafwa03/olims
    def render_field_view(self, field):
        fieldname = field.getName()
        field = self.context.Schema()[fieldname]
        ret = {'fieldName': fieldname, 'mode': 'view'}
        try:
            adapter = getAdapter(self.context,
                                 interface=IHeaderTableFieldRenderer,
                                 name=fieldname)
        except ComponentLookupError:
            adapter = None
        if adapter:
            ret = {'fieldName': fieldname,
                   'mode': 'structure',
                   'html': adapter(field)}
        else:
            if field.getType().find("ool") > -1:
                value = field.get(self.context)
                ret = {'fieldName': fieldname,
                       'mode': 'structure',
                       'html': t(_('Yes')) if value else t(_('No'))
                }
            elif field.getType().find("Reference") > -1:
                # Prioritize method retrieval over schema's field
                targets = None
                if hasattr(self.context, 'get%s' % fieldname):
                    fieldaccessor = getattr(self.context, 'get%s' % fieldname)
                    if callable(fieldaccessor):
                        targets = fieldaccessor()
                if not targets:
                    targets = field.get(self.context)

                if targets:
                    if not type(targets) == list:
                        targets = [targets,]
                    sm = getSecurityManager()
                    if all([sm.checkPermission(view, ta) for ta in targets]):
                        a = ["<a href='%s'>%s</a>" % (target.absolute_url(),
                                                      target.Title())
                             for target in targets]
                        ret = {'fieldName': fieldname,
                               'mode': 'structure',
                               'html': ", ".join(a)}
                    else:
                        ret = {'fieldName': fieldname,
                               'mode': 'structure',
                               'html': ", ".join([ta.Title() for ta in targets])}
                else:
                    ret = {'fieldName': fieldname,
                           'mode': 'structure',
                           'html': ''}
            elif field.getType().lower().find('datetime') > -1:
                value = field.get(self.context)
                ret = {'fieldName': fieldname,
                       'mode': 'structure',
                       'html': self.ulocalized_time(value, long_format=True)
                }
        return ret
コード例 #34
0
ファイル: instrument.py プロジェクト: pureboy8/OLiMS
    def folderitems(self):
        items = BikaListingView.folderitems(self)
        valid = [c.UID() for c in self.context.getValidCertifications()]
        latest = self.context.getLatestValidCertification()
        latest = latest.UID() if latest else ''
        for x in range(len(items)):
            if not items[x].has_key('obj'): continue
            obj = items[x]['obj']
            # items[x]['getAgency'] = obj.getAgency()
            items[x]['getDate'] = self.ulocalized_time(obj.getDate(),
                                                       long_format=0)
            items[x]['getValidFrom'] = self.ulocalized_time(obj.getValidFrom(),
                                                            long_format=0)
            items[x]['getValidTo'] = self.ulocalized_time(obj.getValidTo(),
                                                          long_format=0)
            items[x]['replace']['Title'] = "<a href='%s'>%s</a>" % \
                 (items[x]['url'], items[x]['Title'])
            if obj.getInternal() == True:
                items[x]['replace']['getAgency'] = ""
                items[x]['state_class'] = '%s %s' % (items[x]['state_class'],
                                                     'internalcertificate')

            items[x]['getDocument'] = ""
            items[x]['replace']['getDocument'] = ""
            try:
                doc = obj.getDocument()
                if doc and doc.get_size() > 0:
                    anchor = "<a href='%s/at_download/Document'>%s</a>" % \
                            (obj.absolute_url(), doc.filename)
                    items[x]['getDocument'] = doc.filename
                    items[x]['replace']['getDocument'] = anchor
            except:
                # POSKeyError: 'No blob file'
                # Show the record, but not the link
                title = _('Not available')
                items[x]['getDocument'] = _('Not available')
                items[x]['replace']['getDocument'] = _('Not available')

            uid = obj.UID()
            if uid in valid:
                # Valid calibration.
                items[x]['state_class'] = '%s %s' % (items[x]['state_class'],
                                                     'active')
            elif uid == latest:
                # Latest valid certificate
                img = "<img title='%s' src='%s/++resource++bika.lims.images/exclamation.png'/>&nbsp;" \
                % (t(_('Out of date')), self.portal_url)
                items[x]['replace']['getValidTo'] = '%s %s' % (
                    items[x]['getValidTo'], img)
                items[x]['state_class'] = '%s %s' % (items[x]['state_class'],
                                                     'inactive outofdate')
            else:
                # Old and further calibrations
                items[x]['state_class'] = '%s %s' % (items[x]['state_class'],
                                                     'inactive')

        return items
コード例 #35
0
 def getMaintenanceTypes(self):
     """ Return the current list of maintenance types
     """
     types = [
         ("Preventive", safe_unicode(_("Preventive")).encode("utf-8")),
         ("Repair", safe_unicode(_("Repair")).encode("utf-8")),
         ("Enhancement", safe_unicode(_("Enhancement")).encode("utf-8")),
     ]
     return DisplayList(types)
コード例 #36
0
    def getTaskTypes(self):
        """ Return the current list of task types
        """
        types = [('Calibration', safe_unicode(_('Calibration')).encode('utf-8')),
                 ('Enhancement', safe_unicode(_('Enhancement')).encode('utf-8')),
                 ('Preventive',safe_unicode(_('Preventive')).encode('utf-8')),
                 ('Repair', safe_unicode(_('Repair')).encode('utf-8')),
                 ('Validation', safe_unicode(_('Validation')).encode('utf-8'))]

        return DisplayList(types)
コード例 #37
0
ファイル: validators.py プロジェクト: nafwa03/olims
    def __call__(self, value, *args, **kwargs):

        instance = kwargs['instance']
        request = kwargs.get('REQUEST', {})
        fieldname = kwargs['field'].getName()

        translate = getToolByName(instance, 'translation_service').translate

        mins = request.get('min', {})[0]
        maxs = request.get('max', {})[0]
        errors = request.get('error', {})[0]

        # We run through the validator once per form submit, and check all values
        # this value in request prevents running once per subfield value.
        key = instance.id + fieldname
        if instance.REQUEST.get(key, False):
            return True

        # Retrieve all AS uids
        for uid in mins.keys():

            # Foreach AS, check spec. input values
            minv = mins.get(uid, '') == '' and '0' or mins[uid]
            maxv = maxs.get(uid, '') == '' and '0' or maxs[uid]
            err = errors.get(uid, '') == '' and '0' or errors[uid]

            # Values must be numbers
            try:
                minv = float(minv)
            except ValueError:
                instance.REQUEST[key] = to_utf8(translate(_("Validation failed: Min values must be numeric")))
                return instance.REQUEST[key]
            try:
                maxv = float(maxv)
            except ValueError:
                instance.REQUEST[key] = to_utf8(translate(_("Validation failed: Max values must be numeric")))
                return instance.REQUEST[key]
            try:
                err = float(err)
            except ValueError:
                instance.REQUEST[key] = to_utf8(translate(_("Validation failed: Percentage error values must be numeric")))
                return instance.REQUEST[key]

            # Min value must be < max
            if minv > maxv:
                instance.REQUEST[key] = to_utf8(translate(_("Validation failed: Max values must be greater than Min values")))
                return instance.REQUEST[key]

            # Error percentage must be between 0 and 100
            if err < 0 or err > 100:
                instance.REQUEST[key] = to_utf8(translate(_("Validation failed: Error percentage must be between 0 and 100")))
                return instance.REQUEST[key]

        instance.REQUEST[key] = True
        return True
コード例 #38
0
ファイル: __init__.py プロジェクト: pureboy8/OLiMS
 def __call__(self, context):
     translate = context.translate
     types = (('AnalysisRequest',
               translate(to_utf8(_('Analysis Request')))),
              ('Batch', translate(to_utf8(_('Batch')))),
              ('Sample', translate(to_utf8(_('Sample')))),
              ('ReferenceSample',
               translate(to_utf8(_('Reference Sample')))),
              ('Worksheet', translate(to_utf8(_('Worksheet')))))
     items = [SimpleTerm(i[0], i[0], i[1]) for i in types]
     return SimpleVocabulary(items)
コード例 #39
0
ファイル: __init__.py プロジェクト: nafwa03/olims
 def __call__(self, context):
     translate = context.translate
     types = (
         ('AnalysisRequest', translate(to_utf8(_('Analysis Request')))),
         ('Batch',  translate(to_utf8(_('Batch')))),
         ('Sample',  translate(to_utf8(_('Sample')))),
         ('ReferenceSample',  translate(to_utf8(_('Reference Sample')))),
         ('Worksheet',  translate(to_utf8(_('Worksheet'))))
     )
     items = [SimpleTerm(i[0], i[0], i[1]) for i in types]
     return SimpleVocabulary(items)
コード例 #40
0
    def getTaskTypes(self):
        """ Return the current list of task types
        """
        types = [
            ('Calibration', safe_unicode(_('Calibration')).encode('utf-8')),
            ('Enhancement', safe_unicode(_('Enhancement')).encode('utf-8')),
            ('Preventive', safe_unicode(_('Preventive')).encode('utf-8')),
            ('Repair', safe_unicode(_('Repair')).encode('utf-8')),
            ('Validation', safe_unicode(_('Validation')).encode('utf-8'))
        ]

        return DisplayList(types)
コード例 #41
0
 def getCriteria(self):
     criteria = "";
     criterias = self.getScheduleCriteria()
     if criterias and len(criterias) > 0:
         crit = criterias[0]
         if crit['fromenabled'] == True and crit['fromdate']:
             criteria += _('From') + " " + crit['fromdate'] + " "
         if crit['repeatenabled'] == True and crit['repeatunit'] and crit['repeatperiod']:
             criteria += _("repeating every") + " " + crit['repeatunit'] + " " + _(crit['repeatperiod']) + " "
         if crit['repeatuntilenabled'] == True and crit['repeatuntil']:
             criteria += _("until") + " " + crit['repeatuntil']
     return criteria;
コード例 #42
0
ファイル: bika_samplepoints.py プロジェクト: nafwa03/olims
    def __call__(self):
        CheckAuthenticator(self.request)
        bsc = getToolByName(self.context, 'bika_setup_catalog')
        term = safe_unicode(self.request.get('term', '')).lower()
        items = []
        if not term:
            return json.dumps(items)
        # Strip "Lab: " from sample point title
        term = term.replace("%s: " % _("Lab"), '')
        sampletype = safe_unicode(self.request.get('sampletype', ''))
        if sampletype and len(sampletype) > 1:
            st = bsc(portal_type = "SampleType",
                     title = sampletype,
                     inactive_state = 'active')
            if not st:
                return json.dumps([])
            st = st[0].getObject()
            items = [o.Title() for o in st.getSamplePoints()]

        if not items:
            client_items = lab_items = []

            # User (client) sample points
            if self.context.portal_type in ('Client', 'AnalysisRequest'):
                if self.context.portal_type == 'Client':
                    client_path = self.context.getPhysicalPath()
                else:
                    client_path = self.context.aq_parent.getPhysicalPath()
                client_items = list(
                    bsc(portal_type = "SamplePoint",
                        path = {"query": "/".join(client_path), "level" : 0 },
                        inactive_state = 'active',
                        sort_on='sortable_title'))

            # Global (lab) sample points
            lab_path = self.context.bika_setup.bika_samplepoints.getPhysicalPath()
            lab_items = list(
                bsc(portal_type = "SamplePoint",
                    path = {"query": "/".join(lab_path), "level" : 0 },
                    inactive_state = 'active',
                    sort_on='sortable_title'))

            client_items = [callable(s.Title) and s.Title() or s.title
                     for s in self.filter_list(client_items, term)]
            lab_items = [callable(s.Title) and s.Title() or s.title
                     for s in self.filter_list(lab_items, term)]
            lab_items = ["%s: %s" % (_("Lab"), safe_unicode(i))
                         for i in lab_items]

            items = client_items + lab_items

        return json.dumps(items)
コード例 #43
0
ファイル: referencesample.py プロジェクト: pureboy8/OLiMS
        def make_title(o):
            # the javascript uses these strings to decide if it should
            # check the blank or hazardous checkboxes when a reference
            # definition is selected (./js/referencesample.js)
            if not o:
                return ''
            title = _u(o.Title())
            if o.getBlank():
                title += " %s" % t(_('(Blank)'))
            if o.getHazardous():
                title += " %s" % t(_('(Hazardous)'))

            return title
コード例 #44
0
ファイル: arimports.py プロジェクト: pureboy8/OLiMS
 def validate_arimport(self):
     """ validate the current ARImport object """
     request = self.request
     arimport = self.context
     if arimport.getImportOption() in ('c', 'p'):
         valid = arimport.validateIt()
         if not valid:
             msg = 'AR Import invalid'
             IStatusMessage(request).addStatusMessage(_(msg), "error")
     else:
         msg = 'validation not yet implemented'
         istatusmessage(request).addstatusmessage(_(msg), "error")
     request.response.redirect('%s/view' % arimport.absolute_url())
コード例 #45
0
ファイル: referencesample.py プロジェクト: rockfruit/OLiMS
        def make_title(o):
            # the javascript uses these strings to decide if it should
            # check the blank or hazardous checkboxes when a reference
            # definition is selected (./js/referencesample.js)
            if not o:
                return ''
            title = _u(o.Title())
            if o.getBlank():
                title += " %s" % t(_('(Blank)'))
            if o.getHazardous():
                title += " %s" % t(_('(Hazardous)'))

            return title
コード例 #46
0
ファイル: methods.py プロジェクト: nafwa03/olims
    def __init__(self, context, request):
        super(MethodsView, self).__init__(context, request)
        self.catalog = 'bika_setup_catalog'
        self.contentFilter = {'portal_type': 'Method',
                              'sort_on': 'sortable_title'}
        self.context_actions = {}
        self.title = self.context.translate(_("Methods"))
        self.icon = self.portal_url + "/++resource++bika.lims.images/method_big.png"
        self.description = ""
        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_column = True
        self.pagesize = 25

        self.columns = {
            'Title': {'title': _('Method'),
                      'index': 'sortable_title'},
            'Description': {'title': _('Description'),
                            'index': 'description',
                            'toggle': True},
            'Instrument': {'title': _('Instrument'),
                             'toggle': True},
            'Calculation': {'title': _('Calculation'),
                             'toggle': True},
            'ManualEntry': {'title': _('Manual entry'),
                             'toggle': True},
        }

        self.review_states = [
            {'id':'default',
             'title': _('Active'),
             'contentFilter': {'inactive_state': 'active'},
             'transitions': [{'id':'deactivate'}, ],
             'columns': ['Title', 
                         'Description', 
                         'Instrument',
                         'Calculation',
                         'ManualEntry']},
            {'id':'inactive',
             'title': _('Dormant'),
             'contentFilter': {'inactive_state': 'inactive'},
             'transitions': [{'id':'activate'}, ],
             'columns': ['Title', 
                         'Description', 
                         'Instrument',
                         'Calculation',
                         'ManualEntry']},
            {'id':'all',
             'title': _('All'),
             'contentFilter':{},
             'columns': ['Title', 
                         'Description', 
                         'Instrument',
                         'Calculation',
                         'ManualEntry']},
        ]
コード例 #47
0
class ReferenceResultsField(RecordsField):

    """a list of reference sample results """
    _properties = RecordsField._properties.copy()
    _properties.update({
        'type': 'referenceresult',
        'subfields': ('uid', 'result', 'min', 'max', 'error'),
        'subfield_labels': {'uid': _('Analysis Service'),
                           'result': _('Expected Result'),
                           'error': _('Permitted Error %'),
                           'min': _('Min'),
                           'max': _('Max')},
        })
    security = ClassSecurityInfo()
コード例 #48
0
ファイル: sample.py プロジェクト: pureboy8/OLiMS
 def __init__(self, context, request, **kwargs):
     AnalysesView.__init__(self, context, request)
     self.show_select_column = False
     self.allow_edit = False
     self.show_workflow_action_buttons = False
     for k, v in kwargs.items():
         self.contentFilter[k] = v
     self.columns['Request'] = {'title': _("Request"), 'sortable': False}
     self.columns['Priority'] = {'title': _("Priority"), 'sortable': False}
     # Add Request and Priority columns
     pos = self.review_states[0]['columns'].index('Service') + 1
     self.review_states[0]['columns'].insert(pos, 'Request')
     pos += 1
     self.review_states[0]['columns'].insert(pos, 'Priority')
コード例 #49
0
    def __call__(self, value, *args, **kwargs):
        instance = kwargs['instance']
        # fieldname = kwargs['field'].getName()
        # request = kwargs.get('REQUEST', {})
        # form = request.get('form', {})

        translate = getToolByName(instance, 'translation_service').translate

        if re.findall(r"[^A-Za-z\w\d\-\_]", value):
            return _("Validation failed: keyword contains invalid characters")

        # check the value against all AnalysisService keywords
        # this has to be done from catalog so we don't
        # clash with ourself
        bsc = getToolByName(instance, 'bika_setup_catalog')
        services = bsc(portal_type='AnalysisService', getKeyword=value)
        for service in services:
            if service.UID != instance.UID():
                msg = _(
                    "Validation failed: '${title}': This keyword "
                    "is already in use by service '${used_by}'",
                    mapping={
                        'title': safe_unicode(value),
                        'used_by': safe_unicode(service.Title)
                    })
                return to_utf8(translate(msg))

        calc = hasattr(instance, 'getCalculation') and \
            instance.getCalculation() or None
        our_calc_uid = calc and calc.UID() or ''

        # check the value against all Calculation Interim Field ids
        calcs = [c for c in bsc(portal_type='Calculation')]
        for calc in calcs:
            calc = calc.getObject()
            interim_fields = calc.getInterimFields()
            if not interim_fields:
                continue
            for field in interim_fields:
                if field['keyword'] == value and our_calc_uid != calc.UID():
                    msg = _(
                        "Validation failed: '${title}': This keyword "
                        "is already in use by calculation '${used_by}'",
                        mapping={
                            'title': safe_unicode(value),
                            'used_by': safe_unicode(calc.Title())
                        })
                    return to_utf8(translate(msg))
        return True
コード例 #50
0
 def getCriteria(self):
     criteria = ""
     criterias = self.getScheduleCriteria()
     if criterias and len(criterias) > 0:
         crit = criterias[0]
         if crit['fromenabled'] == True and crit['fromdate']:
             criteria += _('From') + " " + crit['fromdate'] + " "
         if crit['repeatenabled'] == True and crit['repeatunit'] and crit[
                 'repeatperiod']:
             criteria += _(
                 "repeating every") + " " + crit['repeatunit'] + " " + _(
                     crit['repeatperiod']) + " "
         if crit['repeatuntilenabled'] == True and crit['repeatuntil']:
             criteria += _("until") + " " + crit['repeatuntil']
     return criteria
コード例 #51
0
 def __call__(self, result=None, specification=None, **kwargs):
     workflow = getToolByName(self.context, 'portal_workflow')
     astate = workflow.getInfoFor(self.context, 'review_state')
     if astate == 'retracted':
         return {}
     result = self.context.getResult() if result is None else result
     alerts = {}
     path = '++resource++bika.lims.images'
     uid = self.context.UID()
     try:
         indet = result.startswith("<") or result.startswith(">")
     except AttributeError:
         indet = False
     if indet:
         alert = {
             'field': 'Result',
             'icon': path + '/exclamation.png',
             'msg': t(_("Indeterminate result"))
         }
         if uid in alerts:
             alerts[uid].append(alert)
         else:
             alerts[uid] = [
                 alert,
             ]
     return alerts
コード例 #52
0
ファイル: validators.py プロジェクト: nafwa03/olims
    def __call__(self, value, *args, **kwargs):
        instance = kwargs['instance']
        # fieldname = kwargs['field'].getName()
        # request = kwargs.get('REQUEST', {})
        # form = request.get('form', {})

        translate = getToolByName(instance, 'translation_service').translate
        bsc = getToolByName(instance, 'bika_setup_catalog')
        # uc = getToolByName(instance, 'uid_catalog')

        failures = []

        for category in value:
            if not category:
                continue
            services = bsc(portal_type="AnalysisService",
                           getCategoryUID=category)
            for service in services:
                service = service.getObject()
                calc = service.getCalculation()
                deps = calc and calc.getDependentServices() or []
                for dep in deps:
                    if dep.getCategoryUID() not in value:
                        title = dep.getCategoryTitle()
                        if title not in failures:
                            failures.append(title)
        if failures:
            msg = _("Validation failed: The selection requires the following "
                    "categories to be selected: ${categories}",
                    mapping={'categories': safe_unicode(','.join(failures))})
            return to_utf8(translate(msg))

        return True
コード例 #53
0
    def __call__(self):
        form = self.request.form
        bsc = getToolByName(self.context, 'bika_setup_catalog')

        # find and remove existing specs
        cs = bsc(portal_type = 'AnalysisSpec',
                  getClientUID = self.context.UID())
        if cs:
            self.context.manage_delObjects([s.id for s in cs])

        # find and duplicate lab specs
        ls = bsc(portal_type = 'AnalysisSpec',
                 getClientUID = self.context.bika_setup.bika_analysisspecs.UID())
        ls = [s.getObject() for s in ls]
        for labspec in ls:
            clientspec = _createObjectByType("AnalysisSpec", self.context, tmpID())
            clientspec.processForm()
            clientspec.edit(
                SampleType = labspec.getSampleType(),
                ResultsRange = labspec.getResultsRange(),
            )
        translate = self.context.translate
        message = _("Analysis specifications reset to lab defaults.")
        self.context.plone_utils.addPortalMessage(message, 'info')
        self.request.RESPONSE.redirect(self.context.absolute_url() +
                                       "/analysisspecs")
        return
コード例 #54
0
 def get_methods_vocabulary(self, analysis=None):
     """ Returns a vocabulary with the methods available for the
         analysis specified.
         If the service has the getInstrumentEntryOfResults(), returns
         the methods available from the instruments capable to perform
         the service, as well as the methods set manually for the
         analysis on its edit view. If getInstrumentEntryOfResults()
         is unset, only the methods assigned manually to that service
         are returned. If the Analysis service method is set to None,
         but have also at least one method available, adds the 'None'
         option to the vocabulary.
         If the analysis is None, retrieves all the
         active methods from the catalog.
     """
     ret = []
     if analysis:
         service = analysis.getService()
         methods = service.getAvailableMethods()
         if methods and not service.getMethod():
             ret.append({'ResultValue': '', 'ResultText': _('None')})
         for method in methods:
             ret.append({
                 'ResultValue': method.UID(),
                 'ResultText': method.Title()
             })
     else:
         # All active methods
         bsc = getToolByName(self.context, 'bika_setup_catalog')
         brains = bsc(portal_type='Method', inactive_state='active')
         for brain in brains:
             ret.append({
                 'ResultValue': brain.UID,
                 'ResultText': brain.title
             })
     return ret
コード例 #55
0
    def __call__(self, value, *args, **kwargs):
        instance = kwargs['instance']
        fieldname = kwargs['field'].getName()
        # request = kwargs.get('REQUEST', {})
        # form = request.get('form', {})

        translate = getToolByName(instance, 'translation_service').translate

        if value == instance.get(fieldname):
            return True

        for item in aq_parent(instance).objectValues():
            if hasattr(item, 'UID') and item.UID() != instance.UID() and \
               fieldname in item.Schema() and \
               str(item.Schema()[fieldname].get(item)) == str(value):   # We have to compare them as strings because
                # even if a number (as an  id) is saved inside
                # a string widget and string field, it will be
                # returned as an int. I don't know if it is
                # caused because is called with
                # <item.Schema()[fieldname].get(item)>,
                # but it happens...
                msg = _("Validation failed: '${value}' is not unique",
                        mapping={'value': safe_unicode(value)})
                return to_utf8(translate(msg))
        return True
コード例 #56
0
ファイル: instrument.py プロジェクト: pureboy8/OLiMS
 def __init__(self, context, request):
     super(InstrumentReferenceAnalysesViewView,
           self).__init__(context, request)
     self.icon = self.portal_url + "/++resource++bika.lims.images/referencesample_big.png"
     self.title = self.context.translate(_("Internal Calibration Tests"))
     self.description = ""
     self._analysesview = None
コード例 #57
0
    def generate_id(self, portal_type, batch_size = None):
        """ Generate a new id for 'portal_type'
        """
        plone = getSite()
        portal_id = plone.getId()

        if portal_type == 'News Item':
            portal_type = 'NewsItem'

        idserver_url = os.environ.get('IDServerURL')
        try:
            if batch_size:
                # GET
                f = urllib.urlopen('%s/%s%s?%s' % (
                        idserver_url,
                        portal_id,
                        portal_type,
                        urllib.urlencode({'batch_size': batch_size}))
                        )
            else:
                f = urllib.urlopen('%s/%s%s' % (
                    idserver_url, portal_id, portal_type
                    )
                )
            id = f.read()
            f.close()
        except:
            from sys import exc_info
            info = exc_info()
            import zLOG; zLOG.LOG('INFO', 0, '', 'generate_id raised exception: %s, %s \n idserver_url: %s' % (info[0], info[1], idserver_url))
            raise IDServerUnavailable(_('ID Server unavailable'))
        return id
コード例 #58
0
    def __call__(self, value, *args, **kwargs):
        instance = kwargs['instance']
        # fieldname = kwargs['field'].getName()
        # request = kwargs.get('REQUEST', {})
        # form = request.get('form', {})

        translate = getToolByName(instance, 'translation_service').translate
        bsc = getToolByName(instance, 'bika_setup_catalog')
        # uc = getToolByName(instance, 'uid_catalog')

        failures = []

        for category in value:
            if not category:
                continue
            services = bsc(portal_type="AnalysisService",
                           getCategoryUID=category)
            for service in services:
                service = service.getObject()
                calc = service.getCalculation()
                deps = calc and calc.getDependentServices() or []
                for dep in deps:
                    if dep.getCategoryUID() not in value:
                        title = dep.getCategoryTitle()
                        if title not in failures:
                            failures.append(title)
        if failures:
            msg = _(
                "Validation failed: The selection requires the following "
                "categories to be selected: ${categories}",
                mapping={'categories': safe_unicode(','.join(failures))})
            return to_utf8(translate(msg))

        return True