def __init__(self, context, request): BikaListingView.__init__(self, context, request) self.content_add_actions = {} self.contentFilter = {'portal_type': 'Analysis', 'review_state':'impossible_state'} self.base_url = self.context.absolute_url() self.view_url = self.base_url + "/add_analyses" self.show_sort_column = False self.show_select_row = False self.show_select_column = True self.pagesize = 100 self.columns = { 'ClientName': {'title': _('Client')}, 'getClientOrderNumber': {'title': _('Order')}, 'getRequestID': {'title': _('Request ID')}, 'CategoryName': {'title': _('Category')}, 'Title': {'title': _('Analysis')}, 'getDateReceived': {'title': _('Date Received')}, 'getDueDate': {'title': _('Due Date')}, } self.review_states = [ {'title': _('All'), 'id':'all', 'transitions': ['assign'], 'columns':['ClientName', 'getClientOrderNumber', 'getRequestID', 'CategoryName', 'Title', 'getDateReceived', 'getDueDate'], }, ]
def __init__(self, context, request, fieldvalue, allow_edit): BikaListingView.__init__(self, context, request) self.context_actions = {} self.contentFilter = {'review_state' : 'impossible_state'} self.context_actions = {} self.base_url = self.context.absolute_url() self.view_url = self.base_url self.show_sort_column = False self.show_select_row = False self.show_select_all_checkbox = False self.show_select_column = False self.pagesize = 1000 self.allow_edit = allow_edit self.specsresults = {} for specresults in fieldvalue: self.specsresults[specresults['keyword']] = specresults self.columns = { 'service': {'title': _('Service'), 'index': 'sortable_title', 'sortable': False}, 'min': {'title': _('Min'), 'sortable': False,}, 'max': {'title': _('Max'), 'sortable': False,}, 'error': {'title': _('Permitted Error %'), 'sortable': False}, } self.review_states = [ {'id':'default', 'title': _('All'), 'contentFilter':{}, 'transitions': [], 'columns': ['service', 'min', 'max', 'error'], }, ]
def __init__(self, context, request): BikaListingView.__init__(self, context, request) self.context_actions = {} self.catalog = 'bika_setup_catalog' self.contentFilter = {'review_state':'impossible_state'} self.base_url = self.context.absolute_url() self.view_url = self.context.absolute_url() self.show_sort_column = False self.show_select_row = False self.show_select_all_checkbox = False self.show_select_column = True self.pagesize = 999999 self.show_workflow_action_buttons = False self.show_categories=context.bika_setup.getCategoriseAnalysisServices() self.expand_all_categories = False self.ajax_categories = True self.ajax_categories_url = self.base_url + '/service_view' self.category_index = 'getCategoryTitle' self.columns = { 'Service': {'title': _('Service'), 'sortable': False}, } self.review_states = [ {'id':'default', 'title': _('All'), 'contentFilter': {}, 'transitions': [], 'columns':['Service'], }, ]
def __init__(self, context, request): BikaListingView.__init__(self, context, request) self.context_actions = {} self.catalog = 'bika_setup_catalog' self.contentFilter = {'review_state':'impossible_state'} self.base_url = self.context.absolute_url() self.view_url = self.context.absolute_url() self.show_sort_column = False self.show_select_row = False self.show_select_all_checkbox = False self.show_select_column = True self.pagesize = 1000 self.show_workflow_action_buttons = False self.columns = { 'Service': {'title': _('Service'), 'sortable': False}, } self.review_states = [ {'id':'default', 'title': _('All'), 'contentFilter': {}, 'transitions': [], 'columns':['Service'], }, ]
def __init__(self, context, request, **kwargs): BikaListingView.__init__(self, context, request, **kwargs) self.form_id = "instrumentcertifications" self.columns = { 'Title': {'title': _('Cert. Num'), 'index': 'sortable_title'}, 'getAgency': {'title': _('Agency')}, 'getDate': {'title': _('Date')}, 'getValidFrom': {'title': _('Valid from')}, 'getValidTo': {'title': _('Valid to')}, 'getDocument': {'title': _('Document')}, } self.review_states = [ {'id':'default', 'title':_('All'), 'contentFilter':{}, 'columns': [ 'Title', 'getAgency', 'getDate', 'getValidFrom', 'getValidTo', 'getDocument'], 'transitions': [{}]}, ] self.allow_edit = False self.show_select_column = False self.show_workflow_action_buttons = False uids = [c.UID() for c in self.context.getCertifications()] self.catalog = 'portal_catalog' self.contentFilter = {'UID': uids, 'sort_on': 'sortable_title'}
def __init__(self, context, request, field): BikaListingView.__init__(self, context, request) self.selected = [o.UID() for o in getattr(field, field.accessor)()] self.context_actions = {} self.catalog = "bika_setup_catalog" self.contentFilter = {'review_state': 'impossible_state'} self.base_url = self.context.absolute_url() self.view_url = self.base_url self.show_categories = True self.show_sort_column = False self.show_select_row = False self.show_select_all_checkbox = False self.show_select_column = True self.pagesize = 1000 self.form_id = 'serviceswidget' self.columns = { 'Service': {'title': _('Service')}, 'Keyword': {'title': _('Keyword'), 'index': 'getKeyword'}, 'Method': {'title': _('Method')}, 'Calculation': {'title': _('Calculation')}, } self.review_states = [ {'id':'default', 'title': _('All'), 'contentFilter':{}, 'transitions': [], 'columns':['Service', 'Keyword', 'Method', 'Calculation', ] }, ]
def __init__(self, context, request, fieldvalue, allow_edit): BikaListingView.__init__(self, context, request) self.context_actions = {} self.contentFilter = {"review_state": "impossible_state"} self.base_url = self.context.absolute_url() self.view_url = self.base_url self.show_sort_column = False self.show_select_row = False self.show_select_all_checkbox = False self.show_column_toggles = False self.show_select_column = False self.pagesize = 1000 self.allow_edit = allow_edit self.form_id = "partitions" self.columns = { "part_id": {"title": _("Partition"), "sortable": False}, "container_uid": {"title": _("Container"), "sortable": False}, "preservation_uid": {"title": _("Preservation"), "sortable": False}, } self.review_states = [ { "id": "default", "title": _("All"), "contentFilter": {}, "transitions": [{"id": "empty"}], # none "columns": ["part_id", "container_uid", "preservation_uid"], } ] self.fieldvalue = fieldvalue
def __init__(self, context, request, fieldvalue, allow_edit): BikaListingView.__init__(self, context, request) self.context_actions = {} self.contentFilter = {'review_state': 'impossible_state'} self.base_url = self.context.absolute_url() self.view_url = self.base_url self.show_sort_column = False self.show_select_row = False self.show_select_all_checkbox = False self.show_select_column = False self.setoddeven = False self.pagesize = 1000 self.allow_edit = allow_edit self.referenceresults = {} # we want current field value as a dict # key:uid, value:{dictionary from field list of dict} for refres in fieldvalue: self.referenceresults[refres['uid']] = refres self.columns = { 'service': {'title': _('Service')}, 'result': {'title': _('Expected Result')}, 'error': {'title': _('Permitted Error %')}, 'min': {'title': _('Min')}, 'max': {'title': _('Max')} } self.review_states = [ {'id':'default', 'title': _('All'), 'contentFilter':{}, 'transitions': [], 'columns':['service', 'result', 'error', 'min', 'max'], }, ]
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 = 1000 self.icon = "++resource++bika.lims.images/%s_big.png" % \ context.portal_type.lower() self.title = "%s %s" % (self.context.Title(), self.context.translate(_("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']}, ]
def __init__(self, context, request, fieldvalue, allow_edit): BikaListingView.__init__(self, context, request) self.context_actions = {} self.contentFilter = {'review_state': 'impossible_state'} self.base_url = self.context.absolute_url() self.view_url = self.base_url self.show_sort_column = False self.show_select_row = False self.show_select_all_checkbox = False self.show_column_toggles = False self.show_select_column = False self.setoddeven = False self.pagesize = 1000 self.allow_edit = allow_edit self.form_id = "partitions" self.columns = { 'part_id': {'title': _('Partition'), 'sortable': False,}, 'container_uid': {'title': _('Container'), 'sortable': False,}, 'preservation_uid': {'title': _('Preservation'), 'sortable': False,}, } self.review_states = [ {'id':'default', 'title': _('All'), 'contentFilter':{}, 'transitions': [{'id':'empty'}], # none 'columns':['part_id', 'container_uid', 'preservation_uid'], }, ] self.fieldvalue = fieldvalue
def __init__(self, context, request): BikaListingView.__init__(self, context, request) self.context_actions = {} self.catalog = 'bika_analysis_catalog' self.contentFilter = {'portal_type': 'Analysis', 'review_state':'impossible_state'} self.base_url = self.context.absolute_url() self.view_url = self.context.absolute_url() + "/add_duplicate" self.show_sort_column = False self.show_select_row = False self.show_select_all_checkbox = False self.show_select_column = False self.columns = { 'Position': {'title': _('Position')}, 'RequestID': {'title': _('Request ID')}, 'Client': {'title': _('Client')}, 'created': {'title': _('Date Requested')}, } self.review_states = [ {'id':'default', 'title': _('All'), 'contentFilter':{}, 'transitions': [], 'columns':['Position', 'RequestID', 'Client', 'created'], }, ]
def __init__(self, context, request): BikaListingView.__init__(self, context, request) self.icon = "++resource++bika.lims.images/worksheet_big.png" self.title = _("Add Analyses") self.description = "" self.catalog = "bika_analysis_catalog" self.context_actions = {} # initial review state for first form display of the worksheet # add_analyses search view - first batch of analyses, latest first. self.contentFilter = {'portal_type': 'Analysis', 'review_state':'sample_received', 'worksheetanalysis_review_state':'unassigned', 'cancellation_state':'active'} self.base_url = self.context.absolute_url() self.view_url = self.base_url + "/add_analyses" self.show_sort_column = False self.show_select_row = False self.show_select_column = True self.pagesize = 50 self.columns = { 'Client': { 'title': _('Client'), 'index':'getClientTitle'}, 'getClientOrderNumber': { 'title': _('Order'), 'index': 'getClientOrderNumber'}, 'getRequestID': { 'title': _('Request ID'), 'index': 'getRequestID'}, 'CategoryTitle': { 'title': _('Category'), 'index':'getCategoryTitle'}, 'Title': { 'title': _('Analysis'), 'index':'sortable_title'}, 'getDateReceived': { 'title': _('Date Received'), 'index': 'getDateReceived'}, 'getDueDate': { 'title': _('Due Date'), 'index': 'getDueDate'}, } self.filter_indexes = ['Title',] self.review_states = [ {'id':'default', 'title': _('All'), 'contentFilter': {}, 'transitions': [{'id':'assign'}, ], 'columns':['Client', 'getClientOrderNumber', 'getRequestID', 'CategoryTitle', 'Title', 'getDateReceived', 'getDueDate'], }, ]
def __init__(self, context, request, field=None, category=None): BikaListingView.__init__(self, context, request) if field: self.selected = [o.UID() for o in getattr(field, field.accessor)()] else: self.selected = [] self.category = category if category else None self.context_actions = {} self.catalog = "bika_setup_catalog" self.contentFilter = {'review_state': 'impossible_state'} self.base_url = self.context.absolute_url() self.view_url = self.base_url self.show_sort_column = False self.show_select_row = False self.show_select_all_checkbox = False self.show_select_column = True self.pagesize = 999999 self.form_id = 'serviceswidget' self.show_categories = False self.categories = [] # TODO Check if filtering by multiple UIDs should be enabled self.do_cats = self.context.bika_setup.getCategoriseAnalysisServices() if self.do_cats: self.show_categories = True self.expand_all_categories = False self.ajax_categories = True self.category_index = 'getCategoryTitle' self.ajax_categories_url = context.absolute_url() + \ "/ajax_services_expand_category" self.columns = { 'Service': {'title': _('Service')}, 'Keyword': {'title': _('Keyword'), 'index': 'getKeyword'}, 'Method': {'title': _('Method')}, 'Calculation': {'title': _('Calculation')}, } self.review_states = [ {'id':'default', 'title': _('All'), 'contentFilter':{}, 'transitions': [], 'columns':['Service', 'Keyword', 'Method', 'Calculation', ] }, ]
def __call__(self): ar = self.context workflow = getToolByName(ar, "portal_workflow") # If is a retracted AR, show the link to child AR and show a warn msg if workflow.getInfoFor(ar, "review_state") == "invalid": childar = hasattr(ar, "getChildAnalysisRequest") and ar.getChildAnalysisRequest() or None childid = childar and childar.getRequestID() or None message = _( "This Analysis Request has been withdrawn and is " "shown for trace-ability purposes only. Retest: " "${retest_child_id}.", mapping={"retest_child_id": safe_unicode(childid) or ""}, ) self.context.plone_utils.addPortalMessage(self.context.translate(message), "warning") # If is an AR automatically generated due to a Retraction, show it's # parent AR information if hasattr(ar, "getParentAnalysisRequest") and ar.getParentAnalysisRequest(): par = ar.getParentAnalysisRequest() message = _( "This Analysis Request has been " "generated automatically due to " "the retraction of the Analysis " "Request ${retracted_request_id}.", mapping={"retracted_request_id": par.getRequestID()}, ) self.context.plone_utils.addPortalMessage(self.context.translate(message), "info") template = BikaListingView.__call__(self) return template
def folderitems(self): mtool = getToolByName(self.context, "portal_membership") if mtool.checkPermission(ManageBika, self.context): del self.review_states[0]["transitions"] self.show_select_column = True self.review_states.append( { "id": "active", "title": _("Active"), "contentFilter": {"inactive_state": "active"}, "transitions": [{"id": "deactivate"}], "columns": ["Title", "Description"], } ) self.review_states.append( { "id": "inactive", "title": _("Dormant"), "contentFilter": {"inactive_state": "inactive"}, "transitions": [{"id": "activate"}], "columns": ["Title", "Description"], } ) items = BikaListingView.folderitems(self) for x in range(len(items)): if "obj" in items[x]: items[x]["replace"]["Title"] = "<a href='%s'>%s</a>" % (items[x]["url"], items[x]["Title"]) return items
def folderitems(self): items = BikaListingView.folderitems(self) props = self.context.portal_properties.site_properties for x in range(len(items)): if 'obj' not in items[x]: continue obj = items[x]['obj'] obj_url = obj.absolute_url() file = obj.getReportFile() icon = file.icon items[x]['Client'] = '' client = obj.getClient() if client: items[x]['replace']['Client'] = "<a href='%s'>%s</a>" % \ (client.absolute_url(), client.Title()) items[x]['FileSize'] = '%sKb' % (file.get_size() / 1024) items[x]['Created'] = self.ulocalized_time(obj.created()) items[x]['By'] = self.user_fullname(obj.Creator()) items[x]['replace']['Title'] = \ "<a href='%s/at_download/ReportFile'>%s</a>" % \ (obj_url, items[x]['Title']) return items
def folderitems(self): mtool = getToolByName(self.context, 'portal_membership') if mtool.checkPermission(ManageBika, self.context): del self.review_states[0]['transitions'] self.show_select_column = True self.review_states.append( {'id': 'active', 'title': _('Active'), 'contentFilter': {'inactive_state': 'active'}, 'transitions': [{'id':'deactivate'}, ], 'columns': ['Title', 'Description']}) self.review_states.append( {'id': 'inactive', 'title': _('Dormant'), 'contentFilter': {'inactive_state': 'inactive'}, 'transitions': [{'id':'activate'}, ], 'columns': ['Title', 'Description']}) items = BikaListingView.folderitems(self) for x in range(len(items)): if 'obj' in items[x]: items[x]['replace']['Title'] = "<a href='%s'>%s</a>" % \ (items[x]['url'], items[x]['Title']) return items
def folderitems(self): items = BikaListingView.folderitems(self) outitems = [] toshow = [] for val in self.context.getDocuments(): toshow.append(val.UID()) for x in range(len(items)): if not items[x].has_key('obj'): continue obj = items[x]['obj'] if obj.UID() in toshow: items[x]['replace']['DocumentID'] = "<a href='%s'>%s</a>" % \ (items[x]['url'], items[x]['DocumentID']) items[x]['SmallDesc'] = obj.getSmallDescription() items[x]['FileDownload'] = obj.getFile().filename filename = obj.getFile().filename if obj.getFile().filename \ != '' else 'Image' items[x]['replace']['FileDownload'] = "<a href='%s'>%s</a>" % \ ( obj.getFile().absolute_url_path(), filename) items[x]['DatetimeCreated'] = self.ulocalized_time( obj.getDatetimeCreated()) outitems.append(items[x]) return outitems
def __call__(self): ar = self.context workflow = getToolByName(ar, 'portal_workflow') # If is a retracted AR, show the link to child AR and show a warn msg if workflow.getInfoFor(ar, 'review_state') == 'invalid': childar = hasattr(ar, 'getChildAnalysisRequest') \ and ar.getChildAnalysisRequest() or None childid = childar and childar.getRequestID() or None message = _('This Analysis Request has been withdrawn and is ' 'shown for trace-ability purposes only. Retest: ' '${retest_child_id}.', mapping={'retest_child_id': safe_unicode(childid) or ''}) self.context.plone_utils.addPortalMessage( self.context.translate(message), 'warning') # If is an AR automatically generated due to a Retraction, show it's # parent AR information if hasattr(ar, 'getParentAnalysisRequest') \ and ar.getParentAnalysisRequest(): par = ar.getParentAnalysisRequest() message = _('This Analysis Request has been ' 'generated automatically due to ' 'the retraction of the Analysis ' 'Request ${retracted_request_id}.', mapping={'retracted_request_id': par.getRequestID()}) self.context.plone_utils.addPortalMessage( self.context.translate(message), 'info') template = BikaListingView.__call__(self) return template
def folderitems(self): items = BikaListingView.folderitems(self) for x in range(len(items)): if not items[x].has_key('obj'): continue obj = items[x]['obj'] itype = obj.getInstrumentType() items[x]['Type'] = itype.Title() if itype else '' ibrand = obj.getManufacturer() items[x]['Brand'] = ibrand.Title() if ibrand else '' items[x]['Model'] = obj.getModel() data = obj.getCertificateExpireDate() if data is None: items[x]['ExpiryDate'] = _("No date set") else: items[x]['ExpiryDate'] = data.asdatetime().strftime(self.date_format_short) if obj.isOutOfDate(): items[x]['WeeksToExpire'] = _("Out of date") else: weeks, days = obj.getWeeksToExpire() weeks_to_expire = _("{} weeks and {} day(s)".format(str(weeks), str(days))) items[x]['WeeksToExpire'] = weeks_to_expire if obj.getMethod(): items[x]['Method'] = obj.getMethod().Title() items[x]['replace']['Method'] = "<a href='%s'>%s</a>" % \ (obj.getMethod().absolute_url(), items[x]['Method']) else: items[x]['Method'] = '' items[x]['replace']['Title'] = "<a href='%s'>%s</a>" % \ (items[x]['url'], items[x]['Title']) return items
def folderitems(self): items = BikaListingView.folderitems(self) for x in range(len(items)): if not items[x].has_key('obj'): continue obj = items[x]['obj'] service = obj.getService() client = obj.aq_parent.aq_parent items[x]['getClientOrderNumber'] = obj.getClientOrderNumber() items[x]['getDateReceived'] = self.ulocalized_time(obj.getDateReceived()) DueDate = obj.getDueDate() items[x]['getDueDate'] = self.ulocalized_time(DueDate) if DueDate < DateTime(): items[x]['after']['DueDate'] = '<img width="16" height="16" src="%s/++resource++bika.lims.images/late.png" title="%s"/>' % \ (self.context.absolute_url(), self.context.translate(_("Late Analysis"))) items[x]['CategoryTitle'] = service.getCategory().Title() if getSecurityManager().checkPermission(EditResults, obj.aq_parent): url = obj.aq_parent.absolute_url() + "/manage_results" else: url = obj.aq_parent.absolute_url() items[x]['getRequestID'] = obj.aq_parent.getRequestID() items[x]['replace']['getRequestID'] = "<a href='%s'>%s</a>" % \ (url, items[x]['getRequestID']) items[x]['Client'] = client.Title() items[x]['replace']['Client'] = "<a href='%s'>%s</a>" % \ (client.absolute_url(), client.Title()) return items
def folderitems(self): self.filter_indexes = None items = BikaListingView.folderitems(self) for x in range(len(items)): if 'obj' not in items[x]: continue obj = items[x]['obj'] bid = obj.getBatchID() items[x]['BatchID'] = bid items[x]['replace']['BatchID'] = "<a href='%s/%s'>%s</a>" % (items[x]['url'], 'analysisrequests', bid) title = obj.Title() items[x]['Title'] = title items[x]['replace']['Title'] = "<a href='%s/%s'>%s</a>" % (items[x]['url'], 'analysisrequests', title) if obj.getClient(): items[x]['Client'] = obj.getClient().Title() items[x]['replace']['Client'] = "<a href='%s'>%s</a>" % ( obj.getClient().absolute_url(), obj.getClient().Title()) else: items[x]['Client'] = '' date = obj.Schema().getField('BatchDate').get(obj) if callable(date): date = date() items[x]['BatchDate'] = date items[x]['replace']['BatchDate'] = self.ulocalized_time(date) return items
def folderitems(self, full_objects=False): currency = currency_format(self.context, 'en') self.show_all = True self.contentsMethod = self.getInvoices items = BikaListingView.folderitems(self, full_objects) for item in items: obj = item['obj'] number_link = "<a href='%s'>%s</a>" % ( item['url'], obj.getId() ) item['replace']['id'] = number_link if obj.getClient(): item['client'] = obj.getClient().Title() item['replace']['client'] = "<a href='%s'>%s</a>" % ( obj.getClient().absolute_url(), obj.getClient().Title() ) item['email'] = obj.getClient().getEmailAddress() item['replace']['email'] = "<a href='%s'>%s</a>" % ( 'mailto:%s' % obj.getClient().getEmailAddress(), obj.getClient().getEmailAddress() ) item['phone'] = obj.getClient().getPhone() else: item['client'] = '' item['email'] = '' item['phone'] = '' item['invoicedate'] = self.ulocalized_time(obj.getInvoiceDate()) item['startdate'] = self.ulocalized_time(obj.getBatchStartDate()) item['enddate'] = self.ulocalized_time(obj.getBatchEndDate()) item['subtotal'] = currency(obj.getSubtotal()) item['vatamount'] = currency(obj.getVATAmount()) item['total'] = currency(obj.getTotal()) return items
def folderitems(self, full_objects=False): items = BikaListingView.folderitems(self, full_objects=False) # Hide Preservation/Sampling workflow actions if the edit columns # are not displayed. # Hide schedule_sampling if user has no rights toggle_cols = self.get_toggle_cols() new_states = [] for i,state in enumerate(self.review_states): if state and self.review_state and state['id'] == self.review_state.get('id', ''): if 'getSampler' not in toggle_cols \ or 'DateSampled' not in toggle_cols: if 'hide_transitions' in state: state['hide_transitions'].append('sample') else: state['hide_transitions'] = ['sample',] if 'getPreserver' not in toggle_cols \ or 'getDatePreserved' not in toggle_cols: if 'hide_transitions' in state: state['hide_transitions'].append('preserve') else: state['hide_transitions'] = ['preserve',] # Check if the user has the rights to schedule samplings and # the check-box 'ScheduleSamplingEnabled' in bikasetup is set if self._schedule_sampling_permissions(): # Show the workflow transition button 'schedule_sampling' pass else: # Hiddes the button state['hide_transitions'] = ['schedule_sampling', ] new_states.append(state) self.review_states = new_states return items
def folderitems(self): items = BikaListingView.folderitems(self) for x in range(len(items)): if not items[x].has_key('obj'): continue obj = items[x]['obj'] items[x]['ID'] = obj.id items[x]['Manufacturer'] = obj.getReferenceManufacturer() and \ obj.getReferenceManufacturer().Title() or '' items[x]['Definition'] = obj.getReferenceDefinition() and \ obj.getReferenceDefinition().Title() or '' items[x]['DateSampled'] = \ TimeOrDate(self.context, obj.getDateSampled()) items[x]['DateReceived'] = \ TimeOrDate(self.context, obj.getDateReceived()) items[x]['DateOpened'] = \ TimeOrDate(self.context, obj.getDateOpened()) items[x]['ExpiryDate'] = \ TimeOrDate(self.context, obj.getExpiryDate()) after_icons = '' if obj.getBlank(): after_icons += "<img src='++resource++bika.lims.images/blank.png' title='Blank'>" if obj.getHazardous(): after_icons += "<img src='++resource++bika.lims.images/hazardous.png' title='Hazardous'>" items[x]['replace']['ID'] = "<a href='%s/base_view'>%s</a> %s" % \ (items[x]['url'], items[x]['ID'], after_icons) return items
def folderitems(self): items = BikaListingView.folderitems(self) for x in range(len(items)): if not items[x].has_key('obj'): continue obj = items[x]['obj'] items[x]['SampleID'] = obj.getSampleID() items[x]['replace']['SampleID'] = "<a href='%s'>%s</a>" % \ (items[x]['url'], items[x]['SampleID']) items[x]['replace']['Requests'] = ",".join( ["<a href='%s'>%s</a>" % (o.absolute_url(), o.Title()) for o in obj.getAnalysisRequests()]) items[x]['ClientReference'] = obj.getClientReference() items[x]['ClientSampleID'] = obj.getClientSampleID() items[x]['SampleTypeTitle'] = obj.getSampleTypeTitle() items[x]['SamplePointTitle'] = obj.getSamplePointTitle() datesampled = obj.getDateSampled() items[x]['DateSampled'] = TimeOrDate(self.context, datesampled, long_format = 0) items[x]['future_DateSampled'] = datesampled.Date() > DateTime() and \ TimeOrDate(self.context, datesampled) or '' items[x]['DateReceived'] = TimeOrDate(self.context, obj.getDateReceived()) after_icons = '' if obj.getSampleType().getHazardous(): after_icons += "<img title='Hazardous' src='++resource++bika.lims.images/hazardous.png'>" if after_icons: items[x]['after']['SampleID'] = after_icons return items
def folderitems(self): mtool = getToolByName(self.context, 'portal_membership') member = mtool.getAuthenticatedMember() roles = member.getRoles() self.allow_edit = 'LabManager' in roles or 'Manager' in roles items = BikaListingView.folderitems(self) for x in range(len(items)): if not items[x].has_key('obj'): continue obj = items[x]['obj'] cat = obj.getCategoryTitle() # Category (upper C) is for display column value items[x]['Category'] = cat if self.do_cats: # category is for bika_listing to groups entries items[x]['category'] = cat if cat not in self.categories: self.categories.append(cat) analyses = [a.UID() for a in self.field_value] items[x]['selected'] = items[x]['uid'] in analyses items[x]['class']['Title'] = 'service_title' calculation = obj.getCalculation() items[x]['Calculation'] = calculation and calculation.Title() locale = locales.getLocale('en') currency = self.context.bika_setup.getCurrency() symbol = locale.numbers.currencies[currency].symbol items[x]['Price'] = "%s %s" % (symbol, obj.getPrice()) items[x]['class']['Price'] = 'nowrap' after_icons = '' if obj.getAccredited(): after_icons += "<img\ src='%s/++resource++bika.lims.images/accredited.png'\ title='%s'>" % (self.context.absolute_url(), _("Accredited")) if obj.getReportDryMatter(): after_icons += "<img\ src='%s/++resource++bika.lims.images/dry.png'\ title='%s'>" % (self.context.absolute_url(), _("Can be reported as dry matter")) if obj.getAttachmentOption() == 'r': after_icons += "<img\ src='%s/++resource++bika.lims.images/attach_reqd.png'\ title='%s'>" % (self.context.absolute_url(), _("Attachment required")) if obj.getAttachmentOption() == 'n': after_icons += "<img\ src='%s/++resource++bika.lims.images/attach_no.png'\ title='%s'>" % (self.context.absolute_url(), _('Attachment not permitted')) if after_icons: items[x]['after']['Title'] = after_icons return items
def folderitems(self): items = BikaListingView.folderitems(self) for x in range(len(items)): if not items[x].has_key('obj'): continue obj = items[x]['obj'] itype = obj.getInstrumentType() items[x]['Type'] = itype.Title() if itype else '' ibrand = obj.getManufacturer() items[x]['Brand'] = ibrand.Title() if ibrand else '' items[x]['Model'] = obj.getModel() data = obj.getCertificateExpireDate() if data == '': items[x]['ExpiryDate'] = "No date avaliable" else: items[x]['ExpiryDate'] = data.asdatetime().strftime(self.date_format_short) if obj.isOutOfDate(): items[x]['WeeksToExpire'] = "Out of date" else: date = int(str(obj.getWeeksToExpire()).split(',')[0].split(' ')[0]) weeks,days = divmod(date,7) items[x]['WeeksToExpire'] = str(weeks)+" weeks"+" "+str(days)+" days" if obj.getMethod(): items[x]['Method'] = obj.getMethod().Title() items[x]['replace']['Method'] = "<a href='%s'>%s</a>" % \ (obj.getMethod().absolute_url(), items[x]['Method']) else: items[x]['Method'] = '' items[x]['replace']['Title'] = "<a href='%s'>%s</a>" % \ (items[x]['url'], items[x]['Title']) return items
def folderitems(self): mtool = getToolByName(self.context, 'portal_membership') if mtool.checkPermission(ManageBika, self.context): del self.review_states[0]['transitions'] self.show_select_column = True self.review_states.append( {'id':'active', 'title': _('Active'), 'contentFilter': {'inactive_state': 'active'}, 'transitions': [{'id':'deactivate'}, ], 'columns': ['Title', 'Description']}) self.review_states.append( {'id':'inactive', 'title': _('Dormant'), 'contentFilter': {'inactive_state': 'inactive'}, 'transitions': [{'id':'activate'}, ], 'columns': ['Title', 'Description']}) items = BikaListingView.folderitems(self) for x in range(len(items)): if not items[x].has_key('obj'): continue items[x]['replace']['Title'] = "<a href='%s'>%s</a>" % \ (items[x]['url'], items[x]['Title']) # chop the description down to 120-ish chars... descr = items[x]['Description'][:100].split(" ") descr = " ".join(descr[:-1]) if len(items[x]['Description']) > 100: descr += "..." items[x]['Description'] = descr return items
def folderitems(self): self.contentsMethod = self.getClientList items = BikaListingView.folderitems(self) registry = getUtility(IRegistry) if 'bika.lims.client.default_landing_page' in registry: landing_page = registry['bika.lims.client.default_landing_page'] else: landing_page = 'analysisrequests' for item in items: if "obj" not in item: continue obj = item['obj'] item['replace']['title'] = "<a href='%s/%s'>%s</a>" % \ (item['url'], landing_page.encode('ascii'), item['title']) item['EmailAddress'] = obj.getEmailAddress() item['replace']['EmailAddress'] = "<a href='%s'>%s</a>" % \ ('mailto:%s' % obj.getEmailAddress(), obj.getEmailAddress()) item['Phone'] = obj.getPhone() item['Fax'] = obj.getFax() item['ClientID'] = obj.getClientID() item['BulkDiscount'] = obj.getBulkDiscount() and 'Y' or 'N' item['MemberDiscountApplies'] = obj.getMemberDiscountApplies() and 'Y' or 'N' return items
def folderitems(self): self.categories = [] bsc = getToolByName(self.context, 'bika_setup_catalog') wf = getToolByName(self.context, 'portal_workflow') mtool = getToolByName(self.context, 'portal_membership') member = mtool.getAuthenticatedMember() roles = member.getRoles() self.allow_edit = 'LabManager' in roles or 'Manager' in roles items = BikaListingView.folderitems(self) for x in range(len(items)): if not items[x].has_key('obj'): continue obj = items[x]['obj'] cat = obj.getCategoryTitle() # Category (upper C) is for display column value items[x]['Category'] = cat if self.do_cats: # category is for bika_listing to groups entries items[x]['category'] = cat if cat not in self.categories: self.categories.append(cat) analyses = [a.UID() for a in self.fieldvalue] items[x]['selected'] = items[x]['uid'] in analyses items[x]['class']['Title'] = 'service_title' calculation = obj.getCalculation() items[x]['Calculation'] = calculation and calculation.Title() locale = locales.getLocale('en') currency = self.context.bika_setup.getCurrency() symbol = locale.numbers.currencies[currency].symbol items[x]['Price'] = "%s %s" % (symbol, obj.getPrice()) items[x]['class']['Price'] = 'nowrap' after_icons = '' if obj.getAccredited(): after_icons += "<img\ src='%s/++resource++bika.lims.images/accredited.png'\ title='%s'>" % (self.context.absolute_url(), _("Accredited")) if obj.getReportDryMatter(): after_icons += "<img\ src='%s/++resource++bika.lims.images/dry.png'\ title='%s'>" % (self.context.absolute_url(), _("Can be reported as dry matter")) if obj.getAttachmentOption() == 'r': after_icons += "<img\ src='%s/++resource++bika.lims.images/attach_reqd.png'\ title='%s'>" % (self.context.absolute_url(), _("Attachment required")) if obj.getAttachmentOption() == 'n': after_icons += "<img\ src='%s/++resource++bika.lims.images/attach_no.png'\ title='%s'>" % (self.context.absolute_url(), _('Attachment not permitted')) if after_icons: items[x]['after']['Title'] = after_icons if self.profile: # Display analyses for this Analysis Service in results? ser = self.profile.getAnalysisServiceSettings(obj.UID()) items[x]['allow_edit'] = [ 'Hidden', ] items[x]['Hidden'] = ser.get('hidden', obj.getHidden()) self.categories.sort() return items
def folderitem(self, obj, item, index): # Additional info from AnalysisRequest to be added in the item # generated by default by bikalisting. # Call the folderitem method from the base class item = BikaListingView.folderitem(self, obj, item, index) if not item: return None # This variable will contain the full analysis request if there is # need to work with the full object instead of the brain full_object = None item["Creator"] = self.user_fullname(obj.Creator) # If we redirect from the folderitems view we should check if the # user has permissions to medify the element or not. priority_sort_key = obj.getPrioritySortkey if not priority_sort_key: # Default priority is Medium = 3. # The format of PrioritySortKey is <priority>.<created> priority_sort_key = "3.%s" % obj.created.ISO8601() priority = priority_sort_key.split(".")[0] priority_text = PRIORITIES.getValue(priority) priority_div = """<div class="priority-ico priority-%s"> <span class="notext">%s</span><div> """ item["replace"]["Priority"] = priority_div % (priority, priority_text) item["replace"]["getProfilesTitle"] = obj.getProfilesTitleStr analysesnum = obj.getAnalysesNum if analysesnum: num_verified = str(analysesnum[0]) num_total = str(analysesnum[1]) item["getAnalysesNum"] = "{0}/{1}".format(num_verified, num_total) else: item["getAnalysesNum"] = "" # Progress num_verified = 0 num_submitted = 0 num_total = 0 if analysesnum and len(analysesnum) > 1: num_verified = analysesnum[0] num_total = analysesnum[1] num_submitted = num_total - num_verified if len(analysesnum) > 2: num_wo_results = analysesnum[2] num_submitted = num_total - num_verified - num_wo_results num_steps_total = num_total * 2 num_steps = (num_verified * 2) + (num_submitted) progress_perc = 0 if num_steps > 0 and num_steps_total > 0: progress_perc = (num_steps * 100) / num_steps_total progress = '<div class="progress-bar-container">' + \ '<div class="progress-bar" style="width:{0}%"></div>' + \ '<div class="progress-perc">{0}%</div></div>' item["replace"]["Progress"] = progress.format(progress_perc) item["BatchID"] = obj.getBatchID if obj.getBatchID: item['replace']['BatchID'] = "<a href='%s'>%s</a>" % \ (obj.getBatchURL, obj.getBatchID) # TODO: SubGroup ??? # val = obj.Schema().getField('SubGroup').get(obj) # item['SubGroup'] = val.Title() if val else '' date = obj.getSamplingDate item["SamplingDate"] = \ self.ulocalized_time(date, long_format=1) if date else "" date = obj.getDateReceived item["getDateReceived"] = \ self.ulocalized_time(date, long_format=1) if date else "" date = obj.getDueDate item["getDueDate"] = \ self.ulocalized_time(date, long_format=1) if date else "" date = obj.getDatePublished item["getDatePublished"] = \ self.ulocalized_time(date, long_format=1) if date else "" date = obj.getDateVerified item["getDateVerified"] = \ self.ulocalized_time(date, long_format=1) if date else "" if self.printwfenabled: item["Printed"] = "" printed = obj.getPrinted if hasattr(obj, "getPrinted") else "0" print_icon = "" if printed == "0": print_icon = get_image("delete.png", title=t(_("Not printed yet"))) elif printed == "1": print_icon = get_image("ok.png", title=t(_("Printed"))) elif printed == "2": print_icon = get_image("exclamation.png", title=t( _("Republished after last print"))) item["after"]["Printed"] = print_icon item["SamplingDeviation"] = obj.getSamplingDeviationTitle item["getStorageLocation"] = obj.getStorageLocationTitle after_icons = "" # Getting a dictionary with each workflow id and current state in it states_dict = obj.getObjectWorkflowStates if obj.assigned_state == 'assigned': after_icons += get_image("worksheet.png", title=t(_("All analyses assigned"))) if states_dict.get('review_state', '') == 'invalid': after_icons += get_image("delete.png", title=t(_("Results have been withdrawn"))) due_date = obj.getDueDate if due_date and due_date < (obj.getDatePublished or DateTime()): due_date_str = self.ulocalized_time(due_date) img_title = "{}: {}".format(t(_("Late Analyses")), due_date_str) after_icons += get_image("late.png", title=img_title) if obj.getSamplingDate and obj.getSamplingDate > DateTime(): after_icons += get_image("calendar.png", title=t(_("Future dated sample"))) if obj.getInvoiceExclude: after_icons += get_image("invoice_exclude.png", title=t(_("Exclude from invoice"))) if obj.getHazardous: after_icons += get_image("hazardous.png", title=t(_("Hazardous"))) if after_icons: item['after']['getId'] = after_icons item['Created'] = self.ulocalized_time(obj.created, long_format=1) if obj.getContactUID: item['ClientContact'] = obj.getContactFullName item['replace']['ClientContact'] = "<a href='%s'>%s</a>" % \ (obj.getContactURL, obj.getContactFullName) else: item["ClientContact"] = "" # TODO-performance: If SamplingWorkflowEnabled, we have to get the # full object to check the user permissions, so far this is # a performance hit. if obj.getSamplingWorkflowEnabled: # We don't do anything with Sampling Date. # User can modify Sampling date # inside AR view. In this listing view, # we only let the user to edit Date Sampled # and Sampler if he wants to make 'sample' transaction. if not obj.getDateSampled: datesampled = self.ulocalized_time(DateTime(), long_format=True) item["class"]["getDateSampled"] = "provisional" else: datesampled = self.ulocalized_time(obj.getDateSampled, long_format=True) sampler = obj.getSampler if sampler: item["replace"]["getSampler"] = obj.getSamplerFullName if "Sampler" in self.roles and not sampler: sampler = self.member.id item["class"]["getSampler"] = "provisional" # sampling workflow - inline edits for Sampler and Date Sampled if states_dict.get('review_state', '') == 'to_be_sampled': # We need to get the full object in order to check # the permissions full_object = obj.getObject() checkPermission =\ self.context.portal_membership.checkPermission if checkPermission(SampleSample, full_object): item["required"] = ["getSampler", "getDateSampled"] item["allow_edit"] = ["getSampler", "getDateSampled"] # TODO-performance: hit performance while getting the # sample object... # TODO Can LabManagers be a Sampler?! samplers = getUsers(full_object.getSample(), [ "Sampler", ]) username = self.member.getUserName() users = [({ "ResultValue": u, "ResultText": samplers.getValue(u) }) for u in samplers] item['choices'] = {'getSampler': users} Sampler = sampler and sampler or \ (username in samplers.keys() and username) or '' sampler = Sampler else: datesampled = self.ulocalized_time(obj.getDateSampled, long_format=True) sampler = obj.getSamplerFullName if obj.getSampler else '' else: datesampled = self.ulocalized_time(obj.getDateSampled, long_format=True) sampler = "" item["getDateSampled"] = datesampled item["getSampler"] = sampler # These don't exist on ARs # XXX This should be a list of preservers... item["getPreserver"] = "" item["getDatePreserved"] = "" # TODO-performance: If inline preservation wants to be used, we # have to get the full object to check the user permissions, so # far this is a performance hit. # inline edits for Preserver and Date Preserved # if checkPermission(PreserveSample, obj): # item['required'] = ['getPreserver', 'getDatePreserved'] # item['allow_edit'] = ['getPreserver', 'getDatePreserved'] # preservers = getUsers(obj, ['Preserver', # 'LabManager', 'Manager']) # username = self.member.getUserName() # users = [({'ResultValue': u, # 'ResultText': preservers.getValue(u)}) # for u in preservers] # item['choices'] = {'getPreserver': users} # preserver = username in preservers.keys() and username or '' # item['getPreserver'] = preserver # item['getDatePreserved'] = self.ulocalized_time( # DateTime(), # long_format=1) # item['class']['getPreserver'] = 'provisional' # item['class']['getDatePreserved'] = 'provisional' # Submitting user may not verify results # Thee conditions to improve performance, some functions to check # the condition need to get the full analysis request. if states_dict.get("review_state", "") == "to_be_verified": allowed = user.has_permission(VerifyPermission, username=self.member.getUserName()) # TODO-performance: isUserAllowedToVerify getts all analysis # objects inside the analysis request. if allowed: # Gettin the full object if not get before full_object = full_object if full_object else obj.getObject() if not full_object.isUserAllowedToVerify(self.member): item["after"]["state_title"] = get_image( "submitted-by-current-user.png", title=t(_("Cannot verify: Submitted by current user"))) return item
def __call__(self): if getSecurityManager().checkPermission(ManageKits, self.context): self.show_select_row = True self.show_select_column = True return BikaListingView.__call__(self)
def folderitems(self, full_objects=False, classic=False): # We need to get the portal catalog here in roder to save process # while iterating over folderitems self.portal_catalog = api.get_tool("portal_catalog") return BikaListingView.folderitems(self, full_objects, classic)
def __init__(self, context, request, fieldvalue=[], allow_edit=True): BikaListingView.__init__(self, context, request) self.context_actions = {} self.contentFilter = { 'inactive_state': 'active', 'sort_on': 'sortable_title' } self.context_actions = {} self.base_url = self.context.absolute_url() self.view_url = self.base_url self.show_sort_column = False self.show_select_row = False self.show_select_all_checkbox = False self.show_select_column = False self.pagesize = 999999 self.allow_edit = allow_edit self.show_categories = True # self.expand_all_categories = False self.ajax_categories = True self.ajax_categories_url = self.context.absolute_url( ) + "/analysis_spec_widget_view" self.category_index = 'getCategoryTitle' self.specsresults = {} for specresults in fieldvalue: self.specsresults[specresults['keyword']] = specresults self.columns = { 'service': { 'title': _('Service'), 'index': 'sortable_title', 'sortable': False }, 'min': { 'title': _('Min'), 'sortable': False, }, 'max': { 'title': _('Max'), 'sortable': False, }, 'error': { 'title': _('Permitted Error %'), 'sortable': False }, 'hidemin': { 'title': _('< Min'), 'sortable': False }, 'hidemax': { 'title': _('> Max'), 'sortable': False }, 'rangecomment': { 'title': _('Range comment'), 'sortable': False, 'toggle': False } } self.review_states = [ { 'id': 'default', 'title': _('All'), 'contentFilter': {}, 'transitions': [], 'columns': [ 'service', 'min', 'max', 'error', 'hidemin', 'hidemax', 'rangecomment' ], }, ]
def __init__(self, context, request, **kwargs): BikaListingView.__init__( self, context, request, show_categories=context.bika_setup.getCategoriseAnalysisServices(), expand_all_categories=True) # prepare the content filter of this listing self.contentFilter = dict(kwargs) self.contentFilter.update({ "portal_type": "Analysis", "sort_on": "sortable_title", "sort_order": "ascending", }) # set the listing view config self.catalog = CATALOG_ANALYSIS_LISTING self.sort_order = 'ascending' self.context_actions = {} self.show_sort_column = False self.show_select_row = False self.show_select_column = False self.show_column_toggles = False self.pagesize = 999999 self.form_id = 'analyses_form' self.context_active = isActive(context) self.interim_fields = {} self.interim_columns = OrderedDict() self.specs = {} self.bsc = getToolByName(context, 'bika_setup_catalog') self.portal = getToolByName(context, 'portal_url').getPortalObject() self.portal_url = self.portal.absolute_url() self.rc = getToolByName(context, REFERENCE_CATALOG) self.dmk = context.bika_setup.getResultsDecimalMark() self.scinot = context.bika_setup.getScientificNotationResults() self.categories = [] request.set('disable_plone.rightcolumn', 1) # each editable item needs it's own allow_edit # which is a list of field names. self.allow_edit = False self.columns = { # Although 'created' column is not displayed in the list (see # review_states to check the columns that will be rendered), this # column is needed to sort the list by create date 'created': { 'title': _('Date Created'), 'toggle': False}, 'Service': { 'title': _('Analysis'), 'attr': 'Title', 'index': 'sortable_title', 'sortable': False}, 'Partition': { 'title': _("Partition"), 'attr': 'getSamplePartitionID', 'sortable': False}, 'Method': { 'title': _('Method'), 'sortable': False, 'toggle': True}, 'Instrument': { 'title': _('Instrument'), 'sortable': False, 'toggle': True}, 'Analyst': { 'title': _('Analyst'), 'sortable': False, 'toggle': True}, 'state_title': { 'title': _('Status'), 'sortable': False}, 'DetectionLimit': { 'title': _('DL'), 'sortable': False, 'toggle': False}, 'Result': { 'title': _('Result'), 'input_width': '6', 'input_class': 'ajax_calculate numeric', 'sortable': False}, 'Specification': { 'title': _('Specification'), 'sortable': False}, 'Uncertainty': { 'title': _('+-'), 'sortable': False}, 'retested': { 'title': "<img title='%s' " "src='%s/++resource++bika.lims.images/retested.png" "'/>" % \ (t(_('Retested')), self.portal_url), 'type': 'boolean', 'sortable': False}, 'Attachments': { 'title': _('Attachments'), 'sortable': False}, 'CaptureDate': { 'title': _('Captured'), 'index': 'getResultCaptureDate', 'sortable': False}, 'DueDate': { 'title': _('Due Date'), 'index': 'getDueDate', 'sortable': False}, 'Hidden': { 'title': _('Hidden'), 'toggle': True, 'sortable': False, 'input_class': 'autosave', 'type': 'boolean'}, } self.review_states = [ { 'id': 'default', 'title': _('All'), 'contentFilter': {}, 'columns': [ 'Service', 'Partition', 'DetectionLimit', 'Result', 'Specification', 'Method', 'Instrument', 'Analyst', 'Uncertainty', 'CaptureDate', 'DueDate', 'state_title', 'Hidden' ] }, ] if not context.bika_setup.getShowPartitions(): self.review_states[0]['columns'].remove('Partition') # This is used to display method and instrument columns if there is at # least one analysis to be rendered that allows the assignment of method # and/or instrument self.show_methodinstr_columns = False
def __init__(self, context, request): BikaListingView.__init__(self, context, request) self.icon = self.portal_url + "/++resource++bika.lims.images/worksheet_big.png" self.title = self.context.translate(_("Add Analyses")) self.description = "" self.catalog = CATALOG_ANALYSIS_LISTING self.context_actions = {} # initial review state for first form display of the worksheet # add_analyses search view - first batch of analyses, latest first. self.sort_on = 'Priority' self.contentFilter = { 'portal_type': 'Analysis', 'review_state': 'sample_received', 'worksheetanalysis_review_state': 'unassigned', 'sort_on': 'getPrioritySortkey', 'cancellation_state': 'active' } self.base_url = self.context.absolute_url() self.view_url = self.base_url + "/add_analyses" self.show_sort_column = False self.show_select_row = False self.show_select_column = True self.pagesize = 50 self.columns = { 'Priority': { 'title': '', 'sortable': True, 'index': 'getPrioritySortkey' }, 'Client': { 'title': _('Client'), 'attr': 'getClientTitle', 'replace_url': 'getClientURL', 'index': 'getClientTitle' }, 'getClientOrderNumber': { 'title': _('Order'), 'index': 'getClientOrderNumber' }, 'getRequestID': { 'title': _('Request ID'), 'attr': 'getRequestID', 'replace_url': 'getRequestURL', 'index': 'getRequestID' }, 'CategoryTitle': { 'title': _('Category'), 'attr': 'getCategoryTitle', 'sortable': False }, 'Title': { 'title': _('Analysis'), 'index': 'getId' }, 'getDateReceived': { 'title': _('Date Received'), 'index': 'getDateReceived' }, 'getDueDate': { 'title': _('Due Date'), 'index': 'getDueDate' }, } self.filter_indexes = [ 'Title', ] self.review_states = [ { 'id': 'default', 'title': _('All'), 'contentFilter': {}, 'transitions': [ { 'id': 'assign' }, ], 'columns': [ 'Priority', 'Client', 'getClientOrderNumber', 'getRequestID', 'CategoryTitle', 'Title', 'getDateReceived', 'getDueDate' ], }, ]
def folderitems(self): return BikaListingView.folderitems(self, classic=False)
def __init__(self, context, request): BikaListingView.__init__(self, context, request) self.context = context self.request = request self.catalog = 'bika_catalog' request.set('disable_plone.rightcolumn', 1) self.contentFilter = { 'portal_type': 'Kit', 'sort_on': 'sortable_title', 'sort_order': 'reverse' } # Todo: I added these two line to set the sort and the order of kit listing because # Todo: the values in self.contentFilter seems have no effect! self.sort_on = 'sortable_title' self.request.set('list_sort_order', 'reverse') self.context_actions = {} self.title = self.context.translate(_("Kits")) self.icon = self.portal_url + \ "/++resource++baobab.lims.images/kit_big.png" self.description = '' self.show_sort_column = False self.show_select_row = False self.show_select_column = False self.pagesize = 25 if self.context.portal_type == 'Kits': self.request.set('disable_border', 1) self.columns = { 'Title': { 'title': _('Kit Name') }, 'Project': { 'title': _('Project'), 'toggle': True }, 'kitTemplate': { 'title': _('Kit template'), 'toggle': True }, 'state_title': { 'title': _('State'), 'index': 'review_state' }, 'sortable_title': {} } self.review_states = [ { 'id': 'default', 'title': _('Active'), 'contentFilter': { 'inactive_state': 'active', }, 'transitions': [ { 'id': 'deactivate' }, { 'id': 'receive_kit' }, { 'id': 'process' }, # {'id': 'ship'} ], 'columns': ['Title', 'Project', 'kitTemplate', 'state_title'] }, { 'id': 'shipped', 'title': _('Shipped'), 'contentFilter': { 'review_state': 'shipped', 'sort_on': 'sortable_title', 'sort_order': 'reverse' }, 'transitions': [{ 'id': 'deactivate' }, { 'id': 'receive_kit' }], 'columns': ['Title', 'Project', 'kitTemplate', 'state_title'] }, { 'id': 'received', 'title': _('Received'), 'contentFilter': { 'review_state': 'received', 'sort_on': 'sortable_title', 'sort_order': 'reverse' }, 'transitions': [{ 'id': 'deactivate' }, { 'id': 'process' }], 'columns': ['Title', 'Project', 'kitTemplate', 'state_title'] }, { 'id': 'processed', 'title': _('Processed'), 'contentFilter': { 'review_state': 'processed', 'sort_on': 'sortable_title', 'sort_order': 'reverse' }, 'transitions': [{ 'id': 'deactivate' }], 'columns': ['Title', 'Project', 'kitTemplate', 'state_title'] }, { 'id': 'all', 'title': _('All'), 'contentFilter': { 'sort_on': 'sortable_title', 'sort_order': 'reverse' }, 'columns': ['Title', 'Project', 'kitTemplate', 'state_title'] }, ]
def folderitem(self, obj, item, index): # Additional info from AnalysisRequest to be added in the item # generated by default by bikalisting. # Call the folderitem method from the base class item = BikaListingView.folderitem(self, obj, item, index) if not item: return None # This variable will contain the full analysis request if there is # need to work with the full object instead of the brain full_object = None item["Creator"] = self.user_fullname(obj.Creator) # If we redirect from the folderitems view we should check if the # user has permissions to medify the element or not. priority_sort_key = obj.getPrioritySortkey if not priority_sort_key: # Default priority is Medium = 3. # The format of PrioritySortKey is <priority>.<created> priority_sort_key = "3.%s" % obj.created.ISO8601() priority = priority_sort_key.split(".")[0] priority_text = PRIORITIES.getValue(priority) priority_div = """<div class="priority-ico priority-%s"> <span class="notext">%s</span><div> """ item["replace"]["Priority"] = priority_div % (priority, priority_text) item["replace"]["getProfilesTitle"] = obj.getProfilesTitleStr analysesnum = obj.getAnalysesNum if analysesnum: num_verified = str(analysesnum[0]) num_total = str(analysesnum[1]) item["getAnalysesNum"] = "{0}/{1}".format(num_verified, num_total) else: item["getAnalysesNum"] = "" # Progress progress_perc = self.get_progress_percentage(obj) item["replace"]["Progress"] = get_progress_bar_html(progress_perc) item["BatchID"] = obj.getBatchID if obj.getBatchID: item['replace']['BatchID'] = "<a href='%s'>%s</a>" % \ (obj.getBatchURL, obj.getBatchID) # TODO: SubGroup ??? # val = obj.Schema().getField('SubGroup').get(obj) # item['SubGroup'] = val.Title() if val else '' date = obj.getSamplingDate item["SamplingDate"] = \ self.ulocalized_time(date, long_format=1) if date else "" date = obj.getDateReceived item["getDateReceived"] = \ self.ulocalized_time(date, long_format=1) if date else "" date = obj.getDueDate item["getDueDate"] = \ self.ulocalized_time(date, long_format=1) if date else "" date = obj.getDatePublished item["getDatePublished"] = \ self.ulocalized_time(date, long_format=1) if date else "" date = obj.getDateVerified item["getDateVerified"] = \ self.ulocalized_time(date, long_format=1) if date else "" if self.printwfenabled: item["Printed"] = "" printed = obj.getPrinted if hasattr(obj, "getPrinted") else "0" print_icon = "" if printed == "0": print_icon = get_image("delete.png", title=t(_("Not printed yet"))) elif printed == "1": print_icon = get_image("ok.png", title=t(_("Printed"))) elif printed == "2": print_icon = get_image("exclamation.png", title=t( _("Republished after last print"))) item["after"]["Printed"] = print_icon item["SamplingDeviation"] = obj.getSamplingDeviationTitle item["getStorageLocation"] = obj.getStorageLocationTitle after_icons = "" # Getting a dictionary with each workflow id and current state in it states_dict = obj.getObjectWorkflowStates if obj.assigned_state == 'assigned': after_icons += get_image("worksheet.png", title=t(_("All analyses assigned"))) if states_dict.get('review_state', '') == 'invalid': after_icons += get_image("delete.png", title=t(_("Results have been withdrawn"))) due_date = obj.getDueDate if due_date and due_date < (obj.getDatePublished or DateTime()): due_date_str = self.ulocalized_time(due_date) img_title = "{}: {}".format(t(_("Late Analyses")), due_date_str) after_icons += get_image("late.png", title=img_title) if obj.getSamplingDate and obj.getSamplingDate > DateTime(): after_icons += get_image("calendar.png", title=t(_("Future dated sample"))) if obj.getInvoiceExclude: after_icons += get_image("invoice_exclude.png", title=t(_("Exclude from invoice"))) if obj.getHazardous: after_icons += get_image("hazardous.png", title=t(_("Hazardous"))) if after_icons: item['after']['getId'] = after_icons item['Created'] = self.ulocalized_time(obj.created, long_format=1) if obj.getContactUID: item['ClientContact'] = obj.getContactFullName item['replace']['ClientContact'] = "<a href='%s'>%s</a>" % \ (obj.getContactURL, obj.getContactFullName) else: item["ClientContact"] = "" # TODO-performance: If SamplingWorkflowEnabled, we have to get the # full object to check the user permissions, so far this is # a performance hit. if obj.getSamplingWorkflowEnabled: # We don't do anything with Sampling Date. # User can modify Sampling date # inside AR view. In this listing view, # we only let the user to edit Date Sampled # and Sampler if he wants to make 'sample' transaction. if not obj.getDateSampled: datesampled = self.ulocalized_time(DateTime(), long_format=True) item["class"]["getDateSampled"] = "provisional" else: datesampled = self.ulocalized_time(obj.getDateSampled, long_format=True) sampler = obj.getSampler if sampler: item["replace"]["getSampler"] = obj.getSamplerFullName if "Sampler" in self.roles and not sampler: sampler = self.member.id item["class"]["getSampler"] = "provisional" # sampling workflow - inline edits for Sampler and Date Sampled if states_dict.get('review_state', '') == 'to_be_sampled': # We need to get the full object in order to check # the permissions full_object = obj.getObject() checkPermission =\ self.context.portal_membership.checkPermission # TODO Do we really need this check? if checkPermission(TransitionSampleSample, full_object): item["required"] = ["getSampler", "getDateSampled"] item["allow_edit"] = ["getSampler", "getDateSampled"] # TODO-performance: hit performance while getting the # sample object... # TODO Can LabManagers be a Sampler?! samplers = getUsers(full_object, [ "Sampler", ]) username = self.member.getUserName() users = [({ "ResultValue": u, "ResultText": samplers.getValue(u) }) for u in samplers] item['choices'] = {'getSampler': users} Sampler = sampler and sampler or \ (username in samplers.keys() and username) or '' sampler = Sampler else: datesampled = self.ulocalized_time(obj.getDateSampled, long_format=True) sampler = obj.getSamplerFullName if obj.getSampler else '' else: datesampled = self.ulocalized_time(obj.getDateSampled, long_format=True) sampler = "" item["getDateSampled"] = datesampled item["getSampler"] = sampler # These don't exist on ARs # XXX This should be a list of preservers... item["getPreserver"] = "" item["getDatePreserved"] = "" # Advanced partitioning # append the UID of the primary AR as parent item["parent"] = obj.getRawParentAnalysisRequest or "" # append partition UIDs of this AR as children item["children"] = obj.getDescendantsUIDs or [] return item
def folderitems(self, full_objects=False, classic=False): """We add this function to tell baselisting to use brains instead of full objects""" items = BikaListingView.folderitems(self, full_objects, classic) return sorted(items, key=lambda item: item["position"])
def folderitems(self, full_objects = False): workflow = getToolByName(self.context, "portal_workflow") items = BikaListingView.folderitems(self) mtool = getToolByName(self.context, 'portal_membership') member = mtool.getAuthenticatedMember() translate = self.context.translate roles = member.getRoles() hideclientlink = 'RegulatoryInspector' in roles \ and 'Manager' not in roles \ and 'LabManager' not in roles \ and 'LabClerk' not in roles for x in range(len(items)): if not items[x].has_key('obj'): continue obj = items[x]['obj'] items[x]['replace']['getSampleID'] = "<a href='%s'>%s</a>" % \ (items[x]['url'], obj.getSampleID()) items[x]['replace']['Requests'] = ",".join( ["<a href='%s'>%s</a>" % (o.absolute_url(), o.Title()) for o in obj.getAnalysisRequests()]) items[x]['Client'] = obj.aq_parent.Title() if hideclientlink == False: items[x]['replace']['Client'] = "<a href='%s'>%s</a>" % \ (obj.aq_parent.absolute_url(), obj.aq_parent.Title()) items[x]['Creator'] = self.user_fullname(obj.Creator()) items[x]['DateReceived'] = self.ulocalized_time(obj.getDateReceived()) deviation = obj.getSamplingDeviation() items[x]['SamplingDeviation'] = deviation and deviation.Title() or '' items[x]['getStorageLocation'] = obj.getStorageLocation() and obj.getStorageLocation().Title() or '' items[x]['AdHoc'] = obj.getAdHoc() and True or '' items[x]['Created'] = self.ulocalized_time(obj.created()) samplingdate = obj.getSamplingDate() items[x]['getSamplingDate'] = self.ulocalized_time(samplingdate, long_format=1) after_icons = '' if obj.getSampleType().getHazardous(): after_icons += "<img title='%s' " \ "src='%s/++resource++bika.lims.images/hazardous.png'>" % \ (t(_("Hazardous")), self.portal_url) if obj.getSamplingDate() > DateTime(): after_icons += "<img title='%s' " \ "src='%s/++resource++bika.lims.images/calendar.png' >" % \ (t(_("Future dated sample")), self.portal_url) if after_icons: items[x]['after']['getSampleID'] = after_icons SamplingWorkflowEnabled =\ self.context.bika_setup.getSamplingWorkflowEnabled() if not samplingdate > DateTime() \ and SamplingWorkflowEnabled: datesampled = self.ulocalized_time(obj.getDateSampled()) if not datesampled: datesampled = self.ulocalized_time(DateTime()) items[x]['class']['getDateSampled'] = 'provisional' sampler = obj.getSampler().strip() if sampler: items[x]['replace']['getSampler'] = self.user_fullname(sampler) if 'Sampler' in member.getRoles() and not sampler: sampler = member.id items[x]['class']['getSampler'] = 'provisional' else: datesampled = '' sampler = '' items[x]['getDateSampled'] = datesampled items[x]['getSampler'] = sampler # sampling workflow - inline edits for Sampler and Date Sampled checkPermission = self.context.portal_membership.checkPermission state = workflow.getInfoFor(obj, 'review_state') if state == 'to_be_sampled' \ and checkPermission(SampleSample, obj) \ and not samplingdate > DateTime(): items[x]['required'] = ['getSampler', 'getDateSampled'] items[x]['allow_edit'] = ['getSampler', 'getDateSampled'] samplers = getUsers(obj, ['Sampler', 'LabManager', 'Manager']) getAuthenticatedMember = self.context.portal_membership.getAuthenticatedMember username = getAuthenticatedMember().getUserName() users = [({'ResultValue': u, 'ResultText': samplers.getValue(u)}) for u in samplers] items[x]['choices'] = {'getSampler': users} Sampler = sampler and sampler or \ (username in samplers.keys() and username) or '' items[x]['getSampler'] = Sampler # These don't exist on samples # the columns exist just to set "preserve" transition from lists. # XXX This should be a list of preservers... items[x]['getPreserver'] = '' items[x]['getDatePreserved'] = '' # inline edits for Preserver and Date Preserved checkPermission = self.context.portal_membership.checkPermission if checkPermission(PreserveSample, obj): items[x]['required'] = ['getPreserver', 'getDatePreserved'] items[x]['allow_edit'] = ['getPreserver', 'getDatePreserved'] preservers = getUsers(obj, ['Preserver', 'LabManager', 'Manager']) getAuthenticatedMember = self.context.portal_membership.getAuthenticatedMember username = getAuthenticatedMember().getUserName() users = [({'ResultValue': u, 'ResultText': preservers.getValue(u)}) for u in preservers] items[x]['choices'] = {'getPreserver': users} preserver = username in preservers.keys() and username or '' items[x]['getPreserver'] = preserver items[x]['getDatePreserved'] = self.ulocalized_time(DateTime()) items[x]['class']['getPreserver'] = 'provisional' items[x]['class']['getDatePreserved'] = 'provisional' # Hide Preservation/Sampling workflow actions if the edit columns # are not displayed. toggle_cols = self.get_toggle_cols() new_states = [] for i,state in enumerate(self.review_states): if state['id'] == self.review_state: if 'getSampler' not in toggle_cols \ or 'getDateSampled' not in toggle_cols: if 'hide_transitions' in state: state['hide_transitions'].append('sample') else: state['hide_transitions'] = ['sample',] if 'getPreserver' not in toggle_cols \ or 'getDatePreserved' not in toggle_cols: if 'hide_transitions' in state: state['hide_transitions'].append('preserve') else: state['hide_transitions'] = ['preserve',] new_states.append(state) self.review_states = new_states return items
def folderitems(self): wf = getToolByName(self, 'portal_workflow') rc = getToolByName(self, REFERENCE_CATALOG) pm = getToolByName(self.context, "portal_membership") member = pm.getAuthenticatedMember() # Only show "my" worksheets # this cannot be setup in contentFilter, # because AuthenticatedMember is not available in __init__ cookie = json.loads(self.request.get("review_state", '{}')) cookie_key = "%s%s" % (self.context.portal_type, self.form_id) # POST selected_state = self.request.get("%s_review_state"%self.form_id, '') if not selected_state: # cookie selected_state = cookie.get(cookie_key, '') if selected_state == 'mine': # modify contentFolter for current state new_review_states = [] for state in self.review_states: if state['id'] == 'mine': state['contentFilter']['getAnalyst'] = member.getId() else: new_review_states.append(state) self.review_states = new_review_states items = BikaListingView.folderitems(self) new_items = [] analyst_choices = [] for a in self.analysts: analyst_choices.append({'ResultValue': a, 'ResultText': self.analysts.getValue(a)}) can_reassign = False for x in range(len(items)): if not items[x].has_key('obj'): new_items.append(items[x]) continue obj = items[x]['obj'] review_state = wf.getInfoFor(obj, 'review_state') analyst = obj.getAnalyst().strip() creator = obj.Creator().strip() items[x]['Analyst'] = analyst instrument = obj.getInstrument() items[x]['Instrument'] = instrument and instrument.Title() or '' items[x]['Title'] = obj.Title() wst = obj.getWorksheetTemplate() items[x]['Template'] = wst and wst.Title() or '' if wst: items[x]['replace']['Template'] = "<a href='%s'>%s</a>" % \ (wst.absolute_url(), wst.Title()) items[x]['CreationDate'] = self.ulocalized_time(obj.creation_date) nr_analyses = len(obj.getAnalyses()) if nr_analyses == '0': # manager and labmanager see *all* worksheets # otherwise we must be Analyst or Creator to see empties. roles = member.getRoles() if not 'Manager' in roles \ and not 'LabManager' in roles \ and not member.getId() in (analyst, creator): continue # give empties pretty classes. items[x]['table_row_class'] = 'state-empty-worksheet' layout = obj.getLayout() if len(layout) > 0: items[x]['replace']['Title'] = "<a href='%s/manage_results'>%s</a>" % \ (items[x]['url'], items[x]['Title']) else: items[x]['replace']['Title'] = "<a href='%s/add_analyses'>%s</a>" % \ (items[x]['url'], items[x]['Title']) # set Services ws_services = {} for slot in [s for s in layout if s['type'] == 'a']: analysis = rc.lookupObject(slot['analysis_uid']) service = analysis.getService() title = service.Title() if title not in ws_services: ws_services[title] = "<a href='%s'>%s,</a>" % \ (service.absolute_url(), title) keys = list(ws_services.keys()) keys.sort() services = [] for key in keys: services.append(ws_services[key]) if services: services[-1] = services[-1].replace(",", "") items[x]['Services'] = "" items[x]['replace']['Services'] = " ".join(services) # set Sample Types pos_parent = {} for slot in layout: if slot['position'] in pos_parent: continue pos_parent[slot['position']] = rc.lookupObject(slot['container_uid']) sampletypes = {} blanks = {} controls = {} for container in pos_parent.values(): if container.portal_type == 'AnalysisRequest': sampletypes["<a href='%s'>%s,</a>" % \ (container.getSample().getSampleType().absolute_url(), container.getSample().getSampleType().Title())] = 1 if container.portal_type == 'ReferenceSample' and container.getBlank(): blanks["<a href='%s'>%s,</a>" % \ (container.absolute_url(), container.Title())] = 1 if container.portal_type == 'ReferenceSample' and not container.getBlank(): controls["<a href='%s'>%s,</a>" % \ (container.absolute_url(), container.Title())] = 1 sampletypes = list(sampletypes.keys()) sampletypes.sort() blanks = list(blanks.keys()) blanks.sort() controls = list(controls.keys()) controls.sort() # remove trailing commas if sampletypes: sampletypes[-1] = sampletypes[-1].replace(",", "") if controls: controls[-1] = controls[-1].replace(",", "") else: if blanks: blanks[-1] = blanks[-1].replace(",", "") items[x]['SampleTypes'] = "" items[x]['replace']['SampleTypes'] = " ".join(sampletypes) items[x]['QC'] = "" items[x]['replace']['QC'] = " ".join(blanks + controls) if items[x]['review_state'] == 'open': items[x]['allow_edit'] = ['Analyst', ] items[x]['required'] = ['Analyst', ] can_reassign = True items[x]['choices'] = {'Analyst': analyst_choices} new_items.append(items[x]) if can_reassign: for x in range(len(self.review_states)): if self.review_states[x]['id'] in ['default', 'mine', 'open']: self.review_states[x]['custom_actions'] = [{'id': 'reassign', 'title': _('Reassign')}, ] return new_items
def folderitem(self, obj, item, index): # Additional info from AnalysisRequest to be added in the item generated # by default by bikalisting. # Call the folderitem method from the base class item = BikaListingView.folderitem(self, obj, item, index) if not item: return None member = self.mtool.getAuthenticatedMember() roles = member.getRoles() hideclientlink = 'RegulatoryInspector' in roles \ and 'Manager' not in roles \ and 'LabManager' not in roles \ and 'LabClerk' not in roles sample = obj.getSample() url = obj.absolute_url() if getSecurityManager().checkPermission(EditResults, obj): url += "/manage_results" item['Client'] = obj.aq_parent.Title() if (hideclientlink == False): item['replace']['Client'] = "<a href='%s'>%s</a>" % \ (obj.aq_parent.absolute_url(), obj.aq_parent.Title()) item['Creator'] = self.user_fullname(obj.Creator()) item['getRequestID'] = obj.getRequestID() item['replace']['getRequestID'] = "<a href='%s'>%s</a>" % \ (url, item['getRequestID']) item['getSample'] = sample item['replace']['getSample'] = \ "<a href='%s'>%s</a>" % (sample.absolute_url(), sample.Title()) item['replace']['getProfilesTitle'] = ", ".join( [p.Title() for p in obj.getProfiles()]) analysesnum = obj.getAnalysesNum() if analysesnum: item['getAnalysesNum'] = str(analysesnum[0]) + '/' + str( analysesnum[1]) else: item['getAnalysesNum'] = '' batch = obj.getBatch() if batch: item['BatchID'] = batch.getBatchID() item['replace']['BatchID'] = "<a href='%s'>%s</a>" % \ (batch.absolute_url(), item['BatchID']) else: item['BatchID'] = '' val = obj.Schema().getField('SubGroup').get(obj) item['SubGroup'] = val.Title() if val else '' sd = obj.getSample().getSamplingDate() item['SamplingDate'] = \ self.ulocalized_time(sd, long_format=1) if sd else '' item['getDateReceived'] = self.ulocalized_time(obj.getDateReceived()) item['getDatePublished'] = self.ulocalized_time(obj.getDatePublished()) item['getDateVerified'] = getTransitionDate(obj, 'verify') deviation = sample.getSamplingDeviation() item['SamplingDeviation'] = deviation and deviation.Title() or '' priority = obj.getPriority() item['Priority'] = '' # priority.Title() item['getStorageLocation'] = sample.getStorageLocation( ) and sample.getStorageLocation().Title() or '' item['AdHoc'] = sample.getAdHoc() and True or '' after_icons = "" state = self.workflow.getInfoFor(obj, 'worksheetanalysis_review_state') if state == 'assigned': after_icons += "<img src='%s/++resource++bika.lims.images/worksheet.png' title='%s'/>" % \ (self.portal_url, t(_("All analyses assigned"))) if self.workflow.getInfoFor(obj, 'review_state') == 'invalid': after_icons += "<img src='%s/++resource++bika.lims.images/delete.png' title='%s'/>" % \ (self.portal_url, t(_("Results have been withdrawn"))) if obj.getLate(): after_icons += "<img src='%s/++resource++bika.lims.images/late.png' title='%s'>" % \ (self.portal_url, t(_("Late Analyses"))) if sd and sd > DateTime(): after_icons += "<img src='%s/++resource++bika.lims.images/calendar.png' title='%s'>" % \ (self.portal_url, t(_("Future dated sample"))) if obj.getInvoiceExclude(): after_icons += "<img src='%s/++resource++bika.lims.images/invoice_exclude.png' title='%s'>" % \ (self.portal_url, t(_("Exclude from invoice"))) if sample.getSampleType().getHazardous(): after_icons += "<img src='%s/++resource++bika.lims.images/hazardous.png' title='%s'>" % \ (self.portal_url, t(_("Hazardous"))) if after_icons: item['after']['getRequestID'] = after_icons item['Created'] = self.ulocalized_time(obj.created()) contact = obj.getContact() if contact: item['ClientContact'] = contact.Title() item['replace']['ClientContact'] = "<a href='%s'>%s</a>" % \ (contact.absolute_url(), contact.Title()) else: item['ClientContact'] = "" SamplingWorkflowEnabled = sample.getSamplingWorkflowEnabled() if SamplingWorkflowEnabled and (not sd or not sd > DateTime()): datesampled = self.ulocalized_time(sample.getDateSampled(), long_format=True) if not datesampled: datesampled = self.ulocalized_time(DateTime(), long_format=True) item['class']['getDateSampled'] = 'provisional' sampler = sample.getSampler().strip() if sampler: item['replace']['getSampler'] = self.user_fullname(sampler) if 'Sampler' in member.getRoles() and not sampler: sampler = member.id item['class']['getSampler'] = 'provisional' else: datesampled = '' sampler = '' item['getDateSampled'] = datesampled item['getSampler'] = sampler # sampling workflow - inline edits for Sampler and Date Sampled checkPermission = self.context.portal_membership.checkPermission state = self.workflow.getInfoFor(obj, 'review_state') if state == 'to_be_sampled' \ and checkPermission(SampleSample, obj) \ and (not sd or not sd > DateTime()): item['required'] = ['getSampler', 'getDateSampled'] item['allow_edit'] = ['getSampler', 'getDateSampled'] samplers = getUsers(sample, ['Sampler', 'LabManager', 'Manager']) username = member.getUserName() users = [({ 'ResultValue': u, 'ResultText': samplers.getValue(u) }) for u in samplers] item['choices'] = {'getSampler': users} Sampler = sampler and sampler or \ (username in samplers.keys() and username) or '' item['getSampler'] = Sampler # These don't exist on ARs # XXX This should be a list of preservers... item['getPreserver'] = '' item['getDatePreserved'] = '' # inline edits for Preserver and Date Preserved checkPermission = self.context.portal_membership.checkPermission if checkPermission(PreserveSample, obj): item['required'] = ['getPreserver', 'getDatePreserved'] item['allow_edit'] = ['getPreserver', 'getDatePreserved'] preservers = getUsers(obj, ['Preserver', 'LabManager', 'Manager']) username = member.getUserName() users = [({ 'ResultValue': u, 'ResultText': preservers.getValue(u) }) for u in preservers] item['choices'] = {'getPreserver': users} preserver = username in preservers.keys() and username or '' item['getPreserver'] = preserver item['getDatePreserved'] = self.ulocalized_time(DateTime(), long_format=1) item['class']['getPreserver'] = 'provisional' item['class']['getDatePreserved'] = 'provisional' # Submitting user may not verify results if item['review_state'] == 'to_be_verified' and \ not checkPermission(VerifyOwnResults, obj): self_submitted = False try: review_history = list( self.workflow.getInfoFor(obj, 'review_history')) review_history.reverse() for event in review_history: if event.get('action') == 'submit': if event.get('actor') == member.getId(): self_submitted = True break if self_submitted: item['after']['state_title'] = \ "<img src='++resource++bika.lims.images/submitted-by-current-user.png' title='%s'/>" % \ t(_("Cannot verify: Submitted by current user")) except Exception: pass return item
def folderitems(self): wf = getToolByName(self, 'portal_workflow') rc = getToolByName(self, REFERENCE_CATALOG) pm = getToolByName(self.context, "portal_membership") self.member = pm.getAuthenticatedMember() roles = self.member.getRoles() self.restrict_results = 'Manager' not in roles \ and 'LabManager' not in roles \ and 'LabClerk' not in roles \ and 'RegulatoryInspector' not in roles \ and self.context.bika_setup.getRestrictWorksheetUsersAccess() if self.restrict_results == True: # Remove 'Mine' button and hide 'Analyst' column del self.review_states[1] # Mine self.columns['Analyst']['toggle'] = False can_manage = pm.checkPermission(ManageWorksheets, self.context) self.selected_state = self.request.get( "%s_review_state" % self.form_id, 'default') items = BikaListingView.folderitems(self) new_items = [] analyst_choices = [] for a in self.analysts: analyst_choices.append({ 'ResultValue': a, 'ResultText': self.analysts.getValue(a) }) can_reassign = False self.allow_edit = self.isEditionAllowed() for x in range(len(items)): if not items[x].has_key('obj'): new_items.append(items[x]) continue obj = items[x]['obj'] analyst = obj.getAnalyst().strip() creator = obj.Creator().strip() items[x]['Analyst'] = analyst priority = obj.getPriority() items[x]['Priority'] = '' instrument = obj.getInstrument() items[x]['Instrument'] = instrument and instrument.Title() or '' items[x]['Title'] = obj.Title() wst = obj.getWorksheetTemplate() items[x]['Template'] = wst and wst.Title() or '' if wst: items[x]['replace']['Template'] = "<a href='%s'>%s</a>" % \ (wst.absolute_url(), wst.Title()) items[x]['getPriority'] = '' items[x]['CreationDate'] = self.ulocalized_time(obj.creation_date) nr_analyses = len(obj.getAnalyses()) if nr_analyses == '0': # give empties pretty classes. items[x]['table_row_class'] = 'state-empty-worksheet' layout = obj.getLayout() if len(layout) > 0: items[x]['replace']['Title'] = "<a href='%s/manage_results'>%s</a>" % \ (items[x]['url'], items[x]['Title']) else: items[x]['replace']['Title'] = "<a href='%s/add_analyses'>%s</a>" % \ (items[x]['url'], items[x]['Title']) # set Services ws_services = {} for slot in [s for s in layout if s['type'] == 'a']: analysis = rc.lookupObject(slot['analysis_uid']) service = analysis.getService() title = service.Title() if title not in ws_services: ws_services[title] = "<a href='%s'>%s,</a>" % \ (service.absolute_url(), title) keys = list(ws_services.keys()) keys.sort() services = [] for key in keys: services.append(ws_services[key]) if services: services[-1] = services[-1].replace(",", "") items[x]['Services'] = "" items[x]['replace']['Services'] = " ".join(services) # set Sample Types pos_parent = {} for slot in layout: # compensate for bad data caused by a stupid bug. if type(slot['position']) in (list, tuple): slot['position'] = slot['position'][0] if slot['position'] == 'new': continue if slot['position'] in pos_parent: continue pos_parent[slot['position']] = rc.lookupObject( slot['container_uid']) sampletypes = {} blanks = {} controls = {} for container in pos_parent.values(): if container.portal_type == 'AnalysisRequest': sampletypes["<a href='%s'>%s,</a>" % \ (container.getSample().getSampleType().absolute_url(), container.getSample().getSampleType().Title())] = 1 if container.portal_type == 'ReferenceSample' and container.getBlank( ): blanks["<a href='%s'>%s,</a>" % \ (container.absolute_url(), container.Title())] = 1 if container.portal_type == 'ReferenceSample' and not container.getBlank( ): controls["<a href='%s'>%s,</a>" % \ (container.absolute_url(), container.Title())] = 1 sampletypes = list(sampletypes.keys()) sampletypes.sort() blanks = list(blanks.keys()) blanks.sort() controls = list(controls.keys()) controls.sort() # remove trailing commas if sampletypes: sampletypes[-1] = sampletypes[-1].replace(",", "") if controls: controls[-1] = controls[-1].replace(",", "") else: if blanks: blanks[-1] = blanks[-1].replace(",", "") items[x]['SampleTypes'] = "" items[x]['replace']['SampleTypes'] = " ".join(sampletypes) items[x]['QC'] = "" items[x]['replace']['QC'] = " ".join(blanks + controls) items[x]['QCTotals'] = '' # Get all Worksheet QC Analyses totalQCAnalyses = [ a for a in obj.getAnalyses() if a.portal_type == 'ReferenceAnalysis' or a.portal_type == 'DuplicateAnalysis' ] totalQCSamples = [] # Get all Worksheet QC samples for analysis in totalQCAnalyses: if analysis.getSample().UID() not in totalQCSamples: totalQCSamples.append(analysis.getSample().UID()) # Total QC Samples (Total Routine Analyses) items[x]['QCTotals'] = str(len(totalQCSamples)) + '(' + str( len(totalQCAnalyses)) + ')' totalRoutineAnalyses = [ a for a in obj.getAnalyses() if a not in totalQCAnalyses ] totalRoutineSamples = [] for analysis in totalRoutineAnalyses: if analysis.getSample().UID() not in totalRoutineSamples: totalRoutineSamples.append(analysis.getSample().UID()) # Total Routine Samples (Total Routine Analyses) items[x]['RoutineTotals'] = str( len(totalRoutineSamples)) + '(' + str( len(totalRoutineAnalyses)) + ')' if items[x]['review_state'] == 'open' \ and self.allow_edit \ and self.restrict_results == False \ and can_manage == True: items[x]['allow_edit'] = [ 'Analyst', ] items[x]['required'] = [ 'Analyst', ] can_reassign = True items[x]['choices'] = {'Analyst': analyst_choices} new_items.append(items[x]) if can_reassign: for x in range(len(self.review_states)): if self.review_states[x]['id'] in ['default', 'mine', 'open']: self.review_states[x]['custom_actions'] = [ { 'id': 'reassign', 'title': _('Reassign') }, ] self.show_select_column = can_reassign self.show_workflow_action_buttons = can_reassign return new_items
def folderitems(self): self.categories = [] analyses = self.context.getAnalyses(full_objects=True) self.analyses = dict([(a.getServiceUID(), a) for a in analyses]) self.selected = self.analyses.keys() self.show_categories = \ self.context.bika_setup.getCategoriseAnalysisServices() self.expand_all_categories = False wf = getToolByName(self.context, 'portal_workflow') mtool = getToolByName(self.context, 'portal_membership') self.allow_edit = mtool.checkPermission('Modify portal content', self.context) items = BikaListingView.folderitems(self) analyses = self.context.getAnalyses(full_objects=True) parts = self.context.getSample().objectValues('SamplePartition') partitions = [{ 'ResultValue': o.Title(), 'ResultText': o.getId() } for o in parts if wf.getInfoFor(o, 'cancellation_state', '') == 'active' ] for x in range(len(items)): if not 'obj' in items[x]: continue obj = items[x]['obj'] cat = obj.getCategoryTitle() items[x]['category'] = cat if cat not in self.categories: self.categories.append(cat) items[x]['selected'] = items[x]['uid'] in self.selected items[x]['class']['Title'] = 'service_title' # js checks in row_data if an analysis may be removed. row_data = {} # keyword = obj.getKeyword() # if keyword in review_states.keys() \ # and review_states[keyword] not in ['sample_due', # 'to_be_sampled', # 'to_be_preserved', # 'sample_received', # ]: # row_data['disabled'] = True items[x]['row_data'] = json.dumps(row_data) calculation = obj.getCalculation() items[x]['Calculation'] = calculation and calculation.Title() locale = locales.getLocale('en') currency = self.context.bika_setup.getCurrency() symbol = locale.numbers.currencies[currency].symbol items[x]['before']['Price'] = symbol items[x]['Price'] = obj.getPrice() items[x]['class']['Price'] = 'nowrap' items[x]['Priority'] = '' if items[x]['selected']: items[x]['allow_edit'] = ['Partition', 'min', 'max', 'error'] if not logged_in_client(self.context): items[x]['allow_edit'].append('Price') items[x]['required'].append('Partition') items[x]['choices']['Partition'] = partitions if obj.UID() in self.analyses: analysis = self.analyses[obj.UID()] part = analysis.getSamplePartition() part = part and part or obj items[x]['Partition'] = part.Title() spec = self.get_spec_from_ar( self.context, analysis.getService().getKeyword()) items[x]["min"] = spec["min"] items[x]["max"] = spec["max"] items[x]["error"] = spec["error"] # Add priority premium items[x]['Price'] = analysis.getPrice() priority = analysis.getPriority() items[x]['Priority'] = priority and priority.Title() or '' else: items[x]['Partition'] = '' items[x]["min"] = '' items[x]["max"] = '' items[x]["error"] = '' items[x]["Priority"] = '' after_icons = '' if obj.getAccredited(): after_icons += "<img\ src='%s/++resource++bika.lims.images/accredited.png'\ title='%s'>" % (self.portal_url, t(_("Accredited"))) if obj.getReportDryMatter(): after_icons += "<img\ src='%s/++resource++bika.lims.images/dry.png'\ title='%s'>" % (self.portal_url, t(_("Can be reported as dry matter"))) if obj.getAttachmentOption() == 'r': after_icons += "<img\ src='%s/++resource++bika.lims.images/attach_reqd.png'\ title='%s'>" % (self.portal_url, t(_("Attachment required"))) if obj.getAttachmentOption() == 'n': after_icons += "<img\ src='%s/++resource++bika.lims.images/attach_no.png'\ title='%s'>" % (self.portal_url, t(_('Attachment not permitted'))) if after_icons: items[x]['after']['Title'] = after_icons self.categories.sort() return items
def folderitems(self, full_objects = False): items = BikaListingView.folderitems(self) bsc = getToolByName(self.context, 'bika_setup_catalog') containers = [({'ResultValue':o.UID, 'ResultText':o.title}) for o in bsc(portal_type="Container", inactive_state="active")] preservations = [({'ResultValue':o.UID, 'ResultText':o.title}) for o in bsc(portal_type="Preservation", inactive_state="active")] for x in range(len(items)): if not items[x].has_key('obj'): continue obj = items[x]['obj'] items[x]['PartTitle'] = obj.getId() container = obj.getContainer() if self.allow_edit: items[x]['getContainer'] = container and container.UID() or '' else: items[x]['getContainer'] = container and container.Title() or '' preservation = obj.getPreservation() if self.allow_edit: items[x]['getPreservation'] = preservation and preservation.UID() or '' else: items[x]['getPreservation'] = preservation and preservation.Title() or '' ## sampler = obj.getSampler().strip() ## items[x]['getSampler'] = \ ## sampler and self.user_fullname(sampler) or '' ## datesampled = obj.getDateSampled() ## items[x]['getDateSampled'] = \ ## datesampled and self.ulocalized_time(datesampled) or '' preserver = obj.getPreserver().strip() items[x]['getPreserver'] = \ preserver and self.user_fullname(preserver) or '' datepreserved = obj.getDatePreserved() items[x]['getDatePreserved'] = \ datepreserved and self.ulocalized_time(datepreserved) or '' disposaldate = obj.getDisposalDate() items[x]['getDisposalDate'] = \ disposaldate and self.ulocalized_time(disposaldate) or '' samplingdate = obj.getSamplingDate() # inline edits for Container and Preservation items[x]['allow_edit'] = ['getContainer', 'getPreservation'] items[x]['choices']['getPreservation'] = preservations items[x]['choices']['getContainer'] = containers # inline edits for Sampler and Date Sampled ## checkPermission = self.context.portal_membership.checkPermission ## if checkPermission(SampleSample, obj) \ ## and not samplingdate > DateTime(): ## items[x]['required'] += ['getSampler', 'getDateSampled'] ## items[x]['allow_edit'] += ['getSampler', 'getDateSampled'] ## samplers = getUsers(obj, ['Sampler', 'LabManager', 'Manager']) ## getAuthenticatedMember = obj.portal_membership.getAuthenticatedMember ## username = getAuthenticatedMember().getUserName() ## users = [({'ResultValue': u, 'ResultText': samplers.getValue(u)}) ## for u in samplers] ## items[x]['choices']['getSampler'] = users ## items[x]['getSampler'] = sampler and sampler or \ ## (username in samplers.keys() and username) or '' ## items[x]['getDateSampled'] = items[x]['getDateSampled'] \ ## or DateTime().strftime(self.date_format_short) ## items[x]['class']['getSampler'] = 'provisional' ## items[x]['class']['getDateSampled'] = 'provisional' # inline edits for Preserver and Date Preserved checkPermission = self.context.portal_membership.checkPermission if checkPermission(PreserveSample, obj): items[x]['required'] += ['getPreserver', 'getDatePreserved'] items[x]['allow_edit'] += ['getPreserver', 'getDatePreserved'] preservers = getUsers(obj, ['Preserver', 'LabManager', 'Manager']) getAuthenticatedMember = obj.portal_membership.getAuthenticatedMember username = getAuthenticatedMember().getUserName() users = [({'ResultValue': u, 'ResultText': preservers.getValue(u)}) for u in preservers] items[x]['choices']['getPreserver'] = users items[x]['getPreserver'] = preserver and preserver or \ (username in preservers.keys() and username) or '' items[x]['getDatePreserved'] = items[x]['getDatePreserved'] \ or DateTime().strftime(self.date_format_short) items[x]['class']['getPreserver'] = 'provisional' items[x]['class']['getDatePreserved'] = 'provisional' return items
def folderitem(self, obj, item, index): # Additional info from Worksheet to be added in the item generated by # default by bikalisting. # Call the folderitem method from the base class item = BikaListingView.folderitem(self, obj, item, index) if not item: return None item['CreationDate'] = self.ulocalized_time(obj.creation_date) item['Analyst'] = obj.getAnalyst().strip() item['Priority'] = '' item['getPriority'] = '' instrument = obj.getInstrument() item['Instrument'] = instrument.Title() if instrument else '' wst = obj.getWorksheetTemplate() item['Template'] = wst.Title() if wst else '' if wst: item['replace']['Template'] = "<a href='%s'>%s</a>" % \ (wst.absolute_url(), wst.Title()) if len(obj.getAnalyses()) == 0: item['table_row_class'] = 'state-empty-worksheet' layout = obj.getLayout() item['Title'] = obj.Title() turl = "manage_results" if len(layout) > 0 else "add_analyses" item['replace']['Title'] = "<a href='%s/%s'>%s</a>" % \ (item['url'], turl, item['Title']) # Set services ws_services = {} for slot in [s for s in layout if s['type'] == 'a']: analysis = self.rc.lookupObject(slot['analysis_uid']) if not analysis: error = "Analysis with uid '%s' NOT FOUND in Reference Catalog.\n Worksheet: '%s'. Layout: '%s'" % \ (slot['analysis_uid'], obj, layout) logging.info(error) continue service = analysis.getService() title = service.Title() if title not in ws_services: ws_services[title] = "<a href='%s'>%s</a>" % \ (service.absolute_url(), title) keys = list(ws_services.keys()) keys.sort() services = [ws_services[k] for k in keys] item['Services'] = "" item['replace']['Services'] = ", ".join(services) pos_parent = {} for slot in layout: # compensate for bad data caused by a stupid bug. if type(slot['position']) in (list, tuple): slot['position'] = slot['position'][0] if slot['position'] == 'new': continue if slot['position'] in pos_parent: continue pos_parent[slot['position']] = self.rc.lookupObject( slot['container_uid']) # Set Sample Types and QC Samples sampletypes = [] qcsamples = [] for container in pos_parent.values(): if container.portal_type == 'AnalysisRequest': sampletype = "<a href='%s'>%s</a>" % \ (container.getSample().getSampleType().absolute_url(), container.getSample().getSampleType().Title()) sampletypes.append(sampletype) if container.portal_type == 'ReferenceSample': qcsample = "<a href='%s'>%s</a>" % \ (container.absolute_url(), container.Title()) qcsamples.append(qcsample) sampletypes = list(set(sampletypes)) sampletypes.sort() item['SampleTypes'] = "" item['replace']['SampleTypes'] = ", ".join(sampletypes) qcsamples = list(set(qcsamples)) qcsamples.sort() item['QC'] = "" item['replace']['QC'] = ", ".join(qcsamples) item['QCTotals'] = '' # Total QC Samples (Total Routine Analyses) analyses = obj.getAnalyses() totalQCAnalyses = [ a for a in analyses if a.portal_type == 'ReferenceAnalysis' or a.portal_type == 'DuplicateAnalysis' ] totalQCSamples = [a.getSample().UID() for a in totalQCAnalyses] totalQCSamples = list(set(totalQCSamples)) item['QCTotals'] = str(len(totalQCSamples)) + ' (' + str( len(totalQCAnalyses)) + ')' # Total Routine Samples (Total Routine Analyses) totalRoutineAnalyses = [ a for a in analyses if a not in totalQCAnalyses ] totalRoutineSamples = [ a.getSample().UID() for a in totalRoutineAnalyses ] totalRoutineSamples = list(set(totalRoutineSamples)) item['RoutineTotals'] = str(len(totalRoutineSamples)) + ' (' + str( len(totalRoutineAnalyses)) + ')' if item['review_state'] == 'open' \ and self.allow_edit \ and self.restrict_results == False \ and self.can_manage == True: item['allow_edit'] = [ 'Analyst', ] item['required'] = [ 'Analyst', ] item['choices'] = {'Analyst': self.analyst_choices} self.can_reassign = True return item