def __call__(self, result=None, specification=None, **kwargs): searchTerm = _c(self.request.get('searchTerm', '')).lower() force_all = self.request.get('force_all', 'true') searchFields = 'search_fields' in self.request \ and json.loads(_u(self.request.get('search_fields', '[]'))) \ or ('Title',) # lookup objects from ZODB catalog_name = _c(self.request.get('catalog_name', 'portal_catalog')) catalog = getToolByName(self.context, catalog_name) base_query = json.loads(_c(self.request['base_query'])) search_query = json.loads(_c(self.request.get('search_query', "{}"))) # first with all queries contentFilter = dict((k, v) for k, v in base_query.items()) contentFilter.update(search_query) try: brains = catalog(contentFilter) except: from lims import logger logger.info(contentFilter) raise if brains and searchTerm: _brains = [] if len(searchFields) == 0 \ or (len(searchFields) == 1 and searchFields[0] == 'Title'): _brains = [ p for p in brains if p.Title.lower().find(searchTerm) > -1 ] else: for p in brains: for fieldname in searchFields: value = getattr(p, fieldname, None) if not value: instance = p.getObject() schema = instance.Schema() if fieldname in schema: value = schema[fieldname].get(instance) if value and value.lower().find(searchTerm) > -1: _brains.append(p) break brains = _brains # Then just base_query alone ("show all if no match") if not brains and force_all.lower() == 'true': if search_query: brains = catalog(base_query) if brains and searchTerm: _brains = [ p for p in brains if p.Title.lower().find(searchTerm) > -1 ] if _brains: brains = _brains return brains
def __call__(self, result=None, specification=None, **kwargs): searchTerm = _c(self.request.get('searchTerm', '')).lower() force_all = self.request.get('force_all', 'true') searchFields = 'search_fields' in self.request \ and json.loads(_u(self.request.get('search_fields', '[]'))) \ or ('Title',) # lookup objects from ZODB catalog_name = _c(self.request.get('catalog_name', 'portal_catalog')) catalog = getToolByName(self.context, catalog_name) base_query = json.loads(_c(self.request['base_query'])) search_query = json.loads(_c(self.request.get('search_query', "{}"))) # first with all queries contentFilter = dict((k, v) for k, v in base_query.items()) contentFilter.update(search_query) try: brains = catalog(contentFilter) except: from lims import logger logger.info(contentFilter) raise if brains and searchTerm: _brains = [] if len(searchFields) == 0 \ or (len(searchFields) == 1 and searchFields[0] == 'Title'): _brains = [p for p in brains if p.Title.lower().find(searchTerm) > -1] else: for p in brains: for fieldname in searchFields: value = getattr(p, fieldname, None) if not value: instance = p.getObject() schema = instance.Schema() if fieldname in schema: value = schema[fieldname].get(instance) if value and value.lower().find(searchTerm) > -1: _brains.append(p) break brains = _brains # Then just base_query alone ("show all if no match") if not brains and force_all.lower() == 'true': if search_query: brains = catalog(base_query) if brains and searchTerm: _brains = [p for p in brains if p.Title.lower().find(searchTerm) > -1] if _brains: brains = _brains return brains
def isItemAllowed(self, obj): # Only show "my" worksheets # this cannot be setup in contentFilter, # because AuthenticatedMember is not available in __init__ if self.selected_state == 'mine' or self.restrict_results == True: analyst = obj.getAnalyst().strip() if analyst != _c(self.member.getId()): return False return BikaListingView.isItemAllowed(self, obj)
def checkUserAccess(self): """ Checks if the current user has granted access to this worksheet. Returns False if the user has no access, otherwise returns True """ # Deny access to foreign analysts allowed = True pm = getToolByName(self, "portal_membership") member = pm.getAuthenticatedMember() analyst = self.getAnalyst().strip() if analyst != _c(member.getId()): roles = member.getRoles() restrict = 'Manager' not in roles \ and 'LabManager' not in roles \ and 'LabClerk' not in roles \ and 'RegulatoryInspector' not in roles \ and self.bika_setup.getRestrictWorksheetUsersAccess() allowed = not restrict return allowed
def checkUserManage(self): """ Checks if the current user has granted access to this worksheet and if has also privileges for managing it. """ granted = False can_access = self.checkUserAccess() if can_access == True: pm = getToolByName(self, 'portal_membership') edit_allowed = pm.checkPermission(EditWorksheet, self) if edit_allowed: # Check if the current user is the WS's current analyst member = pm.getAuthenticatedMember() analyst = self.getAnalyst().strip() if analyst != _c(member.getId()): # Has management privileges? if pm.checkPermission(ManageWorksheets, self): granted = True else: granted = True return granted
def __call__(self): """Create and render selected report """ # if there's an error, we return productivity.pt which requires these. self.selection_macros = SelectionMacrosView(self.context, self.request) self.additional_reports = [] adapters = getAdapters((self.context, ), IProductivityReport) for name, adapter in adapters: report_dict = adapter(self.context, self.request) report_dict['id'] = name self.additional_reports.append(report_dict) report_id = self.request.get('report_id', '') if not report_id: message = _("No report specified in request") self.logger.error(message) self.context.plone_utils.addPortalMessage(message, 'error') return self.template() self.date = DateTime() username = self.context.portal_membership.getAuthenticatedMember().getUserName() self.reporter = self.user_fullname(username) self.reporter_email = self.user_email(username) # signature image self.reporter_signature = "" c = [x for x in self.bika_setup_catalog(portal_type='LabContact') if x.getObject().getUsername() == username] if c: sf = c[0].getObject().getSignature() if sf: self.reporter_signature = sf.absolute_url() + "/Signature" lab = self.context.bika_setup.laboratory self.laboratory = lab self.lab_title = lab.getName() self.lab_address = lab.getPrintAddress() self.lab_email = lab.getEmailAddress() self.lab_url = lab.getLabURL() client = logged_in_client(self.context) if client: clientuid = client.UID() self.client_title = client.Title() self.client_address = client.getPrintAddress() else: clientuid = None self.client_title = None self.client_address = None # Render form output # the report can add file names to this list; they will be deleted # once the PDF has been generated. temporary plot image files, etc. self.request['to_remove'] = [] if "report_module" in self.request: module = self.request["report_module"] else: module = "bika.lims.browser.reports.%s" % report_id try: exec ("from %s import Report" % module) # required during error redirect: the report must have a copy of # additional_reports, because it is used as a surrogate view. Report.additional_reports = self.additional_reports except ImportError: message = "Report %s.Report not found (shouldn't happen)" % module self.logger.error(message) self.context.plone_utils.addPortalMessage(message, 'error') return self.template() # Report must return dict with: # - report_title - title string for pdf/history listing # - report_data - rendered report output = Report(self.context, self.request)() # if CSV output is chosen, report returns None if not output: return if type(output) in (str, unicode, bytes): # remove temporary files for f in self.request['to_remove']: os.remove(f) return output # The report output gets pulled through report_frame.pt self.reportout = output['report_data'] framed_output = self.frame_template() # this is the good part result = createPdf(framed_output) # remove temporary files for f in self.request['to_remove']: os.remove(f) if result: # Create new report object reportid = self.aq_parent.generateUniqueId('Report') report = _createObjectByType("Report", self.aq_parent, reportid) report.edit(Client=clientuid) report.processForm() # write pdf to report object report.edit(title=output['report_title'], ReportFile=result) report.reindexObject() fn = "%s - %s" % (self.date.strftime(self.date_format_short), _u(output['report_title'])) setheader = self.request.RESPONSE.setHeader setheader('Content-Type', 'application/pdf') setheader("Content-Disposition", "attachment;filename=\"%s\"" % _c(fn)) self.request.RESPONSE.write(result) return
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): 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)