当前位置: 首页>>代码示例>>Python>>正文


Python WorkflowAction._get_selected_items方法代码示例

本文整理汇总了Python中bika.lims.browser.bika_listing.WorkflowAction._get_selected_items方法的典型用法代码示例。如果您正苦于以下问题:Python WorkflowAction._get_selected_items方法的具体用法?Python WorkflowAction._get_selected_items怎么用?Python WorkflowAction._get_selected_items使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在bika.lims.browser.bika_listing.WorkflowAction的用法示例。


在下文中一共展示了WorkflowAction._get_selected_items方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: workflow_action_aliquot_receive

# 需要导入模块: from bika.lims.browser.bika_listing import WorkflowAction [as 别名]
# 或者: from bika.lims.browser.bika_listing.WorkflowAction import _get_selected_items [as 别名]
    def workflow_action_aliquot_receive(self):
        form = self.request.form
        selected_aliquots = WorkflowAction._get_selected_items(self)
        aliquots = []
        for uid in selected_aliquots.keys():
            if not form["AliquotType"][0][uid] or not form["Volume"][0][uid] or not form["Unit"][0][uid]:
                continue
            try:
                aliquot = selected_aliquots.get(uid, None)
                aliquot.getField("SampleType").set(aliquot, form["AliquotType"][0][uid])
                aliquot.getField("Volume").set(aliquot, form["Volume"][0][uid])
                unit = "ml"
                for u in VOLUME_UNITS:
                    if u["ResultValue"] == form["Unit"][0][uid]:
                        unit = u["ResultText"]
                aliquot.getField("Unit").set(aliquot, unit)
                aliquot.reindexObject()
                aliquots.append(aliquot)
            except ReferenceException:
                continue

        message = PMF("Changes saved.")
        self.context.plone_utils.addPortalMessage(message, "info")

        for aliquot in aliquots:
            doActionFor(aliquot, "receive")
            for partition in aliquot.objectValues("SamplePartition"):
                doActionFor(partition, "receive")

        self.destination_url = self.context.absolute_url()
        if self.context.portal_type == "Project":
            self.destination_url += "/aliquots"
        self.request.response.redirect(self.destination_url)
开发者ID:rockfruit,项目名称:bika.sanbi,代码行数:35,代码来源:workflow.py

示例2: __call__

# 需要导入模块: from bika.lims.browser.bika_listing import WorkflowAction [as 别名]
# 或者: from bika.lims.browser.bika_listing.WorkflowAction import _get_selected_items [as 别名]
    def __call__(self):
        form = self.request.form
        plone.protect.CheckAuthenticator(form)
        workflow = getToolByName(self.context, 'portal_workflow')
        rc = getToolByName(self.context, REFERENCE_CATALOG)
        action, came_from = WorkflowAction._get_form_workflow_action(self)

        if action == 'reassign':
            selected_worksheets = WorkflowAction._get_selected_items(self)
            selected_worksheet_uids = selected_worksheets.keys()

            if selected_worksheets:
                changes = False
                for uid in selected_worksheet_uids:
                    worksheet = selected_worksheets[uid]
                    # Double-check the state first
                    if workflow.getInfoFor(worksheet, 'review_state') == 'open':
                        worksheet.setAnalyst(form['Analyst'][0][uid])
                        changes = True

                if changes:
                    message = self.context.translate(PMF('Changes saved.'))
                    self.context.plone_utils.addPortalMessage(message, 'info')

            self.destination_url = self.request.get_header("referer",
                                   self.context.absolute_url())
            self.request.response.redirect(self.destination_url)
        else:
            # default bika_listing.py/WorkflowAction for other transitions
            WorkflowAction.__call__(self)
开发者ID:institutmontilivi,项目名称:Bika-LIMS,代码行数:32,代码来源:worksheetfolder.py

示例3: __call__

# 需要导入模块: from bika.lims.browser.bika_listing import WorkflowAction [as 别名]
# 或者: from bika.lims.browser.bika_listing.WorkflowAction import _get_selected_items [as 别名]
    def __call__(self):
        form = self.request.form
        plone.protect.CheckAuthenticator(form)
        action, came_from = WorkflowAction._get_form_workflow_action(self)

        if action == 'submit':

            objects = WorkflowAction._get_selected_items(self)
            if not objects:
                message = self.context.translate(
                    _b("No analyses have been selected"))
                self.context.plone_utils.addPortalMessage(message, 'info')
                self.destination_url = self.context.absolute_url() + \
                    "/batchbook"
                self.request.response.redirect(self.destination_url)
                return

            for ar_uid, ar in objects.items():
                for analysis in ar.getAnalyses(full_objects=True):
                    kw = analysis.getKeyword()
                    values = form.get(kw)
                    analysis.setResult(values[0][ar_uid])
                    if values[0][ar_uid]:
                        doActionFor(analysis, 'submit')

            message = self.context.translate(_p("Changes saved."))
            self.context.plone_utils.addPortalMessage(message, 'info')
            self.request.response.redirect(self.request.get('URL'))
            return

        else:

            WorkflowAction.__call__(self)
开发者ID:bikalabs,项目名称:bika.wine,代码行数:35,代码来源:workflowaction.py

示例4: workflow_action_preserve

# 需要导入模块: from bika.lims.browser.bika_listing import WorkflowAction [as 别名]
# 或者: from bika.lims.browser.bika_listing.WorkflowAction import _get_selected_items [as 别名]
    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)
开发者ID:KaskMartin,项目名称:Bika-LIMS,代码行数:61,代码来源:workflow.py

示例5: workflow_action_schedule_sampling

# 需要导入模块: from bika.lims.browser.bika_listing import WorkflowAction [as 别名]
# 或者: from bika.lims.browser.bika_listing.WorkflowAction import _get_selected_items [as 别名]
    def workflow_action_schedule_sampling(self):
        """
        This function prevent the transition if the fields "SamplingDate"
        and "ScheduledSamplingSampler" are uncompleted.
        :return: bool
        """
        from bika.lims.utils.workflow import schedulesampling

        message = "Not expected transition."
        # In Samples Folder we have to get each selected item
        if interfaces.ISamplesFolder.providedBy(self.context):
            select_objs = WorkflowAction._get_selected_items(self)
            message = _("Transition done.")
            for key in select_objs.keys():
                sample = select_objs[key]
                # Getting the sampler
                sch_sampl = (
                    self.request.form.get("getScheduledSamplingSampler", None)[0].get(key)
                    if self.request.form.get("getScheduledSamplingSampler", None)
                    else ""
                )
                # Getting the date
                sampl_date = (
                    self.request.form.get("getSamplingDate", None)[0].get(key)
                    if self.request.form.get("getSamplingDate", None)
                    else ""
                )
                # Setting both values
                sample.setScheduledSamplingSampler(sch_sampl)
                sample.setSamplingDate(sampl_date)
                # Transitioning the sample
                success, errmsg = schedulesampling.doTransition(sample)
                if errmsg == "missing":
                    message = _(
                        "'Sampling date' and 'Define the Sampler for the"
                        + " scheduled sampling' must be completed and saved "
                        + "in order to schedule a sampling. Element: %s" % sample.getId()
                    )
                elif errmsg == "cant_trans":
                    message = _("The item %s can't be transitioned." % sample.getId())
                else:
                    message = _("Transition done.")
                self.context.plone_utils.addPortalMessage(message, "info")
        else:
            success, errmsg = schedulesampling.doTransition(self.context)
            if errmsg == "missing":
                message = _(
                    "'Sampling date' and 'Define the Sampler for the"
                    + " scheduled sampling' must be completed and saved in "
                    + "order to schedule a sampling."
                )
            elif errmsg == "cant_trans":
                message = _("The item can't be transitioned.")
            else:
                message = _("Transition done.")
            self.context.plone_utils.addPortalMessage(message, "info")
        # Reload the page in order to show the portal message
        self.request.response.redirect(self.context.absolute_url())
        return success
开发者ID:bikalabs,项目名称:bika.lims,代码行数:61,代码来源:workflow.py

示例6: __call__

# 需要导入模块: from bika.lims.browser.bika_listing import WorkflowAction [as 别名]
# 或者: from bika.lims.browser.bika_listing.WorkflowAction import _get_selected_items [as 别名]
    def __call__(self):
        form = self.request.form
        plone.protect.CheckAuthenticator(form)
        workflow = getToolByName(self.context, 'portal_workflow')
        rc = getToolByName(self.context, REFERENCE_CATALOG)
        uc = getToolByName(self.context, 'uid_catalog')
        action, came_from = WorkflowAction._get_form_workflow_action(self)

        if action == 'duplicate':
            selected_services = WorkflowAction._get_selected_items(self)

            ## Create a copy of the selected services
            folder = self.context.bika_setup.bika_analysisservices
            created = []
            for service in selected_services.values():
                _id = folder.invokeFactory('AnalysisService', id = 'tmp')
                dup = folder[_id]
                dup.setTitle('%s (copy)' % service.Title())
                _id = renameAfterCreation(dup)
                dup.edit(
                    description = service.Description(),
                    PointOfCapture = service.getPointOfCapture(),
                    ReportDryMatter = service.getReportDryMatter(),
                    Unit = service.getUnit(),
                    Precision = service.getPrecision(),
                    Price = service.getPrice(),
                    CorporatePrice = service.getCorporatePrice(),
                    VAT = service.getVAT(),
                    Calculation = service.getCalculation(),
                    Instrument = service.getInstrument(),
                    MaxTimeAllowed = service.getMaxTimeAllowed(),
                    DuplicateVariation = service.getDuplicateVariation(),
                    Category = service.getCategory(),
                    Department = service.getDepartment(),
                    Accredited = service.getAccredited(),
                    Uncertainties = service.getUncertainties(),
                    ResultOptions = service.getResultOptions()
                )
                created.append(_id)

            if len(created) > 1:
                message = self.context.translation_service.translate(
                    _('Services ${services} were successfully created.',
                      mapping = {'services': ', '.join(created)}))
                self.destination_url = self.request.get_header("referer",
                                                               self.context.absolute_url())
            else:
                message = self.context.translation_service.translate(
                    _('Analysis request ${service} was successfully created.',
                    mapping = {'service': ', '.join(created)}))
                self.destination_url = dup.absolute_url() + "/base_edit"

            self.context.plone_utils.addPortalMessage(message, 'info')
            self.request.response.redirect(self.destination_url)

        else:
            # default bika_listing.py/WorkflowAction for other transitions
            WorkflowAction.__call__(self)
开发者ID:udithap,项目名称:Bika-LIMS,代码行数:60,代码来源:bika_analysisservices.py

示例7: workflow_action_save_analyses_button

# 需要导入模块: from bika.lims.browser.bika_listing import WorkflowAction [as 别名]
# 或者: from bika.lims.browser.bika_listing.WorkflowAction import _get_selected_items [as 别名]
    def workflow_action_save_analyses_button(self):
        form = self.request.form
        workflow = getToolByName(self.context, 'portal_workflow')
        action, came_from = WorkflowAction._get_form_workflow_action(self)
        # AR Manage Analyses: save Analyses
        ar = self.context
        sample = ar.getSample()
        objects = WorkflowAction._get_selected_items(self)
        if not objects:
            message = _("No analyses have been selected")
            self.context.plone_utils.addPortalMessage(message, 'info')
            self.destination_url = self.context.absolute_url() + "/analyses"
            self.request.response.redirect(self.destination_url)
            return
        Analyses = objects.keys()
        prices = form.get("Price", [None])[0]
        specs = {}
        if form.get("min", None):
            for service_uid in Analyses:
                specs[service_uid] = {
                    "min": form["min"][0][service_uid],
                    "max": form["max"][0][service_uid],
                    "error": form["error"][0][service_uid]
                }
        else:
            for service_uid in Analyses:
                specs[service_uid] = {"min": "", "max": "", "error": ""}
        new = ar.setAnalyses(Analyses, prices=prices, specs=specs)
        # link analyses and partitions
        # If Bika Setup > Analyses > 'Display individual sample
        # partitions' is checked, no Partitions available.
        # https://github.com/bikalabs/Bika-LIMS/issues/1030
        if 'Partition' in form:
            for service_uid, service in objects.items():
                part_id = form['Partition'][0][service_uid]
                part = sample[part_id]
                analysis = ar[service.getKeyword()]
                analysis.setSamplePartition(part)
                analysis.reindexObject()
        if new:
            for analysis in new:
                # if the AR has progressed past sample_received, we need to bring it back.
                ar_state = workflow.getInfoFor(ar, 'review_state')
                if ar_state in ('attachment_due', 'to_be_verified'):
                    # Apply to AR only; we don't want this transition to cascade.
                    ar.REQUEST['workflow_skiplist'].append("retract all analyses")
                    workflow.doActionFor(ar, 'retract')
                    ar.REQUEST['workflow_skiplist'].remove("retract all analyses")
                    ar_state = workflow.getInfoFor(ar, 'review_state')
                # Then we need to forward new analyses state
                analysis.updateDueDate()
                changeWorkflowState(analysis, 'bika_analysis_workflow', ar_state)

        message = PMF("Changes saved.")
        self.context.plone_utils.addPortalMessage(message, 'info')
        self.destination_url = self.context.absolute_url()
        self.request.response.redirect(self.destination_url)
开发者ID:Adam-Brown,项目名称:Bika-LIMS,代码行数:59,代码来源:workflow.py

示例8: workflow_action_save_partitions_button

# 需要导入模块: from bika.lims.browser.bika_listing import WorkflowAction [as 别名]
# 或者: from bika.lims.browser.bika_listing.WorkflowAction import _get_selected_items [as 别名]
 def workflow_action_save_partitions_button(self):
     form = self.request.form
     # Sample Partitions or AR Manage Analyses: save Partition Table
     sample = self.context.portal_type == 'Sample' and self.context or\
         self.context.getSample()
     part_prefix = sample.getId() + "-P"
     nr_existing = len(sample.objectIds())
     nr_parts = len(form['PartTitle'][0])
     # add missing parts
     if nr_parts > nr_existing:
         for i in range(nr_parts - nr_existing):
             part = _createObjectByType("SamplePartition", sample, tmpID())
             part.setDateReceived = DateTime()
             part.processForm()
     # remove excess parts
     if nr_existing > nr_parts:
         for i in range(nr_existing - nr_parts):
             part = sample['%s%s' % (part_prefix, nr_existing - i)]
             for a in part.getBackReferences("AnalysisSamplePartition"):
                 a.setSamplePartition(None)
             sample.manage_delObjects(['%s%s' % (part_prefix, nr_existing - i), ])
     # modify part container/preservation
     for part_uid, part_id in form['PartTitle'][0].items():
         part = sample["%s%s" % (part_prefix, part_id.split(part_prefix)[1])]
         part.edit(
             Container=form['getContainer'][0][part_uid],
             Preservation=form['getPreservation'][0][part_uid],
         )
         part.reindexObject()
         # Adding the Security Seal Intact checkbox's value to the container object
         container_uid = form['getContainer'][0][part_uid]
         uc = getToolByName(self.context, 'uid_catalog')
         cbr = uc(UID=container_uid)
         if cbr and len(cbr) > 0:
             container_obj = cbr[0].getObject()
         else:
             continue
         value = form.get('setSecuritySealIntact', {}).get(part_uid, '') == 'on'
         container_obj.setSecuritySealIntact(value)
     objects = WorkflowAction._get_selected_items(self)
     if not objects:
         message = _("No items have been selected")
         self.context.plone_utils.addPortalMessage(message, 'info')
         if self.context.portal_type == 'Sample':
             # in samples his table is on 'Partitions' tab
             self.destination_url = self.context.absolute_url() +\
                 "/partitions"
         else:
             # in ar context this table is on 'ManageAnalyses' tab
             self.destination_url = self.context.absolute_url() +\
                 "/analyses"
         self.request.response.redirect(self.destination_url)
开发者ID:fqblab,项目名称:bika.lims,代码行数:54,代码来源:workflow.py

示例9: workflow_action_copy_to_new

# 需要导入模块: from bika.lims.browser.bika_listing import WorkflowAction [as 别名]
# 或者: from bika.lims.browser.bika_listing.WorkflowAction import _get_selected_items [as 别名]
 def workflow_action_copy_to_new(self):
     # Pass the selected AR UIDs in the request, to ar_add.
     objects = WorkflowAction._get_selected_items(self)
     if not objects:
         message = _("No analyses have been selected")
         self.context.plone_utils.addPortalMessage(message, 'info')
         referer = self.request.get_header("referer")
         self.request.response.redirect(referer)
         return
     url = self.context.absolute_url() + "/ar_add" + \
         "?ar_count={0}".format(len(objects)) + \
         "&copy_from={0}".format(",".join(reversed(objects.keys())))
     self.request.response.redirect(url)
     return
开发者ID:bikalabs,项目名称:bika.lims,代码行数:16,代码来源:workflow.py

示例10: workflow_action_keep

# 需要导入模块: from bika.lims.browser.bika_listing import WorkflowAction [as 别名]
# 或者: from bika.lims.browser.bika_listing.WorkflowAction import _get_selected_items [as 别名]
 def workflow_action_keep(self):
     workflow = getToolByName(self.context, 'portal_workflow')
     action, came_from = WorkflowAction._get_form_workflow_action(self)
     objects = WorkflowAction._get_selected_items(self)
     for obj_uid, obj in objects.items():
         pitem = obj
         old_d = pitem.Description()
         new_message = "\n*** Restored in Inventory at " + time.strftime("%c") + " ***\n"
         pitem.setDescription(old_d + new_message)
         pitem.reindexObject()
         workflow.doActionFor(pitem, action)
     message = PMF("Changes saved.")
     self.context.plone_utils.addPortalMessage(message, 'info')
     self.destination_url = self.context.absolute_url()
     self.request.response.redirect(self.destination_url)
开发者ID:hocinebendou,项目名称:bika.gsoc,代码行数:17,代码来源:bika_stockitems.py

示例11: __call__

# 需要导入模块: from bika.lims.browser.bika_listing import WorkflowAction [as 别名]
# 或者: from bika.lims.browser.bika_listing.WorkflowAction import _get_selected_items [as 别名]
    def __call__(self):
        form = self.request.form
        CheckAuthenticator(form)
        workflow = getToolByName(self.context, 'portal_workflow')
        rc = getToolByName(self.context, REFERENCE_CATALOG)
        action, came_from = WorkflowAction._get_form_workflow_action(self)

        if action == 'reassign':
            mtool = getToolByName(self.context, 'portal_membership')
            if not mtool.checkPermission(ManageWorksheets, self.context):

                # Redirect to WS list
                msg = _('You do not have sufficient privileges to '
                        'manage worksheets.')
                self.context.plone_utils.addPortalMessage(msg, 'warning')
                portal = getToolByName(self.context, 'portal_url').getPortalObject()
                self.destination_url = portal.absolute_url() + "/worksheets"
                self.request.response.redirect(self.destination_url)
                return

            selected_worksheets = WorkflowAction._get_selected_items(self)
            selected_worksheet_uids = selected_worksheets.keys()

            if selected_worksheets:
                changes = False
                for uid in selected_worksheet_uids:
                    worksheet = selected_worksheets[uid]
                    # Double-check the state first
                    if workflow.getInfoFor(worksheet, 'review_state') == 'open':
                        worksheet.setAnalyst(form['Analyst'][0][uid])
                        worksheet.reindexObject(idxs=['getAnalyst'])
                        changes = True

                if changes:
                    message = PMF('Changes saved.')
                    self.context.plone_utils.addPortalMessage(message, 'info')

            self.destination_url = self.request.get_header("referer",
                                   self.context.absolute_url())
            self.request.response.redirect(self.destination_url)
        else:
            # default bika_listing.py/WorkflowAction for other transitions
            WorkflowAction.__call__(self)
开发者ID:xispa,项目名称:bika.lims,代码行数:45,代码来源:workflow.py

示例12: workflow_action_receive

# 需要导入模块: from bika.lims.browser.bika_listing import WorkflowAction [as 别名]
# 或者: from bika.lims.browser.bika_listing.WorkflowAction import _get_selected_items [as 别名]
    def workflow_action_receive(self):
        form = self.request.form
        # print form
        selected_biospecimens = WorkflowAction._get_selected_items(self)
        biospecimens = []
        for uid in selected_biospecimens.keys():
            if not form['Barcode'][0][uid] or \
                    not form['Type'][0][uid] or \
                    not form['Volume'][0][uid] or \
                    not form['Unit'][0][uid] or \
                    not form['SubjectID'][0][uid]:
                continue

            try:
                obj = selected_biospecimens.get(uid, None)
                obj.getField('Barcode').set(obj, form['Barcode'][0][uid])
                obj.getField('SampleType').set(obj, form['Type'][0][uid])
                obj.getField('Volume').set(obj, form['Volume'][0][uid])
                obj.getField('SubjectID').set(obj, form['SubjectID'][0][uid])
                unit = 'ml'
                for u in VOLUME_UNITS:
                    if u['ResultValue'] == form['Unit'][0][uid]:
                        unit = u['ResultText']
                obj.getField('Unit').set(obj, unit)
                obj.reindexObject()
                biospecimens.append(obj)
            except ReferenceException:
                continue

        message = PMF("Changes saved.")
        self.context.plone_utils.addPortalMessage(message, 'info')

        for biospecimen in biospecimens:
            doActionFor(biospecimen, 'receive')
            for partition in biospecimen.objectValues('SamplePartition'):
                doActionFor(partition, 'receive')

        self.destination_url = self.context.absolute_url()
        if self.context.portal_type == 'Project':
            self.destination_url += '/biospecimens'
        self.request.response.redirect(self.destination_url)
开发者ID:rockfruit,项目名称:bika.sanbi,代码行数:43,代码来源:workflow.py

示例13: __call__

# 需要导入模块: from bika.lims.browser.bika_listing import WorkflowAction [as 别名]
# 或者: from bika.lims.browser.bika_listing.WorkflowAction import _get_selected_items [as 别名]
    def __call__(self):
        form = self.request.form
        plone.protect.CheckAuthenticator(form)
        workflow = getToolByName(self.context, 'portal_workflow')
        rc = getToolByName(self.context, REFERENCE_CATALOG)
        bsc = getToolByName(self.context, 'bika_setup_catalog')
        bac = getToolByName(self.context, 'bika_analysis_catalog')
        action, came_from = WorkflowAction._get_form_workflow_action(self)

        # XXX combine data from multiple bika listing tables.
        item_data = {}
        if 'item_data' in form:
            if type(form['item_data']) == list:
                for i_d in form['item_data']:
                    for i, d in json.loads(i_d).items():
                        item_data[i] = d
            else:
                item_data = json.loads(form['item_data'])

        if action == 'submit' and self.request.form.has_key("Result"):
            selected_analyses = WorkflowAction._get_selected_items(self)
            results = {}
            hasInterims = {}

            # first save results for entire form
            for uid, result in self.request.form['Result'][0].items():
                if uid in selected_analyses:
                    analysis = selected_analyses[uid]
                else:
                    analysis = rc.lookupObject(uid)
                if not analysis:
                    # ignore result if analysis object no longer exists
                    continue
                if not(getSecurityManager().checkPermission(EditResults, analysis)):
                    # or changes no longer allowed
                    continue
                if not isActive(analysis):
                    # or it's cancelled
                    continue
                results[uid] = result
                service = analysis.getService()
                interimFields = item_data[uid]
                if len(interimFields) > 0:
                    hasInterims[uid] = True
                else:
                    hasInterims[uid] = False
                unit = service.getUnit()
                analysis.edit(
                    Result = result,
                    InterimFields = interimFields,
                    Retested = form.has_key('retested') and \
                               form['retested'].has_key(uid),
                    Unit = unit and unit or '')

            # discover which items may be submitted
            submissable = []
            for uid, analysis in selected_analyses.items():
                if uid not in results:
                    continue
                can_submit = True
                if hasattr(analysis, 'getDependencies'):
                    dependencies = analysis.getDependencies()
                    for dependency in dependencies:
                        dep_state = workflow.getInfoFor(dependency, 'review_state')
                        if hasInterims[uid]:
                            if dep_state in ('to_be_sampled', 'to_be_preserved',
                                             'sample_due', 'sample_received',
                                             'attachment_due', 'to_be_verified',):
                                can_submit = False
                                break
                        else:
                            if dep_state in ('to_be_sampled', 'to_be_preserved',
                                             'sample_due', 'sample_received',):
                                can_submit = False
                                break
                    for dependency in dependencies:
                        if workflow.getInfoFor(dependency, 'review_state') in \
                           ('to_be_sampled', 'to_be_preserved',
                            'sample_due', 'sample_received'):
                            can_submit = False
                if can_submit:
                    submissable.append(analysis)

            # and then submit them.
            for analysis in submissable:
                doActionFor(analysis, 'submit')

            message = PMF("Changes saved.")
            self.context.plone_utils.addPortalMessage(message, 'info')
            self.destination_url = self.request.get_header("referer",
                                   self.context.absolute_url())
            self.request.response.redirect(self.destination_url)
        ## assign
        elif action == 'assign':
            if not(getSecurityManager().checkPermission(EditWorksheet, self.context)):
                self.request.response.redirect(self.context.absolute_url())
                return

            selected_analyses = WorkflowAction._get_selected_items(self)
            selected_analysis_uids = selected_analyses.keys()
#.........这里部分代码省略.........
开发者ID:RaulKite,项目名称:Bika-LIMS,代码行数:103,代码来源:worksheet.py

示例14: retractInvalidAnalyses

# 需要导入模块: from bika.lims.browser.bika_listing import WorkflowAction [as 别名]
# 或者: from bika.lims.browser.bika_listing.WorkflowAction import _get_selected_items [as 别名]
    def retractInvalidAnalyses(self):
        """ Retract the analyses with validation pending status for which
            the instrument used failed a QC Test.
        """
        toretract = {}
        instruments = {}
        refs = []
        rc = getToolByName(self.context, REFERENCE_CATALOG)
        selected = WorkflowAction._get_selected_items(self)
        for uid in selected.iterkeys():
            # We need to do this instead of using the dict values
            # directly because all these analyses have been saved before
            # and don't know if they already had an instrument assigned
            an = rc.lookupObject(uid)
            if an.portal_type == 'ReferenceAnalysis':
                refs.append(an)
                instrument = an.getInstrument()
                if instrument and instrument.UID() not in instruments:
                    instruments[instrument.UID()] = instrument

        for instr in instruments.itervalues():
            analyses = instr.getAnalysesToRetract()
            for a in analyses:
                if a.UID() not in toretract:
                    toretract[a.UID] = a

        retracted = []
        for analysis in toretract.itervalues():
            try:
                # add a remark to this analysis
                failedtxt = ulocalized_time(DateTime(), long_format=0)
                failedtxt = '%s: %s' % (failedtxt, _("Instrument failed reference test"))
                analysis.setRemarks(failedtxt)

                # retract the analysis
                doActionFor(analysis, 'retract')
                retracted.append(analysis)
            except:
                # Already retracted as a dependant from a previous one?
                pass

        if len(retracted) > 0:
            # Create the Retracted Analyses List
            rep = AnalysesRetractedListReport(self.context,
                                               self.request,
                                               self.portal_url,
                                               'Retracted analyses',
                                               retracted)

            # Attach the pdf to the ReferenceAnalysis (accessible
            # from Instrument's Internal Calibration Tests list
            pdf = rep.toPdf()
            for ref in refs:
                ref.setRetractedAnalysesPdfReport(pdf)

            # Send the email
            try:
                rep.sendEmail()
            except:
                pass

            # TODO: mostra una finestra amb els resultats publicats d'AS
            # que han utilitzat l'instrument des de la seva última
            # calibració vàlida, amb els emails, telèfons dels
            # contactes associats per a una intervenció manual
            pass
开发者ID:xispa,项目名称:bika.lims,代码行数:68,代码来源:workflow.py

示例15: submit

# 需要导入模块: from bika.lims.browser.bika_listing import WorkflowAction [as 别名]
# 或者: from bika.lims.browser.bika_listing.WorkflowAction import _get_selected_items [as 别名]
    def submit(self):
        """ Saves the form
        """

        form = self.request.form
        remarks = form.get('Remarks', [{}])[0]
        results = form.get('Result',[{}])[0]
        retested = form.get('retested', {})
        methods = form.get('Method', [{}])[0]
        instruments = form.get('Instrument', [{}])[0]
        analysts = self.request.form.get('Analyst', [{}])[0]
        uncertainties = self.request.form.get('Uncertainty', [{}])[0]
        dlimits = self.request.form.get('DetectionLimit', [{}])[0]
        selected = WorkflowAction._get_selected_items(self)
        workflow = getToolByName(self.context, 'portal_workflow')
        rc = getToolByName(self.context, REFERENCE_CATALOG)
        sm = getSecurityManager()

        hasInterims = {}
        # XXX combine data from multiple bika listing tables.
        item_data = {}
        if 'item_data' in form:
            if type(form['item_data']) == list:
                for i_d in form['item_data']:
                    for i, d in json.loads(i_d).items():
                        item_data[i] = d
            else:
                item_data = json.loads(form['item_data'])

        # Iterate for each selected analysis and save its data as needed
        for uid, analysis in selected.items():

            allow_edit = sm.checkPermission(EditResults, analysis)
            analysis_active = isActive(analysis)

            # Need to save remarks?
            if uid in remarks and allow_edit and analysis_active:
                analysis.setRemarks(remarks[uid])

            # Retested?
            if uid in retested and allow_edit and analysis_active:
                analysis.setRetested(retested[uid])

            # Need to save the instrument?
            if uid in instruments and analysis_active:
                # TODO: Add SetAnalysisInstrument permission
                # allow_setinstrument = sm.checkPermission(SetAnalysisInstrument)
                allow_setinstrument = True
                # ---8<-----
                if allow_setinstrument == True:
                    # The current analysis allows the instrument regards
                    # to its analysis service and method?
                    if (instruments[uid]==''):
                        previnstr = analysis.getInstrument()
                        if previnstr:
                            previnstr.removeAnalysis(analysis)
                        analysis.setInstrument(None);
                    elif analysis.isInstrumentAllowed(instruments[uid]):
                        previnstr = analysis.getInstrument()
                        if previnstr:
                            previnstr.removeAnalysis(analysis)
                        analysis.setInstrument(instruments[uid])
                        instrument = analysis.getInstrument()
                        instrument.addAnalysis(analysis)
                        if analysis.meta_type == 'ReferenceAnalysis':
                            instrument.setDisposeUntilNextCalibrationTest(False)

            # Need to save the method?
            if uid in methods and analysis_active:
                # TODO: Add SetAnalysisMethod permission
                # allow_setmethod = sm.checkPermission(SetAnalysisMethod)
                allow_setmethod = True
                # ---8<-----
                if allow_setmethod == True and analysis.isMethodAllowed(methods[uid]):
                    analysis.setMethod(methods[uid])

            # Need to save the analyst?
            if uid in analysts and analysis_active:
                analysis.setAnalyst(analysts[uid]);

            # Need to save the uncertainty?
            if uid in uncertainties and analysis_active:
                analysis.setUncertainty(uncertainties[uid])

            # Need to save the detection limit?
            if analysis_active and uid in dlimits and dlimits[uid]:
                analysis.setDetectionLimitOperand(dlimits[uid])

            # Need to save results?
            if uid in results and results[uid] and allow_edit \
                and analysis_active:
                interims = item_data.get(uid, [])
                analysis.setInterimFields(interims)
                analysis.setResult(results[uid])
                analysis.reindexObject()

                can_submit = True
                deps = analysis.getDependencies() \
                        if hasattr(analysis, 'getDependencies') else []
                for dependency in deps:
#.........这里部分代码省略.........
开发者ID:xispa,项目名称:bika.lims,代码行数:103,代码来源:workflow.py


注:本文中的bika.lims.browser.bika_listing.WorkflowAction._get_selected_items方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。