course_group_config.py 12.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
"""
Class for manipulating groups configuration on a course object.
"""
import json
import logging

from util.db import generate_int_id, MYSQL_MAX_INT

from django.utils.translation import ugettext as _
from contentstore.utils import reverse_usage_url
from xmodule.partitions.partitions import UserPartition
from xmodule.split_test_module import get_split_user_partitions
from openedx.core.djangoapps.course_groups.partition_scheme import get_cohorted_user_partition

MINIMUM_GROUP_ID = 100

RANDOM_SCHEME = "random"
COHORT_SCHEME = "cohort"

# Note: the following content group configuration strings are not
# translated since they are not visible to users.
CONTENT_GROUP_CONFIGURATION_DESCRIPTION = 'The groups in this configuration can be mapped to cohort groups in the LMS.'

CONTENT_GROUP_CONFIGURATION_NAME = 'Content Group Configuration'

log = logging.getLogger(__name__)


class GroupConfigurationsValidationError(Exception):
    """
    An error thrown when a group configurations input is invalid.
    """
    pass


class GroupConfiguration(object):
    """
    Prepare Group Configuration for the course.
    """
    def __init__(self, json_string, course, configuration_id=None):
        """
        Receive group configuration as a json (`json_string`), deserialize it
        and validate.
        """
        self.configuration = GroupConfiguration.parse(json_string)
        self.course = course
        self.assign_id(configuration_id)
        self.assign_group_ids()
        self.validate()

    @staticmethod
    def parse(json_string):
        """
        Deserialize given json that represents group configuration.
        """
        try:
            configuration = json.loads(json_string)
        except ValueError:
            raise GroupConfigurationsValidationError(_("invalid JSON"))
        configuration["version"] = UserPartition.VERSION
        return configuration

    def validate(self):
        """
        Validate group configuration representation.
        """
        if not self.configuration.get("name"):
            raise GroupConfigurationsValidationError(_("must have name of the configuration"))
        if len(self.configuration.get('groups', [])) < 1:
            raise GroupConfigurationsValidationError(_("must have at least one group"))

    def assign_id(self, configuration_id=None):
        """
        Assign id for the json representation of group configuration.
        """
        if configuration_id:
            self.configuration['id'] = int(configuration_id)
        else:
            self.configuration['id'] = generate_int_id(
                MINIMUM_GROUP_ID, MYSQL_MAX_INT, GroupConfiguration.get_used_ids(self.course)
            )

    def assign_group_ids(self):
        """
        Assign ids for the group_configuration's groups.
        """
        used_ids = [g.id for p in self.course.user_partitions for g in p.groups]
        # Assign ids to every group in configuration.
        for group in self.configuration.get('groups', []):
            if group.get('id') is None:
                group["id"] = generate_int_id(MINIMUM_GROUP_ID, MYSQL_MAX_INT, used_ids)
                used_ids.append(group["id"])

    @staticmethod
    def get_used_ids(course):
        """
        Return a list of IDs that already in use.
        """
        return set([p.id for p in course.user_partitions])

    def get_user_partition(self):
        """
        Get user partition for saving in course.
        """
        return UserPartition.from_json(self.configuration)

    @staticmethod
    def _get_usage_info(course, unit, item, usage_info, group_id, scheme_name=None):
        """
        Get usage info for unit/module.
        """
        unit_url = reverse_usage_url(
            'container_handler',
            course.location.course_key.make_usage_key(unit.location.block_type, unit.location.name)
        )

        usage_dict = {'label': u"{} / {}".format(unit.display_name, item.display_name), 'url': unit_url}
        if scheme_name == RANDOM_SCHEME:
            validation_summary = item.general_validation_message()
            usage_dict.update({'validation': validation_summary.to_json() if validation_summary else None})

        usage_info[group_id].append(usage_dict)

        return usage_info

    @staticmethod
    def get_content_experiment_usage_info(store, course):
        """
        Get usage information for all Group Configurations currently referenced by a split_test instance.
        """
        split_tests = store.get_items(course.id, qualifiers={'category': 'split_test'})
        return GroupConfiguration._get_content_experiment_usage_info(store, course, split_tests)

    @staticmethod
    def get_split_test_partitions_with_usage(store, course):
        """
        Returns json split_test group configurations updated with usage information.
        """
        usage_info = GroupConfiguration.get_content_experiment_usage_info(store, course)
        configurations = []
        for partition in get_split_user_partitions(course.user_partitions):
            configuration = partition.to_json()
            configuration['usage'] = usage_info.get(partition.id, [])
            configurations.append(configuration)
        return configurations

    @staticmethod
    def _get_content_experiment_usage_info(store, course, split_tests):  # pylint: disable=unused-argument
        """
        Returns all units names, their urls and validation messages.

        Returns:
        {'user_partition_id':
            [
                {
                    'label': 'Unit 1 / Experiment 1',
                    'url': 'url_to_unit_1',
                    'validation': {'message': 'a validation message', 'type': 'warning'}
                },
                {
                    'label': 'Unit 2 / Experiment 2',
                    'url': 'url_to_unit_2',
                    'validation': {'message': 'another validation message', 'type': 'error'}
                }
            ],
        }
        """
        usage_info = {}
        for split_test in split_tests:
            if split_test.user_partition_id not in usage_info:
                usage_info[split_test.user_partition_id] = []

            unit = split_test.get_parent()
            if not unit:
                log.warning("Unable to find parent for split_test %s", split_test.location)
                continue

            usage_info = GroupConfiguration._get_usage_info(
                course=course,
                unit=unit,
                item=split_test,
                usage_info=usage_info,
                group_id=split_test.user_partition_id,
                scheme_name=RANDOM_SCHEME
            )
        return usage_info

    @staticmethod
    def get_content_groups_usage_info(store, course):
        """
        Get usage information for content groups.
        """
193
        items = store.get_items(course.id, settings={'group_access': {'$exists': True}}, include_orphans=False)
194 195 196 197 198 199 200 201

        return GroupConfiguration._get_content_groups_usage_info(course, items)

    @staticmethod
    def _get_content_groups_usage_info(course, items):
        """
        Returns all units names and their urls.

202 203
        This will return only groups for the cohort user partition.

204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
        Returns:
        {'group_id':
            [
                {
                    'label': 'Unit 1 / Problem 1',
                    'url': 'url_to_unit_1'
                },
                {
                    'label': 'Unit 2 / Problem 2',
                    'url': 'url_to_unit_2'
                }
            ],
        }
        """
        usage_info = {}
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
        for item, group_id in GroupConfiguration._iterate_items_and_content_group_ids(course, items):
            if group_id not in usage_info:
                usage_info[group_id] = []

            unit = item.get_parent()
            if not unit:
                log.warning("Unable to find parent for component %s", item.location)
                continue

            usage_info = GroupConfiguration._get_usage_info(
                course,
                unit=unit,
                item=item,
                usage_info=usage_info,
                group_id=group_id
            )
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251

        return usage_info

    @staticmethod
    def get_content_groups_items_usage_info(store, course):
        """
        Get usage information on items for content groups.
        """
        items = store.get_items(course.id, settings={'group_access': {'$exists': True}})

        return GroupConfiguration._get_content_groups_items_usage_info(course, items)

    @staticmethod
    def _get_content_groups_items_usage_info(course, items):
        """
        Returns all items names and their urls.

252 253
        This will return only groups for the cohort user partition.

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
        Returns:
        {'group_id':
            [
                {
                    'label': 'Problem 1 / Problem 1',
                    'url': 'url_to_item_1'
                },
                {
                    'label': 'Problem 2 / Problem 2',
                    'url': 'url_to_item_2'
                }
            ],
        }
        """
        usage_info = {}
269 270 271 272 273 274 275 276 277 278 279
        for item, group_id in GroupConfiguration._iterate_items_and_content_group_ids(course, items):
            if group_id not in usage_info:
                usage_info[group_id] = []

            usage_info = GroupConfiguration._get_usage_info(
                course,
                unit=item,
                item=item,
                usage_info=usage_info,
                group_id=group_id
            )
280 281 282 283

        return usage_info

    @staticmethod
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
    def _iterate_items_and_content_group_ids(course, items):
        """
        Iterate through items and content group IDs in a course.

        This will yield group IDs *only* for cohort user partitions.

        Yields: tuple of (item, group_id)
        """
        content_group_configuration = get_cohorted_user_partition(course)
        if content_group_configuration is not None:
            for item in items:
                if hasattr(item, 'group_access') and item.group_access:
                    group_ids = item.group_access.get(content_group_configuration.id, [])

                    for group_id in group_ids:
                        yield item, group_id

    @staticmethod
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
    def update_usage_info(store, course, configuration):
        """
        Update usage information for particular Group Configuration.

        Returns json of particular group configuration updated with usage information.
        """
        configuration_json = None
        # Get all Experiments that use particular  Group Configuration in course.
        if configuration.scheme.name == RANDOM_SCHEME:
            split_tests = store.get_items(
                course.id,
                category='split_test',
                content={'user_partition_id': configuration.id}
            )
            configuration_json = configuration.to_json()
            usage_information = GroupConfiguration._get_content_experiment_usage_info(store, course, split_tests)
            configuration_json['usage'] = usage_information.get(configuration.id, [])
        elif configuration.scheme.name == COHORT_SCHEME:
            # In case if scheme is "cohort"
            configuration_json = GroupConfiguration.update_content_group_usage_info(store, course, configuration)
        return configuration_json

    @staticmethod
    def update_content_group_usage_info(store, course, configuration):
        """
        Update usage information for particular Content Group Configuration.

        Returns json of particular content group configuration updated with usage information.
        """
        usage_info = GroupConfiguration.get_content_groups_usage_info(store, course)
        content_group_configuration = configuration.to_json()

        for group in content_group_configuration['groups']:
            group['usage'] = usage_info.get(group['id'], [])

        return content_group_configuration

    @staticmethod
    def get_or_create_content_group(store, course):
        """
        Returns the first user partition from the course which uses the
        CohortPartitionScheme, or generates one if no such partition is
        found.  The created partition is not saved to the course until
        the client explicitly creates a group within the partition and
        POSTs back.
        """
348
        content_group_configuration = get_cohorted_user_partition(course)
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
        if content_group_configuration is None:
            content_group_configuration = UserPartition(
                id=generate_int_id(MINIMUM_GROUP_ID, MYSQL_MAX_INT, GroupConfiguration.get_used_ids(course)),
                name=CONTENT_GROUP_CONFIGURATION_NAME,
                description=CONTENT_GROUP_CONFIGURATION_DESCRIPTION,
                groups=[],
                scheme_id=COHORT_SCHEME
            )
            return content_group_configuration.to_json()

        content_group_configuration = GroupConfiguration.update_content_group_usage_info(
            store,
            course,
            content_group_configuration
        )
        return content_group_configuration