def _constructFilterForProjectSelection(self, survey, params): """Returns the filter needed for the Project selection view. Constructs a filter that returns all valid projects for which the current user is the mentor. Only for the projects in the program given by the survey's scope of course. For args see project_survey.View._constructFilterForProjectSelection(). """ from soc.modules.gsoc.logic.models.mentor import logic as mentor_logic survey_logic = params['logic'] user_entity = user_logic.getForCurrentAccount() # get the mentor entities for the current user and program fields = {'user': user_entity, 'program': survey_logic.getScope(survey), 'status': 'active'} mentor_entities = mentor_logic.getForFields(fields) # TODO: Ensure that this doesn't break when someone is a mentor for # a lot of organizations. fields = {'mentor': mentor_entities, 'status': 'accepted'} return fields
def _constructFilterForProjectSelection(self, survey, params): """Returns the filter needed for the Project selection view. Constructs a filter that returns all valid projects for which the current user is the mentor. Only for the projects in the program given by the survey's scope of course. For args see project_survey.View._constructFilterForProjectSelection(). """ from soc.logic.models.mentor import logic as mentor_logic survey_logic = params['logic'] user_entity = user_logic.getForCurrentAccount() # get the mentor entities for the current user and program fields = {'user': user_entity, 'program': survey_logic.getScope(survey), 'status': 'active'} mentor_entities = mentor_logic.getForFields(fields) # TODO: Ensure that this doesn't break when someone is a mentor for # a lot of organizations. fields = {'mentor': mentor_entities, 'status': 'accepted'} return fields
def getRolesListData(self, request): """Returns the list data for roles. """ user = user_logic.getForCurrentAccount() # only select the roles for the current user # pylint: disable-msg=E1103 fields = {'link_id': user.link_id, 'status': ['active', 'inactive']} keys = role_view.ROLE_VIEWS.keys() keys.sort() idx = request.GET.get('idx', '') idx = int(idx) if idx.isdigit() else -1 if not 0 <= idx < len(keys): return responses.jsonErrorResponse(request, "idx not valid") idx = int(idx) key = keys[idx] list_params = role_view.ROLE_VIEWS[key].getParams() contents = helper.lists.getListData(request, list_params, fields) json = simplejson.dumps(contents) return responses.jsonResponse(request, json)
def checkIsNotStudentForProgramInScope(self, django_args): """Checks if the current user is not a student for the given program in django_args. Args: django_args: a dictionary with django's arguments Raises: AccessViolationResponse: if the current user has a student role for the given program. """ if django_args.get('seed'): key_name = django_args['seed']['scope_path'] else: key_name = django_args['scope_path'] program_entity = program_logic.getFromKeyNameOr404(key_name) user_entity = user_logic.getForCurrentAccount() filter = {'user': user_entity, 'scope': program_entity, 'status': 'active'} # check if the current user is already a student for this program student_role = student_logic.getForFields(filter, unique=True) if student_role: raise out_of_band.AccessViolation( message_fmt=DEF_ALREADY_STUDENT_ROLE_MSG) return
def editProfile(self, request, access_type, page_name=None, params=None, **kwargs): """Displays User profile edit page for the current user. Args: request: the standard Django HTTP request object page_name: the page name displayed in templates as page and header title params: a dict with params for this View kwargs: The Key Fields for the specified entity """ # set the link_id to the current user's link_id user_entity = user_logic.getForCurrentAccount() # pylint: disable-msg=E1103 link_id = user_entity.link_id return self.edit(request, access_type, page_name=page_name, params=params, link_id=link_id, **kwargs)
def _constructFilterForProjectSelection(self, survey, params): """Returns the filter needed for the Project selection view. Returns a filter for all the valid projects for which the current user is a student. Of course only in the survey's scope. Args: survey: a Survey entity params: the params dict for the requesting view Returns: Dictionary that can be used as a input for a query. """ from soc.logic.models.student import logic as student_logic survey_logic = params["logic"] user_entity = user_logic.getForCurrentAccount() # get the student entity for the current user and program fields = {"user": user_entity, "scope": survey_logic.getScope(survey), "status": "active"} student_entity = student_logic.getForFields(fields, unique=True) # TODO(ljvderijk) transform StudentProject to handle multiple surveys fields = {"student": student_entity, "status": "accepted"} return fields
def _constructFilterForProjectSelection(self, survey, params): """Returns the filter needed for the Project selection view. Returns a filter for all the valid projects for which the current user is a student. Of course only in the survey's scope. Args: survey: a Survey entity params: the params dict for the requesting view Returns: Dictionary that can be used as a input for a query. """ from soc.modules.gsoc.logic.models.student import logic as \ student_logic survey_logic = params['logic'] user_entity = user_logic.getForCurrentAccount() # get the student entity for the current user and program fields = { 'user': user_entity, 'scope': survey_logic.getScope(survey), 'status': 'active' } student_entity = student_logic.getForFields(fields, unique=True) fields = {'student': student_entity, 'status': 'accepted'} return fields
def editGet(self, request, entity, context, params=None): """Process GET requests for the specified entity. Builds the SurveyForm that represents the Survey question contents. """ self._entity = entity survey_content = entity.survey_content user = user_logic.getForCurrentAccount() # no project or survey_record needed for survey prototype project = None survey_record = None survey_form = surveys.SurveyForm(survey_content=survey_content, this_user=user, project=project, survey_logic=params['logic'], survey_record=survey_record, editing=True, read_only=False) survey_form.getFields() local = dict(survey_form=survey_form, question_types=QUESTION_TYPES, survey_h=entity.survey_content) context.update(local) params['edit_form'] = surveys.HelperForm(params['edit_form']) if entity.survey_end and datetime.datetime.now() > entity.survey_end: # are we already passed the survey_end? context["passed_survey_end"] = True return super(View, self).editGet(request, entity, context, params=params)
def checkIsNotStudentForProgramOfOrg(self, django_args): """Checks if the current user has no active Student role for the program that the organization in the scope_path is participating in. Args: django_args: a dictionary with django's arguments Raises: AccessViolationResponse: if the current user is a student for the program the organization is in. """ if not django_args.get('scope_path'): raise out_of_band.AccessViolation(message_fmt=DEF_PAGE_DENIED_MSG) org_entity = org_logic.getFromKeyNameOr404(django_args['scope_path']) user_entity = user_logic.getForCurrentAccount() filter = {'scope': org_entity.scope, 'user': user_entity, 'status': 'active'} student_role = student_logic.getForFields(filter=filter, unique=True) if student_role: raise out_of_band.AccessViolation( message_fmt=DEF_ALREADY_STUDENT_ROLE_MSG) return
def scheduleAddToFeedTask(sender, receivers, update_type, **kwargs): """ Create new feed items for an event, using the Task API Params: sender - the entity sending the event receivers - a list of receivers receiving items in their feed for this event update_type - create, update, delete, etc. """ #create unique feed_item_key for this item, in case task repeats feed_item_key = sender.key().id_or_name() + str(time.time()) # optional payload message for this item payload = kwargs.get('payload', None) task_params = { 'feed_item_key' : feed_item_key, 'payload': payload, 'receivers': [receiver.key() for receiver in receivers], 'sender_key': sender.key(), 'update_type': update_type } user = user_logic.getForCurrentAccount() if user: task_params['user_key'] = user.key().name() task = taskqueue.Task(params=task_params, url="/" + TASK_FEED_URL) task.add()
def sendInviteNotification(entity): """Sends out an invite notification to the user the request is for. Args: entity : A request containing the information needed to create the message """ from soc.logic.models.user import logic as user_logic # get the user the request is for properties = {'link_id': entity.link_id } to_user = user_logic.getForFields(properties, unique=True) invitation_url = "http://%(host)s%(index)s" % { 'host' : os.environ['HTTP_HOST'], 'index': redirects.getInviteProcessRedirect(entity, None), } message_properties = { 'role_verbose' : entity.role_verbose, 'group': entity.scope.name, 'invitation_url': invitation_url, } subject = DEF_INVITATION_MSG_FMT % { 'role_verbose' : entity.role_verbose, 'group' : entity.scope.name } template = DEF_GROUP_INVITE_NOTIFICATION_TEMPLATE from_user = user_logic.getForCurrentAccount() sendNotification(to_user, from_user, message_properties, subject, template)
def viewResults(self, request, access_type, page_name=None, params=None, **kwargs): """View for SurveyRecord and SurveyRecordGroup. """ results_logic = params['logic'].getRecordLogic() user = user_logic.getForCurrentAccount() # TODO(ajaksu): use the named parameter link_id from the re if request.path == '/survey/show/user/' + user.link_id: records = tuple(user.surveys_taken.run()) context = responses.getUniversalContext(request) context['content'] = records[0].survey.survey_content responses.useJavaScript(context, params['js_uses_all']) context['page_name'] = u'Your survey records.' else: entity, context = self.getContextEntity(request, page_name, params, kwargs) if context is None: # user cannot see this page, return error response return entity context['content'] = entity.survey_content can_write = False rights = self._params['rights'] try: rights.checkIsSurveyWritable({'key_name': entity.key().name(), 'prefix': entity.prefix, 'scope_path': entity.scope_path, 'link_id': entity.link_id,}, 'key_name') can_write = True except out_of_band.AccessViolation: pass filter = self._params.get('filter') or {} # if user can edit the survey, show everyone's results if can_write: filter['survey'] = entity else: filter.update({'user': user, 'survey': entity}) limit = self._params.get('limit') or 1000 offset = self._params.get('offset') or 0 order = self._params.get('order') or [] idx = self._params.get('idx') or 0 records = results_logic.getForFields(filter=filter, limit=limit, offset=offset, order=order) updates = dicts.rename(params, params['list_params']) context.update(updates) context['results'] = records, records template = 'soc/survey/results_page.html' return responses.respond(request, template, context=context)
def _getResultsViewRecordFields(self, survey, allowed_to_read): """Get the Results View filter for ProjectSurveyRecords. For args see survey.View()._getResultsViewRecordFields() Returns: Returns the dictionary containing the fields to filter on """ from soc.modules.gsoc.logic.models.org_admin import logic as \ org_admin_logic from soc.modules.gsoc.logic.models.student import logic as \ student_logic if allowed_to_read: return super(View, self)._getResultsViewRecordFields( survey, allowed_to_read) fields = {'survey': survey} program_entity = survey.scope user_entity = user_logic.getForCurrentAccount() student_fields = { 'scope': program_entity, 'user': user_entity, 'status': ['active', 'inactive'] } student_entity = student_logic.getForFields(student_fields, unique=True) if student_entity: # just get all records for the current user fields['user'] = user_entity return fields org_admin_fields = { 'user': user_entity, 'program': program_entity, 'status': ['active', 'inactive'] } org_admins = org_admin_logic.getForFields(org_admin_fields) if org_admins: # filter on all the organizations this user is org admin for organizations = [] for org_admin in org_admins: organizations.append(org_admin.scope) # TODO: this might blow up if the user is org admin for too many orgs fields['org'] = organizations if not student_entity and not org_admins: # return only the surveys for the current user fields['user'] = user_entity return fields
def _getResultsViewRecordFields(self, survey, allowed_to_read): """Get the Results View filter for ProjectSurveyRecords. For args see survey.View()._getResultsViewRecordFields() Returns: Returns the dictionary containing the fields to filter on """ from soc.modules.gsoc.logic.models.mentor import logic as mentor_logic from soc.modules.gsoc.logic.models.org_admin import logic as \ org_admin_logic if allowed_to_read: return super(View, self)._getResultsViewRecordFields(survey, allowed_to_read) fields = {'survey': survey} user_entity = user_logic.getForCurrentAccount() program_entity = survey.scope role_fields = {'user': user_entity, 'program': program_entity, 'status': ['active', 'inactive']} org_admins = org_admin_logic.getForFields(role_fields) mentors = mentor_logic.getForFields(role_fields) organizations = {} if org_admins: for org_admin in org_admins: # for each org admin store the organization org_scope = org_admin.scope org_key_name = org_scope.key().id_or_name() organizations[org_key_name] = org_scope if mentors: for mentor in mentors: # for each mentor store the organization # This will allow the user to view the GradingProjectSurvey Records # listing for projects which he might have no further access to. org_scope = mentor.scope org_key_name = org_scope.key().id_or_name() organizations[org_key_name] = org_scope if organizations: # filter on all the found organizations fields['org'] = organizations.values() else: # This user is no org admin or mentor and should only see # his/her own records. fields['user'] = user_entity return fields
def _editPost(self, request, entity, fields): """See base.View._editPost(). """ # get the current user current_user = user_logic.getForCurrentAccount() fields['link_id'] = 't%i' % (int(time.time()*100)) fields['scope'] = fields['to_user'] fields['from_user'] = current_user fields['scope_path'] = fields['to_user'].link_id
def _editPost(self, request, entity, fields): """See base.View._editPost(). """ # get the current user current_user = user_logic.getForCurrentAccount() fields['link_id'] = 't%i' % (int(time.time() * 100)) fields['scope'] = fields['to_user'] fields['from_user'] = current_user fields['scope_path'] = fields['to_user'].link_id
def checkIsNotParticipatingInProgramInScope(self, django_args): """Checks if the current user has no roles for the given program in django_args. Args: django_args: a dictionary with django's arguments Raises: AccessViolationResponse: if the current user has a student, mentor or org admin role for the given program. """ if not django_args.get('scope_path'): raise out_of_band.AccessViolation(message_fmt=DEF_PAGE_DENIED_MSG) program_entity = program_logic.getFromKeyNameOr404( django_args['scope_path']) user_entity = user_logic.getForCurrentAccount() filter = {'user': user_entity, 'scope': program_entity, 'status': 'active'} # check if the current user is already a student for this program student_role = student_logic.getForFields(filter, unique=True) if student_role: raise out_of_band.AccessViolation( message_fmt=DEF_ALREADY_PARTICIPATING_MSG) # fill the role_list with all the mentor and org admin roles for this user # role_list = [] filter = {'user': user_entity, 'program': program_entity, 'status': 'active'} mentor_role = mentor_logic.getForFields(filter, unique=True) if mentor_role: # the current user has a role for the given program raise out_of_band.AccessViolation( message_fmt=DEF_ALREADY_PARTICIPATING_MSG) org_admin_role = org_admin_logic.getForFields(filter, unique=True) if org_admin_role: # the current user has a role for the given program raise out_of_band.AccessViolation( message_fmt=DEF_ALREADY_PARTICIPATING_MSG) # no roles found, access granted return
def _editPost(self, request, entity, fields): """See base.View._editPost(). """ user = user_logic.getForCurrentAccount() if not entity: fields['author'] = user else: fields['author'] = entity.author fields['modified_by'] = user super(View, self)._editPost(request, entity, fields)
def listSelf(self, request, access_type, page_name=None, params=None, **kwargs): """List all applications from the current logged-in user. For params see base.View.public(). """ user_entity = user_logic.getForCurrentAccount() filter = {'applicant' : user_entity} if kwargs['scope_path']: filter['scope_path'] = kwargs['scope_path'] return self.list(request, access_type, page_name=page_name, params=params, filter=filter, visibility="self", **kwargs)
def _editPost(self, request, entity, fields): """See base.View._editPost(). """ if not entity: # set the applicant field to the current user fields['applicant'] = user_logic.getForCurrentAccount() #set the backup_admin field with the cleaned link_id fields['backup_admin'] = fields['backup_admin_link_id'] # the application has either been created or edited so # the status needs to be set accordingly fields['status'] = 'needs review' super(View, self)._editPost(request, entity, fields)
def list(self, request, access_type, page_name=None, params=None, filter=None, order=None, **kwargs): """Lists all notifications that the current logged in user has stored. for parameters see base.list() """ # get the current user user_entity = user_logic.getForCurrentAccount() # only select the notifications for this user so construct a filter filter = { 'scope': user_entity, 'unread': True, } # create the list parameters un_params = params.copy() # unread notifications # define the list redirect action to show the notification un_params['list_action'] = (redirects.getPublicRedirect, params) un_params['list_description'] = ugettext( "An overview of your unread Notifications.") # TODO(Lennard) when list sorting is implemented sort on descending date un_list = list_helper.getListContent( request, un_params, filter, idx=0) # Now get the read list # Reuse the filter, but only for read notifications filter['unread'] = False rn_params = params.copy() # read notifications rn_params['list_action'] = (redirects.getPublicRedirect, params) rn_params['list_description'] = ugettext( "An overview of your read Notifications.") rn_list = list_helper.getListContent( request, rn_params, filter, idx=1) # fill contents with all the needed lists contents = [un_list, rn_list] # call the _list method from base to display the list return self._list(request, params, contents, page_name)
def _editPost(self, request, entity, fields): """See base.View._editPost(). Processes POST request items to add new dynamic field names, question types, and default prompt values to SurveyContent model. """ user = user_logic.getForCurrentAccount() schema = {} survey_fields = {} if not entity: # new Survey if 'serialized' in request.POST: fields, schema, survey_fields = self.importSerialized( request, fields, user) fields['author'] = user else: fields['author'] = entity.author schema = self.loadSurveyContent(schema, survey_fields, entity) # remove deleted properties from the model self.deleteQuestions(schema, survey_fields, request.POST) # add new text questions and re-build choice questions self.getRequestQuestions(schema, survey_fields, request.POST) # get schema options for choice questions self.getSchemaOptions(schema, survey_fields, request.POST) survey_content = getattr(entity, 'survey_content', None) # create or update a SurveyContent for this Survey survey_content = survey_logic.createSurvey( survey_fields, schema, survey_content=survey_content) # save survey_content for existent survey or pass for creating a new one if entity: entity.modified_by = user entity.survey_content = survey_content db.put(entity) else: fields['survey_content'] = survey_content fields['modified_by'] = user super(View, self)._editPost(request, entity, fields)
def _editPost(self, request, entity, fields): """See base.View._editPost(). Processes POST request items to add new dynamic field names, question types, and default prompt values to SurveyContent model. """ user = user_logic.getForCurrentAccount() schema = {} survey_fields = {} if not entity: # new Survey if 'serialized' in request.POST: fields, schema, survey_fields = self.importSerialized(request, fields, user) fields['author'] = user else: fields['author'] = entity.author schema = self.loadSurveyContent(schema, survey_fields, entity) # remove deleted properties from the model self.deleteQuestions(schema, survey_fields, request.POST) # add new text questions and re-build choice questions self.getRequestQuestions(schema, survey_fields, request.POST) # get schema options for choice questions self.getSchemaOptions(schema, survey_fields, request.POST) survey_content = getattr(entity,'survey_content', None) # create or update a SurveyContent for this Survey survey_content = survey_logic.createSurvey(survey_fields, schema, survey_content=survey_content) # save survey_content for existent survey or pass for creating a new one if entity: entity.modified_by = user entity.survey_content = survey_content db.put(entity) else: fields['survey_content'] = survey_content fields['modified_by'] = user super(View, self)._editPost(request, entity, fields)
def getFeed(self): """gets HTML version of Newsfeed for entity """ feed_items = self.retrieveFeed() feed_url = self.getFeedUrl() account = user_logic.getForCurrentAccount() is_subscribed = subscription_logic.isSubscribed( account, self.entity) context = { 'account': account, 'subscribed': is_subscribed, 'entity_key': self.entity.key(), 'feed_items': feed_items, 'feed_url': feed_url } return loader.render_to_string('soc/news_feed/news_feed.html', dictionary=context)
def render(self, this_survey): #check if user has already submitted form. If so, show existing form import soc.models.user from soc.logic.models.user import logic as user_logic user = user_logic.getForCurrentAccount() survey_record = SurveyRecord.gql("WHERE user = :1 AND this_survey = :2", user, this_survey.survey_parent.get()).get() survey = SurveyForm(this_survey=this_survey, survey_record=survey_record) if survey_record: help_text = "Edit and re-submit this survey." status = "edit" else: help_text = "Please complete this survey." status = "create" result = self.WIDGET_HTML % {'survey': str(survey), 'help_text': help_text, 'status': status } return result
def editProfile(self, request, access_type, page_name=None, params=None, **kwargs): """Displays User profile edit page for the current user. Args: request: the standard Django HTTP request object page_name: the page name displayed in templates as page and header title params: a dict with params for this View kwargs: The Key Fields for the specified entity """ # set the link_id to the current user's link_id user_entity = user_logic.getForCurrentAccount() link_id = user_entity.link_id return self.edit(request, access_type, page_name=page_name, params=params, link_id=link_id, **kwargs)
def _editPost(self, request, entity, fields): """See base.View._editPost(). """ user = user_logic.getForCurrentAccount() scope_path = fields['scope_path'] if not entity: fields['author'] = user fields['link_id'] = 't%i' % (int(time.time()*100)) else: fields['author'] = entity.author fields['link_id'] = entity.link_id fields['modified_by'] = user fields['commented'] = self._getWorkByKeyName(scope_path).key() super(View, self)._editPost(request, entity, fields)
def roles(self, request, access_type, page_name=None, params=None, **kwargs): """Displays the valid roles for this user. 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 """ user = user_logic.getForCurrentAccount() # only select the roles for the current user # pylint: disable-msg=E1103 filter = { 'link_id': user.link_id, 'status': ['active', 'inactive'] } contents = [] i = 0 for _, loop_view in sorted(role_view.ROLE_VIEWS.iteritems()): list_params = loop_view.getParams().copy() list_params['list_action'] = (redirects.getEditRedirect, list_params) list_params['list_description'] = self.DEF_ROLE_LIST_MSG_FMT % list_params list = helper.lists.getListContent(request, list_params, filter, idx=i, need_content=True) if list: contents.append(list) i += 1 site = site_logic.getSingleton() site_name = site.site_name params = params.copy() params['no_lists_msg'] = self.DEF_NO_ROLES_MSG_FMT % site_name return self._list(request, params, contents, page_name)
def takePost(self, request, template, context, params, survey_form, entity, record, **kwargs): """Handles the POST request for the Survey's take page. Args: template: the template used for this view survey_form: instance of SurveyTakeForm entity: the Survey entity record: a SurveyRecord entity rest: see base.View.public() """ survey_logic = params['logic'] record_logic = survey_logic.getRecordLogic() if not survey_form.is_valid(): # show the form errors return self._constructResponse(request, entity=entity, context=context, form=survey_form, params=params, template=template) # retrieve the data from the form _, properties = forms_helper.collectCleanedFields(survey_form) # add the required SurveyRecord properties properties['user'] = user_logic.getForCurrentAccount() properties['survey'] = entity # call the hook method before updating the SurveyRecord self._takePost(request, params, entity, record, properties) # update the record entity if any and clear all dynamic properties record = record_logic.updateOrCreateFromFields(record, properties, clear_dynamic=True) # TODO: add notice to page that the response has been saved successfully # get the path to redirect the user to redirect = self._getRedirectOnSuccessfulTake(request, params, entity, record) return http.HttpResponseRedirect(redirect)
def _takePost(self, request, params, entity, record, properties): """Hook into the view for the take's page POST request. For params see survey.View._takePost(). """ from soc.logic.models.user import logic as user_logic if not record: # creating a new record user_entity = user_logic.getForCurrentAccount() properties['main_admin'] = user_entity if properties['agreed_to_tos']: properties['agreed_to_admin_agreement'] = True # remove fields we don't need to store in the SurveyRecord properties.pop('tos') properties.pop('agreed_to_tos')
def _getResultsViewRecordFields(self, survey, allowed_to_read): """Retrieves the Results View filter for SurveyRecords. Args: survey: Survey instance for which the Records need to be shown allowed_to_read: specifies if the current User has read access Returns: Returns the dictionary containing the fields to filter on """ # only show records for the retrieved survey fields = {'survey': survey} if not allowed_to_read: # this user is not allowed to view all the Records so only show their own fields['user'] = user_logic.getForCurrentAccount() return fields
def _getSurveyRecordFor(self, survey, request, params): """Returns the SurveyRecord for the given Survey and request. Args: survey: a Survey entity request: a Django HTTPRequest object params: params for the requesting view Returns: An existing SurveyRecord iff any exists for the given Survey, request and any other conditions that must apply. """ survey_logic = params['logic'] record_logic = survey_logic.getRecordLogic() user_entity = user_logic.getForCurrentAccount() filter = {'survey': survey, 'user': user_entity} return record_logic.getForFields(filter, unique=True)
def _public(self, request, entity, context): """Marks the Notification as read if that hasn't happened yet. for parameters see base._public() """ # if the user viewing is the user for which this notification is meant # and the notification has not been read yet if entity.unread: # get the current user user = user_logic.getForCurrentAccount() # if the message is meant for the user that is reading it if entity.scope.key() == user.key(): # mark the entity as read self._logic.updateEntityProperties(entity, {'unread' : False} ) context['entity_type_url'] = self._params['url_name'] context['entity_suffix'] = entity.key().id_or_name() if entity else None return True
def listProjects(self, request, access_type, page_name=None, params=None, **kwargs): """View that lists all of the current user's Student Projects for the Program given as Scope. """ from soc.modules.gsoc.views.models import student_project as project_view user_entity = user_logic.getForCurrentAccount() # pylint: disable-msg=E1103 fields = { 'link_id': user_entity.link_id, 'scope_path': kwargs['scope_path'] } try: student_entity = student_logic.getFromKeyFieldsOr404(fields) except out_of_band.Error, error: return responses.errorResponse( error, request, template=params['error_public'])
def takePost(self, request, template, context, params, survey_form, entity, record, **kwargs): """Handles the POST request for the Survey's take page. Args: template: the template used for this view survey_form: instance of SurveyTakeForm entity: the Survey entity record: a SurveyRecord entity rest: see base.View.public() """ survey_logic = params['logic'] record_logic = survey_logic.getRecordLogic() if not survey_form.is_valid(): # show the form errors return self._constructResponse(request, entity=entity, context=context, form=survey_form, params=params, template=template) # retrieve the data from the form _, properties = forms_helper.collectCleanedFields(survey_form) # add the required SurveyRecord properties properties['user'] = user_logic.getForCurrentAccount() properties['survey'] = entity # call the hook method before updating the SurveyRecord self._takePost(request, params, entity, record, properties) # update the record entity if any and clear all dynamic properties record_logic.updateOrCreateFromFields(record, properties, clear_dynamic=True) # TODO: add notice to page that the response has been saved successfully # redirect to the same page for now redirect = request.path return http.HttpResponseRedirect(redirect)
def listSelf(self, request, access_type, page_name=None, params=None, **kwargs): """List all applications from the current logged-in user. For params see base.View.public(). """ user_entity = user_logic.getForCurrentAccount() filter = {'applicant' : user_entity} if kwargs['scope_path']: filter['scope_path'] = kwargs['scope_path'] # create the selection list selection = [(['needs review', 'pre-accepted', 'pre-rejected'], (redirects.getEditRedirect, params)), ('accepted', (redirects.getApplicantRedirect, {'url_name': params['group_url_name']})), ('rejected', (redirects.getPublicRedirect, params))] return self._applicationListConstructor(request, params, page_name, filter=filter, selection=selection, **kwargs)
def _public(self, request, entity, context): """Marks the Notification as read if that hasn't happened yet. for parameters see base._public() """ # if the user viewing is the user for which this notification is meant # and the notification has not been read yet if entity.unread: # get the current user user = user_logic.getForCurrentAccount() # if the message is meant for the user that is reading it # pylint: disable-msg=E1103 if entity.scope.key() == user.key(): # mark the entity as read self._logic.updateEntityProperties(entity, {'unread': False}) context['entity_type_url'] = self._params['url_name'] context['entity_suffix'] = entity.key().id_or_name( ) if entity else None context['page_name'] = 'Notification - %s' % (entity.subject) return True
def _public(self, request, entity, context): """Survey taking and result display handler. Args: request: the django request object entity: the entity to make public context: the context object -- Taking Survey Pages Are Not 'Public' -- For surveys, the "public" page is actually the access-protected survey-taking page. --- Deadlines --- A survey_end can also be used as a conditional for updating values, we have a special read_only UI and a check on the POST handler for this. Passing read_only=True here allows one to fetch the read_only view. """ # check ACL rights = self._params['rights'] rights.checkIsSurveyReadable({'key_name': entity.key().name(), 'prefix': entity.prefix, 'scope_path': entity.scope_path, 'link_id': entity.link_id,}, 'key_name') survey = entity user = user_logic.getForCurrentAccount() status = self.getStatus(request, context, user, survey) read_only, can_write, not_ready = status # If user can edit this survey and is requesting someone else's results, # in a read-only request, we fetch them. if can_write and read_only and 'user_results' in request.GET: user = user_logic.getFromKeyNameOr404(request.GET['user_results']) if not_ready and not can_write: context['notice'] = "No survey available." return False elif not_ready: return False else: # check for existing survey_record record_query = SurveyRecord.all( ).filter("user ="******"survey =", survey) survey_record = record_query.get() if len(request.POST) < 1 or read_only or not_ready: # not submitting completed survey OR we're ignoring late submission pass else: # save/update the submitted survey context['notice'] = "Survey Submission Saved" record_logic = self._logic.getRecordLogic() survey_record = record_logic.updateSurveyRecord(user, survey, survey_record, request.POST) survey_content = survey.survey_content if not survey_record and read_only: # no recorded answers, we're either past survey_end or want to see answers is_same_user = user.key() == user_logic.getForCurrentAccount().key() if not can_write or not is_same_user: # If user who can edit looks at her own taking page, show the default # form as readonly. Otherwise, below, show nothing. context["notice"] = "There are no records for this survey and user." return False survey_form = surveys.SurveyForm(survey_content=survey_content, this_user=user, project=None, survey_logic=self._params['logic'], survey_record=survey_record, read_only=read_only, editing=False) survey_form.getFields() # set help and status text self.setHelpStatus(context, read_only, survey_record, survey_form, survey) if not context['survey_form']: access_tpl = "Access Error: This Survey Is Limited To %s" context["notice"] = access_tpl % string.capwords(survey.taking_access) context['read_only'] = read_only context['project'] = None return True
class View(survey_view.View): """View methods for the ProjectSurvey model. """ def __init__(self, params=None): """Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View """ new_params = {} new_params['logic'] = org_app_logic new_params['name'] = "Org Application Survey" new_params['url_name'] = 'org_app' new_params['extra_dynaexclude'] = ['taking_access'] new_params['survey_take_form'] = OrgAppSurveyForm new_params['survey_record_form'] = OrgAppRecordForm new_params['extra_django_patterns'] = [ (r'^%(url_name)s/(?P<access_type>list_self)/%(key_fields)s$', '%(module_package)s.%(module_name)s.list_self', 'Overview of %(name_plural)s Taken by You'), ] params = dicts.merge(params, new_params, sub_merge=True) super(View, self).__init__(params=params) @decorators.check_access def create(self, request, access_type, page_name=None, params=None, **kwargs): """Displays the create page for this entity type. If an OrgAppSurvey already exists it will redirect to the edit page. """ params = dicts.merge(params, self._params) program_view = params['scope_view'] program_logic = program_view.getParams()['logic'] program_entity = program_logic.getFromKeyName(kwargs['scope_path']) org_app = org_app_logic.getForProgram(program_entity) if org_app: # redirect to edit page return http.HttpResponseRedirect( redirects.getEditRedirect(org_app, params)) else: # show create page return super(View, self).create(request, access_type, page_name=page_name, params=params, **kwargs) def _getSurveyRecordFor(self, survey, request, params): """Returns the SurveyRecord for the given Survey and request. This method also take the ID specified as GET param into account when querying for the SurveyRecord. For params see survey.View._getSurveyRecordFor(). """ get_dict = request.GET record_id = get_dict.get('id', None) survey_logic = params['logic'] record_logic = survey_logic.getRecordLogic() if not record_id or not record_id.isdigit(): return None else: return record_logic.getFromIDOr404(int(record_id)) def _takeGet(self, request, template, context, params, entity, record, **kwargs): """Hooking into the view for the take's page GET request. For params see survey.View._takeGet(). """ # the form action should contain the requested record if record: context['form_action'] = "?id=%s" % (request.GET['id']) def _takePost(self, request, params, entity, record, properties): """Hook into the view for the take's page POST request. For params see survey.View._takePost(). """ from soc.logic.models.user import logic as user_logic if not record: # creating a new record user_entity = user_logic.getForCurrentAccount() properties['main_admin'] = user_entity if properties['agreed_to_tos']: properties['agreed_to_admin_agreement'] = True # remove fields we don't need to store in the SurveyRecord properties.pop('tos') properties.pop('agreed_to_tos') def _getRedirectOnSuccessfulTake(self, request, params, survey, record): """Returns a path to which the user should be redirected after successfully taking a OrgAppSurvey. """ return request.path + '?id=' + str(record.key().id_or_name()) @decorators.merge_params @decorators.check_access def list_self(self, request, access_type, page_name=None, params=None, **kwargs): """View that lists all the OrgRecords you have access to. For Args see base.View().public(). """ from soc.logic.models.user import logic as user_logic survey_logic = params['logic'] record_logic = survey_logic.getRecordLogic() try: entity = survey_logic.getFromKeyFieldsOr404(kwargs) except out_of_band.Error, error: return responses.errorResponse(error, request, template=params['error_public']) # get the context for this webpage context = responses.getUniversalContext(request) responses.useJavaScript(context, params['js_uses_all']) context['entity'] = entity list_contents = [] user_entity = user_logic.getForCurrentAccount() list_params = params.copy() list_params['logic'] = record_logic list_params[ 'list_heading'] = 'soc/org_app_survey/list/records_heading.html' list_params['list_row'] = 'soc/org_app_survey/list/records_row.html' if timeline_helper.isActivePeriod(entity, 'survey'): info = {'url_name': list_params['url_name'], 'survey': entity} list_params['public_row_extra'] = lambda entity: { 'link': redirects.getRetakeOrgAppSurveyRedirect(entity, info) } else: list_params['public_row_extra'] = lambda entity: { 'link': redirects.getViewSurveyRecordRedirect( entity, list_params) } fields = {'survey': entity, 'main_admin': user_entity} list_params['list_description'] = \ 'List of Applications for which you are Main Admin.' main_list = lists.getListContent(request, list_params, fields, need_content=True, idx=0) # TODO(LIST) if main_list: list_contents.append(main_list) fields = {'survey': entity, 'backup_admin': user_entity} list_params['list_description'] = \ 'List of Applications for which your are Backup Admin.' backup_list = lists.getListContent(request, list_params, fields, need_content=True, idx=1) if backup_list: list_contents.append(backup_list) return self._list(request, list_params, list_contents, page_name, context)
return responses.errorResponse(error, request, template=params['error_public']) # get the context for this webpage context = responses.getUniversalContext(request) responses.useJavaScript(context, params['js_uses_all']) context['page_name'] = "%s titled '%s'" % (page_name, entity.title) context['entity'] = entity # add the first question to the context show a preview can be shown context['first_question'] = entity.survey_content.orderedProperties( )[0] # get the rights checker user_entity = user_logic.getForCurrentAccount() rights = self._params['rights'] rights.setCurrentUser(user_entity.account, user_entity) # check if the current user is allowed to visit the read the survey allowed_to_read = False try: rights.checkIsSurveyReadable( { 'key_name': entity.key().name(), 'prefix': entity.prefix, 'scope_path': entity.scope_path, 'link_id': entity.link_id, 'user': user_entity }, survey_logic)
def getListProposalsData(self, request, rp_params, mp_params, p_params, org_entity): """Returns the list data for listProposals. """ from soc.modules.gsoc.logic.models.ranker_root import logic \ as ranker_root_logic from soc.modules.gsoc.logic.models.student_proposal import logic \ as sp_logic from soc.modules.gsoc.models import student_proposal from soc.modules.gsoc.views.helper import list_info as list_info_helper from soc.modules.gsoc.views.models import student_proposal \ as student_proposal_view idx = request.GET.get('idx', '') idx = int(idx) if idx.isdigit() else -1 args = order = [] if idx == 0: # retrieve the ranker fields = { 'link_id': student_proposal.DEF_RANKER_NAME, 'scope': org_entity } ranker_root = ranker_root_logic.getForFields(fields, unique=True) ranker = ranker_root_logic.getRootFromEntity(ranker_root) keys = [] # only when the program allows allocations # to be seen we should color the list if org_entity.scope.allocations_visible: proposals = sp_logic.getProposalsToBeAcceptedForOrg(org_entity) keys = [i.key() for i in proposals] # show the amount of slots assigned on the webpage context['slots_visible'] = True # TODO(ljvderijk) once sorting with IN operator is fixed, # make this list show more filter = {'org': org_entity, 'status': 'pending'} params = rp_params # order by descending score order = ['-score'] args = [ranker, keys] elif idx == 1: # check if the current user is a mentor user_entity = user_logic.getForCurrentAccount() fields = { 'user': user_entity, 'scope': org_entity, } mentor_entity = mentor_logic.getForFields(fields, unique=True) filter = { 'org': org_entity, 'mentor': mentor_entity, 'status': 'pending' } params = mp_params elif idx == 2: filter = {'org': org_entity} params = p_params else: return responses.jsonErrorResponse(request, "idx not valid") contents = helper.lists.getListData(request, params, filter, 'public', order=order, args=args) json = simplejson.dumps(contents) return responses.jsonResponse(request, json)
try: entity = params['logic'].getFromKeyFieldsOr404(kwargs) except out_of_band.Error, error: return responses.errorResponse( error, request, template=params['error_public']) # get the context for this webpage context = responses.getUniversalContext(request) responses.useJavaScript(context, params['js_uses_all']) context['page_name'] = "%s titled '%s'" % (page_name, entity.title) context['entity'] = entity results_logic = params['logic'].getRecordLogic() user = user_logic.getForCurrentAccount() # only show truncated preview of first answer context['first_question'] = entity.survey_content.orderedProperties( )[0] context['record_redirect'] = redirects.getSurveyRecordRedirect( entity, params) filter = self._params.get('filter') or {} filter['survey'] = entity list_params = params.copy() list_params['list_description'] = \ 'List of %(name_plural)s.' % list_params