Skip to content

Commit 73a0d54

Browse files
committed
fixup! feat(pathways): implement CatalogPathway
1 parent c0047cd commit 73a0d54

9 files changed

Lines changed: 300 additions & 203 deletions

File tree

‎src/openedx_catalog/admin.py‎

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from django.utils.html import format_html
1414
from django.utils.translation import gettext_lazy as _
1515

16+
from .api import get_default_pathway_category
1617
from .models import (
1718
CatalogCourse,
1819
CatalogPathway,
@@ -124,16 +125,17 @@ def warnings(self, obj: CourseRun) -> str | None:
124125

125126
class PathwayCategoryTranslationInline(admin.TabularInline):
126127
"""
127-
The category's name in languages other than the instance's default.
128+
The category's title in languages other than the instance's default.
128129
129-
Learners whose language has no translation here see the category's own name.
130+
Learners whose language has no translation here see the category's own title.
130131
"""
131132

132133
model = PathwayCategoryTranslation
133-
fields = ["language_code", "name"]
134+
fields = ["language_code", "title"]
134135
extra = 0
135136

136137

138+
@admin.register(PathwayCategory)
137139
class PathwayCategoryAdmin(admin.ModelAdmin):
138140
"""
139141
The PathwayCategory model admin.
@@ -142,8 +144,8 @@ class PathwayCategoryAdmin(admin.ModelAdmin):
142144
"Pathway".
143145
"""
144146

145-
list_display = ["name", "category_code", "pathways_summary"]
146-
search_fields = ["name", "category_code", "translations__name"]
147+
list_display = ["title", "category_code", "pathways_summary"]
148+
search_fields = ["title", "category_code", "translations__title"]
147149
inlines = [PathwayCategoryTranslationInline]
148150

149151
def get_readonly_fields(self, request, obj: PathwayCategory | None = None) -> tuple[str, ...]:
@@ -154,7 +156,8 @@ def get_readonly_fields(self, request, obj: PathwayCategory | None = None) -> tu
154156
def get_queryset(self, request) -> QuerySet[PathwayCategoryWithPathwayCount]:
155157
"""Add the 'pathway_count' to the list_display queryset"""
156158
qs = super().get_queryset(request)
157-
qs = qs.annotate(pathway_count=Count("pathways"))
159+
# distinct, because searching joins in the translations, which would otherwise multiply the count.
160+
qs = qs.annotate(pathway_count=Count("pathways", distinct=True))
158161
return qs
159162

160163
@admin.display(description=_("Pathways"), ordering="pathway_count")
@@ -166,9 +169,7 @@ def pathways_summary(self, obj: PathwayCategoryWithPathwayCount) -> str:
166169
return format_html('<a href="{}">{}</a>', url, obj.pathway_count)
167170

168171

169-
admin.site.register(PathwayCategory, PathwayCategoryAdmin)
170-
171-
172+
@admin.register(CatalogPathway)
172173
class CatalogPathwayAdmin(admin.ModelAdmin):
173174
"""
174175
The CatalogPathway model admin.
@@ -186,6 +187,17 @@ def get_readonly_fields(self, request, obj: CatalogPathway | None = None) -> tup
186187
return ("org", "pathway_code")
187188
return tuple()
188189

190+
def get_changeform_initial_data(self, request) -> dict[str, str | list[str]]:
191+
"""Preselect the default category on the add form, if the operator hasn't deleted it."""
192+
initial = super().get_changeform_initial_data(request)
193+
if "category" not in initial:
194+
try:
195+
# Initial data is typed like query parameters, as strings; the form compares the pk as a string anyway.
196+
initial["category"] = str(get_default_pathway_category().pk)
197+
except PathwayCategory.DoesNotExist:
198+
pass
199+
return initial
200+
189201
@admin.display(description="Organization", ordering="org__short_name")
190202
def org_display(self, obj: CatalogPathway) -> str:
191203
"""Display the organization, only showing the short_name if different from full name"""
@@ -199,9 +211,7 @@ def created_date(self, obj: CatalogPathway) -> datetime.date:
199211
return obj.created.date()
200212

201213

202-
admin.site.register(CatalogPathway, CatalogPathwayAdmin)
203-
204-
214+
@admin.register(PathwayEnrollment)
205215
class PathwayEnrollmentAdmin(admin.ModelAdmin):
206216
"""
207217
The PathwayEnrollment model admin.
@@ -216,6 +226,3 @@ class PathwayEnrollmentAdmin(admin.ModelAdmin):
216226
def created_date(self, obj: PathwayEnrollment) -> datetime.date:
217227
"""Display the enrollment date without the timestamp"""
218228
return obj.created.date()
219-
220-
221-
admin.site.register(PathwayEnrollment, PathwayEnrollmentAdmin)

‎src/openedx_catalog/api_impl.py‎

Lines changed: 42 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,14 @@
55
import logging
66
from typing import overload
77

8-
from django.db import transaction
98
from django.db.models import QuerySet
109
from django.utils import timezone
1110
from opaque_keys.edx.keys import CourseKey
1211
from organizations.api import ensure_organization # type: ignore[import]
1312
from organizations.api import exceptions as org_exceptions
1413

1514
from .models import CatalogCourse, CatalogPathway, CourseRun, PathwayCategory, PathwayEnrollment
16-
from .models.pathway_category import get_default_pathway_category
15+
from .models.pathway_category import DEFAULT_PATHWAY_CATEGORY_CODE
1716

1817
log = logging.getLogger(__name__)
1918

@@ -273,15 +272,31 @@ def delete_course_run(course_key: CourseKey) -> None:
273272
# half; creating and versioning the *definition* of a Pathway is done through `openedx_learning.api`.
274273

275274

276-
# `get_default_pathway_category` is part of this API too, and is re-exported via `__all__`. It's defined next to the
277-
# model because the `CatalogPathway.category` field default needs it as well.
275+
def get_default_pathway_category() -> PathwayCategory:
276+
"""
277+
Get the default `PathwayCategory`: the one `create_catalog_pathway` uses when it isn't given a category.
278+
279+
Rather than falling back to the word "Pathway" in code, the initial migration ships a database row with that title,
280+
so that operators can rename it or add categories of their own without a code change (see the openedx_learning
281+
ADR 0007). Renaming it keeps it the default, because only its ``title`` changes; its ``category_code`` can't.
282+
283+
Nothing ever creates this category except that migration. If an operator has deleted it, this raises
284+
`PathwayCategory.DoesNotExist`, and catalog pathways have to be given a category explicitly.
285+
"""
286+
try:
287+
return PathwayCategory.objects.get(category_code=DEFAULT_PATHWAY_CATEGORY_CODE)
288+
except PathwayCategory.DoesNotExist as exc:
289+
raise PathwayCategory.DoesNotExist(
290+
f'The default pathway category ("{DEFAULT_PATHWAY_CATEGORY_CODE}") has been deleted, so catalog pathways '
291+
"must be given a category explicitly."
292+
) from exc
278293

279294

280295
def get_pathway_category(category_code: str) -> PathwayCategory:
281296
"""
282297
Get a `PathwayCategory` by its stable code.
283298
284-
Its translations come with it, so ``category.localized_name`` costs no further queries, however often it's read.
299+
Its translations come with it, so ``category.localized_title`` costs no further queries, however often it's read.
285300
286301
⚠️ Does not check permissions.
287302
"""
@@ -292,7 +307,7 @@ def _catalog_pathways() -> QuerySet[CatalogPathway]:
292307
"""
293308
Catalog pathways along with everything needed to show them: org, category, and the category's translations.
294309
295-
With the translations prefetched, ``pathway.category.localized_name`` costs no further queries.
310+
With the translations prefetched, ``pathway.category.localized_title`` costs no further queries.
296311
"""
297312
return CatalogPathway.objects.select_related("org", "category").prefetch_related("category__translations")
298313

@@ -314,7 +329,7 @@ def get_catalog_pathway(
314329
"""
315330
Get a catalog pathway.
316331
317-
Its org and category come with it, and so do the category's translations, so ``pathway.category.localized_name``
332+
Its org and category come with it, and so do the category's translations, so ``pathway.category.localized_title``
318333
costs no further queries.
319334
320335
⚠️ Does not check permissions or visibility rules.
@@ -345,7 +360,7 @@ def get_catalog_pathways(
345360
346361
Both filters match exactly; an unknown org or category simply matches nothing. The result is a `QuerySet`, so that
347362
callers can narrow, search and paginate it further. Each pathway's org and category come with it, and so do the
348-
category's translations, so ``pathway.category.localized_name`` costs no further queries.
363+
category's translations, so ``pathway.category.localized_title`` costs no further queries.
349364
350365
⚠️ Does not check permissions or visibility rules. That suits authoring and administration, but a listing shown to
351366
learners will need the visibility logic described in the `openedx_catalog.api` docstring, which doesn't exist yet.
@@ -372,21 +387,17 @@ def create_catalog_pathway(
372387
"""
373388
Create a `CatalogPathway`.
374389
375-
The `Organization` identified by `org_code` must already exist. Pass `category=None` to use the default category.
390+
The `Organization` identified by `org_code` must already exist. Pass `category=None` to use the default category,
391+
which raises `PathwayCategory.DoesNotExist` if an operator has deleted it (see `get_default_pathway_category`).
376392
377393
This creates only the catalog half of a Pathway. Use `openedx_learning.api` to create the versioned content that
378394
implements it.
379395
380396
⚠️ Does not check permissions.
381397
"""
382-
pathway = CatalogPathway(
383-
pathway_code=pathway_code,
384-
title=title,
385-
description=description,
386-
# Only pass the category if given, so that the field default (which queries for the shipped category) runs
387-
# only when it's actually needed.
388-
**({"category": category} if category is not None else {}),
389-
)
398+
if category is None:
399+
category = get_default_pathway_category()
400+
pathway = CatalogPathway(pathway_code=pathway_code, title=title, category=category, description=description)
390401
pathway.org_code = org_code # Resolves the Organization by short_name; raises Organization.DoesNotExist.
391402
pathway.save()
392403
return pathway
@@ -427,10 +438,12 @@ def update_catalog_pathway(
427438

428439
def delete_catalog_pathway(catalog_pathway: CatalogPathway | CatalogPathway.ID) -> None:
429440
"""
430-
Delete a `CatalogPathway`, along with its enrollments.
441+
Delete a `CatalogPathway`.
431442
432-
This will fail with a `ProtectedError` if any Pathway content still implements it, because that link is a `PROTECT`
433-
foreign key on the content side.
443+
This fails with a `ProtectedError` while anyone is or ever was enrolled in it, including learners who have since
444+
unenrolled, so that deleting the wrong pathway can't wipe out enrollment history; delete those enrollments first if
445+
that's really intended. It also fails while any Pathway content still implements it, because that link is a
446+
`PROTECT` foreign key on the content side.
434447
435448
⚠️ Does not check permissions.
436449
"""
@@ -451,17 +464,16 @@ def enroll_in_pathway(user_id: int, catalog_pathway: CatalogPathway | CatalogPat
451464
Enrollment does not pin a content version: progress is always evaluated against whatever is published at the time,
452465
so that authoring changes reach learners who are already enrolled.
453466
467+
Raises `CatalogPathway.DoesNotExist` if given the ID of a pathway that doesn't exist.
468+
454469
⚠️ Does not check permissions.
455470
"""
456-
pathway_id = catalog_pathway.id if isinstance(catalog_pathway, CatalogPathway) else catalog_pathway
457-
with transaction.atomic():
458-
# Lock the row so a concurrent unenroll can't slip in between reading `is_active` and writing it back.
459-
enrollment, created = PathwayEnrollment.objects.select_for_update().get_or_create(
460-
user_id=user_id, catalog_pathway_id=pathway_id
461-
)
462-
if not created and not enrollment.is_active:
463-
enrollment.is_active = True
464-
enrollment.save(update_fields=["is_active", "modified"])
471+
if not isinstance(catalog_pathway, CatalogPathway):
472+
catalog_pathway = CatalogPathway.objects.get(pk=catalog_pathway)
473+
enrollment, created = PathwayEnrollment.objects.get_or_create(user_id=user_id, catalog_pathway=catalog_pathway)
474+
if not created and not enrollment.is_active:
475+
enrollment.is_active = True
476+
enrollment.save(update_fields=["is_active", "modified"])
465477
return enrollment
466478

467479

@@ -495,7 +507,7 @@ def get_pathway_enrollments(user_id: int, *, include_inactive: bool = False) ->
495507
496508
Only active enrollments are returned unless ``include_inactive`` is set. Each enrollment's catalog pathway comes
497509
with it, along with the pathway's org, category and the category's translations, so a dashboard can show
498-
``enrollment.catalog_pathway.category.localized_name`` without further queries.
510+
``enrollment.catalog_pathway.category.localized_title`` without further queries.
499511
500512
⚠️ Does not check permissions or visibility rules.
501513
"""

‎src/openedx_catalog/migrations/0002_pathways.py‎

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -17,22 +17,21 @@
1717
from django.conf import settings
1818
from django.db import migrations, models
1919

20-
import openedx_catalog.models.pathway_category
2120
import openedx_django_lib.fields
2221
import openedx_django_lib.validators
2322

2423
# These values are duplicated from openedx_catalog.models.pathway_category rather than imported, because a migration
2524
# should represent a point-in-time transformation and must not change if those constants later do.
2625
DEFAULT_CATEGORY_CODE = "pathway"
27-
DEFAULT_CATEGORY_NAME = "Pathway"
26+
DEFAULT_CATEGORY_TITLE = "Pathway"
2827

2928

3029
def create_default_pathway_category(apps, schema_editor):
3130
"""Create the default category."""
3231
PathwayCategory = apps.get_model("openedx_catalog", "PathwayCategory")
3332
PathwayCategory.objects.get_or_create(
3433
category_code=DEFAULT_CATEGORY_CODE,
35-
defaults={"name": DEFAULT_CATEGORY_NAME},
34+
defaults={"title": DEFAULT_CATEGORY_TITLE},
3635
)
3736

3837

@@ -56,7 +55,7 @@ class Migration(migrations.Migration):
5655
fields=[
5756
(
5857
"id",
59-
models.BigAutoField(
58+
models.AutoField(
6059
editable=False,
6160
help_text="The internal database ID for this pathway category. Should not be exposed to users nor in APIs.",
6261
primary_key=True,
@@ -80,18 +79,18 @@ class Migration(migrations.Migration):
8079
),
8180
),
8281
(
83-
"name",
82+
"title",
8483
openedx_django_lib.fields.MultiCollationCharField(
8584
db_collations={"mysql": "utf8mb4_unicode_ci", "sqlite": "NOCASE"},
86-
help_text='The learner-facing name of this category, e.g. "Master\'s Degree". Operators may change this.',
85+
help_text='The learner-facing title of this category, e.g. "Master\'s Degree". Operators may change this.',
8786
max_length=255,
8887
),
8988
),
9089
],
9190
options={
9291
"verbose_name": "Pathway Category",
9392
"verbose_name_plural": "Pathway Categories",
94-
"ordering": ("name",),
93+
"ordering": ("title",),
9594
"constraints": [
9695
models.UniqueConstraint(
9796
django.db.models.functions.text.Lower("category_code"),
@@ -103,7 +102,7 @@ class Migration(migrations.Migration):
103102
violation_error_message='Enter a valid "code name" consisting of latin letters (A-Z, a-z), numbers, underscores, hyphens, or periods.',
104103
),
105104
models.CheckConstraint(
106-
condition=models.Q(("name__length__gt", 0)), name="oex_catalog_pathwaycategory_name_not_blank"
105+
condition=models.Q(("title__length__gt", 0)), name="oex_catalog_pathwaycategory_title_not_blank"
107106
),
108107
],
109108
},
@@ -117,7 +116,7 @@ class Migration(migrations.Migration):
117116
fields=[
118117
(
119118
"id",
120-
models.BigAutoField(
119+
models.AutoField(
121120
editable=False,
122121
help_text="The internal database ID for this translation. Should not be exposed to users nor in APIs.",
123122
primary_key=True,
@@ -129,15 +128,15 @@ class Migration(migrations.Migration):
129128
"language_code",
130129
openedx_django_lib.fields.MultiCollationCharField(
131130
db_collations={"mysql": "utf8mb4_bin", "sqlite": "BINARY"},
132-
help_text='The language of this name, as in the LANGUAGES setting: a lowercase ISO 639-1 code, optionally followed by a hyphen and a country/locale code, e.g. "fr", "pt-br", "zh-cn".',
131+
help_text='The language of this title, as in the LANGUAGES setting: a lowercase ISO 639-1 code, optionally followed by a hyphen and a country/locale code, e.g. "fr", "pt-br", "zh-cn".',
133132
max_length=64,
134133
),
135134
),
136135
(
137-
"name",
136+
"title",
138137
openedx_django_lib.fields.MultiCollationCharField(
139138
db_collations={"mysql": "utf8mb4_unicode_ci", "sqlite": "NOCASE"},
140-
help_text="The learner-facing name of the category in this language.",
139+
help_text="The learner-facing title of the category in this language.",
141140
max_length=255,
142141
),
143142
),
@@ -165,8 +164,8 @@ class Migration(migrations.Migration):
165164
violation_error_message='The language code must be lowercase, e.g. "fr". If a country/locale code is provided, it must be separated by a hyphen, e.g. "pt-br", "zh-cn".',
166165
),
167166
models.CheckConstraint(
168-
condition=models.Q(("name__length__gt", 0)),
169-
name="oex_catalog_pathwaycategorytranslation_name_not_blank",
167+
condition=models.Q(("title__length__gt", 0)),
168+
name="oex_catalog_pathwaycategorytranslation_title_not_blank",
170169
),
171170
],
172171
},
@@ -243,8 +242,7 @@ class Migration(migrations.Migration):
243242
(
244243
"category",
245244
models.ForeignKey(
246-
default=openedx_catalog.models.pathway_category.get_default_pathway_category_id,
247-
help_text="The learner-facing kind of pathway this is. Always required; defaults to a category we ship.",
245+
help_text="The learner-facing kind of pathway this is.",
248246
on_delete=django.db.models.deletion.PROTECT,
249247
related_name="pathways",
250248
to="openedx_catalog.pathwaycategory",
@@ -290,7 +288,7 @@ class Migration(migrations.Migration):
290288
(
291289
"catalog_pathway",
292290
models.ForeignKey(
293-
on_delete=django.db.models.deletion.CASCADE,
291+
on_delete=django.db.models.deletion.PROTECT,
294292
related_name="enrollments",
295293
to="openedx_catalog.catalogpathway",
296294
),

0 commit comments

Comments
 (0)