Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions projects/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@
path("tagging/rest_api/", include("openedx_tagging.urls")),
# Mirrors the prefix openedx-platform mounts CBE at; a consuming project picks its own.
path("api/", include("openedx_learning.urls")),
path("api/", include("openedx_learning.learner_urls")),
path('__debug__/', include('debug_toolbar.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
178 changes: 177 additions & 1 deletion src/openedx_learning/applets/cbe/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,19 @@
from openedx_tagging import api as tagging_api
from openedx_tagging.api import create_taxonomy, get_ancestor_tags, get_descendant_tags
from openedx_tagging.models import ObjectTag, Tag, Taxonomy
from openedx_tagging.models.base import TAXONOMY_MAX_DEPTH
from openedx_tagging.rules import ObjectTagPermissionItem, UserType

from .data import CriterionDeletionResult, GradedObjectScore, GroupDeletionResult
from .data import (
CourseCompetencyCriteria,
CourseCriteriaCompetency,
CourseCriteriaCriterion,
CourseCriteriaGroup,
CourseCriteriaTaxonomy,
CriterionDeletionResult,
GradedObjectScore,
GroupDeletionResult,
)
from .models import (
CompetencyCourseRun,
CompetencyCriteriaGroup,
Expand All @@ -46,6 +56,11 @@
"CompetencyCriteriaGroupArchivedError",
"CompetencyCriteriaTree",
"CompetencyCriterionArchivedError",
"CourseCompetencyCriteria",
"CourseCriteriaCompetency",
"CourseCriteriaCriterion",
"CourseCriteriaGroup",
"CourseCriteriaTaxonomy",
"CriterionDeletionResult",
"GradedObjectScore",
"GroupDeletionResult",
Expand All @@ -58,6 +73,7 @@
"get_blocked_courses",
"get_competency_criteria_tree",
"get_competency_rule_profiles",
"get_course_competency_criteria",
"get_courses_with_live_criteria",
"is_competency_taxonomy",
"record_graded_object_statuses",
Expand Down Expand Up @@ -286,6 +302,166 @@ def get_competency_criteria_tree(tag: Tag, course_keys: list[CourseKey] | None =
)


def _has_archived_ancestor_tag() -> Q:
"""
Return a filter on CompetencyCriteriaGroup that matches a group whose tag has an archived ancestor tag.

Tags nest at most ``TAXONOMY_MAX_DEPTH`` levels deep, so the ancestor chain is a fixed number of joins.
That keeps the check inside the caller's query instead of walking up the chain one query per level.
"""
archived_ancestor = Q()
for level in range(1, TAXONOMY_MAX_DEPTH + 1):
archived_ancestor |= Q(**{"tag" + "__parent" * level + "__archived": True})
return archived_ancestor


def get_course_competency_criteria(course_key: CourseKey) -> CourseCompetencyCriteria:
"""
Return one course run's live competency criteria hierarchy, as four flat lists that reference each other by id.

UNSTABLE: becomes stable once the learner Progress tab frontends
(https://github.com/openedx/openedx-core/issues/734 and https://github.com/openedx/openedx-core/issues/839)
ship and the learner status endpoints reuse the same shape.

This function reads data and checks no permission; the caller decides who may see the result.
``course_key`` must be a plain course run key with its branch and version already stripped, and is
matched exactly against the course run of each course-level group. A key with no course run, or a
course run with no live criteria, returns a result whose four lists are all empty.

A competency's criteria tree has a root group, one course-level group per course run, and bottom-tier
groups nested below a course-level group at any depth. The result holds, for each course-level group of
the requested run, its root group, the course-level group, and every group below it. A group below a
course-level group of another course run is never returned, even under a shared root. Criteria are
returned for every returned group except the root: a criterion attached directly to a root group is
never returned.

Left out:

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay I grant that the caller needs to know what is excluded.
Try to make this simple to understand. Use ASCII art to illustrate how it is for the tree.


- An archived criterion, and a criterion whose ObjectTag is archived.
- An archived group, and everything beneath it, even when the archive cascade did not reach the
groups below. An archived root group hides the whole competency.
- A competency whose tag, or any ancestor tag, is archived. A competency whose taxonomy is archived
or disabled. Only tags of competency taxonomies are competencies.
- After those, any group with no remaining criterion in its subtree, any competency with no remaining
course-level group, and any taxonomy with no remaining competency.

An archived rule profile does not hide a criterion. The criterion's rule is the profile's
Comment on lines +326 to +348

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The docstring is way to large.
It should only state:

  • what arguments come in (incl. shape)
  • what gets returned (incl. shape)
  • what the caller of the function critically needs to know

``rule_type`` and ``rule_payload`` when it has a profile, and its own overrides otherwise, returned
exactly as stored, including a rule type this library does not know.

``groups`` are ordered by ``(ordering, id)``, and ``taxonomies``, ``competencies`` and ``criteria`` by
``id``, so repeated calls return equal results. The number of database queries is fixed (one, when the
course run has no course-level group, otherwise three) however many taxonomies, competencies, groups
and criteria the course has.
Comment on lines +352 to +355

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
``groups`` are ordered by ``(ordering, id)``, and ``taxonomies``, ``competencies`` and ``criteria`` by
``id``, so repeated calls return equal results. The number of database queries is fixed (one, when the
course run has no course-level group, otherwise three) however many taxonomies, competencies, groups
and criteria the course has.
Ordering by:
``groups``: ``(ordering, id)``
``taxonomies``, ``competencies``, ``criteria``: ``id``

"""
course_level_groups = list(
CompetencyCriteriaGroup.objects.filter(
course__course_key=course_key,
parent__isnull=False,
parent__parent__isnull=True,
archived=False,
parent__archived=False,
tag__archived=False,
tag__taxonomy__archived=False,
tag__taxonomy__enabled=True,
tag__taxonomy_id__in=CompetencyTaxonomy.objects.values("pk"),
)
.exclude(_has_archived_ancestor_tag())
.select_related("parent", "tag__taxonomy")
)
if not course_level_groups:
return CourseCompetencyCriteria(taxonomies=[], competencies=[], groups=[], criteria=[])

# Bottom-tier groups carry no course, so they can only be found through their tag and then walked down
# from the requested run's course-level groups. Another run's branch under the same root is never
# reached by that walk.
Comment on lines +375 to +377

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove comment and extract code into a highly readable function that expresses what it does through good naming.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is all this for, anyway? Finding subtree_groups? And is anything excluded?

below_course_level = CompetencyCriteriaGroup.objects.filter(
tag_id__in={group.tag_id for group in course_level_groups},
archived=False,
parent__isnull=False,
course__isnull=True,
)
children_by_parent_id: dict[int, list[CompetencyCriteriaGroup]] = {}
for group in below_course_level:
assert group.parent_id is not None
children_by_parent_id.setdefault(group.parent_id, []).append(group)
subtree_groups: dict[int, CompetencyCriteriaGroup] = {}
pending = list(course_level_groups)
while pending:
group = pending.pop()
subtree_groups[group.id] = group
pending.extend(children_by_parent_id.get(group.id, []))

criteria = list(
CompetencyCriterion.objects.filter(
group_id__in=subtree_groups.keys(), archived=False, object_tag__archived=False,
)
.select_related("object_tag", "rule_profile")
.order_by("id")
)

# A group is kept when its subtree holds a criterion, so mark each criterion's group and its ancestors.
# The walk ends above the course-level group, whose parent, the root, is not in subtree_groups.
kept_group_ids: set[int] = set()
for criterion in criteria:
group_id: int | None = criterion.group_id
while group_id in subtree_groups and group_id not in kept_group_ids:
kept_group_ids.add(group_id)
group_id = subtree_groups[group_id].parent_id
kept_course_level_groups = [group for group in course_level_groups if group.id in kept_group_ids]

roots = {group.parent_id: group.parent for group in kept_course_level_groups}
tags = {group.tag_id: group.tag for group in kept_course_level_groups}
taxonomies = {}
for tag in tags.values():
# A group's tag is always a competency tag, so its taxonomy is always set.
assert tag.taxonomy is not None
taxonomies[tag.taxonomy_id] = tag.taxonomy
groups = [group for group in roots.values() if group is not None]
groups.extend(group for group in subtree_groups.values() if group.id in kept_group_ids)
groups.sort(key=lambda group: (group.ordering, group.id))
Comment on lines +403 to +422

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also remove comment and extract this into another function. The comment is unclear (what does "mark" mean and why?) The second line of the comment is also not clear (too vague, and doesn't explain why the walk ends there). But the comment gets removed anyway - the thing is just this needs to be clear enough from the code itself.
And the code is very unreadable. It should clearly express its intention through applying the principles of maintainability.


return CourseCompetencyCriteria(
taxonomies=[
CourseCriteriaTaxonomy(id=taxonomy.id, name=taxonomy.name)
for _, taxonomy in sorted(taxonomies.items())
],
competencies=[
CourseCriteriaCompetency(
id=tag.id,
name=tag.value,
external_id=tag.external_id,
lineage=tag.get_lineage(),
taxonomy_id=cast(int, tag.taxonomy_id),
)
for _, tag in sorted(tags.items())
],
groups=[
CourseCriteriaGroup(
id=group.id,
competency_id=group.tag_id,
parent_id=group.parent_id,
name=group.name,
logic_operator=group.logic_operator,
ordering=group.ordering,
)
for group in groups
],
criteria=[
CourseCriteriaCriterion(
id=criterion.id,
group_id=criterion.group_id,
usage_key=criterion.object_tag.object_id,
rule_type=rule_type,
rule_payload=rule_payload,
)
for criterion in criteria
if criterion.group_id in kept_group_ids
for rule_type, rule_payload in [_effective_rule(criterion)]
],
)


def _create_leaf_group(
tag: Tag,
course_run: CourseRun,
Expand Down
87 changes: 87 additions & 0 deletions src/openedx_learning/applets/cbe/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,90 @@ class GroupDeletionResult:
archived: bool
cascaded_group_count: int
cascaded_criteria_count: int

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are these data classes needed? The data model is already in place, what values do these add and why aren't they in the code yet then?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not saying they are a bad idea, just want to understand why they are introduced in this PR specifically, and trying to understand their intention


@dataclass(frozen=True, kw_only=True, slots=True)
class CourseCriteriaTaxonomy:
"""
A competency taxonomy that has at least one competency with criteria in a course run.

UNSTABLE: see :func:`openedx_learning.applets.cbe.api.get_course_competency_criteria`.
"""

id: int
name: str


@dataclass(frozen=True, kw_only=True, slots=True)
class CourseCriteriaCompetency:
"""
A competency (a Tag of a competency taxonomy) that has criteria in a course run.

``id`` is the Tag id. ``lineage`` holds the tag values from the taxonomy's top level down to the
competency itself, so a top-level competency's lineage is a single entry.

UNSTABLE: see :func:`openedx_learning.applets.cbe.api.get_course_competency_criteria`.
"""

id: int
name: str
external_id: str | None
lineage: list[str]
taxonomy_id: int


@dataclass(frozen=True, kw_only=True, slots=True)
class CourseCriteriaGroup:
"""
One CompetencyCriteriaGroup of a competency's criteria tree in a course run.

``competency_id`` is the id of the group's tag, which every group of a competency's tree shares.
``parent_id`` is None only for the root group. ``logic_operator`` is the stored value: ``"AND"``,
``"OR"``, or None.

UNSTABLE: see :func:`openedx_learning.applets.cbe.api.get_course_competency_criteria`.
"""

id: int
competency_id: int
parent_id: int | None
name: str
logic_operator: str | None
ordering: int


@dataclass(frozen=True, kw_only=True, slots=True)
class CourseCriteriaCriterion:

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's a CourseCriteriaCriterion? That seems like criterion is doubled.

"""
One CompetencyCriterion of a course run.

``usage_key`` is the object id of the criterion's ObjectTag. ``rule_type`` and ``rule_payload`` are
the effective rule: the rule profile's when the criterion has one, its own override otherwise.

UNSTABLE: see :func:`openedx_learning.applets.cbe.api.get_course_competency_criteria`.
"""

id: int
group_id: int
usage_key: str
rule_type: str
rule_payload: dict


@dataclass(frozen=True, kw_only=True, slots=True)
class CourseCompetencyCriteria:
"""
The competency criteria of one course run, as four flat lists that reference each other by id.

Every ``parent_id``, ``competency_id``, ``group_id`` and ``taxonomy_id`` in one list names an
item in the list it refers to. See :func:`openedx_learning.applets.cbe.api.get_course_competency_criteria`.

UNSTABLE: becomes stable once the learner Progress tab frontends
(https://github.com/openedx/openedx-core/issues/734 and https://github.com/openedx/openedx-core/issues/839)
ship and the learner status endpoints reuse the same shape.
"""

taxonomies: list[CourseCriteriaTaxonomy]
competencies: list[CourseCriteriaCompetency]
groups: list[CourseCriteriaGroup]
criteria: list[CourseCriteriaCriterion]
13 changes: 13 additions & 0 deletions src/openedx_learning/applets/cbe/rest_api/learner_urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
"""
CBE API URLs for learners.
"""

from django.urls import include, path

from .v1 import learner_urls as v1_learner_urls

# A namespace distinct from the authoring "cbe", because a project that includes both URL modules cannot
# register two includes under one namespace (urls.W005).
app_name = "cbe_learner"

urlpatterns = [path("v1/", include(v1_learner_urls))]
15 changes: 15 additions & 0 deletions src/openedx_learning/applets/cbe/rest_api/paginators.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,18 @@ class CompetencyBlockedCoursesPagination(DefaultPagination):

page_size = 100
max_page_size = 500


class CourseCompetencyCriteriaPagination(DefaultPagination):
"""
Page size for the competencies of a course run's criteria.

Pinned here rather than inherited from the consuming project's DEFAULT_PAGINATION_CLASS: this
is a published library, so the page size is part of its REST contract instead of varying by
deployment. One page is a slice of competencies, with the taxonomies, groups and criteria that
belong to them, so the view builds the page body itself rather than using this class's
``results`` envelope.
"""

page_size = 100
max_page_size = 500
17 changes: 17 additions & 0 deletions src/openedx_learning/applets/cbe/rest_api/v1/learner_urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
"""
CBE API v1 URLs for learners.
"""

from django.urls import re_path

from . import views

urlpatterns = [
# A broad pattern rather than the platform's COURSE_KEY_PATTERN, so every malformed value reaches the
# view and gets its 400, and old slash-separated course keys still match.
re_path(
r"^courses/(?P<course_key>.+)/criteria/$",
views.CourseCompetencyCriteriaView.as_view(),
name="course-criteria",
),
]
24 changes: 16 additions & 8 deletions src/openedx_learning/applets/cbe/rest_api/v1/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,21 @@ def validate(self, attrs: dict) -> dict:
MAX_COURSE_KEYS = 100


def parse_plain_course_key(value: str) -> CourseKey:
"""
Parse ``value`` into the plain course key the database stores, or raise InvalidKeyError.

Accepts course-v1, old slash-separated and CCX keys; library keys, usage keys and anything else are
rejected. A course key may carry a branch (draft or published copy) and a version (one saved
snapshot), and both are dropped to match what the database field holds. A version-only key has no
org, so it can't be turned into a plain key and is rejected.
"""
key = CourseKey.from_string(value)
if not isinstance(key, CourseLocator):
raise InvalidKeyError(type(key), value)
return key.for_branch(None)


class CompetencyCriteriaQueryParamsSerializer(serializers.Serializer):
"""Query params shared by the criteria-tree and blocked-courses read endpoints."""

Expand All @@ -200,14 +215,7 @@ def validate_course_keys(self, value: str) -> list[CourseKey]:
parsed = []
for entry in entries:
try:
key = CourseKey.from_string(entry)
if not isinstance(key, CourseLocator):
raise InvalidKeyError(type(key), entry)
# A course key may carry a branch (draft or published copy) and a version (one saved
# snapshot). The database field stores only the plain key, so we drop both here to
# match what it holds. A version-only key has no org, so it can't be turned into a
# plain key and is rejected.
key = key.for_branch(None)
key = parse_plain_course_key(entry)
except InvalidKeyError as exc:
raise serializers.ValidationError(
_("'%(entry)s' is not a valid course key.") % {"entry": entry}
Expand Down
Loading
Loading