예제 #1
0
 def __setitem__(self, name, item):
     #print "AlchemistContainer.__setitem__", self, repr(name), item
     #from bungeni.utils.probing import class_inheritance
     #print class_inheritance(self)
     #import pdb; pdb.set_trace()
     session = Session()
     session.add(item)
예제 #2
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()
예제 #3
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")
예제 #4
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)
예제 #5
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"
예제 #6
0
 def __call__(self):
     self.request.response.setHeader("Content-type", "application/pdf")
     self.request.response.setHeader("Content-disposition", 'inline;filename="'
                         + removeSecurityProxy(self.report.report_type) + "_"
                         + removeSecurityProxy(self.report.start_date).strftime("%Y-%m-%d") + '.pdf"')
     
     
     session = Session()
     report = session.query(domain.Report).get(self.report.report_id)
     d = dict([(f.file_title, f.file_data) for f in report.attached_files])
     if "pdf" not in d.keys():
         params = {}
         params["body_text"] = self.cleanupText()
         openofficepath = getUtility(IOpenOfficeConfig).getPath()
         renderer = Renderer(self.odt_file, params, self.tempFileName, pythonWithUnoPath=openofficepath)
         renderer.run()
         f = open(self.tempFileName, "rb")
         doc = f.read()
         f.close()
         os.remove(self.tempFileName)
         attached_file = domain.AttachedFile()
         attached_file.file_title = "pdf"
         attached_file.file_data = doc
         attached_file.language = report.language
         report.attached_files.append(attached_file)
         notify(ObjectCreatedEvent(attached_file))
         session.add(report)
         session.commit()
         return doc
     else:
         return d["pdf"].__str__()
예제 #7
0
 def create(self, message, manual=False):
     """Store the existing state of the adapted context as a new version.
     """
     context = self.__parent__
     if manual:
         if not self.has_write_permission(context):
             raise Unauthorized
     version = self.domain_model()
     trusted = removeSecurityProxy(context)
     
     # set values on version from context
     self._copyFields(trusted, version)
     
     # content domain ids are typically not in the interfaces
     # manually inspect and look for one, by hand to save on the new version
     mapper = orm.object_mapper(trusted)
     version.content_id = mapper.primary_key_from_instance(trusted)[0]
     version.status = None
     version.manual = manual
     
     # we rely on change handler to attach the change object to the version
     event.notify(
         interfaces.VersionCreated(context, self, version, message))
     
     session = Session()
     session.add(version)
     
     version.context = context
     event.notify(ObjectCreatedEvent(version))
     
     return version
예제 #8
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)
예제 #9
0
 def handle_insert(self, action, data):
     session = Session()
     sitting = domain.GroupSitting()
     trusted = removeSecurityProxy(ISchedulingContext(self.context))
     group = session.query(domain.Group).get(trusted.group_id)
     if ("rec_type" not in data.keys()) or (data["rec_type"] == ""):
         sitting.start_date = datetime.datetime.strptime(data["start_date"], '%Y-%m-%d %H:%M')
         sitting.end_date = datetime.datetime.strptime(data["end_date"], '%Y-%m-%d %H:%M')
         sitting.group_id = trusted.group_id
         if "language" in data.keys():
             sitting.language = data["language"]
         if "venue" in data.keys():
             sitting.venue_id = data["venue"]
         session.add(sitting)
         notify(ObjectCreatedEvent(sitting))
         session.commit()
         self.request.response.setHeader('Content-type', 'text/xml')
         return '<data><action type="inserted" sid="'+str(data["ids"])+'" tid="'+str(sitting.sitting_id)+'" /></data>'
     else:
         try:
             recurrence_start_date = datetime.datetime.strptime(data["start_date"], '%Y-%m-%d %H:%M')
             recurrence_end_date = datetime.datetime.strptime(data["end_date"], '%Y-%m-%d %H:%M')
         except:
             print "Date is not in the correct format"
         year = timedelta(days=365)
         #max end date is one year from now or end_date of the group whichever is sooner
         if (group is not None) and (group.end_date is not None):
             if (datetime.datetime.now() + year) < group.end_date:
                 end = datetime.datetime.now() + year 
             else:
                 end = group.end_date
             if recurrence_end_date > end:
                 recurrence_end_date = end 
         else:
             if recurrence_end_date > (datetime.datetime.now() + year):
                 recurrence_end_date = datetime.datetime.now() + year
         recurrence_type = data["rec_type"]
         length = data["event_length"]
         sitting_length = timedelta(seconds=int(length))
         dates = self.generate_recurrence_dates(recurrence_start_date, recurrence_end_date, recurrence_type)
         output = '<data>'
         for date in dates:
             sitting = domain.GroupSitting()
             sitting.group_id = trusted.group_id
             sitting.start_date = date
             sitting.end_date = date + sitting_length
             sitting.status = None
             if "language" in data.keys():
                 sitting.language = data["language"]
             if "venue" in data.keys():
                 sitting.venue_id = data["venue"]
             session.add(sitting)
             notify(ObjectCreatedEvent(sitting))
             output = output+'<action type="inserted" sid="'+str(data["ids"])+'" tid="'+str(sitting.sitting_id)+'" />'
         session.commit()
         output = output + '</data>'
         self.request.response.setHeader('Content-type', 'text/xml')
         return output
예제 #10
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)
예제 #11
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
예제 #12
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
예제 #13
0
 def handle_generate_takes(self, action, data):
     session = Session()
     trusted = removeSecurityProxy(self.context)
     takes = session.query(domain.Take).filter(
         domain.Take.sitting_id == trusted.sitting_id)
     for t in takes:
         session.delete(t)
     
     sitting = trusted
     current_start_time = sitting.start_date
     sitting_duration = sitting.end_date - sitting.start_date
     take_duration = timedelta(minutes=int(data["duration"]))
     assigned_reporters = get_assigned_staff(self.context, "Reporter")
     assigned_readers = get_assigned_staff(self.context, "Reader")
     assigned_editors = get_assigned_staff(self.context, "Editor")
     c_reporter = 0 
     c_reader = 0
     c_editor = 0
     
     while sitting_duration > timedelta(minutes=0):
         take = domain.Take()
         take.sitting_id = sitting.sitting_id
         if (sitting_duration - take_duration) > timedelta(minutes=0):
             sitting_duration = sitting_duration - take_duration
             take.start_date = current_start_time
             take.end_date = take.start_date + take_duration
             current_start_time = take.end_date
         else:
             take.start_date = current_start_time
             take.end_date = take.start_date + sitting_duration
             sitting_duration = timedelta(minutes=0)
         if c_reporter > len(assigned_reporters)-1:
             c_reporter = 0
             take.reporter_id = assigned_reporters[c_reporter]
         else:
             take.reporter_id = assigned_reporters[c_reporter]
         c_reporter = c_reporter + 1
         
         if c_reader > len(assigned_readers)-1:
             c_reader = 0
             take.reader_id = assigned_readers[c_reader]
         else:
             take.reader_id = assigned_readers[c_reader]
         c_reader = c_reader + 1
         
         if c_editor > len(assigned_editors)-1:
             c_editor = 0
             take.editor_id = assigned_editors[c_editor]
         else:
             take.editor_id = assigned_editors[c_editor]
         c_editor = c_editor + 1
         session.add(take)
     session.commit()
     self.request.response.redirect('./takes')
예제 #14
0
def group_sitting_created(ob, event):
    '''
    Recieves notification that a new sitting has been created and creates
    a hansard for it.
    '''
    session = Session()
    ob = removeSecurityProxy(ob)
    hansard = domain.Hansard()
    hansard.sitting_id = ob.sitting_id
    session.add(hansard)
    session.commit()
예제 #15
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
예제 #16
0
 def callback(channel, method, properties, body):
     #channel.confirm_delivery()
     notification_utl = component.getUtility(INotificationsUtility)
     exchange = str(mq_utility.get_message_exchange())
     message = simplejson.loads(body)
     domain_class = notification_utl.get_domain(
         message["document_type"])
     session = Session()
     if domain_class and message["document_id"]:
         document = session.query(domain_class).get(message["document_id"])
         if document:
             # first we handle the transition based notifications
             transition_roles = notification_utl.get_transition_based_roles(
                 domain_class, message["destination"]
             )
             transition_principal_ids = get_principal_ids(
                 document, transition_roles)
             if transition_principal_ids:
                 mes = get_message(document, transition_principal_ids)
                 mes["notification_type"] = "onstate"
                 dthandler = lambda obj: obj.isoformat() if isinstance(
                     obj, datetime.datetime) else obj
                 #channel_conf = 
                 channel.basic_publish(
                     exchange=exchange,
                     body=simplejson.dumps(mes, default=dthandler),
                     properties=pika.BasicProperties(
                         content_type="text/plain",
                         delivery_mode=1
                     ),
                     routing_key=""
                 )
                 #if channel_conf:
                 #   log.info("Message published for exchange %r", exchange)
                 #else:
                 #   log.error("Message publication failed for exchange %s and message %s" % (exchange, mes))
             # then we handle the time based notifications
             time_roles = notification_utl.get_time_based_time_and_roles(
                 domain_class, message["destination"]
             )
             for time_string, roles in time_roles.iteritems():
                 time_ntf = domain.TimeBasedNotication()
                 time_ntf.object_id = message["document_id"]
                 time_ntf.object_type = message["document_type"]
                 time_ntf.object_status = message["destination"]
                 time_ntf.time_string = time_string
                 time_ntf.notification_date_time = notification_time(
                     time_string)
                 session.add(time_ntf)
     # we commit manually here as this code is not executed in a zope
     # transaction
     session.commit()
     session.close()
     channel.basic_ack(delivery_tag=method.delivery_tag)
예제 #17
0
 def handle_restore(self, action, data):
     site_url = ui_utils.url.absoluteURL(getSite(), self.request)
     login = data.get("login", "")
     email = data.get("email", "")
     user = None
         
     app = BungeniApp()
     settings = EmailSettings(app)
         
     session = Session()
     if email:
         user = session.query(User).filter(
                             User.email==email).first()
     elif login:
         user = session.query(User).filter(
                             User.login==login).first()
                                 
     if user:
         email = user.email
         link = session.query(PasswordRestoreLink).filter(
             PasswordRestoreLink.user_id==user.user_id).first()
         if link:
             if not link.expired():
                 self.status = _(u"This user's link is still active!")
                 return
         else:
             link = PasswordRestoreLink()
             
         link.hash = hashlib.sha224(user.login + 
                                     SECRET_KEY + 
                                     str(datetime.datetime.now())).hexdigest()
         link.expiration_date = datetime.datetime.now() + datetime.timedelta(1)
         link.user_id = user.user_id
         session.add(link)
                     
         mailer = getUtility(ISMTPMailer, name="bungeni.smtp")
             
             
         self.message = _(u"Restore password link: ")\
                     + "%s/reset_password?key=%s" % (site_url, link.hash)
         self.message += u"\n\n"
         self.message += _(u"This link will expire in 24 hours.")
             
         text = ViewPageTemplateFile("templates/mail.pt")(self)
         message = MIMEText(text)
         message.set_charset("utf-8")
         message["Subject"] = _(u"Bungeni password restoration")
         message["From"] = settings.default_sender
             
         mailer.send(settings.default_sender, email, str(message))
         self.status = _(u"Email was sent!")
     else:
         self.status = _(u"User not found!")
예제 #18
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
예제 #19
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)
예제 #20
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
예제 #21
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))
 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()
예제 #23
0
 def handle_save(self, action, data):
     report = domain.Report()
     session = Session()
     report.body_text = data["body_text"]
     report.start_date = data["start_date"]
     report.end_date = data["end_date"]
     report.note = data["note"]
     report.short_name = report.short_name = data["short_name"]
     owner_id = get_db_user_id()
     '''!+TODO(Miano, 18/08/2010) The admin user is currently not a db user
         thus the line above returns None when the admin publishes a report.
         to go around this if it returns None, just query the db for users
         and set the owner id to be the first result'''
     if owner_id is not None:
         report.owner_id = owner_id
     else:
         query = session.query(domain.User)
         results = query.all()
         report.owner_id = results[0].user_id
     # TODO get language from config
     report.language = "en"
     report.created_date = datetime.datetime.now()
     report.group_id = self.context.group_id
     session.add(report)
     notify(ObjectCreatedEvent(report))
     # !+INVALIDATE(mr, sep-2010)
     container.invalidate_caches_for("Report", "add")
     if "sittings" in data.keys():
         try:
             ids = data["sittings"].split(",")
             for id_number in ids:
                 sit_id = int(id_number)
                 sitting = session.query(domain.GroupSitting).get(sit_id)
                 sr = domain.SittingReport()
                 sr.report = report
                 sr.sitting = sitting
                 session.add(sr)
                 # !+INVALIDATE(mr, sep-2010) via an event...
                 container.invalidate_caches_for("SittingReport", "add")
         except:
             #if no sittings are present in report or some other error occurs
             pass
     session.commit()
     
     if IGroupSitting.providedBy(self.context):
         back_link = "./schedule"
     elif ISchedulingContext.providedBy(self.context):
         back_link = "./"
     else:
         raise NotImplementedError
     self.request.response.redirect(back_link)
예제 #24
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
예제 #25
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
예제 #26
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)
예제 #27
0
 def subscribe(self):
     session = Session()
     context = removeSecurityProxy(self.context)
     redirect_url = absoluteURL(context, self.request)
     user = session.query(User).filter(User.login == self.request.principal.id).first()
     # In case we somewhy couldn't find the user
     if user is None:
         return self.request.response.redirect(redirect_url)
     # Adding context item to user's subscriptions
     #!+<class 'sqlalchemy.exc.IntegrityError'>: null value in column "activity" violates not-null constraint
     #user.subscriptions.append(context)
     us = UserSubscription()
     us.principal = user
     us.doc = context
     session.add(us)
     # Redirecting back to the item's page
     return self.request.response.redirect(redirect_url)
예제 #28
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
예제 #29
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))
예제 #30
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
예제 #31
0
 def __setitem__(self, name, item):
     session = Session()
     current_parliament = get_current_parliament()
     item.parliament_id = current_parliament.parliament_id
     session.add(item)