diff --git a/app/integrations/simbrella.py b/app/integrations/simbrella.py index a1f0f55..3f72188 100644 --- a/app/integrations/simbrella.py +++ b/app/integrations/simbrella.py @@ -4,6 +4,9 @@ from app.helpers.response_helper import ResponseHelper from app.services.loan import LoanService from app.utils.auth import get_headers from app.utils.extras import preprocess_loan_charges_data +import random +import random +import string from app.utils.logger import logger from flask import jsonify, current_app from app.services.transactions import TransactionService @@ -90,6 +93,9 @@ class SimbrellaClient: try: logger.info(f"Here is your Disbursement Request data ****** : {disbursement_data}") response = requests.post(api_url, json=disbursement_data, timeout=10, headers=get_headers()) + if response.status_code == 404: + logger.error("Received 404 from external service") + return ResponseHelper.error("Disbursement Service url not found (404)", status_code=404) logger.info(f"Disbursement response: {response.json()}") result = response.json() LoanService.set_disbursement_result(loan_data['debtId'],result.get('responseCode', ''), result.get('responseMessage', '')) @@ -154,6 +160,9 @@ class SimbrellaClient: try: logger.info(f"Here is your TransactionVerify Request data ****** : {verify_data}") response = requests.post(api_url, json=verify_data, timeout=10, headers=get_headers()) + if response.status_code == 404: + logger.error("Received 404 from external service") + return ResponseHelper.error("Verify Service url not found (404)", status_code=404) result = response.json() logger.info(f"this is verify result, {result}") LoanService.set_disburse_verify_result(loan_data['debtId'],result.get('responseCode', ''), result.get('responseMessage', '')) @@ -165,6 +174,7 @@ class SimbrellaClient: try: sms_response = requests.post(sms_url, json=sms_data, timeout=10, headers=get_headers()) sms_response.raise_for_status() # Raise an exception for 4xx or 5xx status codes + result = sms_response.json() logger.info(f"SMS Response JSON: {result}") if result.get('isSuccess'): @@ -241,14 +251,15 @@ class SimbrellaClient: repayment_data = repayment.to_dict() debtId = str(loan_data.get('debtId', "")).strip().zfill(6) + t_id = ''.join(random.choices(string.ascii_uppercase, k=22)) collect_loan_data = { - "transactionId": loan_data['transactionId'], + "transactionId": t_id, #made this a random string to avoid duplicate transaction with transactionId from Charles "fbnTransactionId": loan_data['transactionId'], "debtId": debtId, "customerId": repayment_data['customerId'], "accountId": loan_data['accountId'], "productId": repayment_data['productId'], - "collectAmount": loan_data['repaymentAmount'] or 0, + "collectAmount": loan_data['balance'] or 0, "penalCharge": 0, "channel": "USSD", "collectionMethod": collectionMethod, @@ -258,8 +269,17 @@ class SimbrellaClient: } try: - logger.info(f"Sending CollectLoan request: {collect_loan_data}") + logger.info(f"Sending CollectLoan request............ {collect_loan_data}") response = requests.post(api_url, json=collect_loan_data, timeout=30, headers=get_headers()) + logger.info(f"respnse structure {response}") + if response.status_code == 404: + RepaymentService.set_repay_result( + repayment_data['Id'], + '404', + 'Collection Service url not found') + logger.error("Received 404 from external service") + return ResponseHelper.error("Collection Service url not found", status_code=404) + result = response.json() logger.info(f"CollectLoan response: {result}") @@ -269,13 +289,9 @@ class SimbrellaClient: result.get('responseMessage', '') ) - if not result.get('transactionId'): - logger.error("Missing transactionId in response") - return ResponseHelper.error("Missing transactionId from Simbrella response", status_code=500) - data_to_add = { "transactionId": result.get('transactionId') or collect_loan_data.get('transactionId'), - "fbnTransactionId": result.get('fbnTransactionId') or collect_loan_data.get('fbnTransactionId'), + "fbnTransactionId": loan_data['transactionId'], "accountId": result.get('accountId') or collect_loan_data.get('accountId'), "customerId": result.get('customerId') or collect_loan_data.get('customerId'), "amountCollected": float(result.get('amountCollected', 0)), @@ -325,8 +341,8 @@ class SimbrellaClient: return ResponseHelper.success(result, "Successful") except Exception as e: - logger.exception("Failed to call CollectLoan endpoint") - return ResponseHelper.error("Failed to call CollectLoan endpoint") + logger.exception("Failed to call CollectLoan endpoint, {e}") + return ResponseHelper.error("Failed to process salary list", status_code=500, error=str(e)) @staticmethod diff --git a/app/models/repayment.py b/app/models/repayment.py index cc2f78d..451be6e 100644 --- a/app/models/repayment.py +++ b/app/models/repayment.py @@ -2,6 +2,8 @@ from app.extensions import db from datetime import datetime, timezone from app.utils.logger import logger from app.enums.loan_status import LoanStatus +from sqlalchemy.exc import IntegrityError + class Repayment(db.Model): __tablename__ = "repayments" @@ -51,7 +53,7 @@ class Repayment(db.Model): @classmethod def create_repayment(cls, repayment_data): - if repayment_data["LoanStatus"] not in [LoanStatus.ACTIVE, LoanStatus.START_REPAY]: + if repayment_data["LoanStatus"] not in [LoanStatus.ACTIVE, LoanStatus.START_REPAY,LoanStatus.ACTIVE_PARTIAL]: raise ValueError(f"Repayment cannot be processed. Loan status: ({repayment_data['LoanStatus']})") repayment = cls( @@ -70,9 +72,9 @@ class Repayment(db.Model): db.session.commit() logger.info("Repayment record committed.") return repayment - except InqtegrityError as err: + except IntegrityError as err: logger.error(f"Database integrity error: {err}") - return [q] + return {"error": "Integrity error", "details": str(err)} @classmethod