Esempio n. 1
0
    def getAvailableTemplates(self):
        """Returns an array with the templates of stickers available.

        Each array item is a dictionary with the following structure:

            {'id': <template_id>,
            'title': <teamplate_title>,
            'selected: True/False'}
        """
        # Getting adapters for current context. those adapters will return
        # the desired sticker templates for the current context:
        try:
            adapters = getAdapters((self.context, ), IGetStickerTemplates)
        except ComponentLookupError:
            logger.info("No IGetStickerTemplates adapters found.")
            adapters = None
        templates = []
        if adapters is not None:
            # Gather all templates
            for name, adapter in adapters:
                templates += adapter(self.request)
        if templates:
            return templates
        # If there are no adapters, get all sticker templates in the system
        seltemplate = self.getSelectedTemplate()
        for temp in getStickerTemplates(filter_by_type=self.filter_by_type):
            out = temp
            out["selected"] = temp.get("id", "") == seltemplate
            templates.append(out)
        return templates
Esempio n. 2
0
    def test_default_stickers(self):
        """https://jira.bikalabs.com/browse/WINE-44: display SampleID or
        SamplePartition ID depending on bikasetup.ShowPartitions value
        """

        folder = self.portal.bika_setup.bika_analysisservices
        services = [_createObjectByType("AnalysisService", folder, tmpID()),
                    _createObjectByType("AnalysisService", folder, tmpID())]
        services[0].processForm()
        services[1].processForm()
        services[0].edit(title="Detect Dust")
        services[1].edit(title="Detect water")
        service_uids = [s.UID for s in services]
        folder = self.portal.clients
        client = _createObjectByType("Client", folder, tmpID())
        client.processForm()
        folder = self.portal.clients.objectValues("Client")[0]
        contact = _createObjectByType("Contact", folder, tmpID())
        contact.processForm()
        contact.edit(Firstname="Bob", Surname="Dobbs", email="*****@*****.**")
        folder = self.portal.bika_setup.bika_sampletypes
        sampletype = _createObjectByType("SampleType", folder, tmpID())
        sampletype.processForm()
        sampletype.edit(title="Air", Prefix="AIR")

        values = {'Client': client.UID(),
                  'Contact': contact.UID(),
                  'SamplingDate': '2015-01-01',
                  'SampleType': sampletype.UID()}

        for stemp in getStickerTemplates():

            # create and receive AR
            ar = create_analysisrequest(client, {}, values, service_uids)
            ar.bika_setup.setShowPartitions(False)
            doActionFor(ar, 'receive')
            self.assertEquals(ar.portal_workflow.getInfoFor(ar, 'review_state'), 'sample_received')
            # check sticker text
            ar.REQUEST['items'] = ar.getId()
            ar.REQUEST['template'] = stemp.get('id')
            sticker = Sticker(ar, ar.REQUEST)()
            pid = ar.getSample().objectValues("SamplePartition")[0].getId()
            self.assertNotIn(pid, sticker, "Sticker must not contain partition ID %s"%pid)

            # create and receive AR
            ar = create_analysisrequest(client, {}, values, service_uids)
            ar.bika_setup.setShowPartitions(True)
            doActionFor(ar, 'receive')
            self.assertEquals(ar.portal_workflow.getInfoFor(ar, 'review_state'), 'sample_received')
            # check sticker text
            ar.REQUEST['items'] = ar.getId()
            ar.REQUEST['template'] = stemp.get('id')
            sticker = Sticker(ar, ar.REQUEST)()
            pid = ar.getSample().objectValues("SamplePartition")[0].getId()
            self.assertIn(pid, sticker, "Sticker must contain partition ID %s"%pid)
Esempio n. 3
0
def sticker_templates():
    """
    It returns the registered stickers in the system.
    :return: a DisplayList object
    """
    voc = DisplayList()
    stickers = getStickerTemplates()
    for sticker in stickers:
        voc.add(sticker.get('id'), sticker.get('title'))
    if voc.index == 0:
        logger.warning('Sampletype: getStickerTemplates is empty!')
    return voc
Esempio n. 4
0
 def getAvailableTemplates(self):
     """ Returns an array with the templates of stickers available. Each
         array item is a dictionary with the following structure:
             {'id': <template_id>,
              'title': <teamplate_title>,
              'selected: True/False'}
     """
     seltemplate = self.getSelectedTemplate()
     templates = []
     for temp in getStickerTemplates():
         out = temp
         out['selected'] = temp.get('id', '') == seltemplate
         templates.append(out)
     return templates
Esempio n. 5
0
 def getAvailableTemplates(self):
     """ Returns an array with the templates of stickers available. Each
         array item is a dictionary with the following structure:
             {'id': <template_id>,
              'title': <teamplate_title>,
              'selected: True/False'}
     """
     seltemplate = self.getSelectedTemplate()
     templates = []
     for temp in getStickerTemplates():
         out = temp
         out['selected'] = temp.get('id', '') == seltemplate
         templates.append(out)
     return templates
Esempio n. 6
0
    def _sticker_templates_vocabularies(self):
        """
        Returns the vocabulary to be used in
        AdmittedStickerTemplates.small_default

        If the object has saved not AdmittedStickerTemplates.admitted stickers,
        this method will return an empty DisplayList. Otherwise it returns
        the stickers selected in admitted.

        :return: A DisplayList
        """
        admitted = self.getAdmittedStickers()
        if not admitted:
            return DisplayList()
        voc = DisplayList()
        stickers = getStickerTemplates()
        for sticker in stickers:
            if sticker.get('id') in admitted:
                voc.add(sticker.get('id'), sticker.get('title'))
        return voc
Esempio n. 7
0
 def __call__(self, request):
     self.request = request
     # Stickers admittance are saved in sample type
     if not hasattr(self.context, 'getSampleType'):
         logger.warning(
             "{} has no attribute 'getSampleType', so no sticker will be "
             "returned.".format(self.context.getId()))
         return []
     self.sample_type = self.context.getSampleType()
     sticker_ids = self.sample_type.getAdmittedStickers()
     default_sticker_id = self.get_default_sticker_id()
     result = []
     # Getting only existing templates and its info
     stickers = getStickerTemplates()
     for sticker in stickers:
         if sticker.get('id') in sticker_ids:
             sticker_info = sticker.copy()
             sticker_info['selected'] = \
                 default_sticker_id == sticker.get('id')
             result.append(sticker_info)
     return result
Esempio n. 8
0
    def getSelectedTemplate(self, default="Code_39_40x20mm.pt"):
        """Returns the id of the sticker template selected.

        If no specific template found in the request (parameter template),
        returns the default template set in Setup > Stickers.

        If the template doesn't exist, uses the default template.

        If no template selected but size param, get the sticker template set as
        default in Bika Setup for the size set.
        """
        # Default sticker
        bs_template = self.context.bika_setup.getAutoStickerTemplate()
        size = self.request.get("size", "")

        if self.filter_by_type:
            templates = getStickerTemplates(filter_by_type=self.filter_by_type)
            # Get the first sticker
            bs_template = templates[0].get("id", "") if templates else ""
        elif size == "small":
            bs_template = self.context.bika_setup.getSmallStickerTemplate()
        elif size == "large":
            bs_template = self.context.bika_setup.getLargeStickerTemplate()
        rq_template = self.request.get("template", bs_template)
        # Check if the template exists. If not, fallback to default's
        # 'prefix' is also the resource folder's name
        prefix = ""
        templates_dir = ""
        if rq_template.find(":") >= 0:
            prefix, rq_template = rq_template.split(":")
            templates_dir = self._getStickersTemplatesDirectory(prefix)
        else:
            this_dir = os.path.dirname(os.path.abspath(__file__))
            templates_dir = os.path.join(this_dir, "templates/stickers/")
            if self.filter_by_type:
                templates_dir = templates_dir + "/" + self.filter_by_type
        if not os.path.isfile(os.path.join(templates_dir, rq_template)):
            rq_template = default
        return "%s:%s" % (prefix, rq_template) if prefix else rq_template
Esempio n. 9
0
def set_sample_type_default_stickers(portal):
    """
    Fills the admitted stickers and their default stickers to every sample
    type.
    """
    # Getting all sticker templates
    stickers = getStickerTemplates()
    sticker_ids = []
    for sticker in stickers:
        sticker_ids.append(sticker.get('id'))
    def_small_template = portal.bika_setup.getSmallStickerTemplate()
    def_large_template = portal.bika_setup.getLargeStickerTemplate()
    # Getting all Sample Type objects
    catalog = api.get_tool('bika_setup_catalog')
    brains = catalog(portal_type='SampleType')
    for brain in brains:
        obj = api.get_object(brain)
        if obj.getAdmittedStickers() is not None:
            continue
        obj.setAdmittedStickers(sticker_ids)
        obj.setDefaultLargeSticker(def_large_template)
        obj.setDefaultSmallSticker(def_small_template)
Esempio n. 10
0
 def getSelectedTemplate(self):
     """ Returns the id of the sticker template selected. If no specific
         template found in the request (parameter template), returns the
         default template set in Bika Setup > Stickers.
         If the template doesn't exist, uses the default bika.lims'
         Code_128_1x48mm.pt template (was sticker_small.pt).
         If no template selected but size param, get the sticker template
         set as default in Bika Setup for the size set.
     """
     # Default sticker
     bs_template = self.context.bika_setup.getAutoStickerTemplate()
     size = self.request.get('size', '')
     resource_type = 'stickers'
     if self.filter_by_type:
         templates = getStickerTemplates(filter_by_type=self.filter_by_type)
         # Get the first sticker
         bs_template = templates[0].get('id', '') if templates else ''
     elif size == 'small':
         bs_template = self.context.bika_setup.getSmallStickerTemplate()
     elif size == 'large':
         bs_template = self.context.bika_setup.getLargeStickerTemplate()
     rq_template = self.request.get('template', bs_template)
     # Check if the template exists. If not, fallback to default's
     # 'prefix' is also the resource folder's name
     prefix = ''
     templates_dir = ''
     if rq_template.find(':') >= 0:
         prefix, rq_template = rq_template.split(':')
         templates_dir = self._getStickersTemplatesDirectory(prefix)
     else:
         this_dir = os.path.dirname(os.path.abspath(__file__))
         templates_dir = os.path.join(this_dir, 'templates/stickers/')
         if self.filter_by_type:
             templates_dir = templates_dir + '/' + self.filter_by_type
     if not os.path.isfile(os.path.join(templates_dir, rq_template)):
         rq_template = 'Code_128_1x48mm.pt'
     return '%s:%s' % (prefix, rq_template) if prefix else rq_template
Esempio n. 11
0
    def test_default_stickers(self):
        """https://jira.bikalabs.com/browse/WINE-44: display SampleID or
        SamplePartition ID depending on bikasetup.ShowPartitions value
        """

        folder = self.portal.bika_setup.bika_analysisservices
        services = [
            _createObjectByType("AnalysisService", folder, tmpID()),
            _createObjectByType("AnalysisService", folder, tmpID())
        ]
        services[0].processForm()
        services[1].processForm()
        services[0].edit(title="Detect Dust")
        services[1].edit(title="Detect water")
        service_uids = [s.UID for s in services]
        folder = self.portal.clients
        client = _createObjectByType("Client", folder, tmpID())
        client.processForm()
        folder = self.portal.clients.objectValues("Client")[0]
        contact = _createObjectByType("Contact", folder, tmpID())
        contact.processForm()
        contact.edit(Firstname="Bob",
                     Surname="Dobbs",
                     email="*****@*****.**")
        folder = self.portal.bika_setup.bika_sampletypes
        sampletype = _createObjectByType("SampleType", folder, tmpID())
        sampletype.processForm()
        sampletype.edit(title="Air", Prefix="AIR")

        values = {
            'Client': client.UID(),
            'Contact': contact.UID(),
            'SamplingDate': '2015-01-01',
            'SampleType': sampletype.UID()
        }
        for stemp in getStickerTemplates():

            # create and receive AR
            ar = create_analysisrequest(client, {}, values, service_uids)
            ar.bika_setup.setShowPartitions(False)
            doActionFor(ar, 'receive')
            self.assertEquals(
                ar.portal_workflow.getInfoFor(ar, 'review_state'),
                'sample_received')
            # check sticker text
            ar.REQUEST['items'] = ar.UID()
            ar.REQUEST['template'] = stemp.get('id')
            sticker = Sticker(ar, ar.REQUEST)()
            pid = ar.getSample().objectValues("SamplePartition")[0].getId()
            self.assertNotIn(pid, sticker,
                             "Sticker must not contain partition ID %s" % pid)

            # create and receive AR
            ar = create_analysisrequest(client, {}, values, service_uids)
            ar.bika_setup.setShowPartitions(True)
            doActionFor(ar, 'receive')
            self.assertEquals(
                ar.portal_workflow.getInfoFor(ar, 'review_state'),
                'sample_received')
            # check sticker text
            ar.REQUEST['items'] = ar.UID()
            ar.REQUEST['template'] = stemp.get('id')
            sticker = Sticker(ar, ar.REQUEST)()
            pid = ar.getSample().objectValues("SamplePartition")[0].getId()
            self.assertIn(pid, sticker,
                          "Sticker must contain partition ID %s" % pid)