app/soc/views/models/role.py
changeset 3054 6ca30967d1bb
parent 2782 3944749338d3
equal deleted inserted replaced
3053:1dc307cb97d0 3054:6ca30967d1bb
    27 from django import http
    27 from django import http
    28 from django.utils.translation import ugettext
    28 from django.utils.translation import ugettext
    29 
    29 
    30 from soc.logic import cleaning
    30 from soc.logic import cleaning
    31 from soc.logic import dicts
    31 from soc.logic import dicts
    32 from soc.logic.models import request as request_logic
       
    33 from soc.logic.models import user as user_logic
    32 from soc.logic.models import user as user_logic
    34 from soc.logic.helper import request as request_helper
    33 from soc.logic.models.request import logic as request_logic
    35 from soc.views.helper import decorators
    34 from soc.views.helper import decorators
    36 from soc.views.helper import redirects
    35 from soc.views.helper import redirects
    37 from soc.views.helper import responses
    36 from soc.views.helper import responses
    38 from soc.views.models import base
    37 from soc.views.models import base
    39 from soc.views.models import request as request_view
    38 from soc.views.models import request as request_view
    63 
    62 
    64   All views that only Role entities have are defined in this subclass.
    63   All views that only Role entities have are defined in this subclass.
    65   """
    64   """
    66 
    65 
    67   DEF_INVITE_INSTRUCTION_MSG_FMT = ugettext(
    66   DEF_INVITE_INSTRUCTION_MSG_FMT = ugettext(
    68       'Please use this form to invite someone to become a %(name)s.')
    67       'Please use this form to invite someone to become a %s for %s.')
    69 
    68 
    70   DEF_REQUEST_INSTRUCTION_MSG_FMT = ugettext(
    69   DEF_REQUEST_INSTRUCTION_MSG_FMT = ugettext(
    71       'Please use this form to request to become a %(name)s')
    70       'Please use this form to request to become a %s for %s.')
    72 
    71 
    73   DEF_INVITE_ERROR_MSG_FMT = ugettext(
    72   DEF_INVITE_ERROR_MSG_FMT = ugettext(
    74       'This user can not receive an invite to become a %(name)s. <br/>'
    73       'This user can not receive an invite to become a %(name)s. <br/>'
    75       'Please make sure there is no outstanding invite or request and '
    74       'Please make sure there is no outstanding invite or request and '
    76       'be sure that this user is not a %(name)s.')
    75       'be sure that this user is not a %(name)s.')
    80       'Please make sure there is no outstanding invite or request and '
    79       'Please make sure there is no outstanding invite or request and '
    81       'be sure that you are not a %(name)s already.')
    80       'be sure that you are not a %(name)s already.')
    82 
    81 
    83 
    82 
    84   def __init__(self, params=None):
    83   def __init__(self, params=None):
    85     """
    84     """Defines the fields and methods required for the base View class
       
    85     to provide the user with list, public, create, edit and delete views.
    86 
    86 
    87     Args:
    87     Args:
    88       params: This dictionary should be filled with the parameters
    88       params: This dictionary should be filled with the parameters
    89     """
    89     """
    90 
    90 
    98     if params.get('allow_requests_and_invites'):
    98     if params.get('allow_requests_and_invites'):
    99       # add patterns concerning requests and invites
    99       # add patterns concerning requests and invites
   100       patterns += [(r'^%(url_name)s/(?P<access_type>invite)/%(scope)s$',
   100       patterns += [(r'^%(url_name)s/(?P<access_type>invite)/%(scope)s$',
   101           '%(module_package)s.%(module_name)s.invite',
   101           '%(module_package)s.%(module_name)s.invite',
   102           'Create invite for %(name)s'),
   102           'Create invite for %(name)s'),
   103           (r'^%(url_name)s/(?P<access_type>accept_invite)/%(scope)s/%(lnp)s$',
   103           (r'^%(url_name)s/(?P<access_type>accept_invite)/(?P<id>[0-9]*)$',
   104           '%(module_package)s.%(module_name)s.accept_invite',
   104           '%(module_package)s.%(module_name)s.accept_invite',
   105           'Accept invite for %(name)s'),
   105           'Accept invite for %(name)s'),
   106           (r'^%(url_name)s/(?P<access_type>process_request)/%(scope)s/%(lnp)s$',
   106           (r'^%(url_name)s/(?P<access_type>process_request)/(?P<id>[0-9]*)$',
   107           '%(module_package)s.%(module_name)s.process_request',
   107           '%(module_package)s.%(module_name)s.process_request',
   108           'Process request'),
   108           'Process request'),
   109           (r'^%(url_name)s/(?P<access_type>request)/%(scope)s$',
   109           (r'^%(url_name)s/(?P<access_type>request)/%(scope)s$',
   110           '%(module_package)s.%(module_name)s.role_request',
   110           '%(module_package)s.%(module_name)s.role_request',
   111           'Create a Request to become %(name)s')]
   111           'Create a Request to become %(name)s')]
   112     elif params.get('allow_invites'):
   112     elif params.get('allow_invites'):
   113       # add patterns concerning only invites
   113       # add patterns concerning only invites
   114       patterns += [(r'^%(url_name)s/(?P<access_type>invite)/%(scope)s$',
   114       patterns += [(r'^%(url_name)s/(?P<access_type>invite)/%(scope)s$',
   115           '%(module_package)s.%(module_name)s.invite',
   115           '%(module_package)s.%(module_name)s.invite',
   116           'Create invite for %(name)s'),
   116           'Create invite for %(name)s'),
   117           (r'^%(url_name)s/(?P<access_type>accept_invite)/%(scope)s/%(lnp)s$',
   117           (r'^%(url_name)s/(?P<access_type>accept_invite)/(?P<id>[0-9]*)$',
   118           '%(module_package)s.%(module_name)s.accept_invite',
   118           '%(module_package)s.%(module_name)s.accept_invite',
   119           'Accept invite for %(name)s'),
   119           'Accept invite for %(name)s'),
   120           (r'^%(url_name)s/(?P<access_type>process_request)/%(scope)s/%(lnp)s$',
   120           (r'^%(url_name)s/(?P<access_type>process_request)/%(scope)s/%(lnp)s$',
   121           '%(module_package)s.%(module_name)s.process_request',
   121           '%(module_package)s.%(module_name)s.process_request',
   122           'Process request for %(name)s')]
   122           'Process request for %(name)s')]
   188 
   188 
   189     # get the context for this webpage
   189     # get the context for this webpage
   190     context = responses.getUniversalContext(request)
   190     context = responses.getUniversalContext(request)
   191     responses.useJavaScript(context, params['js_uses_all'])
   191     responses.useJavaScript(context, params['js_uses_all'])
   192     context['page_name'] = page_name
   192     context['page_name'] = page_name
       
   193 
       
   194     group_entity = params['group_logic'].getFromKeyName(kwargs['scope_path'])
       
   195 
   193     context['instruction_message'] = (self.DEF_INVITE_INSTRUCTION_MSG_FMT %
   196     context['instruction_message'] = (self.DEF_INVITE_INSTRUCTION_MSG_FMT %
   194         params)
   197         (params['name'], group_entity.name))
   195 
   198 
   196     if request.method == 'POST':
   199     if request.method == 'POST':
   197       return self.invitePost(request, context, params, **kwargs)
   200       return self.invitePost(request, context, params, group_entity, **kwargs)
   198     else:
   201     else:
   199       # request.method == 'GET'
   202       # request.method == 'GET'
   200       return self.inviteGet(request, context, params, **kwargs)
   203       return self.inviteGet(request, context, params, **kwargs)
   201 
   204 
   202   def inviteGet(self, request, context, params, **kwargs):
   205   def inviteGet(self, request, context, params, **kwargs):
   208       context: dictionary containing the context for this view
   211       context: dictionary containing the context for this view
   209       params: a dict with params for this View
   212       params: a dict with params for this View
   210       kwargs: the Key Fields for the specified entity
   213       kwargs: the Key Fields for the specified entity
   211     """
   214     """
   212 
   215 
   213     # set the role to the right name
   216     # get the request view parameters and initialize the invite form
   214     fields = {'role': params['logic'].role_name}
       
   215 
       
   216     # get the request view parameters and initialize the create form
       
   217     request_params = request_view.view.getParams()
   217     request_params = request_view.view.getParams()
   218     form = request_params['invite_form'](initial=fields)
   218     form = request_params['invite_form']()
   219 
   219 
   220     # construct the appropriate response
   220     # construct the appropriate response
   221     return super(View, self)._constructResponse(request, entity=None,
   221     return super(View, self)._constructResponse(request, entity=None,
   222         context=context, form=form, params=request_params)
   222         context=context, form=form, params=request_params)
   223 
   223 
   224   def invitePost(self, request, context, params, **kwargs):
   224   def invitePost(self, request, context, params, group_entity, **kwargs):
   225     """Handles the POST request concerning the view that creates an invite
   225     """Handles the POST request concerning the view that creates an invite
   226     for attaining a certain Role.
   226     for attaining a certain Role.
   227 
   227 
   228     Args:
   228     Args:
   229       request: the standard Django HTTP request object
   229       request: the standard Django HTTP request object
   230       page_name: the page name displayed in templates as page and header title
   230       page_name: the page name displayed in templates as page and header title
   231       params: a dict with params for this View
   231       params: a dict with params for this View
       
   232       group_entity: Group entity which this invite is from
   232       kwargs: the Key Fields for the specified entity
   233       kwargs: the Key Fields for the specified entity
   233     """
   234     """
   234 
   235 
   235     # get the request view parameters and populate the form using POST data
   236     # get the request view parameters and populate the form using POST data
   236     request_params = request_view.view.getParams()
   237     request_params = request_view.view.getParams()
   240       # return the invalid form response
   241       # return the invalid form response
   241       return self._constructResponse(request, entity=None, context=context,
   242       return self._constructResponse(request, entity=None, context=context,
   242           form=form, params=request_params)
   243           form=form, params=request_params)
   243 
   244 
   244     # collect the cleaned data from the valid form
   245     # collect the cleaned data from the valid form
   245     key_name, form_fields = soc.views.helper.forms.collectCleanedFields(form)
   246     _, form_fields = soc.views.helper.forms.collectCleanedFields(form)
   246 
       
   247     # get the group entity for which this request is via the scope_path
       
   248     group = self._logic.getGroupEntityFromScopePath(params['group_logic'],
       
   249          kwargs['scope_path'])
       
   250 
       
   251     # get the request scope path
       
   252     request_scope_path = self._getRequestScopePathFromGroup(group)
       
   253 
   247 
   254     # create the fields for the new request entity
   248     # create the fields for the new request entity
   255     request_fields = {'link_id': form_fields['link_id'].link_id,
   249     request_fields = {
   256         'scope': group,
   250         'user': form_fields['user_id'],
   257         'scope_path': request_scope_path,
   251         'group': group_entity,
   258         'role': params['logic'].role_name,
   252         'role': params['logic'].role_name,
   259         'role_verbose': params['name'],
       
   260         'status': 'group_accepted'}
   253         'status': 'group_accepted'}
   261 
   254 
   262     if not self._isValidNewRequest(request_fields, params):
   255     if not request_logic.isValidNewRequest(request_fields, params['logic']):
   263       # not a valid invite
   256       # not a valid invite
   264       context['error_message'] = self.DEF_INVITE_ERROR_MSG_FMT % (
   257       context['error_message'] = self.DEF_INVITE_ERROR_MSG_FMT % (
   265           params)
   258           params)
   266       return self.inviteGet(request, context, params, **kwargs)
   259       return super(View, self)._constructResponse(request, entity=None,
   267 
   260           context=context, form=form, params=request_params)
   268     # extract the key_name for the new request entity
       
   269     key_name = request_logic.logic.getKeyNameFromFields(request_fields)
       
   270 
   261 
   271     # create the request entity
   262     # create the request entity
   272     request_logic.logic.updateOrCreateFromKeyName(request_fields, key_name)
   263     request_logic.updateOrCreateFromFields(request_fields)
   273 
   264 
   274     group_view = params.get('group_view')
   265     group_view = params.get('group_view')
       
   266 
   275     if not group_view:
   267     if not group_view:
   276       return http.HttpResponseRedirect('/')
   268       return http.HttpResponseRedirect('/')
   277     else:
   269     else:
   278       # redirect to the requests list
   270       # redirect to the requests list
   279       return http.HttpResponseRedirect(
   271       return http.HttpResponseRedirect(
   280           redirects.getListRequestsRedirect(group, group_view.getParams()))
   272           redirects.getListRequestsRedirect(group_entity, group_view.getParams()))
   281 
       
   282   def _getRequestScopePathFromGroup(self, group_entity):
       
   283     """Returns the scope_path that should be put in a request for a given group.
       
   284 
       
   285     Args:
       
   286       group_entity: The group entity for which the request scope_path should
       
   287                     be returned.
       
   288     """
       
   289 
       
   290     if group_entity.scope_path:
       
   291       request_scope_path = '%s/%s' % (
       
   292           group_entity.scope_path, group_entity.link_id)
       
   293     else:
       
   294       request_scope_path = group_entity.link_id
       
   295 
       
   296     return request_scope_path
       
   297 
   273 
   298   @decorators.merge_params
   274   @decorators.merge_params
   299   @decorators.check_access
   275   @decorators.check_access
   300   def acceptInvite(self, request, access_type,
   276   def acceptInvite(self, request, access_type,
   301                    page_name=None, params=None, **kwargs):
   277                    page_name=None, params=None, **kwargs):
   304     Args:
   280     Args:
   305       request: the standard Django HTTP request object
   281       request: the standard Django HTTP request object
   306       access_type : the name of the access type which should be checked
   282       access_type : the name of the access type which should be checked
   307       page_name: the page name displayed in templates as page and header title
   283       page_name: the page name displayed in templates as page and header title
   308       params: a dict with params for this View
   284       params: a dict with params for this View
   309       kwargs: the Key Fields for the specified entity
   285       kwargs: contains the ID for the Request entity
   310     """
   286     """
       
   287 
       
   288     request_entity = request_logic.getFromIDOr404(int(kwargs['id']))
   311 
   289 
   312      # get the context for this webpage
   290      # get the context for this webpage
   313     context = responses.getUniversalContext(request)
   291     context = responses.getUniversalContext(request)
   314     responses.useJavaScript(context, params['js_uses_all'])
   292     responses.useJavaScript(context, params['js_uses_all'])
   315     context['page_name'] = page_name
   293     context['page_name'] = page_name
   316 
   294 
   317     if request.method == 'POST':
   295     if request.method == 'POST':
   318       return self.acceptInvitePost(request, context, params, **kwargs)
   296       return self.acceptInvitePost(request, context, params, request_entity,
       
   297                                    **kwargs)
   319     else:
   298     else:
   320       # request.method == 'GET'
   299       # request.method == 'GET'
   321       return self.acceptInviteGet(request, context, params, **kwargs)
   300       return self.acceptInviteGet(request, context, params, request_entity,
   322 
   301                                   **kwargs)
   323   def acceptInviteGet(self, request, context, params, **kwargs):
   302 
       
   303   def acceptInviteGet(self, request, context, params, request_entity,
       
   304                       **kwargs):
   324     """Handles the GET request concerning the creation of a Role via an
   305     """Handles the GET request concerning the creation of a Role via an
   325     invite.
   306     invite.
   326 
   307 
   327     Args:
   308     Args:
   328       request: the standard Django HTTP request object
   309       request: the standard Django HTTP request object
   329       context: dictionary containing the context for this view
   310       context: dictionary containing the context for this view
   330       params: a dict with params for this View
   311       params: a dict with params for this View
   331       kwargs: the Key Fields for the specified entity
   312       request_entity: Request that is being accepted
       
   313       kwargs: contains the ID for the Request entity
   332     """
   314     """
   333 
   315 
   334     # create the form using the scope_path and link_id from kwargs 
   316     # create the form using the scope_path and link_id from kwargs 
   335     # as initial value
   317     # as initial value
   336     fields = {'link_id': kwargs['link_id'],
   318     fields = {'link_id': request_entity.user.link_id,
   337               'scope_path': kwargs['scope_path']}
   319               'scope_path': request_entity.group.key().id_or_name()}
   338     form = params['invited_create_form'](initial=fields)
   320     form = params['invited_create_form'](initial=fields)
   339 
   321 
   340     # construct the appropriate response
   322     # construct the appropriate response
   341     return super(View, self)._constructResponse(request, entity=None,
   323     return super(View, self)._constructResponse(request, entity=None,
   342         context=context, form=form, params=params)
   324         context=context, form=form, params=params)
   343 
   325 
   344   def acceptInvitePost(self, request, context, params, **kwargs):
   326   def acceptInvitePost(self, request, context, params, request_entity, **kwargs):
   345     """Handles the POST request concerning the creation of a Role via an
   327     """Handles the POST request concerning the creation of a Role via an
   346     invite.
   328     invite.
   347 
   329 
   348     Args:
   330     Args:
   349       request: the standard Django HTTP request object
   331       request: the standard Django HTTP request object
   350       context: dictionary containing the context for this view
   332       context: dictionary containing the context for this view
   351       params: a dict with params for this View
   333       params: a dict with params for this View
   352       kwargs: the Key Fields for the specified entity
   334       request_entity: Request that is being accepted
       
   335       kwargs: contains the ID for the Request entity
   353     """
   336     """
   354 
   337 
   355     # populate the form using the POST data
   338     # populate the form using the POST data
   356     form = params['invited_create_form'](request.POST)
   339     form = params['invited_create_form'](request.POST)
   357 
   340 
   361           form=form, params=params)
   344           form=form, params=params)
   362 
   345 
   363     # collect the cleaned data from the valid form
   346     # collect the cleaned data from the valid form
   364     key_name, fields = soc.views.helper.forms.collectCleanedFields(form)
   347     key_name, fields = soc.views.helper.forms.collectCleanedFields(form)
   365 
   348 
   366     # call the post process method
   349     # set the user and link_id fields to the right property
   367     self._acceptInvitePost(fields, request, context, params, **kwargs)
   350     fields['user'] = request_entity.user
   368 
   351     fields['link_id'] = request_entity.user.link_id
   369     group_logic = params['group_logic']
   352     fields['scope'] = request_entity.group
   370     group_entity = group_logic.getFromKeyName(fields['scope_path'])
   353     fields['scope_path'] = request_entity.group.key().id_or_name()
   371     fields['scope'] = group_entity
       
   372 
       
   373     # make sure that this role becomes active once more in case this user
   354     # make sure that this role becomes active once more in case this user
   374     # has been reinvited
   355     # has been reinvited
   375     fields ['status'] = 'active'
   356     fields ['status'] = 'active'
   376 
   357 
       
   358     # call the post process method
       
   359     self._acceptInvitePost(fields, request, context, params, **kwargs)
       
   360 
   377     # get the key_name for the new entity
   361     # get the key_name for the new entity
   378     key_name = self._logic.getKeyNameFromFields(fields)
   362     key_name = self._logic.getKeyNameFromFields(fields)
   379 
   363 
   380     # create new Role entity
   364     # create new Role entity
   381     entity = self._logic.updateOrCreateFromKeyName(fields, key_name)
   365     entity = self._logic.updateOrCreateFromKeyName(fields, key_name)
   382 
   366 
   383     # mark the request as completed
   367     # mark the request as completed
   384     request_helper.completeRequestForRole(entity, params['logic'].role_name)
   368     request_fields = {'status': 'completed'}
       
   369     request_logic.updateEntityProperties(request_entity, request_fields)
   385 
   370 
   386     # redirect to the roles overview page
   371     # redirect to the roles overview page
   387     return http.HttpResponseRedirect('/user/roles')
   372     return http.HttpResponseRedirect('/user/roles')
   388 
   373 
   389   def _acceptInvitePost(self, fields, request, context, params, **kwargs):
   374   def _acceptInvitePost(self, fields, request, context, params, **kwargs):
   474 
   459 
   475     # get the context for this webpage
   460     # get the context for this webpage
   476     context = responses.getUniversalContext(request)
   461     context = responses.getUniversalContext(request)
   477     responses.useJavaScript(context, params['js_uses_all'])
   462     responses.useJavaScript(context, params['js_uses_all'])
   478     context['page_name'] = page_name
   463     context['page_name'] = page_name
       
   464 
       
   465     group_entity = params['group_logic'].getFromKeyName(kwargs['scope_path'])
       
   466 
   479     context['instruction_message'] = (self.DEF_REQUEST_INSTRUCTION_MSG_FMT %
   467     context['instruction_message'] = (self.DEF_REQUEST_INSTRUCTION_MSG_FMT %
   480         params)
   468         (params['name'], group_entity.name))
   481 
   469 
   482     if request.method == 'POST':
   470     if request.method == 'POST':
   483       return self.requestPost(request, context, params, **kwargs)
   471       return self.requestPost(request, context, params, group_entity, **kwargs)
   484     else:
   472     else:
   485       # request.method == 'GET'
   473       # request.method == 'GET'
   486       return self.requestGet(request, context, params, **kwargs)
   474       return self.requestGet(request, context, params, **kwargs)
   487 
   475 
   488   def requestGet(self, request, context, params, **kwargs):
   476   def requestGet(self, request, context, params, **kwargs):
   494       context: dictionary containing the context for this view
   482       context: dictionary containing the context for this view
   495       params: a dict with params for this View
   483       params: a dict with params for this View
   496       kwargs: the Key Fields for the specified entity
   484       kwargs: the Key Fields for the specified entity
   497     """
   485     """
   498 
   486 
   499     # set right fields for the request form
       
   500     user_entity = user_logic.logic.getForCurrentAccount()
       
   501     # pylint: disable-msg=E1103
       
   502     fields = {'link_id' : user_entity.link_id,
       
   503               'role' : params['logic'].role_name,
       
   504               'group_id' : kwargs['scope_path']}
       
   505 
       
   506     # get the request view parameters and initialize the create form
   487     # get the request view parameters and initialize the create form
   507     request_params = request_view.view.getParams()
   488     request_params = request_view.view.getParams()
   508     form = request_params['request_form'](initial=fields)
   489     form = request_params['request_form']()
   509 
   490 
   510     # construct the appropriate response
   491     # construct the appropriate response
   511     return super(View, self)._constructResponse(request, entity=None,
   492     return super(View, self)._constructResponse(request, entity=None,
   512         context=context, form=form, params=request_params)
   493         context=context, form=form, params=request_params)
   513 
   494 
   514   def requestPost(self, request, context, params, **kwargs):
   495   def requestPost(self, request, context, params, group_entity, **kwargs):
   515     """Handles the POST request concerning the creation of a request
   496     """Handles the POST request concerning the creation of a request
   516     to attain a role.
   497     to attain a role.
   517 
   498 
   518     Args:
   499     Args:
   519       request: the standard Django HTTP request object
   500       request: the standard Django HTTP request object
   520       context: dictionary containing the context for this view
   501       context: dictionary containing the context for this view
   521       params: a dict with params for this View
   502       params: a dict with params for this View
       
   503       group_entity: the Group entity this request is for
   522       kwargs: the Key Fields for the specified entity
   504       kwargs: the Key Fields for the specified entity
   523     """
   505     """
   524 
   506 
   525     # get the request view parameters and populate the form using POST data
   507     # get the request view parameters and populate the form using POST data
   526     request_params = request_view.view.getParams()
   508     request_params = request_view.view.getParams()
   527     form = request_params['invite_form'](request.POST)
   509     form = request_params['request_form'](request.POST)
   528 
   510 
   529     if not form.is_valid():
   511     if not form.is_valid():
   530       # return the invalid form response
   512       # return the invalid form response
   531       return self._constructResponse(request, entity=None, context=context,
   513       return self._constructResponse(request, entity=None, context=context,
   532           form=form, params=request_params)
   514           form=form, params=request_params)
   533 
   515 
   534     # get the group entity for which this request is via the scope_path
   516     _, fields = soc.views.helper.forms.collectCleanedFields(form)
   535     group = self._logic.getGroupEntityFromScopePath(params['group_logic'],
   517 
   536          kwargs['scope_path'])
   518     # set the fields for the new request
   537 
       
   538     # get the request scope path
       
   539     request_scope_path = self._getRequestScopePathFromGroup(group)
       
   540 
       
   541     # defensively set the fields we need for this request and set status to new
       
   542     user_entity = user_logic.logic.getForCurrentAccount()
   519     user_entity = user_logic.logic.getForCurrentAccount()
   543     # pylint: disable-msg=E1103
   520 
   544     request_fields = {'link_id' : user_entity.link_id,
   521     request_fields = {
   545         'scope' : group,
   522         'user': user_entity,
   546         'scope_path' : request_scope_path,
   523         'group' : group_entity,
       
   524         'message': fields['message'],
   547         'role' : params['logic'].role_name,
   525         'role' : params['logic'].role_name,
   548         'role_verbose' : params['name'],
       
   549         'status' : 'new'}
   526         'status' : 'new'}
   550 
   527 
   551     if not self._isValidNewRequest(request_fields, params):
   528     if not request_logic.isValidNewRequest(request_fields, params['logic']):
   552       # not a valid request
   529       # not a valid request
   553       context['error_message'] = self.DEF_REQUEST_ERROR_MSG_FMT % (
   530       context['error_message'] = self.DEF_REQUEST_ERROR_MSG_FMT % (
   554           params)
   531           params)
   555       return self.requestGet(request, context, params, **kwargs)
   532       return super(View, self)._constructResponse(request, entity=None,
   556 
   533           context=context, form=form, params=request_params)
   557     # extract the key_name for the new request entity
       
   558     key_name = request_logic.logic.getKeyNameFromFields(request_fields)
       
   559 
   534 
   560     # create the request entity
   535     # create the request entity
   561     request_logic.logic.updateOrCreateFromKeyName(request_fields, key_name)
   536     request_logic.updateOrCreateFromFields(request_fields)
   562 
   537 
   563     # redirect to requests overview
   538     # redirect to requests overview
   564     return http.HttpResponseRedirect('/user/requests')
   539     return http.HttpResponseRedirect('/user/requests')
   565 
   540 
   566   @decorators.merge_params
   541   @decorators.merge_params
   575       page_name: the page name displayed in templates as page and header title
   550       page_name: the page name displayed in templates as page and header title
   576       params: a dict with params for this View
   551       params: a dict with params for this View
   577       kwargs: the Key Fields for the specified entity
   552       kwargs: the Key Fields for the specified entity
   578     """
   553     """
   579 
   554 
   580 
       
   581     # get the request entity using the information from kwargs
   555     # get the request entity using the information from kwargs
   582     fields = {'link_id': kwargs['link_id'],
   556     request_entity = request_logic.getFromIDOr404(int(kwargs['id']))
   583         'scope_path': kwargs['scope_path'],
       
   584         'role': params['logic'].role_name}
       
   585     request_entity = request_logic.logic.getForFields(fields, unique=True)
       
   586 
   557 
   587     # get the context for this webpage
   558     # get the context for this webpage
   588     context = responses.getUniversalContext(request)
   559     context = responses.getUniversalContext(request)
   589     responses.useJavaScript(context, params['js_uses_all'])
   560     responses.useJavaScript(context, params['js_uses_all'])
   590 
   561 
   591     # pylint: disable-msg=E1103
       
   592     user_entity = user_logic.logic.getFromKeyNameOr404(request_entity.link_id)
       
   593 
       
   594     context['page_name'] = '%s from %s to become a %s' %(
   562     context['page_name'] = '%s from %s to become a %s' %(
   595         page_name, user_entity.name, request_entity.role_verbose)
   563         page_name, request_entity.user.name, params['name'])
   596 
   564 
   597     get_dict = request.GET
   565     get_dict = request.GET
   598 
   566 
   599     if 'status' in get_dict.keys():
   567     if 'status' in get_dict.keys():
   600       if get_dict['status'] in ['group_accepted', 'rejected', 'ignored']:
   568       if get_dict['status'] in ['group_accepted', 'rejected', 'ignored']:
   601         # update the request_entity and redirect away from this page
   569         # update the request_entity and redirect away from this page
   602         request_status = get_dict['status']
   570         request_status = get_dict['status']
   603 
   571 
   604         # only update when the status is changing
   572         # only update when the status is changing
   605         if request_status != request_entity.status:
   573         if request_status != request_entity.status:
   606           request_logic.logic.updateEntityProperties(request_entity, {
   574           request_logic.updateEntityProperties(request_entity, {
   607               'status': get_dict['status']})
   575               'status': get_dict['status']})
   608 
   576 
   609         group_view = params.get('group_view')
   577         group_view = params.get('group_view')
   610         if not group_view:
   578         if not group_view:
   611           return http.HttpResponseRedirect('/')
   579           return http.HttpResponseRedirect('/')
   612         else:
   580         else:
   613           # redirect to the requests list
   581           # redirect to the requests list
   614           return http.HttpResponseRedirect(
   582           return http.HttpResponseRedirect(
   615               redirects.getListRequestsRedirect(request_entity.scope, 
   583               redirects.getListRequestsRedirect(request_entity.group,
   616                   group_view.getParams()))
   584                   group_view.getParams()))
   617 
   585 
   618     # put the entity in the context
   586     # put the entity in the context
   619     context['entity'] = request_entity
   587     context['entity'] = request_entity
   620     context['user_in_request'] = user_entity
       
   621     context['request_status'] = request_entity.status 
   588     context['request_status'] = request_entity.status 
   622     context['role_name'] = params['logic'].role_name
   589     context['role_verbose'] = params['name']
       
   590     context['url_name'] = params['url_name']
   623 
   591 
   624     #display the request processing page using the appropriate template
   592     #display the request processing page using the appropriate template
   625     template = request_view.view.getParams()['request_processing_template']
   593     template = request_view.view.getParams()['request_processing_template']
   626 
   594 
   627     return responses.respond(request, template, context=context)
   595     return responses.respond(request, template, context=context)
   628 
       
   629   def _isValidNewRequest(self, request_fields, params):
       
   630     """Checks if this is a valid Request object to make.
       
   631 
       
   632     Args:
       
   633     request_fields: dict containing the fields for the new request entity.
       
   634     params: parameters for the current view
       
   635     """
       
   636     fields = request_fields.copy()
       
   637     fields['status'] = ['new', 'group_accepted', 'ignored']
       
   638 
       
   639     request_entity = request_logic.logic.getForFields(fields, unique=True)
       
   640     
       
   641     if request_entity:
       
   642       # already outstanding request
       
   643       return False
       
   644 
       
   645     # check if the role already exists
       
   646     fields = {'scope': request_fields['scope'],
       
   647         'link_id': request_fields['link_id'],
       
   648         'status': ['active','inactive'],
       
   649         }
       
   650 
       
   651     role_entity = params['logic'].getForFields(fields, unique=True)
       
   652 
       
   653     if role_entity:
       
   654       # already has this role
       
   655       return False
       
   656 
       
   657     # no oustanding request or a valid role
       
   658     return True