2 Commits

Author SHA1 Message Date
VivianDee 33ee8a286b [fix]: request schems 2025-07-30 05:24:02 +01:00
VivianDee 038c5323b0 [add]: eco endpoints and dummy responses 2025-07-30 05:16:47 +01:00
70 changed files with 1145 additions and 691 deletions
Vendored
BIN
View File
Binary file not shown.
+5 -2
View File
@@ -55,7 +55,8 @@ This command will build the Docker image and start the Flask application in a co
You can check if the Flask application is running by accessing the `/health` endpoint. To perform a health check, run the following command:
```bash
curl http://localhost:6337/health
curl http://localhost:6337/api/health
curl http://localhost:6337/eco/health
```
If the application is running properly, you should receive a response similar to this:
@@ -71,7 +72,9 @@ If the application is running properly, you should receive a response similar to
You can check the Swagger Doc by accessing the `/documentation` endpoint. Run the following command:
```bash
curl http://localhost:6337/documentation
curl http://localhost:6337/api/documentation
curl http://localhost:6337/eco/documentation
```
+27 -33
View File
@@ -1,60 +1,54 @@
from flask import Flask, jsonify
from re import S
from flask import Flask
import os
from flask_swagger_ui import get_swaggerui_blueprint
from flask_cors import CORS
from app.config import Config
from app.api.routes import api, auth_bp
from app.api.routes import api
from app.eco.routes import eco
from app.errors import register_error_handlers
from flask_jwt_extended import JWTManager
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 """
app = Flask(__name__)
# Load configuration
app.config.from_object(Config)
jwt = JWTManager(app)
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 with /api prefix for the main API routes
app.register_blueprint(api, url_prefix='/api')
# Register blueprints with /auth prefix for the authentication routes
app.register_blueprint(auth_bp, url_prefix='/api/Auth')
app.register_blueprint(api, url_prefix="/api")
app.register_blueprint(eco, url_prefix="/eco")
swagger_ui_blueprint = get_swaggerui_blueprint(SWAGGER_URL, API_URL)
app.register_blueprint(swagger_ui_blueprint, url_prefix=SWAGGER_URL)
def jwt_error(message, code=401):
return jsonify({
"status": "error",
"message": message
}), code
# Swagger UI Blueprint
api_docs = "/api" + SWAGGER_URL
api_url = "/api" + API_URL
swagger_ui_api = get_swaggerui_blueprint(api_docs, api_url)
swagger_ui_api.name = 'swagger_ui_api' # Rename blueprint
app.register_blueprint(swagger_ui_api, url_prefix=api_docs)
# Second UI (ECO)
eco_docs = "/eco" + SWAGGER_URL
eco_api = "/eco" + API_URL
swagger_ui_eco = get_swaggerui_blueprint(eco_docs, eco_api)
swagger_ui_eco.name = 'swagger_ui_eco' # Rename blueprint
app.register_blueprint(swagger_ui_eco, url_prefix=eco_docs)
@jwt.unauthorized_loader
def unauthorized_response(callback):
return jwt_error("Unauthorized access")
@jwt.expired_token_loader
def expired_token_callback(jwt_header, jwt_payload):
return jwt_error("Expired token")
@jwt.invalid_token_loader
def invalid_token_callback(error):
return jwt_error("Invalid authentication token.", 422)
@jwt.revoked_token_loader
def revoked_token_callback(jwt_header, jwt_payload):
return jwt_error("This token has been revoked. Please log in again.")
# Error Handlers
register_error_handlers(app)
+1 -1
View File
@@ -1,3 +1,3 @@
from .verify_api_key import require_api_key
from .app_id_checker import require_app_id
from .cors import enforce_json
from .cors import enforce_json
-1
View File
@@ -1,5 +1,4 @@
from flask import request, jsonify
from app.utils.logger import logger
def enforce_json():
-1
View File
@@ -1,2 +1 @@
from .routes import api
from .authentication import auth_bp
-24
View File
@@ -1,24 +0,0 @@
from flask import Blueprint, request, jsonify
from app.utils.logger import logger
from app.api.middlewares import enforce_json
from app.api.services.generate_token import GenerateTokenService
auth_bp = Blueprint("api/Auth", __name__)
# Enforce json
@auth_bp.before_request
def cors_middleware():
"""Middleware applied globally to all API routes in this blueprint"""
return enforce_json()
@auth_bp.route('/generate-token', methods=['POST'])
def get_token():
try:
data = request.get_json()
logger.info(f"GenerateToken request received: {data}")
response = GenerateTokenService.process_request(data)
return response
except Exception as e:
logger.exception("Unhandled exception in /GenerateToken route", exc_info=e)
return jsonify({"message": "Unhandled server error"}), 500
+26 -37
View File
@@ -11,13 +11,10 @@ from app.api.services import (
TokenValidationService,
LienCheckService,
NewTransactionCheckService,
CompleteRACcheckService,
VerifyAccountBalanceService
CompleteRACcheckService
)
from app.utils.logger import logger
from app.api.middlewares import enforce_json
from flask_jwt_extended import (jwt_required)
from app.api.middlewares import require_api_key, require_app_id, enforce_json
@@ -46,37 +43,21 @@ def serve_paths(filename):
# RACCheck Endpoint
@api.route('/rac-check', methods=['POST'])
@jwt_required()
@require_api_key
@require_app_id
def rac_check():
logger.info("RACCheck request received")
try:
logger.info("RACCheck inside try request received")
data = request.get_json()
response = RACCheckService.process_request(data)
return response
except Exception as e:
logger.exception("Unhandled exception in /RACCheck route")
return jsonify({"message": "Unhandled server error"}), 500
# VerifyAccountBalance Endpoint
@api.route('/VerifyAccountBalance', methods=['POST'])
@jwt_required()
def verify_account_balance():
logger.info("VerifyAccountBalance request received")
try:
logger.info("VerifyAccountBalance inside try request received")
data = request.get_json()
response = VerifyAccountBalanceService.process_request(data)
return response
except Exception as e:
logger.exception("Unhandled exception in /VerifyAccountBalance route")
return jsonify({"message": "Unhandled server error"}), 500
# CompleteRACcheck Endpoint
@api.route('/CompleteRACcheck', methods=['POST'])
@jwt_required()
@require_api_key
@require_app_id
def complete_rac_check():
try:
data = request.get_json()
@@ -88,7 +69,8 @@ def complete_rac_check():
# Disbursement Endpoint
@api.route('/DisburseLoan', methods=['POST'])
@jwt_required()
@require_api_key
@require_app_id
def disbursement():
try:
data = request.get_json()
@@ -101,7 +83,8 @@ def disbursement():
# CollectLoan Endpoint
@api.route('/CollectLoan', methods=['POST'])
@jwt_required()
@require_api_key
@require_app_id
def collect_loan():
try:
data = request.get_json()
@@ -114,7 +97,8 @@ def collect_loan():
# TransactionVerify Endpoint
@api.route('/TransactionVerify', methods=['POST'])
@jwt_required()
@require_api_key
@require_app_id
def transaction_verify():
try:
data = request.get_json()
@@ -125,22 +109,25 @@ def transaction_verify():
logger.exception("Unhandled exception in /TransactionVerify route")
return jsonify({"message": "Unhandled server error"}), 500
# CollectPenalCharge Endpoint
@api.route('/CollectPenalCharge', methods=['POST'])
@jwt_required()
# PenalCharge Endpoint
@api.route('/CollectPenalFee', methods=['POST'])
@require_api_key
@require_app_id
def penal_charge():
try:
data = request.get_json()
# logger.info(f"PenalCharge request received: {data}")
response = PenalChargeService.process_request(data)
return response
except Exception as e:
logger.exception("Unhandled exception in /CollectPenalCharge route")
logger.exception("Unhandled exception in /PenalCharge route")
return jsonify({"message": "Unhandled server error"}), 500
# RevokeEnableConsent Endpoint
@api.route('/RevokeEnableConsent', methods=['POST'])
@jwt_required()
@require_api_key
@require_app_id
def revoke_enable_consent():
data = request.get_json()
# logger.info(f"RevokeEnableConsent request received: {data}")
@@ -149,7 +136,8 @@ def revoke_enable_consent():
# TokenValidation Endpoint
@api.route('/TokenValidation', methods=['POST'])
@jwt_required()
@require_api_key
@require_app_id
def token_validation():
data = request.get_json()
# logger.info(f"TokenValidation request received: {data}")
@@ -158,7 +146,8 @@ def token_validation():
# LienCheck Endpoint
@api.route('/LienCheck', methods=['POST'])
@jwt_required()
@require_api_key
@require_app_id
def lien_check():
data = request.get_json()
# logger.info(f"LienCheck request received: {data}")
@@ -167,7 +156,8 @@ def lien_check():
# NewTransactionCheck Endpoint
@api.route('/NewTransactionCheck', methods=['POST'])
@jwt_required()
@require_api_key
@require_app_id
def new_transaction_check():
data = request.get_json()
# logger.info(f"NewTransactionCheck request received: {data}")
@@ -177,7 +167,6 @@ def new_transaction_check():
# Health Check Endpoint
@api.route('/system-health-check', methods=['GET'])
@jwt_required()
def health_check():
"""Basic system health check"""
try:
+3 -8
View File
@@ -16,20 +16,15 @@ class CollectLoanSchema(Schema):
comment = fields.Str(allow_none=True)
class CollectLoanResponseSchema(Schema):
responseCode = fields.Str(allow_none=True)
responseDescr = fields.Str(allow_none=True)
fullDescription = fields.Str(allow_none=True)
transactionId = fields.Str(allow_none=True)
fbnTransactionId = fields.Str(allow_none=True)
debtId = fields.Str(allow_none=True)
customerId = fields.Str(allow_none=True)
accountId = fields.Str(allow_none=True)
productId = fields.Str(allow_none=True)
amountCollected = fields.Float(required=True)
interestCollected = fields.Float(required=True)
penalChargeCollected = fields.Float(required=True)
lienAmount = fields.Float(required=True)
countryId = fields.Str(allow_none=True)
comment = fields.Str(allow_none=True)
responseCode = fields.Str(allow_none=True)
responseMessage = fields.Str(allow_none=True)
responseDescr = fields.Str(allow_none=True)
fullDescription = fields.Str(allow_none=True)
+2 -2
View File
@@ -2,7 +2,7 @@ from marshmallow import Schema, fields
class DisbursementSchema(Schema):
transactionId = fields.Str(required=False, allow_none=True)
fbnTransactionId = fields.Str(required=False, allow_none=True)
FbnTransactionId = fields.Str(required=False, allow_none=True)
debtId = fields.Str(required=False, allow_none=True)
customerId = fields.Str(required=False, allow_none=True)
accountId = fields.Str(required=False, allow_none=True)
@@ -32,7 +32,7 @@ class DisburseLoanResponseSchema(Schema):
countryId = fields.Str(allow_none=True)
responseCode = fields.Str(allow_none=True)
responseMessage = fields.Str(allow_none=True)
disburseResult = fields.Str(allow_none=True)
disburseMessage = fields.Str(allow_none=True)
disburseDate = fields.Str(allow_none=True)
disburseVerify = fields.Str(allow_none=True)
disburseDescription = fields.Str(allow_none=True)
-18
View File
@@ -1,18 +0,0 @@
from marshmallow import Schema, fields
class GenerateTokenRequestSchema(Schema):
username = fields.Str(required=True)
password = fields.Str(required=True)
grant_type = fields.Str(required=True)
class GenerateTokenResponseSchema(Schema):
access_token = fields.Str(required=True)
token_type = fields.Str(required=True)
expires_in = fields.Int(required=True)
userName = fields.Str(required=False, allow_none=True)
ipaddress = fields.Str(required=False, allow_none=True)
errorMessage = fields.Str(required=False, allow_none=True)
issued = fields.DateTime(required=False, allow_none=True)
expires = fields.DateTime(required=False, allow_none=True)
+10 -11
View File
@@ -2,23 +2,22 @@ from marshmallow import Schema, fields
# This file contains the schema for penal charge operations
class PenalChargeSchema(Schema):
channel = fields.Str(required=True)
transactionId = fields.Str(required=True)
fbnTransactionId = fields.Str(required=True)
debtId = fields.Str(required=True)
accountId = fields.Str(required=True)
penalCharge = fields.Int(required=True)
customerId = fields.Str(required=True)
lienAmount = fields.Int(required=True)
comment = fields.Str(required=True)
countryId = fields.Str(required=True)
channel = fields.Str(allow_none=True)
transactionId = fields.Str(allow_none=True)
fbnTransactionId = fields.Str(allow_none=True)
debtId = fields.Str(allow_none=True)
accountId = fields.Str(allow_none=True)
penalCharge = fields.Float(required=True)
customerId = fields.Str(allow_none=True)
lienAmount = fields.Float(required=True)
comment = fields.Str(allow_none=True)
countryId = fields.Str(allow_none=True)
#represents the response schema for penal charge
class CollectPenalFeeResponseSchema(Schema):
customerId = fields.Str(allow_none=True)
transactionId = fields.Str(allow_none=True)
amountCollected = fields.Float(required=True)
lienAmount = fields.Int(allow_none=True)
accountId = fields.Str(allow_none=True)
responseCode = fields.Str(allow_none=True)
responseMessage = fields.Str(allow_none=True)
+6 -27
View File
@@ -1,6 +1,6 @@
from marshmallow import Schema, fields
class TransactionVerifySchemaNotGood(Schema):
class TransactionVerifySchema(Schema):
channel = fields.Str(allow_none=True)
accountId = fields.Str(allow_none=True)
customerId = fields.Str(allow_none=True)
@@ -9,38 +9,17 @@ class TransactionVerifySchemaNotGood(Schema):
countryId = fields.Str(allow_none=True)
requestId = fields.Str(allow_none=True)
class TransactionVerifySchema(Schema):
customerId = fields.Str(allow_none=True)
accountId = fields.Str(allow_none=True)
transactionId = fields.Str(allow_none=True)
transactionType = fields.Str(allow_none=True)
fbnTransactionId = fields.Str(allow_none=True)
countryId = fields.Str(allow_none=True)
requestId = fields.Str(allow_none=True)
class TransactionVerifyResponseSchema(Schema):
responseCode = fields.Str(allow_none=True)
responseDescr = fields.Str(allow_none=True)
responseMessage = fields.Str(allow_none=True)
fullDescription = fields.Str(allow_none=True)
customerId = fields.Str(allow_none=True)
accountId = fields.Str(allow_none=True)
providedAmount = fields.Float(required=True)
collectedAmount = fields.Float(required=True)
transactionId = fields.Str(allow_none=True)
transactionType = fields.Str(allow_none=True)
# '''
# verify_data = {
# "customerId": loan_data.get('customerId'),
# "accountId": loan_data.get('accountId'),
# "transactionId": loan_data.get('transactionId'),
# "transactionType": "provide",
# "fbnTransactionId": loan_data.get('transactionId'),
# "countryId": "NG",
# "requestId": loan_data.get('transactionId')
# }
# '''
disburseVerify = fields.Str(allow_none=True)
verifyDescription = fields.Str(allow_none=True)
verifyResult = fields.Str(allow_none=True)
-10
View File
@@ -1,10 +0,0 @@
from marshmallow import Schema, fields
from marshmallow import Schema, fields
from datetime import date
class VerifyAccountBalanceSchema(Schema):
accountId = fields.Str(required=True)
amount = fields.Str(required=True)
requestId = fields.Str(required=True)
-2
View File
@@ -8,5 +8,3 @@ from app.api.services.token_validation import TokenValidationService
from app.api.services.lien_check import LienCheckService
from app.api.services.new_transaction_check import NewTransactionCheckService
from app.api.services.complete_rac_check_service import CompleteRACcheckService
from app.api.services.generate_token import GenerateTokenService
from app.api.services.verify_account_balance import VerifyAccountBalanceService
+35 -48
View File
@@ -1,10 +1,8 @@
import random
from flask import request, jsonify
from marshmallow import ValidationError
from app.utils.logger import logger
from app.api.helpers.response_helper import ResponseHelper
from app.api.schemas.collect_loan import CollectLoanSchema, CollectLoanResponseSchema
from app.config import Config
"""
Process the CollectLoan request.
@@ -26,62 +24,51 @@ class CollectLoanService:
validated_data = schema.load(data)
amountForCollection = validated_data.get("collectAmount")
productId = validated_data.get("productId")
customerId = validated_data.get("customerId")
amountCollected = amountForCollection
responseDescr= "Loan Collection Successful EMULATOR"
fullDescription= "Loan collection completed successfully EMULATOR"
responseMessage= "Loan collection completed successfully EMULATOR"
interestCollected = amountForCollection * 0.03
lienAmount = validated_data.get("lienAmount", 0)
isValid = not (
int(customerId[-1]) in [2, 7, 9]
)
if Config.MIN_AMOUNT_FOR_COLLECTION <= amountForCollection <= Config.MAX_AMOUNT_FOR_COLLECTION:
# amountCollected = amountForCollection if lienAmount >= amountForCollection else 0
if amountForCollection in [5555.0, 6666.0, 7777.0, 8888.0 , 9999.0, 22222.0] :
amountCollected = amountForCollection * 0.85
responseDescr = "Partial Loan Collection Successful EMULATOR"
fullDescription = "Partial Loan collection completed successfully EMULATOR"
responseMessage = "Partial Loan collection completed successfully EMULATOR"
response_data = {
"transactionId": validated_data.get("transactionId"),
"fbnTransactionId": validated_data.get("fbnTransactionId"),
"debtId": validated_data.get("debtId"),
"customerId": validated_data.get("customerId"),
"accountId": validated_data.get("accountId"),
"productId": validated_data.get("productId"),
"amountCollected": amountCollected,
"interestCollected": interestCollected,
"penalChargeCollected": 0,
"lienAmount": lienAmount if amountCollected == 0 else 0,
"countryId": validated_data.get("countryId"),
"comment": validated_data.get("comment", "Testing CollectionLoanRequest EMULATOR"),
"responseCode": "00",
"responseDescr": responseDescr,
"fullDescription": fullDescription,
"responseMessage": responseMessage
}
# Simulated processing logic
response_data = {
"transactionId": validated_data.get("transactionId"),
"debtId": validated_data.get("debtId"),
"customerId": validated_data.get("customerId"),
"accountId": validated_data.get("accountId"),
"productId": validated_data.get("productId"),
"amountCollected": amountCollected,
"countryId": validated_data.get("countryId"),
"comment": validated_data.get("comment", "Testing CollectionLoanRequest EMULATOR"),
"responseCode": "00",
"responseDescr": responseDescr,
"fullDescription": fullDescription,
"responseMessage": responseMessage
}
else:
response_data = {
"transactionId": validated_data.get("transactionId"),
"fbnTransactionId": validated_data.get("fbnTransactionId"),
"debtId": validated_data.get("debtId"),
"customerId": validated_data.get("customerId"),
"accountId": validated_data.get("accountId"),
"productId": validated_data.get("productId"),
"amountCollected": amountCollected,
"interestCollected": interestCollected,
"penalChargeCollected": 0,
"amountCollected": amountCollected,
"countryId": validated_data.get("countryId"),
"comment": validated_data.get("comment", "Testing CollectionLoanRequest EMULATOR"),
"responseCode": "00",
"responseDescr": responseDescr,
"fullDescription": fullDescription,
"responseMessage": responseMessage
}
# # Simulated processing logic
# response_data = {
# "transactionId": validated_data.get("transactionId", "T002"),
# "debtId": validated_data.get("debtId", "273194670"),
# "customerId": validated_data.get("customerId", "CN621868"),
# "accountId": validated_data.get("accountId", "2017821799"),
# "productId": validated_data.get("productId", "101"),
# "amountCollected": validated_data.get("collectAmount", 60000.00),
# "countryId": validated_data.get("countryId", "01"),
# "comment": validated_data.get("comment", "Testing CollectionLoanRequest"),
# "responseCode": "00",
# "responseDescr": "Loan Collection Successful",
# "fullDescription": "Loan collection completed successfully",
# "responseMessage": "Loan collection completed successfully"
# }
#
# Validate and serialize the response data
response_schema = CollectLoanResponseSchema()
-3
View File
@@ -40,9 +40,6 @@ class DisbursementService:
"countryId": validated_data.get("countryId"),
"responseCode": "00", # success code example
"responseMessage": "Loan Request Completed Successfully!",
"disburseVerify": datetime.datetime.now().isoformat(),
"verifyResult": "00",
"verifyDescription": "Collect Status retrieved successfully.",
"disburseDate": datetime.datetime.now().isoformat(),
"disburseResult": "00",
"disburseDescription": "Loan Request Completed Successfully!",
-89
View File
@@ -1,89 +0,0 @@
import datetime
from datetime import timedelta
from flask import request, jsonify
from marshmallow import ValidationError
from app.utils.logger import logger
from app.api.helpers.response_helper import ResponseHelper
from app.api.schemas.generate_token import GenerateTokenRequestSchema, GenerateTokenResponseSchema
from app.config import Config
from flask_jwt_extended import (
create_access_token,
)
class GenerateTokenService:
USERNAME = Config.BANK_CALL_BASIC_AUTH_USERNAME
PASSWORD = Config.BANK_CALL_BASIC_AUTH_PASSWORD
TYPE = Config.BANK_GRANT_TYPE
@staticmethod
def process_request(data):
"""
Process the GenerateToken request.
Args:
data (dict): The request JSON payload.
Returns:
tuple: (JSON response, status code)
"""
try:
logger.info("Processing GenerateToken request")
# Step 1: Validate input using schema
schema = GenerateTokenRequestSchema()
validated_data = schema.load(data)
logger.info(f"Validated data: {validated_data}")
username = validated_data.get("username")
password = validated_data.get("password")
grant_type = validated_data.get("grant_type")
if password != GenerateTokenService.PASSWORD or username != GenerateTokenService.USERNAME or grant_type != GenerateTokenService.TYPE:
return {
"message": "Invalid credentials",
"status": 401
}
expires_in = 1800
identity = username
# Step 2: Generate JWT token
access_token = create_access_token(identity=identity, expires_delta=timedelta(seconds=expires_in))
# Step 3: Get client IP address
ipaddress = request.remote_addr or "127.0.0.1"
# Step 4: Build response timestamps
issued_time = datetime.datetime.utcnow()
expires_time = issued_time + datetime.timedelta(seconds=expires_in)
# Step 5: Construct response payload
response_data = {
"access_token": access_token,
"token_type": "bearer",
"expires_in": expires_in,
"userName": username,
"ipaddress": ipaddress,
"errorMessage": "",
"issued": issued_time,
"expires": expires_time
}
# Serialize with response schema
response_schema = GenerateTokenResponseSchema()
response_json = response_schema.dump(response_data)
return jsonify(response_json), 200
except ValidationError as err:
logger.error(f"Validation Error: {err.messages}")
return jsonify({
"message": "Validation exception",
"errors": err.messages
}), 422
except Exception as e:
logger.error(f"An error occurred while generating token: {str(e)}", exc_info=True)
return jsonify({
"message": "Internal Server Error"
}), 500
+14 -21
View File
@@ -2,10 +2,7 @@ from flask import request, jsonify
from marshmallow import ValidationError
from app.utils.logger import logger
from app.api.helpers.response_helper import ResponseHelper
from app.api.schemas.penal_charge import (
PenalChargeSchema,
CollectPenalFeeResponseSchema,
)
from app.api.schemas.penal_charge import PenalChargeSchema, CollectPenalFeeResponseSchema
class PenalChargeService:
@@ -27,20 +24,14 @@ class PenalChargeService:
schema = PenalChargeSchema()
validated_data = schema.load(data)
customerId = validated_data["customerId"]
transactionId = validated_data["transactionId"]
penalCharge = validated_data["penalCharge"]
accountId = validated_data["accountId"]
lienAmount = validated_data["lienAmount"]
# Simulated processing logic
response_data = {
"customerId": validated_data.get("customerId"),
"transactionId": validated_data.get("transactionId"),
"amountCollected": validated_data.get("penalCharge", 0.0),
"accountId": validated_data.get("accountId"),
"responseCode": "00",
"responseMessage": "Penal Collection Successful",
"customerId": customerId,
"transactionId": transactionId,
"amountCollected": penalCharge,
"lienAmount": lienAmount,
"accountId": accountId,
"responseMessage": "Penal charge debited successfully"
}
# Optionally validate/serialize response using schema
@@ -51,11 +42,13 @@ class PenalChargeService:
except ValidationError as err:
logger.error(f"Validation Error: {err.messages}")
return (
jsonify({"message": "Validation exception", "errors": err.messages}),
422,
)
return jsonify({
"message": "Validation exception",
"errors": err.messages
}), 422
except Exception as e:
logger.error(f"An error occurred: {str(e)}", exc_info=True)
return jsonify({"message": "Internal Server Error"}), 500
return jsonify({
"message": "Internal Server Error"
}), 500
+4 -2
View File
@@ -26,7 +26,9 @@ class RACCheckService:
validated_data = schema.load(data)
customer_id = validated_data["customerId"]
is_valid = True
is_valid = not (
int(customer_id[-1]) in [2, 7, 9]
)
try:
@@ -40,7 +42,7 @@ class RACCheckService:
total_salary = 0
for i in range(1, salary_count + 1):
salary = (((salary_count + i) * 7919) % 200000 + 10000) * 5
salary = ((salary_count + i ) * 7919) % 200000 + 10000
salary_payments[f"salarypaymenT_{i}"] = salary
total_salary += salary
+6 -2
View File
@@ -6,6 +6,7 @@ from app.api.schemas.transaction_verify import (
TransactionVerifySchema,
TransactionVerifyResponseSchema
)
import datetime
class TransactionVerifyService:
@@ -31,13 +32,16 @@ class TransactionVerifyService:
response_data = {
"responseCode": "00",
"responseDescr": "Success",
"responseMessage": "Verification Status retrieved Successfully.",
"fullDescription": "Collect Status retrieved successfully.",
"customerId": validated_data.get("customerId"),
"accountId": validated_data.get("accountId"),
"providedAmount": 0.0,
"collectedAmount": 7.50,
"transactionId": validated_data.get("transactionId"),
"transactionType": validated_data.get("transactionType")
"transactionType": validated_data.get("transactionType"),
"disburseVerify": datetime.datetime.now().isoformat(),
"verifyResult": "00",
"verifyDescription": "Collect Status retrieved successfully.",
}
# Validate and serialize response with TransactionVerifyResponseSchema
@@ -1,50 +0,0 @@
from app.api.schemas.verify_account_balance import VerifyAccountBalanceSchema
from flask import request, jsonify
from marshmallow import ValidationError
from app.utils.logger import logger
from app.api.helpers.response_helper import ResponseHelper
class VerifyAccountBalanceService:
@staticmethod
def process_request(data):
"""
Process the RACCheck request.
Args:
data (dict): The request data.
Returns:
tuple: JSON response and status code.
"""
try:
logger.info("Processing VerifyBalance request")
# Validate input data
schema = VerifyAccountBalanceSchema()
validated_data = schema.load(data)
account_id = validated_data["accountId"]
request_id = validated_data["requestId"]
amount = validated_data["amount"]
result = {
"responseCode": "00",
"responseMessage": "Operation Successful",
"isSufficient": True
}
return jsonify(result), 200
except ValidationError as err:
logger.error(f"Validation Error: {err.messages}")
return jsonify({
"message": "Validation exception",
"errors": err.messages
}), 422
except Exception as e:
logger.error(f"An error occurred: {str(e)}", exc_info=True)
return jsonify({
"message": "Internal Server Error"
}), 500
+14 -10
View File
@@ -1,5 +1,4 @@
import os
from re import M
from dotenv import load_dotenv
from datetime import timedelta
@@ -7,23 +6,28 @@ class Config:
"""Base configuration for Flask app"""
load_dotenv()
SWAGGER_URL = os.getenv("SWAGGER_URL")
API_URL = '/api/swagger.json'
API_URL = os.getenv("API_URL")
DEBUG = True
JWT_SECRET_KEY = os.getenv("JWT_SECRET_KEY", "753fc155-6a63-4314-bd97-ae91d61dbafe")
JWT_ACCESS_TOKEN_EXPIRES = timedelta(seconds=int(os.getenv("JWT_ACCESS_TOKEN_EXPIRES", 1800)))
VALID_APP_ID = os.getenv("VALID_APP_ID", "app1")
VALID_API_KEY = os.getenv("VALID_API_KEY", "test-api-key-12345")
MIN_AMOUNT_FOR_COLLECTION = int(os.getenv("MIN_AMOUNT_FOR_COLLECTION", 10000))
MAX_AMOUNT_FOR_COLLECTION = int(os.getenv("MAX_AMOUNT_FOR_COLLECTION", 25000))
BANK_CALL_BASIC_AUTH_USERNAME = os.environ.get("BANK_CALL_BASIC_AUTH_USERNAME", "simbrella")
BANK_CALL_BASIC_AUTH_PASSWORD = os.environ.get("BANK_CALL_BASIC_AUTH_PASSWORD", "G7$k9@pL2!qR")
BANK_GRANT_TYPE = os.getenv("BANK_GRANT_TYPE", "password")
# SQLALCHEMY_DATABASE_URI =os.environ.get("DATABASE_URL", "database_url")
# SQLALCHEMY_TRACK_MODIFICATIONS = False
# SECRET_KEY = os.environ.get("SECRET_KEY", "your_secret_key")
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)
)
BASIC_AUTH_USERNAME = os.environ.get("BASIC_AUTH_USERNAME", "user")
BASIC_AUTH_PASSWORD = os.environ.get("BASIC_AUTH_PASSWORD", "password")
DEBUG = True
def configure():
load_dotenv()
load_dotenv()
settings = Config()
+1
View File
@@ -0,0 +1 @@
from .transaction_type import TransactionType
+7
View File
@@ -0,0 +1,7 @@
from enum import Enum
class InstallmentStatus(str, Enum):
PENDING = 'PENDING'
PAID = 'PAID'
OVERDUE = 'OVERDUE'
PARTIALLY_PAID = 'PARTIALLY_PAID'
+8
View File
@@ -0,0 +1,8 @@
from enum import Enum
class LoanStatus(str, Enum):
PENDING = 'PENDING'
ACTIVE = 'ACTIVE'
PAID = 'PAID'
DEFAULTED = 'DEFAULTED'
CLOSED = 'CLOSED'
+7
View File
@@ -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"
+112
View File
@@ -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)
+1
View File
@@ -0,0 +1 @@
from .routes import eco
+87
View File
@@ -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
+5
View File
@@ -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
+6
View File
@@ -0,0 +1,6 @@
from marshmallow import Schema, fields
class AuthorizeRequestSchema(Schema):
username = fields.Str(required=True)
password = fields.Str(required=True)
+13
View File
@@ -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
+15
View File
@@ -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
+10
View File
@@ -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
+5
View File
@@ -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
+102
View File
@@ -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}"
)
+32
View File
@@ -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,
# )
+33
View File
@@ -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()
+32
View File
@@ -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()
+31
View File
@@ -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()
+20 -49
View File
@@ -28,15 +28,6 @@
}
],
"tags": [
{
"name": "Auth",
"description": "Get access token for verification",
"externalDocs": {
"description": "Find out more",
"url": "https://www.simbrellang.net"
}
},
{
"name": "RACCheck",
"description": "Risk Acceptance Criteria Request",
@@ -45,14 +36,6 @@
"url": "https://www.simbrellang.net"
}
},
{
"name": "VerifyAccountBalance",
"description": "Verify Account Balance Request",
"externalDocs": {
"description": "Find out more",
"url": "https://www.simbrellang.net"
}
},
{
"name": "CompleteRACcheck",
"description": "Complete Risk Acceptance Criteria Request",
@@ -127,17 +110,11 @@
}
],
"paths": {
"/api/Auth/generate-token": {
"$ref": "swagger/paths/GenerateToken.json"
},
"/api/system-health-check": {
"$ref": "swagger/paths/HealthCheck.json"
},
"/api/rac-check": {
"$ref": "swagger/paths/RACCheck.json"
},
"/api/VerifyAccountBalance": {
"$ref": "swagger/paths/VerifyAccountBalance.json"
},
"/api/CompleteRACcheck": {
"$ref": "swagger/paths/CompleteRACcheck.json"
@@ -151,7 +128,7 @@
"/api/TransactionVerify": {
"$ref": "swagger/paths/TransactionVerify.json"
},
"/api/CollectPenalCharge": {
"/api/CollectPenalFee": {
"$ref": "swagger/paths/PenalCharge.json"
},
"/api/RevokeEnableConsent": {
@@ -169,24 +146,12 @@
},
"components": {
"schemas": {
"GenerateTokenRequest": {
"$ref": "./schemas/GenerateTokenRequest.json"
},
"GenerateTokenResponse": {
"$ref": "./schemas/GenerateTokenResponse.json"
},
"RACCheckRequest": {
"$ref": "./schemas/RACCheckRequest.json"
},
"RACCheckResponse": {
"$ref": "./schemas/RACCheckResponse.json"
},
"VerifyAccountBalanceRequest": {
"$ref": "./schemas/VerifyAccountBalanceRequest.json"
},
"VerifyAccountBalanceResponse": {
"$ref": "./schemas/VerifyAccountBalanceResponse.json"
},
"CompleteRACcheckRequest": {
"$ref": "./schemas/CompleteRACcheckRequest.json"
},
@@ -252,18 +217,24 @@
}
},
"securitySchemes": {
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT",
"description": "Standard Authorization header using the Bearer scheme. Example: 'Bearer {token}'"
}
}
"api_key": {
"type": "apiKey",
"name": "x-api-key",
"in": "header"
},
"app_id": {
"type": "apiKey",
"name": "App-Id",
"in": "header"
}
}
},
"security": [
{
"BearerAuth": []
}
]
"security": [
{
"api_key": []
},
{
"app_id": []
}
]
}
+128
View File
@@ -0,0 +1,128 @@
{
"openapi": "3.0.3",
"info": {
"title": "bank Emulator Swagger Simbrella EcoBank - OpenAPI 3.0",
"description": "This is a Simbrella EcoBank bank Backend Server Emulator 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": {
"email": "support@chiefsoft.com"
},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
},
"version": "1.0.11"
},
"servers": [
{
"url": "http://localhost:6337"
},
{
"url": "http://localhost:5000"
},
{
"url": "http://10.10.11.17:6337"
},
{
"url": "https://bank-emulator.dev.simbrellang.net"
}
],
"tags": [
{
"name": "Authentication",
"description": "EcoBank Authentication Token Request",
"externalDocs": {
"description": "Find out more",
"url": "https://www.simbrellang.net"
}
},
{
"name": "Disbursement",
"description": "Loan Disbursement Request to EcoBank",
"externalDocs": {
"description": "Find out more",
"url": "https://www.simbrellang.net"
}
},
{
"name": "CollectLoan",
"description": "Collect Loan Repayment from EcoBank Customer",
"externalDocs": {
"description": "Find out more",
"url": "https://www.simbrellang.net"
}
},
{
"name": "DebtClosureNotification",
"description": "Notify EcoBank of Loan Closure",
"externalDocs": {
"description": "Find out more",
"url": "https://www.simbrellang.net"
}
},
{
"name": "SendSMS",
"description": "Send SMS to EcoBank Customers",
"externalDocs": {
"description": "Find out more",
"url": "https://www.simbrellang.net"
}
}
],
"paths": {
"/eco/Authorize": {
"$ref": "swagger/paths/eco/Authentication.json"
},
"/eco/Disbursement": {
"$ref": "swagger/paths/eco/Disbursement.json"
},
"/eco/CollectLoan": {
"$ref": "swagger/paths/eco/CollectLoan.json"
},
"/eco/DebtClosureNotification": {
"$ref": "swagger/paths/eco/DebtClosureNotification.json"
},
"/eco/SendSMS": {
"$ref": "swagger/paths/eco/SendSMS.json"
}
},
"components": {
"schemas": {
"AuthenticationRequest": {
"$ref": "swagger/schemas/eco/AuthenticationRequest.json"
},
"AuthenticationResponse": {
"$ref": "swagger/schemas/eco/AuthenticationResponse.json"
},
"DebtClosureNotificationRequest": {
"$ref": "swagger/schemas/eco/DebtClosureNotificationRequest.json"
},
"DebtClosureNotificationResponse": {
"$ref": "swagger/schemas/eco/DebtClosureNotificationResponse.json"
},
"SendSMSRequest": {
"$ref": "swagger/schemas/eco/SendSMSRequest.json"
},
"SendSMSResponse": {
"$ref": "swagger/schemas/eco/SendSMSResponse.json"
}
},
"securitySchemes": {
"basicAuth": {
"type": "http",
"scheme": "basic"
},
"bearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT"
}
}
},
"security": [
{
"basicAuth": [],
"bearerAuth": []
}
]
}
-56
View File
@@ -1,56 +0,0 @@
{
"post": {
"tags": [
"GenerateToken"
],
"summary": "Generate Access Token Request",
"description": "Generate Access Token Request",
"operationId": "GenerateToken",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "../schemas/GenerateTokenRequest.json"
}
},
"application/xml": {
"schema": {
"$ref": "../schemas/GenerateTokenRequest.json"
}
},
"application/x-www-form-urlencoded": {
"schema": {
"$ref": "../schemas/GenerateTokenRequest.json"
}
}
}
},
"responses": {
"200": {
"description": "GenerateToken Successful",
"content": {
"application/json": {
"schema": {
"$ref": "../schemas/GenerateTokenResponse.json"
}
},
"application/xml": {
"schema": {
"$ref": "../schemas/GenerateTokenResponse.json"
}
}
}
},
"400": {
"description": "Invalid request"
},
"422": {
"description": "Validation exception"
},
"500": {
"description": "Internal server error"
}
}
}
}
@@ -1,56 +0,0 @@
{
"post": {
"tags": [
"VerifyAccountBalance"
],
"summary": "Risk Acceptance Criteria Check",
"description": "Check if a customer passes the Risk Acceptance Criteria defined by the bank",
"operationId": "verifyAccountBalance",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "../schemas/VerifyAccountBalanceRequest.json"
}
},
"application/xml": {
"schema": {
"$ref": "../schemas/VerifyAccountBalanceRequest.json"
}
},
"application/x-www-form-urlencoded": {
"schema": {
"$ref": "../schemas/VerifyAccountBalanceRequest.json"
}
}
}
},
"responses": {
"200": {
"description": "Verify Account Balance Successful",
"content": {
"application/json": {
"schema": {
"$ref": "../schemas/VerifyAccountBalanceResponse.json"
}
},
"application/xml": {
"schema": {
"$ref": "../schemas/VerifyAccountBalanceResponse.json"
}
}
}
},
"400": {
"description": "Invalid request"
},
"422": {
"description": "Validation exception"
},
"500": {
"description": "Internal server error"
}
}
}
}
+32
View File
@@ -0,0 +1,32 @@
{
"post": {
"tags": ["Authentication"],
"summary": "EcoBank Authentication",
"description": "Get bearer token from EcoBank",
"operationId": "authenticate",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "../../schemas/eco/AuthenticationRequest.json"
}
}
}
},
"responses": {
"200": {
"description": "Authentication Successful",
"content": {
"application/json": {
"schema": {
"$ref": "../../schemas/eco/AuthenticationResponse.json"
}
}
}
},
"400": { "description": "Invalid request" },
"500": { "description": "Internal server error" }
}
}
}
+33
View File
@@ -0,0 +1,33 @@
{
"post": {
"tags": ["CollectLoan"],
"summary": "Collect Loan Repayment",
"description": "Collect repayment amount from EcoBank customer",
"operationId": "collectLoan",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "../../schemas/eco/CollectLoanRequest.json"
}
}
}
},
"responses": {
"200": {
"description": "Loan Collection Successful",
"content": {
"application/json": {
"schema": {
"$ref": "../../schemas/eco/CollectLoanResponse.json"
}
}
}
},
"400": { "description": "Invalid request" },
"422": { "description": "Validation exception" },
"500": { "description": "Internal server error" }
}
}
}
@@ -0,0 +1,33 @@
{
"post": {
"tags": ["DebtClosureNotification"],
"summary": "Debt Closure Notification",
"description": "Notify EcoBank that debt has been fully repaid",
"operationId": "notifyDebtClosure",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "../../schemas/eco/DebtClosureNotificationRequest.json"
}
}
}
},
"responses": {
"200": {
"description": "Debt Closure Acknowledged",
"content": {
"application/json": {
"schema": {
"$ref": "../../schemas/eco/DebtClosureNotificationResponse.json"
}
}
}
},
"400": { "description": "Invalid request" },
"422": { "description": "Validation exception" },
"500": { "description": "Internal server error" }
}
}
}
+33
View File
@@ -0,0 +1,33 @@
{
"post": {
"tags": ["Disbursement"],
"summary": "Loan Disbursement",
"description": "Disburse loan to EcoBank customer account",
"operationId": "disburseLoan",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "../../schemas/eco/DisbursementRequest.json"
}
}
}
},
"responses": {
"200": {
"description": "Disbursement Successful",
"content": {
"application/json": {
"schema": {
"$ref": "../../schemas/eco/DisbursementResponse.json"
}
}
}
},
"400": { "description": "Invalid request" },
"422": { "description": "Validation exception" },
"500": { "description": "Internal server error" }
}
}
}
+33
View File
@@ -0,0 +1,33 @@
{
"post": {
"tags": ["SendSMS"],
"summary": "Send SMS Notification",
"description": "Send a message to one or more EcoBank customers",
"operationId": "sendSms",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "../../schemas/eco/SendSMSRequest.json"
}
}
}
},
"responses": {
"200": {
"description": "SMS Sent Successfully",
"content": {
"application/json": {
"schema": {
"$ref": "../../schemas/eco/SendSMSResponse.json"
}
}
}
},
"400": { "description": "Invalid request" },
"422": { "description": "Validation exception" },
"500": { "description": "Internal server error" }
}
}
}
@@ -86,22 +86,6 @@
"type": "string",
"example": "Loan Request Completed Successfully!",
"nullable": true
},
"disburseVerify": {
"type": "string",
"format": "date-time",
"example": "2023-10-01T12:00:00Z",
"nullable": true
},
"verifyResult": {
"type": "string",
"example": "00",
"nullable": true
},
"verifyDescription": {
"type": "string",
"example": "Collect Status retrieved successfully.",
"nullable": true
}
},
"required": [
@@ -1,21 +0,0 @@
{
"type": "object",
"properties": {
"username": {
"type": "string"
},
"password": {
"type": "string"
},
"grant_type":{
"type":"string"
}
},
"required": [
"username",
"password",
"grant_type"
]
}
@@ -1,41 +0,0 @@
{
"type": "object",
"properties": {
"access_token": {
"type": "string",
"format": "eyjhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwic3ViIjoiYWRtaW4ifQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
},
"token_type": {
"type": "string",
"format": "bearer"
},
"expires_in": {
"type": "integer",
"format": "1800"
},
"userName": {
"type": "string",
"format": "sinbrella"
},
"ipaddress": {
"type": "string",
"format": "127.0.0.1"
},
"errorMessage":{
"type":"string"
},
"issued": {
"type": "string",
"format":"date-time"
},
"expires": {
"type": "string",
"format": "date-time"
}
},
"xml": {
"name": "##default"
}
}
+2 -8
View File
@@ -16,10 +16,6 @@
"format": "double",
"example": 101.2
},
"lienAmount": {
"type": "integer",
"example": 1000
},
"accountId": {
"type": "string",
"nullable": true,
@@ -36,8 +32,6 @@
"example": "Penal charge debited successfully"
}
},
"required": [
"amountCollected"
],
"required": ["amountCollected"],
"additionalProperties": false
}
}
@@ -38,6 +38,20 @@
"transactionType": {
"type": "string",
"example": "Disbursement"
},
"disburseVerify":{
"type": "string",
"format": "date-time",
"example": "2023-10-01T12:00:00Z",
"nullable": true
},
"verifyResult": {
"type": "string",
"example": "Success"
},
"verifyDescription": {
"type": "string",
"example": "Disbursement was verified and collection completed."
}
},
"required": [
@@ -1,25 +0,0 @@
{
"type": "object",
"properties": {
"amount": {
"type": "string",
"example": "200"
},
"requestId": {
"type": "string",
"example": "RQ621868"
},
"accountId": {
"type": "string",
"example": "2017821799"
}
},
"required": [
"accountId",
"requestId",
"amount"
],
"xml": {
"name": "VerifyAccountBalanceRequest"
}
}
@@ -1,15 +0,0 @@
{
"type": "object",
"properties": {
"isSufficient": {
"type": "string",
"example": "true"
}
},
"required": [
"isSufficient"
],
"xml": {
"name": "VerifyAccountBalanceResponse"
}
}
@@ -0,0 +1,14 @@
{
"type": "object",
"required": ["username", "password"],
"properties": {
"username": {
"type": "string",
"example": "user"
},
"password": {
"type": "string",
"example": "password"
}
}
}
@@ -0,0 +1,16 @@
{
"type": "object",
"properties": {
"resultCode": {
"type": "string"
},
"resultDescription": {
"type": "string",
"example": "Authentication successful"
},
"token": {
"type": "string",
"example": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
}
}
@@ -0,0 +1,13 @@
{
"type": "object",
"required": ["requestId", "affiliateCode", "debtId", "principal", "interest", "penalty", "collectAmount"],
"properties": {
"requestId": { "type": "string", "example": "req-12345" },
"affiliateCode": { "type": "string", "example": "aff-67890" },
"debtId": { "type": "integer", "example": 123456 },
"principal": { "type": "number", "example": 1000.00 },
"interest": { "type": "number", "example": 100.00 },
"penalty": { "type": "number", "example": 50.00 },
"collectAmount": { "type": "number", "example": 1150.00 }
}
}
@@ -0,0 +1,9 @@
{
"type": "object",
"properties": {
"transactionId": { "type": "string", "example": "txn-12345" },
"amountCollected": { "type": "number", "example": 1150.00 },
"resultCode": { "type": "integer", "example": 0 },
"resultDescription": { "type": "string", "example": "Collection successful" }
}
}
@@ -0,0 +1,11 @@
{
"type": "object",
"required": ["requestId", "affiliateCode", "customerId", "accountId", "debtId"],
"properties": {
"requestId": { "type": "string", "example": "req-12345" },
"affiliateCode": { "type": "string", "example": "aff-67890" },
"customerId": { "type": "string", "example": "cust-54321" },
"accountId": { "type": "string", "example": "acc-98765" },
"debtId": { "type": "integer", "example": 123456 }
}
}
@@ -0,0 +1,7 @@
{
"type": "object",
"properties": {
"resultCode": { "type": "integer", "example": 0 },
"resultDescription": { "type": "string", "example": "Debt closure notification sent successfully" }
}
}
@@ -0,0 +1,15 @@
{
"type": "object",
"required": ["requestId", "affiliateCode", "debtId", "productId", "customerId", "accountId", "provideAmount", "collectAmount", "interestRate"],
"properties": {
"requestId": { "type": "string", "example": "req-12345" },
"affiliateCode": { "type": "string", "example": "aff-67890" },
"debtId": { "type": "integer", "example": 123456 },
"productId": { "type": "string", "example": "prod-78901" },
"customerId": { "type": "string", "example": "cust-54321" },
"accountId": { "type": "string", "example": "acc-98765" },
"provideAmount": { "type": "number", "example": 1000.00 },
"collectAmount": { "type": "number", "example": 1150.00 },
"interestRate": { "type": "number", "example": 5.0 }
}
}
@@ -0,0 +1,8 @@
{
"type": "object",
"properties": {
"transactionId": { "type": "string", "example": "txn-12345" },
"resultCode": { "type": "integer", "example": 0 },
"resultDescription": { "type": "string", "example": "Disbursement successful" }
}
}
@@ -0,0 +1,13 @@
{
"type": "object",
"required": ["requestId", "phoneNums", "affiliateCode", "message"],
"properties": {
"requestId": { "type": "string", "example": "req-12345" },
"phoneNums": {
"type": "array",
"items": { "type": "string", "example": "+1234567890" }
},
"affiliateCode": { "type": "string", "example": "aff-67890" },
"message": { "type": "string", "example": "Your verification code is 123456" }
}
}
@@ -0,0 +1,11 @@
{
"type": "object",
"properties": {
"undelivered": {
"type": "array",
"items": { "type": "string", "example": "+1234567890" }
},
"resultCode": { "type": "integer", "example": 0 },
"resultDescription": { "type": "string", "example": "SMS sent successfully" }
}
}
+2 -2
View File
@@ -6,10 +6,10 @@ Flask-Cors==3.0.10
gunicorn
flask-swagger-ui
python-dotenv
flask-jwt-extended==4.7.1
flask-jwt-extended
flask-apispec
# Logging (Python Standard Library, for reference)