Beispiel #1
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
Beispiel #2
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 allready boooked for this sitting
    cq = session.query(domain.ResourceBooking).filter(
        sql.and_(domain.ResourceBooking.resource_id == resource.resource_id,
                 domain.ResourceBooking.sitting_id == sitting.sitting_id))
    results = cq.all()
    if results:
        print "allready booked"
        #session.close()
        return
        #nothing to do here it is already booked

    if check_availability(sitting.start_date, sitting.end_date, resource):
        booking = domain.ResourceBooking()
        booking.resource_id = resource.resource_id
        booking.sitting_id = sitting.sitting_id
        session.add(booking)
        session.flush()

    else:
        print "not available"
def book_resource( sitting, resource ):
    """
    book a resource for a sitting,
    check if the resource is available first
    """
    assert( type(sitting) == domain.GroupSitting)
    assert( type(resource) == domain.Resource )
    session = Session()
    # check if resource is allready boooked for this sitting
    cq = session.query( domain.ResourceBooking).filter( 
            sql.and_(domain.ResourceBooking.resource_id == 
                        resource.resource_id,
                    domain.ResourceBooking.sitting_id == sitting.sitting_id) )
    results = cq.all()
    if results:
        print "allready booked"
        #session.close()
        return
        #nothing to do here it is already booked
    
    if check_availability( sitting.start_date, sitting.end_date, resource):
        booking = domain.ResourceBooking()
        booking.resource_id = resource.resource_id
        booking.sitting_id = sitting.sitting_id 
        session.add(booking)
        session.flush()
        
    else:
        print "not available"
Beispiel #4
0
    def create( self, message, manual = False ):
        """Store the existing state of the adapted context as a new
        version."""

        version = self.domain_model()
        context = self.__parent__
        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
Beispiel #5
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__()
Beispiel #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__()
Beispiel #7
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
Beispiel #8
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()
        
        #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
Beispiel #9
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()
        
        #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
Beispiel #10
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)
     
     #import pdb; pdb.set_trace()
     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')
Beispiel #11
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
Beispiel #12
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)

        #import pdb; pdb.set_trace()
        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')
Beispiel #13
0
 def handle_save(self, action, data):
     session = Session()
     transcript = domain.Transcript()
     transcript.start_date = data['start_time']
     transcript.end_date = data['end_time']
     transcript.text = data['speech']
     transcript.person = data['person']
     transcript.sitting_id = self.context.sitting_id
     session.add(transcript)
     session.commit()
     return 'Save'
Beispiel #14
0
 def handle_save(self, action, data):
     session = Session()
     transcript = domain.Transcript()
     transcript.start_date =  data['start_time']                    
     transcript.end_date =  data['end_time']                      
     transcript.text = data['speech']
     transcript.person = data['person'] 
     transcript.sitting_id = self.context.sitting_id
     session.add(transcript)
     session.commit()
     return 'Save'
Beispiel #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
Beispiel #16
0
 def __init__(self, context):
     self.context = context
     session = Session()
     trusted = removeSecurityProxy(context)        
     session.merge(trusted)
     try:
         self.oid = orm.object_mapper( trusted ).primary_key_from_instance(trusted)[0]
     except UnboundExecutionError:
         session.add(trusted)     
         self.oid = orm.object_mapper( trusted ).primary_key_from_instance(trusted)[0]         
     self.object_type = context.__class__.__name__.lower()
Beispiel #17
0
def __make_owner_signatory(context):
    """Make document owner a default signatory when document is submited to
    signatories for consent.
    """
    signatories = context.signatories
    if context.owner_id not in [sgn.user_id for sgn in signatories._query]:
        session = Session()
        signatory = signatories._class()
        signatory.user_id = context.owner_id,
        signatory.item_id = context.parliamentary_item_id
        session.add(signatory)
        session.flush()
        zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(signatory))
Beispiel #18
0
def __make_owner_signatory(context):
    """Make document owner a default signatory when document is submited to
    signatories for consent.
    """
    signatories = context.signatories
    if context.owner_id not in [sgn.user_id for sgn in signatories._query]:
        session = Session()
        signatory = signatories._class()
        signatory.user_id = (context.owner_id,)
        signatory.item_id = context.parliamentary_item_id
        session.add(signatory)
        session.flush()
        zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(signatory))
Beispiel #19
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
Beispiel #20
0
 def _objectChanged( self, change_kind, object, description=u'' ):
     oid, otype = self._getKey( object )
     user_id = self._getCurrentUserId()
     session = Session()
     change = self.change_object()
     change.action = change_kind
     change.date = datetime.now()
     change.user_id = user_id
     change.description = description
     change.content_type = otype
     change.origin = object
     session.add(change)
     session.flush()
     return change.change_id
Beispiel #21
0
 def _objectChanged(self, change_kind, object, description=u''):
     oid, otype = self._getKey(object)
     user_id = self._getCurrentUserId()
     session = Session()
     change = self.change_object()
     change.action = change_kind
     change.date = datetime.now()
     change.user_id = user_id
     change.description = description
     change.content_type = otype
     change.origin = object
     session.add(change)
     session.flush()
     return change.change_id
Beispiel #22
0
 def handle_save(self, action, data):
     session = Session()
     trusted = removeSecurityProxy(self.context)
     sitting = session.query(domain.Sitting).get(trusted.sitting_id)
     #import pdb; pdb.set_trace()
     if sitting is None:
         sitting = domain.Sitting()
         sitting.sitting_id =  trusted.sitting_id
         sitting.media_path =  data['media_path']     
         session.add(sitting)
     else:
         sitting.media_path =  data['media_path']
     session.commit()
     #import pdb; pdb.set_trace()
     self._next_url = absoluteURL(self.context, self.request)+"/transcripts"
     self.request.response.redirect(self._next_url)
Beispiel #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.report_type = data['report_type']
        report.short_name = data['report_type']
        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
        report.language = "en"
        report.created_date = datetime.datetime.now()
        report.group_id = self.context.group_id
        session.add(report)
        notify(ObjectCreatedEvent(report))
        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)
            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)
Beispiel #24
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.report_type = data['report_type']
        report.short_name = data['report_type']
        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
        report.language = "en"
        report.created_date = datetime.datetime.now()
        report.group_id = self.context.group_id
        session.add(report)
        notify(ObjectCreatedEvent(report))
        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)
            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)
Beispiel #25
0
 def handle_save(self, action, data):
     session = Session()
     trusted = removeSecurityProxy(self.context)
     sitting = session.query(domain.Sitting).get(trusted.sitting_id)
     #import pdb; pdb.set_trace()
     if sitting is None:
         sitting = domain.Sitting()
         sitting.sitting_id = trusted.sitting_id
         sitting.media_path = data['media_path']
         session.add(sitting)
     else:
         sitting.media_path = data['media_path']
     session.commit()
     #import pdb; pdb.set_trace()
     self._next_url = absoluteURL(self.context,
                                  self.request) + "/transcripts"
     self.request.response.redirect(self._next_url)
Beispiel #26
0
    def __call__(self):
        body_text = self.request.form['body_text']
        session = Session()
        report = domain.Report()
        start_date = self.request.form['start_date']
        end_date = self.request.form['end_date']
        report.start_date = start_date
        report.end_date = end_date
        report.created_date = datetime.datetime.now()
        report.note = self.request.form['note']
        report.report_type = self.request.form['report_type']
        report.body_text = body_text
        report.user_id = get_principal_id()
        report.group_id = self.context.group_id
        report.language = "en"
        session.add(report)

        if self.request.form['single'] == "False":
            self.sitting_items = self.get_sittings_items(start_date, end_date)
        else:
            self.sitting_items = []
            st = self.context.sitting_id
            sitting = session.query(domain.GroupSitting).get(st)
            self.sitting_items.append(sitting)

        for sitting in self.sitting_items:
            sr = domain.SittingReport()
            sr.report = report
            sr.sitting = sitting
            session.add(sr)
        session.flush()

        rpm = zope.securitypolicy.interfaces.IRolePermissionMap(report)
        rpm.grantPermissionToRole(u'zope.View', 'bungeni.Anybody')

        if IGroupSitting.providedBy(self.context):
            back_link = './schedule'
        elif ISchedulingContext.providedBy(self.context):
            back_link = './'
        else:
            raise NotImplementedError
        self.request.response.redirect(back_link)
Beispiel #27
0
 def objectNewVersion(self, object, event):
     """
     object: origin domain workflowed object 
     event: bungeni.core.interfaces.VersionCreated
         .object # origin domain workflowed object 
         .message # title of the version object
         .version # bungeni.models.domain.*Version
         .versioned # bungeni.core.version.Versioned
     """
     # At this point, the new version instance (at event.version) is not yet
     # persisted to the db (or added to the session!) so its version_id is
     # still None. We force the issue, by adding it to session and flushing.
     session = Session()
     session.add(event.version)
     session.flush()
     # as base description, record a the version object's title
     description = event.message
     # extras, that may be used e.g. to elaborate description at runtime
     notes = {"version_id": event.version.version_id}
     return self._objectChanged("new-version", object, description, notes)
Beispiel #28
0
    def createRecurringSittings(self, ob, data):
        start = data['start_date']
        end = data['end_date']
        weekdays = data.get('weekdays')
        monthly = data.get('monthly')
        repeat = data.get('repeat')
        repeat_until = data.get('repeat_until')
        exceptions = data.get('exceptions', ())

        objs = []
        session = Session()
        group_id = self.context.__parent__.group_id
        group = session.query(domain.Group).get(group_id)

        if repeat or repeat_until:
            for date in validations.generate_recurring_sitting_dates(
                    start.date(), repeat, repeat_until, weekdays, monthly,
                    exceptions):
                # create the object, inspect data for constructor args

                data['start_date'] = datetime.datetime(date.year, date.month,
                                                       date.day, start.hour,
                                                       start.minute)
                data['end_date'] = datetime.datetime(date.year, date.month,
                                                     date.day, end.hour,
                                                     end.minute)

                try:
                    ob = generic.createInstance(self.domain_model, data)
                except TypeError:
                    ob = self.domain_model()

                form.applyChanges(ob, self.form_fields, data, {})
                ob.group_id = group_id

                session.add(ob)
                notify(ObjectCreatedEvent(ob))

                objs.append(ob)
        return objs
Beispiel #29
0
 def __call__(self):
     ids = self.request.form['ids']
     action = self.request.form[ids + "_!nativeeditor_status"]
     session = Session()
     sitting = domain.GroupSitting()
     trusted = removeSecurityProxy(self.context)
     sitting.group_id = trusted.group_id
     if action == "inserted":
         sitting.start_date = self.request.form[ids + "_start_date"]
         sitting.end_date = self.request.form[ids + "_end_date"]
         sitting.sitting_type_id = self.request.form[ids + "_type"]
         sitting.status = None
         if ids + "_type" in self.request.form.keys():
             sitting.sitting_type_id = self.request.form[ids + "_type"]
         if ids + "_language" in self.request.form.keys():
             sitting.language = self.request.form[ids + "_language"]
         if ids + "_venue" in self.request.form.keys():
             sitting.venue_id = self.request.form[ids + "_venue"]
         session.add(sitting)
         notify(ObjectCreatedEvent(sitting))
         session.commit()
     elif action == "updated":
         sitting = session.query(domain.GroupSitting).get(ids)
         sitting.start_date = self.request.form[ids + "_start_date"]
         sitting.end_date = self.request.form[ids + "_end_date"]
         if ids + "_type" in self.request.form.keys():
             sitting.sitting_type_id = self.request.form[ids + "_type"]
         if ids + "_language" in self.request.form.keys():
             sitting.language = self.request.form[ids + "_language"]
         if ids + "_venue" in self.request.form.keys():
             sitting.venue_id = self.request.form[ids + "_venue"]
         session.update(sitting)
         session.commit()
     elif action == "deleted":
         sitting = session.query(domain.GroupSitting).get(ids)
         session.delete(sitting)
         session.commit()
     self.request.response.setHeader('Content-type', 'text/xml')
     return '<data><action type="' + action + '" sid="' + str(
         ids) + '" tid="' + str(sitting.sitting_id) + '" /></data>'
Beispiel #30
0
 def objectNewVersion(self, object, event):
     """
     object: origin domain workflowed object 
     event: bungeni.core.interfaces.VersionCreated
         .object # origin domain workflowed object 
         .message # title of the version object
         .version # bungeni.models.domain.*Version
         .versioned # bungeni.core.version.Versioned
     """
     # At this point, the new version instance (at event.version) is not yet 
     # persisted to the db (or added to the session!) so its version_id is
     # still None. We force the issue, by adding it to session and flushing.
     session = Session()
     session.add(event.version)
     session.flush()
     # as base description, record a the version object's title
     description = event.message
     # extras, that may be used e.g. to elaborate description at runtime        
     notes = {
         "version_id": event.version.version_id
     }
     return self._objectChanged("new-version", object, description, notes)
Beispiel #31
0
def create_sitting(group_id=1, language="en"):
    """Sitting to schedule content."""
    
    session = Session()
    
    st = domain.SittingType()
    st.sitting_type = u"morning"
    st.start_time = datetime.time(8,30)
    st.end_time = datetime.time(12,30)
    st.language = language
    session.add(st)
    session.flush()

    sitting = domain.GroupSitting()
    sitting.start_date = datetime.datetime.now()
    sitting.end_date = datetime.datetime.now()
    sitting.sitting_type_id = st.sitting_type_id
    sitting.group_id = group_id
    sitting.language = language
    session.add(sitting)
    session.flush()
    
    return sitting
Beispiel #32
0
    def createRecurringSittings(self, ob, data):
        start = data['start_date']
        end = data['end_date']
        weekdays = data.get('weekdays')
        monthly = data.get('monthly')
        repeat = data.get('repeat')
        repeat_until = data.get('repeat_until')
        exceptions = data.get('exceptions', ())

        objs = []
        session = Session()
        group_id = self.context.__parent__.group_id
        group = session.query(domain.Group).get(group_id)
        
        if repeat or repeat_until:
            for date in validations.generate_recurring_sitting_dates(
                start.date(), repeat, repeat_until, weekdays, monthly, exceptions):
                # create the object, inspect data for constructor args

                data['start_date'] = datetime.datetime(
                    date.year, date.month, date.day, start.hour, start.minute)
                data['end_date'] = datetime.datetime(
                    date.year, date.month, date.day, end.hour, end.minute)

                try:
                    ob = generic.createInstance(self.domain_model, data)
                except TypeError:
                    ob = self.domain_model()

                form.applyChanges(ob, self.form_fields, data, {})
                ob.group_id = group_id
                
                session.add(ob)
                notify(ObjectCreatedEvent(ob))

                objs.append(ob)
        return objs
Beispiel #33
0
 def handle_assignment(self, action, data):
     session = Session()
     session.query(domain.Assignment).filter(domain.Assignment.sitting_id == self.context.sitting_id).delete()
     for editor_id in data["editors"]:
         assignment = domain.Assignment()
         assignment.sitting_id = self.context.sitting_id
         assignment.staff_id = editor_id
         session.add(assignment)
     for reader_id in data["readers"]:
         assignment = domain.Assignment()
         assignment.sitting_id = self.context.sitting_id
         assignment.staff_id = reader_id
         session.add(assignment)
     for reporter_id in data["reporters"]:
         assignment = domain.Assignment()
         assignment.sitting_id = self.context.sitting_id
         assignment.staff_id = reporter_id
         session.add(assignment)
     session.commit()
     self.request.response.redirect('./transcripts')    
Beispiel #34
0
 def handle_assignment(self, action, data):
     session = Session()
     session.query(domain.Assignment).filter(
         domain.Assignment.sitting_id == self.context.sitting_id).delete()
     for editor_id in data["editors"]:
         assignment = domain.Assignment()
         assignment.sitting_id = self.context.sitting_id
         assignment.staff_id = editor_id
         session.add(assignment)
     for reader_id in data["readers"]:
         assignment = domain.Assignment()
         assignment.sitting_id = self.context.sitting_id
         assignment.staff_id = reader_id
         session.add(assignment)
     for reporter_id in data["reporters"]:
         assignment = domain.Assignment()
         assignment.sitting_id = self.context.sitting_id
         assignment.staff_id = reporter_id
         session.add(assignment)
     session.commit()
     self.request.response.redirect('./transcripts')
Beispiel #35
0
    def __call__(self):
        date = datetime.datetime.strptime(self.request.form['date'],
                                          '%Y-%m-%d').date()
        self.display_minutes = (self.request.form['display_minutes'] == "True")
        time_span = self.request.form['time_span']
        if time_span == TIME_SPAN.daily:
            time_span = TIME_SPAN.daily
        elif time_span == TIME_SPAN.weekly:
            time_span = TIME_SPAN.weekly
        end = self.get_end_date(date, time_span)
        body_text = super(StoreReportView, self).__call__()
        sitting_items = []
        for sitting in self.sitting_items:
            if self.display_minutes:
                if sitting.status in ["published-minutes"]:
                    sitting_items.append(sitting)
            else:
                if sitting.status in [
                        "published-agenda", "draft-minutes",
                        "published-minutes"
                ]:
                    sitting_items.append(sitting)
        if len(sitting_items) == 0:
            referer = self.request.getHeader('HTTP_REFERER')
            if referer:
                referer = referer.split('?')[0]
            else:
                referer = ""
            self.request.response.redirect(
                referer + "?portal_status_message=No data found")
            return
        self.sitting_items = sitting_items
        session = Session()
        report = domain.Report()
        report.start_date = date
        report.end_date = end
        report.created_date = datetime.datetime.now()
        if self.display_minutes:
            report.report_type = 'minutes'
        else:
            report.report_type = 'agenda'
        report.body_text = body_text
        report.user_id = get_principal_id()
        report.group_id = self.group.group_id
        session.add(report)
        for sitting in self.sitting_items:
            sr = domain.SittingReport()
            sr.report = report
            sr.sitting = sitting
            session.add(sr)
        session.flush()

        rpm = zope.securitypolicy.interfaces.IRolePermissionMap(report)
        rpm.grantPermissionToRole(u'zope.View', 'bungeni.Anybody')

        if IGroupSitting.providedBy(self.context):
            back_link = ui_url.absoluteURL(self.context,
                                           self.request) + '/schedule'
        elif ISchedulingContext.providedBy(self.context):
            back_link = ui_url.absoluteURL(self.context, self.request)
        else:
            raise NotImplementedError
        self.request.response.redirect(back_link)
        session.close()
 def chooseName(self, name, obj):
     # flush the object to make sure it contains an id
     session = Session()
     session.add(obj)
     return stringKey(obj)
 def __setitem__( self, name, item ):
     session = Session()
     session.add( item )