Beispiel #1
0
  def select(self, request, view, redirect,
             page_name=None, params=None, filter=None):
    """Displays a list page allowing the user to select an entity.

    After having selected the Scope, the user is redirected to the
    'create a new entity' page with the scope_path set appropriately.

    Params usage:
      The params dictionary is also passed to getListContent from
        the helper.list module, please refer to its docstring also.
      The params dictionary is passed to self._list as well, refer
        to its docstring for details on how it uses it.

    Args:
      request: the standard Django HTTP request object
      view: the view for which to generate the select page
      redirect: the redirect to use
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      filter: a filter that all displayed entities should satisfy
    """

    params = dicts.merge(params, view.getParams())
    params = dicts.merge(params, self._params)
    params['list_action'] = (redirect, self._params)
    params['list_description'] = self.DEF_CREATE_INSTRUCTION_MSG_FMT % (
        params['name'], self._params['name'])

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

    return self._list(request, params, contents, page_name)
Beispiel #2
0
  def testMergeWhenBothSubListsAndDictsArePresent(self):
    """Tests that lists and dicts can not be merged.
    """
    #do not merge lists and dicts and sub_merge is True
    target = self.dummy_dict.copy()
    target.update({'foo': {'alpha': 1, 'beta': 2}})
    updates = {'foo':['gamma', 'delta']}
    expected = target
    self.assertEqual(dicts.merge(target, updates), expected)

    target = self.dummy_dict.copy()
    target.update({'foo':['gamma', 'delta']})
    updates = {'foo': {'alpha': 1, 'beta': 2}}
    expected = target
    self.assertEqual(dicts.merge(target, updates), expected)
Beispiel #3
0
    def testMergeWhenBothSubListsAndDictsArePresent(self):
        """Tests that lists and dicts can not be merged.
    """
        # do not merge lists and dicts and sub_merge is True
        target = self.dummy_dict.copy()
        target.update({"foo": {"alpha": 1, "beta": 2}})
        updates = {"foo": ["gamma", "delta"]}
        expected = target
        self.assertEqual(dicts.merge(target, updates), expected)

        target = self.dummy_dict.copy()
        target.update({"foo": ["gamma", "delta"]})
        updates = {"foo": {"alpha": 1, "beta": 2}}
        expected = target
        self.assertEqual(dicts.merge(target, updates), expected)
Beispiel #4
0
  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.Checker(params)
    rights['edit'] = [('checkCanEditTimeline', [program_logic.logic])]

    new_params = {}
    new_params['rights'] = rights
    new_params['logic'] = soc.logic.models.timeline.logic
    new_params['edit_template'] = 'soc/timeline/edit.html'
    new_params['name'] = "Timeline"

    patterns = [(r'^%(url_name)s/(?P<access_type>edit)/%(key_fields)s$',
                  '%(module_package)s.%(module_name)s.edit',
                  "Edit %(name_short)s")]

    new_params['create_extra_dynaproperties'] = {
        'link_id': forms.CharField(widget=forms.HiddenInput)
        }
    new_params['django_patterns_defaults'] = patterns

    new_params['edit_dynaproperties'] = []

    params = dicts.merge(params, new_params)

    super(View, self).__init__(params=params)
Beispiel #5
0
  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.Checker(params)

    new_params = {}
    new_params['rights'] = rights
    new_params['logic'] = job_logic

    new_params['name'] = "Job"

    new_params['no_create_raw'] = True
    new_params['no_create_with_scope'] = True
    new_params['no_create_with_key_fields'] = True

    new_params['extra_dynaexclude'] = ['key_data', 'text_data']

    new_params['edit_dynaproperties'] = {
      'task': forms.CharField(widget=widgets.PlainTextWidget()),
      }

    params = dicts.merge(params, new_params)

    super(View, self).__init__(params=params)
Beispiel #6
0
  def _list(self, request, params, contents, page_name, context=None):
    """Returns the list page for the specified contents.

    Args:
      request: the standard Django HTTP request object
      params: a dict with params for this View
      contents: a list of content dicts
      page_name: the page name displayed in templates as page and header title
      context: the context for this page

    Params usage:
      list_template: The list_template value is used as template for
        to display the list of all entities for this View.
    """

    context = dicts.merge(context,
        helper.responses.getUniversalContext(request))
    helper.responses.useJavaScript(context, params['js_uses_all'])
    context['page_name'] = page_name
    context['list'] = soc.logic.lists.Lists(contents)

    context['list_msg'] = params.get('list_msg', None)
    context['no_lists_msg'] = params.get('no_lists_msg', None)

    template = params['list_template']

    return helper.responses.respond(request, template, context)
Beispiel #7
0
 def testMergeUpdatesEmpty(self):
     """Tests that nothing is updated if no updates.
 """
     target = self.dummy_dict
     updates = {}
     expected_dict = target
     self.assertEqual(dicts.merge(target, updates), expected_dict)
Beispiel #8
0
  def __init__(self, params=None):
    """Defines the fields and methods required for the mentor View class
    to provide the user with list, public, create, edit and delete views.

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

    rights = gci_access.GCIChecker(params)
    rights['create'] = ['checkIsDeveloper']
    rights['edit'] = [('checkIsMyActiveRole', gci_mentor_logic.logic)]
    rights['delete'] = ['checkIsDeveloper']
    rights['invite'] = [('checkHasRoleForScope',
                         gci_org_admin_logic.logic)]
    rights['accept_invite'] = [
        ('checkIsMyRequestWithStatus', [['group_accepted']]),
        ('checkIsNotStudentForProgramOfOrgInRequest',
         [gci_org_logic.logic, gci_student_logic.logic])]
    rights['request'] = [
        ('checkIsNotStudentForProgramOfOrg',
         [gci_org_logic.logic, gci_student_logic.logic]),
        ('checkCanMakeRequestToGroup', gci_org_logic.logic)]
    rights['process_request'] = [
        ('checkCanProcessRequest', [[gci_org_admin_logic.logic]])]
    rights['manage'] = [
        ('checkIsAllowedToManageRole', [gci_mentor_logic.logic,
                                        gci_org_admin_logic.logic])]
    rights['list_mentor_tasks'] = [
        ('checkCanOpenTaskList', [gci_mentor_logic.logic, 'gci/mentor']),
        ('checkIsAfterEvent', ['accepted_organization_announced_deadline',
                               '__all__', gci_program_logic.logic])]

    new_params = {}
    new_params['logic'] = soc.modules.gci.logic.models.mentor.logic
    new_params['group_logic'] = gci_org_logic.logic
    new_params['group_view'] = gci_org_view.view
    new_params['rights'] = rights

    new_params['scope_view'] = gci_org_view

    new_params['name'] = "GCI Mentor"
    new_params['module_name'] = "mentor"
    new_params['sidebar_grouping'] = 'Organizations'

    new_params['module_package'] = 'soc.modules.gci.views.models'
    new_params['url_name'] = 'gci/mentor'

    new_params['role'] = 'gci/mentor'

    patterns = []
    patterns += [
        (r'^%(url_name)s/(?P<access_type>list_mentor_tasks)/%(key_fields)s$',
        '%(module_package)s.%(module_name)s.list_mentor_tasks',
        'List Mentor tasks')]

    new_params['extra_django_patterns'] = patterns

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

    super(View, self).__init__(params=params)
Beispiel #9
0
 def testMergeTargetEmptyUpdatesNotEmpty(self):
     """Tests that an empty target is updated.
 """
     target = {}
     updates = {"a": "1"}
     expected = updates
     self.assertEqual(dicts.merge(target, updates), expected)
Beispiel #10
0
 def testMergeRecursiveTrueSubMergeFalse(self):
     """Tests if dicts are updated correctly when recursive True, sub_merge False.
 """
     target = {"a": 1, "b": {"c": {"d": {"e": 2}}}}
     updates = {"f": 3, "b": {"c": {"d": {"g": 5}}}}
     expected = {"a": 1, "f": 3, "b": {"c": {"d": {"e": 2}}}}
     self.assertEqual(dicts.merge(target, updates, sub_merge=False, recursive=True), expected)
  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.Checker(params)
    rights['any_access'] = ['allow']
    rights['show'] = [('checkIsSurveyReadable', grading_survey_logic)]
    rights['create'] = ['checkIsUser']
    rights['edit'] = [('checkIsSurveyWritable', grading_survey_logic)]
    rights['delete'] = [('checkIsSurveyWritable', grading_survey_logic)]
    rights['list'] = ['checkDocumentList']
    rights['pick'] = ['checkDocumentPick']

    new_params = {}
    new_params['logic'] = grading_survey_logic
    new_params['rights'] = rights

    new_params['extra_django_patterns'] = [
        (r'^%(url_name)s/(?P<access_type>activate)/%(scope)s$',
         'soc.views.models.%(module_name)s.activate',
         'Activate grades for %(name)s')]

    new_params['name'] = "Grading Project Survey"

    params = dicts.merge(params, new_params)

    super(View, self).__init__(params=params)
Beispiel #12
0
  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.Checker(params)
    rights['any_access'] = ['allow']
    rights['show'] = [('checkIsSurveyReadable', project_survey_logic)]
    rights['create'] = ['checkIsUser']
    rights['edit'] = [('checkIsSurveyWritable', project_survey_logic)]
    rights['delete'] = [('checkIsSurveyWritable', project_survey_logic)]
    rights['list'] = ['checkDocumentList']
    rights['pick'] = ['checkDocumentPick']

    new_params = {}
    new_params['logic'] = project_survey_logic
    new_params['rights'] = rights

    new_params['name'] = "Project Survey"

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

    params = dicts.merge(params, new_params)

    super(View, self).__init__(params=params)
Beispiel #13
0
  def create(self, request, access_type,
             page_name=None, params=None, **kwargs):
    """Displays the create page for this entity type.

    Params usage:
      The params dictionary is passed on to edit, see the docstring
      for edit on how it uses it.

    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: not used for create()
    """

    new_params = dicts.merge(params, self._params)

    # redirect to scope selection view
    if ('scope_view' in new_params) and ('scope_path' not in kwargs):
      view = new_params['scope_view'].view
      redirect = new_params['scope_redirect']
      return self.select(request, view, redirect,
                         params=params, page_name=page_name, **kwargs)

    params = new_params

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

    if request.method == 'POST':
      return self.createPost(request, context, params)
    else:
      return self.createGet(request, context, params, kwargs)
Beispiel #14
0
  def getSidebarMenus(self, id, user, params=None):
    """See base.View.getSidebarMenus.

    Returns a custom sidebar entry for the 'site' singleton.
    """

    entity = self._logic.getSingleton()

    submenus = document_view.view.getMenusForScope(entity, self._params)

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

    if is_host:
      submenus += [(redirects.getCreateDocumentRedirect(entity, 'site'),
          "Create a New Document", 'any_access')]

      submenus += [(redirects.getListDocumentsRedirect(entity, 'site'),
          "List Documents", 'any_access')]
    submenus += [('/priority_group/list', "List Priority Groups", 'edit')]
    submenus += [('/job/list', "List Jobs", 'edit')]

    new_params = {}
    new_params['sidebar_additional'] = submenus

    params = dicts.merge(params, new_params)
    return super(View, self).getSidebarMenus(id, user, params=params)
Beispiel #15
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 #16
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['public_row_extra'] = lambda entity: {
          'link': redirects.getAdminRedirect(entity, params)
      }
    else:
      params['public_row_extra'] = lambda entity: {
          'link': redirects.getPublicRedirect(entity, params)
      }

    new_filter = {}

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

    return self.list(request, 'allow', page_name=page_name,
                      params=params, filter=filter)
Beispiel #17
0
  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.Checker(params)
    rights['unspecified'] = ['deny']
    rights['edit'] = ['deny']
    rights['show'] = [('checkIsMyEntity', [notification_logic, 'scope_path'])]
    rights['delete'] = [('checkIsMyEntity', [notification_logic, 'scope_path'])]
    rights['list'] = ['checkIsUser']
    # create is developer only for the time being to test functionality
    rights['create'] = ['checkIsDeveloper']

    new_params = {}
    new_params['logic'] = notification_logic
    new_params['rights'] = rights

    new_params['name'] = "Notification"

    new_params['no_create_with_key_fields'] = True
    new_params['create_form'] = CreateForm

    new_params['edit_redirect'] = '/%(url_name)s/list'

    params = dicts.merge(params, new_params)

    super(View, self).__init__(params=params)
Beispiel #18
0
  def getSidebarMenus(self, id, user, params=None):
    """See base.View.getSidebarMenus().
    """

    link_title = ugettext('Notifications')

    filter = {
        'scope': user,
        'unread': True,
        }

    notifications = model_logic.notification.logic.getForFields(filter)
    count = len(list(notifications))

    if count > 0:
      link_title = '<span class="unread">%s (%d)</span>' % (
          force_unicode(link_title), count)
      link_title = mark_safe(link_title)

    items = [('/' + 'notification/list', link_title, 'notification')]
    if user:
      items += [(redirects.getCreateDocumentRedirect(user, 'user'),
          "Create a New Document", 'any_access')]

      items += [(redirects.getListDocumentsRedirect(user, 'user'),
          "List Documents", 'any_access')]

    new_params = {}
    new_params['sidebar_additional'] = items

    params = dicts.merge(params, new_params)

    return super(View, self).getSidebarMenus(id, user, params=params)
Beispiel #19
0
  def __init__(self, params=None):
    """Defines the fields and methods required for the work_submission.

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

    rights = gci_access.GCIChecker(params)
    rights['any_access'] = ['allow']
    rights['download_blob'] = ['allow']

    new_params = {}
    new_params['logic'] = soc.modules.gci.logic.models.work_submission.logic
    new_params['rights'] = rights

    new_params['name'] = "Work Submission"
    new_params['module_name'] = "work_submission"

    new_params['module_package'] = 'soc.modules.gci.views.models'
    new_params['url_name'] = 'gci/work_submission'

    patterns = []
    patterns += [
        (r'^%(url_name)s/(?P<access_type>download_blob)$',
        '%(module_package)s.%(module_name)s.download_blob',
        'Download the blob'),
        ]

    new_params['extra_django_patterns'] = patterns

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

    super(View, self).__init__(params=params)
Beispiel #20
0
 def testMergeTargetEmptyUpdatesEmpty(self):
     """Tests that an empty dict is returned when no target and updates.
 """
     target = {}
     updates = {}
     expected_dict = updates
     self.assertEqual(dicts.merge(target, updates), expected_dict)
Beispiel #21
0
  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'] = student_project_logic
    new_params['name'] = "Student Project"
    new_params['url_name'] = "student_project"

    patterns = [
        (r'^%(url_name)s/(?P<access_type>manage_overview)/%(scope)s$',
        'soc.views.models.%(module_name)s.manage_overview',
        'Overview of %(name_plural)s to Manage for'),
        (r'^%(url_name)s/(?P<access_type>manage)/%(key_fields)s$',
        'soc.views.models.%(module_name)s.manage',
        'Manage %(name)s'),
        (r'^%(url_name)s/(?P<access_type>st_edit)/%(key_fields)s$',
        'soc.views.models.%(module_name)s.st_edit',
        'Edit my %(name)s'),
    ]

    new_params['extra_django_patterns'] = patterns

    params = dicts.merge(params, new_params)

    super(View, self).__init__(params=params)
Beispiel #22
0
  def getSidebarMenus(self, id, user, params=None):
    """See base.View.getSidebarMenus.

    Returns a custom sidebar entry for the 'site' singleton.
    """

    entity = site_logic.getSingleton()

    submenus = document_view.view.getMenusForScope(entity, self._params)

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

    if is_host:
      submenus += [(redirects.getCreateDocumentRedirect(entity, 'site'),
          "Create a New Document", 'any_access')]

      submenus += [(redirects.getListDocumentsRedirect(entity, 'site'),
          "List Documents", 'any_access')]

    if entity.cse_key:
      # only add the search entry if a key is defined
      submenus += [('/site/search', 'Search', 'any_access')]

    new_params = {}
    new_params['sidebar_additional'] = submenus

    params = dicts.merge(params, new_params)
    return super(View, self).getSidebarMenus(id, user, params=params)
Beispiel #23
0
  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.Checker(params)
    rights['create'] = ['checkIsDeveloper']
    rights['edit'] = [('checkIsMyActiveRole', club_member_logic.logic)]
    rights['delete'] = ['checkIsDeveloper']
    rights['invite'] = [('checkHasRoleForScope', club_admin_logic.logic)]
    rights['accept_invite'] = [
        ('checkIsMyRequestWithStatus', [['group_accepted']])]
    rights['request'] = ['checkIsUser',
                         ('checkCanMakeRequestToGroup', club_logic.logic)]
    rights['process_request'] = [('checkCanProcessRequest', 
                                  [[club_admin_logic.logic]])]
    rights['manage'] = [('checkIsAllowedToManageRole',
                         [soc.logic.models.club_member.logic,
                          club_admin_logic.logic])]

    new_params = {}
    new_params['logic'] = soc.logic.models.club_member.logic
    new_params['group_logic'] = club_logic.logic
    new_params['group_view'] = club_view.view
    new_params['rights'] = rights

    new_params['scope_view'] = club_view

    new_params['name'] = "Club Member"
    new_params['sidebar_grouping'] = 'Clubs'

    new_params['extra_dynaexclude'] = ['agreed_to_tos']

    new_params['allow_requests_and_invites'] = True
    new_params['show_in_roles_overview'] = False

    new_params['public_field_keys'] = ["name", "link_id", "scope_path"]
    new_params['public_field_names'] = ["Member Name", "Member ID", "Club ID"]

    params = dicts.merge(params, new_params)

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

    # register the role with the group_view
    self._params['group_view'].registerRole(self._logic.role_name, self)

    # create and store the special form for invited users
    updated_fields = {
        'link_id': forms.CharField(widget=widgets.ReadOnlyInput(),
            required=False)}

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

    self._params['invited_create_form'] = invited_create_form
Beispiel #24
0
  def _startShipmentSync(self, request, *args, **kwargs):
    """Start syncing shipment data.

    POST Args:
      program_key: the key of the program which task is runnig for.
      sheet_content: sheet content data in JSON format.
      sheet_type: 'usa' or 'intl'
      shipment_info_id: id of the shipment info object that task is running 
                        for.
    """
    params = dicts.merge(request.POST, request.GET)
    redirect = RedirectHelper(None, None)

    if 'program_key' not in params:
      logging.error("missing program_key in params: '%s'" % params)
      return responses.terminateTask()

    if 'sheet_content' not in params:
      logging.error("missing sheet_content in params: '%s'" % params)
      return responses.terminateTask()

    if 'sheet_type' not in params:
      logging.error("missing sheet_type in params: '%s'" % params)
      return responses.terminateTask()

    if 'shipment_info_id' not in params:
      logging.error("missing shipment_info_id in params: '%s'" % params)
      return responses.terminateTask()

    self.setProgram(params['program_key'])
    self.setShipmentInfo(int(params['shipment_info_id']))

    self.__shipment_info.status = 'syncing'
    self.__shipment_info.put()

    sheet_content = StringIO.StringIO(
        simplejson.loads(params['sheet_content']))
    sheet_type = params['sheet_type']

    sheet_rows = [row for row in csv.reader(sheet_content)]

    if sheet_type == 'usa':
      column_indexes = self.findColumnIndexes(
          sheet_rows[0], self.USA_EXPECTED_COLUMNS)

    elif sheet_type == 'intl':
      column_indexes = self.findColumnIndexes(
          sheet_rows[0], self.INTL_EXPECTED_COLUMNS)

    params = {
        'program_key': params['program_key'],
        'shipment_info_id': params['shipment_info_id'],
        'column_indexes': simplejson.dumps(column_indexes),
        'sheet_rows': simplejson.dumps(sheet_rows[1:]),
    }

    taskqueue.add(url=redirect.urlOf('shipment_sync_task_continue'),
                  params=params)
    return responses.terminateTask()
Beispiel #25
0
 def testMergeRecursiveTrue(self):
   """Tests if dicts are updated correctly when recursive is set True.
   """
   target = {'a':1, 'b': {'c': {"d": {"e": 2}}}}
   updates = {'f': 3, 'b': {'c' :{"d": {"g": 5}}}}
   expected = {'a':1, 'f':3, 'b': {'c': {"d": {"e": 2, 'g':5}}}}
   self.assertEqual(dicts.merge(target, updates,
                                sub_merge=True, recursive=True), expected)
Beispiel #26
0
    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.Checker(params)
        rights["create"] = ["checkIsDeveloper"]
        rights["edit"] = [
            ("checkHasActiveRoleForScope", club_member_logic.logic),
            ("checkIsMyEntity", [club_member_logic.logic, "user", True]),
        ]
        rights["delete"] = ["checkIsDeveloper"]
        rights["invite"] = [("checkHasActiveRoleForScope", club_admin_logic.logic)]
        rights["accept_invite"] = [("checkCanCreateFromRequest", "club_member")]
        rights["request"] = ["checkIsUser", ("checkCanMakeRequestToGroup", club_logic)]
        rights["process_request"] = [
            ("checkHasActiveRoleForScope", club_admin_logic.logic),
            ("checkCanProcessRequest", "club_member"),
        ]
        rights["manage"] = [
            ("checkIsAllowedToManageRole", [soc.logic.models.club_member.logic, club_admin_logic.logic])
        ]

        new_params = {}
        new_params["logic"] = soc.logic.models.club_member.logic
        new_params["group_logic"] = club_logic.logic
        new_params["group_view"] = club_view.view
        new_params["rights"] = rights

        new_params["scope_view"] = club_view

        new_params["name"] = "Club Member"
        new_params["sidebar_grouping"] = "Clubs"

        new_params["extra_dynaexclude"] = ["agreed_to_tos"]

        new_params["allow_requests_and_invites"] = True
        new_params["show_in_roles_overview"] = False

        params = dicts.merge(params, new_params)

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

        # register the role with the group_view
        self._params["group_view"].registerRole(self._logic.role_name, self)

        # create and store the special form for invited users
        updated_fields = {"link_id": forms.CharField(widget=widgets.ReadOnlyInput(), required=False)}

        invited_create_form = dynaform.extendDynaForm(
            dynaform=self._params["create_form"], dynaproperties=updated_fields
        )

        self._params["invited_create_form"] = invited_create_form
Beispiel #27
0
 def testMergeSubMergeFalseSubDictsPresent(self):
   """Tests if sub-dicts are not merged if sub_merge=False.
   """
   #merge sub dict present in both target and updates
   target = self.dummy_dict.copy()
   target.update({'foo': {'k1': 'v1', 'k2': 'v2'}})
   updates = {'foo': {'a': '3', 'b': '11'}}
   expected_dict = target
   self.assertEqual(dicts.merge(target, updates, sub_merge=False), expected_dict)
Beispiel #28
0
 def testMergeTargetHasNoKeysInUpdates(self):
   """Tests if a dictionary is updated correctly.
   """
   target = self.dummy_dict
   updates = {'h': '8', 'i': {'a': '3', 'b': '11'}}
   temp = target.copy()
   temp.update(updates)
   expected_dict = temp
   self.assertEqual(dicts.merge(target, updates), expected_dict)
Beispiel #29
0
 def testMergeSubMergeFalseSubDictsPresent(self):
     """Tests if sub-dicts are not merged if sub_merge=False.
 """
     # merge sub dict present in both target and updates
     target = self.dummy_dict.copy()
     target.update({"foo": {"k1": "v1", "k2": "v2"}})
     updates = {"foo": {"a": "3", "b": "11"}}
     expected_dict = target
     self.assertEqual(dicts.merge(target, updates, sub_merge=False), expected_dict)
Beispiel #30
0
 def testMergeTargetHasNoKeysInUpdates(self):
     """Tests if a dictionary is updated correctly.
 """
     target = self.dummy_dict
     updates = {"h": "8", "i": {"a": "3", "b": "11"}}
     temp = target.copy()
     temp.update(updates)
     expected_dict = temp
     self.assertEqual(dicts.merge(target, updates), expected_dict)
Beispiel #31
0
    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)
Beispiel #32
0
  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.Checker(params)
    rights['create'] = ['checkIsDeveloper']
    rights['edit'] = [('checkIsMyActiveRole', student_logic.logic)]
    rights['delete'] = ['checkIsDeveloper']
    rights['apply'] = [
        'checkIsUser',
        ('checkIsActivePeriod', 
         ['student_signup', 'scope_path', program_logic.logic]),
        ('checkIsNotParticipatingInProgramInScope', [program_logic.logic,
        student_logic.logic, org_admin_logic.logic, mentor_logic.logic]),
        ]
    rights['manage'] = [('checkIsMyActiveRole', student_logic.logic)]

    new_params = {}
    new_params['logic'] = soc.logic.models.student.logic
    new_params['group_logic'] = program_logic.logic
    new_params['group_view'] = program_view.view
    new_params['rights'] = rights

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

    new_params['name'] = "Student"
    new_params['module_name'] = "student"
    new_params['sidebar_grouping'] = 'Students'

    new_params['create_template'] = 'soc/student/edit.html'
    new_params['edit_template'] = 'soc/student/edit.html'

    new_params['public_field_keys'] = ["name", "link_id", "scope_path"]
    new_params['public_field_names'] = ["Student Name", "Student ID", "Program ID"]

    # add apply pattern
    patterns = [(r'^%(url_name)s/(?P<access_type>apply)/%(scope)s$',
        '%(module_package)s.%(module_name)s.apply',
        'Become a %(name)s'),]

    new_params['extra_django_patterns'] = patterns

    new_params['extra_dynaexclude'] = ['agreed_to_tos', 'school']

    current_year = time.gmtime().tm_year
    # the current year is not the minimum because a program could span
    # more than one year
    allowed_years = range(current_year-1, current_year+20)

    view_logic = params['logic'] if params else new_params['logic']

    new_params['create_extra_dynaproperties'] = {
        'expected_graduation': forms.TypedChoiceField(
            choices=[(x,x) for x in allowed_years],
            coerce=lambda val: int(val)
            ),
        'clean': cleaning.validate_student(view_logic.getScopeLogic().logic),
        'school_home_page': forms.fields.URLField(required=True),
        'clean_school_home_page': cleaning.clean_url('school_home_page'),
        }

    new_params['create_dynafields'] = [
        {'name': 'scope_path',
         'base': forms.fields.CharField,
         'widget': forms.HiddenInput,
         'required': True,
         },
        {'name': 'student_agreement',
         'base': forms.fields.CharField,
         'required': False,
         'widget': widgets.AgreementField,
         'group': ugettext("5. Terms of Service"),
         },
        {'name': 'agreed_to_student_agreement',
         'base': forms.fields.BooleanField,
         'initial': False,
         'required':True,
         'label': ugettext('I agree to the Student Agreement'),
         'group': ugettext("5. Terms of Service"),
         },
        ]

    # only if subclassed, so params is not empty
    new_params['show_in_roles_overview'] = bool(params)

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

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

    params = self.getParams()

    # create and store the special form for users
    updated_fields = {
        'link_id': forms.CharField(widget=forms.HiddenInput,
            required=True),
        'clean_link_id': cleaning.clean_user_is_current('link_id'),
        }

    user_create_form = dynaform.extendDynaForm(
        dynaform = params['create_form'],
        dynaproperties = updated_fields)

    params['user_create_form'] = user_create_form

    params['admin_field_keys'].extend([
        'school_name', 'school_country', 'school_home_page', 'school_type',
        'major', 'degree', 'grade', 'expected_graduation', 'program_knowledge',
        'can_we_contact_you'])
    params['admin_field_names'].extend([
        'School Name', 'School Country', 'School Homepage', 'School Type',
        'Major', 'Degree', 'Grade', 'Expected Graduation Year',
        'How did you hear about us?', 'Allowed to Contact?'])
    params['admin_field_hidden'].extend([
        'school_name', 'school_country', 'school_home_page', 'school_type',
        'major', 'degree', 'grade', 'expected_graduation', 'program_knowledge',
        'can_we_contact_you'])
Beispiel #33
0
    def __init__(self, params=None):
        """Defines the fields and methods required for the program View class
    to provide the user with list, public, create, edit and delete views.

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

        rights = ghop_access.GHOPChecker(params)
        rights['create'] = ['checkIsDeveloper']
        rights['edit'] = [(
            'checkHasRoleForKeyFieldsAsScope',
            ghop_org_admin_logic.logic,
        ), ('checkGroupIsActiveForLinkId', ghop_org_logic.logic)]
        rights['delete'] = ['checkIsDeveloper']
        rights['home'] = ['allow']
        rights['public_list'] = ['allow']
        rights['apply_mentor'] = ['checkIsUser']
        rights['list_requests'] = [('checkHasRoleForKeyFieldsAsScope',
                                    ghop_org_admin_logic.logic)]
        rights['list_roles'] = [('checkHasRoleForKeyFieldsAsScope',
                                 ghop_org_admin_logic.logic)]

        new_params = {}
        new_params['logic'] = soc.modules.ghop.logic.models.organization.logic
        new_params['rights'] = rights

        new_params['scope_view'] = ghop_program_view

        new_params['name'] = "GHOP Organization"
        new_params['module_name'] = "organization"
        new_params['sidebar_grouping'] = 'Organizations'

        new_params['public_template'] = 'modules/ghop/organization/public.html'
        new_params['list_row'] = 'modules/ghop/organization/list/row.html'
        new_params[
            'list_heading'] = 'modules/ghop/organization/list/heading.html'
        new_params['home_template'] = 'modules/ghop/organization/home.html'

        new_params['module_package'] = 'soc.modules.ghop.views.models'
        new_params['url_name'] = 'ghop/org'
        new_params['document_prefix'] = 'ghop_org'

        new_params['extra_dynaexclude'] = [
            'slots', 'slots_calculated', 'nr_applications', 'nr_mentors',
            'slots_desired', 'ideas', 'task_quota_limit'
        ]

        new_params['mentor_role_name'] = 'ghop_mentor'
        new_params['mentor_url_name'] = 'ghop/mentor'

        new_params['edit_extra_dynaproperties'] = {
            'clean': cleaning.clean_refs(new_params, ['home_link_id'])
        }

        new_params['public_field_extra'] = lambda entity: {
            "open_tasks":
            str(
                len(
                    ghop_task_logic.logic.getForFields({
                        'scope':
                        entity,
                        'status': ['Open', 'Reopened']
                    }))),
            "claimed_tasks":
            str(
                len(
                    ghop_task_logic.logic.getForFields({
                        'scope':
                        entity,
                        'status': [
                            'ClaimRequested', 'Claimed', 'ActionNeeded',
                            'NeedsReview', 'NeedsWork'
                        ],
                    }))),
            "closed_tasks":
            str(
                len(
                    ghop_task_logic.logic.getForFields({
                        'scope':
                        entity,
                        'status': ['AwaitingRegistration', 'Closed'],
                    }))),
            "home_page":
            lists.urlize(entity.home_page),
        }
        new_params['public_field_keys'] = [
            "name",
            "task_quota_limit",
            "open_tasks",
            "claimed_tasks",
            "closed_tasks",
            "home_page",
        ]
        new_params['public_field_names'] = [
            "Name",
            "Tasks Quota",
            "Open Tasks",
            "Claimed Tasks",
            "Closed Tasks",
            "Home Page",
        ]

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

        super(View, self).__init__(params=params)
Beispiel #34
0
class View(object):
  """Views for entity classes.

  The View class functions specific to Entity classes by relying
  on the the child-classes to define the following fields:

  self._logic: the logic singleton for this entity
  """

  DEF_CREATE_NEW_ENTITY_MSG_FMT = ugettext(
      ' You can create a new %(entity_type)s by visiting'
      ' <a href="%(create)s">Create '
      'a New %(entity_type)s</a> page.')

  DEF_CREATE_INSTRUCTION_MSG_FMT = ugettext(
      'Please select a %s for the new %s.')

  def __init__(self, params=None):
    """

    Args:
      params: This dictionary should be filled with the parameters
        specific to this entity. See the methods in this class on
        the fields it should contain, and how they are used.
    """

    self._params = helper.params.constructParams(params)
    self._logic = params['logic']

  @decorators.merge_params
  @decorators.check_access
  def public(self, request, access_type,
             page_name=None, params=None, **kwargs):
    """Displays the public page for the entity specified by **kwargs.

    Params usage:
      rights: The rights dictionary is used to check if the user has
        the required rights to view the public page for this entity.
        See checkAccess for more details on how the rights dictionary
        is used to check access rights.
      error_public: The error_public value is used as template when
        the key values (as defined by the page's url) do not
        correspond to an existing entity.
      name: The name value is used to set the entity_type in the
        context so that the template can refer to it.
      public_template: The public_template value is used as template
        to display the public page of the found entity.

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

    # create default template context for use with any templates
    context = helper.responses.getUniversalContext(request)
    helper.responses.useJavaScript(context, params['js_uses_all'])
    context['page_name'] = page_name
    entity = None
    logic = params['logic']

    if not all(kwargs.values()):
      #TODO: Change this into a proper redirect
      return http.HttpResponseRedirect('/')

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

    if not self._public(request, entity, context):
      redirect = params['public_redirect']
      if redirect:
        return http.HttpResponseRedirect(redirect)

    context['entity'] = entity
    context['entity_type'] = params['name']
    context['entity_type_url'] = params['url_name']

    context = dicts.merge(params['context'], context)

    template = params['public_template']

    return helper.responses.respond(request, template, context=context)
Beispiel #35
0
    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.Checker(params)
        rights['unspecified'] = ['deny']
        rights['any_access'] = ['allow']
        rights['create_profile'] = ['checkIsUnusedAccount']
        rights['edit_profile'] = ['checkHasUserEntity']
        rights['roles'] = ['checkIsUser']
        rights['requests'] = ['checkIsUser']
        rights['signIn'] = ['checkNotLoggedIn']
        rights['notification'] = ['checkIsUser']

        new_params = {}
        new_params['rights'] = rights
        new_params['logic'] = user_logic

        new_params['name'] = "User"
        new_params['module_name'] = "user_self"
        new_params['url_name'] = "user"

        new_params['create_template'] = 'soc/user/edit_profile.html'
        new_params['edit_template'] = 'soc/user/edit_profile.html'
        new_params['save_message'] = [ugettext('Profile saved.')]
        new_params['edit_redirect'] = '/%(url_name)s/edit_profile'

        # set the specific fields for the users profile page
        new_params['extra_dynaexclude'] = [
            'former_accounts', 'account', 'is_developer', 'status',
            'agreed_to_tos_on'
        ]

        new_params['create_extra_dynaproperties'] = {
            'clean_agreed_to_tos':
            cleaning.clean_agrees_to_tos('agreed_to_tos'),
            'clean_link_id': cleaning.clean_user_not_exist('link_id'),
        }

        new_params['edit_extra_dynaproperties'] = {
            'clean_link_id':
            cleaning.clean_user_is_current('link_id', False),
            'agreed_to_tos_on':
            forms.DateTimeField(
                widget=widgets.ReadOnlyInput(attrs={'disabled': 'true'}),
                required=False),
        }

        new_params['sidebar_heading'] = 'User (self)'
        new_params['sidebar'] = [
            (users.create_login_url("/"), 'Sign In', 'signIn'),
            ('/' + new_params['url_name'] + '/create_profile',
             'Create Profile', 'create_profile'),
            ('/' + new_params['url_name'] + '/edit_profile', 'Edit Profile',
             'edit_profile'),
            ('/' + new_params['url_name'] + '/roles', 'Roles', 'roles'),
            ('/' + new_params['url_name'] + '/requests', 'Requests',
             'requests'),
        ]

        patterns = []

        page_name = ugettext("Create your profile")
        patterns += [(r'^%(url_name)s/(?P<access_type>create_profile)$',
                      'soc.views.models.%(module_name)s.create', page_name)]

        page_name = ugettext("Edit your profile")
        patterns += [(r'^%(url_name)s/(?P<access_type>edit_profile)$',
                      'soc.views.models.%(module_name)s.edit', page_name)]

        page_name = ugettext("List of your roles")
        patterns += [(r'^%(url_name)s/(?P<access_type>roles)$',
                      'soc.views.models.user_self.roles', page_name)]

        page_name = ugettext("List of your requests")
        patterns += [(r'^%(url_name)s/(?P<access_type>requests)$',
                      'soc.views.models.request.list_self', page_name)]

        new_params['django_patterns_defaults'] = patterns

        params = dicts.merge(params, new_params)

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

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

        patterns = []
        patterns += [
            (r'^%(url_name)s/(?P<access_type>submit_forms)/%(key_fields)s$',
             '%(module_package)s.%(module_name)s.submit_forms',
             'Submit forms'),
            (r'^%(url_name)s/(?P<access_type>download_blob)/%(key_fields)s$',
             '%(module_package)s.%(module_name)s.download_blob',
             'Download the blob'),
        ]

        rights = gci_access.GCIChecker(params)
        rights['edit'] = [('checkIsMyActiveRole', gci_student_logic)]
        rights['apply'] = [
            'checkIsUser',
            ('checkIsActivePeriod',
             ['student_signup', 'scope_path', gci_program_logic.logic]),
            ('checkIsNotParticipatingInProgramInScope', [
                gci_program_logic.logic, gci_student_logic,
                gci_org_admin_logic.logic, gci_mentor_logic.logic
            ]), 'checkCanApply'
        ]
        rights['manage'] = [('checkIsMyActiveRole', gci_student_logic)]
        rights['submit_forms'] = [
            ('checkIsActivePeriod',
             ['program', 'scope_path', gci_program_logic.logic]),
            ('checkIsMyActiveRole', gci_student_logic)
        ]
        rights['download_blob'] = [('checkCanDownloadConsentForms', [
            gci_student_logic, {
                'consent_form_upload_form': 'consent_form',
                'consent_form_two_upload_form': 'consent_form_two',
                'student_id_form_upload_form': 'student_id_form'
            }
        ])]

        new_params = {}
        new_params['logic'] = gci_student_logic
        new_params['rights'] = rights

        new_params['group_logic'] = gci_program_logic.logic
        new_params['group_view'] = gci_program_view.view

        new_params['scope_view'] = gci_program_view

        new_params['name'] = "GCI Student"
        new_params['module_name'] = "student"
        new_params['sidebar_grouping'] = 'Students'

        new_params['module_package'] = 'soc.modules.gci.views.models'
        new_params['url_name'] = 'gci/student'

        new_params['extra_dynaexclude'] = [
            'agreed_to_tos',
            'school',
            'parental_form_mail',
            'consent_form',
            'consent_form_two',
            'student_id_form',
        ]

        new_params['extra_django_patterns'] = patterns

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

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

        base_form = self._params['dynabase']
        gci_student_model = gci_student_logic.getModel()

        def getUploadForms(name, label, help_text):
            dynafields = [{
                'name': name,
                'base': forms.FileField,
                'label': label,
                'required': False,
                'help_text': help_text,
            }]

            dynaproperties = params_helper.getDynaFields(dynafields)

            add_form = dynaform.newDynaForm(dynabase=base_form,
                                            dynaproperties=dynaproperties)

            dynaproperties = {
                'name':
                django_fields.CharField(label='Name',
                                        required=False,
                                        widget=widgets.HTMLTextWidget),
                'uploaded':
                django_fields.CharField(label='Uploaded on',
                                        required=False,
                                        widget=widgets.PlainTextWidget),
                'size':
                django_fields.CharField(label='Size',
                                        required=False,
                                        widget=widgets.PlainTextWidget),
            }
            edit_form = dynaform.extendDynaForm(
                add_form,
                dynaproperties=dynaproperties,
                dynainclude=['name', 'size', 'uploaded', name])

            return add_form, edit_form

        self._params['consent_form_upload_form'] = getUploadForms(
            'consent_form_upload', 'Consent Form',
            gci_student_model.consent_form.help_text)

        self._params['consent_form_two_upload_form'] = getUploadForms(
            'consent_form_two_upload', 'Consent Form (page two)',
            gci_student_model.consent_form_two.help_text)

        self._params['student_id_form_upload_form'] = getUploadForms(
            'student_id_form_upload', 'Student ID Form',
            gci_student_model.student_id_form.help_text)
Beispiel #37
0
    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['any_access'] = ['allow']
        rights['show'] = [('checkIsSurveyReadable', project_survey_logic)]
        rights['create'] = ['checkIsUser']
        rights['edit'] = [('checkIsSurveyWritable', project_survey_logic)]
        rights['delete'] = ['checkIsDeveloper'
                            ]  # TODO: fix deletion of Surveys
        rights['list'] = ['checkDocumentList']
        rights['record'] = [('checkHasAny', [[
            ('checkIsAllowedToViewProjectSurveyRecordAs',
             [project_survey_logic, 'student', 'id']),
            ('checkIsSurveyReadable', [project_survey_logic]),
        ]])]
        rights['results'] = ['checkIsUser']
        rights['take'] = [('checkIsSurveyTakeable', project_survey_logic),
                          ('checkIsAllowedToTakeProjectSurveyAs',
                           [project_survey_logic, 'student', 'project'])]
        rights['send_reminder'] = ['checkIsDeveloper'
                                   ]  #TODO: proper access check

        new_params = {}
        new_params['logic'] = project_survey_logic
        new_params['rights'] = rights

        new_params['name'] = "Project Survey"
        new_params['url_name'] = 'gsoc/project_survey'
        new_params['module_package'] = 'soc.modules.gsoc.views.models'

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

        new_params['extra_django_patterns'] = [
            (r'^%(url_name)s/(?P<access_type>send_reminder)/%(key_fields)s$',
             '%(module_package)s.%(module_name)s.send_reminder',
             'Send Reminder for %(name)s')
        ]

        new_params['take_template'] = 'soc/project_survey/take.html'

        # used for sending reminders
        new_params['survey_type'] = 'project'
        new_params['reminder_template'] = 'soc/project_survey/reminder.html'

        new_params['manage_student_project_heading'] = \
            'soc/project_survey/list/heading_manage_student_project.html'
        new_params['manage_student_project_row'] = \
            'soc/project_survey/list/row_manage_student_project.html'

        new_params['public_field_extra'] = lambda entity: {
            "path": entity.scope_path + '/' + entity.link_id,
            "created_by": entity.author.link_id,
        }
        new_params['public_field_keys'] = [
            "path",
            "title",
            "link_id",
            "is_featured",
            "created_by",
            "created",
            "modified",
        ]
        new_params['public_field_names'] = [
            "Path",
            "Title",
            "Link ID",
            "Featured",
            "Created By",
            "Created On",
            "Modified",
        ]

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

        super(View, self).__init__(params=params)
Beispiel #38
0
  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.Checker(params)
    rights['create'] = ['checkIsDeveloper']
    rights['edit'] = [('checkIsMyActiveRole', soc.logic.models.mentor.logic)]
    rights['delete'] = ['checkIsDeveloper']
    rights['invite'] = [('checkHasRoleForScope',
                         soc.logic.models.org_admin.logic)]
    rights['accept_invite'] = [
        ('checkIsMyRequestWithStatus', [['group_accepted']]),
        ('checkIsNotStudentForProgramOfOrgInRequest',[org_logic.logic,
                                                      student_logic.logic])]
    rights['request'] = [
        ('checkIsNotStudentForProgramOfOrg',
            [org_logic.logic, student_logic.logic]),
        ('checkCanMakeRequestToGroup', org_logic.logic)]
    rights['process_request'] = [
        ('checkCanProcessRequest', [[soc.logic.models.org_admin.logic]])]
    rights['manage'] = [
        ('checkIsAllowedToManageRole', [soc.logic.models.mentor.logic,
             soc.logic.models.org_admin.logic])]

    new_params = {}
    new_params['logic'] = soc.logic.models.mentor.logic
    new_params['group_logic'] = org_logic.logic
    new_params['group_view'] = org_view.view
    new_params['rights'] = rights
    new_params['pickable'] = True
    new_params['cache_pick_order'] = ['link_id', 'name']

    new_params['scope_view'] = org_view

    new_params['name'] = "Mentor"
    new_params['module_name'] = "mentor"
    new_params['sidebar_grouping'] = 'Organizations'

    new_params['extra_dynaexclude'] = ['agreed_to_tos', 'program']

    new_params['create_dynafields'] = [
        {'name': 'scope_path',
         'base': forms.fields.CharField,
         'widget': forms.HiddenInput,
         'required': True,
         },
        {'name': 'mentor_agreement',
         'base': forms.fields.CharField,
         'required': False,
         'widget': widgets.AgreementField,
         'group': ugettext("5. Terms of Service"),
         },
        {'name': 'agreed_to_mentor_agreement',
         'base': forms.fields.BooleanField,
         'initial': False,
         'required':True,
         'label': ugettext('I agree to the Mentor Agreement'),
         'group': ugettext("5. Terms of Service"),
         },
        ]

    new_params['allow_requests_and_invites'] = True
    # only if subclassed, so params is not empty
    new_params['show_in_roles_overview'] = bool(params)

    new_params['public_field_keys'] = ["name", "link_id", "scope_path"]
    new_params['public_field_names'] = ["Name", "Mentor ID", "Organization ID"]

    params = dicts.merge(params, new_params)

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

    params = self.getParams()

    # register the role with the group_view
    params['group_view'].registerRole(self._logic.role_name, self)

    # create and store the special form for invited users
    dynafields = [
        {'name': 'link_id',
         'base': forms.CharField,
         'widget': widgets.ReadOnlyInput(),
         'required': False,
         },
        {'name': 'mentor_agreement',
         'base': forms.fields.Field,
         'required': False,
         'widget': widgets.AgreementField,
         'group': ugettext("5. Terms of Service"),
        },
        ]

    dynaproperties = params_helper.getDynaFields(dynafields)

    invited_create_form = dynaform.extendDynaForm(
        dynaform=params['create_form'],
        dynaproperties=dynaproperties)

    params['invited_create_form'] = invited_create_form

    # add the contact field to the admin list
    params['admin_field_keys'].append('can_we_contact_you')
    params['admin_field_names'].append('Allowed to Contact?')
    params['admin_field_hidden'].append('can_we_contact_you')
Beispiel #39
0
    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['any_access'] = ['allow']
        rights['show'] = ['allow']
        rights['create'] = ['checkIsDeveloper']
        rights['edit'] = [('checkHasRoleForKeyFieldsAsScope', org_admin_logic),
                          ('checkGroupIsActiveForLinkId', org_logic)]
        rights['delete'] = ['checkIsDeveloper']
        rights['home'] = ['allow']
        rights['public_list'] = ['allow']
        rights['applicant'] = [('checkIsOrgAppAccepted', org_app_logic)]
        rights['apply_mentor'] = ['checkIsUser']
        rights['list_requests'] = [('checkHasRoleForKeyFieldsAsScope',
                                    org_admin_logic)]
        rights['list_roles'] = [('checkHasRoleForKeyFieldsAsScope',
                                 org_admin_logic)]
        rights['list_proposals'] = [
            ('checkHasAny', [[('checkHasRoleForKeyFieldsAsScope',
                               [org_admin_logic, ['active', 'inactive']]),
                              ('checkHasRoleForKeyFieldsAsScope',
                               [mentor_logic, ['active', 'inactive']])]])
        ]

        new_params = {}
        new_params['logic'] = org_logic
        new_params['rights'] = rights

        new_params['scope_view'] = program_view

        new_params['name'] = "GSoC Organization"
        new_params['module_name'] = "organization"
        new_params['sidebar_grouping'] = 'Organizations'

        new_params['module_package'] = 'soc.modules.gsoc.views.models'
        new_params['url_name'] = 'gsoc/org'
        new_params['document_prefix'] = 'gsoc_org'

        new_params['mentor_role_name'] = 'gsoc_mentor'
        new_params['mentor_url_name'] = 'gsoc/mentor'
        new_params['org_admin_role_name'] = 'gsoc_org_admin'

        patterns = []

        patterns += [
            (r'^org_tags/(?P<access_type>pick)$',
             '%(module_package)s.%(module_name)s.pick_suggested_tags',
             "Pick a list of suggested tags."),
        ]

        new_params['extra_django_patterns'] = patterns

        new_params['extra_dynaexclude'] = [
            'slots', 'slots_calculated', 'nr_applications', 'nr_mentors'
        ]

        new_params['create_extra_dynaproperties'] = {
            'tags':
            widgets.ReferenceField(
                required=False,
                reference_url='org_tags',
                label=ugettext('Tags'),
                help_text=ugettext("A list of comma seperated tags"),
                example_text="e.g. python, django, appengine",
                filter=['scope_path'],
                group="1. Public Info"),
            'clean_tags':
            gsoc_cleaning.cleanTagsList('tags', gsoc_cleaning.COMMA_SEPARATOR),
            'contrib_template':
            forms.fields.CharField(widget=helper.widgets.FullTinyMCE(
                attrs={
                    'rows': 25,
                    'cols': 100
                })),
            'clean_contrib_template':
            cleaning.clean_html_content('contrib_template'),
            'clean_facebook':
            cleaning.clean_url('facebook'),
            'clean_twitter':
            cleaning.clean_url('twitter'),
            'clean_blog':
            cleaning.clean_url('blog'),
        }

        new_params['org_app_logic'] = org_app_logic

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

        super(View, self).__init__(params)

        self._params['public_field_keys'].append('tags')
        self._params['public_field_names'].append("Tags")
        self._params['public_field_extra'] = lambda entity: {
            'ideas': lists.urlize(entity.ideas, 'Click Here'),
            'tags': entity.tags_string(entity.org_tag),
        }
        self._params['select_field_extra'] = self._params['public_field_extra']
Beispiel #40
0
    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'),
            (r'^%(url_name)s/(?P<access_type>review)/%(key_fields)s$',
             '%(module_package)s.%(module_name)s.review',
             'Review %(name)s from '),
            (r'^%(url_name)s/(?P<access_type>review_overview)/%(key_fields)s$',
             '%(module_package)s.%(module_name)s.review_overview',
             'Overview of %(name_plural)s for Review')
        ]

        new_params['review_template'] = 'soc/org_app_survey/review.html'

        new_params['successful_take_message'] = ugettext(
            'Organization Application submitted.')

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

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

        # create the form to review an Organization Application
        dynaproperties = {
            'status':
            forms.fields.ChoiceField(required=True,
                                     label='New Status',
                                     choices=[
                                         ('accepted', 'Accept'),
                                         ('pre-accepted', 'Pre-Accept'),
                                         ('rejected', 'Reject'),
                                         ('pre-rejected', 'Pre-Reject'),
                                         ('ignored', 'Ignore'),
                                     ])
        }

        review_form = dynaform.newDynaForm(
            dynabase=self._params['dynabase'],
            dynaproperties=dynaproperties,
        )

        self._params['review_form'] = review_form

        # define the params for the OrgAppSurveyRecord listing
        record_list_params = {}
        record_list_params['logic'] = self._params['logic'].getRecordLogic()
        record_list_params['js_uses_all'] = self._params['js_uses_all']
        record_list_params['list_template'] = self._params['list_template']

        # define the fields for the public list
        record_list_params['public_field_keys'] = ['name', 'home_page']
        record_list_params['public_field_names'] = ['Name', 'Home Page']
        record_list_params['public_field_extra'] = lambda entity: {
            'home_page': lists.urlize(entity.home_page, 'Click Here'),
        }

        # define the fields for the self list
        record_list_params['self_field_keys'] = [
            'name', 'main_admin', 'backup_admin'
        ]
        record_list_params['self_field_names'] = [
            'Organization Name', 'Main Admin', 'Backup Admin'
        ]
        record_list_params['self_field_prefetch'] = [
            'main_admin', 'backup_admin'
        ]
        record_list_params['self_field_extra'] = lambda entity: {
            'main_admin': entity.main_admin.name,
            'backup_admin': entity.backup_admin.name
        }
        record_list_params['self_row_action'] = {
            "type": "redirect_custom",
            "parameters": dict(new_window=False),
        }

        self._params['record_list_params'] = record_list_params
Beispiel #41
0
    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.Checker(params)
        rights['create'] = [('checkHasRoleForScope', host_logic.logic)]
        rights['edit'] = [('checkIsMyActiveRole', host_logic.logic)]
        rights['invite'] = [('checkHasRoleForScope', host_logic.logic)]
        rights['list'] = ['checkIsDeveloper']
        rights['accept_invite'] = [('checkIsMyRequestWithStatus',
                                    [['group_accepted']])]
        rights['process_request'] = [('checkCanProcessRequest',
                                      [[host_logic.logic]])]
        rights['manage'] = [('checkIsAllowedToManageRole',
                             [host_logic.logic, host_logic.logic])]

        new_params = {}
        new_params['rights'] = rights
        new_params['logic'] = soc.logic.models.host.logic
        new_params['group_logic'] = sponsor_logic.logic
        new_params['group_view'] = soc.views.models.sponsor.view

        new_params['scope_view'] = sponsor_view

        new_params['name'] = "Program Administrator"
        new_params['module_name'] = "host"
        new_params['sidebar_grouping'] = 'Programs'

        new_params['extra_dynaexclude'] = ['agreed_to_tos']

        new_params['create_extra_dynaproperties'] = {
            'scope_path': forms.CharField(widget=forms.HiddenInput,
                                          required=True),
            'clean_link_id': cleaning.clean_existing_user('link_id'),
            'clean_home_page': cleaning.clean_url('home_page'),
            'clean_blog': cleaning.clean_url('blog'),
            'clean_photo_url': cleaning.clean_url('photo_url')
        }

        new_params['allow_invites'] = True
        new_params['show_in_roles_overview'] = True

        new_params['public_field_keys'] = ["name", "link_id", "scope_path"]
        new_params['public_field_names'] = [
            "Name", "Administrator ID", "Program Owner"
        ]

        params = dicts.merge(params, new_params)

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

        # register the role with the group_view
        self._params['group_view'].registerRole(self._logic.role_name, self)

        # create and store the special form for invited users
        updated_fields = {
            'link_id':
            forms.CharField(widget=widgets.ReadOnlyInput(), required=False)
        }

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

        self._params['invited_create_form'] = invited_create_form
Beispiel #42
0
  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['any_access'] = ['allow']
    rights['show'] = [('checkIsSurveyReadable', project_survey_logic)]
    rights['create'] = ['checkIsUser']
    rights['edit'] = [('checkIsSurveyWritable', project_survey_logic)]
    rights['delete'] = ['checkIsDeveloper'] # TODO: fix deletion of Surveys
    rights['list'] = ['checkDocumentList']
    rights['record'] = [('checkHasAny', [
        [('checkIsAllowedToViewProjectSurveyRecordAs',
          [project_survey_logic, 'student', 'id']),
        ('checkIsSurveyReadable', [project_survey_logic]),
        ]])]
    rights['results'] = ['checkIsUser']
    rights['take'] = [('checkIsSurveyTakeable', project_survey_logic),
                      ('checkIsAllowedToTakeProjectSurveyAs',
                       [project_survey_logic, 'student', 'project'])]
    rights['send_reminder'] = [('checkIsHostForProgramInScope', program_logic)]

    new_params = {}
    new_params['logic'] = project_survey_logic
    new_params['rights'] = rights

    new_params['name'] = "Project Survey"
    new_params['url_name'] = 'gsoc/project_survey'
    new_params['module_package'] = 'soc.modules.gsoc.views.models'

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

    new_params['extra_django_patterns'] = [
         (r'^%(url_name)s/(?P<access_type>send_reminder)/%(key_fields)s$',
          '%(module_package)s.%(module_name)s.send_reminder',
         'Send Reminder for %(name)s')]

    new_params['take_template'] = 'soc/project_survey/take.html'

    # used for sending reminders
    new_params['survey_type'] = 'project'
    new_params['reminder_template'] = 'soc/project_survey/reminder.html'

    new_params['records_field_keys'] = [
        'mentor_id', 'student_id', 'organization'
    ]
    new_params['records_field_names'] = [
        'Mentor Link ID', 'Student Link ID', 'Organization'
    ]
    new_params['records_field_prefetch'] = ['project', 'org']

    # TODO(ljvderijk): If we ever fix the merging of field_extra remove the
    # taken_by.
    new_params['records_field_extra'] = lambda entity: { 
        'mentor_id': entity.project.mentor.link_id,
        'student_id': entity.project.student.link_id,
        'organization': entity.org.name,
        'taken_by': '%s (%s)' %(entity.user.name, entity.user.link_id),
    }

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

    super(View, self).__init__(params=params)
Beispiel #43
0
    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.Checker(params)
        rights['listSelf'] = ['checkIsUser']
        rights['create'] = ['deny']
        rights['edit'] = ['checkIsDeveloper']
        rights['process_invite'] = [('checkIsMyRequestWithStatus',
                                     [['group_accepted']])]
        rights['list'] = ['checkIsDeveloper']
        rights['delete'] = ['checkIsDeveloper']
        rights['roles'] = ['checkIsUser']

        new_params = {}
        new_params['rights'] = rights
        new_params['logic'] = request_logic

        new_params['name'] = "Request"

        new_params['sidebar_developer'] = [('/%s/list', 'List %(name_plural)s',
                                            'list')]

        new_params['create_template'] = ['soc/request/create.html']

        new_params['extra_dynaexclude'] = ['user', 'role', 'group', 'status']

        patterns = [
            (r'^%(url_name)s/(?P<access_type>process_invite)/(?P<id>[0-9]*)$',
             'soc.views.models.%(module_name)s.process_invite',
             'Process Invite to become')
        ]

        new_params['extra_django_patterns'] = patterns

        new_params[
            'invite_processing_template'] = 'soc/request/process_invite.html'
        new_params['request_processing_template'] = \
            'soc/request/process_request.html'

        new_params['public_field_extra'] = lambda entity: {
            "user": "******" % (entity.user.name, entity.user.link_id),
            "for": entity.group.name,
        }
        new_params['public_field_keys'] = [
            "role", "user", "for", "status", "created_on"
        ]
        new_params['public_field_names'] = [
            "Role", "User", "For", "Status", "Created On"
        ]

        params = dicts.merge(params, new_params)

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

        # create and store the special forms for invite and requests
        self._params['request_form'] = self._params['create_form']

        updated_fields = {
            'user_id': widgets.ReferenceField(reference_url='user'),
            'clean_user_id': cleaning.clean_existing_user('user_id'),
        }

        invite_form = dynaform.extendDynaForm(
            dynaform=self._params['create_form'],
            dynaproperties=updated_fields)
        # reverse the fields so that user_id field comes first
        invite_form.base_fields.keyOrder.reverse()

        self._params['invite_form'] = invite_form
Beispiel #44
0
    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.Checker(params)
        rights['any_access'] = ['allow']
        rights['show'] = ['checkIsDocumentReadable']
        rights['create'] = ['checkIsDocumentCreatable']
        rights['edit'] = ['checkIsDocumentWritable']
        rights['delete'] = ['checkIsDocumentWritable']
        rights['list'] = ['checkDocumentList']
        rights['pick'] = ['checkDocumentPick']

        new_params = {}
        new_params['logic'] = document_logic
        new_params['rights'] = rights

        new_params['name'] = "Document"
        new_params['pickable'] = True

        new_params['export_content_type'] = 'text/text'
        new_params['export_extension'] = '.html'
        new_params['export_function'] = lambda x: (x.content, x.link_id)
        new_params['delete_redirect'] = '/'

        new_params['no_create_raw'] = True
        new_params['no_create_with_scope'] = True
        new_params['no_create_with_key_fields'] = True
        new_params['no_list_raw'] = True
        new_params['sans_link_id_create'] = True
        new_params['sans_link_id_list'] = True

        new_params['create_dynafields'] = [
            {
                'name': 'link_id',
                'base': forms.fields.CharField,
                'label': 'Document Link ID',
            },
        ]

        new_params['create_extra_dynaproperties'] = {
            'content':
            forms.fields.CharField(widget=widgets.FullTinyMCE(attrs={
                'rows': 25,
                'cols': 100
            })),
            'scope_path':
            forms.fields.CharField(widget=forms.HiddenInput, required=True),
            'prefix':
            forms.fields.CharField(widget=widgets.ReadOnlyInput(),
                                   required=True),
            'clean_content':
            cleaning.clean_html_content('content'),
            'clean_link_id':
            cleaning.clean_link_id('link_id'),
            'clean_scope_path':
            cleaning.clean_scope_path('scope_path'),
            'clean':
            cleaning.validate_document_acl(self, True),
        }
        new_params['extra_dynaexclude'] = [
            'author', 'created', 'home_for', 'modified_by', 'modified'
        ]

        new_params['edit_extra_dynaproperties'] = {
            'doc_key_name':
            forms.fields.CharField(widget=forms.HiddenInput),
            'created_by':
            forms.fields.CharField(widget=widgets.ReadOnlyInput(),
                                   required=False),
            'last_modified_by':
            forms.fields.CharField(widget=widgets.ReadOnlyInput(),
                                   required=False),
            'clean':
            cleaning.validate_document_acl(self),
        }

        new_params['public_field_prefetch'] = ['author']
        new_params['public_field_extra'] = lambda entity: {
            'path': entity.scope_path + '/' + entity.link_id,
            'author_id': entity.author.link_id,
        }
        new_params['public_field_keys'] = [
            "path", "title", "link_id", "is_featured", "author_id", "created",
            "modified"
        ]
        new_params['public_field_names'] = [
            "Path", "Title", "Link ID", "Featured", "Created By", "Created On",
            "Modified"
        ]

        params = dicts.merge(params, new_params)

        super(View, self).__init__(params=params)
Beispiel #45
0
  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.Checker(params)
    rights['unspecified'] = ['checkIsDeveloper']
    rights['any_access'] = ['allow']
    rights['home'] = ['allow']
    rights['show'] = ['checkIsDeveloper']

    new_params = {}
    new_params['logic'] = soc.logic.models.site.logic
    new_params['rights'] = rights

    new_params['name'] = "Site Settings"
    new_params['name_plural'] = new_params['name']
    new_params['document_prefix'] = 'site'
    new_params['name_short'] = "Site"

    new_params['sidebar_developer'] = []

    new_params['sidebar_defaults'] = [('/%s/edit', 'Edit %(name)s', 'edit')]
    new_params['sidebar_heading'] = new_params['name_short']

    new_params['edit_template'] = 'soc/site/edit.html'
    new_params['home_template'] = 'soc/site/home.html'

    new_params['create_extra_dynaproperties'] = {
        'link_id': forms.CharField(widget=forms.HiddenInput, required=True),
        'noreply_email': forms.EmailField(required=False),
        }
    new_params['edit_extra_dynaproperties'] = {
        'link_id': forms.CharField(widget=forms.HiddenInput, required=True),
        'home_link_id': widgets.ReferenceField(
            reference_url='document', required=False,
            filter_fields={'prefix': new_params['document_prefix']},
            label=ugettext('Home page Document link ID'),
            help_text=soc.models.work.Work.link_id.help_text),
        'tos_link_id': widgets.ReferenceField(
            reference_url='document', required=False,
            filter_fields={'prefix': new_params['document_prefix']},
            label=ugettext('Terms of Service Document link ID'),
            help_text=soc.models.work.Work.link_id.help_text),
        'clean_noreply_email': cleaning.clean_empty_field('noreply_email'),
        }

    # XSRF secret key is not editable by mere mortals.
    new_params['extra_dynaexclude'] = ['xsrf_secret_key']

    patterns = []

    page_name = "Home Page"
    patterns += [(r'^$', 'soc.views.models.%(module_name)s.main_public',
                  page_name)]

    page_name = "Edit Site"
    patterns += [(r'^%(url_name)s/(?P<access_type>edit)$',
                  'soc.views.models.%(module_name)s.main_edit',
                  page_name)]

    if soc.logic.system.isDebug():
      patterns += [('^seed_db$', 'soc.models.seed_db.seed', "Seed DB"),
                   ('^clear_db$', 'soc.models.seed_db.clear', "Clear DB"),
                   ('^reseed_db$', 'soc.models.seed_db.reseed', "Reseed DB"),
                   ('^seed_many$', 'soc.models.seed_db.seed_many', "Seed Many"),
                   ('^new_seed_many$', 'soc.models.seed_db.new_seed_many',
                    "New Seed Many"),
                   ]

    new_params['extra_django_patterns'] = patterns

    params = dicts.merge(params, new_params)

    super(View, self).__init__(params=params)
Beispiel #46
0
    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['extra_dynaexclude'] = [
            'founder', 'home', 'tos', 'member_template', 'status'
        ]
        new_params['edit_extra_dynaproperties'] = {
            'founded_by':
            forms.CharField(widget=widgets.ReadOnlyInput(), required=False),
        }

        #set the extra_django_patterns and include the one from params
        patterns = params.get('extra_django_patterns', [])

        patterns += [
            (r'^%(url_name)s/(?P<access_type>list_requests)/%(key_fields)s$',
             '%(module_package)s.%(module_name)s.list_requests',
             'List of requests for %(name)s'),
            (r'^%(url_name)s/(?P<access_type>list_roles)/%(key_fields)s$',
             '%(module_package)s.%(module_name)s.list_roles',
             'List of roles for %(name)s')
        ]

        new_params['extra_django_patterns'] = patterns

        # TODO(tlarsen): Add support for Django style template lookup
        new_params['public_template'] = 'soc/group/public.html'

        new_params['create_extra_dynaproperties'] = {
            'email':
            forms.fields.EmailField(required=True),
            'clean_phone':
            cleaning.clean_phone_number('phone'),
            'clean_contact_street':
            cleaning.clean_valid_shipping_chars('contact_street'),
            'clean_contact_street_extra':
            cleaning.clean_valid_shipping_chars('contact_street_extra'),
            'clean_contact_city':
            cleaning.clean_valid_shipping_chars('contact_city'),
            'clean_contact_state':
            cleaning.clean_valid_shipping_chars('contact_state'),
            'clean_contact_postalcode':
            cleaning.clean_valid_shipping_chars('contact_postalcode'),
            'clean_shipping_street':
            cleaning.clean_valid_shipping_chars('shipping_street'),
            'clean_shipping_street_extra':
            cleaning.clean_valid_shipping_chars('shipping_street_extra'),
            'clean_shipping_city':
            cleaning.clean_valid_shipping_chars('shipping_city'),
            'clean_shipping_state':
            cleaning.clean_valid_shipping_chars('shipping_state'),
            'clean_shipping_postalcode':
            cleaning.clean_valid_shipping_chars('shipping_postalcode'),
        }

        new_params['role_views'] = {}

        new_params['public_field_keys'] = ["name", "link_id", "short_name"]
        new_params['public_field_names'] = ["Name", "Link ID", "Short name"]

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

        super(View, self).__init__(params=params)
Beispiel #47
0
    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['any_access'] = ['allow']
        rights['create'] = ['checkIsDeveloper']
        rights['edit'] = ['checkIsDeveloper']
        rights['delete'] = ['checkIsDeveloper']
        rights['show'] = ['allow']
        rights['list'] = ['checkIsDeveloper']
        rights['manage'] = [('checkHasRoleForScope',
                             [org_admin_logic, ['active', 'inactive']]),
                            ('checkStudentProjectHasStatus',
                             [['accepted', 'failed', 'completed',
                               'withdrawn']])]
        rights['manage_overview'] = [('checkHasAny', [[
            ('checkHasRoleForScope', [org_admin_logic, ['active',
                                                        'inactive']]),
            ('checkHasRoleForScope', [mentor_logic, ['active', 'inactive']])
        ]])]
        # TODO: lack of better name here!
        rights['st_edit'] = [
            'checkCanEditStudentProjectAsStudent',
            ('checkStudentProjectHasStatus', [['accepted', 'completed']])
        ]
        rights['overview'] = [('checkIsHostForProgram', [program_logic])]

        new_params = {}
        new_params['logic'] = project_logic
        new_params['rights'] = rights
        new_params['name'] = 'Student Project'
        new_params['url_name'] = 'gsoc/student_project'
        new_params['module_package'] = 'soc.modules.gsoc.views.models'
        new_params['sidebar_grouping'] = 'Students'

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

        new_params['no_create_with_key_fields'] = True

        new_params['extra_dynaexclude'] = [
            'program', 'status', 'link_id', 'mentor', 'additional_mentors',
            'student', 'passed_evaluations', 'failed_evaluations'
        ]

        new_params['create_extra_dynaproperties'] = {
            'scope_path':
            forms.CharField(widget=forms.HiddenInput, required=True),
            'public_info':
            forms.fields.CharField(required=True,
                                   widget=widgets.FullTinyMCE(attrs={
                                       'rows': 25,
                                       'cols': 100
                                   })),
            'student_id':
            forms.CharField(label='Student Link ID', required=True),
            'mentor_id':
            forms.CharField(label='Mentor Link ID', required=True),
            'clean_abstract':
            cleaning.clean_content_length('abstract'),
            'clean_public_info':
            cleaning.clean_html_content('public_info'),
            'clean_student':
            cleaning.clean_link_id('student'),
            'clean_mentor':
            cleaning.clean_link_id('mentor'),
            'clean_additional_info':
            cleaning.clean_url('additional_info'),
            'clean_feed_url':
            cleaning.clean_feed_url('feed_url'),
            'clean':
            cleaning.validate_student_project('scope_path', 'mentor_id',
                                              'student_id')
        }

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

        patterns = [
            (r'^%(url_name)s/(?P<access_type>manage_overview)/%(scope)s$',
             'soc.modules.gsoc.views.models.%(module_name)s.manage_overview',
             'Overview of %(name_plural)s to Manage for'),
            (r'^%(url_name)s/(?P<access_type>manage)/%(key_fields)s$',
             'soc.modules.gsoc.views.models.%(module_name)s.manage',
             'Manage %(name)s'),
            (r'^%(url_name)s/(?P<access_type>st_edit)/%(key_fields)s$',
             'soc.modules.gsoc.views.models.%(module_name)s.st_edit',
             'Edit my %(name)s'),
            (r'^%(url_name)s/(?P<access_type>overview)/(?P<scope_path>%(ulnp)s)/%(lnp)s$',
             'soc.modules.gsoc.views.models.%(module_name)s.overview',
             'Overview of all %(name_plural)s for'),
        ]

        new_params['extra_django_patterns'] = patterns

        new_params['edit_template'] = 'soc/student_project/edit.html'
        new_params['manage_template'] = 'soc/student_project/manage.html'

        new_params['public_field_prefetch'] = ['mentor', 'student', 'scope']
        new_params['public_field_extra'] = lambda entity: {
            'student': entity.student.name(),
            'mentor': entity.mentor.name(),
            'org': entity.scope.name,
        }
        new_params['public_field_keys'] = [
            'student', 'title', 'mentor', 'org', 'status'
        ]
        new_params['public_field_names'] = [
            'Student', 'Title', 'Mentor', 'Organization', 'Status'
        ]

        new_params['org_home_field_prefetch'] = ['mentor', 'student']
        new_params['org_home_field_extra'] = lambda entity: {
            'student':
            entity.student.name(),
            'mentor':
            ', '.join(mentor.name() for mentor in [entity.mentor] + db.get(
                entity.additional_mentors))
        }
        new_params['org_home_field_keys'] = [
            'student', 'title', 'mentor', 'status'
        ]
        new_params['org_home_field_names'] = [
            'Student', 'Title', 'Mentor', 'Status'
        ]

        # define the list redirect action to show the notification
        new_params['public_row_extra'] = new_params[
            'org_home_row_extra'] = lambda entity: {
                'link': redirects.getPublicRedirect(entity, new_params)
            }
        new_params['org_home_row_action'] = {
            'type': 'redirect_custom',
            'parameters': dict(new_window=False),
        }

        new_params['admin_field_prefetch'] = ['mentor', 'student', 'scope']
        new_params['admin_field_extra'] = lambda entity: {
            'student': entity.student.name(),
            'mentor': entity.mentor.name(),
            'student_id': entity.student.link_id
        }
        new_params['admin_field_keys'] = [
            'student', 'title', 'mentor', 'status', 'student_id'
        ]
        new_params['admin_field_names'] = [
            'Student', 'Title', 'Mentor', 'Status', 'Student Link ID'
        ]
        new_params['admin_field_hidden'] = ['student_id']

        new_params['admin_conf_extra'] = {
            'multiselect': True,
        }
        new_params['admin_button_global'] = [{
            'bounds': [1, 'all'],
            'id': 'withdraw',
            'caption': 'Withdraw Project',
            'type': 'post',
            'parameters': {
                'url': '',
                'keys': ['key'],
                'refresh': 'current',
            }
        }, {
            'bounds': [1, 'all'],
            'id': 'accept',
            'caption': 'Accept Project',
            'type': 'post',
            'parameters': {
                'url': '',
                'keys': ['key'],
                'refresh': 'current',
            }
        }]

        params = dicts.merge(params, new_params)

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

        # create the form that students will use to edit their projects
        dynaproperties = {
            'public_info':
            forms.fields.CharField(required=True,
                                   widget=widgets.FullTinyMCE(attrs={
                                       'rows': 25,
                                       'cols': 100
                                   })),
            'clean_abstract':
            cleaning.clean_content_length('abstract'),
            'clean_public_info':
            cleaning.clean_html_content('public_info'),
            'clean_additional_info':
            cleaning.clean_url('additional_info'),
            'clean_feed_url':
            cleaning.clean_feed_url('feed_url'),
        }

        student_edit_form = dynaform.newDynaForm(
            dynabase=self._params['dynabase'],
            dynamodel=self._params['logic'].getModel(),
            dynaexclude=self._params['create_dynaexclude'],
            dynaproperties=dynaproperties,
        )

        self._params['student_edit_form'] = student_edit_form
Beispiel #48
0
    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.

    Args:
      params: a dict with params for this View

    """

        rights = access.DataSeederChecker(params)

        rights['home'] = ['checkIsDeveloper']

        new_params = {}

        new_params['logic'] = seeder_logic
        new_params['rights'] = rights
        new_params['scope_view'] = None
        new_params['name'] = 'seeder'
        new_params['sidebar_grouping'] = 'Data Seeder'
        new_params['module_package'] = 'soc.modules.seeder.views'
        new_params['module_name'] = 'seeder'

        new_params['url_name'] = 'seeder'
        new_params['link_id_arg_pattern'] = ''
        new_params['link_id_pattern_core'] = ''
        new_params['key_fields_pattern'] = ''
        new_params['scope_path_pattern'] = ''
        new_params['sans_link_id_pattern'] = ''

        patterns = []
        patterns += [
            (r'^%(url_name)s/get_data$',
             '%(module_package)s.%(module_name)s.get_data', 'Get Data'),
            (r'^%(url_name)s/home$', '%(module_package)s.%(module_name)s.home',
             'Manage Data Seeder'),
            (r'^%(url_name)s/seed$', '%(module_package)s.%(module_name)s.seed',
             'Start seeding'),
            (r'^%(url_name)s/echo$', '%(module_package)s.%(module_name)s.echo',
             'Echo'),
            (r'^%(url_name)s/test_provider$',
             '%(module_package)s.%(module_name)s.test_provider',
             'Test data provider'),
            (r'^%(url_name)s/validate_configuration_sheet$',
             '%(module_package)s.%(module_name)s.validate_configuration_sheet',
             'Validate configuration sheet'),
        ]

        new_params['django_patterns'] = None
        new_params['django_patterns_defaults'] = []
        new_params['extra_django_patterns'] = patterns

        new_params['sidebar'] = None
        new_params['sidebar_defaults'] = patterns
        new_params['sidebar_additional'] = patterns
        new_params['sidebar_developer'] = patterns

        params = dicts.merge(params, new_params)

        # FIXME : temporarily added due to errors
        self._params = params
Beispiel #49
0
  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'] = group_app_logic

    new_params['name'] = "Group Application"
    new_params['name_short'] = "Group App"

    # use the twoline templates for these questionnaires
    new_params['create_template'] = 'soc/models/twoline_edit.html'
    new_params['edit_template'] = 'soc/models/twoline_edit.html'

    patterns = [(r'^%(url_name)s/(?P<access_type>list_self)/%(scope)s$',
        'soc.views.models.%(module_name)s.list_self',
        'List my %(name_plural)s'),
        (r'^%(url_name)s/(?P<access_type>review_overview)/%(scope)s$',
        'soc.views.models.%(module_name)s.review_overview',
        'List of %(name_plural)s for reviewing'),
        (r'^%(url_name)s/(?P<access_type>review)/%(key_fields)s$',
          'soc.views.models.%(module_name)s.review',
          'Review %(name_short)s')]

    new_params['extra_django_patterns'] = patterns

    new_params['extra_dynaexclude'] = ['applicant', 'backup_admin', 'status',
        'created_on', 'last_modified_on']

    new_params['create_dynafields'] = [
        {'name': 'backup_admin_link_id',
         'base': widgets.ReferenceField,
         'passthrough': ['reference_url', 'required', 'label'],
         'reference_url': 'user',
         'required': False,
         'label': params['logic'].getModel().backup_admin.verbose_name,
         'example_text': ugettext('The link_id of the backup admin'),
         },
         ]

    new_params['create_extra_dynaproperties'] = {
        'email': forms.fields.EmailField(required=True),
        'clean_backup_admin_link_id': 
            cleaning.clean_users_not_same('backup_admin_link_id'),
        }

    new_params['edit_extra_dynaproperties'] = {
        'clean_link_id' : cleaning.clean_link_id('link_id'),
        }

    new_params['public_field_extra'] = lambda entity: {
        'ideas': list_helper.urlize(entity.ideas),
    }
    new_params['public_field_keys'] = new_params['self_field_keys'] = [
        "name", "link_id", "ideas", "status",
    ]
    new_params['public_field_names'] = new_params['self_field_names'] = [
        "Name", "Link ID", "Ideas Page", "Status",
    ]
    new_params['self_field_extra'] = lambda entity: {
        'ideas': list_helper.urlize(entity.ideas),
        'status': "accepted" if entity.status == "accepted" else
                  "rejected" if entity.status == "rejected" else
                  "under review",
    }

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

    super(View, self).__init__(params=params)
Beispiel #50
0
    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.Checker(params)
        rights['any_access'] = ['allow']
        rights['show'] = [('checkIsSurveyWritable', survey_logic)]
        rights['create'] = ['checkIsUser']
        rights['edit'] = [('checkIsSurveyWritable', survey_logic)]
        rights['delete'] = ['checkIsDeveloper'
                            ]  # TODO: fix deletion of Surveys
        rights['list'] = ['checkDocumentList']
        rights['pick'] = ['checkDocumentPick']
        rights['record'] = [('checkHasAny', [[
            ('checkIsSurveyReadable', [survey_logic]),
            ('checkIsMySurveyRecord', [survey_logic, 'id'])
        ]])]
        rights['results'] = ['checkIsUser']
        rights['take'] = [('checkIsSurveyTakeable', survey_logic)]

        new_params = {}
        new_params['logic'] = survey_logic
        new_params['rights'] = rights

        new_params['name'] = 'Survey'
        new_params['sidebar_grouping'] = "Surveys"

        new_params['extra_django_patterns'] = [
            (r'^%(url_name)s/(?P<access_type>take)/%(key_fields)s$',
             '%(module_package)s.%(module_name)s.take', 'Take %(name)s'),
            (r'^%(url_name)s/(?P<access_type>json)/%(scope)s$',
             '%(module_package)s.%(module_name)s.json',
             'Export %(name)s as JSON'),
            (r'^%(url_name)s/(?P<access_type>record)/%(key_fields)s$',
             '%(module_package)s.%(module_name)s.record',
             'View survey record for %(name)s'),
            (r'^%(url_name)s/(?P<access_type>results)/%(key_fields)s$',
             '%(module_package)s.%(module_name)s.results',
             'View survey results for %(name)s'),
            (r'^%(url_name)s/(?P<access_type>show)/user/(?P<link_id>)\w+$',
             '%(module_package)s.%(module_name)s.results',
             'View survey results for user'),
        ]

        new_params['export_content_type'] = 'text/text'
        new_params['export_extension'] = '.csv'
        new_params['export_function'] = surveys.toCSV(self)
        new_params['delete_redirect'] = '/'
        new_params['list_key_order'] = [
            'link_id', 'scope_path', 'name', 'short_name', 'title', 'content',
            'prefix', 'read_access', 'write_access'
        ]

        new_params['edit_template'] = 'soc/survey/edit.html'
        new_params['create_template'] = 'soc/survey/edit.html'
        new_params['public_template'] = 'soc/survey/public.html'
        new_params['record_template'] = 'soc/survey/view_record.html'
        new_params['take_template'] = 'soc/survey/take.html'

        new_params['no_create_raw'] = True
        new_params['no_create_with_scope'] = True
        new_params['no_create_with_key_fields'] = True
        new_params['no_list_raw'] = True
        new_params['sans_link_id_create'] = True
        new_params['sans_link_id_list'] = True

        new_params['create_dynafields'] = [
            {
                'name': 'link_id',
                'base': forms.fields.CharField,
                'label': 'Survey Link ID',
            },
        ]

        new_params['create_extra_dynaproperties'] = {
            'content':
            forms.fields.CharField(required=False,
                                   label='Description',
                                   widget=widgets.FullTinyMCE(attrs={
                                       'rows': 25,
                                       'cols': 100
                                   })),
            'survey_html':
            forms.fields.CharField(widget=forms.HiddenInput, required=False),
            'scope_path':
            forms.fields.CharField(widget=forms.HiddenInput, required=True),
            'prefix':
            forms.fields.CharField(widget=widgets.ReadOnlyInput(),
                                   required=True),
            'clean_content':
            cleaning.clean_html_content('content'),
            'clean_link_id':
            cleaning.clean_link_id('link_id'),
            'clean_scope_path':
            cleaning.clean_scope_path('scope_path'),
            'clean':
            cleaning.validate_document_acl(self, True),
        }

        new_params['extra_dynaexclude'] = [
            'author', 'created', 'home_for', 'modified_by', 'modified',
            'take_survey', 'survey_content'
        ]

        new_params['edit_extra_dynaproperties'] = {
            'doc_key_name':
            forms.fields.CharField(widget=forms.HiddenInput),
            'created_by':
            forms.fields.CharField(widget=widgets.ReadOnlyInput(),
                                   required=False),
            'last_modified_by':
            forms.fields.CharField(widget=widgets.ReadOnlyInput(),
                                   required=False),
            'clean':
            cleaning.validate_document_acl(self),
        }

        new_params['survey_take_form'] = surveys.SurveyTakeForm
        new_params['survey_record_form'] = surveys.SurveyRecordForm

        new_params['public_field_extra'] = lambda entity: {
            "path": entity.scope_path + '/' + entity.link_id,
            "created_by": entity.author.link_id,
        }
        new_params['public_field_keys'] = [
            "path", "title", "link_id", "is_featured", "created_by", "created",
            "modified"
        ]
        new_params['public_field_names'] = [
            "Path",
            "Title",
            "Link ID",
            "Featured",
            "Created By",
            "Created On",
            "Modified",
        ]

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

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

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

        rights = gci_access.GCIChecker(params)
        rights['show'] = ['allow']
        rights['create'] = [('checkSeeded',
                             ['checkHasRoleForScope', host_logic])]
        rights['edit'] = [('checkIsHostForProgram', [gci_program_logic.logic])]
        rights['delete'] = ['checkIsDeveloper']
        rights['assign_task_quotas'] = [('checkIsHostForProgram',
                                         [gci_program_logic.logic])]
        rights['accepted_orgs'] = [('checkIsAfterEvent', [
            'accepted_organization_announced_deadline', '__all__',
            gci_program_logic.logic
        ])]
        rights['list_participants'] = [('checkIsHostForProgram',
                                        [gci_program_logic.logic])]
        rights['task_difficulty'] = [('checkIsHostForProgram',
                                      [gci_program_logic.logic])]
        rights['task_type'] = [('checkIsHostForProgram',
                                [gci_program_logic.logic])]
        rights['type_tag_edit'] = [('checkIsHostForProgram',
                                    [gci_program_logic.logic])]
        rights['list_self'] = [
            ('checkIsAfterEvent',
             ['tasks_publicly_visible', '__all__',
              gci_program_logic.logic]), 'checkIsUser'
        ]
        rights['list_tasks'] = [
            ('checkIsAfterEvent',
             ['tasks_publicly_visible', '__all__', gci_program_logic.logic])
        ]
        rights['show_ranking'] = ['allow']
        rights['request_tasks'] = [
            ('checkHasRoleForKeyFieldsAsScope', [gci_student_logic.logic]),
            ('checkIsAfterEvent',
             ['tasks_publicly_visible', '__all__', gci_program_logic.logic]),
            ('checkIsBeforeEvent',
             ['task_claim_deadline', '__all__', gci_program_logic.logic])
        ]

        new_params = {}
        new_params['logic'] = soc.modules.gci.logic.models.program.logic
        new_params['rights'] = rights

        new_params['name'] = "GCI Program"
        new_params['module_name'] = "program"
        new_params['sidebar_grouping'] = 'Programs'
        new_params['document_prefix'] = 'gci_program'

        new_params['module_package'] = 'soc.modules.gci.views.models'
        new_params['url_prefix'] = 'gci'
        new_params['url_name'] = 'gci/program'

        new_params['extra_dynaexclude'] = [
            'task_difficulties', 'task_types', 'ranking_schema'
        ]

        patterns = []
        patterns += [
            (r'^%(url_name)s/(?P<access_type>assign_task_quotas)/%(key_fields)s$',
             '%(module_package)s.%(module_name)s.assign_task_quotas',
             'Assign task quota limits'),
            (r'^%(url_name)s/(?P<access_type>task_difficulty)/%(key_fields)s$',
             '%(module_package)s.%(module_name)s.task_difficulty_edit',
             'Edit Task Difficulty Tags'),
            (r'^%(url_name)s/(?P<access_type>task_type)/%(key_fields)s$',
             '%(module_package)s.%(module_name)s.task_type_edit',
             'Edit Task Type Tags'),
            (r'^%(url_name)s/(?P<access_type>type_tag_edit)/%(key_fields)s$',
             '%(module_package)s.%(module_name)s.task_type_tag_edit',
             'Edit a Task Type Tag'),
            (r'^%(url_name)s/(?P<access_type>list_self)/%(key_fields)s$',
             '%(module_package)s.%(module_name)s.list_my_tasks',
             'List of my starred tasks'),
            (r'^%(url_name)s/(?P<access_type>list_tasks)/%(key_fields)s$',
             '%(module_package)s.%(module_name)s.list_tasks',
             'List of all Tasks in'),
            (r'^%(url_name)s/(?P<access_type>show_ranking)/%(key_fields)s$',
             '%(module_package)s.%(module_name)s.show_ranking',
             'Show ranking'),
            (r'^%(url_name)s/(?P<access_type>request_tasks)/%(key_fields)s$',
             '%(module_package)s.%(module_name)s.request_tasks',
             'Request more tasks'),
        ]

        new_params['public_field_keys'] = ["name", "scope_path"]
        new_params['public_field_names'] = ["Program Name", "Program Owner"]

        new_params['extra_django_patterns'] = patterns

        new_params['org_app_logic'] = org_app_logic

        # used to list the participants in this program
        new_params['participants_logic'] = [
            (gci_org_admin_logic.logic, 'program'),
            (gci_mentor_logic.logic, 'program'),
            (gci_student_logic.logic, 'scope')
        ]

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

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

        dynafields = [
            {
                'name':
                'overview_task_difficulties',
                'base':
                forms.CharField,
                'label':
                'Task Difficulty Levels',
                'group':
                'Task Settings',
                'widget':
                widgets.ReadOnlyInput(),
                'required':
                False,
                'help_text':
                ugettext('Lists all the difficulty levels that '
                         'can be assigned to a task. Edit them '
                         'from the Program menu on sidebar.'),
            },
            {
                'name':
                'overview_task_types',
                'base':
                forms.CharField,
                'label':
                'Task Type Tags',
                'group':
                'Task Settings',
                'widget':
                widgets.ReadOnlyInput(),
                'required':
                False,
                'help_text':
                ugettext('Lists all the types a task can be in. '
                         'Edit them from the Program menu on sidebar.'),
            },
        ]

        dynaproperties = params_helper.getDynaFields(dynafields)

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

        self._params['edit_form'] = edit_form
Beispiel #52
0
  def getExtraMenus(self, id, user, params=None):
    """Returns the extra menu's for this view.

    A menu item is generated for each group that the user has an active
    role for. The public page for each group is added as menu item,
    as well as all public documents for that group.

    Args:
      params: a dict with params for this View.
    """

    params = dicts.merge(params, self._params)

    # set fields to match every active/inactive role this user has
    fields = {
        'user': user,
        'status': ['active', 'inactive']
        }

    # get the role views and start filling group_entities
    role_views = self._params['role_views']
    role_descriptions = {}

    for role_name in role_views.keys():
      role_view = role_views[role_name]
      role_view_params = role_view.getParams()
      role_logic = role_view_params['logic']

      roles = role_logic.getForFields(fields)

      for role in roles:
        group_key_name = role.scope.key().id_or_name()
        existing_role_descriptions = role_descriptions.get(group_key_name)

        if existing_role_descriptions:
          # add this description to existing roles
          existing_roles = existing_role_descriptions['roles']
          existing_roles[role_name] = role
        else:
          # create a description of this role
          role_description = {'roles': {role_name: role},
              'group': role.scope}

          # add the new entry to our dictionary
          role_descriptions[group_key_name] = role_description

    # get the document view params to add the group's documents to the menu
    doc_params = document_view.view.getParams()

    menus = []

    # for each role description in our collection
    for role_description in role_descriptions.itervalues():
      #start with an empty menu
      menu = {}

      # get the group for this role description
      group_entity = role_description['group']

      # set the menu header name
      menu['heading'] = group_entity.short_name

      # get the documents for this group entity
      doc_items = document_view.view.getMenusForScope(group_entity, params)
      doc_items = sidebar.getSidebarMenu(id, user, doc_items,
                                         params=doc_params)

      # get the group specific items
      group_items = self._getExtraMenuItems(role_description, params)
      group_items = sidebar.getSidebarMenu(id, user, group_items,
                                           params=self._params)

      # add the items together
      menu['items'] = doc_items + group_items
      menu['group'] = params['name_plural']

      # append this as a new menu
      menus.append(menu)

    return menus
Beispiel #53
0
def convert_proposals(request, *args, **kwargs):
    """Convert proposals for all organizations.

  POST Args:
    programkey: the key of the program whose proposals should be converted
    orgkey: the organization key to start at
  """

    # Setup an artifical request deadline
    timelimit = 20000
    timekeeper = Timekeeper(timelimit)

    # Copy for modification below
    params = dicts.merge(request.POST, request.GET)

    if "programkey" not in params:
        logging.error("missing programkey in params: '%s'" % params)
        return responses.terminateTask()

    program = program_logic.getFromKeyName(params["programkey"])

    if not program:
        logging.error("invalid programkey in params: '%s'" % params)
        return responses.terminateTask()

    fields = {
        "scope": program,
        "status": "active",
    }

    # Continue from the next organization
    if "orgkey" in params:
        org = org_logic.getFromKeyName(params["orgkey"])

        if not org:
            logging.error("invalid orgkey in params: '%s'" % params)
            return responses.terminateTask()

        fields["__key__ >="] = org

    # Add a task for each organization
    org = None
    try:
        orgs = org_logic.getQueryForFields(filter=fields)

        for remain, org in timekeeper.iterate(orgs):
            logging.info("convert %s %s", remain, org.key())

            # Compound accept/reject taskflow
            taskqueue.add(url="/tasks/accept_proposals/accept",
                          params={
                              "orgkey": org.key().id_or_name(),
                              "timelimit": timelimit,
                              "nextpath": "/tasks/accept_proposals/reject"
                          })

    # Requeue this task for continuation
    except DeadlineExceededError:
        if org:
            params["orgkey"] = org.key().id_or_name()

        taskqueue.add(url=request.path, params=params)

    # Exit this task successfully
    return responses.terminateTask()
Beispiel #54
0
    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['any_access'] = ['allow']
        rights['show'] = ['allow']
        rights['create'] = [('checkSeeded',
                             ['checkHasRoleForScope', host_logic])]
        rights['edit'] = [('checkIsHostForProgram', [program_logic])]
        rights['delete'] = ['checkIsDeveloper']
        rights['assign_slots'] = [('checkIsHostForProgram', [program_logic])]
        rights['slots'] = [('checkIsHostForProgram', [program_logic])]
        rights['show_duplicates'] = [('checkIsHostForProgram', [program_logic])
                                     ]
        rights['assigned_proposals'] = [('checkIsHostForProgram',
                                         [program_logic])]
        rights['accepted_orgs'] = [('checkIsAfterEvent', [
            'accepted_organization_announced_deadline', '__all__',
            program_logic
        ])]
        rights['list_projects'] = [('checkIsAfterEvent', [
            'accepted_students_announced_deadline', '__all__', program_logic
        ])]

        new_params = {}
        new_params['logic'] = program_logic
        new_params['rights'] = rights

        new_params['name'] = "GSoC Program"
        new_params['module_name'] = "program"
        new_params['sidebar_grouping'] = 'Programs'
        new_params['document_prefix'] = 'gsoc_program'

        new_params['module_package'] = 'soc.modules.gsoc.views.models'
        new_params['url_name'] = 'gsoc/program'

        new_params['extra_dynaexclude'] = ['slots_allocation']

        new_params['create_dynafields'] = [
            {
                'name':
                'org_tags',
                'base':
                forms.fields.Field,
                'widget':
                forms.widgets.Textarea,
                'label':
                'Predefined organization tags',
                'required':
                False,
                'group':
                ugettext('Manage organization tags'),
                'help_text':
                ugettext(
                    'Enter predefined tags to be used by '
                    'organization admins to tag their organizations. Each line '
                    'should contain only one tag')
            },
        ]

        new_params['create_extra_dynaproperties'] = {
            'clean_org_tags': cleaning.cleanTagsList('org_tags')
        }

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

        super(View, self).__init__(params)