[add]: db sessions

This commit is contained in:
VivianDee
2025-04-10 23:45:40 +01:00
parent a196d4d3c4
commit d397c834f4
7 changed files with 231 additions and 217 deletions
+22 -18
View File
@@ -23,13 +23,13 @@ class CustomerConsentService(BaseService):
dict: A standardized response. dict: A standardized response.
""" """
try: try:
with db.session.begin():
validated_data = CustomerConsentService.validate_data(data, CustomerConsentSchema())
account_id = validated_data.get('accountId')
customer_id = validated_data.get('customerId')
validated_data = CustomerConsentService.validate_data(data, CustomerConsentSchema()) if(CustomerConsentService.validate_account_ownership(account_id = account_id, customer_id = customer_id)):
account_id = validated_data.get('accountId')
customer_id = validated_data.get('customerId')
if(CustomerConsentService.validate_account_ownership(account_id = account_id, customer_id = customer_id)):
with db.session.begin():
transaction = CustomerConsentService.log_transaction(validated_data = validated_data) transaction = CustomerConsentService.log_transaction(validated_data = validated_data)
if not transaction: if not transaction:
@@ -37,23 +37,25 @@ class CustomerConsentService(BaseService):
return jsonify({ return jsonify({
"message": "Failed to log transaction." "message": "Failed to log transaction."
}), 400 }), 400
else: else:
return jsonify({ return jsonify({
"message": "Invalid Customer or Account" "message": "Invalid Customer or Account"
}), 400 }), 400
# Simulated processing logic # Simulated processing logic
response_data = { response_data = {
"resultCode": "00", "resultCode": "00",
"resultDescription": "Request is received" "resultDescription": "Request is received"
} }
return response_data db.session.commit()
return response_data
except ValidationError as err: except ValidationError as err:
logger.error(f"Validation Error: {getattr(err, 'messages', str(err))}") logger.error(f"Validation Error: {getattr(err, 'messages', str(err))}")
db.session.rollback()
return jsonify({ return jsonify({
"message": "Validation exception" "message": "Validation exception"
@@ -61,6 +63,7 @@ class CustomerConsentService(BaseService):
except ValueError as err: except ValueError as err:
logger.error(f"{getattr(err, 'messages', str(err))}") logger.error(f"{getattr(err, 'messages', str(err))}")
db.session.rollback()
return jsonify({ return jsonify({
"message": str(err) "message": str(err)
@@ -68,6 +71,7 @@ class CustomerConsentService(BaseService):
except Exception as e: except Exception as e:
logger.error(f"An error occurred: {str(e)}", exc_info=True) logger.error(f"An error occurred: {str(e)}", exc_info=True)
db.session.rollback()
return jsonify({ return jsonify({
"message": "Internal Server Error" "message": "Internal Server Error"
}) , 500 }) , 500
+55 -52
View File
@@ -22,17 +22,18 @@ class EligibilityCheckService(BaseService):
dict: A standardized response. dict: A standardized response.
""" """
try: try:
with db.session.begin():
validated_data = EligibilityCheckService.validate_data(data, EligibilityCheckSchema()) validated_data = EligibilityCheckService.validate_data(data, EligibilityCheckSchema())
account_id = validated_data.get('accountId') account_id = validated_data.get('accountId')
customer_id = validated_data.get('customerId') customer_id = validated_data.get('customerId')
transactionId = validated_data.get('transactionId') transactionId = validated_data.get('transactionId')
msisdn = validated_data.get('msisdn') msisdn = validated_data.get('msisdn')
customer = EligibilityCheckService.get_or_create_customer(validated_data = validated_data) customer = EligibilityCheckService.get_or_create_customer(validated_data = validated_data)
if (EligibilityCheckService.validate_account_ownership(account_id = account_id, customer_id = customer_id)): if (EligibilityCheckService.validate_account_ownership(account_id = account_id, customer_id = customer_id)):
with db.session.begin():
transaction = EligibilityCheckService.log_transaction(validated_data = validated_data) transaction = EligibilityCheckService.log_transaction(validated_data = validated_data)
if not transaction: if not transaction:
@@ -40,54 +41,56 @@ class EligibilityCheckService(BaseService):
return jsonify({ return jsonify({
"message": "Failed to log transaction." "message": "Failed to log transaction."
}), 400 }), 400
else:
return jsonify({ else:
"message": "Invalid Customer or Account" return jsonify({
}), 400 "message": "Invalid Customer or Account"
}), 400
# Call RACCheck
response = SimbrellaIntegration.rac_check( # Call RACCheck
customer_id = customer_id, response = SimbrellaIntegration.rac_check(
account_id = account_id, customer_id = customer_id,
transaction_id = transaction.id, account_id = account_id,
) transaction_id = transaction.id,
logger.error(f"This is Response Returned ****** : {str(response)}") )
logger.error(f"This is Response Returned ****** : {str(response)}")
# this chck for error is not valid # this chck for error is not valid
logger.error(f"Check for ERROR is not valid ****** FIX THIS !!!!!") logger.error(f"Check for ERROR is not valid ****** FIX THIS !!!!!")
#if "error" in response or response.get("status") != 200: #if "error" in response or response.get("status") != 200:
# return jsonify({"message": "RACCheck failed"}), 400 # return jsonify({"message": "RACCheck failed"}), 400
offers = [ offers = [
{ {
"offerId": "SAL90", "offerId": "SAL90",
"productId": "2030", "productId": "2030",
"minAmount": 5000, "minAmount": 5000,
"maxAmount": 100000, "maxAmount": 100000,
"tenor": 30 "tenor": 30
}, },
{ {
"offerId": "SAL30", "offerId": "SAL30",
"productId": "2090", "productId": "2090",
"minAmount": 3000, "minAmount": 3000,
"maxAmount": 500000, "maxAmount": 500000,
"tenor": 90 "tenor": 90
} }
] ]
# Simulate processing # Simulate processing
response_data = { response_data = {
"customerId": customer_id, "customerId": customer_id,
"transactionId": transactionId, "transactionId": transactionId,
"countryCode": "NG", "countryCode": "NG",
"msisdn": msisdn, "msisdn": msisdn,
"eligibleOffers": offers, "eligibleOffers": offers,
"resultDescription": "Successful", "resultDescription": "Successful",
"resultCode": "00", "resultCode": "00",
"accountId": account_id "accountId": account_id
} }
return response_data return response_data
except ValidationError as err: except ValidationError as err:
logger.error(f"Validation Error: {getattr(err, 'messages', str(err))}") logger.error(f"Validation Error: {getattr(err, 'messages', str(err))}")
+36 -40
View File
@@ -22,55 +22,49 @@ class LoanStatusService(BaseService):
dict: A standardized response. dict: A standardized response.
""" """
try: try:
validated_data = LoanStatusService.validate_data(data, LoanStatusSchema()) with db.session.begin():
customer_id = validated_data.get('customerId') validated_data = LoanStatusService.validate_data(data, LoanStatusSchema())
customer = LoanStatusService.get_or_create_customer(validated_data) customer_id = validated_data.get('customerId')
account = customer.accounts[0]
transaction = LoanStatusService.log_transaction(validated_data = validated_data)
if (LoanStatusService.validate_account_ownership(account_id = account.id, customer_id = customer_id)): if not transaction:
with db.session.begin(): logger.error(f"Failed to log transaction")
transaction = LoanStatusService.log_transaction(validated_data = validated_data) return jsonify({
"message": "Failed to log transaction."
if not transaction:
logger.error(f"Failed to log transaction")
return jsonify({
"message": "Failed to log transaction."
}), 400
else:
return jsonify({
"message": "Invalid Customer or Account"
}), 400 }), 400
loans = [ loans = [
{ {
"debtId": "123456789", "debtId": "123456789",
"loanDate": "2019-10-18 14:26:21.063", "loanDate": "2019-10-18 14:26:21.063",
"dueDate": "2019-11-20 14:26:21.063", "dueDate": "2019-11-20 14:26:21.063",
"currentLoanAmount": 8500, "currentLoanAmount": 8500,
"initialLoanAmount": 10000, "initialLoanAmount": 10000,
"defaultPenaltyFee": 0, "defaultPenaltyFee": 0,
"continuousFee": 0, "continuousFee": 0,
"productId": "101" "productId": "101"
}
]
# Simulated processing logic
response_data = {
"customerId": "CN621868",
"transactionId": "Tr201712RK9232P115",
"loans": loans,
"totalDebtAmount": 8500,
"resultCode": "00",
"resultDescription": "Successful"
} }
]
# Simulated processing logic db.session.commit()
response_data = { return response_data
"customerId": "CN621868",
"transactionId": "Tr201712RK9232P115",
"loans": loans,
"totalDebtAmount": 8500,
"resultCode": "00",
"resultDescription": "Successful"
}
return response_data
except ValidationError as err: except ValidationError as err:
logger.error(f"Validation Error: {getattr(err, 'messages', str(err))}") logger.error(f"Validation Error: {getattr(err, 'messages', str(err))}")
db.session.rollback()
return jsonify({ return jsonify({
"message": "Validation exception" "message": "Validation exception"
@@ -78,6 +72,7 @@ class LoanStatusService(BaseService):
except ValueError as err: except ValueError as err:
logger.error(f"{getattr(err, 'messages', str(err))}") logger.error(f"{getattr(err, 'messages', str(err))}")
db.session.rollback()
return jsonify({ return jsonify({
"message": str(err) "message": str(err)
@@ -85,6 +80,7 @@ class LoanStatusService(BaseService):
except Exception as e: except Exception as e:
logger.error(f"An error occurred: {str(e)}", exc_info=True) logger.error(f"An error occurred: {str(e)}", exc_info=True)
db.session.rollback()
return jsonify({ return jsonify({
"message": "Internal Server Error" "message": "Internal Server Error"
}) , 500 }) , 500
+34 -28
View File
@@ -26,15 +26,16 @@ class ProvideLoanService(BaseService):
dict: A standardized response. dict: A standardized response.
""" """
try: try:
validated_data = ProvideLoanService.validate_data(data, ProvideLoanSchema()) with db.session.begin():
account_id = validated_data.get('accountId') validated_data = ProvideLoanService.validate_data(data, ProvideLoanSchema())
customer_id = validated_data.get('customerId') account_id = validated_data.get('accountId')
request_id = validated_data.get('requestId') customer_id = validated_data.get('customerId')
transaction_id = validated_data.get('transactionId') request_id = validated_data.get('requestId')
transaction_id = validated_data.get('transactionId')
if (ProvideLoanService.validate_account_ownership(account_id = account_id, customer_id = customer_id)): if (ProvideLoanService.validate_account_ownership(account_id = account_id, customer_id = customer_id)):
with db.session.begin():
# Save the loan details # Save the loan details
loan = Loan.create_loan( loan = Loan.create_loan(
customer_id=customer_id, customer_id=customer_id,
@@ -50,6 +51,7 @@ class ProvideLoanService(BaseService):
"message": "Failed to save loan details." "message": "Failed to save loan details."
}), 400 }), 400
db.session.flush()
validated_data['refId'] = loan.id validated_data['refId'] = loan.id
validated_data['refModel'] = "loan" validated_data['refModel'] = "loan"
@@ -63,34 +65,36 @@ class ProvideLoanService(BaseService):
}), 400 }), 400
else: else:
return jsonify({ return jsonify({
"message": "Invalid Customer or Account" "message": "Invalid Customer or Account"
}), 400 }), 400
response_data = { response_data = {
"requestId": request_id, "requestId": request_id,
"transactionId": transaction_id, "transactionId": transaction_id,
"customerId": customer_id, "customerId": customer_id,
"accountId": account_id, "accountId": account_id,
"msisdn": "3451342", "msisdn": "3451342",
"resultCode": "00", "resultCode": "00",
"resultDescription": "Successful" "resultDescription": "Successful"
} }
# KafkaIntegration.send_loan_request(loan_data = response_data, request_id = request_id) # KafkaIntegration.send_loan_request(loan_data = response_data, request_id = request_id)
# Call Kafka in a background thread # Call Kafka in a background thread
thread = Thread(target=ProvideLoanService.async_send_to_kafka, args=(response_data, request_id, "PROCESS_PAYMENT")) thread = Thread(target=ProvideLoanService.async_send_to_kafka, args=(response_data, request_id, "PROCESS_PAYMENT"))
thread.start() thread.start()
return response_data db.session.commit()
return response_data
except ValidationError as err: except ValidationError as err:
logger.error(f"Validation Error: {getattr(err, 'messages', str(err))}") logger.error(f"Validation Error: {getattr(err, 'messages', str(err))}")
db.session.rollback()
return jsonify({ return jsonify({
"message": "Validation exception" "message": "Validation exception"
@@ -98,6 +102,7 @@ class ProvideLoanService(BaseService):
except ValueError as err: except ValueError as err:
logger.error(f"{getattr(err, 'messages', str(err))}") logger.error(f"{getattr(err, 'messages', str(err))}")
db.session.rollback()
return jsonify({ return jsonify({
"message": str(err) "message": str(err)
@@ -105,6 +110,7 @@ class ProvideLoanService(BaseService):
except Exception as e: except Exception as e:
logger.error(f"An error occurred: {str(e)}", exc_info=True) logger.error(f"An error occurred: {str(e)}", exc_info=True)
db.session.rollback()
return jsonify({ return jsonify({
"message": "Internal Server Error" "message": "Internal Server Error"
}) , 500 }) , 500
+30 -23
View File
@@ -25,14 +25,15 @@ class RepaymentService(BaseService):
dict: A standardized response. dict: A standardized response.
""" """
try: try:
validated_data = RepaymentService.validate_data(data, RepaymentSchema())
customer_id = validated_data.get('customerId')
request_id = validated_data.get('requestId')
loan_id = validated_data.get('debtId')
product_id = validated_data.get('productId')
with db.session.begin(): with db.session.begin():
validated_data = RepaymentService.validate_data(data, RepaymentSchema())
customer_id = validated_data.get('customerId')
request_id = validated_data.get('requestId')
loan_id = validated_data.get('debtId')
product_id = validated_data.get('productId')
# Save the repayment details # Save the repayment details
repayment = Repayment.create_repayment( repayment = Repayment.create_repayment(
customer_id = customer_id, customer_id = customer_id,
@@ -47,6 +48,8 @@ class RepaymentService(BaseService):
"message": "Failed to save repayment details." "message": "Failed to save repayment details."
}), 400 }), 400
db.session.flush()
validated_data['refId'] = repayment.id validated_data['refId'] = repayment.id
validated_data['refModel'] = "repayment" validated_data['refModel'] = "repayment"
@@ -62,29 +65,31 @@ class RepaymentService(BaseService):
}), 400 }), 400
# Simulated processing logic # Simulated processing logic
response_data = { response_data = {
"customerId": customer_id, "customerId": customer_id,
"productId": product_id, "productId": product_id,
"debtId": loan_id, "debtId": loan_id,
"resultCode": "00", "resultCode": "00",
"resultDescription": "Successful" "resultDescription": "Successful"
} }
# return ResponseHelper.success( # return ResponseHelper.success(
# data=response_data, # data=response_data,
# message="Repayment processed successfully" # message="Repayment processed successfully"
# ) # )
# Call Kafka in a background thread # Call Kafka in a background thread
thread = Thread(target=RepaymentService.async_send_to_kafka, args=(response_data, request_id, "LOAN_REPAYMENT")) thread = Thread(target=RepaymentService.async_send_to_kafka, args=(response_data, request_id, "LOAN_REPAYMENT"))
thread.start() thread.start()
return response_data db.session.commit()
return response_data
except ValidationError as err: except ValidationError as err:
logger.error(f"Validation Error: {getattr(err, 'messages', str(err))}") logger.error(f"Validation Error: {getattr(err, 'messages', str(err))}")
db.session.rollback()
return jsonify({ return jsonify({
"message": "Validation exception" "message": "Validation exception"
@@ -92,6 +97,7 @@ class RepaymentService(BaseService):
except ValueError as err: except ValueError as err:
logger.error(f"{getattr(err, 'messages', str(err))}") logger.error(f"{getattr(err, 'messages', str(err))}")
db.session.rollback()
return jsonify({ return jsonify({
"message": str(err) "message": str(err)
@@ -99,6 +105,7 @@ class RepaymentService(BaseService):
except Exception as e: except Exception as e:
logger.error(f"An error occurred: {str(e)}", exc_info=True) logger.error(f"An error occurred: {str(e)}", exc_info=True)
db.session.rollback()
return jsonify({ return jsonify({
"message": "Internal Server Error" "message": "Internal Server Error"
}) , 500 }) , 500
+53 -55
View File
@@ -1,13 +1,14 @@
from flask import request, jsonify from flask import request, jsonify
from marshmallow import ValidationError from marshmallow import ValidationError
from app.api.services.base_service import BaseService from app.api.services.base_service import BaseService
from app.api.enums import TransactionType from app.api.enums import TransactionType
from app.utils.logger import logger from app.utils.logger import logger
from app.api.schemas.select_offer import SelectOfferSchema from app.api.schemas.select_offer import SelectOfferSchema
from app.extensions import db from app.extensions import db
class SelectOfferService(BaseService): class SelectOfferService(BaseService):
TRANSACTION_TYPE = TransactionType.SELECT_OFFER TRANSACTION_TYPE = TransactionType.SELECT_OFFER
@staticmethod @staticmethod
def process_request(data): def process_request(data):
@@ -21,75 +22,72 @@ class SelectOfferService(BaseService):
dict: A standardized response. dict: A standardized response.
""" """
try: try:
validated_data = SelectOfferService.validate_data(data, SelectOfferSchema()) with db.session.begin():
account_id = validated_data.get('accountId') validated_data = SelectOfferService.validate_data(
customer_id = validated_data.get('customerId') data, SelectOfferSchema()
)
account_id = validated_data.get("accountId")
customer_id = validated_data.get("customerId")
if (SelectOfferService.validate_account_ownership(account_id = account_id, customer_id = customer_id)): if SelectOfferService.validate_account_ownership(
with db.session.begin(): account_id=account_id, customer_id=customer_id
transaction = SelectOfferService.log_transaction(validated_data = validated_data) ):
transaction = SelectOfferService.log_transaction(
validated_data=validated_data
)
if not transaction: if not transaction:
logger.error(f"Failed to log transaction") logger.error(f"Failed to log transaction")
return jsonify({ return jsonify({"message": "Failed to log transaction."}), 400
"message": "Failed to log transaction." else:
}), 400 return jsonify({"message": "Invalid Customer or Account"}), 400
else:
return jsonify({ offers = [
"message": "Invalid Customer or Account"
}), 400
offers = [
{ {
"offerId": "14451", "offerId": "14451",
"productId": "2030", "productId": "2030",
"amount": 10000.0, "amount": 10000.0,
"upfrontPayment": 1000.0, "upfrontPayment": 1000.0,
"interestRate": 3.0, "interestRate": 3.0,
"managementRate": 1.0, "managementRate": 1.0,
"managementFee": 1.0, "managementFee": 1.0,
"insuranceRate": 1.0, "insuranceRate": 1.0,
"insuranceFee": 100.0, "insuranceFee": 100.0,
"VATRate": 7.5, "VATRate": 7.5,
"VATAmount": 100.0, "VATAmount": 100.0,
"recommendedRepaymentDates": ["2022-11-30"], "recommendedRepaymentDates": ["2022-11-30"],
"installmentAmount": 11000.0, "installmentAmount": 11000.0,
"totalRepaymentAmount": 11000.0 "totalRepaymentAmount": 11000.0,
} }
] ]
# Business logic - selecting an offer # Business logic - selecting an offer
response_data = { response_data = {
"outstandingDebtAmount": 0, "outstandingDebtAmount": 0,
"requestId": "202111170001371256908", "requestId": "202111170001371256908",
"transactionId": transaction.id, "transactionId": transaction.id,
"customerId": customer_id, "customerId": customer_id,
"accountId": account_id, "accountId": account_id,
"loan": offers, "loan": offers,
"resultCode": "00", "resultCode": "00",
"resultDescription": "Successful" "resultDescription": "Successful",
} }
db.session.commit()
return response_data return response_data
except ValidationError as err: except ValidationError as err:
logger.error(f"Validation Error: {getattr(err, 'messages', str(err))}") logger.error(f"Validation Error: {getattr(err, 'messages', str(err))}")
db.session.rollback()
return jsonify({"message": "Validation exception"}), 422
return jsonify({ except ValueError as err:
"message": "Validation exception"
}) , 422
except ValueError as err:
logger.error(f"{getattr(err, 'messages', str(err))}") logger.error(f"{getattr(err, 'messages', str(err))}")
db.session.rollback()
return jsonify({ return jsonify({"message": str(err)}), 400
"message": str(err)
}) , 400
except Exception as e: except Exception as e:
logger.error(f"An error occurred: {str(e)}", exc_info=True) logger.error(f"An error occurred: {str(e)}", exc_info=True)
return jsonify({ db.session.rollback()
"message": "Internal Server Error" return jsonify({"message": "Internal Server Error"}), 500
}) , 500
+1 -1
View File
@@ -38,7 +38,7 @@ class Repayment(db.Model):
repayment = cls( repayment = cls(
customer_id=customer_id, customer_id=customer_id,
loan_id=loan.id, loan_id=loan_id,
product_id=product_id, product_id=product_id,
) )