from flask import request, jsonify from marshmallow import ValidationError from app.api.services.base_service import BaseService from app.api.enums import TransactionType from app.utils.logger import logger from app.api.schemas.select_offer import SelectOfferSchema from app.extensions import db class SelectOfferService(BaseService): TRANSACTION_TYPE = TransactionType.SELECT_OFFER @staticmethod def process_request(data): """ Process the SelectOffer request. Args: data (dict): The request data. Returns: dict: A standardized response. """ try: with db.session.begin(): validated_data = SelectOfferService.validate_data( 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 ): transaction = SelectOfferService.log_transaction( validated_data=validated_data ) 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 offers = [ { "offerId": "14451", "productId": "2030", "amount": 10000.0, "upfrontPayment": 1000.0, "interestRate": 3.0, "managementRate": 1.0, "managementFee": 1.0, "insuranceRate": 1.0, "insuranceFee": 100.0, "VATRate": 7.5, "VATAmount": 100.0, "recommendedRepaymentDates": ["2022-11-30"], "installmentAmount": 11000.0, "totalRepaymentAmount": 11000.0, } ] # Business logic - selecting an offer response_data = { "outstandingDebtAmount": 0, "requestId": "202111170001371256908", "transactionId": transaction.id, "customerId": customer_id, "accountId": account_id, "loan": offers, "resultCode": "00", "resultDescription": "Successful", } db.session.commit() return response_data except ValidationError as err: logger.error(f"Validation Error: {getattr(err, 'messages', str(err))}") db.session.rollback() return jsonify({"message": "Validation exception"}), 422 except ValueError as err: logger.error(f"{getattr(err, 'messages', str(err))}") db.session.rollback() return jsonify({"message": str(err)}), 400 except Exception as e: logger.error(f"An error occurred: {str(e)}", exc_info=True) db.session.rollback() return jsonify({"message": "Internal Server Error"}), 500