def copy_generic_fields(event): event_object = event.getObject() temp_id = "temp_copy_of_%s" % event_object.id container = aq_parent(event_object) _createObjectByType('Event', container, id=temp_id, title=event_object.title) new_event = container[temp_id] new_event.subtitle = event_object.subtitle() image_field = new_event.getField('leadImage') if image_field is not None: image_field.getMutator(new_event)(event_object.getEvent_Image()) image_caption_field = new_event.getField('leadImage_caption') if image_caption_field is not None: image_caption_field.getMutator(new_event)(event_object.getEvent_Image_caption()) new_event.speaker = event_object.speaker() new_event.startDate = event_object.start() new_event.endDate = event_object.end() new_event.rsvpRequired = event_object.getEvent_Rsvp() new_event.contactName = event_object.contact_name() new_event.contactEmail = event_object.contact_email() new_event.contactPhone = event_object.contact_phone() new_event.location = event_object.getLocation() text = event_object.abstract() text += event_object.event_Speaker_detail() if event_object.event_Reception: text += "<p>There will be a reception folowing the event.</p>" if event_object.getEvent_Public(): text += "<p>This is a public event.</p>" if event_object.event_custom_Rsvp: text += "<p>To RSVP, please email %s.</p>" % event_object.event_custom_Rsvp.encode('utf-8') else: text += "<p>To RSVP, please email [email protected].</p>" if event_object.event_Invite: text += "<p>This is an invitation only event.</p>" new_event.setText(text) return new_event
def createStructure(context, logger): site = context.getSite() wftool = getToolByName(site, "portal_workflow") # CONTAINER folder = getattr(site, CONTAINER_ID, None) if folder is None: _createObjectByType('Folder', site, id=CONTAINER_ID, title=CONTAINER_TITLE) folder = getattr(site, CONTAINER_ID) folder.setOrdering('unordered') folder.setConstrainTypesMode(constraintypes.ENABLED) #folder.setLocallyAllowedTypes(["Bounty Program Submission"]) #folder.setImmediatelyAddableTypes(["Bounty Program Submission"]) folder.setDefaultPage(TOPIC_ID) folder.unmarkCreationFlag() if wftool.getInfoFor(folder, 'review_state') != 'published': wftool.doActionFor(folder, 'publish') logger.info("Submissions container added") else: logger.info("Submissions container already exist at %s" % \ folder.absolute_url()) createTopic(folder, wftool, logger) createPFGForm(context, folder, wftool, logger)
def test_image_formats(self): """make sure the scales have the same format as the original image """ from cStringIO import StringIO from PIL.Image import open org_data = StringIO(self.img.image.data) self.assertEqual(open(org_data).format, 'PNG') view = self.img.restrictedTraverse('@@crop-image') view._crop(fieldname='image', scale='thumb', box=(14, 14, 218, 218)) traverse = self.portal.REQUEST.traverseName scales = traverse(self.img, '@@images') cropped = scales.scale('image', 'thumb') croppedData = StringIO(cropped.data._data) self.assertEqual( open(croppedData).format, 'PNG', 'cropped scale does not have same format as the original' ) # create a jpeg image out of the png file # and test if created scale is jpeg too _createObjectByType('Image', self.portal, 'testjpeg') jpg = self.portal.testjpeg jpg.image = NamedBlobImage(data=self._jpegImage()) org_data = StringIO(jpg.image.data) self.assertEqual(open(org_data).format, 'JPEG') view = jpg.restrictedTraverse('@@crop-image') view._crop(fieldname='image', scale='thumb', box=(14, 14, 218, 218)) cropped = scales.scale('image', 'thumb') croppedData = StringIO(cropped.data._data)
def createTopic(container, wftool, logger): """ Located in: /bounty-mission/aggregator Item Type = ["Bounty Program Submission",] state = ['published',] sort_on = "creation" """ topic = getattr(container, TOPIC_ID, None) if topic is None: # Add criteria _createObjectByType('Topic', container, id=TOPIC_ID, title=CONTAINER_TITLE) topic = getattr(container, TOPIC_ID, None) crit = topic.addCriterion('Type','ATPortalTypeCriterion') crit.setValue(["Bounty Program Submission",]) crit = topic.addCriterion('review_state','ATSelectionCriterion') crit.setValue("published") crit = topic.addCriterion('created','ATSortCriterion') topic.setLayout('folder_summary_view') topic.unmarkCreationFlag() if wftool.getInfoFor(topic, 'review_state') != 'published': wftool.doActionFor(topic, 'publish') logger.info("Bounty submissions aggregator added") else: logger.info("Bounty submissions aggregator already exist at %s" % \ topic.absolute_url())
def setUp(self): super(self.__class__, self).setUp() # load file content filedata = get_file_content('example.zip') # create an ATFile w/ the content self.loginAsPortalOwner() # self.portal.invokeFactory("File", 'archive') _createObjectByType("File", self.portal, id='archive') self.archive = archive = self.portal.archive # we should not have IArchiveFile self.assertTrue(IArchiveFile not in providedBy(archive)) archive.setFile(filedata) # trigger modified event since we have a subscriber for that event = ObjectModifiedEvent(archive) notify(event) # now we must have IArchiveFile self.assertTrue(IArchiveFile in providedBy(archive)) # look for a zip reader zipreader = component.queryAdapter(archive, IArchiveReader, name=archive.getContentType()) self.failIf(zipreader is None) self.logout()
def addUser(self, login, password): """ Adds a SimpleMember object at the root of the Plone site. """ logger.info("Hello, userAdder!") portal = getToolByName(self, 'portal_url').getPortalObject() _createObjectByType('gcPerson', portal, login, password=password, userName=login)
def bibliography_faceted_navigation(context): xmlconfig = context.readDataFile('ex_bibliography_facets.xml') if xmlconfig is None or not HAS_EEA: return portal = context.getSite() qitool = getToolByName(portal, "portal_quickinstaller") if qitool.isProductInstallable('eea.facetednavigation'): if not qitool.isProductInstalled('eea.facetednavigation'): qitool.installProduct('eea.facetednavigation') folder = portal.restrictedTraverse(EXHIBIT_TEMPLATES) existing = folder.keys() if 'explore-bibliography' not in existing: _createObjectByType('Folder', folder, id='explore-bibliography', title=_(u'Explore Bibliography')) faceted = folder['explore-bibliography'] alsoProvides(faceted, IHidePloneRightColumn) # We need to constrain types in order to allow an ATCT # folder inside a dexterity folder! faceted.setConstrainTypesMode(constraintypes.ENABLED) faceted.setLocallyAllowedTypes([]) faceted.setImmediatelyAddableTypes([]) # Enable faceted search view faceted.unrestrictedTraverse('@@faceted_subtyper/enable')() # Load default facet config/layout importer = faceted.unrestrictedTraverse('@@faceted_exportimport') importer.import_xml(import_file=xmlconfig, redirect=None) notify(FacetedGlobalSettingsChangedEvent(faceted))
def setupSharedFolder(self): """ Create the shared neutral language folder """ doneSomething = False folderId = SHARED_NAME folder = getattr(self.context, folderId, None) wftool = getToolByName(self.context, 'portal_workflow') if folder is None: # bypass all settings that don't allow creating # content in the Plone root _createObjectByType(self.folder_type, self.context, folderId) #self.context.invokeFactory(self.folder_type, folderId) folder = getattr(self.context, folderId) ILanguage(folder).set_language(LANGUAGE_INDEPENDENT) folder.setTitle("Language Shared") state = wftool.getInfoFor(folder, 'review_state', None) # This assumes a direct 'publish' transition from the initial state available_transitions = [t['id'] for t in wftool.getTransitionsFor(folder)] if state != 'published' and 'publish' in available_transitions: wftool.doActionFor(folder, 'publish') folder.reindexObject() doneSomething = True LOG.info("Added LANGUAGE_INDEPENDENT folder: %s" % (folderId)) if not INavigationRoot.providedBy(folder): alsoProvides(folder, INavigationRoot) doneSomething = True LOG.info("INavigationRoot setup on shared folder ") return doneSomething
def addUser(self, login, password): """ Adds a SimpleMember object at the root of the Plone site. """ portal = getToolByName(self, 'portal_url').getPortalObject() _createObjectByType('SimpleMember', portal, login, password=password, userName=login)
def __iter__(self): for item in self.previous: if not isinstance(item['image'], Image): # no image or not an Image yield item; continue path = item['_path'] container = self.context.unrestrictedTraverse(path, None) if not INITF.providedBy(container): # path does not exist or not a NITF yield item; continue try: _createObjectByType('Image', container, 'image', title='image') except: # could not create image yield item; continue image = container['image'] image.setDescription(item['imageCaption']) image.setImage(item['image']) zope.event.notify(ObjectCreatedEvent(image)) yield item
def testDefaultBudgetCategory(self): p = _createObjectByType('ExtropyProject', self.folder, 'project') self.assertEqual(p.getDefaultBudgetCategory(),'Billable') phase =_createObjectByType('ExtropyPhase', p, 'phase') self.assertEqual(phase.getDefaultBudgetCategory(),'Billable') p.setBudgetCategory('Sales') self.assertEqual(phase.getDefaultBudgetCategory(),'Sales')
def _createHomeFolder(portal, member_id, take_ownership=1): '''Creates a memberarea if it does not already exist.''' pm = portal.portal_membership members = pm.getMembersFolder() if not hasattr(aq_base(members), member_id): # Create home folder _createObjectByType('Folder', members, id=member_id) if not PLONE21: # Create personal folder home = pm.getHomeFolder(member_id) _createObjectByType('Folder', home, id=pm.personal_id) # Uncatalog personal folder personal = pm.getPersonalFolder(member_id) personal.unindexObject() if take_ownership: user = portal.acl_users.getUserById(member_id) if user is None: raise ValueError, 'Member %s does not exist' % member_id if not hasattr(user, 'aq_base'): user = user.__of__(portal.acl_users) # Take ownership of home folder home = pm.getHomeFolder(member_id) home.changeOwnership(user) home.__ac_local_roles__ = None home.manage_setLocalRoles(member_id, ['Owner']) if not PLONE21: # Take ownership of personal folder personal = pm.getPersonalFolder(member_id) personal.changeOwnership(user) personal.__ac_local_roles__ = None personal.manage_setLocalRoles(member_id, ['Owner'])
def folder_create(root, dirname, portal_type): current = root components = dirname.split('/') for c in components[:-1]: if not c: continue if c not in current.objectIds(): _createObjectByType('Folder', current, id=c) # current.invokeFactory('Folder', id=c) current = getattr(current, c) if not components[-1] in current.objectIds(): try: constrainsMode = current.getConstrainTypesMode() except AttributeError: constrainsMode = None if constrainsMode is not None: current.setConstrainTypesMode(0) # current.invokeFactory(PT_REPLACE_MAP.get(portal_type, # portal_type), id=components[-1]) _createObjectByType( PT_REPLACE_MAP.get(portal_type, portal_type), current, id=components[-1] ) if constrainsMode is not None: current.setConstrainTypesMode(constrainsMode) return current[components[-1]]
def repository(self): if 'cart_orders' not in self.context.keys(): _createObjectByType('Folder', self.context, 'cart_orders') orders = self.context._getOb('cart_orders') notify(ObjectCreatedEvent(orders)) notify(ObjectAddedEvent(orders)) return self.context._getOb('cart_orders')
def makeItem(context, cid, ctype, title, description, publish=True): """makeItem utility : Item Constructor @param context : Context's Object ID. @param cid : The id of the new Item. @param ctype : The object type of the new Item. @param title : The title of the new Item. @param description : The description of the object being created. @param publish : Set the new item's state to 'Published'. reindexes the object at the end """ if cid not in context.objectIds(): wftool = getToolByName(context, "portal_workflow") _createObjectByType(ctype,context,cid) obj = context[cid] obj.setTitle(obj.translate( msgid='%s_title'%(cid), domain='eduintelligent.courses', default=title)) obj.setDescription(obj.translate( msgid='%s_description'%(cid), domain='eduintelligent.courses', default=description)) obj.unmarkCreationFlag() #?????? if publish: if wftool.getInfoFor(obj, 'review_state') != 'published': wftool.doActionFor(obj, 'publish') obj.reindexObject() return obj
def testDisplayMenuNotIncludedIfContextDoesNotSupportBrowserDefault(self): # We need to create an object that does not have # IBrowserDefault enabled _createObjectByType('ATListCriterion', self.folder, 'c1') items = self.menu.getMenuItems(self.folder.c1, self.request) self.assertEqual([i for i in items if i['extra']['id'] == 'plone-contentmenu-display'], [])
def __call__(self): portal = self.portal request = self.request context = self.context setup = portal.bika_setup # Allow adding items to this context context.setConstrainTypesMode(0) # Collect the products products = setup.bika_labproducts.objectValues('LabProduct') # Handle for submission and regular request if 'submit' in request: portal_factory = getToolByName(context, 'portal_factory') context = portal_factory.doCreate(context, context.id) context.processForm() # Process the order item data for k, v in request.form.items(): if k.startswith('product_') and int(v) > -1: k = k.replace('product_', '') product = setup.bika_labproducts[k] # Create a item if it doesn't yet exist if k not in context: _createObjectByType("SupplyOrderItem", context, k) # Fetch and edit the item obj = context[k] obj.edit( Product=product, Quantity=int(v), Price=product.getPrice(), VAT=product.getVAT(), ) # Redirect to the list of orders obj_url = context.absolute_url_path() request.response.redirect(obj_url) return else: self.orderDate = context.Schema()['OrderDate'] self.contact = context.Schema()['Contact'] self.subtotal = '%.2f' % context.getSubtotal() self.vat = '%.2f' % context.getVATAmount() self.total = '%.2f' % context.getTotal() # Prepare the products items = context.objectValues('SupplyOrderItem') self.products = [] for product in products: item = [o for o in items if o.getProduct() == product] quantity = item[0].getQuantity() if len(item) > 0 else 0 total = item[0].getTotal() if len(item) > 0 else '0.00' self.products.append({ 'id': product.getId(), 'title': product.Title(), 'description': product.Description(), 'volume': product.getVolume(), 'unit': product.getUnit(), 'price': product.getPrice(), 'vat': '%s%%' % product.getVAT(), 'quantity': quantity, 'total': total, }) # Render the template return self.template()
def setUp(self): """\ Sets up the environment that the workspace doctest needs. """ DocTestCase.setUp(self) from Testing.testbrowser import Browser from Products.PloneTestCase.setup import default_user, default_password from pmr2.app.settings.interfaces import IPMR2GlobalSettings # point the physical root for repo_root to the tmpdir. self.pmr2 = zope.component.getUtility(IPMR2GlobalSettings) self.pmr2.repo_root = self.tmpdir # user workspace _createObjectByType('Folder', self.portal, id='w') self.pmr2.user_workspace_subpath = u'w' self.pmr2.create_user_workspace = True # set up test browser with default user logged in. b = Browser() portal_url = self.portal.absolute_url() b.open(portal_url + '/login') b.getControl(name='__ac_name').value = default_user b.getControl(name='__ac_password').value = default_password b.getControl(name='submit').click() self.testbrowser = b
def setupVocabs(portal, logger): # #ATVocabManager setup # logger.info('Starting ATVocabManager configuration ') atvm = getToolByName(portal, ATVOCABULARYTOOL) wftool = getToolByName(portal,'portal_workflow') for vkey in vocabs.keys(): # create vocabulary if it doesnt exist: vocabname = vkey if atvm.getVocabularyByName(vocabname): atvm._delObject(vocabname) logger.debug("adding vocabulary %s" % vocabname) _createObjectByType('SimpleVocabulary', atvm, vocabname) vocab = atvm[vocabname] #delete the 'default' item if hasattr(vocab, 'default'): vocab.manage_delObjects(['default']) for (ikey, value) in vocabs [vkey]: if not hasattr(vocab, ikey): _createObjectByType('SimpleVocabularyTerm', vocab, ikey) logger.debug("adding vocabulary item %s %s" % (ikey,value)) vocab[ikey].setTitle(value) #reindex vocab.reindexObject()
def test_image_formats(self): """make sure the scales have the same format as the original image """ from cStringIO import StringIO from PIL.Image import open org_data = StringIO(self.img.getImage().data) self.assertEqual(open(org_data).format, "PNG") view = self.img.restrictedTraverse("@@crop-image") view._crop(fieldname="image", scale="thumb", box=(14, 14, 218, 218)) traverse = self.portal.REQUEST.traverseName cropped = traverse(self.img, "image_thumb") croppedData = StringIO(cropped.data) self.assertEqual(open(croppedData).format, "PNG", "cropped scale does not have same format as the original") # create a jpeg image out of the png file: img = open(file(join(dirname(tests.__file__), "plone-logo.png"))) out = StringIO() img.save(out, format="JPEG", quality=75) out.seek(0) # and test if created scale is jpeg too _createObjectByType("Image", self.portal, "testjpeg") jpg = self.portal.testjpeg jpg.setImage(out.getvalue()) org_data = StringIO(jpg.getImage().data) self.assertEqual(open(org_data).format, "JPEG") view = jpg.restrictedTraverse("@@crop-image") view._crop(fieldname="image", scale="thumb", box=(14, 14, 218, 218)) cropped = traverse(self.img, "image_thumb") croppedData = StringIO(cropped.data)
def test_step_1_1_to_1_2(self): # Prepare testing data catalog = self.portal.portal_catalog # Create container folder, update its canonical path folder = _createObjectByType('Folder', self.portal, id='test_folder') fldr_cpath = "/my_test_home_folder" fldr_clink = self.portal.absolute_url() + fldr_cpath ICanonicalPath(folder).canonical_path = fldr_cpath # Create inner document, update its canonical_path doc = _createObjectByType('Document', folder, id='test_doc') doc_cpath = "/test_folder/my_test_doc" doc_clink = self.portal.absolute_url() + doc_cpath ICanonicalPath(doc).canonical_path = doc_cpath # Add canonical_path column in catalog if not "canonical_path" in catalog._catalog.names: catalog.addColumn("canonical_path") # Upgrade to 1.2 version step = self.getUpgradeStep(2) if step is not None: step.doStep(self.setup) # canonical_link column replace canonical_path # one in the portal_catalog self.assertEqual("canonical_link" in catalog._catalog.names, True) self.assertEqual("canonical_path" in catalog._catalog.names, False) # canonical_link property refactored from canonical_path one # for inner doc self.assertNotEqual(ICanonicalPath(doc).canonical_path, doc_cpath) self.assertEqual(ICanonicalLink(doc).canonical_link, doc_clink) # canonical_link property refactored from canonical_path one # for home folder self.assertNotEqual(ICanonicalPath(folder).canonical_path, fldr_cpath) self.assertEqual(ICanonicalLink(folder).canonical_link, fldr_clink)
def afterSetUp(self): self.repository = _createObjectByType('ImageRepository', self.portal, 'repository') self.repository.at_post_create_script() self.repositorypath = '/' + self.repository.absolute_url(1) for image in images: _createObjectByType('Image', self.repository, image['id'], image=loadImage(image['file']), subject=image['keywords']) self.portal.manage_addProduct['PageTemplates'].manage_addPageTemplate('main_template', 'Main', templatetext)
def test_getScaytLanguage(self): """ Test the ckeditor_view._getScaytLanguage method. This method will try to find out the SCAYT language to use in case SCAYT is enabled on CKeditor widget startup. It tries to map the current content used language with languages codes supported by SCAYT. """ portal = self.layer['portal'] from Products.CMFPlone import utils as ploneutils ploneutils._createObjectByType('Document', portal, 'front-page') frontPage = getattr(portal, 'front-page') view = getMultiAdapter( (frontPage, frontPage.REQUEST), name='ckeditor_view' ) # by default, frontPage language is 'en' self.assertEquals(frontPage.Language(), 'en') self.assertEquals(view._getScaytLanguage(), 'en_US') # define another language for frontPage frontPage.setLanguage('fr') # used language will now be fr_FR self.assertEquals(view._getScaytLanguage(), 'fr_FR') # define a language with sub language frontPage.setLanguage('fr-ca') # as fr-ca is supported, it will be used self.assertEquals(view._getScaytLanguage(), 'fr_CA') # if NOT supported, the language can not be determined, it returns None frontPage.setLanguage('ru') self.failIf(view._getScaytLanguage()) frontPage.setLanguage('ru-ru') self.failIf(view._getScaytLanguage())
def setUp(self): portal = self.layer['portal'] setRoles(portal, TEST_USER_ID, ['Manager']) folder = portal[portal.invokeFactory('Folder', 'folder')] self.board = _createObjectByType('Ploneboard', folder, 'board') self.forum = _createObjectByType('PloneboardForum', self.board, 'forum') zope.component.provideHandler(dummyEventHandler)
def setUp(cls): app = ztc.app() portal = app.plone def create(container, nr): obj = _createObjectByType('Document', container, 'doc.%d' % nr) obj.setTitle('Title for %d' % nr) obj.setDescription('A long description for %d' % nr) obj.setText('This is the <b>HTML</b> text for item with id %d' % nr) obj.reindexObject(idxs=('Title', 'Description', 'SearchableText')) regular = createNonBTreeFolder('Folder', portal, 'regular') unordered = _createObjectByType('Folder', portal, 'unordered') unordered.setOrdering(u'unordered') ordered = _createObjectByType('Folder', portal, 'ordered') @timecall def testCreateContentRegular(): for x in range(SIZE): create(regular, x) @timecall def testCreateContentUnordered(): for x in range(SIZE): create(unordered, x) @timecall def testCreateContentOrdered(): for x in range(SIZE): create(ordered, x) testCreateContentRegular() testCreateContentUnordered() testCreateContentOrdered() commit() ztc.close(app)
def upgrade(tool): # Hack prevent out-of-date upgrading # Related: PR #1484 # https://github.com/bikalabs/Bika-LIMS/pull/1484 from bika.lims.upgrade import skip_pre315 if skip_pre315(aq_parent(aq_inner(tool))): return True portal = aq_parent(aq_inner(tool)) at = getToolByName(portal, 'archetype_tool') at.setCatalogsByType('SubGroup', ['bika_setup_catalog', ]) setup = portal.portal_setup setup.runImportStepFromProfile('profile-bika.lims:default', 'controlpanel') try: _createObjectByType("SubGroups", portal.bika_setup, "bika_subgroups", title="Sub-groups") obj = portal.bika_setup.bika_subgroups obj.unmarkCreationFlag() obj.reindexObject() except BadRequest: # folder already exists pass return True
def create(portal,type=None,id=None,title=None,description=None): _createObjectByType(type, portal, id=id, title=title, description=description) obj = portal.get(id, None) obj.reindexObject() return obj
def _createObjects(parent, new_object): LOG.info("Creating %s in %s" % (new_object, parent)) existing = parent.objectIds() if new_object['id'] in existing: LOG.info("%s exists, skipping" % new_object['id']) else: _createObjectByType( new_object['type'], parent, id=new_object['id'], title=new_object['title'] ) LOG.info("Now to modify the new_object...") obj = parent.get(new_object['id'], None) if obj is None: msg = "can't get new_object %s to modify it!" % new_object['id'] LOG.info(msg) else: if obj.Type() != new_object['type']: LOG.info("types don't match!") else: if 'layout' in new_object: obj.setLayout(new_object['layout']) if 'exclude_from_nav' in new_object: obj.setExcludeFromNav(new_object['exclude_from_nav']) obj.reindexObject() aspect = ISelectableConstrainTypes(obj) addable = aspect.getImmediatelyAddableTypes() if "collective.history.useraction" not in addable: aspect.setConstrainTypesMode(1) # select manually aspect.setImmediatelyAddableTypes(["collective.history.useraction"])
def setupContentItem(location, itemType, itemID, itemTitle, itemDesc): """ Function attempts to create a piece of content in the desired location. """ if itemID not in location.objectIds(): _createObjectByType(itemType, location, id=itemID, title=itemTitle, description=itemDesc) return getattr(aq_base(location), itemID)
def afterSetUp(self): self.doc = _createObjectByType('Document', self.portal, id='doc') self.image = _createObjectByType('Image', self.portal, id='image') self.field = self.doc.getField('relatedItems') self.field.isMetadata = False self.setRoles('Manager') self.request = FakeRequest()
def Import(self): folder = self.context.bika_setup.bika_drugs for row in self.get_rows(3): obj = _createObjectByType('Drug', folder, tmpID()) if row['title']: obj.edit( title=row['title'], description=row.get('description', ''), Category=row.get('Category', ''), Indications=row.get('Indications', ''), Posology=row.get('Posology', ''), SideEffects=row.get('SideEffects', ''), Preservation=row.get('Preservation', ''), ) obj.unmarkCreationFlag() renameAfterCreation(obj)
def Import(self): folder = self.context.lab_hosts rows = self.get_rows(3) for row in rows: if self.isExistingTitle('LabHost', row.get('title')): continue title = row.get('title') description = row.get('description', '') obj = _createObjectByType('LabHost', folder, tmpID()) obj.edit( title=title, description=description, ) obj.unmarkCreationFlag() renameAfterCreation(obj)
def Import(self): folder = self.context.bika_setup.bika_kittemplates rows = self.get_rows(3) catalog = getToolByName(self.context, 'bika_setup_catalog') for row in rows: template_name = row.get('templateName') kit_component = Kit_Components(self, self.workbook, self.dataset_project, self.dataset_name, template_name, catalog) product_list = kit_component.get_product_list() obj = _createObjectByType('KitTemplate', folder, tmpID()) obj.edit(title=template_name, ProductList=product_list) obj.unmarkCreationFlag() renameAfterCreation(obj)
def generate_requisition_pdf(ar_or_sample): if not ar_or_sample: logger.warn("No Analysis Request or Sample provided") return if ISample.providedBy(ar_or_sample): for ar in ar_or_sample.getAnalysisRequests(): generate_requisition_pdf(ar) return elif not IAnalysisRequest.providedBy(ar_or_sample): logger.warn("Type not supported: {}".format(repr(ar_or_sample))) return html = RequisitionFormPdf(ar_or_sample, ar_or_sample.REQUEST).template() html = safe_unicode(html).encode('utf-8') filename = '%s-requisition' % ar_or_sample.id pdf_fn = tempfile.mktemp(suffix=".pdf") pdf = createPdf(htmlreport=html, outfile=pdf_fn) if not pdf: logger.warn( "Unable to generate the PDF of requisition form for {}".format( ar_or_sample.id)) return # Attach the pdf to the Analysis Request attid = ar_or_sample.aq_parent.generateUniqueId('Attachment') att = _createObjectByType("Attachment", ar_or_sample.aq_parent, attid) att.setAttachmentFile(open(pdf_fn)) att.setReportOption('i') # Ignore in report # Try to assign the Requisition Attachment Type query = dict(portal_type='AttachmentType', title='Requisition') brains = api.search(query, 'bika_setup_catalog') if brains: att_type = api.get_object(brains[0]) att.setAttachmentType(att_type) # Awkward workaround to rename the file attf = att.getAttachmentFile() attf.filename = '%s.pdf' % filename att.setAttachmentFile(attf) att.unmarkCreationFlag() renameAfterCreation(att) atts = ar_or_sample.getAttachment() + [att] if \ ar_or_sample.getAttachment() else [att] atts = [a.UID() for a in atts] ar_or_sample.setAttachment(atts) os.remove(pdf_fn)
def migrate_instrument_locations(portal): bsc = portal.bika_setup_catalog bika_instrumentlocations = portal.bika_setup.get("bika_instrumentlocations") if bika_instrumentlocations is None: logger.error("bika_instrumentlocations not found in bika_setup!") return # This should not happen # move bika_instrumentlocations below bika_instrumenttypes panel_ids = portal.bika_setup.objectIds() target_idx = panel_ids.index("bika_instrumenttypes") current_idx = panel_ids.index("bika_instrumentlocations") delta = current_idx - target_idx if delta > 1: portal.bika_setup.moveObjectsUp("bika_instrumentlocations", delta=delta-1) instrument_brains = bsc(portal_type="Instrument") for instrument_brain in instrument_brains: instrument = instrument_brain.getObject() # get the string value of the `location` field location = instrument.getLocation() if not location: continue # Skip if no location was set # make a dictionary with the Titles as keys and the objects as values instrument_locations = bika_instrumentlocations.objectValues() instrument_location_titles = map(lambda o: o.Title(), instrument_locations) locations = dict(zip(instrument_location_titles, instrument_locations)) instrument_location = None if location in locations: logger.info("Instrument Location {} exists in bika_instrumentlocations".format(location)) instrument_location = locations[location] else: # Create a new location and link it to the instruments InstrumentLocation field instrument_location = _createObjectByType("InstrumentLocation", bika_instrumentlocations, tmpID()) instrument_location.setTitle(location) instrument_location._renameAfterCreation() instrument_location.reindexObject() logger.info("Created Instrument Location {} in bika_instrumentlocations".format(location)) instrument.setLocation(None) # flush the old instrument location instrument.setInstrumentLocation(instrument_location) instrument.reindexObject() logger.info("Linked Instrument Location {} to Instrument {}".format(location, instrument.id))
def create(container, portal_type, *args, **kwargs): """Creates an object in Bika LIMS This code uses most of the parts from the TypesTool see: `Products.CMFCore.TypesTool._constructInstance` :param container: container :type container: ATContentType/DexterityContentType/CatalogBrain :param portal_type: The portal type to create, e.g. "Client" :type portal_type: string :param title: The title for the new content object :type title: string :returns: The new created object """ from bika.lims.utils import tmpID if kwargs.get("title") is None: kwargs["title"] = "New {}".format(portal_type) # generate a temporary ID tmp_id = tmpID() # get the fti types_tool = get_tool("portal_types") fti = types_tool.getTypeInfo(portal_type) if fti.product: obj = _createObjectByType(portal_type, container, tmp_id) else: # newstyle factory factory = getUtility(IFactory, fti.factory) obj = factory(tmp_id, *args, **kwargs) if hasattr(obj, '_setPortalTypeName'): obj._setPortalTypeName(fti.getId()) notify(ObjectCreatedEvent(obj)) # notifies ObjectWillBeAddedEvent, ObjectAddedEvent and ContainerModifiedEvent container._setObject(tmp_id, obj) # we get the object here with the current object id, as it might be renamed # already by an event handler obj = container._getOb(obj.getId()) obj.edit(**kwargs) # handle AT Content if is_at_content(obj): obj.processForm() # explicit notification modified(obj) return obj
def addReply(self, title, text, creator=None, files=None ): """Add a reply to this comment.""" conv = self.getConversation() id = conv.generateId(prefix='') if not title: title = conv.Title() if not title.lower().startswith('re:'): title = 'Re: ' + title m = _createObjectByType(self.portal_type, conv, id) # XXX: There is some permission problem with AT write_permission # and using **kwargs in the _createObjectByType statement. m.setTitle(title) m.setText(text) m.setInReplyTo(self.UID()) if creator is not None: m.setCreators([creator]) # Create files in message if files: for file in files: # Get raw filedata, not persistent object with reference to tempstorage # file.data might in fact be OFS.Image.Pdata - str will piece it all together attachment = File(file.getId(), file.title_or_id(), str(file.data), file.getContentType()) m.addAttachment(attachment) # If this comment is being added by anonymous, make sure that the true # owner in zope is the owner of the forum, not the parent comment or # conversation. Otherwise, that owner may be able to view or delete # the comment. membership = getToolByName(self, 'portal_membership') if membership.isAnonymousUser(): forum = self.getConversation().getForum() utils.changeOwnershipOf(m, forum.owner_info()['id'], False) event.notify(ObjectInitializedEvent(m)) m.reindexObject() conv.reindexObject() # Sets modified return m
def __call__(self): request = self.request context = self.context if 'submitted' in request: from Products.CMFPlone.utils import _createObjectByType from bika.lims.utils import tmpID pc = getToolByName(context, "portal_catalog") parent = context.aq_parent if IProject.providedBy(parent): folder = parent else: folder = pc(portal_type="Project", UID=request.form['Project_uid'])[0].getObject() if not folder.hasObject(context.getId()): sample = _createObjectByType('Sample', folder, tmpID()) else: sample = context if IProject.providedBy(parent): sample.getField('Project').set(sample, parent) else: sample.getField('Project').set(sample, request.form['Project_uid']) # sample.getField('AllowSharing').set(sample, request.form['AllowSharing']) sample.getField('Kit').set(sample, request.form['Kit_uid']) sample.getField('StorageLocation').set( sample, request.form['StorageLocation_uid']) sample.getField('SubjectID').set(sample, request.form['SubjectID']) sample.getField('Barcode').set(sample, request.form['Barcode']) sample.getField('Volume').set(sample, request.form['Volume']) sample.getField('Unit').set(sample, request.form['Unit']) sample.getField('LinkedSample').set( sample, request.form['LinkedSample_uid']) sample.edit(SampleType=request.form['SampleType_uid']) sample_batch = sample.getField('Batch').get(sample) sample.processForm() sample.getField('Batch').set(sample, sample_batch) obj_url = sample.absolute_url_path() request.response.redirect(obj_url) return return self.template()
def addReferenceAnalysis(self, service_uid, reference_type): """ Creates a new Reference Analysis object based on this Sample Reference, with the type passed in and associates the newly created object to the Analysis Service passed in. :param service_uid: The UID of the Analysis Service to be associated to the newly created Reference Analysis :type service_uid: A string :param reference_type: type of ReferenceAnalysis, where 'b' is is Blank and 'c' is Control :type reference_type: A String :returns: the UID of the newly created Reference Analysis :rtype: string """ rc = getToolByName(self, REFERENCE_CATALOG) service = rc.lookupObject(service_uid) calc = service.getCalculation() interim_fields = calc.getInterimFields() if calc else [] analysis = _createObjectByType("ReferenceAnalysis", self, id=tmpID()) # Copy all the values from the schema # TODO Add Service as a param in ReferenceAnalysis constructor and do # this logic there instead of here discard = ['id', ] keys = service.Schema().keys() for key in keys: if key in discard: continue if key not in analysis.Schema().keys(): continue val = service.getField(key).get(service) # Campbell's mental note:never ever use '.set()' directly to a # field. If you can't use the setter, then use the mutator in order # to give the value. We have realized that in some cases using # 'set' when the value is a string, it saves the value # as unicode instead of plain string. # analysis.getField(key).set(analysis, val) mutator_name = analysis.getField(key).mutator mutator = getattr(analysis, mutator_name) mutator(val) analysis.setAnalysisService(service_uid) analysis.setReferenceType(reference_type) analysis.setInterimFields(interim_fields) analysis.unmarkCreationFlag() renameAfterCreation(analysis) return analysis.UID()
def Import(self): folder = self.context.disease_ontologies rows = self.get_rows(3) for row in rows: title = row.get('title') description = row.get('description', '') version = row.get('Version') code = row.get('Code') free_text = row.get('FreeText') obj = _createObjectByType('DiseaseOntology', folder, tmpID()) obj.edit(title=title, description=description, Version=version, Code=code, FreeText=free_text) obj.unmarkCreationFlag() renameAfterCreation(obj)
def __call__(self): # Validation form = self.request.form analyst = self.request.get('analyst', '') template = self.request.get('template', '') instrument = self.request.get('instrument', '') if not analyst: message = _("Analyst must be specified.") self.context.plone_utils.addPortalMessage(message, 'info') self.request.RESPONSE.redirect(self.context.absolute_url()) return rc = getToolByName(self.context, REFERENCE_CATALOG) wf = getToolByName(self.context, "portal_workflow") pm = getToolByName(self.context, "portal_membership") ws = _createObjectByType("Worksheet", self.context, tmpID()) ws.processForm() # Set analyst and instrument ws.setAnalyst(analyst) if instrument: ws.setInstrument(instrument) # overwrite saved context UID for event subscribers self.request['context_uid'] = ws.UID() # if no template was specified, redirect to blank worksheet if not template: ws.processForm() self.request.RESPONSE.redirect(ws.absolute_url() + "/add_analyses") return wst = rc.lookupObject(template) ws.setWorksheetTemplate(wst) ws.applyWorksheetTemplate(wst) if ws.getLayout(): self.request.RESPONSE.redirect(ws.absolute_url() + "/manage_results") else: msg = _("No analyses were added") self.context.plone_utils.addPortalMessage(msg) self.request.RESPONSE.redirect(ws.absolute_url() + "/add_analyses")
def Import(self): folder = self.context.bika_setup.bika_immunizations for row in self.get_rows(3): obj = _createObjectByType('Immunization', folder, tmpID()) if row['title']: obj.edit(title=row['title'], description=row.get('description', ''), Form=row.get('Form', 'active'), RelevantFacts=row.get('RelevantFacts', ''), GeographicalDistribution=row.get('GeographicalDistribution', ''), Transmission=row.get('Transmission', ''), Symptoms=row.get('Symptoms', ''), Risk=row.get('Risk', ''), Treatment=row.get('Treatment', ''), Prevention=row.get('Prevention', ''),) obj.unmarkCreationFlag() renameAfterCreation(obj)
def create_biospecimen(self, row): barcode = str(row.get('Barcode')) project = self.get_project(row.get('Project', '')) sample_type = self.get_sample_type(row.get('SampleType', '')) volume = self.get_volume(row.get('Volume', '')) title = row.get('title', barcode) self.confirm_unique_title(barcode) storage_location = self.get_storage_location(row.get('StorageLocation', '')) sampling_date = row.get('SamplingDate', '') if storage_location: storage_wf_state = self._wf.getInfoFor(storage_location, 'review_state') if storage_wf_state == 'occupied': raise ExcelSheetError('Import Error Sample %s: Storage %s already occupied.' % (title, storage_location.Title())) date_created = row.get('DateCreated', datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M')) if not date_created: date_created = datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M') member = self.get_member() obj = _createObjectByType('Sample', project, tmpID()) obj.edit( title=title, description=row.get('description'), Project=project, SampleType=sample_type, StorageLocation=storage_location, SubjectID=row.get('SubjectID'), Barcode=barcode, Volume=volume, Unit=row.get('Unit'), BabyNumber=row.get('BabyNo', ''), DateCreated=date_created, SamplingDate=sampling_date, # FrozenTime=row.get('FrozenTime'), ChangeUserName=member, ChangeDateTime=date_created, ) obj.reindexObject() obj.unmarkCreationFlag() renameAfterCreation(obj) from baobab.lims.subscribers.sample import ObjectInitializedEventHandler ObjectInitializedEventHandler(obj, None)
def _getContainers(self): """ gets container based on storage path """ containers = [] for storagePath in self.storagePaths: try: containers.append(self.restrictedTraverse(storagePath)) except AttributeError: container = self.restrictedTraverse('/'.join( self.storagePath.split('/')[:-1])) container = utils._createObjectByType( self.containerType, container, id=self.storagePath.split('/')[-1]) containers.append(container) return containers
def testEnumerateGroupsWithSimilarIds(self): """ ensure that enumerating groups while exact_match==True returns only exact matches for a given id """ # add a new group with a similar id self.newgroup = _createObjectByType( 'TestGroup', self.portal, 'testgroup-2') self.newgroup.setTitle('New Test group') self.newgroup.setDescription('A test group') self.newgroup.reindexObject() enumgrps = self.portal.pmm.enumerateGroups # only an exact match should be found when exact_match==True self.failUnlessEqual(len(enumgrps(id=self.group.getGroupName(), exact_match=True)), 1) self.failUnlessEqual(len(enumgrps(id=self.group.getGroupName(), exact_match=False)), 2)
def afterSetUp(self): self.setRoles(['Manager']) self.basic_auth = '%s:%s' % (default_user, default_password) # make sure the test request gets marked with the default theme layer notify(BeforeTraverseEvent(self.portal, self.app.REQUEST)) _createObjectByType('Folder', self.portal, 'atctfolder') _createObjectByType('Document', self.portal, 'atctdocument') _createObjectByType('File', self.portal, 'atctfile') self.putils = getToolByName(self.portal, "plone_utils")
def create_samplepartition(context, data, analyses=None): partition = _createObjectByType('SamplePartition', context, data['part_id']) partition.unmarkCreationFlag() # Determine if the sampling workflow is enabled workflow_enabled = context.bika_setup.getSamplingWorkflowEnabled() # Sort containers and select smallest container = data.get('container_uid', None) if container: containers = [] if type(container[0]) is str: # UIDs containers = context.bika_setup_catalog(UID=container) containers = [_p.getObject() for _p in containers] elif hasattr(container[0], 'getObject'): # Brains containers = [_p.getObject() for _p in container] elif hasattr(container[0], 'portal_type'): containers = [c for c in container] if containers: try: containers.sort(lambda a, b: compare_containers(a, b)) except: pass container = containers[0] # Set the container and preservation preservation = set_container_preservation(context, container, data) # Add analyses partition_services = data['services'] analyses = [a for a in analyses if a.getServiceUID() in partition_services] if analyses: partition.edit(Analyses=analyses) # Set some generated values partition.edit( Container=container, Preservation=preservation, ) # Attach partition to analyses if analyses: for analysis in analyses: analysis.setSamplePartition(partition) # Perform the appropriate workflow action workflow_action = 'sampling_workflow' if workflow_enabled \ else 'no_sampling_workflow' context.portal_workflow.doActionFor(partition, workflow_action) # Return the created partition return partition
def workflow_action_save_partitions_button(self): form = self.request.form # Sample Partitions or AR Manage Analyses: save Partition Table sample = self.context.portal_type == 'Sample' and self.context or\ self.context.getSample() part_prefix = sample.getId() + "-P" nr_existing = len(sample.objectIds()) nr_parts = len(form['PartTitle'][0]) # add missing parts if nr_parts > nr_existing: for i in range(nr_parts - nr_existing): part = _createObjectByType("SamplePartition", sample, tmpID()) part.setDateReceived = DateTime() part.processForm() # remove excess parts if nr_existing > nr_parts: for i in range(nr_existing - nr_parts): part = sample['%s%s' % (part_prefix, nr_existing - i)] for a in part.getBackReferences("AnalysisSamplePartition"): a.setSamplePartition(None) sample.manage_delObjects([ '%s%s' % (part_prefix, nr_existing - i), ]) # modify part container/preservation for part_uid, part_id in form['PartTitle'][0].items(): part = sample["%s%s" % (part_prefix, part_id.split(part_prefix)[1])] part.edit( Container=form['getContainer'][0][part_uid], Preservation=form['getPreservation'][0][part_uid], ) part.reindexObject() objects = WorkflowAction._get_selected_items(self) if not objects: message = _("No items have been selected") self.context.plone_utils.addPortalMessage(message, 'info') if self.context.portal_type == 'Sample': # in samples his table is on 'Partitions' tab self.destination_url = self.context.absolute_url() +\ "/partitions" else: # in ar context this table is on 'ManageAnalyses' tab self.destination_url = self.context.absolute_url() +\ "/analyses" self.request.response.redirect(self.destination_url)
def test_view_template_id_nonbrowserdefault_nonempty(self): # The view template id is taken from the FTI for non-browserdefault # (non ATContentTypes) content. In this case the default view action # includes an actual template name # Set the expression to include a view name. fti = self.portal.portal_types.TempFolder view_action = fti.getActionObject('object/view') view_expression = view_action.getActionExpression() view_action.setActionExpression('foobar') tf = _createObjectByType('TempFolder', self.folder, 'tf') tf.manage_addLocalRoles(TEST_USER_ID, ('Manager', )) tfview = tf.restrictedTraverse('@@plone_context_state') self.assertEqual(tfview.view_template_id(), 'foobar') # Reset the FTI action expression view_action.setActionExpression(view_expression)
def Import(self): folder = self.context.bika_setup.bika_vaccinationcenters for row in self.get_rows(3): obj = _createObjectByType("VaccinationCenter", folder, tmpID()) if row['Name']: obj.edit( Name=row.get('Name', ''), TaxNumber=row.get('TaxNumber', ''), AccountType=row.get('AccountType', {}), AccountName=row.get('AccountName', {}), AccountNumber=row.get('AccountNumber', ''), BankName=row.get('BankName', ''), BankBranch=row.get('BankBranch', ''), ) self.fill_contactfields(row, obj) self.fill_addressfields(row, obj) obj.unmarkCreationFlag() renameAfterCreation(obj)
def setUp(self): super(TestTemplatesListingView, self).setUp() # by pass allowed types restriction sub_folder = _createObjectByType("Folder", self.portal.podtemplates, 'sub_folder', title='Subfolder') self.sft = api.content.create(type='ConfigurablePODTemplate', id='sub_folder_template', container=sub_folder, title='Sub folder template') self.ot = api.content.create(type='ConfigurablePODTemplate', id='other_template', container=self.portal, title='Other template') self.view = self.portal.podtemplates.restrictedTraverse( 'dg-templates-listing') self.view.update()
def Import(self): folder = self.context.bika_setup.bika_treatments for row in self.get_rows(3): obj = _createObjectByType('Treatment', folder, tmpID()) if row['title']: obj.edit( title=row['title'], description=row.get('description', ''), Type=row.get('Type', 'active'), Procedure=row.get('Procedure', ''), Care=row.get('Care', ''), SubjectiveClinicalFindings=row.get( 'SubjectiveClinicalFindings', ''), ObjectiveClinicalFindings=row.get( 'ObjectiveClinicalFindings', ''), ) obj.unmarkCreationFlag() renameAfterCreation(obj)
def resolve_identifier_type(identifier_id): """Search for an identifier type with an ID that matches with the id passed in. If no identifier type is found, creates a new one """ setup = api.get_setup() folder = setup.bika_identifiertypes id_types = folder.objectValues() for id_type in id_types: if api.get_title(id_type) == identifier_id: return id_type # Create a new identifier type logger.info("Creating new Identifier Type: {}".format(identifier_id)) obj = _createObjectByType('IdentifierType', folder, tmpID()) obj.edit(title=identifier_id, description=identifier_id) obj.unmarkCreationFlag() renameAfterCreation(obj) return obj
def create_printer(folder, name, values): query = dict(portal_type="BarcodePrinter", Title=name) brains = api.search(query, "bika_setup_catalog") if brains: printer = api.get_object(brains[0]) printer.FileName = values["FileName"] printer.PrinterPath = values["PrinterPath"] printer.Template = values["Template"] return printer # Create a new Barcode Printer obj = _createObjectByType("BarcodePrinter", folder, tmpID()) obj.edit(title=name, FileName=values["FileName"], PrinterPath=values["PrinterPath"], Template=values["Template"]) obj.unmarkCreationFlag() renameAfterCreation(obj)
def Import(self): folder = self.context.organisms rows = self.get_rows(3) for row in rows: if self.isExistingTitle('Organism', row.get('title')): continue title = row.get('title') genus = row.get('genus', '') species = row.get('species', '') obj = _createObjectByType('Organism', folder, tmpID()) obj.edit( title=title, Genus=genus, Species=species, ) obj.unmarkCreationFlag() renameAfterCreation(obj)
def Import(self): pc = getToolByName(self.context, 'portal_catalog') rows = self.get_rows(3) for row in rows: # get the project project_list = pc(portal_type="Project", Title=row.get('Project')) if project_list: project = project_list[0].getObject() else: continue # get the kit template if it exists bsc = getToolByName(self.context, 'bika_setup_catalog') kit_template_list = bsc(portal_type="KitTemplate", title=row.get('KitTemplate')) kit_template = kit_template_list and kit_template_list[ 0].getObject() or None stock_items = [] try: if kit_template: stock_items = self.assign_stock_items( kit_template, row, bsc, pc) except ValueError as e: continue obj = _createObjectByType('Kit', project, tmpID()) obj.edit( title=row.get('title'), description=row.get('description'), Project=project, KitTemplate=kit_template, FormsThere=row.get('FormsThere'), DateCreated=row.get('DateCreated', ''), ) if kit_template: obj.setStockItems(stock_items) update_quantity_products(obj, bsc) obj.unmarkCreationFlag() renameAfterCreation(obj)
def test_searcheableText(self): """ test circular reference in linkinnerproxy """ self.loginAsPortalOwner() ## article1 reference article2 article1 = self.article article2 = self.addPloneArticle(self.portal, 'article2') _createObjectByType('InnerContentContainer', article1, 'links') _createObjectByType('LinkInnerContentProxy', article1.links, 'link') article1.links.link.update(title='Reference to article 2', description='description2', referencedContent=article2) ## article2 reference artilce1 _createObjectByType('InnerContentContainer', article2, 'links') _createObjectByType('LinkInnerContentProxy', article2.links, 'link') article2.links.link.update(title='Reference to article 1', description='description1', referencedContent=article1) self.failUnless('Reference to article 2' in article1.SearchableText()) self.failUnless('Reference to article 1' in article2.SearchableText())
def create(title=None, description=None, doc_data=None, doc_name=None, step=None): folder = utils.get_folder_unrestricted('resources/documents') id = utils.create_id('staticdocument') item = _createObjectByType('staticdocument', folder, id) item.title = title item.description = description item.file = namedfile.NamedBlobFile( utils.base64decode(doc_data), filename=doc_name.decode('utf-8', 'ignore') ) item.wcc_user = False intids = component.getUtility(IIntIds) step_id = intids.getId(step) item.doc_in_step = [RelationValue(step_id)] notify(ObjectModifiedEvent(item)) return item
def handle_AS_wo_category(portal): """ Apparently, some of Analysis Services remained without category after migration. Creating a new Category ('unknown') and assigning those AS'es to it. """ uc = getToolByName(portal, 'bika_setup_catalog') services = uc(portal_type='AnalysisService', getCategoryUID=None) if not services: logger.info("SKIPPING. There is no Analysis Service without category.") return # First , create a new 'Uknown' Category, if doesn't exist uc = getToolByName(portal, 'uid_catalog') acats = uc(portal_type='AnalysisCategory') for acat in acats: if acat.Title == 'Unknown': logger.info("Category 'Uknown' already exists...") category = acat.getObject() break else: category = _createObjectByType( "AnalysisCategory", portal.bika_setup.bika_analysiscategories, tmpID()) category.setTitle("Unknown") category._renameAfterCreation() category.reindexObject() logger.info("Category 'Unknown' was created...") counter = 0 total = len(services) for s in services: obj = s.getObject() obj.setCategory(category) obj.reindexObject() counter += 1 logger.info( "Assigning Analysis Services to 'unknown' Category: %d of %d" % (counter, total)) logger.info( "Done! %d AnalysisServices were assigned to the Category 'unknown'." % counter)
def test_instrument_calibration(self): # Getting all instruments instrument_names = self.portal.bika_setup.bika_instruments.keys() # Setting calibration dates for instrument_name in instrument_names: # Getting each instrument instrument = self.portal.bika_setup.bika_instruments[ instrument_name] today = date.today() tomorrow = today + timedelta(1) # Getting last valid calibration lastcal = instrument.getLatestValidCalibration() if not lastcal: # Creating a new calibration cal_obj = _createObjectByType("InstrumentCalibration", instrument, tmpID()) cal_obj.edit(title='test', DownFrom=today.strftime("%Y/%m/%d"), DownTo=tomorrow.strftime("%Y/%m/%d"), Instrument=instrument) cal_obj.unmarkCreationFlag() renameAfterCreation(cal_obj) else: # Updating last calibration lastcal.setDownFrom(today) lastcal.setDownTo(tomorrow) # Testing calibration state for instrument_name in instrument_names: instrument = self.portal.bika_setup.bika_instruments[ instrument_name] self.assertTrue(instrument.isCalibrationInProgress()) for instrument_name in instrument_names: instrument = self.portal.bika_setup.bika_instruments[ instrument_name] anotherday = '2014/11/27' lastcal = instrument.getLatestValidCalibration() lastcal.setDownTo(anotherday) lastcal.setDownFrom(anotherday) for instrument_name in instrument_names: instrument = self.portal.bika_setup.bika_instruments[ instrument_name] self.assertFalse(instrument.isCalibrationInProgress())