[add]: eco endpoints and dummy responses
This commit is contained in:
@@ -0,0 +1 @@
|
||||
from .transaction_type import TransactionType
|
||||
@@ -0,0 +1,7 @@
|
||||
from enum import Enum
|
||||
|
||||
class InstallmentStatus(str, Enum):
|
||||
PENDING = 'PENDING'
|
||||
PAID = 'PAID'
|
||||
OVERDUE = 'OVERDUE'
|
||||
PARTIALLY_PAID = 'PARTIALLY_PAID'
|
||||
@@ -0,0 +1,8 @@
|
||||
from enum import Enum
|
||||
|
||||
class LoanStatus(str, Enum):
|
||||
PENDING = 'PENDING'
|
||||
ACTIVE = 'ACTIVE'
|
||||
PAID = 'PAID'
|
||||
DEFAULTED = 'DEFAULTED'
|
||||
CLOSED = 'CLOSED'
|
||||
@@ -0,0 +1,7 @@
|
||||
from enum import Enum
|
||||
|
||||
class TransactionType(str, Enum):
|
||||
DEBT_CLOSURE_NOTIFICATION = "debt_closure_notification"
|
||||
DISBURSEMENT = "disbursement"
|
||||
SEND_SMS = "send_sms"
|
||||
COLLECT_LOAN = "collect_loan"
|
||||
@@ -0,0 +1,112 @@
|
||||
from flask import jsonify
|
||||
from typing import Optional, Union, Dict, List, Any
|
||||
|
||||
|
||||
class ResponseHelper:
|
||||
"""
|
||||
A helper class for building standardized JSON responses using resultCode and resultDescription.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def build_response(
|
||||
result_code: str,
|
||||
result_description: str,
|
||||
data: Optional[Union[Dict, List, str]] = None
|
||||
) -> Dict[str, Any]:
|
||||
response = {
|
||||
"resultCode": result_code,
|
||||
"resultDescription": result_description
|
||||
}
|
||||
|
||||
if isinstance(data, dict):
|
||||
response.update(data)
|
||||
|
||||
return jsonify(response)
|
||||
|
||||
@staticmethod
|
||||
def success(
|
||||
result_description: str = "Successful",
|
||||
result_code: str = "00",
|
||||
data: Optional[Dict[str, Any]] = None
|
||||
) -> Dict[str, Any]:
|
||||
return ResponseHelper.build_response(result_code, result_description, data)
|
||||
|
||||
@staticmethod
|
||||
def error(
|
||||
result_description: str = "An error occurred",
|
||||
result_code: str = "01",
|
||||
data: Optional[Dict[str, Any]] = None
|
||||
) -> Dict[str, Any]:
|
||||
return ResponseHelper.build_response(result_code, result_description, data)
|
||||
|
||||
@staticmethod
|
||||
def created(
|
||||
result_description: str = "Resource created successfully",
|
||||
result_code: str = "00",
|
||||
data: Optional[Dict[str, Any]] = None
|
||||
) -> Dict[str, Any]:
|
||||
return ResponseHelper.build_response(result_code, result_description, data)
|
||||
|
||||
@staticmethod
|
||||
def updated(
|
||||
result_description: str = "Resource updated successfully",
|
||||
result_code: str = "00",
|
||||
data: Optional[Dict[str, Any]] = None
|
||||
) -> Dict[str, Any]:
|
||||
return ResponseHelper.build_response(result_code, result_description, data)
|
||||
|
||||
@staticmethod
|
||||
def internal_server_error(
|
||||
result_description: str = "Internal Server Error",
|
||||
result_code: str = "500",
|
||||
data: Optional[Dict[str, Any]] = None
|
||||
) -> Dict[str, Any]:
|
||||
return ResponseHelper.build_response(result_code, result_description, data)
|
||||
|
||||
@staticmethod
|
||||
def unauthorized(
|
||||
result_description: str = "Unauthorized",
|
||||
result_code: str = "401",
|
||||
data: Optional[Dict[str, Any]] = None
|
||||
) -> Dict[str, Any]:
|
||||
return ResponseHelper.build_response(result_code, result_description, data)
|
||||
|
||||
@staticmethod
|
||||
def forbidden(
|
||||
result_description: str = "Forbidden",
|
||||
result_code: str = "403",
|
||||
data: Optional[Dict[str, Any]] = None
|
||||
) -> Dict[str, Any]:
|
||||
return ResponseHelper.build_response(result_code, result_description, data)
|
||||
|
||||
@staticmethod
|
||||
def not_found(
|
||||
result_description: str = "Resource not found",
|
||||
result_code: str = "404",
|
||||
data: Optional[Dict[str, Any]] = None
|
||||
) -> Dict[str, Any]:
|
||||
return ResponseHelper.build_response(result_code, result_description, data)
|
||||
|
||||
@staticmethod
|
||||
def unprocessable_entity(
|
||||
result_description: str = "Unprocessable entity",
|
||||
result_code: str = "422",
|
||||
data: Optional[Dict[str, Any]] = None
|
||||
) -> Dict[str, Any]:
|
||||
return ResponseHelper.build_response(result_code, result_description, data)
|
||||
|
||||
@staticmethod
|
||||
def method_not_allowed(
|
||||
result_description: str = "Method Not Allowed",
|
||||
result_code: str = "405",
|
||||
data: Optional[Dict[str, Any]] = None
|
||||
) -> Dict[str, Any]:
|
||||
return ResponseHelper.build_response(result_code, result_description, data)
|
||||
|
||||
@staticmethod
|
||||
def bad_request(
|
||||
result_description: str = "Bad Request",
|
||||
result_code: str = "400",
|
||||
data: Optional[Dict[str, Any]] = None
|
||||
) -> Dict[str, Any]:
|
||||
return ResponseHelper.build_response(result_code, result_description, data)
|
||||
@@ -0,0 +1 @@
|
||||
from .routes import eco
|
||||
@@ -0,0 +1,87 @@
|
||||
from flask import Blueprint, request, jsonify, send_from_directory
|
||||
from app.eco.services import (
|
||||
AuthorizationService,
|
||||
DisbursementService,
|
||||
CollectLoanService,
|
||||
DebtClosureNotificationService,
|
||||
SendSMSService
|
||||
)
|
||||
from app.utils.logger import logger
|
||||
from flask_jwt_extended import jwt_required
|
||||
import os
|
||||
|
||||
eco = Blueprint("eco", __name__)
|
||||
|
||||
# Swagger JSON file
|
||||
@eco.route("/swagger.json", methods=["GET"])
|
||||
def swagger_json():
|
||||
swagger_dir = os.path.join("swagger")
|
||||
return send_from_directory(swagger_dir, "eco_digifi_swagger.json")
|
||||
|
||||
@eco.route("/swagger/<path:filename>")
|
||||
def serve_paths(filename):
|
||||
swagger_dir = os.path.join("swagger")
|
||||
return send_from_directory(swagger_dir, filename)
|
||||
|
||||
|
||||
|
||||
# Disbursement (Simbrella -> EcoBank)
|
||||
@eco.route("/Disbursement", methods=["POST"])
|
||||
@jwt_required()
|
||||
def disbursement():
|
||||
data = request.get_json()
|
||||
response = DisbursementService.process_request(data)
|
||||
return response
|
||||
|
||||
|
||||
# CollectLoan (Simbrella -> EcoBank)
|
||||
@eco.route("/CollectLoan", methods=["POST"])
|
||||
@jwt_required()
|
||||
def collect_loan():
|
||||
data = request.get_json()
|
||||
response = CollectLoanService.process_request(data)
|
||||
return response
|
||||
|
||||
|
||||
# Debt Closure Notification (Simbrella -> EcoBank)
|
||||
@eco.route("/DebtClosureNotification", methods=["POST"])
|
||||
@jwt_required()
|
||||
def debt_closure():
|
||||
data = request.get_json()
|
||||
response = DebtClosureNotificationService.process_request(data)
|
||||
return response
|
||||
|
||||
|
||||
# Send SMS (Simbrella -> EcoBank)
|
||||
@eco.route("/SendSMS", methods=["POST"])
|
||||
@jwt_required()
|
||||
def send_sms():
|
||||
data = request.get_json()
|
||||
response = SendSMSService.process_request(data)
|
||||
return response
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# Health Check
|
||||
@eco.route("/health", methods=["GET"])
|
||||
def health_check():
|
||||
return jsonify({"status": "ok"}), 200
|
||||
|
||||
|
||||
|
||||
# Authorize endpoint
|
||||
@eco.route("/Authorize", methods=["POST"])
|
||||
def authorize():
|
||||
data = request.get_json()
|
||||
response = AuthorizationService.process_request(data)
|
||||
return response
|
||||
|
||||
|
||||
# Authorize refresh endpoint
|
||||
@eco.route("/AuthorizeRefresh", methods=["POST"])
|
||||
@jwt_required(refresh=True)
|
||||
def refresh():
|
||||
response = AuthorizationService.process_refresh_request()
|
||||
return response
|
||||
@@ -0,0 +1,5 @@
|
||||
from .authorization import AuthorizeRequestSchema
|
||||
from .disbursement import DisbursementSchema
|
||||
from .debt_closure_notification import DebtClosureNotificationSchema
|
||||
from .send_sms import SendSmsSchema
|
||||
from .collect_loan import CollectLoanSchema
|
||||
@@ -0,0 +1,6 @@
|
||||
from marshmallow import Schema, fields
|
||||
|
||||
|
||||
class AuthorizeRequestSchema(Schema):
|
||||
username = fields.Str(required=True)
|
||||
password = fields.Str(required=True)
|
||||
@@ -0,0 +1,13 @@
|
||||
from marshmallow import Schema, fields, EXCLUDE
|
||||
|
||||
class CollectLoanSchema(Schema):
|
||||
requestId = fields.Str(required=True)
|
||||
affiliateCode = fields.Str(required=True)
|
||||
debtId = fields.Int(required=True)
|
||||
principal = fields.Decimal(required=True)
|
||||
interest = fields.Decimal(required=True)
|
||||
penalty = fields.Decimal(required=True)
|
||||
collectAmount = fields.Decimal(required=True)
|
||||
|
||||
class Meta:
|
||||
unknown = EXCLUDE
|
||||
@@ -0,0 +1,11 @@
|
||||
from marshmallow import Schema, fields, EXCLUDE
|
||||
|
||||
class DebtClosureNotificationSchema(Schema):
|
||||
requestId = fields.Str(required=True)
|
||||
affiliateCode = fields.Str(required=True)
|
||||
customerId = fields.Str(required=True)
|
||||
accountId = fields.Str(required=True)
|
||||
debtId = fields.Int(required=True)
|
||||
|
||||
class Meta:
|
||||
unknown = EXCLUDE
|
||||
@@ -0,0 +1,15 @@
|
||||
from marshmallow import Schema, fields, EXCLUDE
|
||||
|
||||
class DisbursementSchema(Schema):
|
||||
requestId = fields.Str(required=True)
|
||||
affiliateCode = fields.Str(required=True)
|
||||
debtId = fields.Int(required=True)
|
||||
productId = fields.Str(required=True)
|
||||
customerId = fields.Str(required=True)
|
||||
accountId = fields.Str(required=True)
|
||||
provideAmount = fields.Decimal(required=True)
|
||||
collectAmount = fields.Decimal(required=True)
|
||||
interestRate = fields.Decimal(required=True)
|
||||
|
||||
class Meta:
|
||||
unknown = EXCLUDE
|
||||
@@ -0,0 +1,10 @@
|
||||
from marshmallow import Schema, fields, EXCLUDE
|
||||
|
||||
class SendSmsSchema(Schema):
|
||||
requestId = fields.Str(required=True)
|
||||
phoneNums = fields.List(fields.Str(), required=True)
|
||||
affiliateCode = fields.Str(required=True)
|
||||
message = fields.Str(required=True)
|
||||
|
||||
class Meta:
|
||||
unknown = EXCLUDE
|
||||
@@ -0,0 +1,5 @@
|
||||
from .authorization import AuthorizationService
|
||||
from .disbursement import DisbursementService
|
||||
from .debt_closure_notification import DebtClosureNotificationService
|
||||
from .send_sms import SendSMSService
|
||||
from .collect_loan import CollectLoanService
|
||||
@@ -0,0 +1,102 @@
|
||||
from flask import request, jsonify
|
||||
from marshmallow import ValidationError
|
||||
from app.eco.services.base_service import BaseService
|
||||
from app.utils.logger import logger
|
||||
from app.eco.schemas.authorization import AuthorizeRequestSchema
|
||||
from app.eco.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(result_description="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(result_description="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={"data": response_data}, result_description="Authorization processed successfully"
|
||||
)
|
||||
|
||||
except ValidationError as e:
|
||||
logger.error(f"Validation error: {e}")
|
||||
return ResponseHelper.bad_request(result_description=f"Validation error: {e}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing Authorization request: {e}")
|
||||
return ResponseHelper.internal_server_error(
|
||||
result_description=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={"data": response_data}, result_description="RefreshToken processed successfully"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing RefreshToken request: {e}")
|
||||
return ResponseHelper.internal_server_error(
|
||||
result_description=f"Error processing RefreshToken request: {e}"
|
||||
)
|
||||
@@ -0,0 +1,32 @@
|
||||
from app.eco.enums import TransactionType
|
||||
from flask import jsonify
|
||||
from marshmallow import ValidationError
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class BaseService:
|
||||
TRANSACTION_TYPE = None
|
||||
|
||||
@classmethod
|
||||
def validate_data(cls, data, schema):
|
||||
"""
|
||||
Validate input data based on the provided schema.
|
||||
"""
|
||||
logger.info(f"Processing {cls.TRANSACTION_TYPE} request")
|
||||
return schema.load(data)
|
||||
|
||||
# @classmethod
|
||||
# def log_session(cls, validated_data):
|
||||
# """
|
||||
# Create a new session.
|
||||
# """
|
||||
# channel = "USSD" if validated_data.get("channel") is None else validated_data.get("channel")
|
||||
|
||||
# return Session.create_session(
|
||||
# session_id = validated_data.get("transactionId"),
|
||||
# customer_id = validated_data.get('customerId', None),
|
||||
# account_id = validated_data.get("accountId", None),
|
||||
# type = cls.TRANSACTION_TYPE,
|
||||
# channel = channel,
|
||||
# )
|
||||
@@ -0,0 +1,33 @@
|
||||
from app.eco.enums.transaction_type import TransactionType
|
||||
from app.eco.services.base_service import BaseService
|
||||
from app.eco.schemas.collect_loan import CollectLoanSchema
|
||||
from marshmallow import ValidationError
|
||||
from app.eco.helpers.response_helper import ResponseHelper
|
||||
|
||||
class CollectLoanService(BaseService):
|
||||
TRANSACTION_TYPE = TransactionType.COLLECT_LOAN
|
||||
|
||||
@staticmethod
|
||||
def process_request(data):
|
||||
"""
|
||||
Process the loan collection request.
|
||||
|
||||
Args:
|
||||
data (dict): The request data.
|
||||
|
||||
Returns:
|
||||
dict: A standardized response.
|
||||
"""
|
||||
try:
|
||||
validated_data = CollectLoanService.validate_data(data, CollectLoanSchema())
|
||||
|
||||
response_data = {
|
||||
"transactionId": "01135062",
|
||||
"amountCollected": 900.0,
|
||||
}
|
||||
|
||||
return ResponseHelper.success(data=response_data)
|
||||
except ValidationError as err:
|
||||
return ResponseHelper.unprocessable_entity(result_description="Validation exception")
|
||||
except Exception as e:
|
||||
return ResponseHelper.internal_server_error()
|
||||
@@ -0,0 +1,27 @@
|
||||
from app.eco.enums.transaction_type import TransactionType
|
||||
from app.eco.services.base_service import BaseService
|
||||
from app.eco.schemas.debt_closure_notification import DebtClosureNotificationSchema
|
||||
from marshmallow import ValidationError
|
||||
from app.eco.helpers.response_helper import ResponseHelper
|
||||
|
||||
class DebtClosureNotificationService(BaseService):
|
||||
TRANSACTION_TYPE = TransactionType.DEBT_CLOSURE_NOTIFICATION
|
||||
|
||||
@staticmethod
|
||||
def process_request(data):
|
||||
"""
|
||||
Process the debt closure notification request.
|
||||
|
||||
Args:
|
||||
data (dict): The request data.
|
||||
|
||||
Returns:
|
||||
dict: A standardized response.
|
||||
"""
|
||||
try:
|
||||
validated_data = DebtClosureNotificationService.validate_data(data, DebtClosureNotificationSchema())
|
||||
return ResponseHelper.success()
|
||||
except ValidationError as err:
|
||||
return ResponseHelper.unprocessable_entity(result_description="Validation exception")
|
||||
except Exception as e:
|
||||
return ResponseHelper.internal_server_error()
|
||||
@@ -0,0 +1,32 @@
|
||||
from app.eco.enums.transaction_type import TransactionType
|
||||
from app.eco.services.base_service import BaseService
|
||||
from app.eco.schemas.disbursement import DisbursementSchema
|
||||
from marshmallow import ValidationError
|
||||
from app.eco.helpers.response_helper import ResponseHelper
|
||||
|
||||
class DisbursementService(BaseService):
|
||||
TRANSACTION_TYPE = TransactionType.DISBURSEMENT
|
||||
|
||||
@staticmethod
|
||||
def process_request(data):
|
||||
"""
|
||||
Process the disbursement request.
|
||||
|
||||
Args:
|
||||
data (dict): The request data.
|
||||
|
||||
Returns:
|
||||
dict: A standardized response.
|
||||
"""
|
||||
try:
|
||||
validated_data = DisbursementService.validate_data(data, DisbursementSchema())
|
||||
response_data = {
|
||||
"transactionId": "SIM01135042",
|
||||
}
|
||||
|
||||
return ResponseHelper.success(data=response_data)
|
||||
|
||||
except ValidationError as err:
|
||||
return ResponseHelper.unprocessable_entity(result_description="Validation exception")
|
||||
except Exception as e:
|
||||
return ResponseHelper.internal_server_error()
|
||||
@@ -0,0 +1,31 @@
|
||||
from app.eco.enums.transaction_type import TransactionType
|
||||
from app.eco.services.base_service import BaseService
|
||||
from app.eco.schemas.send_sms import SendSmsSchema
|
||||
from marshmallow import ValidationError
|
||||
from app.eco.helpers.response_helper import ResponseHelper
|
||||
|
||||
class SendSMSService(BaseService):
|
||||
TRANSACTION_TYPE = TransactionType.SEND_SMS
|
||||
|
||||
@staticmethod
|
||||
def process_request(data):
|
||||
"""
|
||||
Process the SMS sending request.
|
||||
|
||||
Args:
|
||||
data (dict): The request data.
|
||||
|
||||
Returns:
|
||||
dict: A standardized response.
|
||||
"""
|
||||
try:
|
||||
validated_data = SendSMSService.validate_data(data, SendSmsSchema())
|
||||
|
||||
response_data = {
|
||||
"undelivered": []
|
||||
}
|
||||
return ResponseHelper.success(data=response_data)
|
||||
except ValidationError as err:
|
||||
return ResponseHelper.unprocessable_entity(result_description="Validation exception")
|
||||
except Exception as e:
|
||||
return ResponseHelper.internal_server_error()
|
||||
Reference in New Issue
Block a user