Beispiel #1
0
  def listPublic(self, request, access_type, page_name=None,
                 params=None, filter=None, **kwargs):
    """See base.View.list.
    """

    account = accounts.getCurrentAccount()
    user = user_logic.logic.getForAccount(account) if account else None

    try:
      rights = self._params['rights']
      rights.setCurrentUser(account, user)
      rights.checkIsHost()
      is_host = True
    except out_of_band.Error:
      is_host = False

    params = params.copy()

    if is_host:
      params['list_action'] = (redirects.getAdminRedirect, params)
    else:
      params['list_action'] = (redirects.getPublicRedirect, params)

    new_filter = {}

    new_filter['scope_path'] = kwargs['scope_path']
    new_filter['status'] = 'active'
    filter = dicts.merge(filter, new_filter)

    content = lists.getListContent(request, params, filter)
    contents = [content]

    return self._list(request, params, contents, page_name)
Beispiel #2
0
    def _selectProjects(self, request, page_name, params, survey, fields):
        """Shows a view upon which a User can select a Student Project to fill in
    the ProjectSurvey for.

    Args:
      survey: a Survey entity
      fields: the filter to use on the Project List
      rest: see base.View.public()
    """

        from soc.views.models.student_project import view as student_project_view

        student_project_params = student_project_view.getParams().copy()

        redirect_dict = {"survey": survey, "params": params}

        student_project_params["list_action"] = (redirects.getTakeProjectSurveyRedirect, redirect_dict)
        student_project_params["list_description"] = "Select a %s for which to fill in the %s named %s" % (
            student_project_params["name"],
            params["name"],
            survey.title,
        )

        content = lists.getListContent(request, student_project_params, fields)
        contents = [content]

        return self._list(request, student_project_params, contents, page_name)
Beispiel #3
0
    def _getOrgsWithAcceptedApps(self, request, program_entity, params):
        """
    """

        fmt = {'name': program_entity.name}
        description = self.DEF_ACCEPTED_ORGS_MSG_FMT % fmt

        filter = {
            'status': 'accepted',
            'scope': program_entity,
        }

        from soc.views.models import org_app as org_app_view
        aa_params = org_app_view.view.getParams().copy(
        )  # accepted applications

        # define the list redirect action to show the notification
        del aa_params['list_key_order']
        aa_params['public_row_extra'] = lambda entity: {
            'link': redirects.getHomeRedirect(entity, aa_params)
        }
        aa_params['list_description'] = description
        # TODO(LIST)
        aa_list = lists.getListContent(request,
                                       aa_params,
                                       filter,
                                       idx=0,
                                       need_content=True)

        return aa_list
Beispiel #4
0
  def list(self, request, access_type,
           page_name=None, params=None, filter=None, order=None, **kwargs):
    """Lists all notifications that the current logged in user has stored.

    for parameters see base.list()
    """

    # get the current user
    user_entity = user_logic.getForCurrentAccount()

    # only select the notifications for this user so construct a filter
    filter = {
        'scope': user_entity,
        'unread': True,
        }

    # create the list parameters
    un_params = params.copy() # unread notifications

    # define the list redirect action to show the notification
    un_params['list_action'] = (redirects.getPublicRedirect, params)
    un_params['list_description'] = ugettext(
        "An overview of your unread Notifications.")

    # TODO(Lennard) when list sorting is implemented sort on descending date
    un_list = list_helper.getListContent(
        request, un_params, filter, idx=0)

    # Now get the read list

    # Reuse the filter, but only for read notifications
    filter['unread'] = False

    rn_params = params.copy() # read notifications

    rn_params['list_action'] = (redirects.getPublicRedirect, params)
    rn_params['list_description'] = ugettext(
        "An overview of your read Notifications.")

    rn_list = list_helper.getListContent(
        request, rn_params, filter, idx=1)

    # fill contents with all the needed lists
    contents = [un_list, rn_list]

    # call the _list method from base to display the list
    return self._list(request, params, contents, page_name)
Beispiel #5
0
  def listSelf(self, request, access_type,
               page_name=None, params=None, **kwargs):
    """Lists all proposals from the current logged-in user 
       for the given student.

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

    context = {}
    student_entity = student_logic.logic.getFromKeyName(kwargs['scope_path'])

    filter = {'scope' : student_entity,
              'status': ['new', 'pending', 'accepted', 'rejected']}

    list_params = params.copy()
    list_params['list_description'] = \
        'List of my %(name_plural)s.' % list_params
    list_params['list_action'] = (redirects.getPublicRedirect, list_params)

    valid_list = lists.getListContent(
        request, list_params, filter, idx=0)

    ip_params = list_params.copy() # ineligible proposals

    description = ugettext('List of my ineligible/withdrawn %s.') % (
        ip_params['name_plural'])

    ip_params['list_description'] = description
    ip_params['list_action'] = (redirects.getPublicRedirect, ip_params)

    filter = {'scope' : student_entity,
              'status': 'invalid'}

    ip_list = lists.getListContent(
        request, ip_params, filter, idx=1, need_content=True)

    contents = []
    # fill contents with all the needed lists
    contents.append(valid_list)

    if ip_list != None:
      contents.append(ip_list)

    # call the _list method from base to display the list
    return self._list(request, list_params, contents, page_name, context)
Beispiel #6
0
    def _public(self, request, entity, context):
        """See base.View._public().
    """
        # TODO: This needs to be moved to the GSoC module
        from soc.modules.gsoc.views.models import student_project as \
            student_project_view

        program_entity = entity.scope

        if timeline_helper.isAfterEvent(
                program_entity.timeline,
                'accepted_students_announced_deadline'):
            # accepted projects
            ap_params = student_project_view.view.getParams().copy()

            # define the list redirect action to show the notification
            ap_params['public_row_extra'] = lambda entity: {
                'link': (redirects.getPublicRedirect, ap_params)
            }
            ap_params[
                'list_description'] = self.DEF_ACCEPTED_PROJECTS_MSG_FMT % (
                    entity.name)
            ap_params['list_heading'] = 'soc/student_project/list/heading.html'
            ap_params['list_row'] = 'soc/student_project/list/row.html'
            # TODO(LIST)
            # only show projects that have not failed
            filter = {'scope': entity, 'status': ['accepted', 'completed']}

            ap_list = lists.getListContent(request,
                                           ap_params,
                                           filter,
                                           idx=0,
                                           need_content=True)

            contents = []

            if ap_list:
                # this is a temporary fix for sorting Student Projects
                # by Student name until we have a view that default
                # sorts it self by name (right now we can't do such query)
                ap_list['data'].sort(key=lambda sp: sp.student.name().lower())

                contents.append(ap_list)

            # construct the list and put it into the context
            context['list'] = soc.logic.lists.Lists(contents)

            # obtain data to construct the organization map as json object
            context['org_map_data'] = self._getMapData(filter)

        return super(View, self)._public(request=request,
                                         entity=entity,
                                         context=context)
Beispiel #7
0
  def listRoles(self, request, access_type,
                page_name=None, params=None, **kwargs):
    """Gives an overview of all the roles in a specific group.

    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
    """

    # set the pagename to include the link_id
    page_name = '%s %s' % (page_name, kwargs['link_id'])

    # get the group from the request
    group_logic = params['logic']

    group_entity = group_logic.getFromKeyFields(kwargs)

    # create the filter
    filter = {
        'scope' : group_entity,
        'status': 'active'
        }

    role_views = params['role_views']
    contents = []
    index = 0

    # for each role we create a separate list
    for role_name in role_views.keys():
      # create the list parameters
      list_params = role_views[role_name].getParams().copy()

      list_params['list_action'] = (redirects.getManageRedirect, list_params)
      list_params['list_description'] = ugettext(
          "An overview of the %s for this %s." % (
          list_params['name_plural'], params['name']))

      new_list_content = list_helper.getListContent(
          request, list_params, filter, idx=index)

      contents += [new_list_content]

      index += 1

    # call the _list method from base.View to show the list
    return self._list(request, params, contents, page_name)
Beispiel #8
0
  def acceptedOrgs(self, request, access_type,
                   page_name=None, params=None, filter=None, **kwargs):
    """See base.View.list.
    """

    contents = []
    logic = params['logic']

    program_entity = logic.getFromKeyFieldsOr404(kwargs)

    fmt = {'name': program_entity.name}
    description = self.DEF_ACCEPTED_ORGS_MSG_FMT % fmt

    filter = {
        'status': 'accepted',
        'scope': program_entity,
        }

    from soc.views.models import org_app as org_app_view
    aa_params = org_app_view.view.getParams().copy() # accepted applications

    # define the list redirect action to show the notification
    del aa_params['list_key_order']
    aa_params['list_action'] = (redirects.getHomeRedirect, aa_params)
    aa_params['list_description'] = description

    aa_list = lists.getListContent(request, aa_params, filter, idx=0,
                                   need_content=True)

    if aa_list:
      contents.append(aa_list)

    use_cache = not aa_list # only cache if there are no aa's left
    description = self.DEF_CREATED_ORGS_MSG_FMT % fmt

    filter['status'] = ['new', 'active']

    from soc.views.models.organization import view as org_view
    ao_params = org_view.getParams().copy() # active orgs
    ao_list = self._getAcceptedOrgsList(description, ao_params, 
        filter, use_cache)

    contents.append(ao_list)

    params = params.copy()
    params['list_msg'] = program_entity.accepted_orgs_msg

    return self._list(request, params, contents, page_name)
Beispiel #9
0
  def _public(self, request, entity, context):
    """See base.View._public().
    """

    from soc.views.models import student_project as student_project_view

    program_entity = entity.scope

    if timeline_helper.isAfterEvent(program_entity.timeline,
                                    'accepted_students_announced_deadline'):
      # accepted projects
      ap_params = student_project_view.view.getParams().copy()

      # define the list redirect action to show the notification
      ap_params['list_action'] = (redirects.getPublicRedirect, ap_params)
      ap_params['list_description'] = self.DEF_ACCEPTED_PROJECTS_MSG_FMT %(
          entity.name)
      ap_params['list_heading'] = 'soc/student_project/list/heading.html'
      ap_params['list_row'] = 'soc/student_project/list/row.html'

      # only show projects that have not failed
      filter = {'scope': entity,
                'status': ['accepted', 'completed']}

      ap_list = lists.getListContent(request, ap_params, filter, idx=0,
                                     need_content=True)

      contents = []

      if ap_list:
        # this is a temporary fix for sorting Student Projects 
        # by Student name until we have a view that default 
        # sorts it self by name (right now we can't do such query)
        ap_list['data'].sort(key=lambda sp: sp.student.name().lower())

        contents.append(ap_list)

      # construct the list and put it into the context
      context['list'] = soc.logic.lists.Lists(contents)

      # obtain data to construct the organization map as json object
      context['org_map_data'] = self._getMapData(filter)
      
    news_feed = NewsFeed(entity)
    context['news_feed'] = news_feed.getFeed()
    
    return super(View, self)._public(request=request, entity=entity,
                                     context=context)
Beispiel #10
0
  def _applicationListConstructor(self, request, params, page_name, filter={}, 
                                  selection=[], **kwargs):
    """Constructs the list containing applications for the given the arguments.
    
    Args:
      filter: This is the filter used for all application
      selection: This is a list containing tuples stating the status for an
        application and the redirect action.
      See base.View.public() for the rest.
    
    Returns:
      HTTP Response containing the list view.

    """

    contents = []
    list_params = params.copy()
    index = 0

    if not filter:
      filter = {}

    for status, action in selection:
      # only select the requests that have been pre-accpeted
      filter['status'] = status

      name = status[0] if isinstance(status, list) else status

      list_params['list_description'] = (
          DEF_APPLICATION_LIST_DESCRIPTION_FMT % (
          {'name_plural': params['name_plural'], 'status': name}))
      list_params['list_action'] = action

      list_content = list_helper.getListContent(
          request, list_params, filter, idx=index)

      contents += [list_content]

      index += 1

    # call the _list method from base to display the list
    if kwargs.get('context'):
      context = kwargs['context']
    else:
      context = {}

    return self._list(request, params, contents, page_name, context=context)
Beispiel #11
0
  def _public(self, request, entity, context):
    """See base.View._public().
    """

    from soc.views.models import student_project as student_project_view

    program_entity = entity.scope

    if timeline_helper.isAfterEvent(program_entity.timeline,
                                    'accepted_students_announced_deadline'):
      # accepted projects
      ap_params = student_project_view.view.getParams().copy() 

      # define the list redirect action to show the notification
      ap_params['list_action'] = (redirects.getPublicRedirect, ap_params)
      ap_params['list_description'] = self.DEF_ACCEPTED_PROJECTS_MSG_FMT % (
          entity.name)
      ap_params['list_heading'] = 'soc/student_project/list/heading.html'
      ap_params['list_row'] = 'soc/student_project/list/row.html'

      # only show projects that have not failed
      filter = {'scope': entity,
                'status': ['accepted', 'mid_term_passed', 'passed']}

      ap_list = lists.getListContent(request, ap_params, filter, idx=0,
                                     need_content=True)

      contents = []

      if ap_list:
        contents.append(ap_list)

      # construct the list and put it into the context
      context['list'] = soc.logic.lists.Lists(contents)

      # obtain data to construct the organization map as json object
      context['org_map_data'] = self._getMapData(ap_params, filter)

    return super(View, self)._public(request=request, entity=entity,
                                     context=context)
Beispiel #12
0
  def _getEvaluationLists(self, request, params, entity):
    """Returns List Object containing the list to be shown on the Student 
    Project's manage page.

    This list contains all Surveys that have at least one record and will also 
    contain information about the presence (or absence) of a accompanying 
    record for the given Student Project.

    Args:
      request: Django HTTP Request Object
      params: the params dict for this View
      entity: a StudentProject entity for which the Surveys(Records) should be
              retrieved

    Returns:
      A List Object as specified by this method.
    """

    from soc.views.helper import list_info
    from soc.views.models.grading_project_survey import view as \
        grading_survey_view
    from soc.views.models.project_survey import view as project_survey_view

    fields = {'scope_path': entity.program.key().id_or_name()}

    # get the GradingProjectSurvey list
    gps_params = grading_survey_view.getParams().copy()
    gps_params['list_key_order'] = None
    gps_params['list_heading'] = gps_params['manage_student_project_heading']
    gps_params['list_row'] = gps_params['manage_student_project_row']
    gps_params['list_info'] = (
        list_info.getProjectSurveyInfoForProject(entity, gps_params), None)

    # list all surveys for this Project's Program
    fields['scope_path'] = entity.program.key().id_or_name()
    gps_params['list_description'] = \
        'List of all Mentor Evaluations for this Project'
    gps_params['list_action'] = None

    gps_list = lists.getListContent(
        request, gps_params, fields, idx=0)

    # get the ProjectSurvey list
    ps_params = project_survey_view.getParams().copy()
    ps_params['list_key_order'] = None
    ps_params['list_heading'] = ps_params['manage_student_project_heading']
    ps_params['list_row'] = ps_params['manage_student_project_row']
    ps_params['list_info'] = (
        list_info.getProjectSurveyInfoForProject(entity, ps_params), None)

    ps_params['list_description'] = \
        'List of all Student Evaluations for this Project'
    ps_params['list_action'] = None

    # list all surveys for this Project's Program
    fields['scope_path'] = entity.program.key().id_or_name()
    ps_list = lists.getListContent(
        request, ps_params, fields, idx=1)

    # store both lists in the content
    content = [gps_list, ps_list]

    for list in content:
      # remove all the surveys that have no records attached
      list['data'] = [i for i in list['data'] if
                      list['logic'].hasRecord(i)]

    # return the List Object with the filtered list content
    return soc.logic.lists.Lists(content)
Beispiel #13
0
  def _getEvaluationLists(self, request, params, entity):
    """Returns List Object containing the list to be shown on the Student 
    Project's manage page.

    This list contains all Surveys that have at least one record and will also 
    contain information about the presence (or absence) of a accompanying 
    record for the given Student Project.

    Args:
      request: Django HTTP Request Object
      params: the params dict for this View
      entity: a StudentProject entity for which the Surveys(Records) should be
              retrieved

    Returns:
      A List Object as specified by this method.
    """

    import soc.logic.lists

    from soc.modules.gsoc.views.helper import list_info
    from soc.modules.gsoc.views.models.grading_project_survey import view as \
        grading_survey_view
    from soc.modules.gsoc.views.models.project_survey import view as \
        project_survey_view

    fields = {'scope_path': entity.program.key().id_or_name()}

    # get the GradingProjectSurvey list
    gps_params = grading_survey_view.getParams().copy()
    gps_params['list_key_order'] = None
    gps_params['list_heading'] = gps_params['manage_student_project_heading']
    gps_params['list_row'] = gps_params['manage_student_project_row']

    # list all surveys for this Project's Program
    fields['scope_path'] = entity.program.key().id_or_name()
    gps_params['list_description'] = \
        'List of all Mentor Evaluations for this Project'
    gps_params['public_row_extra'] = lambda entity: {}
    gps_params['public_row_action'] = {}
# TODO(LIST)
    gps_list = lists.getListContent(
        request, gps_params, fields, idx=0)
    list_info.setProjectSurveyInfoForProject(gps_list, entity, gps_params)

    # get the ProjectSurvey list
    ps_params = project_survey_view.getParams().copy()
    ps_params['list_key_order'] = None
    ps_params['list_heading'] = ps_params['manage_student_project_heading']
    ps_params['list_row'] = ps_params['manage_student_project_row']

    ps_params['list_description'] = \
        'List of all Student Evaluations for this Project'
    ps_params['public_row_extra'] = lambda entity: {}
    ps_params['public_row_action'] = {}

    # list all surveys for this Project's Program
    fields['scope_path'] = entity.program.key().id_or_name()
    ps_list = lists.getListContent(
        request, ps_params, fields, idx=1)
    list_info.setProjectSurveyInfoForProject(ps_list, entity, ps_params)

    # store both lists in the content
    content = [gps_list, ps_list]

    for list in content:
      # remove all the surveys that have no records attached
      list['data'] = [i for i in list['data'] if
                      list['logic'].hasRecord(i)]

    # return the List Object with the filtered list content
    return soc.logic.lists.Lists(content)
Beispiel #14
0
  def manageOverview(self, request, access_type,
             page_name=None, params=None, **kwargs):
    """View that allows Organization Admins to see an overview of 
       their Organization's Student Projects.

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

    # make sure the organization exists
    org_entity = org_logic.getFromKeyNameOr404(kwargs['scope_path'])
    fields = {'scope': org_entity}

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

    list_params = params.copy()

    #list all active projects
    fields['status'] = ['accepted', 'mid_term_passed']
    active_params = list_params.copy()
    active_params['list_description'] = \
        'List of all active %(name_plural)s' % list_params
    active_params['list_action'] = (redirects.getManageRedirect, list_params)

    active_list = lists.getListContent(
        request, active_params, fields, idx=0)

    # list all failed projects
    fields['status'] = ['mid_term_failed', 'final_failed']
    failed_params = list_params.copy()
    failed_params['list_description'] = ('List of all failed %(name_plural)s, '
        'these cannot be managed.') % list_params
    failed_params['list_action'] = (redirects.getPublicRedirect, list_params)

    failed_list = lists.getListContent(
        request, failed_params, fields, idx=1, need_content=True)

    #list all completed projects
    fields['status'] = ['passed']
    completed_params = list_params.copy()
    completed_params['list_description'] = ('List of %(name_plural)s that have '
        'successfully completed the program, '
        'these cannot be managed.' % list_params)
    completed_params['list_action'] = (redirects.getPublicRedirect, list_params)

    completed_list = lists.getListContent(
        request, completed_params, fields, idx=2, need_content=True)

    # always show the list with active projects
    content = [active_list]

    if failed_list != None:
      # do not show empty failed list
      content.append(failed_list)

    if completed_list != None:
      # do not show empty completed list
      content.append(completed_list)

    # call the _list method from base to display the list
    return self._list(request, list_params, content,
                      context['page_name'], context)
Beispiel #15
0
      return responses.errorResponse(
          error, request, template=params['error_public'])

    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['list_action'] = (redirects.getEditGradingRecordRedirect,
                                  list_params)

    fields = {'grading_survey_group': survey_group}

    # get the list content for all records
    list_params['list_description'] = \
        'List of all GradingRecords. Pick one to edit it.'
    list_content = lists.getListContent(
        request, list_params, fields, idx=0)

    contents = [list_content]

    # return the view which renders the set content
    return self._list(request, list_params, contents, page_name)


view = View()

create = decorators.view(view.create)
delete = decorators.view(view.delete)
edit = decorators.view(view.edit)
edit_record = decorators.view(view.editRecord)
list = decorators.view(view.list)
public = decorators.view(view.public)
Beispiel #16
0
  def listRequests(self, request, access_type,
                   page_name=None, params=None, **kwargs):
    """Gives an overview of all the requests for a specific group.

    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
    """

    # set the pagename to include the link_id
    page_name = '%s %s' % (page_name, kwargs['link_id'])

    # get the group from the request
    group_logic = params['logic']

    group_entity = group_logic.getFromKeyFields(kwargs)

    role_names = params['role_views'].keys()

    # list all incoming requests
    filter = {
        'scope': group_entity,
        'role': role_names,
        'status': 'new'
        }

    # create the list parameters
    inc_req_params = request_view.getParams()

    # define the list redirect action to the request processing page
    inc_req_params['list_action'] = (redirects.getProcessRequestRedirect, None)
    inc_req_params['list_description'] = ugettext(
        "An overview of the %(name)s's incoming requests." % params)

    inc_req_content = list_helper.getListContent(
        request, inc_req_params, filter, idx=0)

    # list all outstanding invites
    filter = {
        'scope': group_entity,
        'role': role_names,
        'status': 'group_accepted'
        }

    # create the list parameters
    out_inv_params = request_view.getParams()

    # define the list redirect action to the request processing page
    out_inv_params['list_action'] = (redirects.getProcessRequestRedirect, None)
    out_inv_params['list_description'] = ugettext(
        "An overview of the %(name)s's outstanding invites." % params)

    out_inv_content = list_helper.getListContent(
        request, out_inv_params, filter, idx=1)

    # list all ignored requests
    filter = {
        'scope': group_entity,
        'role': role_names,
        'status': 'ignored'
        }

    # create the list parameters
    ignored_params = request_view.getParams()

    # define the list redirect action to the request processing page
    ignored_params['list_action'] = (redirects.getProcessRequestRedirect, None)
    ignored_params['list_description'] = ugettext(
        "An overview of the %(name)s's ignored requests." % params)

    ignored_content = list_helper.getListContent(
        request, ignored_params, filter, idx=2)

    contents = [inc_req_content, out_inv_content, ignored_content]

    return self._list(request, params, contents, page_name)
Beispiel #17
0
    def _public(self, request, entity, context):
        """See base.View._public().
    """
        #TODO(LIST)
        from soc.modules.ghop.views.models import task as ghop_task_view

        contents = []

        ghop_program_entity = entity.scope

        is_after_student_signup = timeline_helper.isAfterEvent(
            ghop_program_entity.timeline, 'student_signup_start')

        is_after_tasks_become_public = timeline_helper.isAfterEvent(
            ghop_program_entity.timeline, 'tasks_publicly_visible')

        if is_after_student_signup and is_after_tasks_become_public:
            # open tasks
            to_params = ghop_task_view.view.getParams().copy()

            # define the list redirect action to show the task public page
            to_params['public_row_extra'] = lambda entity: {
                'link': redirects.getPublicRedirect(entity, to_params)
            }
            to_params['list_description'] = self.DEF_OPEN_PROJECTS_MSG_FMT % (
                entity.name)
            to_params['list_heading'] = 'modules/ghop/task/list/heading.html'
            to_params['list_row'] = 'modules/ghop/task/list/row.html'

            filter = {'scope': entity, 'status': ['Open', 'Reopened']}

            to_list = lists.getListContent(request,
                                           to_params,
                                           filter,
                                           idx=0,
                                           need_content=True)

            if to_list:
                to_list['data'].sort(key=lambda task: task.modified_on)

                contents.append(to_list)

            # claimed tasks
            tc_params = to_params.copy()

            tc_params[
                'list_description'] = self.DEF_CLAIMED_PROJECTS_MSG_FMT % (
                    entity.name)

            filter = {
                'scope':
                entity,
                'status': [
                    'ClaimRequested', 'Claimed', 'NeedsAction', 'NeedsReview',
                    'NeedsWork'
                ]
            }

            tc_list = lists.getListContent(request,
                                           tc_params,
                                           filter,
                                           idx=1,
                                           need_content=True)

            if tc_list:
                tc_list['data'].sort(key=lambda task: task.modified_on)

                contents.append(tc_list)

            # closed tasks
            tcs_params = to_params.copy()

            tcs_params[
                'list_description'] = self.DEF_CLOSED_PROJECTS_MSG_FMT % (
                    entity.name)

            filter = {
                'scope': entity,
                'status': ['AwaitingRegistration', 'Closed']
            }

            tcs_list = lists.getListContent(request,
                                            tcs_params,
                                            filter,
                                            idx=2,
                                            need_content=True)

            if tcs_list:
                tcs_list['data'].sort(key=lambda task: task.modified_on)

                contents.append(tcs_list)

            # construct the list and put it into the context
            context['list'] = soc.logic.lists.Lists(contents)

        return super(View, self)._public(request=request,
                                         entity=entity,
                                         context=context)
Beispiel #18
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)
Beispiel #19
0
    )[0]

    context['record_redirect'] = redirects.getSurveyRecordRedirect(
    entity, params)
    
    filter = self._params.get('filter') or {}

    filter['survey'] = entity

    list_params = params.copy()
    list_params['list_description'] = \
      'List of  %(name_plural)s.' % list_params

    list_params['logic'] = results_logic

    valid_list = lists.getListContent(request, list_params, filter, idx=0)

    valid_list['row'] = 'soc/survey/list/results_row.html'
    valid_list['heading'] = 'soc/survey/list/results_heading.html'
    valid_list['description'] = 'Survey Results:'

    contents = []
    # fill contents with all the needed lists
    contents.append(valid_list)

    return self._list(request, list_params, contents, page_name, context)

  @decorators.merge_params
  @decorators.check_access
  def viewRecord(self, request, access_type, page_name=None,
                       params=None, **kwargs):
Beispiel #20
0
class View(survey_view.View):
    """View methods for the ProjectSurvey 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
    """

        new_params = {}
        new_params['logic'] = org_app_logic

        new_params['name'] = "Org Application Survey"
        new_params['url_name'] = 'org_app'

        new_params['extra_dynaexclude'] = ['taking_access']

        new_params['survey_take_form'] = OrgAppSurveyForm
        new_params['survey_record_form'] = OrgAppRecordForm

        new_params['extra_django_patterns'] = [
            (r'^%(url_name)s/(?P<access_type>list_self)/%(key_fields)s$',
             '%(module_package)s.%(module_name)s.list_self',
             'Overview of %(name_plural)s Taken by You'),
        ]

        params = dicts.merge(params, new_params, sub_merge=True)

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

    @decorators.check_access
    def create(self,
               request,
               access_type,
               page_name=None,
               params=None,
               **kwargs):
        """Displays the create page for this entity type.

    If an OrgAppSurvey already exists it will redirect to the edit page.
    """

        params = dicts.merge(params, self._params)
        program_view = params['scope_view']
        program_logic = program_view.getParams()['logic']

        program_entity = program_logic.getFromKeyName(kwargs['scope_path'])
        org_app = org_app_logic.getForProgram(program_entity)

        if org_app:
            # redirect to edit page
            return http.HttpResponseRedirect(
                redirects.getEditRedirect(org_app, params))
        else:
            # show create page
            return super(View, self).create(request,
                                            access_type,
                                            page_name=page_name,
                                            params=params,
                                            **kwargs)

    def _getSurveyRecordFor(self, survey, request, params):
        """Returns the SurveyRecord for the given Survey and request.

    This method also take the ID specified as GET param into
    account when querying for the SurveyRecord.

    For params see survey.View._getSurveyRecordFor().
    """

        get_dict = request.GET
        record_id = get_dict.get('id', None)

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

        if not record_id or not record_id.isdigit():
            return None
        else:
            return record_logic.getFromIDOr404(int(record_id))

    def _takeGet(self, request, template, context, params, entity, record,
                 **kwargs):
        """Hooking into the view for the take's page GET request.

    For params see survey.View._takeGet().
    """

        # the form action should contain the requested record
        if record:
            context['form_action'] = "?id=%s" % (request.GET['id'])

    def _takePost(self, request, params, entity, record, properties):
        """Hook into the view for the take's page POST request.

    For params see survey.View._takePost().
    """

        from soc.logic.models.user import logic as user_logic

        if not record:
            # creating a new record
            user_entity = user_logic.getForCurrentAccount()
            properties['main_admin'] = user_entity

            if properties['agreed_to_tos']:
                properties['agreed_to_admin_agreement'] = True

        # remove fields we don't need to store in the SurveyRecord
        properties.pop('tos')
        properties.pop('agreed_to_tos')

    def _getRedirectOnSuccessfulTake(self, request, params, survey, record):
        """Returns a path to which the user should be redirected after successfully
    taking a OrgAppSurvey.
    """
        return request.path + '?id=' + str(record.key().id_or_name())

    @decorators.merge_params
    @decorators.check_access
    def list_self(self,
                  request,
                  access_type,
                  page_name=None,
                  params=None,
                  **kwargs):
        """View that lists all the OrgRecords you have access to.

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

        from soc.logic.models.user import logic as user_logic

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

        try:
            entity = survey_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['entity'] = entity

        list_contents = []
        user_entity = user_logic.getForCurrentAccount()

        list_params = params.copy()
        list_params['logic'] = record_logic
        list_params[
            'list_heading'] = 'soc/org_app_survey/list/records_heading.html'
        list_params['list_row'] = 'soc/org_app_survey/list/records_row.html'

        if timeline_helper.isActivePeriod(entity, 'survey'):
            info = {'url_name': list_params['url_name'], 'survey': entity}
            list_params['public_row_extra'] = lambda entity: {
                'link': redirects.getRetakeOrgAppSurveyRedirect(entity, info)
            }
        else:
            list_params['public_row_extra'] = lambda entity: {
                'link': redirects.getViewSurveyRecordRedirect(
                    entity, list_params)
            }

        fields = {'survey': entity, 'main_admin': user_entity}
        list_params['list_description'] = \
            'List of Applications for which you are Main Admin.'
        main_list = lists.getListContent(request,
                                         list_params,
                                         fields,
                                         need_content=True,
                                         idx=0)
        # TODO(LIST)
        if main_list:
            list_contents.append(main_list)

        fields = {'survey': entity, 'backup_admin': user_entity}
        list_params['list_description'] = \
            'List of Applications for which your are Backup Admin.'
        backup_list = lists.getListContent(request,
                                           list_params,
                                           fields,
                                           need_content=True,
                                           idx=1)

        if backup_list:
            list_contents.append(backup_list)

        return self._list(request, list_params, list_contents, page_name,
                          context)