def main(argv=None): """ run this as a cron job and execute all time based transitions """ db = create_engine('postgres://localhost/bungeni', echo=False) component.provideUtility(db, IDatabaseEngine, 'bungeni-db') model.metadata.bind = db session = Session() component.provideAdapter(bungeni.core.workflows.states.WorkflowState, (bungeni.core.interfaces.IBungeniContent, )) component.provideAdapter( bungeni.core.workflows.question.QuestionWorkflowAdapter, (domain.Question, )) component.provideAdapter(ore.workflow.workflow.WorkflowInfo, (domain.Question, )) component.provideHandler( bungeni.core.workflows.question.workflowTransitionEventDispatcher) # add autitor for time based transitions #component.provideAdapter( # (bungeni.core.interfaces.IAuditable, bungeni.core.interfaces.IQuestion, ), # (domain.Question, )) #component.provideAdapter( audit.objectModified, #(domain.Question, bungeni.core.interfaces.IAuditable, )) deferAdmissibleQuestions() session.flush() session.commit()
def book_resource( sitting, resource ): """ book a resource for a sitting, check if the resource is available first """ assert( type(sitting) == domain.GroupSitting) assert( type(resource) == domain.Resource ) session = Session() # check if resource is allready boooked for this sitting cq = session.query( domain.ResourceBooking).filter( sql.and_(domain.ResourceBooking.resource_id == resource.resource_id, domain.ResourceBooking.sitting_id == sitting.sitting_id) ) results = cq.all() if results: print "allready booked" #session.close() return #nothing to do here it is already booked if check_availability( sitting.start_date, sitting.end_date, resource): booking = domain.ResourceBooking() booking.resource_id = resource.resource_id booking.sitting_id = sitting.sitting_id session.add(booking) session.flush() else: print "not available"
def book_resource(sitting, resource): """ book a resource for a sitting, check if the resource is available first """ assert (type(sitting) == domain.GroupSitting) assert (type(resource) == domain.Resource) session = Session() # check if resource is allready boooked for this sitting cq = session.query(domain.ResourceBooking).filter( sql.and_(domain.ResourceBooking.resource_id == resource.resource_id, domain.ResourceBooking.sitting_id == sitting.sitting_id)) results = cq.all() if results: print "allready booked" #session.close() return #nothing to do here it is already booked if check_availability(sitting.start_date, sitting.end_date, resource): booking = domain.ResourceBooking() booking.resource_id = resource.resource_id booking.sitting_id = sitting.sitting_id session.add(booking) session.flush() else: print "not available"
def createAndAdd(self, data): domain_model = removeSecurityProxy(self.context.domain_model) # create the object, inspect data for constructor args try: ob = generic.createInstance(domain_model, data) except TypeError: ob = domain_model() # apply any context values self.finishConstruction(ob) # apply extra form values form.applyChanges(ob, self.form_fields, data, self.adapters) # save the object, id is generated by db on flush self.context[''] = ob # flush so we have database id session = Session() session.flush() # fire an object created event notify(ObjectCreatedEvent(ob)) # signal to add form machinery to go to next url self._finished_add = True mapper = orm.object_mapper(ob) # TODO single primary key ( need changes to base container) oid = mapper.primary_key_from_instance(ob) # retrieve the object with location and security information return self.context[oid]
def main(argv=None): """ run this as a cron job and execute all time based transitions """ db = create_engine('postgres://localhost/bungeni', echo=False) component.provideUtility( db, IDatabaseEngine, 'bungeni-db' ) model.metadata.bind = db session = Session() component.provideAdapter( bungeni.core.workflows.states.WorkflowState, (bungeni.core.interfaces.IBungeniContent,)) component.provideAdapter( bungeni.core.workflows.question.QuestionWorkflowAdapter, (domain.Question,)) component.provideAdapter( ore.workflow.workflow.WorkflowInfo, (domain.Question,)) component.provideHandler( bungeni.core.workflows.question.workflowTransitionEventDispatcher) # add autitor for time based transitions #component.provideAdapter( # (bungeni.core.interfaces.IAuditable, bungeni.core.interfaces.IQuestion, ), # (domain.Question, )) #component.provideAdapter( audit.objectModified, #(domain.Question, bungeni.core.interfaces.IAuditable, )) deferAdmissibleQuestions() session.flush() session.commit()
def createAndAdd(self, data): domain_model = removeSecurityProxy(self.context.domain_model) # create the object, inspect data for constructor args try: ob = generic.createInstance(domain_model, data) except TypeError: ob = domain_model() # apply any context values self.finishConstruction(ob) # apply extra form values form.applyChanges(ob, self.form_fields, data, self.adapters) # save the object, id is generated by db on flush self.context[""] = ob # flush so we have database id session = Session() session.flush() # fire an object created event notify(ObjectCreatedEvent(ob)) # signal to add form machinery to go to next url self._finished_add = True mapper = orm.object_mapper(ob) # TODO single primary key ( need changes to base container) oid = mapper.primary_key_from_instance(ob) # retrieve the object with location and security information return self.context[oid]
def handle_add_save(self, action, data): """After succesful creation of translation, redirect to the view.""" for key in data.keys(): if isinstance(data[key], str): data[key] = unescape(data[key]) #url = url.absoluteURL(self.context, self.request) #language = get_language_by_name(data["language"])["name"] session = Session() trusted = removeSecurityProxy(self.context) mapper = rdb.orm.object_mapper(trusted) pk = getattr(trusted, mapper.primary_key[0].name) current_translation = get_translation_for(self.context, data["language"]) if current_translation: for translation in current_translation: session.delete(translation) for form_field in data.keys(): if form_field == "language": continue translation = domain.ObjectTranslation() translation.object_id = pk translation.object_type = trusted.__class__.__name__ translation.field_name = form_field translation.lang = data["language"] translation.field_text = data[form_field] session.add(translation) session.flush() session.commit() session.close() #versions = IVersioned(self.context) #version = versions.create("'%s' translation added" % language) # reset workflow state #version.status = None #IWorkflowInfo(version).fireTransition("create-translation") # redefine form context and proceed with edit action #self.setUpAdapters(version) #handle_edit_action(self, action, data) # commit version such that it gets a version id #transaction.commit() #if not self._next_url: # self._next_url = ( \ # '%s/versions/%s' % (url, stringKey(version)) + \ # '?portal_status_message=Translation added') self._finished_add = True
def handle_add_save(self, action, data): """After succesful creation of translation, redirect to the view.""" for key in data.keys(): if isinstance(data[key], str): data[key] = unescape(data[key]) #url = url.absoluteURL(self.context, self.request) #language = get_language_by_name(data["language"])["name"] session = Session() trusted = removeSecurityProxy(self.context) mapper = rdb.orm.object_mapper(trusted) pk = getattr(trusted, mapper.primary_key[0].name) current_translation = get_translation_for(self.context, data["language"]) if current_translation: for translation in current_translation: session.delete(translation) for form_field in data.keys(): if form_field == "language": continue translation = domain.ObjectTranslation() translation.object_id = pk translation.object_type = trusted.__class__.__name__ translation.field_name = form_field translation.lang = data["language"] translation.field_text = data[form_field] session.add(translation) session.flush() session.commit() session.close() #versions = IVersioned(self.context) #version = versions.create("'%s' translation added" % language) # reset workflow state #version.status = None #IWorkflowInfo(version).fireTransition("create-translation") # redefine form context and proceed with edit action #self.setUpAdapters(version) #handle_edit_action(self, action, data) # commit version such that it gets a version id #transaction.commit() #if not self._next_url: # self._next_url = ( \ # '%s/versions/%s' % (url, stringKey(version)) + \ # '?portal_status_message=Translation added') self._finished_add = True
def _objectChanged(self, change_kind, object, description="", notes=None, date_active=None): """ description: this is a non-localized string as base description of the log item, offers a (building block) for the description of this log item. UI components may use this in any of the following ways: - AS IS, optionally localized - as a building block for an elaborated description e.g. for generating descriptions that are hyperlinks to an event or version objects - ignore it entirely, and generate a custom description via other means e.g. from the "notes" extras dict. notes: a python dict, containing "extra" information about the log item; the entries in this dict are a function of the "change_kind". It is serialized for storing in the db. For specific examples, see: "workflow": self.objectStateChanged() "new-version": self.objectNewVersion() date_active: the UI for some changes allow the user to manually set the date_active -- this is what should be used as the *effective* date i.e. the date to be used for all intents and purposes other than for data auditing. When not user-modified, the value should be equal to date_audit. """ oid, otype = self._getKey(object) user_id = get_principal_id() assert user_id is not None, _("No IRequest in interaction") session = Session() change = self.change_object() change.action = change_kind change.date_audit = datetime.now() if date_active: change.date_active = date_active else: change.date_active = change.date_audit change.user_id = user_id change.description = description if notes: change.notes = repr(notes) else: change.notes = None change.content_type = otype change.origin = object session.add(change) session.flush() return change.change_id
def add_content(kls, *args, **kwargs): session = Session() instance = kls(*args) for name, value in kwargs.items(): setattr(instance, name, value) session.add(instance) session.flush() return instance
def __make_owner_signatory(context): """Make document owner a default signatory when document is submited to signatories for consent. """ signatories = context.signatories if context.owner_id not in [sgn.user_id for sgn in signatories._query]: session = Session() signatory = signatories._class() signatory.user_id = context.owner_id, signatory.item_id = context.parliamentary_item_id session.add(signatory) session.flush() zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(signatory))
def __make_owner_signatory(context): """Make document owner a default signatory when document is submited to signatories for consent. """ signatories = context.signatories if context.owner_id not in [sgn.user_id for sgn in signatories._query]: session = Session() signatory = signatories._class() signatory.user_id = (context.owner_id,) signatory.item_id = context.parliamentary_item_id session.add(signatory) session.flush() zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(signatory))
def _objectChanged(self, change_kind, object, description="", notes=None, date_active=None): """ description: this is a non-localized string as base description of the log item, offers a (building block) for the description of this log item. UI components may use this in any of the following ways: - AS IS, optionally localized - as a building block for an elaborated description e.g. for generating descriptions that are hyperlinks to an event or version objects - ignore it entirely, and generate a custom description via other means e.g. from the "notes" extras dict. notes: a python dict, containing "extra" information about the log item; the entries in this dict are a function of the "change_kind". It is serialized for storing in the db. For specific examples, see: "workflow": self.objectStateChanged() "new-version": self.objectNewVersion() date_active: the UI for some changes allow the user to manually set the date_active -- this is what should be used as the *effective* date i.e. the date to be used for all intents and purposes other than for data auditing. When not user-modified, the value should be equal to date_audit. """ oid, otype = self._getKey(object) user_id = get_principal_id() assert user_id is not None, _("No IRequest in interaction") session = Session() change = self.change_object() change.action = change_kind change.date_audit = datetime.now() if date_active: change.date_active = date_active else: change.date_active = change.date_audit change.user_id = user_id change.description = description if notes: change.notes = repr(notes) else: change.notes = None change.content_type = otype change.origin = object session.add(change) session.flush() return change.change_id
def unbook_resource(sitting, resource): """ remove a resource from a sitting """ assert (type(sitting) == domain.GroupSitting) assert (type(resource) == domain.Resource) session = Session() cq = session.query(domain.ResourceBooking).filter( sql.and_(domain.ResourceBooking.resource_id == resource.resource_id, domain.ResourceBooking.sitting_id == sitting.sitting_id)) results = cq.all() for result in results: session.delete(result) session.flush()
def objectNewVersion( ob, event ): """ when an object is versioned we copy the attachments to the version""" if type(ob) == domain.AttachedFileVersion: return ob = removeSecurityProxy( ob ) session = Session() session.merge(ob) session.flush() for attached_file in ob.head.attached_files: versions = interfaces.IVersioned(attached_file) version = versions.create('version created on object versioning: %s' % getattr(ob.change,'description','')) version.file_version_id = ob.version_id
def _objectChanged(self, change_kind, object, description=u''): oid, otype = self._getKey(object) user_id = self._getCurrentUserId() session = Session() change = self.change_object() change.action = change_kind change.date = datetime.now() change.user_id = user_id change.description = description change.content_type = otype change.origin = object session.add(change) session.flush() return change.change_id
def _objectChanged( self, change_kind, object, description=u'' ): oid, otype = self._getKey( object ) user_id = self._getCurrentUserId() session = Session() change = self.change_object() change.action = change_kind change.date = datetime.now() change.user_id = user_id change.description = description change.content_type = otype change.origin = object session.add(change) session.flush() return change.change_id
def objectNewVersion(ob, event): """ when an object is versioned we copy the attachments to the version""" if type(ob) == domain.AttachedFileVersion: return ob = removeSecurityProxy(ob) session = Session() session.merge(ob) session.flush() for attached_file in ob.head.attached_files: versions = interfaces.IVersioned(attached_file) version = versions.create('version created on object versioning: %s' % getattr(ob.change, 'description', '')) version.file_version_id = ob.version_id
def unbook_resource( sitting, resource ): """ remove a resource from a sitting """ assert( type(sitting) == domain.GroupSitting) assert( type(resource) == domain.Resource ) session = Session() cq = session.query( domain.ResourceBooking).filter( sql.and_( domain.ResourceBooking.resource_id == resource.resource_id, domain.ResourceBooking.sitting_id == sitting.sitting_id )) results = cq.all() for result in results: session.delete(result) session.flush()
def __call__(self): body_text = self.request.form['body_text'] session = Session() report = domain.Report() start_date = self.request.form['start_date'] end_date = self.request.form['end_date'] report.start_date = start_date report.end_date = end_date report.created_date = datetime.datetime.now() report.note = self.request.form['note'] report.report_type = self.request.form['report_type'] report.body_text = body_text report.user_id = get_principal_id() report.group_id = self.context.group_id report.language = "en" session.add(report) if self.request.form['single'] == "False": self.sitting_items = self.get_sittings_items(start_date, end_date) else: self.sitting_items = [] st = self.context.sitting_id sitting = session.query(domain.GroupSitting).get(st) self.sitting_items.append(sitting) for sitting in self.sitting_items: sr = domain.SittingReport() sr.report = report sr.sitting = sitting session.add(sr) session.flush() rpm = zope.securitypolicy.interfaces.IRolePermissionMap(report) rpm.grantPermissionToRole(u'zope.View', 'bungeni.Anybody') if IGroupSitting.providedBy(self.context): back_link = './schedule' elif ISchedulingContext.providedBy(self.context): back_link = './' else: raise NotImplementedError self.request.response.redirect(back_link)
def objectNewVersion(self, object, event): """ object: origin domain workflowed object event: bungeni.core.interfaces.VersionCreated .object # origin domain workflowed object .message # title of the version object .version # bungeni.models.domain.*Version .versioned # bungeni.core.version.Versioned """ # At this point, the new version instance (at event.version) is not yet # persisted to the db (or added to the session!) so its version_id is # still None. We force the issue, by adding it to session and flushing. session = Session() session.add(event.version) session.flush() # as base description, record a the version object's title description = event.message # extras, that may be used e.g. to elaborate description at runtime notes = {"version_id": event.version.version_id} return self._objectChanged("new-version", object, description, notes)
def objectNewVersion(self, object, event): """ object: origin domain workflowed object event: bungeni.core.interfaces.VersionCreated .object # origin domain workflowed object .message # title of the version object .version # bungeni.models.domain.*Version .versioned # bungeni.core.version.Versioned """ # At this point, the new version instance (at event.version) is not yet # persisted to the db (or added to the session!) so its version_id is # still None. We force the issue, by adding it to session and flushing. session = Session() session.add(event.version) session.flush() # as base description, record a the version object's title description = event.message # extras, that may be used e.g. to elaborate description at runtime notes = { "version_id": event.version.version_id } return self._objectChanged("new-version", object, description, notes)
def create_sitting(group_id=1, language="en"): """Sitting to schedule content.""" session = Session() st = domain.SittingType() st.sitting_type = u"morning" st.start_time = datetime.time(8,30) st.end_time = datetime.time(12,30) st.language = language session.add(st) session.flush() sitting = domain.GroupSitting() sitting.start_date = datetime.datetime.now() sitting.end_date = datetime.datetime.now() sitting.sitting_type_id = st.sitting_type_id sitting.group_id = group_id sitting.language = language session.add(sitting) session.flush() return sitting
def __call__(self): date = datetime.datetime.strptime(self.request.form['date'], '%Y-%m-%d').date() self.display_minutes = (self.request.form['display_minutes'] == "True") time_span = self.request.form['time_span'] if time_span == TIME_SPAN.daily: time_span = TIME_SPAN.daily elif time_span == TIME_SPAN.weekly: time_span = TIME_SPAN.weekly end = self.get_end_date(date, time_span) body_text = super(StoreReportView, self).__call__() sitting_items = [] for sitting in self.sitting_items: if self.display_minutes: if sitting.status in ["published-minutes"]: sitting_items.append(sitting) else: if sitting.status in [ "published-agenda", "draft-minutes", "published-minutes" ]: sitting_items.append(sitting) if len(sitting_items) == 0: referer = self.request.getHeader('HTTP_REFERER') if referer: referer = referer.split('?')[0] else: referer = "" self.request.response.redirect( referer + "?portal_status_message=No data found") return self.sitting_items = sitting_items session = Session() report = domain.Report() report.start_date = date report.end_date = end report.created_date = datetime.datetime.now() if self.display_minutes: report.report_type = 'minutes' else: report.report_type = 'agenda' report.body_text = body_text report.user_id = get_principal_id() report.group_id = self.group.group_id session.add(report) for sitting in self.sitting_items: sr = domain.SittingReport() sr.report = report sr.sitting = sitting session.add(sr) session.flush() rpm = zope.securitypolicy.interfaces.IRolePermissionMap(report) rpm.grantPermissionToRole(u'zope.View', 'bungeni.Anybody') if IGroupSitting.providedBy(self.context): back_link = ui_url.absoluteURL(self.context, self.request) + '/schedule' elif ISchedulingContext.providedBy(self.context): back_link = ui_url.absoluteURL(self.context, self.request) else: raise NotImplementedError self.request.response.redirect(back_link) session.close()