def add_new_product_to_cart(self, uid, quantity): pid = '1' if self.products is not None: ids = [product.id for product in self.products] for r in range(1, len(ids) + 2): pid = str(r) if pid not in ids: pid = pid break self.context.invokeFactory( 'CartProduct', pid, ) cproduct = self.context[pid] cproduct.uid = uid max_quantity = ICartProduct(cproduct).max_quantity if quantity > max_quantity: quantity = max_quantity cproduct.quantity = quantity product = ICartProduct(cproduct).product cproduct.price = product.price cproduct.title = product.title cproduct.subtotal = cproduct.price * cproduct.quantity cproduct.reindexObject() if not product.unlimited_stock: new_stock = product.stock - quantity product.stock = new_stock notify(ObjectInitializedEvent(cproduct))
def create_seminar(self, parent, seminar_id, title, desc, conclusions, past): if not hasattr(parent, seminar_id): subject = random.sample(['cat1', 'cat2', 'cat3'], 1)[0] if past: end_date = DateTime() - random.randint(1, 10) start_date = end_date - random.randint(1, 4) else: start_date = DateTime() + random.randint(0, 10) end_date = start_date + random.randint(1, 4) parent.invokeFactory( 'SPSeminar', seminar_id, title=title, description=desc, conclusions=conclusions, ) s = getattr(parent, seminar_id) s._renameAfterCreation(check_auto_id=True) s.setStartDate(start_date) s.setEndDate(end_date) s.setSubject(subject) s.reindexObject() event.notify(ObjectInitializedEvent(s)) wftool = getToolByName(self, 'portal_workflow') wftool.doActionFor(s, 'publish') return s
def eventAndReindex(*objects): """fires an objectinitialized event and reindexes the object(s) after creation so it can be found in the catalog """ for obj in objects: event.notify(ObjectInitializedEvent(obj)) obj.reindexObject()
def create_files_and_images_folders(obj, event): log = logging.getLogger('create_files_and_images_folders') wf_tool = getToolByName(obj, 'portal_workflow') folders = { 'images': 'Images', 'curations': 'Curations', 'analyses': 'Analyses', 'files': 'Files', } #if obj.portal_type == 'Mars Site': # folders['curations'] = 'Curations' try: for folder in folders: if not folder in obj.objectIds(): nt = obj.invokeFactory('Folder', folder) subf = obj.restrictedTraverse(nt) subf.setTitle(folders[folder]) subf.unmarkCreationFlag() subf.reindexObject() notify(ObjectInitializedEvent(subf)) rs = wf_tool.getInfoFor(subf, 'review_state', '') if not obj.portal_type in ['Mars Site']: subf.setExcludeFromNav(True) if folder == 'files': subf.setLayout("folder_tabular_view") if folder == 'images': subf.setLayout("atct_album_view") #if not rs == 'published': # wf_tool.doActionFor( # subf, # "publish", # comment="publised programmatically") except Exception, e: msg = 'Ooops, %s' % e log.error(msg)
def create_analysis(context, service, keyword, interim_fields): # Determine if the sampling workflow is enabled #workflow_enabled = context.bika_setup.getSamplingWorkflowEnabled() workflow_enabled = context.getSamplingWorkflow() #print 'The contexte in utils/analysis :'+str(context.getSamplingWorkflow()) workflow_enabled = True # Create the analysis analysis = _createObjectByType("Analysis", context, keyword) analysis.setService(service) analysis.setInterimFields(interim_fields) analysis.setMaxTimeAllowed(service.getMaxTimeAllowed()) analysis.unmarkCreationFlag() analysis.reindexObject() # Trigger the intitialization event of the new object zope.event.notify(ObjectInitializedEvent(analysis)) # Perform the appropriate workflow action try: workflow_action = 'sampling_workflow' if workflow_enabled \ else 'no_sampling_workflow' context.portal_workflow.doActionFor(analysis, workflow_action) except WorkflowException: # The analysis may have been transitioned already! # I am leaving this code here though, to prevent regression. pass # Return the newly created analysis return analysis
def create_analysis(context, source, **kwargs): """Create a new Analysis. The source can be an Analysis Service or an existing Analysis, and all possible field values will be set to the values found in the source object. :param context: The analysis will be created inside this object. :param source: The schema of this object will be used to populate analysis. :param kwargs: The values of any keys which match schema fieldnames will be inserted into the corrosponding fields in the new analysis. :returns: Analysis object that was created :rtype: Analysis """ an_id = kwargs.get('id', source.getKeyword()) analysis = _createObjectByType("Analysis", context, an_id) copy_analysis_field_values(source, analysis, **kwargs) # AnalysisService field is not present on actual AnalysisServices. if IAnalysisService.providedBy(source): analysis.setAnalysisService(source) else: analysis.setAnalysisService(source.getAnalysisService()) # Set the interims from the Service service_interims = analysis.getAnalysisService().getInterimFields() # Avoid references from the analysis interims to the service interims service_interims = copy.deepcopy(service_interims) analysis.setInterimFields(service_interims) analysis.unmarkCreationFlag() zope.event.notify(ObjectInitializedEvent(analysis)) return analysis
def test_converts(self): fi = self.createFile('test.pdf') settings = Settings(fi) self.assertEqual(settings.successfully_converted, None) notify(ObjectInitializedEvent(fi)) self.assertEqual(settings.successfully_converted, True) self.assertEqual(settings.num_pages, 1)
def addDiscussion(portal,discussion,tags,context,discussionTitle=''): from ubify.coretypes import generateDiscussionTitle if discussion == '': return None objDiscussion = None new_id = context.generateUniqueId('Discussion') try: objDiscussion = getOrCreateType(portal,context,new_id,'Discussion') except: objDiscussion = None if objDiscussion <> None: if objDiscussion.title == '': if discussionTitle == '': objDiscussion.title = generateDiscussionTitle(convertHtmlToWebIntelligentPlainText(discussion)) else: objDiscussion.title = discussionTitle objDiscussion.setDescription(discussion) objDiscussion._renameAfterCreation() if tags != '': try: values = tags.split(",") values = [val.strip().lower() for val in values] values = [k.lower() for k in list(unique(values)) if k] except AttributeError: values = [] objDiscussion.setSubject(values) objDiscussion.reindexObject() notify(ObjectInitializedEvent(objDiscussion)) return objDiscussion
def __call__(self, name, content_type, data): ctr = getToolByName(self.context, 'content_type_registry') type_ = ctr.findTypeName(name.lower(), '', '') or 'File' # XXX: quick fix for german umlauts name = name.decode("utf8") normalizer = getUtility(IFileNameNormalizer) chooser = INameChooser(self.context) # otherwise I get ZPublisher.Conflict ConflictErrors # when uploading multiple files upload_lock.acquire() # this should fix #8 newid = chooser.chooseName(normalizer.normalize(name), self.context.aq_parent) try: transaction.begin() obj = ploneutils._createObjectByType(type_, self.context, newid) mutator = obj.getPrimaryField().getMutator(obj) mutator(data, content_type=content_type) obj.setTitle(name) obj.reindexObject() notify(ObjectInitializedEvent(obj)) notify(ObjectModifiedEvent(obj)) transaction.commit() finally: upload_lock.release() return obj
def add_contact(self, folder, **kwargs): obj = _createObjectByType('Contact', folder, tmpID()) obj.edit(**kwargs) obj.unmarkCreationFlag() renameAfterCreation(obj) notify(ObjectInitializedEvent(obj)) return obj
def test_filesystem_storage_works(self): gsettings = GlobalSettings(self.portal) _dir = mkdtemp() gsettings.storage_location = _dir gsettings.storage_type = 'File' fi = self.createFile('test.pdf') notify(ObjectInitializedEvent(fi)) uid = fi.UID() fi.reindexObject() # for pc fiobj = self.portal.unrestrictedTraverse( '@@dvpdffiles/%s/%s/%s/small/dump_1.gif' % (uid[0], uid[1], uid)) self.assertEquals( fiobj.context.path, join(_dir, uid[0], uid[1], uid, 'small', 'dump_1.gif')) fiobj = self.portal.unrestrictedTraverse( '@@dvpdffiles/%s/%s/%s/normal/dump_1.gif' % (uid[0], uid[1], uid)) self.assertEquals( fiobj.context.path, join(_dir, uid[0], uid[1], uid, 'normal', 'dump_1.gif')) fiobj = self.portal.unrestrictedTraverse( '@@dvpdffiles/%s/%s/%s/large/dump_1.gif' % (uid[0], uid[1], uid)) self.assertEquals( fiobj.context.path, join(_dir, uid[0], uid[1], uid, 'large', 'dump_1.gif')) fiobj = self.portal.unrestrictedTraverse( '@@dvpdffiles/%s/%s/%s/text/dump_1.txt' % (uid[0], uid[1], uid)) self.assertEquals( fiobj.context.path, join(_dir, uid[0], uid[1], uid, 'text', 'dump_1.txt'))
def create_test_objects(self, type_name, subject='random', start=0, total=10, publish=True): objs = [] object_ids = \ ['%s-%s' % (type_name, number) for number in range(start, total+start)] parent = self.portal for object_id in object_ids: parent.invokeFactory( type_name, object_id, title="Title for %s" % type_name, description="Description for %s" % type_name, ) obj = getattr(parent, object_id) obj._renameAfterCreation(check_auto_id=True) if subject == 'random': obj.setSubject(random.sample(['cat1', 'cat2', 'cat3'], 1)[0]) else: obj.setSubject(subject) obj.reindexObject() event.notify(ObjectInitializedEvent(obj)) if publish: wftool = getToolByName(self.portal, 'portal_workflow') wftool.doActionFor(obj, 'publish') objs.append(obj) return objs
def addConversation(self, title, text=None, creator=None, files=None, conversation_type='PloneboardConversation', **kwargs): """Adds a new conversation to the forum. XXX should be possible to parameterise the exact type that is being added. """ id = self.generateId(prefix='') conv = _createObjectByType(conversation_type, self, id) # XXX: There is some permission problem with AT write_permission # and using **kwargs in the _createObjectByType statement. conv.setTitle(title) for fieldname, value in kwargs.items(): conv.getField(fieldname).getMutator(conv)(value) if creator is not None: conv.setCreators([creator]) event.notify(ObjectInitializedEvent(conv)) if text is not None or files: m = _createObjectByType('PloneboardComment', conv, conv.generateId(prefix='')) # XXX: There is some permission problem with AT write_permission # and using **kwargs in the _createObjectByType statement. m.setTitle(title) if text is not None: m.setText(text) 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 attachment = File(file.getId(), file.title_or_id(), str(file.data), file.getContentType()) m.addAttachment(attachment) event.notify(ObjectInitializedEvent(m)) m.reindexObject() conv.reindexObject() return conv
def add_calculation(self, **kwargs): folder = self.portal.bika_setup.bika_calculations obj = _createObjectByType('Calculation', folder, tmpID()) obj.edit(**kwargs) obj.unmarkCreationFlag() renameAfterCreation(obj) notify(ObjectInitializedEvent(obj)) return obj
def add_analysiscategory(self, **kwargs): folder = self.portal.bika_setup.bika_analysiscategories obj = _createObjectByType('AnalysisCategory', folder, tmpID()) obj.edit(**kwargs) obj.unmarkCreationFlag() renameAfterCreation(obj) notify(ObjectInitializedEvent(obj)) return obj
def create_object(self, type_name, id_): new_id = self.context.invokeFactory(type_name=type_name, id=id_) assert new_id == id_, "New id (%s) does not equal the excepted " \ "id (%s)." % (new_id, posted_id) entry = self.context.get(new_id) notify(ObjectInitializedEvent(entry)) entry.at_post_create_script() return id_
def add_client(self, **kwargs): folder = self.portal.clients obj = _createObjectByType('Client', folder, tmpID()) obj.edit(**kwargs) obj.unmarkCreationFlag() renameAfterCreation(obj) notify(ObjectInitializedEvent(obj)) return obj
def test_sets_filehash(self): fi = self.createFile('test.odp') gsettings = GlobalSettings(self.portal) gsettings.auto_select_layout = True gsettings.auto_layout_file_types = ['ppt'] notify(ObjectInitializedEvent(fi)) settings = Settings(fi) self.assertTrue(settings.filehash is not None)
def test_sets_can_not_convert_after_conversion(self): fi = self.createFile('test.odp') gsettings = GlobalSettings(self.portal) gsettings.auto_select_layout = True gsettings.auto_layout_file_types = ['ppt'] notify(ObjectInitializedEvent(fi)) converter = Converter(fi) self.assertTrue(not converter.can_convert)
def testHandlersDoNotOverlap(self): """Test that handlers do not overlap themselves, i.e. that at most one handler is called for any event. """ portal = self.portal ntool = getToolByName(portal, NTOOL_ID) wtool = getToolByName(portal, 'portal_workflow') rtool = getToolByName(portal, 'portal_registration') mtool = getToolByName(portal, 'portal_membership') mh = portal.MailHost document = portal.folder.document1 self.login('manager') ## Enable everything users = ['* :: *'] properties = { 'item_creation_notification_enabled': True, 'on_item_creation_users': users, 'on_item_creation_mail_template': ['* :: string:creation_mail_notification'], 'item_modification_notification_enabled': True, 'on_item_modification_users': users, 'on_item_modification_mail_template': ['* :: string:modification_mail_notification'], 'wf_transition_notification_enabled': True, 'on_wf_transition_users': users, 'on_wf_transition_mail_template': ['* :: string:workflow_mail_notification'], 'member_registration_notification_enabled': True, 'on_member_registration_users': users, 'on_member_registration_mail_template':['* :: string:registration_mail_notification'], 'discussion_item_creation_notification_enabled': True, 'on_discussion_item_creation_users': users, 'on_discussion_item_creation_mail_template': ['* :: string:discussion_mail_notification'], } ntool.manage_changeProperties(properties) ## Test item creation portal.invokeFactory('Document', 'document') event.notify(ObjectInitializedEvent(portal['document'])) self.failUnlessSent(1) mh.clearSentList() ## Test item modification document.processForm(data=1, values={'title': 'New title'}) self.failUnlessSent(1) mh.clearSentList() ## Test workflow transition wtool.doActionFor(document, 'publish') self.failUnlessSent(3) wtool.doActionFor(document, 'retract') mh.clearSentList() ## Test member registration userid = 'a_new_member' rtool.addMember(userid, 'password', properties=None) self.failUnlessSent(3) mtool.deleteMembers([userid, ]) mh.clearSentList()
def test_auto_convert_powerpoint(self): fi = self.createFile('test.odp') gsettings = GlobalSettings(self.portal) gsettings.auto_select_layout = True gsettings.auto_layout_file_types = ['ppt'] notify(ObjectInitializedEvent(fi)) settings = Settings(fi) self.assertEqual(settings.successfully_converted, True) self.assertEqual(settings.num_pages, 1)
def test_retrieve_correct_resource_location_new_storage(self): gsettings = GlobalSettings(self.portal) _dir = mkdtemp() gsettings.storage_location = _dir fi = self.createFile('test.pdf') notify(ObjectInitializedEvent(fi)) uid = fi.UID() self.assertEquals(storage.getResourceDirectory(obj=fi), join(_dir, uid[0], uid[1], uid))
def test_actions(self): # BBB Fix test in line 118. Anyway form creation works notify(ObjectInitializedEvent(self.form)) self.assertTrue('registrants' in self.form.actionAdapter) self.assertTrue( 'user_notification_mailer' not in self.form.actionAdapter) self.assertTrue( 'manager_notification_mailer' in self.form.actionAdapter) self.assertEqual(self.form.thanksPage, 'thank-you')
def test_indexation_disabled(self): fi = self.createFile('test.pdf') gsettings = GlobalSettings(self.portal) # indexation is enabled by default, so disable it gsettings.enable_indexation = False notify(ObjectInitializedEvent(fi)) # make sure conversion was successfull self.failUnless(self._isSuccessfullyConverted(fi)) annotations = IAnnotations(fi)['collective.documentviewer'] self.failUnless(annotations['catalog'] is None)
def manage_afterPUT(self, data, marshall_data, file, context, mimetype,filename, REQUEST, RESPONSE): is_new = False title = self.Title() if not title: is_new = True BaseClass.manage_afterPUT(self, data, marshall_data, file, context, mimetype, filename, REQUEST, RESPONSE) if is_new: notify(ObjectInitializedEvent(self)) else: notify(ObjectEditedEvent(self))
def test_migrate_pdfpal_on_convert(self): fi = self.createFile('test.pdf') fi.layout = 'page-turner' annotations = IAnnotations(fi) metadata = {'foo': 'bar'} annotations['wc.pageturner'] = metadata notify(ObjectInitializedEvent(fi)) annotations = IAnnotations(fi) self.assertTrue('wc.pageturner' not in annotations) self.assertEquals(fi.layout, 'documentviewer')
def test_shop_item_default_category(self): self.setRoles(('Manager',)) self.portal.shop.products.invokeFactory('ShopItem', 'test-item') item = self.portal.shop.products['test-item'] self.setRoles(('Member',)) event = ObjectInitializedEvent(item, self.portal.REQUEST) zope.event.notify(event) self.failUnless(self.portal.shop.products in item.listCategories())
def test_cleanup_file_storage(self): gsettings = GlobalSettings(self.portal) _dir = mkdtemp() gsettings.storage_location = _dir gsettings.storage_type = 'File' fi = self.createFile('test.pdf') uid = fi.UID() notify(ObjectInitializedEvent(fi)) self.portal.manage_delObjects([fi.getId()]) self.assertTrue(not exists(join(_dir, uid[0], uid[1], uid)))
def __call__(self, validate_all=False, data=None, create=False): if data is None: data = json_body(self.request) obj = self.context modified = False for field in obj.Schema().fields(): if not field.writeable(obj): continue name = field.getName() if name in data: deserializer = queryMultiAdapter((field, obj, self.request), IFieldDeserializer) if deserializer is None: continue value, kwargs = deserializer(data[name]) mutator = field.getMutator(obj) mutator(value, **kwargs) modified = True if modified: errors = self.validate() if not validate_all: errors = {f: e for f, e in errors.items() if f in data} if errors: errors = [{ "message": e, "field": f, "error": "ValidationError" } for f, e in errors.items()] raise BadRequest(errors) if create: if obj.checkCreationFlag(): obj.unmarkCreationFlag() notify(ObjectInitializedEvent(obj)) obj.at_post_create_script() else: obj.reindexObject() notify(ObjectEditedEvent(obj)) obj.at_post_edit_script() # We'll set the layout after the validation and and even if there # are no other changes. if "layout" in data: layout = data["layout"] self.context.setLayout(layout) # OrderingMixin self.handle_ordering(data) return obj
def test_filesystem_missing_gives_404(self): gsettings = GlobalSettings(self.portal) _dir = mkdtemp() gsettings.storage_location = _dir gsettings.storage_type = 'File' fi = self.createFile('test.pdf') notify(ObjectInitializedEvent(fi)) uid = fi.UID() self.assertRaises( KeyError, self.portal.unrestrictedTraverse, '@@dvpdffiles/%s/%s/%s/small/foobar.gif' % (uid[0], uid[1], uid))