Example #1
0
    def _filter_list_entries(self, query, filters):
        if not filters.get('items'):
            return query
        criteria = []
        if 'status' in filters['items']:
            filtered_statuses = filters['items']['status']
            status_criteria = []
            if 'scheduled' in filtered_statuses:
                status_criteria.append(Contribution.is_scheduled)
            if 'unscheduled' in filtered_statuses:
                status_criteria.append(~Contribution.is_scheduled)
            if status_criteria:
                criteria.append(db.or_(*status_criteria))

        filter_cols = {'session': Contribution.session_id,
                       'track': Contribution.track_id,
                       'type': Contribution.type_id}
        for key, column in filter_cols.iteritems():
            ids = set(filters['items'].get(key, ()))
            if not ids:
                continue
            column_criteria = []
            if None in ids:
                column_criteria.append(column.is_(None))
            if ids - {None}:
                column_criteria.append(column.in_(ids - {None}))
            criteria.append(db.or_(*column_criteria))
        return query.filter(*criteria)
Example #2
0
    def _filter_list_entries(self, query, filters):
        if not filters.get('items'):
            return query
        criteria = []
        if 'state' in filters['items']:
            filtered_states = filters['items']['state']
            state_criteria = []
            for filter_state in filtered_states:
                if filter_state is None:
                    state_criteria.append(
                        ~Contribution._paper_last_revision.has())
                else:
                    state_criteria.append(
                        Contribution._paper_last_revision.has(
                            PaperRevision.state == int(filter_state)))
            if state_criteria:
                criteria.append(db.or_(*state_criteria))

        if 'unassigned' in filters['items']:
            role_map = {
                PaperReviewingRole.judge.value:
                Contribution.paper_judges,
                PaperReviewingRole.content_reviewer.value:
                Contribution.paper_content_reviewers,
                PaperReviewingRole.layout_reviewer.value:
                Contribution.paper_layout_reviewers,
            }
            filtered_roles = map(PaperReviewingRole,
                                 map(int, filters['items']['unassigned']))
            unassigned_criteria = [
                ~role_map[role.value].any() for role in filtered_roles
                if (role == PaperReviewingRole.judge
                    or self.event.cfp.get_reviewing_state(role.review_type))
            ]
            if unassigned_criteria:
                criteria.append(db.or_(*unassigned_criteria))

        filter_cols = {
            'track': Contribution.track_id,
            'session': Contribution.session_id,
            'type': Contribution.type_id
        }
        for key, column in filter_cols.iteritems():
            ids = set(filters['items'].get(key, ()))
            if not ids:
                continue
            column_criteria = []
            if None in ids:
                column_criteria.append(column.is_(None))
            if ids - {None}:
                column_criteria.append(column.in_(ids - {None}))
            criteria.append(db.or_(*column_criteria))

        return query.filter(*criteria)
Example #3
0
def _query_user_tracks(event, user):
    query = Track.query.with_parent(event)
    if user not in event.global_abstract_reviewers and user not in event.global_conveners:
        query = query.filter(
            db.or_(Track.conveners.any(User.id == user.id),
                   Track.abstract_reviewers.any(User.id == user.id)))
    return query
Example #4
0
def get_user_abstracts(event, user):
    """Get the list of abstracts where the user is a reviewer/convener"""
    return (Abstract.query.with_parent(event).options(
        joinedload('reviews'), joinedload('person_links')).filter(
            db.or_(
                Abstract.submitter == user,
                Abstract.person_links.any(
                    AbstractPersonLink.person.has(user=user)))).order_by(
                        Abstract.friendly_id).all())
Example #5
0
    def _filter_list_entries(self, query, filters):
        if not (filters.get('fields') or filters.get('items')):
            return query
        field_types = {
            str(f.id): f.field_impl
            for f in self.regform.form_items
            if f.is_field and not f.is_deleted and (
                f.parent_id is None or not f.parent.is_deleted)
        }
        field_filters = {
            field_id: data_list
            for field_id, data_list in filters['fields'].iteritems()
            if field_id in field_types
        }
        if not field_filters and not filters['items']:
            return query
        criteria = [
            db.and_(RegistrationFormFieldData.field_id == field_id,
                    field_types[field_id].create_sql_filter(data_list))
            for field_id, data_list in field_filters.iteritems()
        ]
        items_criteria = []
        if 'checked_in' in filters['items']:
            checked_in_values = filters['items']['checked_in']
            # If both values 'true' and 'false' are selected, there's no point in filtering
            if len(checked_in_values) == 1:
                items_criteria.append(
                    Registration.checked_in == bool(int(checked_in_values[0])))

        if 'state' in filters['items']:
            states = [
                RegistrationState(int(state))
                for state in filters['items']['state']
            ]
            items_criteria.append(Registration.state.in_(states))

        if field_filters:
            subquery = (RegistrationData.query.with_entities(
                db.func.count(RegistrationData.registration_id)
            ).join(RegistrationData.field_data).filter(
                RegistrationData.registration_id == Registration.id).filter(
                    db.or_(*criteria)).correlate(Registration).as_scalar())
            query = query.filter(subquery == len(field_filters))
        return query.filter(db.or_(*items_criteria))
Example #6
0
def get_not_deletable_templates(obj):
    """Get all non-deletable templates for an event/category"""

    not_deletable_criteria = [
        DesignerTemplate.is_system_template,
        DesignerTemplate.backside_template_of != None,  # noqa
        DesignerTemplate.ticket_for_regforms.any(
            RegistrationForm.event.has(Event.ends_after(now_utc())))
    ]
    return set(
        DesignerTemplate.query.filter(DesignerTemplate.owner == obj,
                                      db.or_(*not_deletable_criteria)))
Example #7
0
 def visible_categories_cte(self):
     """
     Get a sqlalchemy select for the visible categories within
     this category, including the category itself.
     """
     cte_query = (select([
         Category.id, literal(0).label('level')
     ]).where((Category.id == self.id) & (Category.visibility.is_(None)
                                          | (Category.visibility > 0))).cte(
                                              'visibility_chain',
                                              recursive=True))
     parent_query = (select([Category.id, cte_query.c.level + 1]).where(
         db.and_(
             Category.parent_id == cte_query.c.id,
             db.or_(Category.visibility.is_(None),
                    Category.visibility > cte_query.c.level + 1))))
     return cte_query.union_all(parent_query)
Example #8
0
def get_events_with_paper_roles(user, dt=None):
    """
    Get the IDs and PR roles of events where the user has any kind
    of paper reviewing privileges.

    :param user: A `User`
    :param dt: Only include events taking place on/after that date
    :return: A dict mapping event IDs to a set of roles
    """
    paper_roles = {'paper_manager', 'paper_judge', 'paper_content_reviewer', 'paper_layout_reviewer'}
    role_criteria = [EventPrincipal.has_management_role(role, explicit=True) for role in paper_roles]
    query = (user.in_event_acls
             .join(Event)
             .options(noload('user'), noload('local_group'), load_only('event_id', 'roles'))
             .filter(~Event.is_deleted, Event.ends_after(dt))
             .filter(db.or_(*role_criteria)))
    return {principal.event_id: set(principal.roles) & paper_roles for principal in query}
    def _filter_by_sessions(self, session_ids, added_since):
        sid_query = Contribution.session_id.in_(set(session_ids))
        session_query = db.and_(
            AttachmentFolder.link_type == LinkType.session,
            AttachmentFolder.session.has(
                Session.id.in_(session_ids) & ~Session.is_deleted))
        contrib_query = db.and_(
            AttachmentFolder.link_type == LinkType.contribution,
            AttachmentFolder.contribution.has(sid_query
                                              & ~Contribution.is_deleted))
        subcontrib_query = db.and_(
            AttachmentFolder.link_type == LinkType.subcontribution,
            AttachmentFolder.subcontribution.has(sid_query
                                                 & ~SubContribution.is_deleted
                                                 & ~Contribution.is_deleted))

        return self._build_base_query(added_since).filter(
            db.or_(session_query, contrib_query, subcontrib_query)).all()
Example #10
0
 def get_members(self):
     from fossir.modules.users.models.users import User
     if self.group is None:
         warn('Tried to get members for invalid group {}'.format(self))
         return set()
     # We actually care about Users, not identities here!
     emails = set()
     identifiers = set()
     for identity_info in self.group:
         identifiers.add(identity_info.identifier)
         emails |= {x.lower() for x in identity_info.data.getlist('email') if x}
     if not identifiers and not emails:
         return set()
     return set(User.query.outerjoin(Identity).filter(
         ~User.is_deleted,
         db.or_(
             User.all_emails.contains(db.func.any(list(emails))),
             db.and_(
                 Identity.provider == self.provider,
                 Identity.identifier.in_(identifiers)
             )
         )))
Example #11
0
 def __init__(self, edit=False, *args, **kwargs):
     abstract = kwargs.pop('abstract')
     super(AbstractReviewForm, self).__init__(*args, **kwargs)
     self.event = abstract.event
     if not edit:
         self.proposed_action.none = _("Propose an action...")
     self.proposed_related_abstract.excluded_abstract_ids = {abstract.id}
     self.proposed_contribution_type.query = (
         ContributionType.query.with_parent(self.event).order_by(
             ContributionType.name))
     if not self.proposed_contribution_type.query.count():
         del self.proposed_contribution_type
     reviewed_for_track_ids = {t.id for t in abstract.reviewed_for_tracks}
     existing_prop_track_cond = (Track.id.in_(
         t.id for t in self.proposed_tracks.object_data)
                                 if self.proposed_tracks.object_data else
                                 False)
     self.proposed_tracks.query = (Track.query.with_parent(
         self.event).filter(
             db.or_(Track.id.notin_(reviewed_for_track_ids),
                    existing_prop_track_cond)).order_by(Track.position))
     if not self.proposed_tracks.query.count():
         del self.proposed_tracks
         self.proposed_action.skip.add(AbstractAction.change_tracks)
Example #12
0
    def _filter_list_entries(self, query, filters):
        criteria = []
        field_filters = filters.get('fields')
        item_filters = filters.get('items')
        extra_filters = filters.get('extra')

        if not (field_filters or item_filters or extra_filters):
            return query

        if field_filters:
            for contribution_type_id, field_values in field_filters.iteritems(
            ):
                criteria.append(
                    Abstract.field_values.any(
                        db.and_(
                            AbstractFieldValue.contribution_field_id ==
                            contribution_type_id,
                            AbstractFieldValue.data.op('#>>')('{}').in_(
                                field_values))))

        if item_filters:
            static_filters = {
                'accepted_track': Abstract.accepted_track_id,
                'accepted_contrib_type': Abstract.accepted_contrib_type_id,
                'submitted_contrib_type': Abstract.submitted_contrib_type_id,
                'submitted_for_tracks': Abstract.submitted_for_tracks,
                'reviewed_for_tracks': Abstract.reviewed_for_tracks
            }
            for key, column in static_filters.iteritems():
                ids = set(item_filters.get(key, ()))
                if not ids:
                    continue
                column_criteria = []
                if '_for_tracks' in key:
                    if None in ids:
                        column_criteria.append(~column.any())
                        ids.discard(None)
                    if ids:
                        column_criteria.append(column.any(Track.id.in_(ids)))
                else:
                    if None in ids:
                        column_criteria.append(column.is_(None))
                        ids.discard(None)
                    if ids:
                        column_criteria.append(column.in_(ids))
                criteria.append(db.or_(*column_criteria))
            if 'state' in item_filters:
                states = [
                    AbstractState(int(state))
                    for state in item_filters['state']
                ]
                criteria.append(Abstract.state.in_(states))
        if extra_filters:
            if extra_filters.get('multiple_tracks'):
                submitted_for_count = (db.select(
                    [db.func.count()]).as_scalar().where(
                        Abstract.submitted_for_tracks.prop.primaryjoin))
                criteria.append(submitted_for_count > 1)
            if extra_filters.get('comments'):
                criteria.append(Abstract.submission_comment != '')
        return query.filter(db.and_(*criteria))
Example #13
0
def get_non_inheriting_objects(root):
    """Get a set of child objects that do not inherit protection

    :param root: An event object (`Event`, `Session`, `Contribution`
                 or `AttachmentFolder`) which may contain objects
                 with a different protection.
    """
    def _query_folders(obj, crit):
        return (db.m.AttachmentFolder.query.filter_by(
            event=obj.event,
            is_deleted=False).filter(crit).options(joinedload('attachments')))

    def _process_attachments(folders):
        for folder in folders:
            if not folder.is_inheriting:
                yield folder
            for attachment in folder.attachments:
                if not attachment.is_inheriting:
                    yield attachment

    if isinstance(root, db.m.Event):
        # For an event we check sessions, contributions and ALL attachments no matter where
        for sess in db.m.Session.query.with_parent(root).filter(
                ~db.m.Session.is_inheriting):
            yield _ProtectedObjectWrapper(sess)
        for contrib in db.m.Contribution.query.with_parent(root).filter(
                ~db.m.Contribution.is_inheriting):
            yield _ProtectedObjectWrapper(contrib)
        query = (root.all_attachment_folders.filter_by(
            is_deleted=False).options(joinedload('attachments')))
        for obj in _process_attachments(query):
            yield _ProtectedObjectWrapper(obj)

    elif isinstance(root, db.m.Session):
        # For a session we check contributions and attachments within the session
        crit = db.or_(
            # attached to the session
            db.m.AttachmentFolder.object == root,
            # attached to a contribution in the session
            db.and_(
                db.m.AttachmentFolder.link_type == LinkType.contribution,
                db.m.AttachmentFolder.contribution.has(
                    db.and_(db.m.Contribution.session == root,
                            ~db.m.Contribution.is_deleted))),
            # attached to a subcontribution in a contribution in the session
            db.and_(
                db.m.AttachmentFolder.link_type == LinkType.subcontribution,
                db.m.AttachmentFolder.subcontribution.has(
                    db.and_(
                        ~db.m.SubContribution.is_deleted,
                        db.m.SubContribution.contribution.has(
                            db.and_(db.m.Contribution.session == root,
                                    ~db.m.Contribution.is_deleted))))))
        for obj in _process_attachments(_query_folders(root, crit)):
            yield _ProtectedObjectWrapper(obj)
        for contrib in root.contributions:
            if not contrib.is_inheriting:
                yield _ProtectedObjectWrapper(contrib)

    elif isinstance(root, db.m.Contribution):
        # For a contribution we check attachments and subcontrib attachments
        crit = db.or_(
            # attached to the contribution
            db.m.AttachmentFolder.object == root,
            # attached to a subcontribution of the contribution
            db.and_(
                db.m.AttachmentFolder.link_type == LinkType.subcontribution,
                db.m.AttachmentFolder.subcontribution.has(
                    db.and_(db.m.SubContribution.contribution == root,
                            ~db.m.SubContribution.is_deleted))))
        for obj in _process_attachments(_query_folders(root, crit)):
            yield _ProtectedObjectWrapper(obj)

    elif isinstance(root, db.m.AttachmentFolder):
        # For an attachment folder we only check attachments in there
        for attachment in root.attachments:
            if not attachment.is_inheriting:
                yield _ProtectedObjectWrapper(attachment)

    else:
        raise TypeError('Unexpected object of type {}: {}'.format(
            type(root).__name__, root))
Example #14
0
def get_user_submittable_contributions(event, user):
    criteria = [Contribution._paper_last_revision == None,  # noqa
                Contribution._paper_last_revision.has(PaperRevision.state == PaperRevisionState.to_be_corrected)]
    return (_query_contributions_with_user_paper_submission_rights(event, user)
            .filter(db.or_(*criteria))
            .all())
Example #15
0
def _query_contributions_with_user_paper_submission_rights(event, user):
    criteria = [Contribution.person_links.any(ContributionPersonLink.person.has(user=user)),
                Contribution.abstract.has(Abstract.submitter_id == user.id)]
    return Contribution.query.with_parent(event).filter(db.or_(*criteria))
Example #16
0
def _query_contributions_with_user_as_reviewer(event, user):
    query = Contribution.query.with_parent(event)
    query = query.filter(db.or_(Contribution.paper_content_reviewers.any(User.id == user.id),
                                Contribution.paper_layout_reviewers.any(User.id == user.id)),
                         Contribution._paper_revisions.any())
    return query