Ejemplo n.º 1
0
  def reviewPost(self, request, context, params, entity, form,
                 org_admin, mentor, **kwargs):
    """Handles the POST request for the proposal review view.

    Args:
        entity: the student proposal entity
        form: the form to use in this view
        org_admin: org admin entity for the current user/proposal (iff available)
        mentor: mentor entity for the current user/proposal (iff available)
        rest: see base.View.public()
    """

    from soc.modules.gsoc.tasks.proposal_review import run_create_review_for

    post_dict = request.POST

    if post_dict.get('subscribe') or post_dict.get('unsubscribe'):
      self._handleSubscribePost(request, entity)
      return http.HttpResponseRedirect('')
    elif post_dict.get('want_mentor'):
      # Check if the current user is a mentor
      if mentor:
        self._adjustPossibleMentors(entity, mentor)
      return http.HttpResponseRedirect('')
    elif post_dict.get('ineligble'):
      self._handleIneligiblePost(request, entity)

      redirect = redirects.getListProposalsRedirect(
          entity.org, {'url_name': 'gsoc/org'})
      return http.HttpResponseRedirect(redirect)

    # populate the form using the POST data
    form = form(post_dict)

    if not form.is_valid():
      # return the invalid form response
      # get all the extra information that should be in the context
      review_context = self._getDefaultReviewContext(entity, org_admin, mentor)
      context = dicts.merge(context, review_context)

      return self._constructResponse(request, entity=entity, context=context,
          form=form, params=params, template=params['review_template'])

    fields = form.cleaned_data
    user = user_logic.logic.getCurrentUser()
    # Adjust mentor if necessary
    # NOTE: it cannot be put in the same transaction with student_proposal 
    # since they are not in the same entity group
    if org_admin and 'org_admin_action' in request.POST:
      prev_mentor = entity.mentor.key() if entity.mentor else None
      # org admin found, try to adjust the assigned mentor
      self._adjustMentor(entity, fields['mentor'])
      current_mentor = entity.mentor.key() if entity.mentor else None
      mentor_changed = False
      if prev_mentor != current_mentor:
        mentor_name = entity.mentor.name() if entity.mentor else 'None'
        mentor_changed = True
    # try to see if the rank is given and adjust the given_score if needed
    # NOTE: it cannot be put in the same transaction with student_proposal 
    # since they are not in the same entity group
    rank = fields['rank']
    if rank:
      ranker = self._logic.getRankerFor(entity)
      # if a very high rank is filled in use the highest 
      # one that returns a score
      rank = min(ranker.TotalRankedScores(), rank)
      # ranker uses zero-based ranking
      (scores, _) = ranker.FindScore(rank-1)
      # since we only use one score we need it out of the list with scores
      score_at_rank = scores[0]

    # Update student_proposal, rank and review within one transaction
    def txn():
      given_score = fields.get('score')
      # Doing this instead of get('score',0) because fields.get does not use the
      # default argument for u''.
      given_score = int(given_score) if given_score else 0

      is_public = fields['public']

      comment = fields.get('comment')
      comment = comment if comment else ''

      # Reload entity in case that it has changed
      current_entity = db.get(entity.key())

      if org_admin and 'org_admin_action' in request.POST:
        # admin actions are not public, so force private comment
        is_public = False

        if mentor_changed:
          comment = '%s Changed mentor to %s.' %(comment, mentor_name)

        # try to see if the rank is given and adjust the given_score if needed
        if rank:
          # calculate the score that should be given to end up at the given rank
          # give +1 to make sure that in the case of a tie they end up top
          given_score = score_at_rank - current_entity.score + 1
          comment = '%s Proposal has been set to rank %i.' %(comment, rank)

      # store the properties to update the proposal with
      properties = {}

      if (org_admin or mentor) and (not is_public) and (given_score is not 0):
        # if it is not a public comment and it's made by a member of the
        # organization we update the score of the proposal
        new_score = given_score + current_entity.score
        properties = {'score': new_score}

      if comment or (given_score is not 0):
        # if the proposal is new we change it status to pending
        if current_entity.status == 'new':
          properties['status'] = 'pending'

        # create a review for current_entity using taskqueue
        run_create_review_for(current_entity, comment, given_score, 
                              is_public, user, self._params)
      if properties.values():
        # there is something to update
        self._logic.updateEntityProperties(current_entity, properties)

    db.run_in_transaction(txn)
    # Inform users that review may not appear immediately
    self._show_review_not_appeared_msg = True
    # redirect to the same page
    return http.HttpResponseRedirect('')
Ejemplo n.º 2
0
    def _getExtraMenuItems(self, role_description, params=None):
        """Used to create the specific Organization menu entries.

    For args see group.View._getExtraMenuItems().
    """
        submenus = []

        group_entity = role_description['group']
        program_entity = group_entity.scope
        roles = role_description['roles']

        mentor_entity = roles.get('mentor')
        admin_entity = roles.get('org_admin')

        is_active_mentor = mentor_entity and mentor_entity.status == 'active'
        is_active_admin = admin_entity and admin_entity.status == 'active'

        if admin_entity or mentor_entity:
            # add a link to view all the student proposals
            submenu = (redirects.getListProposalsRedirect(
                group_entity,
                params), "View all Student Proposals", 'any_access')
            submenus.append(submenu)

        if admin_entity:
            # add a link to manage student projects after they have been announced
            if timeline_helper.isAfterEvent(
                    program_entity.timeline,
                    'accepted_students_announced_deadline'):
                submenu = (redirects.getManageOverviewRedirect(
                    group_entity, {'url_name': 'gsoc/student_project'}),
                           "Manage Student Projects", 'any_access')
                submenus.append(submenu)

        if is_active_admin:
            # add a link to the management page
            submenu = (redirects.getListRolesRedirect(group_entity, params),
                       "Manage Admins and Mentors", 'any_access')
            submenus.append(submenu)

            # add a link to invite an org admin
            submenu = (redirects.getInviteRedirectForRole(
                group_entity,
                'gsoc/org_admin'), "Invite an Admin", 'any_access')
            submenus.append(submenu)

            # add a link to invite a member
            submenu = (redirects.getInviteRedirectForRole(
                group_entity, 'gsoc/mentor'), "Invite a Mentor", 'any_access')
            submenus.append(submenu)

            # add a link to the request page
            submenu = (redirects.getListRequestsRedirect(group_entity, params),
                       "List Requests and Invites", 'any_access')
            submenus.append(submenu)

            # add a link to the edit page
            submenu = (redirects.getEditRedirect(group_entity, params),
                       "Edit Organization Profile", 'any_access')
            submenus.append(submenu)

        if is_active_admin or is_active_mentor:
            submenu = (redirects.getCreateDocumentRedirect(
                group_entity, params['document_prefix']),
                       "Create a New Document", 'any_access')
            submenus.append(submenu)

            submenu = (redirects.getListDocumentsRedirect(
                group_entity,
                params['document_prefix']), "List Documents", 'any_access')
            submenus.append(submenu)

        if is_active_admin:
            # add a link to the resign page
            submenu = (redirects.getManageRedirect(
                roles['org_admin'], {'url_name': 'gsoc/org_admin'}),
                       "Resign as Admin", 'any_access')
            submenus.append(submenu)

            # add a link to the edit page
            submenu = (redirects.getEditRedirect(
                roles['org_admin'], {'url_name': 'gsoc/org_admin'}),
                       "Edit My Admin Profile", 'any_access')
            submenus.append(submenu)

        if is_active_mentor:
            # add a link to the resign page
            submenu = (redirects.getManageRedirect(
                roles['mentor'],
                {'url_name': 'gsoc/mentor'}), "Resign as Mentor", 'any_access')
            submenus.append(submenu)

            # add a link to the edit page
            submenu = (redirects.getEditRedirect(roles['mentor'],
                                                 {'url_name': 'gsoc/mentor'}),
                       "Edit My Mentor Profile", 'any_access')
            submenus.append(submenu)

        return submenus
Ejemplo n.º 3
0
  def _getExtraMenuItems(self, role_description, params=None):
    """Used to create the specific Organization menu entries.

    For args see group.View._getExtraMenuItems().
    """
    submenus = []

    group_entity = role_description['group']
    program_entity = group_entity.scope
    roles = role_description['roles']

    if roles.get('org_admin') or roles.get('mentor'):
      # add a link to view all the student proposals
      submenu = (redirects.getListProposalsRedirect(group_entity, params),
          "View all Student Proposals", 'any_access')
      submenus.append(submenu)


    if roles.get('org_admin'):
      # add a link to manage student projects after they have been announced
      if timeline_helper.isAfterEvent(program_entity.timeline,
                                     'accepted_students_announced_deadline'):
        submenu = (redirects.getManageOverviewRedirect(group_entity,
            {'url_name': 'student_project'}),
            "Manage Student Projects", 'any_access')
        submenus.append(submenu)

      # add a link to the management page
      submenu = (redirects.getListRolesRedirect(group_entity, params),
          "Manage Admins and Mentors", 'any_access')
      submenus.append(submenu)

      # add a link to invite an org admin
      submenu = (redirects.getInviteRedirectForRole(group_entity, 'org_admin'),
          "Invite an Admin", 'any_access')
      submenus.append(submenu)

      # add a link to invite a member
      submenu = (redirects.getInviteRedirectForRole(group_entity, 'mentor'),
          "Invite a Mentor", 'any_access')
      submenus.append(submenu)

      # add a link to the request page
      submenu = (redirects.getListRequestsRedirect(group_entity, params),
          "List Requests and Invites", 'any_access')
      submenus.append(submenu)

      # add a link to the edit page
      submenu = (redirects.getEditRedirect(group_entity, params),
          "Edit Organization Profile", 'any_access')
      submenus.append(submenu)

    if roles.get('org_admin') or roles.get('mentor'):
      submenu = (redirects.getCreateDocumentRedirect(group_entity, 'org'),
          "Create a New Document", 'any_access')
      submenus.append(submenu)

      submenu = (redirects.getListDocumentsRedirect(group_entity, 'org'),
          "List Documents", 'any_access')
      submenus.append(submenu)


    if roles.get('org_admin'):
      # add a link to the resign page
      submenu = (redirects.getManageRedirect(roles['org_admin'],
          {'url_name': 'org_admin'}),
          "Resign as Admin", 'any_access')
      submenus.append(submenu)

      # add a link to the edit page
      submenu = (redirects.getEditRedirect(roles['org_admin'],
          {'url_name': 'org_admin'}),
          "Edit My Admin Profile", 'any_access')
      submenus.append(submenu)


    if roles.get('mentor'):
      # add a link to the resign page
      submenu = (redirects.getManageRedirect(roles['mentor'],
          {'url_name' : 'mentor'}),
          "Resign as Mentor", 'any_access')
      submenus.append(submenu)

      # add a link to the edit page
      submenu = (redirects.getEditRedirect(roles['mentor'],
          {'url_name': 'mentor'}),
          "Edit My Mentor Profile", 'any_access')
      submenus.append(submenu)

    return submenus
Ejemplo n.º 4
0
  def reviewGet(self, request, context, params, entity, form,
                 org_admin, mentor, **kwargs):
    """Handles the GET request for the proposal review view.

    Args:
        entity: the student proposal entity
        form: the form to use in this view
        org_admin: org admin entity for the current user/proposal (iff available)
        mentor: mentor entity for the current user/proposal (iff available)
        rest: see base.View.public()
    """

    from soc.logic.models.review_follower import logic as review_follower_logic

    get_dict = request.GET

    # check if the current user is a mentor and wants 
    # to change his role for this app
    choice = get_dict.get('mentor')
    if mentor and choice:
      self._adjustPossibleMentors(entity, mentor, choice)

    ineligible = get_dict.get('ineligible')

    if org_admin:
      reviewer = org_admin
    elif mentor:
      reviewer = mentor

    if (org_admin or mentor) and (ineligible != None) and (
        entity.status not in ['accepted', 'rejected']):
      ineligible = int(ineligible)
      if ineligible == 1:
        # mark the proposal invalid and return to the list
        properties = {'status': 'invalid'}
        self._logic.updateEntityProperties(entity, properties)

        redirect = redirects.getListProposalsRedirect(entity.org,
                                                      {'url_name': 'org'})
        comment = "Marked Student Proposal as Ineligible."
        self._createReviewFor(entity, reviewer, comment, is_public=False)
        return http.HttpResponseRedirect(redirect)
      elif ineligible == 0:
        # mark the proposal as new and return to the list
        properties = {'status': 'new'}
        self._logic.updateEntityProperties(entity, properties)

        redirect = redirects.getListProposalsRedirect(entity.org,
                                                      {'url_name': 'org'})
        comment = "Marked Student Proposal as Eligible."
        self._createReviewFor(entity, reviewer, comment, is_public=False)
        return http.HttpResponseRedirect(redirect)

    # check if we should change the subscription state for the current user
    public_subscription = None
    private_subscription = None

    if get_dict.get('public_subscription') and (
      get_dict['public_subscription'] in ['on', 'off']):

      public_subscription = get_dict['public_subscription'] == 'on'

    if get_dict.get('private_subscription') and (
      get_dict['private_subscription'] in ['on', 'off']):
      private_subscription = get_dict['private_subscription'] == 'on'

    if public_subscription != None or private_subscription != None:
      # get the current user
      user_entity = user_logic.logic.getForCurrentAccount()

      # create the fields that should be in the ReviewFollower entity
      fields = {'link_id': user_entity.link_id,
                'scope': entity,
                'scope_path': entity.key().id_or_name(),
                'user': user_entity
               }
      # get the keyname for the ReviewFollower entity
      key_name = review_follower_logic.getKeyNameFromFields(fields)

      # determine which subscription properties we should change
      if public_subscription != None:
        fields['subscribed_public'] = public_subscription

      if private_subscription != None:
        fields['subscribed_private'] = private_subscription

      # update the ReviewFollower
      review_follower_logic.updateOrCreateFromKeyName(fields, key_name)

    # set the initial score since the default is ignored
    initial = {'score': 0}

    if org_admin and entity.mentor:
      # set the mentor field to the current mentor
      initial['mentor'] = entity.mentor.link_id

    context['form'] = form(initial)

    # create the special form for mentors
    comment_public = ['public', 'comment']
    comment_private = ['score']
    comment_admin = ['rank', 'mentor']
    class FilterForm(object):
      """Helper class used for form filtering.
      """
      def __init__(self, form, fields):
        self.__form = form
        self.__fields = fields

      @property
      def fields(self):
        """Property that returns all fields as dictionary."""
        fields = self.__form.fields.iteritems()
        return dict([(k, i) for k, i in fields if k in self.__fields])

      def __iter__(self):
        for field in self.__form:
          if field.name not in self.__fields:
            continue
          yield field

      _marker = []
      def __getattr__(self, key, default=_marker):
        if default is self._marker:
          return getattr(self.__form, key)
        else:
          return getattr(self.__form, key, default)

    context['form'] = form(initial)
    context['comment_public'] = FilterForm(context['form'], comment_public)
    context['comment_private'] = FilterForm(context['form'], comment_private)
    context['comment_admin'] = FilterForm(context['form'], comment_admin)

    # get all the extra information that should be in the context
    review_context = self._getDefaultReviewContext(entity, org_admin, mentor)
    context = dicts.merge(context, review_context)

    template = params['review_template']

    return responses.respond(request, template, context=context)
Ejemplo n.º 5
0
    def reviewGet(self, request, context, params, entity, form, org_admin,
                  mentor, **kwargs):
        """Handles the GET request for the proposal review view.

    Args:
        entity: the student proposal entity
        form: the form to use in this view
        org_admin: org admin entity for the current user/proposal (iff available)
        mentor: mentor entity for the current user/proposal (iff available)
        rest: see base.View.public()
    """

        from soc.modules.gsoc.logic.models.review_follower import logic as \
            review_follower_logic

        get_dict = request.GET

        # check if the current user is a mentor and wants
        # to change his role for this app
        choice = get_dict.get('mentor')
        if mentor and choice:
            self._adjustPossibleMentors(entity, mentor, choice)

        ineligible = get_dict.get('ineligible')

        if (org_admin or mentor) and (ineligible != None) and (
                entity.status not in ['accepted', 'rejected']):
            ineligible = int(ineligible)
            if ineligible == 1:
                # mark the proposal invalid and return to the list
                properties = {'status': 'invalid'}
                self._logic.updateEntityProperties(entity, properties)

                redirect = redirects.getListProposalsRedirect(
                    entity.org, {'url_name': 'org'})
                comment = "Marked Student Proposal as Ineligible."
                self._createReviewFor(entity, comment, is_public=False)
                return http.HttpResponseRedirect(redirect)
            elif ineligible == 0:
                # mark the proposal as new and return to the list
                properties = {'status': 'new'}
                self._logic.updateEntityProperties(entity, properties)

                redirect = redirects.getListProposalsRedirect(
                    entity.org, {'url_name': 'org'})
                comment = "Marked Student Proposal as Eligible."
                self._createReviewFor(entity, comment, is_public=False)
                return http.HttpResponseRedirect(redirect)

        # check if we should change the subscription state for the current user
        public_subscription = None
        private_subscription = None

        if get_dict.get('public_subscription') and (
                get_dict['public_subscription'] in ['on', 'off']):

            public_subscription = get_dict['public_subscription'] == 'on'

        if get_dict.get('private_subscription') and (
                get_dict['private_subscription'] in ['on', 'off']):
            private_subscription = get_dict['private_subscription'] == 'on'

        if public_subscription != None or private_subscription != None:
            # get the current user
            user_entity = user_logic.logic.getForCurrentAccount()

            # create the fields that should be in the ReviewFollower entity
            # pylint: disable-msg=E1103
            fields = {
                'link_id': user_entity.link_id,
                'scope': entity,
                'scope_path': entity.key().id_or_name(),
                'user': user_entity
            }
            # get the keyname for the ReviewFollower entity
            key_name = review_follower_logic.getKeyNameFromFields(fields)

            # determine which subscription properties we should change
            if public_subscription != None:
                fields['subscribed_public'] = public_subscription

            if private_subscription != None:
                fields['subscribed_private'] = private_subscription

            # update the ReviewFollower
            review_follower_logic.updateOrCreateFromKeyName(fields, key_name)

        # set the initial score since the default is ignored
        initial = {'score': 0}

        context['form'] = form(initial)

        # create the special form for mentors
        comment_public = ['public', 'comment']
        comment_private = ['score']
        comment_admin = ['rank', 'mentor']

        class FilterForm(object):
            """Helper class used for form filtering.
      """
            def __init__(self, form, fields):
                self.__form = form
                self.__fields = fields

            @property
            def fields(self):
                """Property that returns all fields as dictionary."""
                fields = self.__form.fields.iteritems()
                return dict([(k, i) for k, i in fields if k in self.__fields])

            def __iter__(self):
                for field in self.__form:
                    if field.name not in self.__fields:
                        continue
                    yield field

            _marker = []

            def __getattr__(self, key, default=_marker):
                if default is self._marker:
                    return getattr(self.__form, key)
                else:
                    return getattr(self.__form, key, default)

        context['form'] = form(initial)
        context['comment_public'] = FilterForm(context['form'], comment_public)
        context['comment_private'] = FilterForm(context['form'],
                                                comment_private)
        context['comment_admin'] = FilterForm(context['form'], comment_admin)

        # get all the extra information that should be in the context
        review_context = self._getDefaultReviewContext(entity, org_admin,
                                                       mentor)
        context = dicts.merge(context, review_context)

        template = params['review_template']

        return responses.respond(request, template, context=context)