def __call__(self): form = self.request.form CheckAuthenticator(form) # Save the results interpretation res = form.get('ResultsInterpretationDepts', []) self.context.setResultsInterpretationDepts(res)
def __call__(self): form = self.request.form CheckAuthenticator(self.request.form) attachment_uid = form.get('attachment_uid', None) if not attachment_uid: return "error" uc = getToolByName(self.context, 'uid_catalog') attachment = uc(UID=attachment_uid) if not attachment: return "%s does not exist" % attachment_uid attachment = attachment[0].getObject() for analysis in attachment.getBackReferences("AnalysisAttachment"): analysis.setAttachment([ r for r in analysis.getAttachment() if r.UID() != attachment.UID() ]) for analysis in attachment.getBackReferences( "DuplicateAnalysisAttachment"): analysis.setAttachment([ r for r in analysis.getAttachment() if r.UID() != attachment.UID() ]) attachment.aq_parent.manage_delObjects(ids=[ attachment.getId(), ]) return "success"
def __call__(self): CheckAuthenticator(self.request) PostOnly(self.request) bsc = getToolByName(self.context, 'bika_setup_catalog') service_url = self.request['service_url'] service_id = service_url.split('/')[-1] services = bsc(portal_type='AnalysisService', id=service_id) if services: service = services[0].getObject() service_interims = service.getInterimFields() else: # portal_factory has no service return calc = service.getCalculation() if calc: calc_interims = calc.getInterimFields() else: calc_interims = [] # overwrite existing fields in position for s_i in service_interims: placed = 0 for c_i in calc_interims: if s_i['keyword'] == c_i['keyword']: c_i['value'] = s_i['value'] placed = 1 break if placed: continue # otherwise, create new ones (last) calc_interims.append(s_i) return json.dumps(calc_interims)
def __call__(self): CheckAuthenticator(self.request) uc = getToolByName(self, 'uid_catalog') allow_blank = self.request.get('allow_blank', False) == 'true' show_container_types = json.loads( self.request.get('show_container_types', 'true')) show_containers = json.loads( self.request.get('show_containers', 'true')) minvol = self.request.get("minvol", "0") try: minvol = minvol.split() minvol = mg(float(minvol[0]), " ".join(minvol[1:])) except: minvol = mg(0) containers = getContainers( self.context, minvol=minvol, allow_blank=allow_blank, show_containers=show_containers, show_container_types=show_container_types, ) return json.dumps(containers)
def __call__(self): request = self.request response = request.response form = request.form CheckAuthenticator(form) if form.get('submitted'): csvfile = form.get('csvfile') option = form.get('ImportOption') client_id = form.get('ClientID') valid = False if option in ('c', 'p'): arimport, msg = self._import_file(option, csvfile, client_id) else: msg = "Import Option not yet available" IStatusMessage(request).addStatusMessage(_(msg), "warn") request.response.redirect('%s/arimports' % ( self.context.absolute_url())) return if arimport: msg = "AR Import complete" IStatusMessage(request).addStatusMessage(_(msg), "info") request.response.write( '<script>document.location.href="%s"</script>' % ( arimport.absolute_url())) return else: IStatusMessage(request).addStatusMessage(_(msg), "error") request.response.write( '<script>document.location.href="%s/arimport_add"</script>' % (self.context.absolute_url())) return return self.template()
def __call__(self): CheckAuthenticator(self.request) calcdict = {} uc = getToolByName(self, 'uid_catalog') method = uc(UID=self.request.get("uid", '0')) if method and len(method) == 1: calc = method[0].getObject().getCalculation() if calc: calcdict = {'uid': calc.UID(), 'title': calc.Title()} return json.dumps(calcdict)
def __call__(self): CheckAuthenticator(self.request) wf = getToolByName(self.context, 'portal_workflow') ret = {'ClientTitle': self.context.Title(), 'ClientID': self.context.getClientID(), 'ClientSysID': self.context.id, 'ClientUID': self.context.UID(), 'ContactUIDs' : [c.UID() for c in self.context.objectValues('Contact') if wf.getInfoFor(c, 'inactive_state', '') == 'active'] } return json.dumps(ret)
def __call__(self): CheckAuthenticator(self.request) uid = self.request.get('UID', '') title = self.request.get('Title', '') ret = { 'UID': '', 'Title': '', 'Prefix': '', 'Hazardous': '', 'SampleMatrixUID': '', 'SampleMatrixTitle': '', 'MinimumVolume': '', 'ContainerTypeUID': '', 'ContainerTypeTitle': '', 'SamplePoints': ('', ), 'StorageLocations': ('', ), } proxies = None if uid: try: bsc = getToolByName(self.context, 'bika_setup_catalog') proxies = bsc(UID=uid) except ParseError: pass elif title: try: bsc = getToolByName(self.context, 'bika_setup_catalog') proxies = bsc(portal_type='SampleType', title=to_unicode(title)) except ParseError: pass if proxies and len(proxies) == 1: st = proxies[0].getObject() ret = { 'UID': st.UID(), 'Title': st.Title(), 'Prefix': st.getPrefix(), 'Hazardous': st.getHazardous(), 'SampleMatrixUID': st.getSampleMatrix() and \ st.getSampleMatrix().UID() or '', 'SampleMatrixTitle': st.getSampleMatrix() and \ st.getSampleMatrix().Title() or '', 'MinimumVolume': st.getMinimumVolume(), 'ContainerTypeUID': st.getContainerType() and \ st.getContainerType().UID() or '', 'ContainerTypeTitle': st.getContainerType() and \ st.getContainerType().Title() or '', 'SamplePoints': dict((sp.UID(),sp.Title()) for sp in st.getSamplePoints()), 'StorageLocations': dict((sp.UID(),sp.Title()) for sp in st.getStorageLocations()), } return json.dumps(ret)
def __call__(self): methoddict = {} try: CheckAuthenticator(self.request) except Forbidden: return json.dumps(methoddict) bsc = getToolByName(self, 'bika_setup_catalog') instrument = bsc(portal_type='Instrument', UID=self.request.get("uid", '0')) if instrument and len(instrument) == 1: method = instrument[0].getObject().getMethod() if method: methoddict = {'uid': method.UID(), 'title': method.Title()} return json.dumps(methoddict)
def __call__(self): form = self.request.form CheckAuthenticator(form) action, came_from = WorkflowAction._get_form_workflow_action(self) if type(action) in (list, tuple): action = action[0] if type(came_from) in (list, tuple): came_from = came_from[0] # Call out to the workflow action method # Use default bika_listing.py/WorkflowAction for other transitions method_name = 'workflow_action_' + action method = getattr(self, method_name, False) if method: method() else: WorkflowAction.__call__(self)
def __call__(self): self.rc = getToolByName(self.context, REFERENCE_CATALOG) CheckAuthenticator(self.request) PostOnly(self.request) self.spec = self.request.get('specification', None) # information about the triggering element uid = self.request.get('uid') self.field = self.request.get('field') self.value = self.request.get('value') self.current_results = json.loads(self.request.get('results')) form_results = json.loads(self.request.get('results')) self.item_data = json.loads(self.request.get('item_data')) # these get sent back the the javascript self.alerts = {} self.uncertainties = [] self.results = [] self.services = {} self.analyses = {} # ignore these analyses if objects no longer exist self.ignore_uids = [] for analysis_uid, result in self.current_results.items(): analysis = self.rc.lookupObject(analysis_uid) if not analysis: self.ignore_uids.append(analysis_uid) continue self.analyses[analysis_uid] = analysis if uid not in self.ignore_uids: self.calculate(uid) results = [] for result in self.results: if result['uid'] in form_results.keys() and \ result['result'] != form_results[result['uid']]: results.append(result) return json.dumps({ 'alerts': self.alerts, 'uncertainties': self.uncertainties, 'results': results })
def __call__(self): try: CheckAuthenticator(self.request) PostOnly(self.request) except: return "" mtool = getToolByName(self.context, 'portal_membership') uc = getToolByName(self.context, 'uid_catalog') entry = self.request.get("entry", '').replace("*", "") items = uc(UID=entry) if not items: return "" item = items[0].getObject() if item.portal_type == "AnalysisRequest": if mtool.checkPermission(EditResults, item): destination_url = item.absolute_url() + "/manage_results" else: destination_url = item.absolute_url() return self.request.response.redirect(destination_url) elif item.portal_type == "Sample": ars = item.getAnalysisRequests() if len(ars) == 1: # If there's only one AR, go there if mtool.checkPermission(EditResults, ars[0]): destination_url = ars[0].absolute_url() + "/manage_results" else: destination_url = ars[0].absolute_url() return self.request.response.redirect(destination_url) else: # multiple or no ARs: direct to sample. destination_url = item.absolute_url() return self.request.response.redirect(destination_url) elif item.portal_type == "Worksheet": if mtool.checkPermission(EditWorksheet, item): destination_url = item.absolute_url() return self.request.response.redirect(destination_url) elif item.portal_type == "ReferenceSample": destination_url = item.absolute_url() return self.request.response.redirect(destination_url)
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)
def __call__(self): CheckAuthenticator(self.request) field = self.context.Schema()["Remarks"] value = self.request['value'].strip() + "\n\n" existing = self.context.getRemarks( mimetype='text/x-web-intelligent').strip() date = DateTime().rfc822() user = getSecurityManager().getUser() divider = "=== %s (%s)\n" % (date, user) remarks = convertWebIntelligentPlainTextToHtml(divider) + \ convertWebIntelligentPlainTextToHtml(value) + \ convertWebIntelligentPlainTextToHtml(existing) self.context.setRemarks(divider + value + existing, mimetype='text/x-web-intelligent') return remarks.strip()
def __call__(self): CheckAuthenticator(self.request) bsc = getToolByName(self.context, 'bika_setup_catalog') term = safe_unicode(self.request.get('term', '')).lower() items = [] if not term: return json.dumps(items) samplepoint = safe_unicode(self.request.get('samplepoint', '')) # Strip "Lab: " from sample point titles samplepoint = samplepoint.replace("%s: " % _("Lab"), '') if samplepoint and len(samplepoint) > 1: sp = bsc(portal_type="SamplePoint", inactive_state='active', title=samplepoint) if not sp: return json.dumps([]) sp = sp[0].getObject() items = sp.getSampleTypes() if not items: items = bsc(portal_type="SampleType", inactive_state='active', sort_on='sortable_title') if term and len(term) < 3: # Items that start with A or AA items = [ s.getObject() for s in items if s.title.lower().startswith(term) ] if not items: # or, items that contain A or AA items = [ s.getObject() for s in items if s.title.lower().find(term) > -1 ] else: # or, items that contain term. items = [ s.getObject() for s in items if s.title.lower().find(term) > -1 ] items = [callable(s.Title) and s.Title() or s.title for s in items] return json.dumps(items)
def __call__(self): instruments = [] try: CheckAuthenticator(self.request) except Forbidden: return json.dumps(instruments) bsc = getToolByName(self, 'portal_catalog') method = bsc(portal_type='Method', UID=self.request.get("uid", '0')) if method and len(method) == 1: method = method[0].getObject() for i in method.getInstruments(): instrument = { 'uid' : i.UID(), 'title': i.Title(), 'url': i.absolute_url_path(), 'outofdate': i.isOutOfDate(), 'qcfail': not i.isQCValid(), 'isvalid': i.isValid()} instruments.append(instrument) return json.dumps(instruments)
def __call__(self): instruments = [] try: CheckAuthenticator(self.request) except Forbidden: return json.dumps(instruments) uc = getToolByName(self, 'uid_catalog') service = uc(portal_type='AnalysisService', UID=self.request.get("suid", '0')) if not service or len(service) != 1: return json.dumps(instruments) service = service[0].getObject() sinstr = service.getAvailableInstruments() if not sinstr: return json.dumps(instruments) method = uc(portal_type='Method', UID=self.request.get("muid", '0')) if not method or len(method) != 1: for i in sinstr: if not i.getMethod(): instrument = { 'uid' : i.UID(), 'title': i.Title(), 'url': i.absolute_url_path(), 'outofdate': i.isOutOfDate(), 'qcfail': not i.isQCValid(), 'isvalid': i.isValid()} instruments.append(instrument) return json.dumps(instruments) method = method[0].getObject() iuids = [s.UID() for s in sinstr] for i in method.getInstruments(): if i.UID() in iuids: instrument = { 'uid' : i.UID(), 'title': i.Title(), 'url': i.absolute_url_path(), 'outofdate': i.isOutOfDate(), 'qcfail': not i.isQCValid(), 'isvalid': i.isValid()} instruments.append(instrument) return json.dumps(instruments)
def __call__(self): CheckAuthenticator(self.request) searchTerm = self.request['searchTerm'].lower() page = self.request['page'] nr_rows = self.request['rows'] sord = self.request['sord'] sidx = self.request['sidx'] rows = [] batches = self.bika_catalog(portal_type='Batch') for batch in batches: batch = batch.getObject() if self.portal_workflow.getInfoFor(batch, 'review_state', 'open') != 'open' \ or self.portal_workflow.getInfoFor(batch, 'cancellation_state') == 'cancelled': continue if batch.Title().lower().find(searchTerm) > -1 \ or batch.Description().lower().find(searchTerm) > -1: rows.append({ 'BatchID': batch.getBatchID(), 'Description': batch.Description(), 'BatchUID': batch.UID() }) rows = sorted(rows, cmp=lambda x, y: cmp(x.lower(), y.lower()), key=itemgetter(sidx and sidx or 'BatchID')) if sord == 'desc': rows.reverse() pages = len(rows) / int(nr_rows) pages += divmod(len(rows), int(nr_rows))[1] and 1 or 0 ret = { 'page': page, 'total': pages, 'records': len(rows), 'rows': rows[(int(page) - 1) * int(nr_rows):int(page) * int(nr_rows)] } return json.dumps(ret)
def __call__(self): CheckAuthenticator(self.request) # get Supplier from request supplier = self.request.form.get('SupplierUID', '') supplier = self.reference_catalog.lookupObject(supplier) if supplier: # get ReferenceSamples for this supplier samples = self.bika_catalog(portal_type='ReferenceSample', path={"query": "/".join( supplier.getPhysicalPath()), "level": 0}) ret = [] for sample in samples: sample = sample.getObject() UID = sample.UID() title = sample.Title() definition = sample.getReferenceDefinition() if definition: title = "%s (%s)" % (title, definition.Title()) ret.append((UID, title)) return json.dumps(ret)
def __call__(self): CheckAuthenticator(self.request) # get Sample from request sample = self.request.form.get('ReferenceSampleUID', '') sample = self.reference_catalog.lookupObject(sample) if sample: # get ReferenceSamples for this supplier analyses = self.bika_analysis_catalog(portal_type='ReferenceAnalysis', path={"query": "/".join( sample.getPhysicalPath()), "level": 0}) ret = {} for analysis in analyses: service = analysis.getObject().getService() if service.UID() in ret: ret[service.UID()]['analyses'].append(analysis.UID) else: ret[service.UID()] = {'title': service.Title(), 'analyses': [analysis.UID, ]} ret = [[k, v['title'], v['analyses']] for k, v in ret.items()] return json.dumps(ret)
def __call__(self): CheckAuthenticator(self.request) searchTerm = 'searchTerm' in self.request and self.request[ 'searchTerm'].lower() or '' page = self.request['page'] nr_rows = self.request['rows'] sord = self.request['sord'] sidx = self.request['sidx'] rows = [] # lookup objects from ZODB catalog = getToolByName(self.context, self.catalog_name) brains = catalog(self.contentFilter) brains = searchTerm and \ [p for p in brains if p.Title.lower().find(searchTerm) > -1] \ or brains rows = [{ 'UID': p.UID, 'container_uid': p.UID, 'Container': p.Title, 'Description': p.Description } for p in brains] rows = sorted(rows, cmp=lambda x, y: cmp(x.lower(), y.lower()), key=itemgetter(sidx and sidx or 'Container')) if sord == 'desc': rows.reverse() pages = len(rows) / int(nr_rows) pages += divmod(len(rows), int(nr_rows))[1] and 1 or 0 ret = { 'page': page, 'total': pages, 'records': len(rows), 'rows': rows[(int(page) - 1) * int(nr_rows):int(page) * int(nr_rows)] } return json.dumps(ret)
def __call__(self): CheckAuthenticator(self.request) bsc = getToolByName(self.context, 'bika_setup_catalog') term = safe_unicode(self.request.get('term', '')).lower() if not term: return json.dumps([]) client_items = lab_items = [] # User (client) storage locations if self.context.portal_type == 'Client': client_path = self.context.getPhysicalPath() client_items = list( bsc(portal_type = "StorageLocation", path = {"query": "/".join(client_path), "level" : 0 }, inactive_state = 'active', sort_on='sortable_title')) # Global (lab) storage locations lab_path = \ self.context.bika_setup.bika_storagelocations.getPhysicalPath() lab_items = list( bsc(portal_type = "StorageLocation", path = {"query": "/".join(lab_path), "level" : 0 }, inactive_state = 'active', sort_on='sortable_title')) client_items = [callable(s.Title) and s.Title() or s.title for s in self.filter_list(client_items, term)] lab_items = [callable(s.Title) and s.Title() or s.title for s in self.filter_list(lab_items, term)] lab_items = ["%s: %s" % (_("Lab"), safe_unicode(i)) for i in lab_items] items = client_items + lab_items return json.dumps(items)
def __call__(self): CheckAuthenticator(self.request) searchTerm = self.request.get('searchTerm', '').lower() page = self.request.get('page', 1) nr_rows = self.request.get('rows', 20) sord = self.request.get('sord', 'asc') sidx = self.request.get('sidx', '') wf = getToolByName(self.context, 'portal_workflow') clients = (x.getObject() for x in self.portal_catalog(portal_type="Client", inactive_state='active')) rows = [{ 'ClientID': b.getClientID() and b.getClientID() or '', 'Title': b.Title(), 'ClientUID': b.UID() } for b in clients if b.Title().lower().find(searchTerm) > -1 or b.getClientID().lower().find(searchTerm) > -1 or b.Description().lower().find(searchTerm) > -1] rows = sorted(rows, cmp=lambda x, y: cmp(x.lower(), y.lower()), key=itemgetter(sidx and sidx or 'Title')) if sord == 'desc': rows.reverse() pages = len(rows) / int(nr_rows) pages += divmod(len(rows), int(nr_rows))[1] and 1 or 0 ret = { 'page': page, 'total': pages, 'records': len(rows), 'rows': rows[(int(page) - 1) * int(nr_rows):int(page) * int(nr_rows)] } return json.dumps(ret)
def __call__(self): CheckAuthenticator(self.request) searchTerm = self.request['searchTerm'].lower() page = self.request['page'] nr_rows = self.request['rows'] sord = self.request['sord'] sidx = self.request['sidx'] rows = [] ars = [] for x in [ a.getObject() for a in self.bika_catalog(portal_type='AnalysisRequest', cancellation_state='active', sort_on="created", sort_order="desc") ]: if searchTerm in x.Title().lower(): ars.append(x) batches = [] for x in [ a.getObject() for a in self.bika_catalog(portal_type='Batch', cancellation_state='active', sort_on="created", sort_order="desc") ]: if searchTerm in x.Title().lower() \ or searchTerm in x.Schema()['BatchID'].get(x).lower() \ or searchTerm in x.Schema()['ClientBatchID'].get(x).lower(): batches.append(x) _rows = [] for item in batches: _rows.append({ 'Title': item.Title(), 'ObjectID': item.id, 'Description': item.Description(), 'UID': item.UID() }) _rows = sorted(_rows, cmp=lambda x, y: cmp(x.lower(), y.lower()), key=itemgetter(sidx and sidx or 'Title')) rows += _rows _rows = [] for item in ars: _rows.append({ 'Title': item.Title(), 'ObjectID': item.id, 'Description': item.Description(), 'UID': item.UID() }) _rows = sorted(_rows, cmp=lambda x, y: cmp(x.lower(), y.lower()), key=itemgetter(sidx and sidx or 'Title')) rows += _rows if sord == 'desc': rows.reverse() pages = len(rows) / int(nr_rows) pages += divmod(len(rows), int(nr_rows))[1] and 1 or 0 start = (int(page) - 1) * int(nr_rows) end = int(page) * int(nr_rows) ret = { 'page': page, 'total': pages, 'records': len(rows), 'rows': rows[start:end] } return json.dumps(ret)
def __call__(self): CheckAuthenticator(self.request) bsc = getToolByName(self.context, 'bika_setup_catalog') term = safe_unicode(self.request.get('term', '')).lower() items = [] if not term: return json.dumps(items) # Strip "Lab: " from sample point title term = term.replace("%s: " % _("Lab"), '') sampletype = safe_unicode(self.request.get('sampletype', '')) if sampletype and len(sampletype) > 1: st = bsc(portal_type="SampleType", title=sampletype, inactive_state='active') if not st: return json.dumps([]) st = st[0].getObject() items = [o.Title() for o in st.getSamplePoints()] if not items: client_items = lab_items = [] # User (client) sample points if self.context.portal_type in ('Client', 'AnalysisRequest'): if self.context.portal_type == 'Client': client_path = self.context.getPhysicalPath() else: client_path = self.context.aq_parent.getPhysicalPath() client_items = list( bsc(portal_type="SamplePoint", path={ "query": "/".join(client_path), "level": 0 }, inactive_state='active', sort_on='sortable_title')) # Global (lab) sample points lab_path = self.context.bika_setup.bika_samplepoints.getPhysicalPath( ) lab_items = list( bsc(portal_type="SamplePoint", path={ "query": "/".join(lab_path), "level": 0 }, inactive_state='active', sort_on='sortable_title')) client_items = [ callable(s.Title) and s.Title() or s.title for s in self.filter_list(client_items, term) ] lab_items = [ callable(s.Title) and s.Title() or s.title for s in self.filter_list(lab_items, term) ] lab_items = [ "%s: %s" % (_("Lab"), safe_unicode(i)) for i in lab_items ] items = client_items + lab_items return json.dumps(items)
def __call__(self): form = self.request.form CheckAuthenticator(self.request.form) PostOnly(self.request.form) uc = getToolByName(self.context, 'uid_catalog') bsc = getToolByName(self.context, 'bika_setup_catalog') portal_catalog = getToolByName(self.context, 'portal_catalog') # Load the form data from request.state. If anything goes wrong here, # put a bullet through the whole process. try: states = json.loads(form['state']) except Exception as e: message = t( _('Badly formed state: ${errmsg}', mapping={'errmsg': e.message})) ajax_form_error(self.errors, message=message) return json.dumps({'errors': self.errors}) # Validate incoming form data required = [ field.getName() for field in AnalysisRequestSchema.fields() if field.required ] + ["Analyses"] # First remove all states which are completely empty; if all # required fields are not present, we assume that the current # AR had no data entered, and can be ignored nonblank_states = {} for arnum, state in states.items(): for key, val in state.items(): if val \ and "%s_hidden" % key not in state \ and not key.endswith('hidden'): nonblank_states[arnum] = state break # in valid_states, all ars that pass validation will be stored valid_states = {} for arnum, state in nonblank_states.items(): # Secondary ARs are a special case, these fields are not required if state.get('Sample', ''): if 'SamplingDate' in required: required.remove('SamplingDate') if 'SampleType' in required: required.remove('SampleType') # fields flagged as 'hidden' are not considered required because # they will already have default values inserted in them for fieldname in required: if fieldname + '_hidden' in state: required.remove(fieldname) missing = [f for f in required if not state.get(f, '')] # If there are required fields missing, flag an error if missing: msg = t( _('Required fields have no values: ' '${field_names}', mapping={'field_names': ', '.join(missing)})) ajax_form_error(self.errors, arnum=arnum, message=msg) continue # This ar is valid! valid_states[arnum] = state # - Expand lists of UIDs returned by multiValued reference widgets # - Transfer _uid values into their respective fields for arnum in valid_states.keys(): for field, value in valid_states[arnum].items(): if field.endswith('_uid') and ',' in value: valid_states[arnum][field] = value.split(',') elif field.endswith('_uid'): valid_states[arnum][field] = value if self.errors: return json.dumps({'errors': self.errors}) # Now, we will create the specified ARs. ARs = [] for arnum, state in valid_states.items(): # Create the Analysis Request ar = create_analysisrequest( portal_catalog(UID=state['Client'])[0].getObject(), self.request, state) ARs.append(ar.Title()) # Display the appropriate message after creation if len(ARs) > 1: message = _('Analysis requests ${ARs} were successfully created.', mapping={'ARs': safe_unicode(', '.join(ARs))}) else: message = _('Analysis request ${AR} was successfully created.', mapping={'AR': safe_unicode(ARs[0])}) self.context.plone_utils.addPortalMessage(message, 'info') # Automatic label printing won't print "register" labels for Secondary. ARs new_ars = [ar for ar in ARs if ar[-2:] == '01'] if 'register' in self.context.bika_setup.getAutoPrintStickers() \ and new_ars: return json.dumps({ 'success': message, 'stickers': new_ars, 'stickertemplate': self.context.bika_setup.getAutoStickerTemplate() }) else: return json.dumps({'success': message})
def __call__(self): CheckAuthenticator(self.request) bsc = getToolByName(self.context, 'bika_setup_catalog') uc = getToolByName(self.context, 'uid_catalog') service_title = self.request.get('service_title', '').strip() if not service_title: return '' analysis = uc(UID=self.request.get('analysis_uid', None)) if analysis: analysis = analysis[0].getObject() self.request['ajax_load'] = 1 tmp = LogView(analysis, self.request) self.log = tmp.folderitems() self.log.reverse() else: self.log = [] brains = bsc(portal_type="AnalysisService", title=to_unicode(service_title)) if not brains: return '' self.service = brains[0].getObject() self.calc = self.service.getCalculation() self.partsetup = self.service.getPartitionSetup() # convert uids to comma-separated list of display titles for i, ps in enumerate(self.partsetup): self.partsetup[i]['separate'] = \ ps.has_key('separate') and _('Yes') or _('No') if type(ps['sampletype']) == str: ps['sampletype'] = [ ps['sampletype'], ] sampletypes = [] for st in ps['sampletype']: res = bsc(UID=st) sampletypes.append(res and res[0].Title or st) self.partsetup[i]['sampletype'] = ", ".join(sampletypes) if ps.has_key('container'): if type(ps['container']) == str: self.partsetup[i]['container'] = [ ps['container'], ] try: containers = [bsc(UID=c)[0].Title for c in ps['container']] except IndexError: containers = [c for c in ps['container']] self.partsetup[i]['container'] = ", ".join(containers) else: self.partsetup[i]['container'] = '' if ps.has_key('preservation'): if type(ps['preservation']) == str: ps['preservation'] = [ ps['preservation'], ] try: preservations = [ bsc(UID=c)[0].Title for c in ps['preservation'] ] except IndexError: preservations = [c for c in ps['preservation']] self.partsetup[i]['preservation'] = ", ".join(preservations) else: self.partsetup[i]['preservation'] = '' return self.template()
def __call__(self): CheckAuthenticator(self.request) page = self.request['page'] nr_rows = self.request['rows'] sord = self.request['sord'] sidx = self.request['sidx'] colModel = json.loads(_u(self.request.get('colModel', '[]'))) discard_empty = json.loads(_c(self.request.get('discard_empty', "[]"))) rows = [] brains = [] for name, adapter in getAdapters((self.context, self.request), IReferenceWidgetVocabulary): brains.extend(adapter()) for p in brains: row = {'UID': getattr(p, 'UID'), 'Title': getattr(p, 'Title')} other_fields = [ x for x in colModel if x['columnName'] not in row.keys() ] instance = schema = None discard = False # This will be faster if the columnNames are catalog indexes for field in other_fields: fieldname = field['columnName'] # Prioritize method retrieval over field retrieval from schema obj = p.getObject() value = getattr(obj, fieldname, None) if not value or hasattr(value, 'im_self'): value = getattr(p, fieldname, None) if not value: if instance is None: instance = p.getObject() schema = instance.Schema() if fieldname in schema: value = schema[fieldname].get(instance) elif hasattr(instance, fieldname): value = getattr(instance, fieldname) if callable(value): value = value() if fieldname in discard_empty and not value: discard = True break # ' ' instead of '' because empty div fields don't render # correctly in combo results table row[fieldname] = value and value or ' ' if discard is False: rows.append(row) rows = sorted(rows, cmp=lambda x, y: cmp(str(x).lower(), str(y).lower()), key=itemgetter(sidx and sidx or 'Title')) if sord == 'desc': rows.reverse() pages = len(rows) / int(nr_rows) pages += divmod(len(rows), int(nr_rows))[1] and 1 or 0 start = (int(page) - 1) * int(nr_rows) end = int(page) * int(nr_rows) ret = { 'page': page, 'total': pages, 'records': len(rows), 'rows': rows[start:end] } return json.dumps(ret)
def __call__(self): form = self.request.form CheckAuthenticator(form) self.context = aq_inner(self.context) workflow = getToolByName(self.context, 'portal_workflow') bc = getToolByName(self.context, 'bika_catalog') rc = getToolByName(self.context, REFERENCE_CATALOG) translate = self.context.translate checkPermission = self.context.portal_membership.checkPermission # use came_from to decide which UI action was clicked. # "workflow_action" is the action name specified in the # portal_workflow transition url. came_from = "workflow_action" action = form.get(came_from, '') if not action: # workflow_action_button is the action name specified in # the bika_listing_view table buttons. came_from = "workflow_action_button" action = form.get('workflow_action_id', '') if not action: if self.destination_url == "": self.destination_url = self.request.get_header("referer", self.context.absolute_url()) self.request.response.redirect(self.destination_url) return if action == "sample": objects = AnalysisRequestWorkflowAction._get_selected_items(self) transitioned = {'to_be_preserved':[], 'sample_due':[]} for obj_uid, obj in objects.items(): if obj.portal_type == "AnalysisRequest": ar = obj sample = obj.getSample() else: sample = obj ar = sample.aq_parent # can't transition inactive items if workflow.getInfoFor(sample, 'inactive_state', '') == 'inactive': continue # grab this object's Sampler and DateSampled from the form # (if the columns are available and edit controls exist) if 'getSampler' in form and 'getDateSampled' in form: try: Sampler = form['getSampler'][0][obj_uid].strip() DateSampled = form['getDateSampled'][0][obj_uid].strip() except KeyError: continue Sampler = Sampler and Sampler or '' DateSampled = DateSampled and DateTime(DateSampled) or '' else: continue # write them to the sample sample.setSampler(Sampler) sample.setDateSampled(DateSampled) sample.reindexObject() ars = sample.getAnalysisRequests() # Analyses and AnalysisRequets have calculated fields # that are indexed; re-index all these objects. for ar in ars: ar.reindexObject() analyses = sample.getAnalyses({'review_state':'to_be_sampled'}) for a in analyses: a.getObject().reindexObject() # transition the object if both values are present if Sampler and DateSampled: workflow.doActionFor(sample, action) new_state = workflow.getInfoFor(sample, 'review_state') doActionFor(ar, action) transitioned[new_state].append(sample.Title()) message = None for state in transitioned: tlist = transitioned[state] if len(tlist) > 1: if state == 'to_be_preserved': message = _('${items} are waiting for preservation.', mapping = {'items': ', '.join(tlist)}) else: message = _('${items} are waiting to be received.', mapping = {'items': ', '.join(tlist)}) self.context.plone_utils.addPortalMessage(message, 'info') elif len(tlist) == 1: if state == 'to_be_preserved': message = _('${item} is waiting for preservation.', mapping = {'item': ', '.join(tlist)}) else: message = _('${item} is waiting to be received.', mapping = {'item': ', '.join(tlist)}) self.context.plone_utils.addPortalMessage(message, 'info') if not message: message = _('No changes made.') 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) elif action == "preserve": objects = AnalysisRequestWorkflowAction._get_selected_items(self) transitioned = {} not_transitioned = [] Preserver = str() DatePreserved = str() for obj_uid, obj in objects.items(): if obj.portal_type == "AnalysisRequest": ar = obj sample = obj.getSample() else: sample = obj ar = sample.aq_parent # can't transition inactive items if workflow.getInfoFor(sample, 'inactive_state', '') == 'inactive': continue if not checkPermission(PreserveSample, sample): continue # grab this object's Preserver and DatePreserved from the form # (if the columns are available and edit controls exist) if 'getPreserver' in form and 'getDatePreserved' in form: try: Preserver = form['getPreserver'][0][obj_uid].strip() DatePreserved = form['getDatePreserved'][0][obj_uid].strip() except KeyError: continue Preserver = Preserver and Preserver or '' DatePreserved = DatePreserved and DateTime(DatePreserved) or '' else: continue for sp in sample.objectValues("SamplePartition"): if workflow.getInfoFor(sp, 'review_state') == 'to_be_preserved': sp.setDatePreserved(DatePreserved) sp.setPreserver(Preserver) for sp in sample.objectValues("SamplePartition"): if workflow.getInfoFor(sp, 'review_state') == 'to_be_preserved': if Preserver and DatePreserved: doActionFor(sp, action) transitioned[sp.aq_parent.Title()] = sp.Title() else: not_transitioned.append(sp) if len(transitioned.keys()) > 1: message = _('${items}: partitions are waiting to be received.', mapping = {'items': ', '.join(transitioned.keys())}) else: message = _('${item}: ${part} is waiting to be received.', mapping = {'item': ', '.join(transitioned.keys()), 'part': ', '.join(transitioned.values()),}) self.context.plone_utils.addPortalMessage(message, 'info') # And then the sample itself if Preserver and DatePreserved and not not_transitioned: doActionFor(sample, action) #message = _('${item} is waiting to be received.', # mapping = {'item': sample.Title()}) #message = t(message) #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) elif action in ('prepublish', 'publish', 'republish'): # We pass a list of AR objects to Publish. # it returns a list of AR IDs which were actually published. objects = AnalysisRequestWorkflowAction._get_selected_items(self) its = [] for uid, obj in objects.items(): if isActive(obj): its.append(uid); its = ",".join(its) q = "/publish?items=" + its dest = self.portal_url+"/analysisrequests" + q self.request.response.redirect(dest) else: AnalysisRequestWorkflowAction.__call__(self)
def __call__(self): CheckAuthenticator(self.request) exim = self.request.get('exim').replace(".", "/") return ViewPageTemplateFile("instruments/%s_import.pt" % exim)(self)