refactor(verification): enhance error handling and response structure in user verification process 🔨

This commit is contained in:
2025-07-15 23:04:11 +05:00
parent eee314af46
commit d64a2675e4
2 changed files with 35 additions and 27 deletions

View File

@ -1,5 +1,5 @@
import logging
from typing import List, TypedDict
from typing import List, Optional, TypedDict
import requests
from decouple import config
from api.models import User
@ -40,7 +40,9 @@ def reverse_dhivehi_string(input_str):
class MismatchResult(TypedDict):
ok: bool
mismatch_fields: List[str]
mismatch_fields: Optional[List[str]]
error: Optional[str]
detail: Optional[str]
def check_person_api_verification(
@ -63,20 +65,22 @@ def check_person_api_verification(
raise ValueError(
"PERSON_VERIFY_BASE_URL is not set in the environment variables."
)
print(id_card)
response = requests.get(f"{PERSON_VERIFY_BASE_URL}/api/person/{id_card}")
api_reponse = response.json()
if response.status_code != 200:
logger.error(
f"Failed to fetch data from Person API for ID Card '{id_card}'. "
f"Status Code: {response.status_code}, Response: {response.text}"
)
return {"ok": False, "mismatch_fields": ["api_error"]}
api_data = response.json()
if not api_data:
logger.error(
f"No data found in Person API for ID Card '{id_card}'. Response: {response.text}"
)
return {"ok": False, "mismatch_fields": ["no_data"]}
return {
"ok": False,
"mismatch_fields": None,
"error": response.json()["error"] if "error" in response.json() else None,
"detail": response.json()["detail"]
if "detail" in response.json()
else None,
}
# Initialize a list to hold fields that do not match
mismatch_fields = []
@ -86,12 +90,12 @@ def check_person_api_verification(
user_dob_iso = user_data.dob.isoformat() if user_data.dob else None
# Prepare API data for comparison
api_nic = api_data.get("nic")
api_name = api_data.get("name_en")
api_house_name = api_data.get("house_name_en")
api_dob = api_data.get("dob")
api_atoll = api_data.get("atoll_en")
api_island_name = api_data.get("island_name_en")
api_nic = api_reponse.get("nic")
api_name = api_reponse.get("name_en")
api_house_name = api_reponse.get("house_name_en")
api_dob = api_reponse.get("dob")
api_atoll = api_reponse.get("atoll_en")
api_island_name = api_reponse.get("island_name_en")
# Perform comparisons and identify mismatches
if user_data.id_card != api_nic:
@ -134,6 +138,11 @@ def check_person_api_verification(
)
if mismatch_fields:
return {"ok": False, "mismatch_fields": mismatch_fields}
return {
"ok": False,
"mismatch_fields": mismatch_fields,
"error": None,
"detail": None,
}
else:
return {"ok": True, "mismatch_fields": []}
return {"ok": True, "mismatch_fields": [], "error": None, "detail": None}