blob: 3a53d912ee5701dc93dca50b35cf1293c10159d8 [file] [log] [blame]
# Copyright 2014 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Logic for task counts."""
import collections
from google.appengine.ext import ndb
from codein.models import task_counts as task_counts_model
from soc.modules.gci.models import task as task_model
# TODO(daniel): handle tie situations
def getStudentsByTaskCountForOrg(org_key, limit=None):
"""Returns mapping between participating students and their task counts
for the specified organization ordered by number of tasks in descending order.
Args:
org_key: ndb.Key of the organization.
limit: Maximum number of results to return.
Returns:
A collections.OrderedDict that maps ndb.Key of student profiles and
corresponding numbers of completed tasks.
"""
limit = limit or 1000
query = task_counts_model.StudentTaskCountForOrg.query(
task_counts_model.StudentTaskCountForOrg.organization == org_key)
query = query.order(
-task_counts_model.StudentTaskCountForOrg.completed_tasks_count)
results = collections.OrderedDict()
task_counts = query.fetch(limit)
for task_count in task_counts:
results[task_count.key.parent()] = task_count.completed_tasks_count
return results
@ndb.transactional
def updateStudentTaskCountForOrg(task):
"""Updates task counts for the student who completed the specified task.
Args:
task: task_model.GCITask entity.
Raises:
ValueError: if the task is not closed or no student is assigned to the task.
"""
if task.status != task_model.CLOSED:
raise ValueError('The task is not closed: %r.' % task.key())
student_key = ndb.Key.from_old_key(
task_model.GCITask.student.get_value_for_datastore(task))
if not student_key:
raise ValueError('No student is defined for the task: %r.' % task.key())
org_key = ndb.Key.from_old_key(
task_model.GCITask.org.get_value_for_datastore(task))
task_counts = task_counts_model.StudentTaskCountForOrg.query(
task_counts_model.StudentTaskCountForOrg.organization == org_key,
ancestor=student_key).get()
if not task_counts:
task_counts = task_counts_model.StudentTaskCountForOrg(
parent=student_key, organization=org_key)
task_counts.completed_tasks_count += 1
task_counts.put()