예제 #1
0
def queue_time_based_notifications():
    session = Session()
    notification_utl = component.getUtility(INotificationsUtility)
    mq_utility = component.getUtility(IMessageQueueConfig)
    connection = get_mq_connection()
    if not connection:
        return
    channel = connection.channel()
    exchange = str(mq_utility.get_message_exchange())
    notifications = session.query(domain.TimeBasedNotication).filter(
        domain.TimeBasedNotication.notification_date_time <
        datetime.datetime.now()).all()
    for notification in notifications:
        domain_class = notification_utl.get_domain(notification.object_type)
        item = session.query(domain_class).get(notification.object_id)
        if item and item.status == notification.object_status:
            roles = notification_utl.get_time_based_roles(
                domain_class, notification.object_status,
                notification.time_string)
            principal_ids = get_principal_ids(item, roles)
            if principal_ids:
                message = get_message(item, principal_ids)
                message["notification_type"] = "afterstate"
                message["notification_time_string"] = notification.time_string
                dthandler = lambda obj: obj.isoformat() if isinstance(
                    obj, datetime.datetime) else obj
                channel.basic_publish(exchange=exchange,
                                      body=simplejson.dumps(message,
                                                            default=dthandler),
                                      properties=pika.BasicProperties(
                                          content_type="text/plain",
                                          delivery_mode=1),
                                      routing_key="")
        session.delete(notification)
        session.commit()
예제 #2
0
    def delete_subobjects(self):
        """Delete subobjects.

        1) For category maintenance, move the scheduling to the bottom
        of the container.

        2) Delete any discussion items that have been associated to
        this scheduling.
        """
        field = self.request.form['field']
        reorder_form = ItemScheduleReorderForm(self.context, self.request)
        container = copy.copy(removeSecurityProxy(self.context.__parent__))
        subset_query = container.subset_query
        container.subset_query = sql.and_(
            subset_query,
            container.domain_model.planned_order > self.context.planned_order)
        for i in range(len(container) * 2):
            reorder_form.handle_move.success({'mode': 'down', 'field': field})
        container.subset_query = subset_query

        count = 0
        session = Session()
        unproxied = removeSecurityProxy(self.context)
        for key, discussion in unproxied.discussions.items():
            del unproxied.discussions[key]
            session.delete(discussion)
            count += 1
        #session.close()
        return count
예제 #3
0
 def handle_delete(self, action, data):
     session = Session()
     sitting = session.query(domain.GroupSitting).get(data["ids"])
     session.delete(sitting)
     session.commit()
     self.request.response.setHeader('Content-type', 'text/xml')
     return '<data><action type="deleted" sid="'+str(data["ids"])+'" tid="'+str(sitting.sitting_id)+'" /></data>'
예제 #4
0
 def handle_delete(self, action, data):
     session = Session()
     sitting = session.query(domain.GroupSitting).get(data["ids"])
     session.delete(sitting)
     session.commit()
     self.request.response.setHeader('Content-type', 'text/xml')
     return '<data><action type="deleted" sid="' + str(
         data["ids"]) + '" tid="' + str(sitting.sitting_id) + '" /></data>'
예제 #5
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
예제 #6
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
예제 #7
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')
예제 #8
0
 def handle_delete(self, action, data):
     session = Session()
     group_sitting_id = self.context.__parent__.group_sitting_id
     sch = session.query(domain.ItemSchedule).filter(
         sql.and_(
             model_schema.item_schedules.c.group_sitting_id == group_sitting_id,
             model_schema.item_schedules.c.item_id == data['item_id']
         )).all()        
     for i in sch:
         session.delete(i)
     self.request.response.redirect(self.next_url)
예제 #9
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')
예제 #10
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
예제 #11
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()
예제 #12
0
 def handle_delete(self, action, data):
     session = Session()
     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({"sitting_id": sitting.sitting_id, 
                                    "action": "deleted",
                                    "ids": data["ids"]})
         session.delete(sitting)
         session.commit()
         return self.template()
예제 #13
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()
예제 #14
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()
예제 #15
0
 def handle_delete(self, action, data):
     session = Session()
     sitting_id = self.context.__parent__.sitting_id
     sch = (
         session.query(domain.ItemSchedule)
         .filter(
             sql.and_(
                 model_schema.item_schedule.c.sitting_id == sitting_id,
                 model_schema.item_schedule.c.item_id == data["item_id"],
                 model_schema.item_schedule.c.item_type == data["item_type"],
             )
         )
         .all()
     )
     for i in sch:
         session.delete(i)
     self.request.response.redirect(self.next_url)
예제 #16
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()
예제 #17
0
파일: common.py 프로젝트: gelie/bungeni_src
 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()
예제 #18
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()

        # !+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
예제 #19
0
def queue_time_based_notifications():
    session = Session()
    notification_utl = component.getUtility(INotificationsUtility)
    mq_utility = component.getUtility(IMessageQueueConfig)
    connection = get_mq_connection()
    if not connection:
        return
    channel = connection.channel()
    exchange = str(mq_utility.get_message_exchange())
    notifications = session.query(domain.TimeBasedNotication).filter(
        domain.TimeBasedNotication.notification_date_time <
        datetime.datetime.now()).all()
    for notification in notifications:
        domain_class = notification_utl.get_domain(
            notification.object_type)
        item = session.query(domain_class).get(notification.object_id)
        if item and item.status == notification.object_status:
            roles = notification_utl.get_time_based_roles(
                domain_class, notification.object_status,
                notification.time_string)
            principal_ids = get_principal_ids(item, roles)
            if principal_ids:
                message = get_message(item, principal_ids)
                message["notification_type"] = "afterstate"
                message["notification_time_string"] = notification.time_string
                dthandler = lambda obj: obj.isoformat() if isinstance(
                    obj, datetime.datetime) else obj
                channel.basic_publish(
                    exchange=exchange,
                    body=simplejson.dumps(message, default=dthandler),
                    properties=pika.BasicProperties(
                        content_type="text/plain",
                        delivery_mode=1
                    ),
                    routing_key="")
        session.delete(notification)
        session.commit()
예제 #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 = 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()

        # !+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 __delitem__(self, name):
     instance = self[name]
     session = Session()
     session.delete(instance)
예제 #22
0
 def __delitem__(self, name):
     instance = self[name]
     session = Session()
     session.delete(instance)
예제 #23
0
 def handle_update(self, action, data):
     session = Session()
     self.template_data = []
     trusted = removeSecurityProxy(ISchedulingContext(self.context))
     if ("rec_type" in data.keys()) and (data["rec_type"] is not None):
         # updating recurring events - we assume existing events fall
         # at the beginning of the sequence and offer in place update.
         parent_sitting_id = int(data["ids"]) or data["event_pid"]
         length = data["event_length"]
         sitting_length = timedelta(seconds=length)
         base_sitting_length = sitting_length + timedelta(hours=1)
         siblings = (
             session.query(domain.Sitting)
             .filter(
                 or_(
                     domain.Sitting.recurring_id == parent_sitting_id, domain.Sitting.sitting_id == parent_sitting_id
                 )
             )
             .order_by(domain.Sitting.sitting_id)
             .all()
         )
         dates = self.generate_dates(data)
         current_count = len(siblings)
         for count, date in enumerate(dates):
             is_new = not count < current_count
             if is_new:
                 sitting = domain.Sitting()
             else:
                 sitting = siblings[count]
             sitting.start_date = date
             if not count:
                 sitting.end_date = dates[len(dates) - 1] + base_sitting_length
                 sitting.recurring_type = data.get("rec_type")
                 sitting.recurring_id = 0
                 sitting.sitting_length = length
             else:
                 end_date = date + sitting_length
                 sitting.end_date = end_date
                 sitting.sitting_length = int(time.mktime(date.timetuple()))
             # apply changes to parent and siblings new or existing
             sitting.short_name = data.get("short_name", None)
             sitting.venue_id = data["venue"]
             sitting.language = data["language"]
             sitting.activity_type = data.get("activity_type", None)
             sitting.meeting_type = data.get("meeting_type", None)
             sitting.convocation_type = data.get("convocation_type", None)
             if is_new:
                 sitting.group_id = trusted.group_id
                 sitting.recurring_id = parent_sitting_id
                 session.add(sitting)
                 session.flush()
                 notify(ObjectCreatedEvent(sitting))
             else:
                 session.flush()
                 notify(ObjectModifiedEvent(sitting))
             self.template_data.append(
                 {
                     "sitting_id": sitting.sitting_id,
                     "action": (is_new and "inserted" or "updated"),
                     "ids": sitting.sitting_id,
                 }
             )
         # delete any sittings outside recurring bounds
         for del_sibling in siblings[len(dates) :]:
             session.delete(del_sibling)
             del_id = del_sibling.sitting_id
             notify(ObjectRemovedEvent(del_sibling))
             self.template_data.append({"sitting_id": del_id, "action": "deleted", "ids": del_id})
     else:
         sitting_id = int(data["ids"])
         parent_id = data["event_pid"]
         sitting = session.query(domain.Sitting).get(sitting_id)
         if sitting is None:
             sitting = session.query(domain.Sitting).get(parent_id)
         sitting.start_date = data["start_date"].replace(tzinfo=None)
         sitting.end_date = data["end_date"].replace(tzinfo=None)
         sitting.sitting_length = data.get("event_length")
         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)
         session.flush()
         notify(ObjectModifiedEvent(sitting))
         self.template_data.append({"sitting_id": sitting.sitting_id, "action": "updated", "ids": data["ids"]})
     self.request.response.setHeader("Content-type", "text/xml")
     return self.xml_template()