diff --git a/learning_resources/models.py b/learning_resources/models.py index 72bbdb4780..0f0769dbaa 100644 --- a/learning_resources/models.py +++ b/learning_resources/models.py @@ -255,8 +255,11 @@ def prices(self) -> list[Decimal]: LearningResourceType.course.name, LearningResourceType.program.name, ]: - next_run = self.next_run - return next_run.prices if next_run else [] + next_run = ( + self.next_run + or self.runs.filter(published=True).order_by("-start_date").first() + ) + return next_run.prices if next_run and next_run.prices else [] else: return [Decimal(0.00)] diff --git a/learning_resources/models_test.py b/learning_resources/models_test.py index 4f0db4d45c..823105e1a4 100644 --- a/learning_resources/models_test.py +++ b/learning_resources/models_test.py @@ -1,10 +1,15 @@ """Tests for learning_resources.models""" +from datetime import timedelta +from decimal import Decimal + import pytest +from django.db.models import F from learning_resources.constants import LearningResourceType from learning_resources.factories import ( CourseFactory, + LearningResourceRunFactory, ProgramFactory, ) @@ -48,3 +53,30 @@ def test_course_creation(): assert resource.offered_by is not None assert resource.runs.count() == course.runs.count() assert resource.prices == resource.next_run.prices + + +def test_course_prices_current_no_next(): + """Test that course.prices == most recent run prices if no next run""" + course = CourseFactory.create() + resource = course.learning_resource + resource.runs.update(start_date=F("start_date") - timedelta(days=3650)) + unpub_run = LearningResourceRunFactory.create( + learning_resource=resource, published=False, prices=[Decimal("987654.32")] + ) + resource.refresh_from_db() + most_recent_run = resource.runs.filter(published=True).order_by("start_date").last() + assert most_recent_run != unpub_run + assert resource.next_run is None + # Prices should be from most recent published run if no next run + assert resource.prices == most_recent_run.prices + assert len(resource.prices) > 0 + + +def test_course_prices_unpublished_runs(): + """Test that course.prices == [] if no published run""" + course = CourseFactory.create() + resource = course.learning_resource + resource.runs.update(published=False) + resource.refresh_from_db() + assert resource.next_run is None + assert resource.prices == []