Skip to content

Commit

Permalink
feat: update related batch to rejected_by_talpa
Browse files Browse the repository at this point in the history
  • Loading branch information
rikuke committed Jan 9, 2024
1 parent 3273422 commit 5a0f019
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 29 deletions.
67 changes: 40 additions & 27 deletions backend/benefit/applications/api/v1/talpa_integration_views.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import logging
from typing import List, Union

from django.contrib.auth.models import AnonymousUser
from django.db import transaction
from rest_framework import status
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView

from applications.api.v1.serializers.talpa_callback import TalpaCallbackSerializer
from applications.enums import ApplicationStatus
from applications.enums import ApplicationBatchStatus, ApplicationStatus
from applications.models import Application
from common.authentications import RobotBasicAuthentication
from common.utils import get_request_ip_address
Expand All @@ -25,34 +27,35 @@ def post(self, request, *args, **kwargs):
serializer = TalpaCallbackSerializer(data=request.data)

if serializer.is_valid():
if request.data["status"] == "Success":
ip_address = get_request_ip_address(request)

self._handle_successful_applications(
request.data["successful_applications"], ip_address
)
self._handle_failed_applications(request.data["failed_applications"])

else:
LOGGER.error(
f"Received a talpa callback with status: {request.data['status']}"
)
self.process_callback(serializer.validated_data, request)
return Response({"message": "Callback received"}, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

return Response(
{"message": "Callback received"},
status=status.HTTP_200_OK,
def process_callback(self, data, request):
if data["status"] == "Success":
self._handle_successful_applications(
data["successful_applications"], get_request_ip_address(request)
)
self._handle_failed_applications(data["failed_applications"])
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
LOGGER.error(f"Received a talpa callback with status: {data['status']}")

def _get_applications(self, application_numbers) -> Union[List[Application], None]:
applications = Application.objects.filter(
application_number__in=application_numbers
)
if not applications.exists() and application_numbers:
LOGGER.error(f"No applications found with numbers: {application_numbers}")
return None
return applications

def _handle_successful_applications(
self, application_numbers: list, ip_address: str
):
"""Add audit log entries for applications which were processed successfully by TALPA"""
if application_numbers:
successful_applications = Application.objects.filter(
application_number__in=application_numbers
)
successful_applications = self._get_applications(application_numbers)
if successful_applications:
for application in successful_applications:
audit_logging.log(
AnonymousUser,
Expand All @@ -63,10 +66,20 @@ def _handle_successful_applications(
additional_information="application was read succesfully by TALPA",
)

@transaction.atomic
def _handle_failed_applications(self, application_numbers: list):
"""Update applications which could not be processed with status REJECTED_BY_TALPA"""
if application_numbers:
applications = Application.objects.filter(
application_number__in=application_numbers
)
applications.update(status=ApplicationStatus.REJECTED_BY_TALPA)
"""Update applications and related batch which could not be processed with status REJECTED_BY_TALPA"""
applications = self._get_applications(application_numbers)
if applications:
try:
batch = applications.first().batch
if batch:
batch.status = ApplicationBatchStatus.REJECTED_BY_TALPA
batch.save()
applications.update(status=ApplicationStatus.REJECTED_BY_TALPA)
else:
LOGGER.error(
f"No batch associated with applications: {applications.values_list('id', flat=True)}"
)
except Exception as e:
LOGGER.error(f"Error updating batch and applications: {str(e)}")
1 change: 1 addition & 0 deletions backend/benefit/applications/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ class ApplicationBatchStatus(models.TextChoices):
) # Theoretically possible: means that a decision was not made
SENT_TO_TALPA = "sent_to_talpa", _("Sent to Talpa")
COMPLETED = "completed", _("Processing is completed")
REJECTED_BY_TALPA = "rejected_by_talpa", _("Rejected by Talpa")


class AhjoDecision(models.TextChoices):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 3.2.23 on 2024-01-09 08:57

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('applications', '0048_add_rejected_by_talpa_status'),
]

operations = [
migrations.AlterField(
model_name='applicationbatch',
name='status',
field=models.CharField(choices=[('draft', 'Draft'), ('exported_ahjo_report', 'Ahjo report created, not yet sent to AHJO'), ('awaiting_ahjo_decision', 'Sent to Ahjo, decision pending'), ('accepted', 'Accepted in Ahjo'), ('rejected', 'Rejected in Ahjo'), ('returned', 'Returned from Ahjo without decision'), ('sent_to_talpa', 'Sent to Talpa'), ('completed', 'Processing is completed'), ('rejected_by_talpa', 'Rejected by Talpa')], default='draft', max_length=64, verbose_name='status of batch'),
),
]
10 changes: 8 additions & 2 deletions backend/benefit/applications/tests/test_talpa_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import pytest
from django.urls import reverse

from applications.enums import ApplicationStatus
from applications.enums import ApplicationBatchStatus, ApplicationStatus
from applications.tests.common import (
check_csv_cell_list_lines_generator,
check_csv_string_lines_generator,
Expand Down Expand Up @@ -150,7 +150,12 @@ def test_talpa_callback_success(talpa_client, decided_application):


@pytest.mark.django_db
def test_talpa_callback_rejected_application(talpa_client, decided_application):
def test_talpa_callback_rejected_application(
talpa_client, decided_application, application_batch
):
decided_application.batch = application_batch
decided_application.save()

url = reverse(
"talpa_callback_url",
)
Expand All @@ -169,3 +174,4 @@ def test_talpa_callback_rejected_application(talpa_client, decided_application):
decided_application.refresh_from_db()

assert decided_application.status == ApplicationStatus.REJECTED_BY_TALPA
assert decided_application.batch.status == ApplicationBatchStatus.REJECTED_BY_TALPA

0 comments on commit 5a0f019

Please sign in to comment.