Ejemplo n.º 1
0
 def saveDiscussions(self):
     session = Session()
     new_record_keys = []
     domain_model = removeSecurityProxy(self.context.domain_model)
     for record in self.data:
         discussion_text = record.get("body", "")
         object_id = record.get("object_id", None)
         if object_id:
             current_record = removeSecurityProxy(
                 self.context.get(getItemKey(object_id)))
             current_record.body = discussion_text
             session.add(current_record)
             session.flush()
             notify(ObjectModifiedEvent(current_record))
             new_record_keys.append(stringKey(current_record))
         else:
             new_record = domain_model(body=discussion_text,
                                       language=get_default_language())
             new_record.scheduled_item = removeSecurityProxy(
                 self.context.__parent__)
             session.add(new_record)
             session.flush()
             notify(ObjectCreatedEvent(new_record))
             new_record_keys.append(stringKey(new_record))
     records_to_delete = [
         removeSecurityProxy(self.context.get(key))
         for key in self.context.keys() if key not in new_record_keys
     ]
     map(session.delete, records_to_delete)
     map(lambda deleted: notify(ObjectRemovedEvent(deleted)),
         records_to_delete)
Ejemplo n.º 2
0
 def saveDiscussions(self):
     session = Session()
     new_record_keys = []
     domain_model = removeSecurityProxy(self.context.domain_model)
     for record in self.data:
         discussion_text = record.get("body", "")
         object_id = record.get("object_id", None)
         if object_id:
             current_record = removeSecurityProxy(self.context.get(getItemKey(object_id)))
             current_record.body = discussion_text
             session.add(current_record)
             session.flush()
             notify(ObjectModifiedEvent(current_record))
             new_record_keys.append(stringKey(current_record))
         else:
             new_record = domain_model(body=discussion_text, language=get_default_language())
             new_record.scheduled_item = removeSecurityProxy(self.context.__parent__)
             session.add(new_record)
             session.flush()
             notify(ObjectCreatedEvent(new_record))
             new_record_keys.append(stringKey(new_record))
     records_to_delete = [
         removeSecurityProxy(self.context.get(key)) for key in self.context.keys() if key not in new_record_keys
     ]
     map(session.delete, records_to_delete)
     map(lambda deleted: notify(ObjectRemovedEvent(deleted)), records_to_delete)
Ejemplo n.º 3
0
def book_resource(sitting, resource):
    """Book a resource for a sitting, check if the resource is available first
    """
    assert(type(sitting) == domain.Sitting)
    assert(type(resource) == domain.Resource)
    session = Session()
    # check if resource is already 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:
        # !+DOCTTEST(mr, sep-2010) a doctest depends on this print !
        print "already booked"
        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:
        # !+DOCTTEST(mr, sep-2010) a doctest depends on this print !
        print "not available"
Ejemplo n.º 4
0
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 already 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:
        # !+DOCTTEST(mr, sep-2010) a doctest depends on this print !
        print "already booked"
        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:
        # !+DOCTTEST(mr, sep-2010) a doctest depends on this print !
        print "not available"
Ejemplo n.º 5
0
 def process_attendance(self):
     session = Session()
     trusted = removeSecurityProxy(self.context)
     gs_id = trusted.sitting_id
     for selection in self.get_selected():
         member_id = selection.get("user_id")
         if not member_id:
             continue
         at = selection.get("attendance_type")
         if not at:
             continue
         member_id = int(member_id)
         # check existing attendance record
         query = session.query(SittingAttendance).filter(
             sql.and_(SittingAttendance.member_id == member_id, SittingAttendance.sitting_id == gs_id)
         )
         result = query.first()
         if result is not None:
             result.attendance_type = at
             session.flush()
             zope.event.notify(
                 zope.lifecycleevent.ObjectModifiedEvent(
                     result, zope.lifecycleevent.Attributes(ISittingAttendance, "attendance_type")
                 )
             )
         else:
             m_attendance = SittingAttendance()
             m_attendance.sitting_id = gs_id
             m_attendance.attendance_type = at
             m_attendance.member_id = member_id
             session.add(m_attendance)
             session.flush()
             zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(m_attendance))
     self.status = _("Updated attendance record")
Ejemplo n.º 6
0
 def handle_update(self, action, data):
     session = Session()
     self.template_data = []
     sitting = domain.GroupSitting()
     sitting = session.query(domain.GroupSitting).get(data["ids"])
     sitting.start_date = data["start_date"].replace(tzinfo=None)
     sitting.end_date = data["end_date"].replace(tzinfo=None)
     if "language" in data.keys():
         sitting.language = data["language"]
     if "venue" in data.keys():
         sitting.venue_id = data["venue"]
     sitting.short_name = data.get("short_name", None)
     sitting.activity_type = data.get("activity_type", None)
     sitting.meeting_type = data.get("meeting_type", None)
     sitting.convocation_type = data.get("convocation_type", None)
     # set extra data needed by template
     session.flush()
     notify(ObjectModifiedEvent(sitting))
     self.template_data.append({
         "group_sitting_id": sitting.group_sitting_id,
         "action": "inserted",
         "ids": data["ids"]
     })
     session.flush()
     self.request.response.setHeader('Content-type', 'text/xml')
     return self.xml_template()
Ejemplo n.º 7
0
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.workflow.states.WorkflowState,
      (bungeni.core.interfaces.IBungeniContent,))

    component.provideAdapter(
      bungeni.core.workflows.question.QuestionWorkflowAdapter,
      (domain.Question,))

    component.provideAdapter(
      bungeni.core.workflow.states.StateWorkflowInfo,
      (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()
Ejemplo n.º 8
0
 def process_attendance(self):
     session = Session()
     trusted = removeSecurityProxy(self.context)
     gs_id = trusted.group_sitting_id
     for selection in self.get_selected():
         member_id = selection.get("user_id")
         if not member_id:
             continue
         at = selection.get("attendance_type")
         if not at:
             continue
         member_id = int(member_id)
         # check existing attendance record
         query = session.query(GroupSittingAttendance).filter(
             sql.and_(GroupSittingAttendance.member_id == member_id,
                      GroupSittingAttendance.group_sitting_id == gs_id))
         result = query.first()
         if result is not None:
             result.attendance_type = at
             session.flush()
             zope.event.notify(
                 zope.lifecycleevent.ObjectModifiedEvent(
                     result,
                     zope.lifecycleevent.Attributes(IGroupSittingAttendance,
                                                    "attendance_type")))
         else:
             m_attendance = GroupSittingAttendance()
             m_attendance.group_sitting_id = gs_id
             m_attendance.attendance_type = at
             m_attendance.member_id = member_id
             session.add(m_attendance)
             session.flush()
             zope.event.notify(
                 zope.lifecycleevent.ObjectCreatedEvent(m_attendance))
     self.status = _("Updated attendance record")
Ejemplo n.º 9
0
    def handle_publish(self, action, data):
        self.generated_content = self.generateContent(data)
        if IWorkspaceScheduling.providedBy(self.request):
            if not hasattr(self.context, "group_id"):
                context_group_id = ISchedulingContext(self.context).group_id
            else:
                context_group_id = self.context.group_id
        else:
            #get the chamber id
            context_group_id = get_chamber_for_context(
                self.context).parliament_id
        report = domain.Report(
            title=self.title,
            start_date=self.start_date,
            end_date=self.end_date,
            body=self.generated_content,
            owner_id=get_login_user().user_id,  # !+GROUP_AS_OWNER
            language=self.language,
            group_id=context_group_id)
        session = Session()
        session.add(report)
        session.flush()
        notify(ObjectCreatedEvent(report))
        self.status = _(u"Report has been processed and saved")

        return self.template()
Ejemplo n.º 10
0
 def handle_generate_takes(self, action, data):
     transcribers = self.get_transcribers()
     sitting = self.context.sitting
     take_time_delta = datetime.timedelta(seconds=self.get_take_duration())
     current_end_time = sitting.start_date
     current_start_time = sitting.start_date
     take_count = 0
     session = Session()
     while current_end_time < sitting.end_date:
         take = domain.DebateTake()
         take.debate_record_id = self.context.debate_record_id
         take.start_date = current_start_time
         if ((current_end_time + take_time_delta) > sitting.end_date):
             current_end_time = sitting.end_date
         else:
             current_end_time = current_end_time + take_time_delta
             current_start_time = current_end_time + datetime.timedelta(
                 seconds=1)
         take.end_date = current_end_time
         take.transcriber_id = transcribers[take_count %
                                            len(transcribers)].user_id
         take.debate_take_name = self.get_take_name(take_count)
         take_count = take_count + 1
         session.add(take)
     session.flush()
     next_url = url.absoluteURL(self, self.request)
     self.request.response.redirect(next_url)
Ejemplo n.º 11
0
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(
      bungeni.core.workflows.states.StateWorkflowInfo,
      (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()
Ejemplo n.º 12
0
 def handle_generate_takes(self, action, data):
     transcribers = self.get_transcribers()
     sitting = self.context.sitting
     take_time_delta = datetime.timedelta(seconds=self.get_take_duration())
     current_end_time = sitting.start_date
     current_start_time = sitting.start_date
     take_count = 0
     session = Session()
     while current_end_time < sitting.end_date:
         take = domain.DebateTake()
         take.debate_record_id = self.context.debate_record_id
         take.start_date = current_start_time
         if ((current_end_time + take_time_delta) > sitting.end_date):
             current_end_time = sitting.end_date
         else:
             current_end_time = current_end_time + take_time_delta
             current_start_time = current_end_time + datetime.timedelta(
                 seconds=1)
         take.end_date = current_end_time
         take.transcriber_id = transcribers[
             take_count % len(transcribers)].user_id
         take.debate_take_name = self.get_take_name(take_count)
         take_count = take_count+1
         session.add(take)
     session.flush()
     next_url = url.absoluteURL(self, self.request)
     self.request.response.redirect(next_url)
Ejemplo n.º 13
0
 def handle_publish(self, action, data):
     self.generated_content = self.generate_content(data)
     if IWorkspaceScheduling.providedBy(self.request):
         if not hasattr(self.context, "group_id"):
             context_group_id = ISchedulingContext(self.context).group_id
         else:
             context_group_id = self.context.group_id
     else:
         # get the chamber id
         context_group_id = get_chamber_for_context(self.context).group_id
     report = domain.Report(
         title=self.title,
         start_date=self.start_date,
         end_date=self.end_date,
         body=self.generated_content,
         owner_id=get_login_user().user_id, # !+GROUP_AS_OWNER
         language=self.language,
         group_id=context_group_id
     )
     session = Session()
     session.add(report)
     session.flush()
     # requires self db id to have been updated
     report.on_create() 
     notify(ObjectCreatedEvent(report))
     self.status = _(u"Report has been processed and saved")
     return self.template()
Ejemplo n.º 14
0
 def handle_save(self, action, data):
     trusted = removeSecurityProxy(self.context)
     if form.applyChanges(trusted.media_paths, self.form_fields, data, 
                                                             self.adapters):
         session = Session()
         session.add(trusted.media_paths)
         session.flush()
     self._next_url = absoluteURL(self.context, self.request)
     self.request.response.redirect(self._next_url)
Ejemplo n.º 15
0
 def handle_save(self, action, data):
     trusted = removeSecurityProxy(self.context)
     if form.applyChanges(trusted.media_paths, self.form_fields, data,
                          self.adapters):
         session = Session()
         session.add(trusted.media_paths)
         session.flush()
     self._next_url = absoluteURL(self.context, self.request)
     self.request.response.redirect(self._next_url)
Ejemplo n.º 16
0
    def handle_add_save(self, action, data):
        """After succesful creation of translation, redirect to the
        view."""
        #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_CLOSE(taras.sterch, july-2011) there is no need to close the
        # session. Transaction manager will take care of this. Hope it does not
        # brake anything.
        #session.commit()
        #session.close()

        # !+EVENT_DRIVEN_CACHE_INVALIDATION(mr, mar-2011) no translate event
        # invalidate caches for this domain object type
        invalidate_caches_for(trusted.__class__.__name__, "translate")

        #versions = IVersioned(self.context)
        #version = versions.create("'%s' translation added" % language)

        # reset workflow state
        #version.status = None
        #IWorkflowController(version).fireTransition("-draft_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
Ejemplo n.º 17
0
 def id(self, object):
     """ defines the xapian 'primary key' """
     #TODO Add the language to the index!
     string_key = container.stringKey(object)
     if string_key == "obj-None":
         session = Session()
         session.flush()
         string_key = container.stringKey(object)
     return "%s.%s-%s" % (object.__class__.__module__,
                          object.__class__.__name__, string_key)
Ejemplo n.º 18
0
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()
    # execute domain.Entity on create hook -- db id must have been set
    instance.on_create()
    return instance
Ejemplo n.º 19
0
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()
    # execute domain.Entity on create hook -- db id must have been set
    instance.on_create()
    return instance
Ejemplo n.º 20
0
    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()
        
        # !+EVENT_DRIVEN_CACHE_INVALIDATION(mr, mar-2011) no translate event
        # invalidate caches for this domain object type
        invalidate_caches_for(trusted.__class__.__name__, "translate")

        #versions = IVersioned(self.context)
        #version = versions.create("'%s' translation added" % language)

        # reset workflow state
        #version.status = None
        #IWorkflowInfo(version).fireTransition("-draft_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
Ejemplo n.º 21
0
 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
Ejemplo n.º 22
0
    def handle_add_save(self, action, data):
        """After succesful creation of translation, redirect to the view.
        """
        #url = url.absoluteURL(self.context, self.request)
        #language = get_language_by_name(data["language"])["name"]
        session = Session()
        trusted = removeSecurityProxy(self.context)
        mapper = sa.orm.object_mapper(trusted)
        pk = getattr(trusted, mapper.primary_key[0].name)

        curr_trans_by_name = dict(
            (ct.field_name, ct)
            for ct in get_field_translations(self.context, data["language"]))

        def is_changed(context, field_name, new_field_text):
            if field_name in curr_trans_by_name:
                old_field_text = curr_trans_by_name[field_name].field_text
            else:
                old_field_text = getattr(context, field_name)
            return not old_field_text == new_field_text

        translated_attribute_names = []
        for field_name in data.keys():
            if field_name == "language":
                continue
            if is_changed(self.context, field_name, data[field_name]):
                translated_attribute_names.append(field_name)
                if field_name in curr_trans_by_name:
                    translation = curr_trans_by_name[field_name]
                else:
                    translation = domain.FieldTranslation()
                    translation.object_id = pk
                    translation.object_type = naming.polymorphic_identity(
                        trusted.__class__)
                    translation.field_name = field_name
                    translation.lang = data["language"]
                    session.add(translation)
                translation.field_text = data[field_name]

        if translated_attribute_names:
            session.flush()
            notify(
                TranslationCreatedEvent(self.context, data["language"],
                                        sorted(translated_attribute_names)))

        # !+EVENT_DRIVEN_CACHE_INVALIDATION(mr, mar-2011) no translate event
        # invalidate caches for this domain object type
        #invalidate_caches_for(trusted.__class__.__name__, "translate")

        #if not self._next_url:
        #    self._next_url = ( \
        #        "%s/versions/%s" % (url, stringKey(version)) + \
        #        "?portal_status_message=Translation added")

        self._finished_add = True
Ejemplo n.º 23
0
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
Ejemplo n.º 24
0
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
Ejemplo n.º 25
0
 def id(self, object): 
     """ defines the xapian 'primary key' """
     #TODO Add the language to the index!
     string_key = container.stringKey(object)
     if string_key == "obj-None":
         session = Session()
         session.flush()
         string_key = container.stringKey(object)
     return "%s.%s-%s"%(object.__class__.__module__,
                         object.__class__.__name__,
                         string_key)
Ejemplo n.º 26
0
    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()

        # invalidate caches for this domain object type
        invalidate_caches_for(trusted.__class__.__name__, "translate")

        #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
Ejemplo n.º 27
0
 def handle_delete(self, action, data):
     session = Session()
     self.template_data = []
     sitting = session.query(domain.Sitting).get(data["ids"])
     # set extra data needed by template
     self.template_data = []
     if sitting is not None:
         self.request.response.setHeader("Content-type", "text/xml")
         self.template_data.append({"sitting_id": sitting.sitting_id, "action": "deleted", "ids": data["ids"]})
         session.delete(sitting)
         session.flush()
         return self.xml_template()
Ejemplo n.º 28
0
def new_signatory(user_id, head_id):
    """Create a new signatory instance for user on doc.
    """
    session = Session()
    sgn = domain.Signatory()
    sgn.user_id = user_id
    sgn.head_id = head_id
    session.add(sgn)
    session.flush()
    sgn.on_create()
    zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(sgn))
    return sgn
Ejemplo n.º 29
0
 def handle_create_application(self, action, data, validator="validateAdd"):
     oauth_app = domain.OAuthApplication()
     oauth_app.identifier = data["identifier"]
     oauth_app.name = data["name"]
     oauth_app.redirection_endpoint = data["redirection_endpoint"]
     oauth_app.secret = get_key()
     session = Session()
     session.add(oauth_app)
     session.flush()
     notify(ObjectCreatedEvent(oauth_app))
     next_url = url.absoluteURL(self.__parent__, self.request)
     self.request.response.redirect(next_url)
Ejemplo n.º 30
0
def new_signatory(user_id, head_id):
    """Create a new signatory instance for user on doc.
    """
    session = Session()
    sgn = domain.Signatory()
    sgn.user_id = user_id
    sgn.head_id = head_id
    session.add(sgn)
    session.flush()
    sgn.on_create()
    zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(sgn))
    return sgn
Ejemplo n.º 31
0
 def handle_create_application(self, action, data, validator="validateAdd"):
     oauth_app = domain.OAuthApplication()
     oauth_app.identifier = data["identifier"]
     oauth_app.name = data["name"]
     oauth_app.redirection_endpoint = data["redirection_endpoint"]
     oauth_app.secret = get_key()
     session = Session()
     session.add(oauth_app)
     session.flush()
     notify(ObjectCreatedEvent(oauth_app))
     next_url = url.absoluteURL(self.__parent__, self.request)
     self.request.response.redirect(next_url)
Ejemplo n.º 32
0
 def __call__(self):
     obj = self.request.form['obj[]']
     session = Session()
     if self.context.status == "draft_agenda":
         for i in range(0,len(obj)):
             sch = session.query(domain.ItemSchedule).get(obj[i])
             setattr(sch, 'planned_order', i+1)
     elif self.context.status == "draft_minutes":
         for i in range(0,len(obj)):
             sch = session.query(domain.ItemSchedule).get(obj[i])
             setattr(sch, 'real_order', i+1)
     session.flush()
Ejemplo n.º 33
0
 def __call__(self):
     obj = self.request.form['obj[]']
     session = Session()
     if self.context.status == "draft_agenda":
         for i in range(0, len(obj)):
             sch = session.query(domain.ItemSchedule).get(obj[i])
             setattr(sch, 'planned_order', i + 1)
     elif self.context.status == "draft_minutes":
         for i in range(0, len(obj)):
             sch = session.query(domain.ItemSchedule).get(obj[i])
             setattr(sch, 'real_order', i + 1)
     session.flush()
Ejemplo n.º 34
0
 def handle_add_save(self, action, data):
     """After succesful creation of translation, redirect to the view.
     """
     #url = url.absoluteURL(self.context, self.request)
     #language = get_language_by_name(data["language"])["name"]
     session = Session()
     trusted = removeSecurityProxy(self.context)
     mapper = sa.orm.object_mapper(trusted)
     pk = getattr(trusted, mapper.primary_key[0].name)
     
     curr_trans_by_name = dict( (ct.field_name, ct) 
         for ct in get_field_translations(self.context, data["language"]) )
     
     def is_changed(context, field_name, new_field_text):
         if field_name in curr_trans_by_name:
             old_field_text = curr_trans_by_name[field_name].field_text
         else:
             old_field_text = getattr(context, field_name)
         return not old_field_text == new_field_text
     
     translated_attribute_names = []
     for field_name in data.keys():
         if field_name == "language":
             continue
         if is_changed(self.context, field_name, data[field_name]):
             translated_attribute_names.append(field_name)
             if field_name in curr_trans_by_name:
                 translation = curr_trans_by_name[field_name]
             else:
                 translation = domain.FieldTranslation()
                 translation.object_id = pk
                 translation.object_type = naming.polymorphic_identity(trusted.__class__)
                 translation.field_name = field_name
                 translation.lang = data["language"]
                 session.add(translation)
             translation.field_text = data[field_name]
     
     if translated_attribute_names:
         session.flush()
         notify(TranslationCreatedEvent(self.context, 
                 data["language"], sorted(translated_attribute_names)))
     
     # !+EVENT_DRIVEN_CACHE_INVALIDATION(mr, mar-2011) no translate event
     # invalidate caches for this domain object type
     #invalidate_caches_for(trusted.__class__.__name__, "translate")
     
     #if not self._next_url:
     #    self._next_url = ( \
     #        "%s/versions/%s" % (url, stringKey(version)) + \
     #        "?portal_status_message=Translation added")
     
     self._finished_add = True
Ejemplo n.º 35
0
def make_owner_signatory(context):
    """Make document owner a default signatory when document is submitted 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.head_id = context.doc_id
        session.add(signatory)
        session.flush()
        zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(signatory))
Ejemplo n.º 36
0
def make_owner_signatory(context):
    """Make document owner a default signatory when document is submitted 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.head_id = context.doc_id
        session.add(signatory)
        session.flush()
        zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(signatory))
Ejemplo n.º 37
0
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
Ejemplo n.º 38
0
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()
Ejemplo n.º 39
0
 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
Ejemplo n.º 40
0
 def documentData(self, cached=False):
     """Either generate ODT/PDF doc or retrieve from attached files of the
     content item. Cached should only be True for content items that
     are immutable eg. reports."""
     #TODO : Either generate a hash of a mutable content item and store it 
     # with the odt/pdf doc or track changes to a doc
     # Add caching by state. items in terminal states do not change
     tempFileName = os.path.dirname(__file__) + "/tmp/%f.%s" % (
                                             time.time(),self.document_type)
     if cached:
         session = Session()
         d = [f.file_title for f in self.document.attached_files]
         if self.document_type not in d:
             file_type = session.query(domain.AttachedFileType) \
                            .filter(domain.AttachedFileType \
                                             .attached_file_type_name 
                                         == "system") \
                            .first()
             if file_type is None:
                 file_type = domain.AttachedFileType()
                 file_type.attached_file_type_name = "system"
                 file_type.language = self.document.language
                 session.add(file_type)
                 session.flush()
             attached_file = domain.AttachedFile()
             attached_file.file_title = self.document_type
             attached_file.file_data = self.generateDoc()
             attached_file.language = self.document.language
             attached_file.type = file_type
             self.document.attached_files.append(attached_file)
             session.add(self.document)
             session.flush()
             #!+ REPORTS(miano, apr-2011) Anonymous users may prompt 
             #the storage of a report if it hasn't been stored before.
             #Actions that are executed when an objectcreatedevent
             #is triggered may require a principal in the 
             #request eg. auditing. Report attachments are not displayed in 
             #listings or any other place so not triggering the event 
             #shouldn't do any harm.
             #notify(ObjectCreatedEvent(attached_file))
         for f in self.document.attached_files:
             if f.file_title == self.document_type: 
                 self.setHeader(self.document_type)
                 return f.file_data.__str__()
         #If file is not found
         try:
             return self.error_template()
         except ComponentLookupError:
             return u"An error occured during ODT/PDF generation."
     else:
         return self.generateDoc()
Ejemplo n.º 41
0
 def documentData(self, cached=False):
     """Either generate ODT/PDF doc or retrieve from attached files of the
     content item. Cached should only be True for content items that
     are immutable eg. reports."""
     #TODO : Either generate a hash of a mutable content item and store it
     # with the odt/pdf doc or track changes to a doc
     # Add caching by state. items in terminal states do not change
     tempFileName = os.path.dirname(
         __file__) + "/tmp/%f.%s" % (time.time(), self.document_type)
     if cached:
         session = Session()
         d = [f.file_title for f in self.document.attached_files]
         if self.document_type not in d:
             file_type = session.query(domain.AttachedFileType) \
                            .filter(domain.AttachedFileType \
                                             .attached_file_type_name
                                         == "system") \
                            .first()
             if file_type is None:
                 file_type = domain.AttachedFileType()
                 file_type.attached_file_type_name = "system"
                 file_type.language = self.document.language
                 session.add(file_type)
                 session.flush()
             attached_file = domain.AttachedFile()
             attached_file.file_title = self.document_type
             attached_file.file_data = self.generateDoc()
             attached_file.language = self.document.language
             attached_file.type = file_type
             self.document.attached_files.append(attached_file)
             session.add(self.document)
             session.flush()
             #!+ REPORTS(miano, apr-2011) Anonymous users may prompt
             #the storage of a report if it hasn't been stored before.
             #Actions that are executed when an objectcreatedevent
             #is triggered may require a principal in the
             #request eg. auditing. Report attachments are not displayed in
             #listings or any other place so not triggering the event
             #shouldn't do any harm.
             #notify(ObjectCreatedEvent(attached_file))
         for f in self.document.attached_files:
             if f.file_title == self.document_type:
                 self.setHeader(self.document_type)
                 return f.file_data.__str__()
         #If file is not found
         try:
             return self.error_template()
         except ComponentLookupError:
             return u"An error occured during ODT/PDF generation."
     else:
         return self.generateDoc()
Ejemplo n.º 42
0
 def handle_delete(self, action, data):
     session = Session()
     self.template_data = []
     sitting = session.query(domain.GroupSitting).get(data["ids"])
     # set extra data needed by template
     self.template_data = []
     if sitting is not None:
         self.request.response.setHeader('Content-type', 'text/xml')
         self.template_data.append({"group_sitting_id": sitting.group_sitting_id, 
                                    "action": "deleted",
                                    "ids": data["ids"]})
         session.delete(sitting)
         session.flush()
         return self.xml_template()
Ejemplo n.º 43
0
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
Ejemplo n.º 44
0
 def handle_authorize_app(self, action, data):
     session = Session()
     authorization = domain.OAuthAuthorization()
     authorization.user_id = get_login_user().user_id
     app = session.query(domain.OAuthApplication).filter(
         domain.OAuthApplication.identifier == data["client_id"]).one()
     authorization.application_id = app.application_id
     authorization.active = True
     session.add(authorization)
     authorization_token = self.get_authorization_token(authorization)
     session.add(authorization_token)
     session.flush()
     redirect_uri = self.get_redirect_uri(authorization_token,
                                          data["state"])
     self.request.response.redirect(redirect_uri, trusted=True)
Ejemplo n.º 45
0
def create_sitting(group_id=1, language="en"):
    """Sitting to schedule content."""
    
    session = Session()
    sitting = domain.Sitting()
    sitting.start_date = datetime.datetime.now()
    sitting.end_date = datetime.datetime.now()
    sitting.activity_type = u"morning_sitting"
    sitting.meeting_type = u"plenary"
    sitting.convocation_type = u"ordinary"
    sitting.group_id = group_id
    sitting.language = language
    session.add(sitting)
    session.flush()
    
    return sitting
Ejemplo n.º 46
0
def create_sitting(group_id=1, language="en"):
    """Sitting to schedule content."""

    session = Session()
    sitting = domain.Sitting()
    sitting.start_date = datetime.datetime.now()
    sitting.end_date = datetime.datetime.now()
    sitting.activity_type = u"morning_sitting"
    sitting.meeting_type = u"plenary"
    sitting.convocation_type = u"ordinary"
    sitting.group_id = group_id
    sitting.language = language
    session.add(sitting)
    session.flush()

    return sitting
Ejemplo n.º 47
0
def unbook_resource(sitting, resource):
    """Remove a resource from a sitting.
    """
    assert(type(sitting) == domain.Sitting)
    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()
Ejemplo n.º 48
0
 def handle_authorize_app(self, action, data):
     session = Session()
     authorization = domain.OAuthAuthorization()
     authorization.user_id = get_login_user().user_id
     app = session.query(domain.OAuthApplication
         ).filter(domain.OAuthApplication.identifier ==
             data["client_id"]
         ).one()
     authorization.application_id = app.application_id
     authorization.active = True
     session.add(authorization)
     authorization_token = self.get_authorization_token(authorization)
     session.add(authorization_token)
     session.flush()
     redirect_uri = self.get_redirect_uri(authorization_token,
         data["state"])
     self.request.response.redirect(redirect_uri, trusted=True)
Ejemplo n.º 49
0
 def _traverse(self, request, name):
     self.context = removeSecurityProxy(self.context)
     session = Session()
     context = session.merge(self.context)
     hansard = session.query(domain.Hansard) \
                             .filter(domain.Hansard.group_sitting_id
                                             == context.group_sitting_id) \
                             .first()
     if not hansard:
         hansard = domain.Hansard()
         hansard.group_sitting_id = context.group_sitting_id
         session.add(hansard)
         session.flush()
         hansard.media_paths = domain.HansardMediaPaths()
     hansard.__name__ = 'hansard'
     hansard.__parent__ = self.context
     interface.alsoProvides(hansard, ILocation)
     return hansard
Ejemplo n.º 50
0
 def _traverse(self, request, name):
     self.context = removeSecurityProxy(self.context)
     session = Session()
     context = session.merge(self.context)
     hansard = session.query(domain.Hansard) \
                             .filter(domain.Hansard.group_sitting_id 
                                             == context.group_sitting_id) \
                             .first()
     if not hansard:
         hansard = domain.Hansard()
         hansard.group_sitting_id = context.group_sitting_id
         session.add(hansard)
         session.flush()
         hansard.media_paths = domain.HansardMediaPaths()
     hansard.__name__ = 'hansard'
     hansard.__parent__ = self.context
     interface.alsoProvides(hansard, ILocation)
     return hansard
Ejemplo n.º 51
0
def default_reports(sitting, event):
    wf = IWorkflow(sitting)
    if sitting.status in wf.get_state_ids(tagged=["published"]):
        sitting = removeSecurityProxy(sitting)
        sittings = [ExpandedSitting(sitting)]
        report_context = ReportContext(sittings=sittings)
        report = domain.Report()
        session = Session()
        # !+GROUP_AS_OWNER(mr, apr-2012) we assume for now that the "owner" of
        # the report is the currently logged in user.
        report.owner_id = get_db_user_id()
        report.created_date = datetime.datetime.now()
        report.group_id = sitting.group_id
        
        # generate using html template in bungeni_custom
        vocabulary = component.queryUtility(
            schema.interfaces.IVocabularyFactory, 
            "bungeni.vocabulary.ReportXHTMLTemplates"
        )
        preview_template = filter(
            lambda t: t.title=="Sitting Agenda", vocabulary.terms
        )[0]
        doc_template = preview_template.value
        generator = generators.ReportGeneratorXHTML(doc_template)
        generator.context = report_context
        report.language = generator.language
        
        if sitting.status in wf.get_state_ids(tagged=["publishedminutes"]):
            report.short_title = generator.title = _(u"Sitting Votes and "
                u" Proceedings"
            )
        else:
            report.short_title = generator.title = _(u"Sitting Agenda")
    
        report.body = generator.generateReport()
        session.add(report)
        session.flush()
        notify(ObjectCreatedEvent(report))
        sr = domain.SittingReport()
        sr.report = report
        sr.sitting = sitting
        session.add(sr)
        session.flush()
        notify(ObjectCreatedEvent(sr))
Ejemplo n.º 52
0
 def _traverse(self, request, name):
     self.context = removeSecurityProxy(self.context)
     session = Session()
     context = session.merge(self.context)
     debate = session.query(domain.DebateRecord) \
         .filter(domain.DebateRecord.sitting_id
             == context.sitting_id) \
             .first()
     if not debate:
         debate = domain.DebateRecord()
         debate.sitting_id = context.sitting_id
         session.add(debate)
         wfc = IWorkflowController(debate)
         wfc.fireAutomatic()
         session.flush()
     debate.__name__ = self.traversalName
     debate.__parent__ = self.context
     interface.alsoProvides(debate, ILocation)
     return debate
Ejemplo n.º 53
0
 def _traverse(self, request, name):
     self.context = removeSecurityProxy(self.context)
     session = Session()
     context = session.merge(self.context)
     debate = session.query(domain.DebateRecord) \
         .filter(domain.DebateRecord.sitting_id
             == context.sitting_id) \
             .first()
     if not debate:
         debate = domain.DebateRecord()
         debate.sitting_id = context.sitting_id
         session.add(debate)
         wfc = IWorkflowController(debate)
         wfc.fireAutomatic()
         session.flush()
     debate.__name__ = self.traversalName
     debate.__parent__ = self.context
     interface.alsoProvides(debate, ILocation)
     return debate
Ejemplo n.º 54
0
 def handle_delete(self, action, data):
     count = self.delete_subobjects()
     container = self.context.__parent__
     trusted = removeSecurityProxy(self.context)
     session = Session()
     session.delete(trusted)
     count += 1
     try:
         session.flush()
     except IntegrityError, e:
         # this should not happen in production; it's a critical
         # error, because the transaction might have failed in the
         # second phase of the commit
         session.rollback()
         log.critical(e)
         self.status = _(
             "Could not delete item due to database integrity error. "
             "You may wish to try deleting any related sub-records first?")
         return self.render()
Ejemplo n.º 55
0
 def handle_delete(self, action, data):
     count = self.delete_subobjects()
     container = self.context.__parent__
     trusted = removeSecurityProxy(self.context)
     session = Session()
     session.delete(trusted)
     count += 1
     try:
         session.flush()
     except IntegrityError, e:
         # this should not happen in production; it's a critical
         # error, because the transaction might have failed in the
         # second phase of the commit
         session.rollback()
         log.critical(e)
         self.status = _(
             "Could not delete item due to database integrity error. "
             "You may wish to try deleting any related sub-records first?")
         return self.render()
Ejemplo n.º 56
0
def default_reports(sitting, event):
    #!+REPORTS(mb, Feb-2013) add a publish_report action - remove this handler
    if "published" in sitting.status:
        sitting = removeSecurityProxy(sitting)
        report_type = "sitting_agenda"
        report_title = _("report_title_sitting_agenda", 
            default=u"Sitting Agenda")
        if "minutes" in sitting.status:
            report_type = "sitting_minutes"
            report_title =  _("report_title_votes_and_proceedings", 
                default=u"Sitting Votes and Proceedings")
        sittings = [ExpandedSitting(sitting)]
        report = domain.Report()
        session = Session()
        # !+GROUP_AS_OWNER(mr, apr-2012) we assume for now that the "owner" of
        # the report is the currently logged in user.
        report.owner_id = get_login_user().user_id
        report.created_date = datetime.datetime.now()
        report.group_id = sitting.group_id
        # generate using html template in bungeni_custom
        vocab = vocabulary.report_xhtml_template_factory
        term = vocab.getTermByFileName(report_type)
        doc_template = term and term.value or vocab.terms[0].value
        generator = generators.ReportGeneratorXHTML(doc_template)
        generator.title = report_title
        report_title_i18n = translate(report_title, 
            target_language=generator.language)
        report_context = ReportContext(sittings=sittings, 
            title=report_title_i18n)
        generator.context = report_context
        report.title = report_title_i18n
        report.language = generator.language
        report.body = generator.generateReport()
        session.add(report)
        session.flush()
        notify(ObjectCreatedEvent(report))
        sr = domain.SittingReport()
        sr.report = report
        sr.sitting = sitting
        session.add(sr)
        session.flush()
        notify(ObjectCreatedEvent(sr))
Ejemplo n.º 57
0
def default_reports(sitting, event):
    #!+REPORTS(mb, Feb-2013) add a publish_report action - remove this handler
    if "published" in sitting.status:
        sitting = removeSecurityProxy(sitting)
        report_type = "sitting_agenda"
        report_title = _("report_title_sitting_agenda",
                         default=u"Sitting Agenda")
        if "minutes" in sitting.status:
            report_type = "sitting_minutes"
            report_title = _("report_title_votes_and_proceedings",
                             default=u"Sitting Votes and Proceedings")
        sittings = [ExpandedSitting(sitting)]
        report = domain.Report()
        session = Session()
        # !+GROUP_AS_OWNER(mr, apr-2012) we assume for now that the "owner" of
        # the report is the currently logged in user.
        report.owner_id = get_login_user().user_id
        report.created_date = datetime.datetime.now()
        report.group_id = sitting.group_id
        # generate using html template in bungeni_custom
        vocab = vocabulary.report_xhtml_template_factory
        term = vocab.getTermByFileName(report_type)
        doc_template = term and term.value or vocab.terms[0].value
        generator = generators.ReportGeneratorXHTML(doc_template)
        generator.title = report_title
        report_title_i18n = translate(report_title,
                                      target_language=generator.language)
        report_context = ReportContext(sittings=sittings,
                                       title=report_title_i18n)
        generator.context = report_context
        report.title = report_title_i18n
        report.language = generator.language
        report.body = generator.generateReport()
        session.add(report)
        session.flush()
        notify(ObjectCreatedEvent(report))
        sr = domain.SittingReport()
        sr.report = report
        sr.sitting = sitting
        session.add(sr)
        session.flush()
        notify(ObjectCreatedEvent(sr))
Ejemplo n.º 58
0
 def handle_update(self, action, data):
     session = Session()
     self.template_data = []
     sitting = domain.GroupSitting()
     sitting = session.query(domain.GroupSitting).get(data["ids"])
     sitting.start_date = data["start_date"].replace(tzinfo=None)
     sitting.end_date = data["end_date"].replace(tzinfo=None)
     if "language" in data.keys():
         sitting.language = data["language"]
     if "venue" in data.keys():
         sitting.venue_id = data["venue"]
     # set extra data needed by template
     session.flush()
     notify(ObjectModifiedEvent(sitting))
     self.template_data.append({"group_sitting_id": sitting.group_sitting_id, 
                                 "action": "inserted",
                                 "ids": data["ids"]})
     session.flush()
     self.request.response.setHeader('Content-type', 'text/xml')
     return self.xml_template()
Ejemplo n.º 59
0
 def documentData(self, cached=False):
     """Either generate ODT/PDF doc or retrieve from attached files of the
     content item. Cached should only be True for content items that
     are immutable eg. reports."""
     #TODO : Either generate a hash of a mutable content item and store it 
     # with the odt/pdf doc or track changes to a doc
     # Add caching by state. items in terminal states do not change
     if cached:
         d = [ f.title for f in self.document.attachments ]
         if self.document_type not in d:
             att = domain.Attachment()
             att.title = self.document_type
             att.data = self.generateDoc()
             att.language = self.document.language
             att.type = "system" # !+ATTACHED_FILE_TYPE_SYSTEM
             self.document.attachments.append(att)
             session = Session()
             session.add(self.document)
             session.flush()
             #!+ REPORTS(miano, apr-2011) Anonymous users may prompt 
             #the storage of a report if it hasn't been stored before.
             #Actions that are executed when an objectcreatedevent
             #is triggered may require a principal in the 
             #request eg. auditing. Report attachments are not displayed in 
             #listings or any other place so not triggering the event 
             #shouldn't do any harm.
             #notify(ObjectCreatedEvent(att))
         for f in self.document.attachments:
             if f.title == self.document_type: 
                 self.setHeader(self.document_type)
                 return f.data.__str__()
         #If file is not found
         try:
             return self.error_template()
         except ComponentLookupError:
             return u"An error occured during ODT/PDF generation."
     else:
         try:
             return self.generateDoc()
         except DocumentGenerationError:
             return self.error_template()