Exemplo n.º 1
0
    def _lab_data(self):
        """ Returns a dictionary that represents the lab object
            Keys: obj, title, url, address, confidence, accredited,
                  accreditation_body, accreditation_logo, logo
        """
        portal = self.context.portal_url.getPortalObject()
        lab = self.context.bika_setup.laboratory
        lab_address = lab.getPostalAddress() \
                        or lab.getBillingAddress() \
                        or lab.getPhysicalAddress()
        if lab_address:
            _keys = ['address', 'city', 'state', 'zip', 'country']
            _list = ["<div>%s</div>" % lab_address.get(v) for v in _keys
                     if lab_address.get(v)]
            lab_address = "".join(_list)
        else:
            lab_address = ''

        return {'obj': lab,
                'title': to_utf8(lab.Title()),
                'url': to_utf8(lab.getLabURL()),
                'address': to_utf8(lab_address),
                'confidence': lab.getConfidence(),
                'accredited': lab.getLaboratoryAccredited(),
                'accreditation_body': to_utf8(lab.getAccreditationBody()),
                'accreditation_logo': lab.getAccreditationBodyLogo(),
                'logo': "%s/logo_print.png" % portal.absolute_url()}
Exemplo n.º 2
0
    def _client_data(self, ar):
        data = {}
        client = ar.aq_parent
        if client:
            data['obj'] = client
            data['id'] = client.id
            data['url'] = client.absolute_url()
            data['name'] = to_utf8(client.getName())
            data['phone'] = to_utf8(client.getPhone())
            data['fax'] = to_utf8(client.getFax())

            client_address = client.getPostalAddress()
            if not client_address:
                # Data from the first contact
                contact = self.getAnalysisRequest().getContact()
                if contact and contact.getBillingAddress():
                    client_address = contact.getBillingAddress()
                elif contact and contact.getPhysicalAddress():
                    client_address = contact.getPhysicalAddress()

            if client_address:
                _keys = ['address', 'city', 'state', 'zip', 'country']
                _list = ["<div>%s</div>" % client_address.get(v) for v in _keys
                         if client_address.get(v)]
                client_address = "".join(_list)
            else:
                client_address = ''
            data['address'] = to_utf8(client_address)
        return data
Exemplo n.º 3
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
Exemplo n.º 4
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
Exemplo n.º 5
0
    def _lab_data(self):
        """ Returns a dictionary that represents the lab object
            Keys: obj, title, url, address, confidence, accredited,
                  accreditation_body, accreditation_logo, logo
        """
        portal = self.context.portal_url.getPortalObject()
        lab = self.context.bika_setup.laboratory
        lab_address = lab.getPostalAddress() \
                        or lab.getBillingAddress() \
                        or lab.getPhysicalAddress()
        if lab_address:
            _keys = ['address', 'city', 'state', 'zip', 'country']
            _list = [
                "<div>%s</div>" % lab_address.get(v) for v in _keys
                if lab_address.get(v)
            ]
            lab_address = "".join(_list)
        else:
            lab_address = ''

        return {
            'obj': lab,
            'title': to_utf8(lab.Title()),
            'url': to_utf8(lab.getLabURL()),
            'address': to_utf8(lab_address),
            'confidence': lab.getConfidence(),
            'accredited': lab.getLaboratoryAccredited(),
            'accreditation_body': to_utf8(lab.getAccreditationBody()),
            'accreditation_logo': lab.getAccreditationBodyLogo(),
            'logo': "%s/logo_print.png" % portal.absolute_url()
        }
Exemplo n.º 6
0
    def _client_data(self, ar):
        data = {}
        client = ar.aq_parent
        if client:
            data['obj'] = client
            data['id'] = client.id
            data['url'] = client.absolute_url()
            data['name'] = to_utf8(client.getName())
            data['phone'] = to_utf8(client.getPhone())
            data['fax'] = to_utf8(client.getFax())

            client_address = client.getPostalAddress()
            if not client_address:
                # Data from the first contact
                contact = self.getAnalysisRequest().getContact()
                if contact and contact.getBillingAddress():
                    client_address = contact.getBillingAddress()
                elif contact and contact.getPhysicalAddress():
                    client_address = contact.getPhysicalAddress()

            if client_address:
                _keys = ['address', 'city', 'state', 'zip', 'country']
                _list = [
                    "<div>%s</div>" % client_address.get(v) for v in _keys
                    if client_address.get(v)
                ]
                client_address = "".join(_list)
            else:
                client_address = ''
            data['address'] = to_utf8(client_address)
        return data
Exemplo n.º 7
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
Exemplo n.º 8
0
 def _createdby_data(self, ws):
     """ Returns a dict that represents the user who created the ws
         Keys: username, fullmame, email
     """
     username = ws.getOwner().getUserName()
     return {'username': username,
             'fullname': to_utf8(self.user_fullname(username)),
             'email': to_utf8(self.user_email(username))}
Exemplo n.º 9
0
 def _analyst_data(self, ws):
     """ Returns a dict that represent the analyst assigned to the
         worksheet.
         Keys: username, fullname, email
     """
     username = ws.getAnalyst();
     return {'username': username,
             'fullname': to_utf8(self.user_fullname(username)),
             'email': to_utf8(self.user_email(username))}
Exemplo n.º 10
0
 def _contact_data(self, ar):
     data = {}
     contact = ar.getContact()
     if contact:
         data = {'obj': contact,
                 'fullname': to_utf8(contact.getFullname()),
                 'email': to_utf8(contact.getEmailAddress()),
                 'pubpref': contact.getPublicationPreference()}
     return data
Exemplo n.º 11
0
 def _createdby_data(self, ws):
     """ Returns a dict that represents the user who created the ws
         Keys: username, fullmame, email
     """
     username = ws.getOwner().getUserName()
     return {
         'username': username,
         'fullname': to_utf8(self.user_fullname(username)),
         'email': to_utf8(self.user_email(username))
     }
Exemplo n.º 12
0
    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
Exemplo n.º 13
0
 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)
Exemplo n.º 14
0
 def _analyst_data(self, ws):
     """ Returns a dict that represent the analyst assigned to the
         worksheet.
         Keys: username, fullname, email
     """
     username = ws.getAnalyst()
     return {
         'username': username,
         'fullname': to_utf8(self.user_fullname(username)),
         'email': to_utf8(self.user_email(username))
     }
Exemplo n.º 15
0
 def _contact_data(self, ar):
     data = {}
     contact = ar.getContact()
     if contact:
         data = {
             'obj': contact,
             'fullname': to_utf8(contact.getFullname()),
             'email': to_utf8(contact.getEmailAddress()),
             'pubpref': contact.getPublicationPreference()
         }
     return data
Exemplo n.º 16
0
 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)
Exemplo n.º 17
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
Exemplo n.º 18
0
Arquivo: log.py Projeto: nafwa03/olims
    def __init__(self, context, request):
        BikaListingView.__init__(self, context, request)

        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_column = False
        self.show_workflow_action_buttons = False
        self.pagesize = 999999

        self.icon = self.portal_url + "/++resource++bika.lims.images/%s_big.png" % \
            context.portal_type.lower()
        self.title = to_utf8(self.context.Title()) + " " + t(_("Log"))
        self.description = ""

        self.columns = {
            'Version': {'title': _('Version'), 'sortable': False},
            'Date': {'title': _('Date'), 'sortable': False},
            'User': {'title': _('User'), 'sortable': False},
            'Action': {'title': _('Action'), 'sortable': False},
            'Description': {'title': _('Description'), 'sortable': False},
        }
        self.review_states = [
            {'id': 'default',
             'title': 'All',
             'contentFilter': {},
             'columns': ['Version',
                         'Date',
                         'User',
                         'Action',
                         'Description']},
        ]
Exemplo n.º 19
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
Exemplo n.º 20
0
    def _managers_data(self, ar):
        managers = {'ids': [], 'dict': {}}
        departments = {}
        ar_mngrs = ar.getResponsible()
        for id in ar_mngrs['ids']:
            new_depts = ar_mngrs['dict'][id]['departments'].split(',')
            if id in managers['ids']:
                for dept in new_depts:
                    if dept not in departments[id]:
                        departments[id].append(dept)
            else:
                departments[id] = new_depts
                managers['ids'].append(id)
                managers['dict'][id] = ar_mngrs['dict'][id]

        mngrs = departments.keys()
        for mngr in mngrs:
            final_depts = ''
            for dept in departments[mngr]:
                if final_depts:
                    final_depts += ', '
                final_depts += to_utf8(dept)
            managers['dict'][mngr]['departments'] = final_depts

        return managers
Exemplo n.º 21
0
    def _managers_data(self, ar):
        managers = {'ids': [], 'dict': {}}
        departments = {}
        ar_mngrs = ar.getResponsible()
        for id in ar_mngrs['ids']:
            new_depts = ar_mngrs['dict'][id]['departments'].split(',')
            if id in managers['ids']:
                for dept in new_depts:
                    if dept not in departments[id]:
                        departments[id].append(dept)
            else:
                departments[id] = new_depts
                managers['ids'].append(id)
                managers['dict'][id] = ar_mngrs['dict'][id]

        mngrs = departments.keys()
        for mngr in mngrs:
            final_depts = ''
            for dept in departments[mngr]:
                if final_depts:
                    final_depts += ', '
                final_depts += to_utf8(dept)
            managers['dict'][mngr]['departments'] = final_depts

        return managers
Exemplo n.º 22
0
    def localise_images(self, htmlreport):
        """WeasyPrint will attempt to retrieve attachments directly from the URL
        referenced in the HTML report, which may refer back to a single-threaded
        (and currently occupied) zeoclient, hanging it.  All "attachments"
        using urls ending with at_download/AttachmentFile must be converted
        to local files.

        Returns a list of files which were created, and a modified copy
        of htmlreport.
        """
        cleanup = []

        _htmltext = to_utf8(htmlreport)
        # first regular image tags
        for match in re.finditer("""http.*at_download\/AttachmentFile""", _htmltext, re.I):
            url = match.group()
            att_path = url.replace(self.portal_url+"/", "")
            attachment = self.portal.unrestrictedTraverse(att_path)
            af = attachment.getAttachmentFile()
            filename = af.filename
            extension = "."+filename.split(".")[-1]
            outfile, outfilename = tempfile.mkstemp(suffix=extension)
            outfile = open(outfilename, 'wb')
            outfile.write(str(af.data))
            outfile.close()
            _htmltext.replace(url, outfilename)
            cleanup.append(outfilename)
        return cleanup, _htmltext
Exemplo n.º 23
0
    def localise_images(self, htmlreport):
        """WeasyPrint will attempt to retrieve attachments directly from the URL
        referenced in the HTML report, which may refer back to a single-threaded
        (and currently occupied) zeoclient, hanging it.  All "attachments"
        using urls ending with at_download/AttachmentFile must be converted
        to local files.

        Returns a list of files which were created, and a modified copy
        of htmlreport.
        """
        cleanup = []

        _htmltext = to_utf8(htmlreport)
        # first regular image tags
        for match in re.finditer("""http.*at_download\/AttachmentFile""",
                                 _htmltext, re.I):
            url = match.group()
            att_path = url.replace(self.portal_url + "/", "")
            attachment = self.portal.unrestrictedTraverse(att_path)
            af = attachment.getAttachmentFile()
            filename = af.filename
            extension = "." + filename.split(".")[-1]
            outfile, outfilename = tempfile.mkstemp(suffix=extension)
            outfile = open(outfilename, 'wb')
            outfile.write(str(af.data))
            outfile.close()
            _htmltext.replace(url, outfilename)
            cleanup.append(outfilename)
        return cleanup, _htmltext
Exemplo n.º 24
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
Exemplo n.º 25
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
Exemplo n.º 26
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
Exemplo n.º 27
0
    def _batch_data(self, ar):
        data = {}
        batch = ar.getBatch()
        if batch:
            data = {'obj': batch,
                    'id': batch.id,
                    'url': batch.absolute_url(),
                    'title': to_utf8(batch.Title()),
                    'date': batch.getBatchDate(),
                    'client_batchid': to_utf8(batch.getClientBatchID()),
                    'remarks': to_utf8(batch.getRemarks())}

            uids = batch.Schema()['BatchLabels'].getAccessor(batch)()
            uc = getToolByName(self.context, 'uid_catalog')
            data['labels'] = [to_utf8(p.getObject().Title()) for p in uc(UID=uids)]

        return data
Exemplo n.º 28
0
    def _reporter_data(self, ar):
        data = {}
        member = self.context.portal_membership.getAuthenticatedMember()
        if member:
            username = member.getUserName()
            data['username'] = username
            data['fullname'] = to_utf8(self.user_fullname(username))
            data['email'] = to_utf8(self.user_email(username))

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

        return data
Exemplo n.º 29
0
    def get_recipients(self, ar):
        """ Returns a list with the recipients and all its publication prefs
        """
        recips = []

        # Contact and CC's
        contact = ar.getContact()
        if contact:
            recips.append({'title': to_utf8(contact.Title()),
                           'email': contact.getEmailAddress(),
                           'pubpref': contact.getPublicationPreference()})
        for cc in ar.getCCContact():
            recips.append({'title': to_utf8(cc.Title()),
                           'email': cc.getEmailAddress(),
                           'pubpref': contact.getPublicationPreference()})

        return recips
Exemplo n.º 30
0
 def _sampler_data(self, sample=None):
     data = {}
     if not sample or not sample.getSampler():
         return data
     sampler = sample.getSampler()
     mtool = getToolByName(self, 'portal_membership')
     member = mtool.getMemberById(sampler)
     if member:
         mfullname = member.getProperty('fullname')
         memail = member.getProperty('email')
         mhomepage = member.getProperty('home_page')
         pc = getToolByName(self, 'portal_catalog')
         c = pc(portal_type='Contact', getUsername=member.id)
         c = c[0].getObject() if c else None
         cfullname = c.getFullname() if c else None
         cemail = c.getEmailAddress() if c else None
         data = {'id': member.id,
                 'fullname': to_utf8(cfullname) if cfullname else to_utf8(mfullname),
                 'email': cemail if cemail else memail,
                 'business_phone': c.getBusinessPhone() if c else '',
                 'business_fax': c.getBusinessFax() if c else '',
                 'home_phone': c.getHomePhone() if c else '',
                 'mobile_phone': c.getMobilePhone() if c else '',
                 'job_title': to_utf8(c.getJobTitle()) if c else '',
                 'department': to_utf8(c.getDepartment()) if c else '',
                 'physical_address': to_utf8(c.getPhysicalAddress()) if c else '',
                 'postal_address': to_utf8(c.getPostalAddress()) if c else '',
                 'home_page': to_utf8(mhomepage)}
     return data
Exemplo n.º 31
0
    def __call__(self, value, *args, **kwargs):
        if not value:
            return True
        instance = kwargs['instance']
        # fieldname = kwargs['field'].getName()
        request = kwargs.get('REQUEST', {})
        form = request.form
        interim_fields = form.get('InterimFields')

        translate = getToolByName(instance, 'translation_service').translate
        bsc = getToolByName(instance, 'bika_setup_catalog')
        interim_keywords = interim_fields and \
            [f['keyword'] for f in interim_fields] or []
        keywords = re.compile(r"\[([^\.^\]]+)\]").findall(value)

        for keyword in keywords:
            # Check if the service keyword exists and is active.
            dep_service = bsc(getKeyword=keyword, inactive_state="active")
            if not dep_service and \
               not keyword in interim_keywords:
                msg = _("Validation failed: Keyword '${keyword}' is invalid",
                        mapping={'keyword': safe_unicode(keyword)})
                return to_utf8(translate(msg))

        # Wildcards
        # LIMS-1769 Allow to use LDL and UDL in calculations
        # https://jira.bikalabs.com/browse/LIMS-1769
        allowedwds = ['LDL', 'UDL', 'BELOWLDL', 'ABOVEUDL']
        keysandwildcards = re.compile(r"\[([^\]]+)\]").findall(value)
        keysandwildcards = [k for k in keysandwildcards if '.' in k]
        keysandwildcards = [k.split('.', 1) for k in keysandwildcards]
        errwilds = [k[1] for k in keysandwildcards if k[0] not in keywords]
        if len(errwilds) > 0:
            msg = _("Wildcards for interims are not allowed: ${wildcards}",
                    mapping={'wildcards': safe_unicode(', '.join(errwilds))})
            return to_utf8(translate(msg))

        wildcards = [k[1] for k in keysandwildcards if k[0] in keywords]
        wildcards = [wd for wd in wildcards if wd not in allowedwds]
        if len(wildcards) > 0:
            msg = _("Invalid wildcards found: ${wildcards}",
                    mapping={'wildcards': safe_unicode(', '.join(wildcards))})
            return to_utf8(translate(msg))

        return True
Exemplo n.º 32
0
    def __call__(self, value, *args, **kwargs):
        if not value:
            return True
        instance = kwargs['instance']
        # fieldname = kwargs['field'].getName()
        request = kwargs.get('REQUEST', {})
        form = request.form
        interim_fields = form.get('InterimFields')

        translate = getToolByName(instance, 'translation_service').translate
        bsc = getToolByName(instance, 'bika_setup_catalog')
        interim_keywords = interim_fields and \
            [f['keyword'] for f in interim_fields] or []
        keywords = re.compile(r"\[([^\.^\]]+)\]").findall(value)

        for keyword in keywords:
            # Check if the service keyword exists and is active.
            dep_service = bsc(getKeyword=keyword, inactive_state="active")
            if not dep_service and \
               not keyword in interim_keywords:
                msg = _("Validation failed: Keyword '${keyword}' is invalid",
                        mapping={'keyword': safe_unicode(keyword)})
                return to_utf8(translate(msg))

        # Wildcards
        # LIMS-1769 Allow to use LDL and UDL in calculations
        # https://jira.bikalabs.com/browse/LIMS-1769
        allowedwds = ['LDL', 'UDL', 'BELOWLDL', 'ABOVEUDL']
        keysandwildcards = re.compile(r"\[([^\]]+)\]").findall(value)
        keysandwildcards = [k for k in keysandwildcards if '.' in k]
        keysandwildcards = [k.split('.',1) for k in keysandwildcards]
        errwilds = [k[1] for k in keysandwildcards if k[0] not in keywords]
        if len(errwilds) > 0:
            msg = _("Wildcards for interims are not allowed: ${wildcards}",
                    mapping={'wildcards': safe_unicode(', '.join(errwilds))})
            return to_utf8(translate(msg))

        wildcards = [k[1] for k in keysandwildcards if k[0] in keywords]
        wildcards = [wd for wd in wildcards if wd not in allowedwds]
        if len(wildcards) > 0:
            msg = _("Invalid wildcards found: ${wildcards}",
                    mapping={'wildcards': safe_unicode(', '.join(wildcards))})
            return to_utf8(translate(msg))

        return True
Exemplo n.º 33
0
 def _sampler_data(self, sample=None):
     data = {}
     if not sample or not sample.getSampler():
         return data
     sampler = sample.getSampler()
     mtool = getToolByName(self, 'portal_membership')
     member = mtool.getMemberById(sampler)
     if member:
         mfullname = member.getProperty('fullname')
         memail = member.getProperty('email')
         mhomepage = member.getProperty('home_page')
         pc = getToolByName(self, 'portal_catalog')
         c = pc(portal_type='Contact', getUsername=member.id)
         c = c[0].getObject() if c else None
         cfullname = c.getFullname() if c else None
         cemail = c.getEmailAddress() if c else None
         data = {
             'id': member.id,
             'fullname':
             to_utf8(cfullname) if cfullname else to_utf8(mfullname),
             'email': cemail if cemail else memail,
             'business_phone': c.getBusinessPhone() if c else '',
             'business_fax': c.getBusinessFax() if c else '',
             'home_phone': c.getHomePhone() if c else '',
             'mobile_phone': c.getMobilePhone() if c else '',
             'job_title': to_utf8(c.getJobTitle()) if c else '',
             'department': to_utf8(c.getDepartment()) if c else '',
             'physical_address':
             to_utf8(c.getPhysicalAddress()) if c else '',
             'postal_address': to_utf8(c.getPostalAddress()) if c else '',
             'home_page': to_utf8(mhomepage)
         }
     return data
Exemplo n.º 34
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

        try:
            value = float(value)
        except:
            msg = _("Validation failed: percent values must be numbers")
            return to_utf8(translate(msg))

        if value < 0 or value > 100:
            msg = _("Validation failed: percent values must be between 0 and 100")
            return to_utf8(translate(msg))

        return True
Exemplo n.º 35
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
Exemplo n.º 36
0
    def _reporter_data(self, ar):
        data = {}
        member = self.context.portal_membership.getAuthenticatedMember()
        if member:
            username = member.getUserName()
            data['username'] = username
            data['fullname'] = to_utf8(self.user_fullname(username))
            data['email'] = to_utf8(self.user_email(username))

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

        return data
Exemplo n.º 37
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

        try:
            value = float(value)
        except:
            msg = _("Validation failed: percent values must be numbers")
            return to_utf8(translate(msg))

        if value < 0 or value > 100:
            msg = _(
                "Validation failed: percent values must be between 0 and 100")
            return to_utf8(translate(msg))

        return True
Exemplo n.º 38
0
    def _printedby_data(self, ws):
        """ Returns a dict that represents the user who prints the ws
            Keys: username, fullname, email
        """
        data = {}
        member = self.context.portal_membership.getAuthenticatedMember()
        if member:
            username = member.getUserName()
            data['username'] = username
            data['fullname'] = to_utf8(self.user_fullname(username))
            data['email'] = to_utf8(self.user_email(username))

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

        return data
Exemplo n.º 39
0
 def _client_data(self, client):
     """ Returns a dict that represents the client specified
         Keys: obj, id, url, name
     """
     data = {}
     if client:
         data['obj'] = client
         data['id'] = client.id
         data['url'] = client.absolute_url()
         data['name'] = to_utf8(client.getName())
     return data
Exemplo n.º 40
0
 def _client_data(self, client):
     """ Returns a dict that represents the client specified
         Keys: obj, id, url, name
     """
     data = {}
     if client:
         data['obj'] = client
         data['id'] = client.id
         data['url'] = client.absolute_url()
         data['name'] = to_utf8(client.getName())
     return data
Exemplo n.º 41
0
    def _batch_data(self, ar):
        data = {}
        batch = ar.getBatch()
        if batch:
            data = {
                'obj': batch,
                'id': batch.id,
                'url': batch.absolute_url(),
                'title': to_utf8(batch.Title()),
                'date': batch.getBatchDate(),
                'client_batchid': to_utf8(batch.getClientBatchID()),
                'remarks': to_utf8(batch.getRemarks())
            }

            uids = batch.Schema()['BatchLabels'].getAccessor(batch)()
            uc = getToolByName(self.context, 'uid_catalog')
            data['labels'] = [
                to_utf8(p.getObject().Title()) for p in uc(UID=uids)
            ]

        return data
Exemplo n.º 42
0
    def get_recipients(self, ar):
        """ Returns a list with the recipients and all its publication prefs
        """
        recips = []

        # Contact and CC's
        contact = ar.getContact()
        if contact:
            recips.append({
                'title': to_utf8(contact.Title()),
                'email': contact.getEmailAddress(),
                'pubpref': contact.getPublicationPreference()
            })
        for cc in ar.getCCContact():
            recips.append({
                'title': to_utf8(cc.Title()),
                'email': cc.getEmailAddress(),
                'pubpref': contact.getPublicationPreference()
            })

        return recips
Exemplo n.º 43
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
Exemplo n.º 44
0
    def __call__(self, value, *args, **kwargs):

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

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

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

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

                # Foreach AS, check spec. input values
                res = ress[uid] if ress[uid] else '0'
                min = mins[uid] if mins[uid] else '0'
                max = maxs[uid] if maxs[uid] else '0'
                err = errs[uid] if errs[uid] else '0'

                # Values must be numbers
                try:
                    res = float(res)
                except ValueError:
                    return to_utf8(translate(_("Validation failed: Expected values must be numeric")))
                try:
                    min = float(min)
                except ValueError:
                    return to_utf8(translate(_("Validation failed: Min values must be numeric")))
                try:
                    max = float(max)
                except ValueError:
                    return to_utf8(translate(_("Validation failed: Max values must be numeric")))
                try:
                    err = float(err)
                except ValueError:
                    return to_utf8(translate(_("Validation failed: Percentage error values must be numeric")))

                # Min value must be < max
                if min > max:
                    return to_utf8(translate(_("Validation failed: Max values must be greater than Min values")))

                # Expected result must be between min and max
                if res < min or res > max:
                    return to_utf8(translate(_("Validation failed: Expected values must be between Min and Max values")))

                # Error percentage must be between 0 and 100
                if err < 0 or err > 100:
                    return to_utf8(translate(_("Validation failed: Percentage error values must be between 0 and 100")))

            return True
Exemplo n.º 45
0
    def _printedby_data(self, ws):
        """ Returns a dict that represents the user who prints the ws
            Keys: username, fullname, email
        """
        data = {}
        member = self.context.portal_membership.getAuthenticatedMember()
        if member:
            username = member.getUserName()
            data['username'] = username
            data['fullname'] = to_utf8(self.user_fullname(username))
            data['email'] = to_utf8(self.user_email(username))

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

        return data
Exemplo n.º 46
0
 def __call__(self, context):
     site = getSite()
     request = aq_get(site, 'REQUEST', None)
     items = []
     for client in site.clients.objectValues('Client'):
         objects = list(client.objectValues('Contact'))
         objects.sort(lambda x, y: cmp(x.getFullname().lower(),
                                       y.getFullname().lower()))
         xitems = [(to_utf8(item.getFullname()), item.getFullname())
                   for item in objects]
         xitems = [SimpleTerm(i[1], i[1], i[0]) for i in xitems]
         items += xitems
     return SimpleVocabulary(items)
Exemplo n.º 47
0
 def __call__(self, context):
     site = getSite()
     request = aq_get(site, 'REQUEST', None)
     items = []
     for client in site.clients.objectValues('Client'):
         objects = list(client.objectValues('Contact'))
         objects.sort(lambda x, y: cmp(x.getFullname().lower(),
                                       y.getFullname().lower()))
         xitems = [(to_utf8(item.getFullname()), item.getFullname())
                   for item in objects]
         xitems = [SimpleTerm(i[1], i[1], i[0]) for i in xitems]
         items += xitems
     return SimpleVocabulary(items)
Exemplo n.º 48
0
    def __call__(self, value, *args, **kwargs):

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

        value = request[fieldname]
        for v in value.values():
            try:
                int(v)
            except:
                return to_utf8(translate(_("Validation failed: Values must be numbers")))
        return True
Exemplo n.º 49
0
    def _specs_data(self, ar):
        data = {}
        specs = ar.getPublicationSpecification()
        if not specs:
            specs = ar.getSpecification()

        if specs:
            data['obj'] = specs
            data['id'] = specs.id
            data['url'] = specs.absolute_url()
            data['title'] = to_utf8(specs.Title())
            data['resultsrange'] = specs.getResultsRangeDict()

        return data
Exemplo n.º 50
0
    def _specs_data(self, ar):
        data = {}
        specs = ar.getPublicationSpecification()
        if not specs:
            specs = ar.getSpecification()

        if specs:
            data['obj'] = specs
            data['id'] = specs.id
            data['url'] = specs.absolute_url()
            data['title'] = to_utf8(specs.Title())
            data['resultsrange'] = specs.getResultsRangeDict()

        return data
Exemplo n.º 51
0
    def __call__(self, subf_value, *args, **kwargs):

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

        # 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

        for i, value in enumerate(request[fieldname]):

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

            # values may be percentages; the rest of the numeric validation must
            # still pass once the '%' is stripped off.
            err = value['errorvalue']
            perc = False
            if err.endswith('%'):
                perc = True
                err = err[:-1]
            try:
                err = float(err)
            except ValueError:
                instance.REQUEST[key] = to_utf8(translate(_("Validation failed: Error values must be numeric")))
                return instance.REQUEST[key]

            if perc and (err < 0 or err > 100):
                # Error percentage must be between 0 and 100
                instance.REQUEST[key] = to_utf8(translate(_("Validation failed: Error percentage must be between 0 and 100")))
                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 values must be >-1
            if err < 0:
                instance.REQUEST[key] = to_utf8(translate(_("Validation failed: Error value must be 0 or greater")))
                return instance.REQUEST[key]

        instance.REQUEST[key] = True
        return True
Exemplo n.º 52
0
    def __call__(self, value, *args, **kwargs):

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

        value = request[fieldname]
        for v in value.values():
            try:
                int(v)
            except:
                return to_utf8(
                    translate(_("Validation failed: Values must be numbers")))
        return True
Exemplo n.º 53
0
    def __init__(self, context, request):
        BikaListingView.__init__(self, context, request)

        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_column = False
        self.show_workflow_action_buttons = False
        self.pagesize = 999999

        self.icon = self.portal_url + "/++resource++bika.lims.images/%s_big.png" % \
            context.portal_type.lower()
        self.title = to_utf8(self.context.Title()) + " " + t(_("Log"))
        self.description = ""

        self.columns = {
            'Version': {
                'title': _('Version'),
                'sortable': False
            },
            'Date': {
                'title': _('Date'),
                'sortable': False
            },
            'User': {
                'title': _('User'),
                'sortable': False
            },
            'Action': {
                'title': _('Action'),
                'sortable': False
            },
            'Description': {
                'title': _('Description'),
                'sortable': False
            },
        }
        self.review_states = [
            {
                'id': 'default',
                'title': 'All',
                'contentFilter': {},
                'columns':
                ['Version', 'Date', 'User', 'Action', 'Description']
            },
        ]
Exemplo n.º 54
0
    def __call__(self, value, *args, **kwargs):

        regex = r"[^A-Za-z\w\d\-\_]"

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

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

        # check the value against all AnalysisService keywords
        if re.findall(regex, value):
            msg = _("Validation failed: keyword contains invalid "
                    "characters")
            return to_utf8(translate(msg))

        return True
Exemplo n.º 55
0
    def __call__(self, value, *args, **kwargs):

        regex = r"[^A-Za-z\w\d\-\_]"

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

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

        # check the value against all AnalysisService keywords
        if re.findall(regex, value):
            msg = _("Validation failed: keyword contains invalid "
                    "characters")
            return to_utf8(translate(msg))

        return True
Exemplo n.º 56
0
    def __call__(self, value, *args, **kwargs):
        """
        Check the NIB number
        value:: string with NIB.
        """
        instance = kwargs['instance']
        translate = getToolByName(instance, 'translation_service').translate
        LEN_NIB = 21
        table = ( 73, 17, 89, 38, 62, 45, 53, 15, 50,
                5, 49, 34, 81, 76, 27, 90, 9, 30, 3 )

        # convert to entire numbers list
        nib = _toIntList(value)

        # checking the length of the number
        if len(nib) != LEN_NIB:
            msg = _('Incorrect NIB number: %s' % value)
            return to_utf8(translate(msg))
        # last numbers algorithm validator
        return nib[-2] * 10 + nib[-1] == 98 - _sumLists(table, nib[:-2]) % 97
Exemplo n.º 57
0
    def __call__(self, value, *args, **kwargs):
        """
        Check the NIB number
        value:: string with NIB.
        """
        instance = kwargs['instance']
        translate = getToolByName(instance, 'translation_service').translate
        LEN_NIB = 21
        table = (73, 17, 89, 38, 62, 45, 53, 15, 50, 5, 49, 34, 81, 76, 27, 90,
                 9, 30, 3)

        # convert to entire numbers list
        nib = _toIntList(value)

        # checking the length of the number
        if len(nib) != LEN_NIB:
            msg = _('Incorrect NIB number: %s' % value)
            return to_utf8(translate(msg))
        # last numbers algorithm validator
        return nib[-2] * 10 + nib[-1] == 98 - _sumLists(table, nib[:-2]) % 97
Exemplo n.º 58
0
 def artemplates(self):
     """ Return applicable client and Lab ARTemplate records
     """
     res = []
     templates = []
     client = self.context.portal_type == 'AnalysisRequest' \
         and self.context.aq_parent or self.context
     for template in client.objectValues("ARTemplate"):
         if isActive(template):
             templates.append((template.Title(), template))
     templates.sort(lambda x, y: cmp(x[0], y[0]))
     res += templates
     templates = []
     for template in self.context.bika_setup.bika_artemplates.objectValues(
             "ARTemplate"):
         if isActive(template):
             lab = t(_('Lab'))
             title = to_utf8(template.Title())
             templates.append(("%s: %s" % (lab, title), template))
     templates.sort(lambda x, y: cmp(x[0], y[0]))
     res += templates
     return res
Exemplo n.º 59
0
 def analysisprofiles(self):
     """ Return applicable client and Lab AnalysisProfile records
     """
     res = []
     profiles = []
     client = self.context.portal_type == 'AnalysisRequest' \
         and self.context.aq_parent or self.context
     for profile in client.objectValues("AnalysisProfile"):
         if isActive(profile):
             profiles.append((profile.Title(), profile))
     profiles.sort(lambda x, y: cmp(x[0], y[0]))
     res += profiles
     profiles = []
     for profile in self.context.bika_setup.bika_analysisprofiles.objectValues(
             "AnalysisProfile"):
         if isActive(profile):
             lab = t(_('Lab'))
             title = to_utf8(profile.Title())
             profiles.append(("%s: %s" % (lab, title), profile))
     profiles.sort(lambda x, y: cmp(x[0], y[0]))
     res += profiles
     return res
Exemplo n.º 60
0
    def __call__(self, value, *args, **kwargs):
        # If not prepreserved, no validation required.
        if not value:
            return True

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

        if type(preservation) in (list, tuple):
            preservation = preservation[0]

        if preservation:
            return True

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

        if not preservation:
            msg = _("Validation failed: PrePreserved containers "
                    "must have a preservation selected.")
            return to_utf8(translate(msg))