Пример #1
0
    def submitFormsGet(self, request, params, template, context, entity):
        if lists.isJsonRequest(request):
            url = blobstore.create_upload_url(gci_redirects.getSubmitFormsRedirect(entity, params))
            return responses.jsonResponse(request, url)

        def setForm(param_name, blob_info):
            add_form, edit_form = params[param_name]

            if blob_info:
                form = edit_form(
                    initial={
                        "name": '<a href="%(url)s">%(name)s</a>'
                        % {
                            "name": blob_info.filename,
                            "url": redirects.getDownloadBlobRedirectWithGet(
                                blob_info, params, scope_path=entity.key().id_or_name(), type=param_name
                            ),
                        },
                        "size": defaultfilters.filesizeformat(blob_info.size),
                        "uploaded": blob_info.creation.strftime(self.DATETIME_FORMAT),
                    }
                )
            else:
                form = add_form()

            context[param_name] = form

        setForm("consent_form_upload_form", entity.consent_form)
        setForm("consent_form_two_upload_form", entity.consent_form_two)
        setForm("student_id_form_upload_form", entity.student_id_form)

        return responses.respond(request, template, context)
Пример #2
0
    def process_exception(self, request, exception):
        """Called when an uncaught exception is raised.

    See the Django middleware documentation for an explanation of
    the method signature.
    """

        template = None
        context = responses.getUniversalContext(request)

        if isinstance(exception, DeadlineExceededError):
            template = 'soc/deadline_exceeded.html'
        if isinstance(exception, MemoryError):
            template = 'soc/memory_error.html'
        if isinstance(exception, AssertionError):
            template = 'soc/assertion_error.html'
        if isinstance(exception, out_of_band.Error):
            return responses.errorResponse(exception, request)

        if template:
            logging.exception(exception)
            return responses.respond(request, template, context=context)

        # let Django handle it
        return None
Пример #3
0
  def visualize(self, request, access_type, page_name=None, params=None,
                **kwargs):
    """Visualization view for a statistic specified in request params.
    """

    link_id = kwargs['link_id']
    scope_path = kwargs['scope_path']
    logic = params['logic']

    statistic = self._getStatisticEntity(link_id, scope_path, logic)

    context = responses.getUniversalContext(request)

    if not logic.checkIfStatisticReady(statistic):
      template = 'soc/error.html'
      context['message'] = self.DEF_NO_VISUALIZATION_MSG_FMT % (statistic.name)
    else:
      responses.useJavaScript(context, params['js_uses_all'])
      context['entity'] = statistic
      context['page_name'] = "Statistic visualization"
      context['link_id'] = statistic.link_id
      context['scope_path'] = statistic.scope_path
      context['visualization_types'] = logic.getVisualizationTypesJson(statistic)

      template = 'soc/statistic/show.html'

    return responses.respond(request, template, context)
Пример #4
0
    def visualize(self,
                  request,
                  access_type,
                  page_name=None,
                  params=None,
                  **kwargs):
        """Visualization view for a statistic specified in request params.
    """

        link_id = kwargs['link_id']
        scope_path = kwargs['scope_path']
        logic = params['logic']

        statistic = self._getStatisticEntity(link_id, scope_path, logic)

        context = responses.getUniversalContext(request)

        if not logic.checkIfStatisticReady(statistic):
            template = 'soc/error.html'
            context['message'] = self.DEF_NO_VISUALIZATION_MSG_FMT % (
                statistic.name)
        else:
            responses.useJavaScript(context, params['js_uses_all'])
            context['entity'] = statistic
            context['page_name'] = "Statistic visualization"
            context['link_id'] = statistic.link_id
            context['scope_path'] = statistic.scope_path
            context['visualization_types'] = logic.getVisualizationTypesJson(
                statistic)

            template = 'soc/statistic/show.html'

        return responses.respond(request, template, context)
Пример #5
0
    def _editRecordGet(self, request, params, context, template,
                       record_entity):
        """Handles the GET request for editing a GradingRecord.
    Args:
      request: a Django Request object
      params: the params for this view
      context: the context for the webpage
      template: the location of the template used for this view
      record_entity: a GradingRecord entity
    """

        survey_group_logic = params['logic']
        record_logic = survey_group_logic.getRecordLogic()

        get_dict = request.GET

        if get_dict.get('update'):
            # try to update this record
            properties = record_logic.getFieldsForGradingRecord(
                record_entity.project, record_entity.grading_survey_group,
                record_entity)
            record_logic.updateEntityProperties(record_entity, properties)

        form = params['record_edit_form'](instance=record_entity)
        context['form'] = form

        return responses.respond(request, template, context)
Пример #6
0
  def _editRecordGet(self, request, params, context, template, record_entity):
    """Handles the GET request for editing a GradingRecord.
    Args:
      request: a Django Request object
      params: the params for this view
      context: the context for the webpage
      template: the location of the template used for this view
      record_entity: a GradingRecord entity
    """

    survey_group_logic = params['logic']
    record_logic = survey_group_logic.getRecordLogic()

    get_dict = request.GET

    if get_dict.get('update'):
      # try to update this record
      properties = record_logic.getFieldsForGradingRecord(
          record_entity.project, record_entity.grading_survey_group,
          record_entity)
      record_logic.updateEntityProperties(record_entity, properties)

    form = params['record_edit_form'](instance=record_entity)
    context['form'] = form

    return responses.respond(request, template, context)
Пример #7
0
    def processRequest(self,
                       request,
                       access_type,
                       page_name=None,
                       params=None,
                       **kwargs):
        """Creates the page upon which a request can be processed.

    Args:
      request: the standard Django HTTP request object
      access_type : the name of the access type which should be checked
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

        # get the request entity using the information from kwargs
        request_entity = request_logic.getFromIDOr404(int(kwargs['id']))

        # get the context for this webpage
        context = responses.getUniversalContext(request)
        responses.useJavaScript(context, params['js_uses_all'])

        context['page_name'] = '%s from %s to become a %s' % (
            page_name, request_entity.user.name, params['name'])

        # TODO(ljvderijk): Should be a POST request
        get_dict = request.GET

        if 'status' in get_dict.keys():
            if get_dict['status'] in [
                    'group_accepted', 'rejected', 'withdrawn', 'ignored'
            ]:
                # update the request_entity and redirect away from this page
                request_status = get_dict['status']

                # only update when the status is changing
                if request_status != request_entity.status:
                    request_logic.updateEntityProperties(
                        request_entity, {'status': get_dict['status']})

                group_view = params.get('group_view')
                if not group_view:
                    return http.HttpResponseRedirect('/')
                else:
                    # redirect to the requests list
                    return http.HttpResponseRedirect(
                        redirects.getListRequestsRedirect(
                            request_entity.group, group_view.getParams()))

        # put the entity in the context
        context['entity'] = request_entity
        context['request_status'] = request_entity.status
        context['role_verbose'] = params['name']
        context['url_name'] = params['url_name']

        #display the request processing page using the appropriate template
        template = request_view.view.getParams()['request_processing_template']

        return responses.respond(request, template, context=context)
Пример #8
0
    def reviewPost(self, request, params, context, survey, record):
        """Handles the GET request for reviewing an OrgAppSurveyRecord.

    Args:
      request: HTTPRequest object
      params: View params dict
      context: page context dictionary
      survey: OrgAppSurvey entity
      record: OrgAppSurveyRecord under review
    """

        survey_logic = params['logic']
        record_logic = survey_logic.getRecordLogic()

        post_dict = request.POST
        review_form = params['review_form'](post_dict)

        if not review_form.is_valid():
            context['review_form'] = review_form
            template = params['review_template']
            return responses.respond(request, template, context)

        new_status = review_form.cleaned_data['status']

        # only update if the status actually changes
        if record.status != new_status:
            fields = {'status': new_status}
            record_logic.updateEntityProperties(record, fields)

        return http.HttpResponseRedirect(
            redirects.getReviewOverviewRedirect(record.survey, params))
Пример #9
0
  def process_exception(self, request, exception):
    """Called when an uncaught exception is raised.

    See the Django middleware documentation for an explanation of
    the method signature.
    """

    template = None
    context = responses.getUniversalContext(request)

    if isinstance(exception, DeadlineExceededError):
      template = 'soc/deadline_exceeded.html'
    if isinstance(exception, MemoryError):
      template = 'soc/memory_error.html'
    if isinstance(exception, AssertionError):
      template = 'soc/assertion_error.html'
    if isinstance(exception, out_of_band.Error):
      return responses.errorResponse(exception, request)

    if template:
      logging.exception(exception)
      return responses.respond(request, template, context=context)

    # let Django handle it
    return None
Пример #10
0
  def reviewPost(self, request, params, context, survey, record):
    """Handles the GET request for reviewing an OrgAppSurveyRecord.

    Args:
      request: HTTPRequest object
      params: View params dict
      context: page context dictionary
      survey: OrgAppSurvey entity
      record: OrgAppSurveyRecord under review
    """

    survey_logic = params['logic']
    record_logic = survey_logic.getRecordLogic()

    post_dict = request.POST
    review_form = params['review_form'](post_dict)

    if not review_form.is_valid():
      context['review_form'] = review_form
      template = params['review_template']
      return responses.respond(request, template, context)

    new_status = review_form.cleaned_data['status']

    # only update if the status actually changes
    if record.status != new_status:
      fields = {'status' : new_status}
      record_logic.updateEntityProperties(record, fields)

    return http.HttpResponseRedirect(
        redirects.getReviewOverviewRedirect(record.survey, params))
Пример #11
0
    def maintenance(self, request):
        """Returns a 'down for maintenance' view.
    """

        context = responses.getUniversalContext(request)
        context['page_name'] = ugettext('Maintenance')

        notice = context.pop('site_notice')

        if not notice:
            context['body_content'] = DEF_IN_UNEXPECTED_MAINTENANCE_MSG
        else:
            context['body_content'] = notice

        context['header_title'] = DEF_DOWN_FOR_MAINTENANCE_MSG
        context['sidebar_menu_items'] = [
            {
                'heading': DEF_DOWN_FOR_MAINTENANCE_MSG,
                'group': ''
            },
        ]

        template = 'soc/base.html'

        return responses.respond(request, template, context=context)
Пример #12
0
  def viewResults(self, request, access_type, page_name=None,
                  params=None, **kwargs):
    """View for SurveyRecord and SurveyRecordGroup.
    """

    results_logic = params['logic'].getRecordLogic()

    user = user_logic.getForCurrentAccount()

    # TODO(ajaksu): use the named parameter link_id from the re
    if request.path == '/survey/show/user/' + user.link_id:
      records = tuple(user.surveys_taken.run())
      context = responses.getUniversalContext(request)
      context['content'] = records[0].survey.survey_content
      responses.useJavaScript(context, params['js_uses_all'])
      context['page_name'] = u'Your survey records.'
    else:
      entity, context = self.getContextEntity(request, page_name,
                                              params, kwargs)

      if context is None:
        # user cannot see this page, return error response
        return entity
      context['content'] = entity.survey_content
      can_write = False
      rights = self._params['rights']
      try:
        rights.checkIsSurveyWritable({'key_name': entity.key().name(),
                                      'prefix': entity.prefix,
                                      'scope_path': entity.scope_path,
                                      'link_id': entity.link_id,},
                                     'key_name')
        can_write = True
      except out_of_band.AccessViolation:
        pass

      filter = self._params.get('filter') or {}

      # if user can edit the survey, show everyone's results
      if can_write:
        filter['survey'] = entity
      else:
        filter.update({'user': user, 'survey': entity})

      limit = self._params.get('limit') or 1000
      offset = self._params.get('offset') or 0
      order = self._params.get('order') or []
      idx = self._params.get('idx') or 0

      records = results_logic.getForFields(filter=filter, limit=limit,
                                        offset=offset, order=order)

    updates = dicts.rename(params, params['list_params'])
    context.update(updates)

    context['results'] = records, records

    template = 'soc/survey/results_page.html'
    return responses.respond(request, template, context=context)
Пример #13
0
  def processRequest(self, request, access_type,
                     page_name=None, params=None, **kwargs):
    """Creates the page upon which a request can be processed.

    Args:
      request: the standard Django HTTP request object
      access_type : the name of the access type which should be checked
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    # get the context for this webpage
    context = responses.getUniversalContext(request)
    responses.useJavaScript(context, params['js_uses_all'])
    context['page_name'] = page_name

    # get the request entity using the information from kwargs
    fields = {'link_id': kwargs['link_id'],
        'scope_path': kwargs['scope_path'],
        'role': params['logic'].role_name}
    request_entity = request_logic.logic.getForFields(fields, unique=True)

    # pylint: disable-msg=E1103
    user_entity = user_logic.logic.getFromKeyNameOr404(request_entity.link_id)

    get_dict = request.GET

    if 'status' in get_dict.keys():
      if get_dict['status'] in ['group_accepted', 'rejected', 'ignored']:
        # update the request_entity and redirect away from this page
        request_status = get_dict['status']

        # only update when the status is changing
        if request_status != request_entity.status:
          request_logic.logic.updateEntityProperties(request_entity, {
              'status': get_dict['status']})

        group_view = params.get('group_view')
        if not group_view:
          return http.HttpResponseRedirect('/')
        else:
          # redirect to the requests list
          return http.HttpResponseRedirect(
              redirects.getListRequestsRedirect(request_entity.scope, 
                  group_view.getParams()))

    # put the entity in the context
    context['entity'] = request_entity
    context['user_in_request'] = user_entity
    context['request_status'] = request_entity.status 
    context['role_name'] = params['logic'].role_name

    #display the request processing page using the appropriate template
    template = request_view.view.getParams()['request_processing_template']

    return responses.respond(request, template, context=context)
Пример #14
0
  def manage(self, request, access_type,
             page_name=None, params=None, **kwargs):
    """Handles the request concerning the view that let's 
       you manage a role's status.

    Args:
      request: the standard Django HTTP request object
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    # get the context for this webpage
    context = responses.getUniversalContext(request)
    responses.useJavaScript(context, params['js_uses_all'])
    context['page_name'] = page_name

    logic = params['logic']

    # get the entity for the given fields in kwargs
    fields = {'scope_path': kwargs['scope_path'],
        'link_id': kwargs['link_id']}
    role_entity = logic.getForFields(kwargs, unique=True)

    # get the redirect for the cancel button or when the resignation is done
    redirect = params['manage_redirect'](role_entity.scope,
        params['group_view'].getParams())

    # check to see if resign is true
    get_dict = request.GET
    resign = get_dict.get('resign')

    if resign == 'true':

      resign_error = params['logic'].canResign(role_entity)

      if not resign_error:
        # change the status of this role_entity to invalid
        fields = {'status': 'invalid'}
        logic.updateEntityProperties(role_entity, fields)

        # redirect to the roles listing
        return http.HttpResponseRedirect(redirect)
      else:
        # show error to the user
        context['resign_error'] = ugettext(resign_error %params)

    # set the appropriate context
    context['entity'] = role_entity
    context['url_name'] = params['url_name']
    context['cancel_redirect'] = redirect

    # get the manage template
    template = params['manage_template']

    # return a proper response
    return responses.respond(request, template, context=context)
Пример #15
0
  def processInvite(self, request, access_type,
                   page_name=None, params=None, **kwargs):
    """Creates the page upon which an invite can be processed.

    Args:
      request: the standard Django HTTP request object
      access_type : the name of the access type which should be checked
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    from soc.views.models.role import ROLE_VIEWS

    # get the context for this webpage
    context = responses.getUniversalContext(request)
    helper.responses.useJavaScript(context, params['js_uses_all'])

    # get the request entity using the information from kwargs
    request_entity = request_logic.getFromIDOr404(int(kwargs['id']))

    invite_accepted_redirect = redirects.getInviteAcceptedRedirect(
        request_entity, self._params)

    role_params = ROLE_VIEWS[request_entity.role].getParams()

    role_logic = role_params['logic']
    if not role_logic.canRejectInvite(request_entity.group):
      return http.HttpResponseRedirect(invite_accepted_redirect)

    # set the page name using the request_entity
    context['page_name'] = '%s %s for %s' % (page_name, 
        role_params['name'], request_entity.group.name)

    get_dict = request.GET

    # TODO(ljvderijk): Should be made a POST request.
    if 'status' in get_dict.keys():
      if get_dict['status'] == 'canceled':
        # this invite has been canceled mark as such
        request_logic.updateEntityProperties(request_entity, {
            'status': 'canceled'})

        # redirect to user request overview
        return http.HttpResponseRedirect('/user/requests')

    # put the entity in the context
    context['entity'] = request_entity
    context['module_name'] = params['module_name']
    context['role_name'] = role_params['name']
    context['invite_accepted_redirect'] = (invite_accepted_redirect)

    #display the invite processing page using the appropriate template
    template = params['invite_processing_template']

    return responses.respond(request, template, context=context)
Пример #16
0
  def commentGet(self, request, context, params, entity, **kwargs):
    """Handles the GET request for the proposal review view.
    """

    self.updateCommentContext(context, entity, params)

    context['form'] = params['public_review_form']()
    template = params['comment_template']

    return responses.respond(request, template, context=context)
Пример #17
0
    def requestTaskGet(self, request, page_name, org_entity, **kwargs):
        """GET request for requestTask.
    """

        context = helper.responses.getUniversalContext(request)
        context["page_name"] = page_name
        context["org_name"] = org_entity.name

        template = "modules/gci/task/request.html"
        return responses.respond(request, template, context=context)
Пример #18
0
    def requestTaskGet(self, request, page_name, org_entity, **kwargs):
        """GET request for requestTask.
    """

        context = helper.responses.getUniversalContext(request)
        context['page_name'] = page_name
        context['org_name'] = org_entity.name

        template = 'modules/gci/task/request.html'
        return responses.respond(request, template, context=context)
Пример #19
0
  def processRequest(self, request, access_type,
                     page_name=None, params=None, **kwargs):
    """Creates the page upon which a request can be processed.

    Args:
      request: the standard Django HTTP request object
      access_type : the name of the access type which should be checked
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    # get the request entity using the information from kwargs
    request_entity = request_logic.getFromIDOr404(int(kwargs['id']))

    # get the context for this webpage
    context = responses.getUniversalContext(request)
    responses.useJavaScript(context, params['js_uses_all'])

    context['page_name'] = '%s from %s to become a %s' % (
        page_name, request_entity.user.name, params['name'])

    # TODO(ljvderijk): Should be a POST request
    get_dict = request.GET

    if 'status' in get_dict.keys():
      if get_dict['status'] in ['group_accepted', 'rejected', 'withdrawn',
                                'ignored']:
        # update the request_entity and redirect away from this page
        request_status = get_dict['status']

        # only update when the status is changing
        if request_status != request_entity.status:
          request_logic.updateEntityProperties(request_entity, {
              'status': get_dict['status']})

        group_view = params.get('group_view')
        if not group_view:
          return http.HttpResponseRedirect('/')
        else:
          # redirect to the requests list
          return http.HttpResponseRedirect(
              redirects.getListRequestsRedirect(request_entity.group,
                  group_view.getParams()))

    # put the entity in the context
    context['entity'] = request_entity
    context['request_status'] = request_entity.status 
    context['role_verbose'] = params['name']
    context['url_name'] = params['url_name']

    #display the request processing page using the appropriate template
    template = request_view.view.getParams()['request_processing_template']

    return responses.respond(request, template, context=context)
Пример #20
0
  def reviewAfterDeadline(self,request, context, params, entity,**kwargs):
    """View that shows the review view after the accepted students announced deadline.

    For Args see base.View.public().
    """

    review_context = self._getDefaultReviewContext(entity, None, None)
    context = dicts.merge(context, review_context)

    template = params['review_after_deadline_template']

    return responses.respond(request, template, context=context)
Пример #21
0
    def processInvite(self,
                      request,
                      access_type,
                      page_name=None,
                      params=None,
                      **kwargs):
        """Creates the page upon which an invite can be processed.

    Args:
      request: the standard Django HTTP request object
      access_type : the name of the access type which should be checked
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

        from soc.views.models.role import ROLE_VIEWS

        # get the context for this webpage
        context = responses.getUniversalContext(request)
        helper.responses.useJavaScript(context, params['js_uses_all'])

        # get the request entity using the information from kwargs
        request_entity = request_logic.getFromIDOr404(int(kwargs['id']))

        role_params = ROLE_VIEWS[request_entity.role].getParams()

        # set the page name using the request_entity
        context['page_name'] = '%s %s for %s' % (
            page_name, role_params['name'], request_entity.group.name)

        get_dict = request.GET

        if 'status' in get_dict.keys():
            if get_dict['status'] == 'rejected':
                # this invite has been rejected mark as rejected
                request_logic.updateEntityProperties(request_entity,
                                                     {'status': 'rejected'})

                # redirect to user request overview
                return http.HttpResponseRedirect('/user/requests')

        # put the entity in the context
        context['entity'] = request_entity
        context['module_name'] = params['module_name']
        context['role_name'] = role_params['name']
        context['invite_accepted_redirect'] = (
            redirects.getInviteAcceptedRedirect(request_entity, self._params))

        #display the invite processing page using the appropriate template
        template = params['invite_processing_template']

        return responses.respond(request, template, context=context)
Пример #22
0
 def subscribe(self, request, page_name=None, params=None, **kwargs):
   """
   
   Returns ATOM feed of recent updates
    
   """
   
   entity = self._params.get('logic').getFromKeyFields(kwargs)
   from soc.views.helper import news_feed 
   feed = news_feed.NewsFeed(entity)
   template, context = feed.getFeedXML()
   response = responses.respond(request, template, context)
   return response
Пример #23
0
    def reviewAfterDeadline(self, request, context, params, entity, **kwargs):
        """View that shows the review view after the accepted students 
       announced deadline.

    For Args see base.View.public().
    """

        review_context = self._getDefaultReviewContext(entity, None, None)
        context = dicts.merge(context, review_context)

        template = params['review_after_deadline_template']

        return responses.respond(request, template, context=context)
Пример #24
0
  def processInvite(self, request, access_type,
                   page_name=None, params=None, **kwargs):
    """Creates the page upon which an invite can be processed.

    Args:
      request: the standard Django HTTP request object
      access_type : the name of the access type which should be checked
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    # get the context for this webpage
    context = responses.getUniversalContext(request)
    helper.responses.useJavaScript(context, params['js_uses_all'])

    request_logic = params['logic']

    # get the request entity using the information from kwargs
    fields = {'link_id': kwargs['link_id'],
        'scope_path': kwargs['scope_path'],
        'role': kwargs['role'],
        'status': 'group_accepted'}
    request_entity = request_logic.getForFields(fields, unique=True)

    # set the page name using the request_entity
    context['page_name'] = '%s %s' % (page_name, 
        request_entity.role_verbose)

    get_dict = request.GET

    if 'status' in get_dict.keys():
      if get_dict['status'] == 'rejected':
        # this invite has been rejected mark as rejected
        request_logic.updateEntityProperties(request_entity, {
            'status': 'rejected'})

        # redirect to user request overview
        return http.HttpResponseRedirect('/user/requests')

    # put the entity in the context
    context['entity'] = request_entity
    context['module_name'] = params['module_name']
    context['invite_accepted_redirect'] = (
        redirects.getInviteAcceptedRedirect(request_entity, self._params))

    #display the invite processing page using the appropriate template
    template = params['invite_processing_template']

    return responses.respond(request, template, context=context)
Пример #25
0
  def _editRecordGet(self, request, params, context, template, record_entity):
    """Handles the GET request for editing a GradingRecord.
    Args:
      request: a Django Request object
      params: the params for this view
      context: the context for the webpage
      template: the location of the template used for this view
      record_entity: a GradingRecord entity
    """

    form = params['record_edit_form'](instance=record_entity)
    context['form'] = form

    return responses.respond(request, template, context)
Пример #26
0
    def publicGet(self, request, context, params, entity, **kwargs):
        """Handles the GET request for the entity's public page.

    Args:
        entity: the student proposal entity
        rest see base.View.public()
    """

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

        get_dict = request.GET

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

            subscription = get_dict['subscription']

            # 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 if we should set subscribed_public to True or False
            if subscription == 'on':
                fields['subscribed_public'] = True
            elif subscription == 'off':
                fields['subscribed_public'] = False

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

        # get some entity specific context
        self.updatePublicContext(context, entity, params)

        context['form'] = params['public_review_form']()
        template = params['public_template']

        return responses.respond(request, template, context=context)
Пример #27
0
    def manage(self,
               request,
               access_type,
               page_name=None,
               params=None,
               **kwargs):
        """Handles the request concerning the view that let's 
       you manage a role's status.

    Args:
      request: the standard Django HTTP request object
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

        # get the context for this webpage
        context = responses.getUniversalContext(request)
        responses.useJavaScript(context, params['js_uses_all'])
        context['page_name'] = page_name

        logic = params['logic']

        # get the entity for the given fields in kwargs
        role_entity = logic.getFromKeyFieldsOr404(kwargs)

        # get the redirect for the cancel button or when the resignation is done
        redirect = params['manage_redirect'](role_entity.scope,
                                             params['group_view'].getParams())

        if request.method == 'POST':
            resign_error = logic.canResign(role_entity)
            if not resign_error:
                return self.managePost(request, params, role_entity, redirect)

            # show error to the user
            context['resign_error'] = resign_error % params

        # set the appropriate context
        context['entity'] = role_entity
        context['url_name'] = params['url_name']
        context['cancel_redirect'] = redirect

        # get the manage template
        template = params['manage_template']

        # return a proper response
        return responses.respond(request, template, context=context)
Пример #28
0
    def _manageSetMentor(self, request, template, context, params, entity,
                         form):
        """Handles the POST request for changing a Projects's mentor.

    Args:
        template: the template used for this view
        entity: the student project entity
        form: instance of the form used to set the mentor
        rest: see base.View.public()
    """

        if not form.is_valid():
            context['mentor_edit_form'] = form

            # add an a fresh additional mentors form
            context['additional_mentor_form'] = params[
                'additional_mentor_form']()

            return responses.respond(request, template, context)

        _, fields = forms_helper.collectCleanedFields(form)

        # get the mentor from the form
        fields = {
            'link_id': fields['mentor_id'],
            'scope': entity.scope,
            'status': 'active'
        }
        mentor = mentor_logic.getForFields(fields, unique=True)

        # update the project with the assigned mentor
        fields = {'mentor': mentor}

        additional_mentors = entity.additional_mentors

        # pylint: disable=E1103
        if additional_mentors and mentor.key() in additional_mentors:
            # remove the mentor that is now becoming the primary mentor
            additional_mentors.remove(mentor.key())
            fields['additional_mentors'] = additional_mentors

        # update the project with the new mentor and possible
        # new set of additional mentors
        project_logic.updateEntityProperties(entity, fields)

        # redirect to the same page
        redirect = request.path
        return http.HttpResponseRedirect(redirect)
Пример #29
0
  def takeGet(self, request, template, context, params, survey_form, entity,
              record, **kwargs):
    """Handles the GET request for the Survey's take page.

    Args:
        template: the template used for this view
        survey_form: instance of SurveyTakeForm
        entity: the Survey entity
        record: a SurveyRecord entity iff any exists
        rest: see base.View.public()
    """

    # call the hook method
    self._takeGet(request, template, context, params, entity, record, **kwargs)

    return responses.respond(request, template, context)
Пример #30
0
  def manageGet(self, request, template, context, params, entity, **kwargs):
    """Handles the GET request for the project's manage page.

    Args:
        template: the template used for this view
        entity: the student project entity
        rest: see base.View.public()
    """

    # populate form with the current mentor
    initial = {'mentor_id': entity.mentor.link_id}
    context['mentor_edit_form'] = params['mentor_edit_form'](initial=initial)

    context['additional_mentor_form'] = params['additional_mentor_form']()

    return responses.respond(request, template, context)
Пример #31
0
    def home(self, request, page_name=None, params=None, **kwargs):
        """Renders the home page for seeding operations.
    """
        template = 'modules/seeder/home.html'
        configuration_sheet = request.FILES.get('configuration_sheet', None)
        if configuration_sheet:
            configuration_sheet = configuration_sheet.read()
        else:
            configuration_sheet = ''

        context = responses.getUniversalContext(request)
        context['configuration_sheet'] = simplejson.dumps(configuration_sheet)

        # FIXME : temporarily comment due to errors
        #responses.useJavaScript(context, params['js_uses_all'])

        return responses.respond(request, template, context)
Пример #32
0
  def reviewGet(self, request, params, context, survey, record):
    """Handles the GET request for reviewing an OrgAppSurveyRecord.

    Args:
      request: HTTPRequest object
      params: View params dict
      context: page context dictionary
      survey: OrgAppSurvey entity
      record: OrgAppSurveyRecord under review
    """

    review_form = params['review_form']()
    review_form.fields['status'].initial = record.status
    context['review_form'] = review_form

    template = params['review_template']
    return responses.respond(request, template, context)
Пример #33
0
  def _bulkReview(self, request, params, from_status, to_status,
                  program_keyname):
    """Returns a HTTP Response containing JSON information needed
       to bulk-review organization applications.

       Args:
         request: Standard Django HTTP Request object
         params: Params for this view
         from_status: The status for the applications which should
                      be reviewed (can be a list)
         to_status: The status to which all applications should be changed to
         program_keyname: The keyname for the program to which
                          the application belongs
    """

    # get the program entity from the keyname
    program_entity = program_logic.logic.getFromKeyName(program_keyname)

    # get all the organization applications for the 
    # given program and from_status
    filter = {'scope': program_entity,
              'status': from_status}

    org_app_entities = params['logic'].getForFields(filter=filter)

    # convert each application into a dictionary containing only the fields
    # given by the dict_filter
    dict_filter = ['link_id', 'name']
    org_apps = [dicts.filter(i.toDict(), dict_filter) for i in org_app_entities]

    to_json = {
        'program' : program_entity.name,
        'nr_applications' : len(org_apps),
        'application_type' : params['name_plural'],
        'applications': org_apps,
        'link' : '/%s/review/%s/(link_id)?status=%s' %(
            params['url_name'] ,program_entity.key().id_or_name(), to_status),
        }

    json = simplejson.dumps(to_json)

    # use the standard JSON template to return our response
    context = {'json': json}
    template = 'soc/json.html'

    return responses.respond(request, template, context)
Пример #34
0
  def home(self, request, page_name=None, params=None, **kwargs):
    """Renders the home page for seeding operations.
    """
    template = 'modules/seeder/home.html'
    configuration_sheet = request.FILES.get('configuration_sheet', None);
    if configuration_sheet:
      configuration_sheet = configuration_sheet.read()
    else:
      configuration_sheet = ''

    context = responses.getUniversalContext(request)
    context['configuration_sheet'] = simplejson.dumps(configuration_sheet)

    # FIXME : temporarily comment due to errors 
    #responses.useJavaScript(context, params['js_uses_all'])

    return responses.respond(request, template, context)
Пример #35
0
    def takeGet(self, request, template, context, params, survey_form, entity,
                record, **kwargs):
        """Handles the GET request for the Survey's take page.

    Args:
        template: the template used for this view
        survey_form: instance of SurveyTakeForm
        entity: the Survey entity
        record: a SurveyRecord entity iff any exists
        rest: see base.View.public()
    """

        # call the hook method
        self._takeGet(request, template, context, params, entity, record,
                      **kwargs)

        return responses.respond(request, template, context)
Пример #36
0
    def reviewGet(self, request, params, context, survey, record):
        """Handles the GET request for reviewing an OrgAppSurveyRecord.

    Args:
      request: HTTPRequest object
      params: View params dict
      context: page context dictionary
      survey: OrgAppSurvey entity
      record: OrgAppSurveyRecord under review
    """

        review_form = params['review_form']()
        review_form.fields['status'].initial = record.status
        context['review_form'] = review_form

        template = params['review_template']
        return responses.respond(request, template, context)
Пример #37
0
  def publicGet(self, request, context, params, entity, **kwargs):
    """Handles the GET request for the entity's public page.

    Args:
        entity: the student proposal entity
        rest see base.View.public()
    """

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

    get_dict = request.GET

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

      subscription = get_dict['subscription']

      # 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 if we should set subscribed_public to True or False
      if subscription == 'on':
        fields['subscribed_public'] = True
      elif subscription == 'off':
        fields['subscribed_public'] = False

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

    # get some entity specific context
    self.updatePublicContext(context, entity, params)

    context['form'] = params['public_review_form']()
    template = params['public_template']

    return responses.respond(request, template, context=context)
Пример #38
0
  def manage(self, request, access_type,
             page_name=None, params=None, **kwargs):
    """Handles the request concerning the view that let's 
       you manage a role's status.

    Args:
      request: the standard Django HTTP request object
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    # get the context for this webpage
    context = responses.getUniversalContext(request)
    responses.useJavaScript(context, params['js_uses_all'])
    context['page_name'] = page_name

    logic = params['logic']

    # get the entity for the given fields in kwargs
    role_entity = logic.getFromKeyFieldsOr404(kwargs)

    # get the redirect for the cancel button or when the resignation is done
    redirect = params['manage_redirect'](role_entity.scope,
        params['group_view'].getParams())

    if request.method == 'POST':
      resign_error = logic.canResign(role_entity)
      if not resign_error:
        return self.managePost(request, params, role_entity, redirect)

      # show error to the user
      context['resign_error'] = resign_error % params

    # set the appropriate context
    context['entity'] = role_entity
    context['url_name'] = params['url_name']
    context['cancel_redirect'] = redirect

    # get the manage template
    template = params['manage_template']

    # return a proper response
    return responses.respond(request, template, context=context)
Пример #39
0
    def _manageAddAdditionalMentor(self, request, template, context, params,
                                   entity, form):
        """Handles the POST request for changing a Projects's additional mentors.

    Args:
        template: the template used for this view
        entity: the student project entity
        form: instance of the form used to add an additional mentor
        rest: see base.View.public()
    """

        if not form.is_valid():
            context['additional_mentor_form'] = form

            # add a fresh edit mentor form
            initial = {'mentor_id': entity.mentor.link_id}
            context['mentor_edit_form'] = params['mentor_edit_form'](
                initial=initial)

            return responses.respond(request, template, context)

        _, fields = forms_helper.collectCleanedFields(form)

        # get the mentor from the form
        fields = {
            'link_id': fields['mentor_id'],
            'scope': entity.scope,
            'status': 'active'
        }
        mentor = mentor_logic.getForFields(fields, unique=True)

        # add this mentor to the additional mentors
        if not entity.additional_mentors:
            additional_mentors = [mentor.key()]
        else:
            additional_mentors = entity.additional_mentors
            additional_mentors.append(mentor.key())

        fields = {'additional_mentors': additional_mentors}
        project_logic.updateEntityProperties(entity, fields)

        # redirect to the same page
        redirect = request.path
        return http.HttpResponseRedirect(redirect)
Пример #40
0
  def _manageSetMentor(self, request, template, context, params, entity, form):
    """Handles the POST request for changing a Projects's mentor.

    Args:
        template: the template used for this view
        entity: the student project entity
        form: instance of the form used to set the mentor
        rest: see base.View.public()
    """

    if not form.is_valid():
      context['mentor_edit_form'] = form

      # add an a fresh additional mentors form
      context['additional_mentor_form'] = params['additional_mentor_form']()

      return responses.respond(request, template, context)

    _, fields = forms_helper.collectCleanedFields(form)

    # get the mentor from the form
    fields = {'link_id': fields['mentor_id'],
              'scope': entity.scope,
              'status': 'active'}
    mentor = mentor_logic.logic.getForFields(fields, unique=True)

    # update the project with the assigned mentor
    fields = {'mentor': mentor}

    additional_mentors = entity.additional_mentors

    # pylint: disable-msg=E1103
    if additional_mentors and mentor.key() in additional_mentors:
      # remove the mentor that is now becoming the primary mentor
      additional_mentors.remove(mentor.key())
      fields['additional_mentors'] = additional_mentors

    # update the project with the new mentor and possible 
    # new set of additional mentors
    project_logic.updateEntityProperties(entity, fields)

    # redirect to the same page
    redirect = request.path
    return http.HttpResponseRedirect(redirect)
Пример #41
0
    def maintenance(self, request, page_name):
        """Returns a 'down for maintenance' view.
    """

        context = responses.getUniversalContext(request)
        context["page_name"] = page_name

        notice = context.pop("site_notice")

        if not notice:
            context["body_content"] = self.DEF_NOT_IN_MAINTENANCE_MSG
        else:
            context["body_content"] = notice
            context["header_title"] = self.DEF_DOWN_FOR_MAINTENANCE_MSG
            context["sidebar_menu_items"] = [{"heading": self.DEF_DOWN_FOR_MAINTENANCE_MSG, "group": ""}]

        template = "soc/base.html"

        return responses.respond(request, template, context=context)
Пример #42
0
  def _manageAddAdditionalMentor(self, request, template, 
                                 context, params, entity, form):
    """Handles the POST request for changing a Projects's additional mentors.

    Args:
        template: the template used for this view
        entity: the student project entity
        form: instance of the form used to add an additional mentor
        rest: see base.View.public()
    """

    if not form.is_valid():
      context['additional_mentor_form'] = form

      # add a fresh edit mentor form
      initial = {'mentor_id': entity.mentor.link_id}
      context['mentor_edit_form'] = params['mentor_edit_form'](initial=initial)

      return responses.respond(request, template, context)

    _, fields = forms_helper.collectCleanedFields(form)

    # get the mentor from the form
    fields = {'link_id': fields['mentor_id'],
              'scope': entity.scope,
              'status': 'active'}
    mentor = mentor_logic.logic.getForFields(fields, unique=True)

    # add this mentor to the additional mentors
    if not entity.additional_mentors:
      additional_mentors = [mentor.key()]
    else:
      additional_mentors = entity.additional_mentors
      additional_mentors.append(mentor.key())

    fields = {'additional_mentors': additional_mentors}
    project_logic.updateEntityProperties(entity, fields)

    # redirect to the same page
    redirect = request.path
    return http.HttpResponseRedirect(redirect)
Пример #43
0
    def submitFormsGet(self, request, params, template, context, entity):
        if lists.isJsonRequest(request):
            url = blobstore.create_upload_url(
                gci_redirects.getSubmitFormsRedirect(entity, params))
            return responses.jsonResponse(request, url)

        def setForm(param_name, blob_info):
            add_form, edit_form = params[param_name]

            if blob_info:
                form = edit_form(
                    initial={
                        'name':
                        '<a href="%(url)s">%(name)s</a>' % {
                            'name':
                            blob_info.filename,
                            'url':
                            redirects.getDownloadBlobRedirectWithGet(
                                blob_info,
                                params,
                                scope_path=entity.key().id_or_name(),
                                type=param_name)
                        },
                        'size':
                        defaultfilters.filesizeformat(blob_info.size),
                        'uploaded':
                        blob_info.creation.strftime(self.DATETIME_FORMAT),
                    })
            else:
                form = add_form()

            context[param_name] = form

        setForm('consent_form_upload_form', entity.consent_form)
        setForm('consent_form_two_upload_form', entity.consent_form_two)
        setForm('student_id_form_upload_form', entity.student_id_form)

        return responses.respond(request, template, context)
Пример #44
0
  def maintenance(self, request):
    """Returns a 'down for maintenance' view.
    """

    context = responses.getUniversalContext(request)
    context['page_name'] = ugettext('Maintenance')

    notice = context.pop('site_notice')

    if not notice:
      context['body_content'] = DEF_IN_UNEXPECTED_MAINTENANCE_MSG
    else:
      context['body_content'] = notice

    context['header_title'] = DEF_DOWN_FOR_MAINTENANCE_MSG
    context['sidebar_menu_items'] = [
        {'heading': DEF_DOWN_FOR_MAINTENANCE_MSG,
         'group': ''},
        ]

    template = 'soc/base.html'

    return responses.respond(request, template, context=context)
Пример #45
0
    def manageGet(self, request, template, context, params, entity, **kwargs):
        """Handles the GET request for the project's manage page.

    Args:
        template: the template used for this view
        entity: the student project entity
        rest: see base.View.public()
    """

        get_dict = request.GET

        if 'remove' in get_dict and entity.status == 'accepted':
            # get the mentor to remove
            fields = {'link_id': get_dict['remove'], 'scope': entity.scope}
            mentor = mentor_logic.getForFields(fields, unique=True)

            additional_mentors = entity.additional_mentors
            # pylint: disable=E1103
            if additional_mentors and mentor.key() in additional_mentors:
                # remove the mentor from the additional mentors list
                additional_mentors.remove(mentor.key())
                fields = {'additional_mentors': additional_mentors}
                project_logic.updateEntityProperties(entity, fields)

            # redirect to the same page without GET arguments
            redirect = request.path
            return http.HttpResponseRedirect(redirect)

        if project_logic.canChangeMentors(entity):
            # populate forms with the current mentors set
            initial = {'mentor_id': entity.mentor.link_id}
            context['mentor_edit_form'] = params['mentor_edit_form'](
                initial=initial)
            context['additional_mentor_form'] = params[
                'additional_mentor_form']()

        return responses.respond(request, template, context)
Пример #46
0
  def manageGet(self, request, template, context, params, entity, **kwargs):
    """Handles the GET request for the project's manage page.

    Args:
        template: the template used for this view
        entity: the student project entity
        rest: see base.View.public()
    """

    get_dict = request.GET

    if 'remove' in get_dict and entity.status == 'accepted':
      # get the mentor to remove
      fields = {'link_id': get_dict['remove'],
                'scope': entity.scope}
      mentor = mentor_logic.getForFields(fields, unique=True)

      additional_mentors = entity.additional_mentors
      # pylint: disable=E1103
      if additional_mentors and mentor.key() in additional_mentors:
        # remove the mentor from the additional mentors list
        additional_mentors.remove(mentor.key())
        fields = {'additional_mentors': additional_mentors}
        project_logic.updateEntityProperties(entity, fields)

      # redirect to the same page without GET arguments
      redirect = request.path
      return http.HttpResponseRedirect(redirect)

    if project_logic.canChangeMentors(entity):
      # populate forms with the current mentors set
      initial = {'mentor_id': entity.mentor.link_id}
      context['mentor_edit_form'] = params['mentor_edit_form'](initial=initial)
      context['additional_mentor_form'] = params['additional_mentor_form']()

    return responses.respond(request, template, context)
Пример #47
0
  def json(self, request, data):
    """Returns data as a json object.
    """

    to_json = {
        'data': data,
        }

    json = simplejson.dumps(to_json)

    context = {'json': json}
    template = 'soc/json.html'

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

    # if the browser supports HTTP/1.1
    # post-check and pre-check and no-store for IE7
    response['Cache-Control'] = 'no-store, no-cache, must-revalidate, ' \
        'post-check=0, pre-check=0'

    # if the browser supports HTTP/1.0
    response['Pragma'] = 'no-cache'

    return response
Пример #48
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()
    """

    initial = {}

    # set the initial score since the default is ignored
    initial['score'] = 0

    # set initial values for fields that are available only for org admins
    if org_admin and entity.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)
Пример #49
0
class View(base.View):
  """View methods for the Student Proposal model.
  """

  DEF_REVIEW_NOT_APPEARED_MSG = ugettext(
      'Your review has been saved. '
      'However, it may take some time for your review to appear. ' 
      'Please refresh your browser or check back later to view your review.')

  def __init__(self, params=None):
    """Defines the fields and methods required for the base View class
    to provide the user with list, public, create, edit and delete views.

    Params:
      params: a dict with params for this View
    """

    rights = access.GSoCChecker(params)
    rights['create'] = ['checkIsDeveloper']
    rights['edit'] = [('checkCanStudentPropose', ['scope_path', False]),
        ('checkRoleAndStatusForStudentProposal',
            [['proposer'], ['active'], ['new', 'pending', 'invalid']])]
    rights['delete'] = ['checkIsDeveloper']
    rights['private'] = [
        ('checkRoleAndStatusForStudentProposal',
            [['proposer', 'org_admin', 'mentor', 'host'], 
            ['active', 'inactive'], 
            ['new', 'pending', 'accepted', 'rejected', 'invalid']])]
    rights['show'] = ['checkIsStudentProposalPubliclyVisible']
    rights['comment'] = [
        ('checkRoleAndStatusForStudentProposal',
            [['org_admin', 'mentor', 'host'], 
            ['active', 'inactive'],
            ['new', 'pending', 'accepted', 'rejected', 'invalid']])]
    rights['list'] = ['checkIsDeveloper']
    rights['list_orgs'] = [
        ('checkIsStudent', ['scope_path', ['active']]),
        ('checkCanStudentPropose', ['scope_path', False])]
    rights['list_self'] = [
        ('checkIsStudent', ['scope_path', ['active', 'inactive']])]
    rights['apply'] = [
        ('checkIsStudent', ['scope_path', ['active']]),
        ('checkCanStudentPropose', ['scope_path', True])]
    rights['review'] = [
            ('checkIsBeforeEvent',
            ['accepted_students_announced_deadline', None,
             program_logic.logic]),
            ('checkRoleAndStatusForStudentProposal',
            [['org_admin', 'mentor', 'host'], 
            ['active'],
            ['new', 'pending', 'accepted', 'invalid']])]

    new_params = {}
    new_params['logic'] = student_proposal_logic.logic
    new_params['rights'] = rights
    new_params['name'] = "Student Proposal"
    new_params['url_name'] = "gsoc/student_proposal"
    new_params['module_package'] = 'soc.modules.gsoc.views.models'
    new_params['sidebar_grouping'] = 'Students'

    new_params['scope_view'] = student_view
    new_params['scope_redirect'] = redirects.getCreateRedirect

    new_params['no_create_with_key_fields'] = True

    patterns = [
        (r'^%(url_name)s/(?P<access_type>apply)/%(scope)s$',
        'soc.modules.gsoc.views.models.%(module_name)s.apply',
        'Create a new %(name)s'),
        (r'^%(url_name)s/(?P<access_type>list_self)/%(scope)s$',
        'soc.modules.gsoc.views.models.%(module_name)s.list_self',
        'List my %(name_plural)s'),
        (r'^%(url_name)s/(?P<access_type>list_orgs)/%(scope)s$',
        'soc.modules.gsoc.views.models.%(module_name)s.list_orgs',
        'List my %(name_plural)s'),
        (r'^%(url_name)s/(?P<access_type>review)/%(key_fields)s$',
        'soc.modules.gsoc.views.models.%(module_name)s.review',
        'Review %(name)s'),
        (r'^%(url_name)s/(?P<access_type>public)/%(key_fields)s$',
        'soc.modules.gsoc.views.models.%(module_name)s.public',
        'Public view for %(name)s'),
        (r'^%(url_name)s/(?P<access_type>private)/%(key_fields)s$',
        'soc.modules.gsoc.views.models.%(module_name)s.private',
        'Private view of %(name)s'),
        (r'^%(url_name)s/(?P<access_type>comment)/%(key_fields)s$',
        'soc.modules.gsoc.views.models.%(module_name)s.comment',
        'Comment view of %(name)s'),
    ]

    new_params['extra_django_patterns'] = patterns

    new_params['extra_dynaexclude'] = ['org', 'program', 'score',
                                       'status', 'mentor', 'link_id',
                                       'possible_mentors']

    new_params['create_extra_dynaproperties'] = {
        'content': forms.fields.CharField(required=True,
            widget=widgets.FullTinyMCE(attrs={'rows': 25, 'cols': 100})),
        'scope_path': forms.CharField(widget=forms.HiddenInput,
            required=True),
        'organization': forms.CharField(label='Organization Link ID',
            required=True),
        'clean_abstract': cleaning.clean_content_length('abstract'),
        'clean_content': cleaning.clean_html_content('content'),
        'clean_organization': cleaning.clean_link_id('organization'),
        'clean_additional_info': cleaning.clean_url('additional_info'),
        'clean': cleaning.validate_student_proposal('organization',
            'scope_path', student_logic, org_logic),
        }

    new_params['edit_extra_dynaproperties'] = {
        'organization': forms.CharField(label='Organization Link ID',
            widget=widgets.ReadOnlyInput),
        'link_id': forms.CharField(widget=forms.HiddenInput)
        }

    new_params['comment_template'] = 'soc/student_proposal/comment.html'
    new_params['edit_template'] = 'soc/student_proposal/edit.html'
    new_params['private_template'] = 'soc/student_proposal/private.html'
    new_params['review_template'] = 'soc/student_proposal/review.html'
    new_params['public_template'] = 'soc/student_proposal/public.html'
    new_params['review_after_deadline_template'] = \
        'soc/student_proposal/review_after_deadline.html'

    new_params['public_field_extra'] = lambda entity: {
        "student": entity.scope.name(),
        "organization_name": entity.org.name,
    }
    new_params['public_field_keys'] = [
        "title", "student", "organization_name", "last_modified_on",
    ]
    new_params['public_field_names'] = [
        "Title", "Student", "Organization Name", "Last Modified On",
    ]

    params = dicts.merge(params, new_params)

    super(View, self).__init__(params=params)

    # create the special form for students
    dynafields = [
        {'name': 'organization',
         'base': forms.CharField,
         'label': 'Organization Link ID',
         'widget': widgets.ReadOnlyInput(),
         'required': False,
         },
        ]

    dynaproperties = params_helper.getDynaFields(dynafields)

    student_create_form = dynaform.extendDynaForm(
        dynaform=self._params['create_form'],
        dynaproperties=dynaproperties)

    self._params['student_create_form'] = student_create_form

    # create the special form for public review
    base_fields = [
        {'name': 'comment',
         'base': forms.CharField,
         'widget': widgets.FullTinyMCE(attrs={'rows': 10, 'cols': 40}),
         'label': 'Comment',
         'required': False,
         'example_text': 'Caution, you will not be able to edit your comment!',
         },
         ]

    dynafields = [field.copy() for field in base_fields]
    dynaproperties = params_helper.getDynaFields(dynafields)
    dynaproperties['clean_comment'] = cleaning.clean_html_content('comment')

    public_review_form = dynaform.newDynaForm(dynamodel=None, 
        dynabase=helper.forms.BaseForm, dynainclude=None, 
        dynaexclude=None, dynaproperties=dynaproperties)
    self._params['public_review_form'] = public_review_form

    # create the special form for mentors when the scoring is locked

    # this fields is used by the on-page JS
    base_fields.append(
        {'name': 'public',
         'base': forms.BooleanField,
         'label': 'Review visible to Student',
         'initial': False,
         'required': False,
         'help_text': 'By ticking this box the score will not be assigned, '
             'and the review will be visible to the student.',
         })

    dynafields = [field.copy() for field in base_fields]
    dynaproperties = params_helper.getDynaFields(dynafields)
    dynaproperties['clean_comment'] = cleaning.clean_html_content('comment')
    locked_review_form = dynaform.newDynaForm(dynamodel=None, 
        dynabase=helper.forms.BaseForm, dynainclude=None, 
        dynaexclude=None, dynaproperties=dynaproperties)
    self._params['locked_review_form'] = locked_review_form

    # create the form for mentors when the scoring is unlocked
    base_fields.append(
        {'name': 'score',
         'base': forms.ChoiceField,
         'label': 'Score',
         'initial': 0,
         'required': False,
         'passthrough': ['initial', 'required', 'choices'],
         'choices': [(-4,'-4'),
                     (-3,'-3'),
                     (-2,'-2'),
                     (-1,'-1'),
                     (0,'No score'),
                     (1,'1'),
                     (2,'2'),
                     (3,'3'),
                     (4,'4')]
        })

    dynafields = [field.copy() for field in base_fields]
    dynaproperties = params_helper.getDynaFields(dynafields)
    dynaproperties['clean_comment'] = cleaning.clean_html_content('comment')
    mentor_review_form = dynaform.newDynaForm(dynamodel=None, 
        dynabase=helper.forms.BaseForm, dynainclude=None, 
        dynaexclude=None, dynaproperties=dynaproperties)
    self._params['mentor_review_form'] = mentor_review_form
    self._show_review_not_appeared_msg = False

  def _editGet(self, request, entity, form):
    """See base.View._editGet().
    """

    form.fields['link_id'].initial = entity.link_id
    form.fields['organization'].initial = entity.org.link_id

    return super(View, self)._editGet(request, entity, form)

  def _editPost(self, request, entity, fields):
    """See base.View._editPost().
    """

    if not entity:
      fields['link_id'] = 't%i' % (int(time.time()*100))
    else:
      fields['link_id'] = entity.link_id

    # fill in the scope via call to super
    super(View, self)._editPost(request, entity, fields)

    if not entity:
      # creating a new application so set the program and org field
      fields['program'] = fields['scope'].scope

      filter = {'scope': fields['program'],
                'link_id': fields['organization']}
      fields['org'] = org_logic.logic.getForFields(filter, unique=True)

    # explicitly change the last_modified_on since the content has been edited
    fields['last_modified_on'] = datetime.datetime.now()

  @decorators.merge_params
  @decorators.check_access
  def public(self, request, access_type, page_name=None, params=None, **kwargs):
    """View which allows the student to show his or her proposal to other
    users. Anyway, they can only see the content of the proposal itself,
    without comments, scores, etc.
    
    Args:
      request: the standard Django HTTP request object
      access_type : the name of the access type which should be checked
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    try:
      entity = self._logic.getFromKeyFieldsOr404(kwargs)
    except out_of_band.Error, error:
      return helper.responses.errorResponse(
          error, request, template=params['error_public'])

    context = helper.responses.getUniversalContext(request)
    helper.responses.useJavaScript(context, params['js_uses_all'])

    context['entity'] = entity
    context['entity_type'] = params['name']
    context['entity_type_url'] = params['url_name']
    context['page_name'] = 'Proposal titled "%s" from %s' % (
        entity.title, entity.scope.name())
    context['student_name'] = entity.scope.name()

    template = params['public_template']

    return responses.respond(request, template, context=context)
Пример #50
0
    def manage(self,
               request,
               access_type,
               page_name=None,
               params=None,
               **kwargs):
        """Handles the request concerning the view that let's 
       you manage a role's status.

    Args:
      request: the standard Django HTTP request object
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

        # get the context for this webpage
        context = responses.getUniversalContext(request)
        responses.useJavaScript(context, params['js_uses_all'])
        context['page_name'] = page_name

        logic = params['logic']

        # get the entity for the given fields in kwargs
        fields = {
            'scope_path': kwargs['scope_path'],
            'link_id': kwargs['link_id']
        }
        role_entity = logic.getForFields(kwargs, unique=True)

        # get the redirect for the cancel button or when the resignation is done
        redirect = params['manage_redirect'](role_entity.scope,
                                             params['group_view'].getParams())

        # check to see if resign is true
        get_dict = request.GET
        resign = get_dict.get('resign')

        if resign == 'true':

            resign_error = params['logic'].canResign(role_entity)

            if not resign_error:
                # change the status of this role_entity to invalid
                fields = {'status': 'invalid'}
                logic.updateEntityProperties(role_entity, fields)

                # redirect to the roles listing
                return http.HttpResponseRedirect(redirect)
            else:
                # show error to the user
                context['resign_error'] = ugettext(resign_error % params)

        # set the appropriate context
        context['entity'] = role_entity
        context['url_name'] = params['url_name']
        context['cancel_redirect'] = redirect

        # get the manage template
        template = params['manage_template']

        # return a proper response
        return responses.respond(request, template, context=context)
Пример #51
0
class View(base.View):
    """View methods for the GradingSurveyGroup model.
  """
    def __init__(self, params=None):
        """Defines the fields and methods required for the base View class
    to provide the user with list, public, create, edit and delete views.

    Params:
      params: a dict with params for this View
    """

        rights = access.GSoCChecker(params)
        rights['create'] = [('checkIsHostForProgramInScope', program_logic)]
        rights['edit'] = [('checkIsHostForProgramInScope', program_logic)]
        rights['delete'] = ['checkIsDeveloper']
        rights['show'] = [('checkIsHostForProgramInScope', program_logic)]
        rights['list'] = ['checkIsDeveloper']
        rights['records'] = [('checkIsHostForProgramInScope', program_logic)]
        rights['edit_record'] = [('checkIsHostForProgramInScope',
                                  program_logic)]

        new_params = {}
        new_params['logic'] = survey_group_logic
        new_params['rights'] = rights
        new_params['name'] = "Grading Survey Group"
        new_params['url_name'] = 'gsoc/grading_survey_group'
        new_params['module_package'] = 'soc.modules.gsoc.views.models'
        new_params['sidebar_grouping'] = "Surveys"

        new_params['scope_view'] = program_view
        new_params['scope_redirect'] = redirects.getCreateRedirect

        new_params['no_admin'] = True
        new_params['no_create_with_key_fields'] = True

        new_params['create_extra_dynaproperties'] = {
            'grading_survey':
            djangoforms.ModelChoiceField(GradingProjectSurvey, required=True),
            'student_survey':
            djangoforms.ModelChoiceField(ProjectSurvey, required=False),
        }

        new_params['extra_dynaexclude'] = [
            'link_id', 'scope', 'scope_path', 'last_update_started',
            'last_update_complete'
        ]

        new_params['edit_extra_dynaproperties'] = {
            'link_id': forms.CharField(widget=forms.HiddenInput),
        }

        patterns = [
            (r'^%(url_name)s/(?P<access_type>records)/%(key_fields)s$',
             '%(module_package)s.%(module_name)s.view_records',
             'Overview of GradingRecords'),
            (r'^%(url_name)s/(?P<access_type>edit_record)/%(key_fields)s$',
             '%(module_package)s.%(module_name)s.edit_record',
             'Edit a GradingRecord'),
        ]

        new_params['extra_django_patterns'] = patterns

        new_params[
            'view_records_template'] = 'soc/grading_survey_group/records.html'
        new_params[
            'records_heading_template'] = 'soc/grading_record/list/heading.html'
        new_params['records_row_template'] = 'soc/grading_record/list/row.html'
        new_params['record_edit_template'] = 'soc/grading_record/edit.html'

        # create the form that will be used to edit a GradingRecord
        record_logic = survey_group_logic.getRecordLogic()

        record_edit_form = dynaform.newDynaForm(
            dynabase=soc.views.helper.forms.BaseForm,
            dynamodel=record_logic.getModel(),
            dynaexclude=[
                'grading_survey_group', 'mentor_record', 'student_record',
                'project'
            ],
        )

        new_params['record_edit_form'] = record_edit_form

        new_params['public_field_keys'] = [
            "name", "last_update_started", "last_update_completed"
        ]
        new_params['public_field_names'] = [
            "Name", "Last update started", "Last update completed"
        ]

        new_params['records_field_extra'] = lambda entity: {
            "project_title":
            entity.project.title,
            "student_name":
            "%s (%s)" %
            (entity.project.student.name, entity.project.student.link_id),
            "organization":
            entity.project.name,
            "mentor_name":
            "%s (%s)" %
            (entity.project.mentor.name, entity.project.mentor.link_id),
            "final_grade":
            entity.grade_decision.capitalize(),
            "mentor_grade": ("Pass" if entity.mentor_record.grade else "Fail")
            if entity.mentor_record else "Not Available",
            "student_eval":
            "Yes" if entity.student_record else "Not Available",
        }
        new_params['records_field_keys'] = [
            "project_title", "student_name", "organization", "mentor_name",
            "final_grade", "mentor_grade", "student_eval", "locked"
        ]
        new_params['records_field_names'] = [
            "Project Name", "Student (link id)", "Organization",
            "Mentor (link id)", "Final Grade", "Mentor Grade", "Student Eval",
            "Locked"
        ]

        params = dicts.merge(params, new_params)

        super(View, self).__init__(params=params)

    @decorators.merge_params
    @decorators.check_access
    def create(self,
               request,
               access_type,
               page_name=None,
               params=None,
               **kwargs):
        """Pass the correct survey queries to GroupForm.

    For params see base.View.create().
    """

        if kwargs.get('scope_path'):
            self.setQueries(kwargs['scope_path'], params['create_form'])

        return super(View, self).create(request,
                                        access_type,
                                        page_name=page_name,
                                        params=params,
                                        **kwargs)

    @decorators.merge_params
    @decorators.check_access
    def edit(self,
             request,
             access_type,
             page_name=None,
             params=None,
             seed=None,
             **kwargs):
        """Pass the correct survey queries to GroupForm.

    For params see base.View.edit().
    """

        self.setQueries(kwargs['scope_path'], params['edit_form'])

        return super(View, self).edit(request,
                                      access_type,
                                      page_name=page_name,
                                      params=params,
                                      seed=seed,
                                      **kwargs)

    def _editGet(self, request, entity, form):
        """Performs any required processing on the form to get its edit page.

    Args:
      request: the django request object
      entity: the entity to get
      form: the django form that will be used for the page
    """

        form.fields['link_id'].initial = entity.link_id

        return super(View, self)._editGet(request, entity, form)

    def _editPost(self, request, entity, fields):
        """See base.View._editPost().
    """

        if not entity:
            # generate a unique link_id
            fields['link_id'] = 't%i' % (int(time.time() * 100))

            # TODO: seriously redesign _editPost to pass along kwargs
            fields['scope_path'] = fields['grading_survey'].scope_path
        else:
            fields['link_id'] = entity.link_id

        # fill in the scope via call to super
        return super(View, self)._editPost(request, entity, fields)

    def setQueries(self, program_keyname, group_form):
        """Add program filtering queries to the GroupForm.

    Args:
      program_keyname: keyname of the program to filter on
      group_form: DynaForm instance to set the queries for
    """

        # fetch the program
        program = program_logic.getFromKeyNameOr404(program_keyname)

        # filter grading surveys by program and use title for display
        grading_query = grading_logic.getQueryForFields(
            filter={'scope_path': program_keyname})

        # filter project surveys by program and use title for display
        student_query = project_logic.getQueryForFields(
            filter={'scope_path': program_keyname})

        group_form.base_fields['grading_survey'].query = grading_query
        group_form.base_fields['student_survey'].query = student_query

        # use survey titles in drop-downs
        self.choiceTitles(group_form, 'grading_survey', grading_logic)
        self.choiceTitles(group_form, 'student_survey', project_logic)

    def choiceTitles(self, group_form, field, logic):
        """Fetch entity titles for choice field entries.

    Args:
      group_form: The form to set the choice field entries for
      field: the field_name to set the choice entries for
      logic: the logic for the model to set the choice entries for
    """

        # TODO(ajaksu): subclass ModelChoiceField so we don't need this method
        choice_list = []

        model = logic.getModel()

        for value, text in tuple(group_form.base_fields[field].choices):
            if value:
                entity = model.get(value)
                text = '%s (%s)' % (entity.title, entity.link_id)
            choice_list.append((value, text))

        choices = tuple(choice_list)

        group_form.base_fields[field].choices = choices

    @decorators.merge_params
    @decorators.check_access
    def viewRecords(self,
                    request,
                    access_type,
                    page_name=None,
                    params=None,
                    **kwargs):
        """View which shows all collected records for a given GradingSurveyGroup.

    For args see base.View.public().
    """

        from google.appengine.api.labs import taskqueue

        from soc.logic import lists as lists_logic

        survey_group_logic = params['logic']
        record_logic = survey_group_logic.getRecordLogic()

        try:
            entity = survey_group_logic.getFromKeyFieldsOr404(kwargs)
        except out_of_band.Error, error:
            return responses.errorResponse(error,
                                           request,
                                           template=params['error_public'])

        # get the context for this webpage
        context = responses.getUniversalContext(request)
        responses.useJavaScript(context, params['js_uses_all'])
        context['page_name'] = "%s for %s named '%s'" % (
            page_name, params['name'], entity.name)
        context['entity'] = entity
        template = params['view_records_template']

        # get the POST request dictionary and check if we should take action
        post_dict = request.POST

        if post_dict.get('update_records'):
            # start the task to update all GradingRecords for the given group
            task_params = {'group_key': entity.key().id_or_name()}
            task_url = '/tasks/grading_survey_group/update_records'

            new_task = taskqueue.Task(params=task_params, url=task_url)
            new_task.add()

            # update the GradingSurveyGroup with the new timestamp
            fields = {'last_update_started': datetime.datetime.now()}
            survey_group_logic.updateEntityProperties(entity, fields)

            context['message'] = 'Grading Records update successfully started.'

        if post_dict.get('update_projects'):
            # start the task to update all StudentProjects for the given group
            task_params = {'group_key': entity.key().id_or_name()}
            task_url = '/tasks/grading_survey_group/update_projects'

            new_task = taskqueue.Task(params=task_params, url=task_url)
            new_task.add()

            context[
                'message'] = 'Student Projects update successfully started.'

        if post_dict.get('update_projects_and_mail'):
            # Start the task to update all StudentProjects for the given group and
            # send out emails.
            task_params = {
                'group_key': entity.key().id_or_name(),
                'send_mail': 'true'
            }
            task_url = '/tasks/grading_survey_group/update_projects'

            new_task = taskqueue.Task(params=task_params, url=task_url)
            new_task.add()

            context['message'] = (
                'Student Projects update successfully started. '
                'And sending out e-mail with the results.')

        list_params = params.copy()
        list_params['logic'] = record_logic
        list_params['list_heading'] = params['records_heading_template']
        list_params['list_row'] = params['records_row_template']
        list_params['public_row_extra'] = lambda entity: {
            'link': redirects.getEditGradingRecordRedirect(
                entity, list_params)
        }
        # TODO(LIST)
        fields = {'grading_survey_group': entity}

        # list all records with grading_decision set to pass
        fields['grade_decision'] = 'pass'

        # get the list content for passing records
        pr_params = list_params.copy()
        pr_params['list_description'] = \
            'List of all Records which have their grading outcome set to pass.'
        pr_list = lists.getListContent(request, pr_params, fields, idx=0)

        # list all records with grading_decision set to fail
        fields['grade_decision'] = 'fail'

        # get the list content for all failing records
        fr_params = list_params.copy()
        fr_params['list_description'] = \
            'List of all Records which have their grading outcome set to fail.'
        fr_list = lists.getListContent(request, fr_params, fields, idx=1)

        # list all records with grading decision set to undecided
        fields['grade_decision'] = 'undecided'

        # get the list content for all undecided records
        ur_params = list_params.copy()
        ur_params['list_description'] = \
            'List of all Records which have their grading outcome set to undecided.'
        ur_list = lists.getListContent(request, ur_params, fields, idx=2)

        # specify the contents and create a Lists object for use in the context
        contents = [pr_list, fr_list, ur_list]
        context['list'] = lists_logic.Lists(contents)

        return responses.respond(request, template, context)
Пример #52
0
        if request.POST and request.POST.get("start"):
            # button has been pressed start the task
            task_params = {
                "program_key": survey_logic.getScope(entity).key().id_or_name(),
                "survey_key": entity.key().id_or_name(),
                "survey_type": params["survey_type"],
            }
            task_url = "/tasks/surveys/projects/send_reminder/spawn"

            new_task = taskqueue.Task(params=task_params, url=task_url)
            new_task.add()

            context["message"] = "Task successfully started!"

        template = params["reminder_template"]
        return responses.respond(request, template, context)


view = View()

create = decorators.view(view.create)
edit = decorators.view(view.edit)
delete = decorators.view(view.delete)
list = decorators.view(view.list)
public = decorators.view(view.public)
record = decorators.view(view.viewRecord)
results = decorators.view(view.viewResults)
send_reminder = decorators.view(view.sendReminder)
take = decorators.view(view.take)
Пример #53
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)
Пример #54
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)
Пример #55
0
        context['page_name'] = "%s titled '%s'" % (page_name,
                                                   survey_entity.title)
        context['entity'] = survey_entity
        context['record'] = record_entity

        # store the read only survey form in the context
        survey_form = params['survey_record_form'](
            survey=survey_entity,
            survey_record=record_entity,
            survey_logic=self._params['logic'],
            read_only=True)
        survey_form.getFields()
        context['survey_form'] = survey_form

        template = params['record_template']
        return responses.respond(request, template, context)

    @decorators.merge_params
    @decorators.check_access
    def exportSerialized(self,
                         request,
                         access_type,
                         page_name=None,
                         params=None,
                         **kwargs):
        """Exports Surveys in JSON format.

    For args see base.View.public().
    """

        survey_logic = params['logic']