Compare commits

..

48 Commits

Author SHA1 Message Date
VivianDee 7026c8378b [fix]: Loan id 2025-04-10 13:23:47 +01:00
VivianDee b22d2f358e [fix]: Removed out product and lien amount 2025-04-10 12:58:30 +01:00
VivianDee f13ca508c2 Update provide_loan.py 2025-04-10 12:40:19 +01:00
VivianDee 87f1fa2152 [fix]: save loan 2025-04-10 12:35:46 +01:00
VivianDee 2c34c16c34 [fix]: Missing account id 2025-04-10 12:27:57 +01:00
VivianDee 1b973322c9 [add]: Loan details and repayment fix 2025-04-10 12:20:57 +01:00
CHIEFSOFT\ameye edd19b9a39 SQL Storage 2025-04-09 05:41:33 -04:00
CHIEFSOFT\ameye 773dedcd5b Arrange swagger 2025-04-07 15:29:29 -04:00
CHIEFSOFT\ameye eb4bcb025d Adjusted swagger file 2025-04-07 15:27:01 -04:00
CHIEFSOFT\ameye 37d808c144 offers fix 2025-04-07 14:02:17 -04:00
CHIEFSOFT\ameye 1f86d30c3a msisdn 2025-04-07 13:27:08 -04:00
CHIEFSOFT\ameye 946818dae6 Transaction ID added to return 2025-04-07 13:24:07 -04:00
CHIEFSOFT\ameye 333e48d32a Filters issues 2025-04-06 20:55:57 -04:00
CHIEFSOFT\ameye 6e24b498dc from sqlalchemy import and_, or_, not_ 2025-04-06 20:49:02 -04:00
CHIEFSOFT\ameye cbf57f4bfb Multiple filter 2025-04-06 20:46:25 -04:00
CHIEFSOFT\ameye bae92d36c6 transaction_id 2025-04-06 00:58:57 -04:00
CHIEFSOFT\ameye dd2da9c462 fix data 2025-04-06 00:53:14 -04:00
CHIEFSOFT\ameye f20563a9b1 transaction.id 2025-04-06 00:32:46 -04:00
CHIEFSOFT\ameye 85671081ec transaction_id 2025-04-06 00:28:44 -04:00
CHIEFSOFT\ameye 53cff748ed Return transactuin is 2025-04-06 00:18:12 -04:00
CHIEFSOFT\ameye 3b098969e2 removed migratin file 2025-04-06 00:04:29 -04:00
CHIEFSOFT\ameye 751bcb7d28 db.create_all() 2025-04-06 00:00:52 -04:00
CHIEFSOFT\ameye 25ccb240ca Fixed serialm 2025-04-05 23:55:05 -04:00
CHIEFSOFT\ameye de4554e247 reverst 2025-04-05 23:51:53 -04:00
CHIEFSOFT\ameye e1b3f4930e transactions 2025-04-05 23:36:52 -04:00
CHIEFSOFT\ameye 900d7b509c identity column 2025-04-05 23:33:51 -04:00
CHIEFSOFT\ameye 31ffbe686a table change 2025-04-05 23:30:48 -04:00
CHIEFSOFT\ameye 7b0d19c0e0 Review error state - error in test script 2025-04-05 22:26:47 -04:00
CHIEFSOFT\ameye 7087254859 test error 2025-04-05 22:23:49 -04:00
CHIEFSOFT\ameye d2d9603914 Check for error is not valid 2025-04-05 21:58:35 -04:00
CHIEFSOFT\ameye f2b5703bcb Seen responses 2025-04-05 21:55:41 -04:00
CHIEFSOFT\ameye 49c3422c94 import json 2025-04-05 21:51:41 -04:00
CHIEFSOFT\ameye 07f1db2050 Json dump result 2025-04-05 21:49:42 -04:00
CHIEFSOFT\ameye 7cbe3aefea result management 2025-04-05 21:44:33 -04:00
CHIEFSOFT\ameye e7ae1f6732 Respose code check 2025-04-05 21:19:50 -04:00
CHIEFSOFT\ameye 30233b7283 test Header for basic auths 2025-04-05 21:14:03 -04:00
CHIEFSOFT\ameye 3a30e0abff VALID_API_KEY 2025-04-05 21:03:16 -04:00
CHIEFSOFT\ameye d3b9708216 auth=auth 2025-04-05 20:59:15 -04:00
CHIEFSOFT\ameye 0e8bc63b4d response tracking to bank emulator - TEST 2025-04-05 19:11:58 -04:00
CHIEFSOFT\ameye cbc9d6363e Tracing rack chck issue 2025-04-05 18:59:35 -04:00
CHIEFSOFT\ameye 24fe303304 Missing on Api CALL - lienAmount 2025-04-05 18:47:32 -04:00
ameye 681ac19028 Merge branch 'vivian-update-01' of DigiFi/digifi-BankToProductCore into master 2025-04-04 21:48:47 +00:00
VivianDee d2ffe1c439 Merge branch 'bank-simbrella-calls' into vivian-update-01 2025-04-04 09:56:37 +01:00
VivianDee 12fc6d0ab6 Update .gitignore 2025-04-04 09:40:21 +01:00
VivianDee 04e5548a4a Create kafka.py 2025-04-04 09:39:36 +01:00
CHIEFSOFT\ameye 823ae9e2a7 Added uRL 2025-04-03 19:10:40 -04:00
VivianDee 79ac972841 [add]: threading for Kafa integration 2025-04-03 12:35:50 +01:00
VivianDee b180f8411d [add]: Kafka Integration 2025-04-03 10:49:21 +01:00
34 changed files with 342 additions and 148 deletions
+2 -1
View File
@@ -4,4 +4,5 @@ app.log
.DS_Store
migrations/__pycache__/
migrations/*.pycg
./vscode
./vscode
.vscode/settings.json
+24 -24
View File
@@ -1,24 +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"
}
// {
// "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"
// }
+14
View File
@@ -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);
+1
View File
@@ -26,6 +26,7 @@ def create_app():
CORS(app)
JWTManager(app)
CORS(app, supports_credentials=True)
# Swagger Doc
SWAGGER_URL = app.config.get("SWAGGER_URL")
+2 -1
View File
@@ -1 +1,2 @@
from .simbrella import SimbrellaClient
from .simbrella import SimbrellaIntegration
from .kafka import KafkaIntegration
+82
View File
@@ -0,0 +1,82 @@
from confluent_kafka import Producer
import json
import logging
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",
}
@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']}"
)
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}")
else:
logger.debug(f'Message delivered to {msg.topic()} [{msg.partition()}] @ offset {msg.offset()}')
@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()
# Sending loan request message to Kafka
producer.produce(
topic="PROCESS_PAYMENT",
key=str(request_id),
value=json.dumps(loan_data).encode("utf-8"),
callback=KafkaIntegration.delivery_report,
)
producer.poll(0)
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
)
raise Exception(f"Failed to send loan request to Kafka: {str(e)}")
@staticmethod
def flush():
"""Shutdown"""
producer = KafkaIntegration._get_producer()
producer.flush()
+16 -7
View File
@@ -1,8 +1,10 @@
import requests
import json
from requests.auth import HTTPBasicAuth
from app.utils.logger import logger
from app.config import settings
class SimbrellaClient:
class SimbrellaIntegration:
BASE_URL = settings.SIMBRELLA_BASE_URL
@staticmethod
@@ -10,7 +12,7 @@ class SimbrellaClient:
"""
Calls the RACCheck endpoit
"""
url = f"{SimbrellaClient.BASE_URL}/RACCheck"
url = f"{SimbrellaIntegration.BASE_URL}/RACCheck"
payload = {
"customerId": customer_id,
@@ -33,14 +35,21 @@ class SimbrellaClient:
]
}
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)
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:
logger.error(f"RACCheck API call failed: {str(err)}", exc_info=True)
return {"error": "RACCheck API error", "details": str(err)}
return {"error": "RACCheck API error"}
+2 -2
View File
@@ -15,12 +15,12 @@ def require_app_id(f):
if not app_id:
logger.error("Unauthorized access: Missing App-ID.")
return jsonify({"message": "Invalid request parameters"}), 400
return jsonify({"message": "Invalid request"}), 400
if app_id != VALID_APP_ID:
logger.error(f"Unauthorized access: Invalid App-ID {app_id}.")
return jsonify({"message": "Invalid request parameters"}), 400
return jsonify({"message": "Invalid request"}), 400
return f(*args, **kwargs)
+1 -1
View File
@@ -11,7 +11,7 @@ def require_auth(f):
def decorated(*args, **kwargs):
auth = request.headers.get('Authorization')
if not auth or not check_auth(auth):
return jsonify({"message": "Invalid request parameters"}), 401
return jsonify({"message": "Invalid request"}), 401
return f(*args, **kwargs)
return decorated
+1 -1
View File
@@ -4,4 +4,4 @@ from flask import request, jsonify
def enforce_json():
"""Middleware to enforce JSON Content-Type for incoming requests"""
if request.method in ["POST", "PUT", "PATCH"] and request.content_type != "application/json":
return jsonify({"message": "Invalid request parameters"}), 400
return jsonify({"message": "Invalid request"}), 400
+2 -2
View File
@@ -14,11 +14,11 @@ def require_api_key(f):
if not api_key:
logger.error("Unauthorized access: Missing API key.")
return jsonify({"message": "Invalid request parameters"}), 400
return jsonify({"message": "Invalid request"}), 400
if api_key != VALID_API_KEY:
logger.error("Unauthorized access: Invalid API key.")
return jsonify({"message": "Invalid request parameters"}), 400
return jsonify({"message": "Invalid request"}), 400
return f(*args, **kwargs)
+2 -2
View File
@@ -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)
+1 -1
View File
@@ -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"),
+23 -20
View File
@@ -4,7 +4,7 @@ from app.api.services.base_service import BaseService
from app.api.schemas.eligibility_check import EligibilityCheckSchema
from marshmallow import ValidationError
from app.api.enums import TransactionType
from app.api.integrations import SimbrellaClient
from app.api.integrations import SimbrellaIntegration
class EligibilityCheckService(BaseService):
TRANSACTION_TYPE = TransactionType.ELIGIBILITY_CHECK
@@ -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)
@@ -42,44 +44,45 @@ class EligibilityCheckService(BaseService):
}), 400
# Call RACCheck
response = SimbrellaClient.rac_check(
response = SimbrellaIntegration.rac_check(
customer_id = customer_id,
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", "error": response.get("message", response)}), 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
+3 -2
View File
@@ -22,10 +22,11 @@ class LoanStatusService(BaseService):
"""
try:
validated_data = LoanStatusService.validate_data(data, LoanStatusSchema())
account_id = validated_data.get('accountId')
customer_id = validated_data.get('customerId')
customer = LoanStatusService.get_or_create_customer(validated_data)
account = customer.accounts[0]
if (LoanStatusService.validate_account_ownership(account_id = account_id, customer_id = customer_id)):
if (LoanStatusService.validate_account_ownership(account_id = account.id, customer_id = customer_id)):
transaction = LoanStatusService.log_transaction(validated_data = validated_data)
if not transaction:
+43 -6
View File
@@ -1,9 +1,14 @@
from flask import request, jsonify
from marshmallow import ValidationError
from app.api.integrations.kafka import KafkaIntegration
from app.api.services.base_service import BaseService
from app.api.enums import TransactionType
from app.utils.logger import logger
from app.api.schemas.provide_loan import ProvideLoanSchema
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):
TRANSACTION_TYPE = TransactionType.PROVIDE_LOAN
@@ -24,8 +29,11 @@ class ProvideLoanService(BaseService):
validated_data = ProvideLoanService.validate_data(data, ProvideLoanSchema())
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:
@@ -33,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"
@@ -40,16 +67,20 @@ class ProvideLoanService(BaseService):
response_data = {
"requestId": "202111170001371256908",
"transactionId": "Tr201712RK9232P115",
"customerId": "CN621868",
"accountId": "ACN8263457",
"requestId": request_id,
"transactionId": transaction_id,
"customerId": customer_id,
"accountId": account_id,
"msisdn": "3451342",
"resultCode": "00",
"resultDescription": "Successful"
}
# KafkaIntegration.send_loan_request(loan_data = response_data, request_id = request_id)
# Call Kafka in a background thread
thread = Thread(target=ProvideLoanService.async_send_to_kafka, args=(response_data, request_id))
thread.start()
return response_data
@@ -72,4 +103,10 @@ class ProvideLoanService(BaseService):
logger.error(f"An error occurred: {str(e)}", exc_info=True)
return jsonify({
"message": "Internal Server Error"
}) , 500
}) , 500
def async_send_to_kafka(loan_data, request_id):
KafkaIntegration.send_loan_request(loan_data = loan_data, request_id = request_id)
KafkaIntegration.flush()
+5 -2
View File
@@ -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:
+4 -4
View File
@@ -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"
+4
View File
@@ -24,11 +24,15 @@ class Config:
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()
+8
View File
@@ -1,4 +1,5 @@
from datetime import datetime, timezone
from sqlalchemy.orm import relationship
from app.extensions import db
class Account(db.Model):
@@ -12,6 +13,13 @@ class Account(db.Model):
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))
customer = relationship(
"Customer",
primaryjoin="Customer.id == Account.customer_id",
foreign_keys=[customer_id],
back_populates="accounts",
)
@classmethod
def create_account(cls, id, customer_id, account_type, status='active'):
account = cls(
+11 -3
View File
@@ -1,4 +1,5 @@
from datetime import datetime, timezone
from sqlalchemy.orm import relationship
from app.extensions import db
from app.models.account import Account
@@ -11,12 +12,19 @@ class Customer(db.Model):
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))
accounts = relationship(
"Account",
primaryjoin="Customer.id == Account.customer_id",
foreign_keys="Account.customer_id",
back_populates="customer",
)
@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
View File
@@ -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):
+17 -5
View File
@@ -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
+25 -44
View File
@@ -19,9 +19,28 @@
},
{
"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",
@@ -61,41 +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"
}
},
{
"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"
}
}
],
"paths": {
"/Authorize": {
"$ref": "swagger/paths/Authorize.json"
},
"/AuthorizeRefresh": {
"$ref": "swagger/paths/AuthorizeRefresh.json"
},
"/EligibilityCheck": {
"$ref": "swagger/paths/EligibilityCheck.json"
},
@@ -110,18 +103,6 @@
},
"/Repayment": {
"$ref": "swagger/paths/Repayment.json"
},
"/CustomerConsent": {
"$ref": "swagger/paths/CustomerConsent.json"
},
"/NotificationCallback": {
"$ref": "swagger/paths/NotificationCallback.json"
},
"/Authorize": {
"$ref": "swagger/paths/Authorize.json"
},
"/AuthorizeRefresh": {
"$ref": "swagger/paths/AuthorizeRefresh.json"
}
},
"components": {
+1 -1
View File
@@ -43,7 +43,7 @@
}
},
"400": {
"description": "Invalid request parameters"
"description": "Invalid request"
},
"422": {
"description": "Validation exception"
+1 -1
View File
@@ -44,7 +44,7 @@
}
},
"400": {
"description": "Invalid request parameters"
"description": "Invalid request"
},
"422": {
"description": "Validation exception"
+1 -1
View File
@@ -44,7 +44,7 @@
}
},
"400": {
"description": "Invalid request parameters"
"description": "Invalid request"
},
"422": {
"description": "Validation exception"
+1 -1
View File
@@ -44,7 +44,7 @@
}
},
"400": {
"description": "Invalid request parameters"
"description": "Invalid request"
},
"422": {
"description": "Validation exception"
+1 -1
View File
@@ -44,7 +44,7 @@
}
},
"400": {
"description": "Invalid request parameters"
"description": "Invalid request"
},
"422": {
"description": "Validation exception"
+1 -1
View File
@@ -43,7 +43,7 @@
}
},
"400": {
"description": "Invalid request parameters"
"description": "Invalid request"
},
"422": {
"description": "Validation exception"
+1 -1
View File
@@ -44,7 +44,7 @@
}
},
"400": {
"description": "Invalid request parameters"
"description": "Invalid request"
},
"422": {
"description": "Validation exception"
@@ -21,15 +21,6 @@
"type": "string",
"example": "3451342"
},
"productId": {
"type": "string",
"example": "101"
},
"lienAmount": {
"type": "number",
"format": "decimal",
"example": 400
},
"requestedAmount": {
"type": "number",
"format": "decimal",
+4
View File
@@ -30,3 +30,7 @@ requests
# JWT
flask-jwt-extended
# Kafka
confluent-kafka==1.9.2