Compare commits
64 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7026c8378b | |||
| b22d2f358e | |||
| f13ca508c2 | |||
| 87f1fa2152 | |||
| 2c34c16c34 | |||
| 1b973322c9 | |||
| edd19b9a39 | |||
| 773dedcd5b | |||
| eb4bcb025d | |||
| 37d808c144 | |||
| 1f86d30c3a | |||
| 946818dae6 | |||
| 333e48d32a | |||
| 6e24b498dc | |||
| cbf57f4bfb | |||
| bae92d36c6 | |||
| dd2da9c462 | |||
| f20563a9b1 | |||
| 85671081ec | |||
| 53cff748ed | |||
| 3b098969e2 | |||
| 751bcb7d28 | |||
| 25ccb240ca | |||
| de4554e247 | |||
| e1b3f4930e | |||
| 900d7b509c | |||
| 31ffbe686a | |||
| 7b0d19c0e0 | |||
| 7087254859 | |||
| d2d9603914 | |||
| f2b5703bcb | |||
| 49c3422c94 | |||
| 07f1db2050 | |||
| 7cbe3aefea | |||
| e7ae1f6732 | |||
| 30233b7283 | |||
| 3a30e0abff | |||
| d3b9708216 | |||
| 0e8bc63b4d | |||
| cbc9d6363e | |||
| 24fe303304 | |||
| 681ac19028 | |||
| d2ffe1c439 | |||
| 12fc6d0ab6 | |||
| 04e5548a4a | |||
| 823ae9e2a7 | |||
| d16978d023 | |||
| 5c38094c22 | |||
| 907b4d1f38 | |||
| 5ff1f2c8bf | |||
| 01b433e7e3 | |||
| a5f3119cdc | |||
| ec2ec07d60 | |||
| 76fc959e2e | |||
| 362f31c100 | |||
| a4df4912d6 | |||
| 87fe0fb5a0 | |||
| f6a3938901 | |||
| aac09bb3a1 | |||
| 19870edf73 | |||
| 4f2f3cccb4 | |||
| 41109d5353 | |||
| 35a54e98ee | |||
| bcb7a27863 |
@@ -7,6 +7,9 @@ BASIC_AUTH_PASSWORD=******
|
||||
SWAGGER_URL="/documentation"
|
||||
API_URL="/swagger.json"
|
||||
|
||||
JWT_SECRET_KEY=******
|
||||
JWT_ACCESS_TOKEN_EXPIRES=******
|
||||
JWT_REFRESH_TOKEN_EXPIRES=******
|
||||
|
||||
|
||||
DATABASE_USER=*****
|
||||
|
||||
+3
-1
@@ -3,4 +3,6 @@ __pycache__/
|
||||
app.log
|
||||
.DS_Store
|
||||
migrations/__pycache__/
|
||||
migrations/*.pycg
|
||||
migrations/*.pycg
|
||||
./vscode
|
||||
.vscode/settings.json
|
||||
|
||||
Vendored
+24
@@ -0,0 +1,24 @@
|
||||
// {
|
||||
// "editor.lineNumbers": "off",
|
||||
// "editor.padding.top": 3,
|
||||
// "editor.padding.bottom": 3,
|
||||
// "editor.formatOnSave": true,
|
||||
// "editor.formatOnPaste": true,
|
||||
// "editor.fontSize": 14,
|
||||
// "editor.lineHeight": 4.5,
|
||||
// "editor.suggestFontSize": 15,
|
||||
// // "editor.suggestLineHeight": 4,
|
||||
// "breadcrumbs.enabled": false,
|
||||
// "workbench.tips.enabled": false,
|
||||
// "workbench.statusBar.visible": false,
|
||||
// // "workbench.editor.showTabs": "single",
|
||||
// "git.enableSmartCommit": true,
|
||||
// "workbench.editor.editorActionsLocation": "hidden",
|
||||
// // "workbench.activityBar.location": "hidden",
|
||||
// "workbench.editor.enablePreviewFromQuickOpen": false,
|
||||
// "editor.lightbulb.enabled": "off",
|
||||
// "editor.selectionHighlight": false,
|
||||
// "editor.overviewRulerBorder": false,
|
||||
// "editor.renderLineHighlight": "none",
|
||||
// "editor.occurrencesHighlight": "off"
|
||||
// }
|
||||
@@ -0,0 +1,14 @@
|
||||
|
||||
CREATE TABLE transactions (
|
||||
id SERIAL,
|
||||
transaction_id VARCHAR(50) NOT NULL,
|
||||
account_id VARCHAR(50) NOT NULL,
|
||||
type VARCHAR(50) NOT NULL,
|
||||
channel VARCHAR(8) NOT NULL,
|
||||
created_at timestamp with time zone DEFAULT now(),
|
||||
updated_at timestamp with time zone DEFAULT now()
|
||||
);
|
||||
ALTER TABLE ONLY transactions
|
||||
ADD CONSTRAINT transactions_id_key UNIQUE (id);
|
||||
|
||||
|
||||
+13
-7
@@ -8,38 +8,44 @@ from app.errors import register_error_handlers
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
from app.extensions import db, migrate
|
||||
from flask_jwt_extended import (
|
||||
JWTManager,
|
||||
jwt_required,
|
||||
create_access_token,
|
||||
get_jwt_identity,
|
||||
)
|
||||
|
||||
|
||||
def create_app():
|
||||
""" Factory function to create a Flask app instance """
|
||||
"""Factory function to create a Flask app instance"""
|
||||
app = Flask(__name__)
|
||||
|
||||
# Load configuration
|
||||
app.config.from_object(Config)
|
||||
|
||||
CORS(app)
|
||||
|
||||
JWTManager(app)
|
||||
CORS(app, supports_credentials=True)
|
||||
|
||||
# Swagger Doc
|
||||
SWAGGER_URL = app.config.get("SWAGGER_URL")
|
||||
API_URL = app.config.get("API_URL")
|
||||
|
||||
|
||||
# Register blueprints
|
||||
app.register_blueprint(api)
|
||||
|
||||
swagger_ui_blueprint = get_swaggerui_blueprint(SWAGGER_URL, API_URL)
|
||||
app.register_blueprint(swagger_ui_blueprint, url_prefix=SWAGGER_URL)
|
||||
|
||||
|
||||
# Error Handlers
|
||||
register_error_handlers(app)
|
||||
|
||||
|
||||
from . import models
|
||||
|
||||
# Database and Migrations
|
||||
db.init_app(app)
|
||||
|
||||
|
||||
|
||||
migrate.init_app(app, db)
|
||||
|
||||
|
||||
return app
|
||||
|
||||
@@ -5,32 +5,35 @@ from app.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class KafkaIntegration:
|
||||
_producer = None
|
||||
_config = {
|
||||
'bootstrap.servers': settings.KAFKA_BROKER,
|
||||
'client.id': 'loan-service-producer',
|
||||
'acks': 'all',
|
||||
'retries': 3,
|
||||
'debug': 'broker,topic,msg'
|
||||
"bootstrap.servers": settings.KAFKA_BROKER,
|
||||
"client.id": "loan-service-producer",
|
||||
"acks": "all",
|
||||
"retries": 3,
|
||||
"debug": "broker,topic,msg",
|
||||
}
|
||||
|
||||
|
||||
@staticmethod
|
||||
def _get_producer():
|
||||
"""Kafka producer"""
|
||||
if not KafkaIntegration._producer:
|
||||
KafkaIntegration._producer = Producer(KafkaIntegration._config)
|
||||
logger.info(f"Connected to Kafka broker at {KafkaIntegration._config['bootstrap.servers']}")
|
||||
|
||||
logger.info(
|
||||
f"Connected to Kafka broker at {KafkaIntegration._config['bootstrap.servers']}"
|
||||
)
|
||||
|
||||
return KafkaIntegration._producer
|
||||
|
||||
|
||||
|
||||
@staticmethod
|
||||
def delivery_report(err, msg):
|
||||
"""Called once for each message produced"""
|
||||
if err is not None:
|
||||
|
||||
logger.error(f'Message delivery failed: {err}')
|
||||
raise RuntimeError(f"Message delivery failed: {err}")
|
||||
|
||||
@@ -39,18 +42,16 @@ class KafkaIntegration:
|
||||
|
||||
|
||||
|
||||
|
||||
@staticmethod
|
||||
def send_loan_request(loan_data, request_id):
|
||||
"""
|
||||
Send loan request to PROCESS_PAYMENT topic
|
||||
|
||||
|
||||
Args:
|
||||
loan_data: Loan request payload as dict
|
||||
request_id: Unique request identifier (used as Kafka key)
|
||||
"""
|
||||
try:
|
||||
|
||||
|
||||
# Proceed to send loan request to Kafka
|
||||
producer = KafkaIntegration._get_producer()
|
||||
@@ -59,8 +60,9 @@ class KafkaIntegration:
|
||||
producer.produce(
|
||||
topic="PROCESS_PAYMENT",
|
||||
key=str(request_id),
|
||||
value=json.dumps(loan_data).encode('utf-8'),
|
||||
callback=KafkaIntegration.delivery_report
|
||||
value=json.dumps(loan_data).encode("utf-8"),
|
||||
callback=KafkaIntegration.delivery_report,
|
||||
|
||||
)
|
||||
|
||||
producer.poll(0)
|
||||
@@ -68,10 +70,11 @@ class KafkaIntegration:
|
||||
logger.info(f"Loan request {request_id} queued for processing")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to send loan request to Kafka: {str(e)}", exc_info=True)
|
||||
logger.error(
|
||||
f"Failed to send loan request to Kafka: {str(e)}", exc_info=True
|
||||
)
|
||||
raise Exception(f"Failed to send loan request to Kafka: {str(e)}")
|
||||
|
||||
|
||||
@staticmethod
|
||||
def flush():
|
||||
"""Shutdown"""
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import requests
|
||||
import json
|
||||
from requests.auth import HTTPBasicAuth
|
||||
from app.utils.logger import logger
|
||||
from app.config import settings
|
||||
|
||||
@@ -33,11 +35,19 @@ class SimbrellaIntegration:
|
||||
]
|
||||
}
|
||||
|
||||
try:
|
||||
response = requests.post(url, json=payload, timeout=10)
|
||||
logger.error(f"This is PayLoad: {str(payload)}",exc_info=True)
|
||||
headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'x-api-key': f'{settings.VALID_API_KEY}',
|
||||
'App-Id': f'{settings.VALID_APP_ID}'
|
||||
}
|
||||
|
||||
try:
|
||||
response = requests.post(url, json=payload, timeout=10, headers=headers)
|
||||
logger.error(f"This is Response: {str(response)}", exc_info=True)
|
||||
# Raise an error for non-200 responses
|
||||
response.raise_for_status()
|
||||
if response.status_code != 200:
|
||||
response.raise_for_status()
|
||||
|
||||
return response.json()
|
||||
except requests.exceptions.RequestException as err:
|
||||
|
||||
+48
-21
@@ -6,11 +6,19 @@ from app.api.services import (
|
||||
LoanStatusService,
|
||||
RepaymentService,
|
||||
CustomerConsentService,
|
||||
NotificationCallbackService
|
||||
NotificationCallbackService,
|
||||
AuthorizationService,
|
||||
)
|
||||
from app.utils.logger import logger
|
||||
from app.api.middlewares import enforce_json, require_auth
|
||||
from app.api.middlewares import enforce_json, require_auth
|
||||
import os
|
||||
from flask_jwt_extended import (
|
||||
JWTManager,
|
||||
jwt_required,
|
||||
create_access_token,
|
||||
get_jwt_identity,
|
||||
create_refresh_token,
|
||||
)
|
||||
|
||||
|
||||
api = Blueprint("api", __name__)
|
||||
@@ -23,31 +31,31 @@ def cors_middleware():
|
||||
|
||||
|
||||
# Swagger JSON file
|
||||
@api.route("/swagger.json", methods=['GET'])
|
||||
@api.route("/swagger.json", methods=["GET"])
|
||||
def swagger_json():
|
||||
swagger_dir = os.path.join("swagger")
|
||||
return send_from_directory(swagger_dir, "digifi_swagger.json")
|
||||
|
||||
|
||||
|
||||
@api.route('/swagger/<path:filename>')
|
||||
@api.route("/swagger/<path:filename>")
|
||||
def serve_paths(filename):
|
||||
swagger_dir = os.path.join("swagger")
|
||||
return send_from_directory(swagger_dir, filename)
|
||||
|
||||
|
||||
# EligibilityCheck Endpoint
|
||||
@api.route('/EligibilityCheck', methods=['POST'])
|
||||
@require_auth
|
||||
@api.route("/EligibilityCheck", methods=["POST"])
|
||||
@jwt_required()
|
||||
def eligibility_check():
|
||||
data = request.get_json()
|
||||
# logger.info(f"EligibilityCheck request received: {data}")
|
||||
response = EligibilityCheckService.process_request(data)
|
||||
return response
|
||||
|
||||
|
||||
# SelectOffer Endpoint
|
||||
@api.route('/SelectOffer', methods=['POST'])
|
||||
@require_auth
|
||||
@api.route("/SelectOffer", methods=["POST"])
|
||||
@jwt_required()
|
||||
def select_offer():
|
||||
data = request.get_json()
|
||||
# logger.info(f"SelectOffer request received: {data}")
|
||||
@@ -56,8 +64,8 @@ def select_offer():
|
||||
|
||||
|
||||
# ProvideLoan Endpoint
|
||||
@api.route('/ProvideLoan', methods=['POST'])
|
||||
@require_auth
|
||||
@api.route("/ProvideLoan", methods=["POST"])
|
||||
@jwt_required()
|
||||
def provide_loan():
|
||||
data = request.get_json()
|
||||
# logger.info(f"ProvideLoan request received: {data}")
|
||||
@@ -66,8 +74,8 @@ def provide_loan():
|
||||
|
||||
|
||||
# LoanStatus Endpoint
|
||||
@api.route('/LoanStatus', methods=['POST'])
|
||||
@require_auth
|
||||
@api.route("/LoanStatus", methods=["POST"])
|
||||
@jwt_required()
|
||||
def loan_status():
|
||||
data = request.get_json()
|
||||
# logger.info(f"LoanStatus request received: {data}")
|
||||
@@ -76,8 +84,8 @@ def loan_status():
|
||||
|
||||
|
||||
# Repayment Endpoint
|
||||
@api.route('/Repayment', methods=['POST'])
|
||||
@require_auth
|
||||
@api.route("/Repayment", methods=["POST"])
|
||||
@jwt_required()
|
||||
def repayment():
|
||||
data = request.get_json()
|
||||
# logger.info(f"Repayment request received: {data}")
|
||||
@@ -86,8 +94,8 @@ def repayment():
|
||||
|
||||
|
||||
# CustomerConsent Endpoint
|
||||
@api.route('/CustomerConsent', methods=['POST'])
|
||||
@require_auth
|
||||
@api.route("/CustomerConsent", methods=["POST"])
|
||||
@jwt_required()
|
||||
def customer_consent():
|
||||
data = request.get_json()
|
||||
# logger.info(f"CustomerConsent request received: {data}")
|
||||
@@ -96,8 +104,8 @@ def customer_consent():
|
||||
|
||||
|
||||
# NotificationCallback Endpoint
|
||||
@api.route('/NotificationCallback', methods=['POST'])
|
||||
@require_auth
|
||||
@api.route("/NotificationCallback", methods=["POST"])
|
||||
@jwt_required()
|
||||
def notification_callback():
|
||||
data = request.get_json()
|
||||
# logger.info(f"NotificationCallback request received: {data}")
|
||||
@@ -106,6 +114,25 @@ def notification_callback():
|
||||
|
||||
|
||||
# Health Check Endpoint
|
||||
@api.route('/health', methods=['GET'])
|
||||
@api.route("/health", methods=["GET"])
|
||||
def health_check():
|
||||
return {"status": "ok"} , 200
|
||||
return {"status": "ok"}, 200
|
||||
|
||||
|
||||
# Authorize endpoint
|
||||
@api.route("/Authorize", methods=["POST"])
|
||||
def authorize():
|
||||
data = request.get_json()
|
||||
# logger.info(f"Authorize request received: {data}")
|
||||
response = AuthorizationService.process_request(data)
|
||||
return response
|
||||
|
||||
|
||||
# Authorize refresh endpoint
|
||||
@api.route("/AuthorizeRefresh", methods=["POST"])
|
||||
@jwt_required(refresh=True)
|
||||
def refresh():
|
||||
data = request.get_json()
|
||||
# logger.info(f"Authorize refresh request received: {data}")
|
||||
response = AuthorizationService.process_refresh_request()
|
||||
return response
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
from marshmallow import Schema, fields
|
||||
|
||||
|
||||
class AuthorizeRequestSchema(Schema):
|
||||
username = fields.Str(required=True)
|
||||
password = fields.Str(required=True)
|
||||
@@ -8,8 +8,8 @@ class ProvideLoanSchema(Schema):
|
||||
customerId = fields.Str(required=True)
|
||||
accountId = fields.Str(required=True)
|
||||
msisdn = fields.Str(required=False)
|
||||
productId = fields.Str(required=True)
|
||||
lienAmount = fields.Float(required=True)
|
||||
# productId = fields.Str(required=True)
|
||||
# lienAmount = fields.Float(required=True)
|
||||
requestedAmount = fields.Float(required=True)
|
||||
collectionType = fields.Int(required=True)
|
||||
offerId = fields.Int(required=True)
|
||||
|
||||
@@ -4,4 +4,5 @@ from app.api.services.provide_loan import ProvideLoanService
|
||||
from app.api.services.loan_status import LoanStatusService
|
||||
from app.api.services.repayment import RepaymentService
|
||||
from app.api.services.customer_consent import CustomerConsentService
|
||||
from app.api.services.notification_callback import NotificationCallbackService
|
||||
from app.api.services.notification_callback import NotificationCallbackService
|
||||
from app.api.services.authorization import AuthorizationService
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
from flask import request, jsonify
|
||||
from marshmallow import ValidationError
|
||||
from app.api.services.base_service import BaseService
|
||||
from app.utils.logger import logger
|
||||
from app.api.schemas.authorization import AuthorizeRequestSchema
|
||||
from app.api.helpers.response_helper import ResponseHelper
|
||||
from flask_jwt_extended import (
|
||||
JWTManager,
|
||||
jwt_required,
|
||||
create_access_token,
|
||||
create_refresh_token,
|
||||
get_jwt_identity,
|
||||
)
|
||||
from app.config import Config
|
||||
|
||||
USERNAME = Config.BASIC_AUTH_USERNAME
|
||||
PASSWORD = Config.BASIC_AUTH_PASSWORD
|
||||
|
||||
|
||||
class AuthorizationService(BaseService):
|
||||
|
||||
@staticmethod
|
||||
def process_request(data):
|
||||
"""
|
||||
Process the Authorization request.
|
||||
|
||||
Args:
|
||||
data (dict): The request data.
|
||||
|
||||
Returns:
|
||||
dict: A standardized response.
|
||||
"""
|
||||
try:
|
||||
logger.info("Processing Authorization request")
|
||||
|
||||
if not data:
|
||||
return ResponseHelper.bad_request(message="Missing JSON in request")
|
||||
|
||||
# Validate input data using the Authorization schema
|
||||
schema = AuthorizeRequestSchema()
|
||||
validated_data = schema.load(data) # Raises ValidationError if invalid
|
||||
|
||||
if (
|
||||
validated_data["username"] != USERNAME
|
||||
or validated_data["password"] != PASSWORD
|
||||
):
|
||||
return ResponseHelper.unauthorized(message="Invalid credentials")
|
||||
|
||||
access_token = create_access_token(identity=validated_data["username"])
|
||||
refresh_token = create_refresh_token(identity=validated_data["username"])
|
||||
|
||||
# Simulated processing logic
|
||||
response_data = {
|
||||
"access_token": access_token,
|
||||
"refresh_token": refresh_token,
|
||||
}
|
||||
|
||||
return ResponseHelper.success(
|
||||
data=response_data, message="Authorization processed successfully"
|
||||
)
|
||||
|
||||
except ValidationError as e:
|
||||
logger.error(f"Validation error: {e}")
|
||||
return ResponseHelper.bad_request(message=f"Validation error: {e}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing Authorization request: {e}")
|
||||
return ResponseHelper.internal_server_error(
|
||||
message=f"Error processing Authorization request: {e}"
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def process_refresh_request():
|
||||
"""
|
||||
Process the RefreshToken request.
|
||||
|
||||
Args:
|
||||
data (dict): The request data.
|
||||
|
||||
Returns:
|
||||
dict: A standardized response.
|
||||
"""
|
||||
try:
|
||||
logger.info("Processing RefreshToken request")
|
||||
|
||||
identity = get_jwt_identity()
|
||||
access_token = create_access_token(identity=identity)
|
||||
|
||||
# Simulated processing logic
|
||||
response_data = {
|
||||
"access_token": access_token,
|
||||
}
|
||||
|
||||
return ResponseHelper.success(
|
||||
data=response_data, message="RefreshToken processed successfully"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing RefreshToken request: {e}")
|
||||
return ResponseHelper.internal_server_error(
|
||||
message=f"Error processing RefreshToken request: {e}"
|
||||
)
|
||||
@@ -48,7 +48,7 @@ class BaseService:
|
||||
Create a new transaction.
|
||||
"""
|
||||
return Transaction.create_transaction(
|
||||
id=validated_data.get("transactionId"),
|
||||
transaction_id =validated_data.get("transactionId"),
|
||||
account_id=validated_data.get("accountId"),
|
||||
type=cls.TRANSACTION_TYPE,
|
||||
channel=validated_data.get("channel"),
|
||||
|
||||
@@ -25,6 +25,8 @@ class EligibilityCheckService(BaseService):
|
||||
validated_data = EligibilityCheckService.validate_data(data, EligibilityCheckSchema())
|
||||
account_id = validated_data.get('accountId')
|
||||
customer_id = validated_data.get('customerId')
|
||||
transactionId = validated_data.get('transactionId')
|
||||
msisdn = validated_data.get('msisdn')
|
||||
|
||||
customer = EligibilityCheckService.get_or_create_customer(validated_data = validated_data)
|
||||
|
||||
@@ -47,39 +49,40 @@ class EligibilityCheckService(BaseService):
|
||||
account_id = account_id,
|
||||
transaction_id = transaction.id,
|
||||
)
|
||||
logger.error(f"This is Response Returned ****** : {str(response)}")
|
||||
|
||||
if "error" in response or response.get("status") != 200:
|
||||
return jsonify({"message": "RACCheck failed"}), 400
|
||||
|
||||
|
||||
# this chck for error is not valid
|
||||
logger.error(f"Check for ERROR is not valid ****** FIX THIS !!!!!")
|
||||
#if "error" in response or response.get("status") != 200:
|
||||
# return jsonify({"message": "RACCheck failed"}), 400
|
||||
|
||||
offers = [
|
||||
{
|
||||
"offerId": "Offer1",
|
||||
"productId": "Product1",
|
||||
"minAamount": 100,
|
||||
"maxAamount": 1000,
|
||||
"tenor": 12
|
||||
"offerId": "SAL90",
|
||||
"productId": "2030",
|
||||
"minAmount": 5000,
|
||||
"maxAmount": 100000,
|
||||
"tenor": 30
|
||||
},
|
||||
{
|
||||
"offerId": "Offer2",
|
||||
"productId": "Product2",
|
||||
"minAamount": 200,
|
||||
"maxAamount": 2000,
|
||||
"tenor": 24
|
||||
"offerId": "SAL30",
|
||||
"productId": "2090",
|
||||
"minAmount": 3000,
|
||||
"maxAmount": 500000,
|
||||
"tenor": 90
|
||||
}
|
||||
]
|
||||
|
||||
# Simulate processing
|
||||
response_data = {
|
||||
"customerId": "CN621868",
|
||||
"transactionId": "TX12345",
|
||||
"customerId": customer_id,
|
||||
"transactionId": transactionId,
|
||||
"countryCode": "NG",
|
||||
"msisdn": "3451342",
|
||||
"msisdn": msisdn,
|
||||
"eligibleOffers": offers,
|
||||
"resultDescription": "Successful",
|
||||
"resultCode": "00",
|
||||
"accountId": "ACN8263457"
|
||||
"accountId": account_id
|
||||
}
|
||||
|
||||
return response_data
|
||||
|
||||
@@ -7,6 +7,7 @@ from app.utils.logger import logger
|
||||
from app.api.schemas.provide_loan import ProvideLoanSchema
|
||||
from app.api.integrations import KafkaIntegration
|
||||
from threading import Thread
|
||||
from app.models.loan import Loan
|
||||
|
||||
|
||||
class ProvideLoanService(BaseService):
|
||||
@@ -29,8 +30,10 @@ class ProvideLoanService(BaseService):
|
||||
account_id = validated_data.get('accountId')
|
||||
customer_id = validated_data.get('customerId')
|
||||
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)):
|
||||
|
||||
transaction = ProvideLoanService.log_transaction(validated_data = validated_data)
|
||||
|
||||
if not transaction:
|
||||
@@ -38,6 +41,25 @@ class ProvideLoanService(BaseService):
|
||||
return jsonify({
|
||||
"message": "Failed to log transaction."
|
||||
}), 400
|
||||
|
||||
# Save the loan details
|
||||
loan_id = f"loan_{transaction_id}"
|
||||
|
||||
loan = Loan.create_loan(
|
||||
customer_id=customer_id,
|
||||
account_id=account_id,
|
||||
offer_id=validated_data.get('offerId'),
|
||||
principal_amount=validated_data.get('requestedAmount'),
|
||||
status="active"
|
||||
)
|
||||
|
||||
if not loan:
|
||||
logger.error(f"Failed to save loan details")
|
||||
return jsonify({
|
||||
"message": "Failed to save loan details."
|
||||
}), 400
|
||||
|
||||
|
||||
else:
|
||||
return jsonify({
|
||||
"message": "Invalid Customer or Account"
|
||||
@@ -46,7 +68,7 @@ class ProvideLoanService(BaseService):
|
||||
|
||||
response_data = {
|
||||
"requestId": request_id,
|
||||
"transactionId": "Tr201712RK9232P115",
|
||||
"transactionId": transaction_id,
|
||||
"customerId": customer_id,
|
||||
"accountId": account_id,
|
||||
"msisdn": "3451342",
|
||||
@@ -88,4 +110,3 @@ class ProvideLoanService(BaseService):
|
||||
KafkaIntegration.send_loan_request(loan_data = loan_data, request_id = request_id)
|
||||
KafkaIntegration.flush()
|
||||
|
||||
|
||||
|
||||
@@ -21,10 +21,13 @@ class RepaymentService(BaseService):
|
||||
"""
|
||||
try:
|
||||
validated_data = RepaymentService.validate_data(data, RepaymentSchema())
|
||||
account_id = validated_data.get('accountId')
|
||||
customer_id = validated_data.get('customerId')
|
||||
customer = RepaymentService.get_or_create_customer(validated_data)
|
||||
account = customer.accounts[0]
|
||||
validated_data['accountId'] = account.id
|
||||
|
||||
if (RepaymentService.validate_account_ownership(account_id = account_id, customer_id = customer_id)):
|
||||
|
||||
if (RepaymentService.validate_account_ownership(account_id = account.id, customer_id = customer_id)):
|
||||
transaction = RepaymentService.log_transaction(validated_data = validated_data)
|
||||
|
||||
if not transaction:
|
||||
|
||||
@@ -3,7 +3,7 @@ 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.api.schemas.select_offer import SelectOfferSchema
|
||||
|
||||
class SelectOfferService(BaseService):
|
||||
TRANSACTION_TYPE = TransactionType.SELECT_OFFER
|
||||
@@ -60,9 +60,9 @@ class SelectOfferService(BaseService):
|
||||
response_data = {
|
||||
"outstandingDebtAmount": 0,
|
||||
"requestId": "202111170001371256908",
|
||||
"transactionId": "1231231321232",
|
||||
"customerId": "1256907",
|
||||
"accountId": "5948306019",
|
||||
"transactionId": transaction.id,
|
||||
"customerId": customer_id,
|
||||
"accountId": account_id,
|
||||
"loan": offers,
|
||||
"resultCode": "00",
|
||||
"resultDescription": "Successful"
|
||||
|
||||
+12
-6
@@ -1,16 +1,17 @@
|
||||
import os
|
||||
from datetime import timedelta
|
||||
|
||||
|
||||
class Config:
|
||||
"""Base configuration for Flask app"""
|
||||
|
||||
|
||||
SWAGGER_URL = os.getenv("SWAGGER_URL", "/documentation")
|
||||
API_URL = os.getenv("API_URL", "/swagger.json")
|
||||
|
||||
DEBUG = True
|
||||
VALID_APP_ID = os.getenv("VALID_APP_ID", "app1")
|
||||
VALID_API_KEY = os.getenv("VALID_API_KEY", "test-api-key-12345")
|
||||
BASIC_AUTH_USERNAME = os.environ.get("BASIC_AUTH_USERNAME", "user")
|
||||
BASIC_AUTH_USERNAME = os.environ.get("BASIC_AUTH_USERNAME", "user")
|
||||
BASIC_AUTH_PASSWORD = os.environ.get("BASIC_AUTH_PASSWORD", "password")
|
||||
|
||||
DATABASE_USER = os.environ.get("DATABASE_USER")
|
||||
@@ -19,14 +20,19 @@ class Config:
|
||||
DATABASE_PORT = os.environ.get("DATABASE_PORT", 10532)
|
||||
DATABASE_NAME = os.environ.get("DATABASE_NAME")
|
||||
|
||||
SQLALCHEMY_DATABASE_URI = (
|
||||
f"postgresql+psycopg2://{DATABASE_USER}:{DATABASE_PASSWORD}@{DATABASE_HOST}:{DATABASE_PORT}/{DATABASE_NAME}"
|
||||
)
|
||||
SQLALCHEMY_DATABASE_URI = f"postgresql+psycopg2://{DATABASE_USER}:{DATABASE_PASSWORD}@{DATABASE_HOST}:{DATABASE_PORT}/{DATABASE_NAME}"
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
SIMBRELLA_BASE_URL = os.getenv("SIMBRELLA_BASE_URL", "http://127.0.0.1:6337")
|
||||
|
||||
|
||||
JWT_SECRET_KEY = os.getenv("JWT_SECRET_KEY", "secret-key")
|
||||
JWT_ACCESS_TOKEN_EXPIRES = os.getenv("JWT_ACCESS_TOKEN_EXPIRES", timedelta(hours=1))
|
||||
JWT_REFRESH_TOKEN_EXPIRES = os.getenv(
|
||||
"JWT_REFRESH_TOKEN_EXPIRES", timedelta(days=30)
|
||||
)
|
||||
|
||||
KAFKA_BROKER = 'dev-events.simbrellang.net:9085'
|
||||
KAFKA_PAYMENT_TOPIC = 'PROCESS_PAYMENT'
|
||||
|
||||
|
||||
settings = Config()
|
||||
settings = Config()
|
||||
|
||||
@@ -20,11 +20,11 @@ class Customer(db.Model):
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def is_eligible(cls, customer_id):
|
||||
def is_valid_customer(cls, customer_id):
|
||||
customer = cls.query.filter_by(id=customer_id).first()
|
||||
if not customer:
|
||||
return False, "Customer not found"
|
||||
return True, "Customer is eligible"
|
||||
return False
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def create_customer(cls, id, msisdn, country_code, account_id, account_type='savings'):
|
||||
|
||||
+38
-4
@@ -1,20 +1,54 @@
|
||||
from datetime import datetime, timezone
|
||||
from app.extensions import db
|
||||
from app.models.customer import Customer
|
||||
from app.models.account import Account
|
||||
|
||||
|
||||
class Loan(db.Model):
|
||||
__tablename__ = 'loans'
|
||||
|
||||
id = db.Column(db.String(50), primary_key=True)
|
||||
id = db.Column(
|
||||
db.Integer,
|
||||
primary_key=True,
|
||||
autoincrement=True,
|
||||
)
|
||||
customer_id = db.Column(db.String(50), nullable=False)
|
||||
account_id = db.Column(db.String(50), nullable=False)
|
||||
product_id = db.Column(db.String(20), nullable=False)
|
||||
offer_id = db.Column(db.String(20), nullable=False)
|
||||
principal_amount = db.Column(db.Float, nullable=False)
|
||||
status = db.Column(db.String(20), default='pending')
|
||||
created_at = db.Column(db.DateTime, default=datetime.now(timezone.utc))
|
||||
updated_at = db.Column(db.DateTime, default=datetime.now(timezone.utc), onupdate=datetime.now(timezone.utc))
|
||||
|
||||
|
||||
@classmethod
|
||||
def create_loan(cls, customer_id, account_id, offer_id, principal_amount, status='pending'):
|
||||
|
||||
# Check if customer exists
|
||||
is_valid = Customer.is_valid_customer(customer_id)
|
||||
if not is_valid:
|
||||
raise ValueError("Customer does not exist")
|
||||
|
||||
# # Check for active loans
|
||||
# has_active_loans = cls.has_active_loans(customer_id)
|
||||
# if has_active_loans:
|
||||
# raise ValueError("Customer has active loans")
|
||||
|
||||
|
||||
# Create and save the loan
|
||||
loan = cls(
|
||||
customer_id=customer_id,
|
||||
account_id=account_id,
|
||||
offer_id=offer_id,
|
||||
principal_amount=principal_amount,
|
||||
status=status
|
||||
)
|
||||
|
||||
db.session.add(loan)
|
||||
db.session.commit()
|
||||
return loan
|
||||
|
||||
|
||||
@classmethod
|
||||
def has_active_loans(cls, customer_id):
|
||||
active_loans = cls.query.filter_by(
|
||||
@@ -23,8 +57,8 @@ class Loan(db.Model):
|
||||
).count()
|
||||
|
||||
if active_loans > 0:
|
||||
return False, "Customer has active loans"
|
||||
return True, "No active loans"
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def __repr__(self):
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
from datetime import datetime, timezone
|
||||
from app.extensions import db
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy import and_, or_, not_
|
||||
|
||||
class Transaction(db.Model):
|
||||
__tablename__ = 'transactions'
|
||||
|
||||
id = db.Column(db.String(50), primary_key=True)
|
||||
id = db.Column(
|
||||
db.Integer,
|
||||
primary_key=True,
|
||||
autoincrement=True,
|
||||
)
|
||||
#id = db.Column(db.Int, primary_key=True)
|
||||
transaction_id = db.Column(db.String(50), nullable=False)
|
||||
account_id = db.Column(db.String(50), nullable=False)
|
||||
type = db.Column(db.String(50), nullable=False)
|
||||
channel = db.Column(db.String(50), nullable=False)
|
||||
@@ -16,12 +22,18 @@ class Transaction(db.Model):
|
||||
return f'<Transaction {self.id}>'
|
||||
|
||||
@classmethod
|
||||
def create_transaction(cls, id, account_id, type, channel):
|
||||
if cls.query.filter_by(id=id).first():
|
||||
def create_transaction(cls, transaction_id, account_id, type, channel):
|
||||
|
||||
# if cls.query.filter_by(transaction_id=transaction_id).first():
|
||||
# raise ValueError("Duplicate Transaction")
|
||||
|
||||
if cls.query.filter( and_( cls.transaction_id ==transaction_id, cls.type==type) ).first():
|
||||
raise ValueError("Duplicate Transaction")
|
||||
|
||||
|
||||
|
||||
transaction = cls(
|
||||
id=id,
|
||||
transaction_id=transaction_id,
|
||||
account_id=account_id,
|
||||
type=type,
|
||||
channel=channel
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"openapi": "3.0.3",
|
||||
"info": {
|
||||
"title": "Swagger Simbrella FirstAdvance - OpenAPI 3.0",
|
||||
"title": "Swagger Bank Channel to Simbrella FirstAdvance - OpenAPI 3.0",
|
||||
"description": "This is a Simbrella FirstAdvance Backend Server with the OpenAPI 3.0 specification. \n\n\nSome useful links:\n- [Web Simulated Demo Page](https://digifi-salaryloan.chiefsoft.net/)\n- [Web Management Support Portal](https://digifi-office.chiefsoft.net/auth/login)",
|
||||
"termsOfService": "http://swagger.io/terms/",
|
||||
"contact": {
|
||||
@@ -16,9 +16,31 @@
|
||||
"servers": [
|
||||
{
|
||||
"url": "http://localhost:4500"
|
||||
},
|
||||
{
|
||||
"url": "http://api.dev.simbrellang.net:4500"
|
||||
},
|
||||
{
|
||||
"url": "https://api.dev.simbrellang.net"
|
||||
}
|
||||
],
|
||||
"tags": [
|
||||
{
|
||||
"name": "Authorize",
|
||||
"description": "This feature will be used for authorizing customers.",
|
||||
"externalDocs": {
|
||||
"description": "Find out more",
|
||||
"url": "https://www.simbrellang.net"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "AuthorizeRefresh",
|
||||
"description": "This feature will be used for refreshing authorized customers.",
|
||||
"externalDocs": {
|
||||
"description": "Find out more",
|
||||
"url": "https://www.simbrellang.net"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "EligibilityCheck",
|
||||
"description": "Eligibility Check Request",
|
||||
@@ -58,25 +80,15 @@
|
||||
"description": "Find out more",
|
||||
"url": "https://www.simbrellang.net"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "CustomerConsent",
|
||||
"description": "CustomerConsent Request.",
|
||||
"externalDocs": {
|
||||
"description": "Find out more",
|
||||
"url": "https://www.simbrellang.net"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "NotificationCallback",
|
||||
"description": "This new feature will be used for informing Simbrella about status of the transactions that FBN have processed.",
|
||||
"externalDocs": {
|
||||
"description": "Find out more",
|
||||
"url": "https://www.simbrellang.net"
|
||||
}
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"/Authorize": {
|
||||
"$ref": "swagger/paths/Authorize.json"
|
||||
},
|
||||
"/AuthorizeRefresh": {
|
||||
"$ref": "swagger/paths/AuthorizeRefresh.json"
|
||||
},
|
||||
"/EligibilityCheck": {
|
||||
"$ref": "swagger/paths/EligibilityCheck.json"
|
||||
},
|
||||
@@ -91,12 +103,6 @@
|
||||
},
|
||||
"/Repayment": {
|
||||
"$ref": "swagger/paths/Repayment.json"
|
||||
},
|
||||
"/CustomerConsent": {
|
||||
"$ref": "swagger/paths/CustomerConsent.json"
|
||||
},
|
||||
"/NotificationCallback": {
|
||||
"$ref": "swagger/paths/NotificationCallback.json"
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
@@ -139,18 +145,36 @@
|
||||
},
|
||||
"ApiResponse": {
|
||||
"$ref": "swagger/schemas/ApiResponse.json"
|
||||
},
|
||||
"AuthorizeResponse": {
|
||||
"$ref": "swagger/schemas/AuthorizeResponse.json"
|
||||
},
|
||||
"AuthorizeRequest": {
|
||||
"$ref": "swagger/schemas/AuthorizeRequest.json"
|
||||
},
|
||||
"AuthorizeRefreshResponse": {
|
||||
"$ref": "swagger/schemas/AuthorizeRefreshResponse.json"
|
||||
},
|
||||
"AuthorizeRefreshRequest": {
|
||||
"$ref": "swagger/schemas/AuthorizeRefreshRequest.json"
|
||||
}
|
||||
},
|
||||
"securitySchemes": {
|
||||
"basicAuth": {
|
||||
"type": "http",
|
||||
"scheme": "basic"
|
||||
"type": "http",
|
||||
"scheme": "basic"
|
||||
},
|
||||
"bearerAuth": {
|
||||
"type": "http",
|
||||
"scheme": "bearer",
|
||||
"bearerFormat": "JWT"
|
||||
}
|
||||
}
|
||||
},
|
||||
"security": [
|
||||
{
|
||||
"basicAuth": []
|
||||
"basicAuth": [],
|
||||
"bearerAuth": []
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"post": {
|
||||
"tags": ["Authorize"],
|
||||
"summary": "Customer Authorize Request",
|
||||
"description": "Customer Authorize Request",
|
||||
"operationId": "Authorize",
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "../schemas/AuthorizeRequest.json"
|
||||
}
|
||||
},
|
||||
"application/xml": {
|
||||
"schema": {
|
||||
"$ref": "../schemas/AuthorizeRequest.json"
|
||||
}
|
||||
},
|
||||
"application/x-www-form-urlencoded": {
|
||||
"schema": {
|
||||
"$ref": "../schemas/AuthorizeRequest.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful operation",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "../schemas/AuthorizeResponse.json"
|
||||
}
|
||||
},
|
||||
"application/xml": {
|
||||
"schema": {
|
||||
"$ref": "../schemas/AuthorizeResponse.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Invalid request parameters"
|
||||
},
|
||||
"422": {
|
||||
"description": "Validation exception"
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal server error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"post": {
|
||||
"tags": ["Authorize Refresh"],
|
||||
"summary": "Customer Authorize Refresh Request",
|
||||
"description": "Customer Authorize Refresh Request",
|
||||
"operationId": "AuthorizeRefresh",
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "../schemas/AuthorizeRefreshRequest.json"
|
||||
}
|
||||
},
|
||||
"application/xml": {
|
||||
"schema": {
|
||||
"$ref": "../schemas/AuthorizeRefreshRequest.json"
|
||||
}
|
||||
},
|
||||
"application/x-www-form-urlencoded": {
|
||||
"schema": {
|
||||
"$ref": "../schemas/AuthorizeRefreshRequest.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful operation",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "../schemas/AuthorizeRefreshResponse.json"
|
||||
}
|
||||
},
|
||||
"application/xml": {
|
||||
"schema": {
|
||||
"$ref": "../schemas/AuthorizeRefreshResponse.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Invalid request parameters"
|
||||
},
|
||||
"422": {
|
||||
"description": "Validation exception"
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal server error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {},
|
||||
"xml": {
|
||||
"name": "AuthorizeRefreshRequest"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"access_token": {
|
||||
"type": "string",
|
||||
"example": "access_token"
|
||||
}
|
||||
},
|
||||
"xml": {
|
||||
"name": "AuthorizeRefreshResponse"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"username": {
|
||||
"type": "string",
|
||||
"example": "user"
|
||||
},
|
||||
"password": {
|
||||
"type": "string",
|
||||
"example": "password"
|
||||
}
|
||||
},
|
||||
"xml": {
|
||||
"name": "AuthorizeRequest"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"access_token": {
|
||||
"type": "string",
|
||||
"example": "access_token"
|
||||
},
|
||||
"refresh_token": {
|
||||
"type": "string",
|
||||
"example": "refresh_token"
|
||||
}
|
||||
},
|
||||
"xml": {
|
||||
"name": "AuthorizeResponse"
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,6 @@
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"example": "ProvideLoanRequest"
|
||||
},
|
||||
"requestId": {
|
||||
"type": "string",
|
||||
"example": "202111170001371256908"
|
||||
@@ -25,15 +21,6 @@
|
||||
"type": "string",
|
||||
"example": "3451342"
|
||||
},
|
||||
"productId": {
|
||||
"type": "string",
|
||||
"example": "101"
|
||||
},
|
||||
"lienAmount": {
|
||||
"type": "number",
|
||||
"format": "decimal",
|
||||
"example": 400
|
||||
},
|
||||
"requestedAmount": {
|
||||
"type": "number",
|
||||
"format": "decimal",
|
||||
|
||||
@@ -27,6 +27,10 @@ python-dotenv
|
||||
# Requests
|
||||
requests
|
||||
|
||||
# JWT
|
||||
flask-jwt-extended
|
||||
|
||||
|
||||
# Kafka
|
||||
confluent-kafka==1.9.2
|
||||
|
||||
|
||||
Reference in New Issue
Block a user