Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Updated assignment state to reversed upon transaction reversal #434

Closed
wants to merge 1 commit into from
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
6 changes: 5 additions & 1 deletion enterprise_access/apps/content_assignments/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class LearnerContentAssignmentStateChoices:
CANCELLED = 'cancelled'
ERRORED = 'errored'
EXPIRED = 'expired'
REVERSED = 'reversed'

CHOICES = (
(ALLOCATED, 'Allocated'),
Expand All @@ -22,7 +23,7 @@ class LearnerContentAssignmentStateChoices:
)

# States which allow reallocation by an admin.
REALLOCATE_STATES = (CANCELLED, ERRORED, EXPIRED)
REALLOCATE_STATES = (CANCELLED, ERRORED, EXPIRED, REVERSED)

# States which allow cancellation by an admin.
CANCELABLE_STATES = (ALLOCATED, ERRORED)
Expand All @@ -33,6 +34,9 @@ class LearnerContentAssignmentStateChoices:
# States from which an assignment can be expired
EXPIRABLE_STATES = (ALLOCATED,)

# States from which an assignment can be reversed
REVERSIBLE_STATES = (ALLOCATED,)


class AssignmentActions:
"""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Generated by Django 4.2.11 on 2024-04-05 11:44

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('content_assignments', '0018_alter_historicallearnercontentassignmentaction_action_type_and_more'),
]

operations = [
migrations.AddField(
model_name='historicallearnercontentassignment',
name='reversed_at',
field=models.DateTimeField(blank=True, help_text='The last time this assignment was reversed. Null means the assignment is not reversed.', null=True),
),
migrations.AddField(
model_name='learnercontentassignment',
name='reversed_at',
field=models.DateTimeField(blank=True, help_text='The last time this assignment was reversed. Null means the assignment is not reversed.', null=True),
),
]
5 changes: 5 additions & 0 deletions enterprise_access/apps/content_assignments/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,11 @@ class Meta:
blank=True,
help_text="The last time this assignment was in an error state. Null means the assignment is not errored.",
)
reversed_at = models.DateTimeField(
null=True,
blank=True,
help_text="The last time this assignment was reversed. Null means the assignment is not reversed.",
)
transaction_uuid = models.UUIDField(
blank=True,
null=True,
Expand Down
32 changes: 32 additions & 0 deletions enterprise_access/apps/content_assignments/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,14 @@

from django.db.models.signals import post_save
from django.dispatch import receiver
from openedx_events.enterprise.signals import SUBSIDY_REDEMPTION_REVERSED

from enterprise_access.apps.content_assignments.models import LearnerContentAssignment
from enterprise_access.apps.core.models import User
from enterprise_access.apps.subsidy_access_policy.models import SubsidyAccessPolicy
from enterprise_access.utils import localized_utcnow

from .constants import LearnerContentAssignmentStateChoices

logger = logging.getLogger(__name__)

Expand All @@ -34,3 +39,30 @@ def update_assignment_lms_user_id_from_user_email(sender, **kwargs): # pylint:
logger.info(
f'Set lms_user_id={user.lms_user_id} on {num_assignments_updated} assignments for User.id={user.id}'
)


@receiver(SUBSIDY_REDEMPTION_REVERSED)
def update_assignment_status_for_reversed_transaction(**kwargs):
"""
OEP-49 event handler to update assignment status for reversed transaction.
"""
redemption = kwargs.get('redemption')
subsidy_access_uuid = redemption.subsidy_identifier
content_key = redemption.content_key
lms_user_id = redemption.lms_user_id

try:
policy = SubsidyAccessPolicy.objects.get(uuid=subsidy_access_uuid)
assignment_to_update = policy.get_assignment(lms_user_id, content_key)
except SubsidyAccessPolicy.DoesNotExist:
logger.error(
f'Unable to access policy {subsidy_access_uuid} for content_key {content_key} and {lms_user_id}'
)
if assignment_to_update and assignment_to_update.state in LearnerContentAssignmentStateChoices.REVERSIBLE_STATES:
assignment_to_update.state = LearnerContentAssignmentStateChoices.REVERSED
assignment_to_update.reversed_at = localized_utcnow()
assignment_to_update.save()
logger.info(
f'Content assignment {assignment_to_update.uuid} for content_key {content_key} and \
{lms_user_id} reversed.'
)
90 changes: 89 additions & 1 deletion enterprise_access/apps/content_assignments/tests/test_signals.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
"""
Signals and handlers tests.
"""
from unittest import mock
from uuid import uuid4

from django.test import TestCase
from django.utils import timezone
from openedx_events.enterprise.data import SubsidyRedemption
from openedx_events.enterprise.signals import SUBSIDY_REDEMPTION_REVERSED

from enterprise_access.apps.content_assignments.tests.factories import LearnerContentAssignmentFactory
from enterprise_access.apps.content_assignments.constants import LearnerContentAssignmentStateChoices
from enterprise_access.apps.content_assignments.signals import update_assignment_status_for_reversed_transaction
from enterprise_access.apps.content_assignments.tests.factories import (
AssignmentConfigurationFactory,
LearnerContentAssignmentFactory
)
from enterprise_access.apps.core.tests.factories import UserFactory
from enterprise_access.apps.subsidy_access_policy.tests.factories import AssignedLearnerCreditAccessPolicyFactory

TEST_EMAIL = '[email protected]'

Expand All @@ -14,6 +25,38 @@ class SignalsTests(TestCase):
"""
Tests for signals and handlers.
"""
def setUp(self):
super().setUp()
self.subsidy_redemption = SubsidyRedemption(
subsidy_identifier='31164bce-e95c-49ef-b578-b1236d3e6e50',
content_key='test-course-1',
lms_user_id='1543675'
)
self.user = UserFactory(lms_user_id=self.subsidy_redemption.lms_user_id)
self.enterprise_uuid = uuid4()
self.assignment_configuration = AssignmentConfigurationFactory(
enterprise_customer_uuid=self.enterprise_uuid,
)
self.assigned_learner_credit_policy = AssignedLearnerCreditAccessPolicyFactory(
uuid=self.subsidy_redemption.subsidy_identifier,
display_name='An assigned learner credit policy, for the test customer.',
enterprise_customer_uuid=self.enterprise_uuid,
active=True,
assignment_configuration=self.assignment_configuration,
spend_limit=1000000,
)
self.content_title = 'edx: Demo 101'
self.assigned_price_cents = 25000
self.assignment = LearnerContentAssignmentFactory.create(
assignment_configuration=self.assignment_configuration,
learner_email='[email protected]',
lms_user_id=self.user.lms_user_id,
content_key=self.subsidy_redemption.content_key,
content_title=self.content_title,
content_quantity=-self.assigned_price_cents,
state=LearnerContentAssignmentStateChoices.ALLOCATED,
)
self.receiver_called = False

def test_update_assignment_lms_user_id_from_user_email_registration(self):
"""
Expand Down Expand Up @@ -71,3 +114,48 @@ def test_update_assignment_lms_user_id_from_user_email_other_assignments(self):
for assignment in assignments_other_learner:
assignment.refresh_from_db()
assert assignment.lms_user_id is None

def _event_receiver_side_effect(self, **kwargs):
"""
Used show that the Open edX Event was called by the Django signal handler.
"""
self.receiver_called = True

def test_send_subsidy_reversal_event(self):
"""
Test the send and receive for the subsidy reversal event.
Expected result:
- SUBSIDY_REDEMPTION_REVERSED is sent and received by the mocked receiver.
- The arguments that the receiver gets are the arguments sent by the event
except the metadata generated on the fly.
"""
event_receiver = mock.Mock(side_effect=self._event_receiver_side_effect)
SUBSIDY_REDEMPTION_REVERSED.connect(event_receiver)
SUBSIDY_REDEMPTION_REVERSED.send_event(
redemption=self.subsidy_redemption,
)
self.assertTrue(self.receiver_called)
self.assertEqual(
event_receiver.call_args.kwargs['redemption'].subsidy_identifier,
self.subsidy_redemption.subsidy_identifier
)
self.assertEqual(
event_receiver.call_args.kwargs['redemption'].content_key,
self.subsidy_redemption.content_key
)
self.assertEqual(
event_receiver.call_args.kwargs['redemption'].lms_user_id,
self.subsidy_redemption.lms_user_id
)

@mock.patch('enterprise_access.apps.subsidy_access_policy.models.assignments_api')
def test_subsidy_reversal_event_processing(self, mock_assignments_api):
"""
Test the receive and correct processing for the subsidy reversal event.
Expected result:
- The receiver processes the event correctly and updates the assignment status.
"""
mock_assignments_api.get_assignment_for_learner.return_value = self.assignment
SUBSIDY_REDEMPTION_REVERSED.connect(update_assignment_status_for_reversed_transaction)
SUBSIDY_REDEMPTION_REVERSED.send_event(redemption=self.subsidy_redemption)
self.assertEqual(self.assignment.state, LearnerContentAssignmentStateChoices.REVERSED)
2 changes: 1 addition & 1 deletion requirements/base.txt
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ oauthlib==3.2.2
# social-auth-core
openapi-codec==1.3.2
# via django-rest-swagger
openedx-events==9.5.2
openedx-events==9.7.0
# via -r requirements/base.in
packaging==24.0
# via drf-yasg
Expand Down
2 changes: 1 addition & 1 deletion requirements/dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ openapi-codec==1.3.2
# via
# -r requirements/validation.txt
# django-rest-swagger
openedx-events==9.5.2
openedx-events==9.7.0
# via -r requirements/validation.txt
packaging==24.0
# via
Expand Down
2 changes: 1 addition & 1 deletion requirements/doc.txt
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ openapi-codec==1.3.2
# via
# -r requirements/test.txt
# django-rest-swagger
openedx-events==9.5.2
openedx-events==9.7.0
# via -r requirements/test.txt
packaging==24.0
# via
Expand Down
2 changes: 1 addition & 1 deletion requirements/production.txt
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ openapi-codec==1.3.2
# via
# -r requirements/base.txt
# django-rest-swagger
openedx-events==9.5.2
openedx-events==9.7.0
# via -r requirements/base.txt
packaging==24.0
# via
Expand Down
2 changes: 1 addition & 1 deletion requirements/quality.txt
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ openapi-codec==1.3.2
# via
# -r requirements/test.txt
# django-rest-swagger
openedx-events==9.5.2
openedx-events==9.7.0
# via -r requirements/test.txt
packaging==24.0
# via
Expand Down
2 changes: 1 addition & 1 deletion requirements/test.txt
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ openapi-codec==1.3.2
# via
# -r requirements/base.txt
# django-rest-swagger
openedx-events==9.5.2
openedx-events==9.7.0
# via -r requirements/base.txt
packaging==24.0
# via
Expand Down
2 changes: 1 addition & 1 deletion requirements/validation.txt
Original file line number Diff line number Diff line change
Expand Up @@ -504,7 +504,7 @@ openapi-codec==1.3.2
# -r requirements/quality.txt
# -r requirements/test.txt
# django-rest-swagger
openedx-events==9.5.2
openedx-events==9.7.0
# via
# -r requirements/quality.txt
# -r requirements/test.txt
Expand Down
Loading