mercore starter
This commit is contained in:
@@ -3,5 +3,6 @@ from enum import Enum
|
||||
class LoanStatus(str, Enum):
|
||||
PENDING = "pending"
|
||||
ACTIVE = "active"
|
||||
ACTIVE_PARTIAL = "active_partial"
|
||||
START_REPAY = "start_repay"
|
||||
REPAID = "repaid"
|
||||
@@ -26,7 +26,7 @@ class ResponseHelper:
|
||||
@staticmethod
|
||||
def success(
|
||||
result_description: str = "Successful",
|
||||
result_code: str = "00",
|
||||
result_code: str = "0",
|
||||
data: Optional[Dict[str, Any]] = None
|
||||
) -> Dict[str, Any]:
|
||||
return ResponseHelper.build_response(result_code, result_description, data)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from flask import Blueprint, request, jsonify, send_from_directory
|
||||
from app.api.services import (
|
||||
LoginService,
|
||||
EligibilityCheckService,
|
||||
SelectOfferService,
|
||||
ProvideLoanService,
|
||||
@@ -42,6 +43,15 @@ def serve_paths(filename):
|
||||
swagger_dir = os.path.join("swagger")
|
||||
return send_from_directory(swagger_dir, filename)
|
||||
|
||||
# EligibilityCheck Endpoint
|
||||
@api.route("/Login", methods=["POST"])
|
||||
@jwt_required()
|
||||
def merms_login():
|
||||
data = request.get_json()
|
||||
# logger.info(f"EligibilityCheck request received: {data}")
|
||||
response = LoginService.process_request(data)
|
||||
return response
|
||||
|
||||
|
||||
# EligibilityCheck Endpoint
|
||||
@api.route("/EligibilityCheck", methods=["POST"])
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
from marshmallow import Schema, fields
|
||||
|
||||
class LoginSchema(Schema):
|
||||
username = fields.Str(required=True)
|
||||
password = fields.Str(required=True)
|
||||
@@ -7,3 +7,4 @@ from app.api.services.customer_consent import CustomerConsentService
|
||||
from app.api.services.notification_callback import NotificationCallbackService
|
||||
from app.api.services.authorization import AuthorizationService
|
||||
from app.api.services.offer_analysis import OfferAnalysis
|
||||
from app.api.services.login import LoginService
|
||||
@@ -0,0 +1,137 @@
|
||||
from flask import session, jsonify
|
||||
from app.models.loan import Loan
|
||||
from app.utils.logger import logger
|
||||
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 SimbrellaIntegration
|
||||
from app.extensions import db
|
||||
from app.models import Offer, RACCheck, Members
|
||||
from app.api.services.offer_analysis import OfferAnalysis
|
||||
from app.api.helpers.response_helper import ResponseHelper
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
from app.api.schemas.login import LoginSchema
|
||||
import datetime
|
||||
import jwt
|
||||
import random
|
||||
from app.config import Config
|
||||
|
||||
|
||||
class LoginService(BaseService):
|
||||
|
||||
@staticmethod
|
||||
def process_request(data):
|
||||
"""
|
||||
Process the Login request.
|
||||
|
||||
Args:
|
||||
data (dict): The request data.
|
||||
|
||||
Returns:
|
||||
dict: A standardized response.
|
||||
"""
|
||||
try:
|
||||
with db.session.begin():
|
||||
|
||||
validated_data = LoginService.validate_data(data, LoginSchema())
|
||||
username = validated_data.get('username')
|
||||
password = validated_data.get('password')
|
||||
|
||||
member = Members.get_member_by_username(username)
|
||||
# pass22 = generate_password_hash(password)
|
||||
# logger.info("Password generated = > {}".format(pass22) )
|
||||
|
||||
pass_check = check_password_hash(member.password, password)
|
||||
logger.info("Password check: {}".format(pass_check))
|
||||
if not member or not pass_check:
|
||||
invalid_data = {
|
||||
"error_message": "invalid username or password",
|
||||
"message_key": "invalid_username_or_password",
|
||||
}
|
||||
return ResponseHelper.success(data=invalid_data)
|
||||
|
||||
user_data = {}
|
||||
user_data["id"] = member.id,
|
||||
user_data["member_id"]= member.id,
|
||||
user_data["uid"] = str(member.uid),
|
||||
|
||||
user_token = jwt.encode(
|
||||
{"user": user_data, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=3330)},
|
||||
Config.JWT_SECRET_KEY,
|
||||
algorithm="HS256"
|
||||
)
|
||||
|
||||
# Simulate processing
|
||||
response_data = {
|
||||
"member_id": member.id,
|
||||
"uid": str(member.uid),
|
||||
"username": member.username,
|
||||
"account_name": member.account_name,
|
||||
"firstname":member.firstname,
|
||||
"lastname": member.lastname,
|
||||
"room": member.uid,
|
||||
"token": user_token
|
||||
}
|
||||
|
||||
# user = {}
|
||||
# user_data = {}
|
||||
# user_data["id"] = result_data["member_id"]
|
||||
# user_data["member_id"] =result_data["member_id"]
|
||||
# user_data["uid"] = result_data["uid"]
|
||||
|
||||
# token should expire after 24 hrs
|
||||
# user["token"] = jwt.encode(
|
||||
# {"user": user_data, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=3330)},
|
||||
# Config.JWT_SECRET_KEY,
|
||||
# algorithm="HS256"
|
||||
# )
|
||||
# user["room"] = result_data["uid"]
|
||||
# response_data = {
|
||||
# "message": "Successfully fetched auth token",
|
||||
# "data": user_data
|
||||
# }
|
||||
|
||||
return ResponseHelper.success(data=response_data)
|
||||
|
||||
except ValidationError as err:
|
||||
|
||||
logger.error(f"Validation Error: {getattr(err, 'messages', str(err))}")
|
||||
db.session.rollback()
|
||||
return ResponseHelper.unprocessable_entity(result_description="Validation exception")
|
||||
|
||||
except ValueError as err:
|
||||
logger.error(f"{getattr(err, 'messages', str(err))}")
|
||||
db.session.rollback()
|
||||
return ResponseHelper.error(result_description=str(err))
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"An error occurred: {str(e)}", exc_info=True)
|
||||
db.session.rollback()
|
||||
return ResponseHelper.internal_server_error()
|
||||
|
||||
@staticmethod
|
||||
def check_loan_limits(customer_id):
|
||||
"""
|
||||
Checks if a customer has exceeded the loan limits for given offer.
|
||||
"""
|
||||
loan = Loan.get_customer_last_loan(customer_id)
|
||||
|
||||
if not loan:
|
||||
return True
|
||||
|
||||
offer_id = loan.offer_id[:5]
|
||||
|
||||
offer = Offer.get_offer_by_id(offer_id)
|
||||
if not offer:
|
||||
logger.error(f"Offer not found for offer_id: {offer_id} (customer_id: {customer_id})")
|
||||
return False
|
||||
|
||||
daily_count = Loan.get_daily_loan_count(customer_id, offer.product_id)
|
||||
|
||||
logger.info(f"daily_count: {daily_count}, Max: {offer.max_daily_loans}")
|
||||
|
||||
if offer.max_daily_loans is not None and daily_count >= offer.max_daily_loans:
|
||||
return False
|
||||
|
||||
return True
|
||||
+2
-1
@@ -3,6 +3,7 @@ from datetime import timedelta
|
||||
|
||||
class Config:
|
||||
"""Base configuration for Flask app"""
|
||||
JWT_SECRET_KEY = os.getenv("JWT_SECRET_KEY", "")
|
||||
|
||||
SWAGGER_URL = os.getenv("SWAGGER_URL", "/documentation")
|
||||
API_URL = os.getenv("API_URL", "/swagger.json")
|
||||
@@ -15,7 +16,7 @@ class Config:
|
||||
DATABASE_USER = os.environ.get("DATABASE_USER")
|
||||
DATABASE_PASSWORD = os.environ.get("DATABASE_PASSWORD")
|
||||
DATABASE_HOST = os.environ.get("DATABASE_HOST")
|
||||
DATABASE_PORT = os.environ.get("DATABASE_PORT", 10532)
|
||||
DATABASE_PORT = os.environ.get("DATABASE_PORT", 5432)
|
||||
DATABASE_NAME = os.environ.get("DATABASE_NAME")
|
||||
|
||||
# Database Connection
|
||||
|
||||
@@ -11,6 +11,8 @@ from .loan_repayment_schedule import LoanRepaymentSchedule
|
||||
from .transaction_offers import TransactionOffer
|
||||
from .repayments_data import RepaymentsData
|
||||
from .salary import Salary
|
||||
from .members import Members
|
||||
|
||||
|
||||
__all__ = ['Customer', 'Account', 'Loan', 'Transaction', 'Repayment', 'LoanCharge', 'Offer', 'Charge', 'RACCheck', 'LoanRepaymentSchedule', 'TransactionOffer', 'RepaymentsData', 'Salary']
|
||||
|
||||
__all__ = ['Members','Customer', 'Account', 'Loan', 'Transaction', 'Repayment', 'LoanCharge', 'Offer', 'Charge', 'RACCheck', 'LoanRepaymentSchedule', 'TransactionOffer', 'RepaymentsData', 'Salary']
|
||||
@@ -0,0 +1,51 @@
|
||||
from datetime import datetime, timezone
|
||||
from app.extensions import db
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
|
||||
class Members(db.Model):
|
||||
__tablename__ = 'members'
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
|
||||
uid = db.Column(db.String(150), nullable=False)
|
||||
username = db.Column(db.String(25), nullable=False)
|
||||
password = db.Column(db.String(100), nullable=True)
|
||||
loc = db.Column(db.String(20), nullable=True)
|
||||
status = db.Column(db.Integer, default=1)
|
||||
added = db.Column(db.DateTime(timezone=False), server_default=func.now())
|
||||
updated = db.Column(db.DateTime(timezone=False), server_default=func.now(), onupdate=func.now())
|
||||
email = db.Column(db.String(100), nullable=False)
|
||||
account_name = db.Column(db.String(100), nullable=True)
|
||||
firstname = db.Column(db.String(25), nullable=False)
|
||||
lastname = db.Column(db.String(100), nullable=True)
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
"id": self.id,
|
||||
"uid": self.uid,
|
||||
"username": self.account_id,
|
||||
"account_id": self.username,
|
||||
"password": self.password,
|
||||
"loc": self.loc,
|
||||
"status": self.status,
|
||||
"added": self.added.isoformat() if self.added else None,
|
||||
"updated": self.updated.isoformat() if self.updated else None,
|
||||
"email": self.email,
|
||||
"account_name": self.account_name,
|
||||
"firstname": self.firstname,
|
||||
"lastname": self.lastname
|
||||
}
|
||||
|
||||
def __repr__(self):
|
||||
return f'<Members {self.id} - {self.amount}>'
|
||||
|
||||
@classmethod
|
||||
def get_member_by_username(cls, username):
|
||||
"""
|
||||
Return an offer by its ID.
|
||||
"""
|
||||
member = cls.query.filter_by(username=str(username)).first()
|
||||
|
||||
if not member:
|
||||
raise ValueError(f"Username = {username} not found")
|
||||
return member
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"openapi": "3.0.3",
|
||||
"info": {
|
||||
"title": "Swagger Bank Channel to Simbrella FirstAdvance - OpenAPI 3.0",
|
||||
"description": "This is a Simbrella FirstAdvance Backend Server with the OpenAPI 3.0 specification. \n\n\nSome useful links:\n- [Web Simulated Demo Page](https://digifi-salaryloan.chiefsoft.net/)\n- [Web Management Support Portal](https://digifi-office.chiefsoft.net/auth/login)",
|
||||
"title": "Swagger MERM Core - OpenAPI 3.0",
|
||||
"description": "This is MERMS Backend Server with the OpenAPI 3.0 specification. \n\n\nSome useful links:\n- [Product Page](https://www.mermsemr.com/)\n- [Dev Product Web](https://panel.mermsemr.com/)",
|
||||
"termsOfService": "http://swagger.io/terms/",
|
||||
"contact": {
|
||||
"email": "support@chiefsoft.com"
|
||||
@@ -15,13 +15,13 @@
|
||||
},
|
||||
"servers": [
|
||||
{
|
||||
"url": "http://localhost:4500"
|
||||
"url": "http://localhost:14700"
|
||||
},
|
||||
{
|
||||
"url": "http://api.dev.simbrellang.net:4500"
|
||||
"url": "https://devapi.mermsemr.com"
|
||||
},
|
||||
{
|
||||
"url": "https://api.dev.simbrellang.net"
|
||||
"url": "https://api.mermsemr.com"
|
||||
}
|
||||
],
|
||||
"tags": [
|
||||
@@ -30,7 +30,7 @@
|
||||
"description": "This feature will be used for authorizing customers.",
|
||||
"externalDocs": {
|
||||
"description": "Find out more",
|
||||
"url": "https://www.simbrellang.net"
|
||||
"url": "https://www.mermsemr.com"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -38,47 +38,23 @@
|
||||
"description": "This feature will be used for refreshing authorized customers.",
|
||||
"externalDocs": {
|
||||
"description": "Find out more",
|
||||
"url": "https://www.simbrellang.net"
|
||||
"url": "https://www.mermsemr.com"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "EligibilityCheck",
|
||||
"description": "Eligibility Check Request",
|
||||
"name": "Login",
|
||||
"description": "User Login",
|
||||
"externalDocs": {
|
||||
"description": "Find out more",
|
||||
"url": "https://www.simbrellang.net"
|
||||
"url": "https://www.mermsemr.com"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "SelectOffer",
|
||||
"description": "This method is used the send the offer the customer selected to Simbrella.",
|
||||
"name": "Register",
|
||||
"description": "Register a new user.",
|
||||
"externalDocs": {
|
||||
"description": "Find out more",
|
||||
"url": "https://www.simbrellang.net"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "ProvideLoan",
|
||||
"description": "Provide Loan Request.",
|
||||
"externalDocs": {
|
||||
"description": "Find out more",
|
||||
"url": "https://www.simbrellang.net"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "LoanStatus",
|
||||
"description": "Loan Information Request.",
|
||||
"externalDocs": {
|
||||
"description": "Find out more",
|
||||
"url": "https://www.simbrellang.net"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Repayment",
|
||||
"description": "Repayment Request.",
|
||||
"externalDocs": {
|
||||
"description": "Find out more",
|
||||
"url": "https://www.simbrellang.net"
|
||||
"url": "https://www.mermsemr.com"
|
||||
}
|
||||
}
|
||||
],
|
||||
@@ -89,59 +65,26 @@
|
||||
"/AuthorizeRefresh": {
|
||||
"$ref": "swagger/paths/AuthorizeRefresh.json"
|
||||
},
|
||||
"/EligibilityCheck": {
|
||||
"$ref": "swagger/paths/EligibilityCheck.json"
|
||||
"/Login": {
|
||||
"$ref": "swagger/paths/Login.json"
|
||||
},
|
||||
"/SelectOffer": {
|
||||
"/Register": {
|
||||
"$ref": "swagger/paths/SelectOffer.json"
|
||||
},
|
||||
"/ProvideLoan": {
|
||||
"$ref": "swagger/paths/ProvideLoan.json"
|
||||
},
|
||||
"/LoanStatus": {
|
||||
"$ref": "swagger/paths/LoanStatus.json"
|
||||
},
|
||||
"/Repayment": {
|
||||
"$ref": "swagger/paths/Repayment.json"
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
"schemas": {
|
||||
"EligibilityCheckRequest": {
|
||||
"$ref": "swagger/schemas/EligibilityCheckRequest.json"
|
||||
"Login": {
|
||||
"$ref": "swagger/schemas/LoginRequest.json"
|
||||
},
|
||||
"EligibilityCheckResponse": {
|
||||
"$ref": "swagger/schemas/EligibilityCheckResponse.json"
|
||||
"LoginResponse": {
|
||||
"$ref": "swagger/schemas/LoginResponse.json"
|
||||
},
|
||||
"SelectOfferRequest": {
|
||||
"Register": {
|
||||
"$ref": "swagger/schemas/SelectOfferRequest.json"
|
||||
},
|
||||
"SelectOfferResponse": {
|
||||
"$ref": "swagger/schemas/SelectOfferResponse.json"
|
||||
},
|
||||
"LoanStatusRequest": {
|
||||
"$ref": "swagger/schemas/LoanStatusRequest.json"
|
||||
},
|
||||
"LoanStatusResponse": {
|
||||
"$ref": "swagger/schemas/LoanStatusResponse.json"
|
||||
},
|
||||
"RepaymentRequest": {
|
||||
"$ref": "swagger/schemas/RepaymentRequest.json"
|
||||
},
|
||||
"RepaymentResponse": {
|
||||
"$ref": "swagger/schemas/RepaymentResponse.json"
|
||||
},
|
||||
"CustomerConsentRequest": {
|
||||
"$ref": "swagger/schemas/CustomerConsentRequest.json"
|
||||
},
|
||||
"CustomerConsentResponse": {
|
||||
"$ref": "swagger/schemas/CustomerConsentResponse.json"
|
||||
},
|
||||
"NotificationCallbackRequest": {
|
||||
"$ref": "swagger/schemas/NotificationCallbackRequest.json"
|
||||
},
|
||||
"NotificationCallbackResponse": {
|
||||
"$ref": "swagger/schemas/NotificationCallbackResponse.json"
|
||||
"RegisterResponse": {
|
||||
"$ref": "swagger/schemas/RegisterResponse.json"
|
||||
},
|
||||
"ApiResponse": {
|
||||
"$ref": "swagger/schemas/ApiResponse.json"
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
{
|
||||
"post": {
|
||||
"tags": [
|
||||
"Login"
|
||||
],
|
||||
"summary": "Start the process - initiate steps to eligibility RAC Checks ",
|
||||
"description": "Initiate Login Request",
|
||||
"operationId": "startLogin",
|
||||
"requestBody": {
|
||||
"description": "Post JSON to conduct eligibility tests",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "../schemas/LoginRequest.json"
|
||||
}
|
||||
},
|
||||
"application/xml": {
|
||||
"schema": {
|
||||
"$ref": "../schemas/LoginRequest.json"
|
||||
}
|
||||
},
|
||||
"application/x-www-form-urlencoded": {
|
||||
"schema": {
|
||||
"$ref": "../schemas/LoginRequest.json"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful operation",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "../schemas/LoginResponse.json"
|
||||
}
|
||||
},
|
||||
"application/xml": {
|
||||
"schema": {
|
||||
"$ref": "../schemas/LoginResponse.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Invalid request"
|
||||
},
|
||||
"422": {
|
||||
"description": "Validation exception"
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal server error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"username": {
|
||||
"type": "string",
|
||||
"example": "testaccount"
|
||||
},
|
||||
"password": {
|
||||
"type": "string",
|
||||
"example": "merms.user.panel"
|
||||
}
|
||||
},
|
||||
"xml": {
|
||||
"name": "LoginRequest"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"member_id": {
|
||||
"type": "string",
|
||||
"example": "200"
|
||||
},
|
||||
"uid": {
|
||||
"type": "string",
|
||||
"example": "8888-999998-9999"
|
||||
},
|
||||
"username": {
|
||||
"type": "string",
|
||||
"example": "username"
|
||||
},
|
||||
"account_name": {
|
||||
"type": "string",
|
||||
"example": "account_name"
|
||||
},
|
||||
"firstname": {
|
||||
"type": "string",
|
||||
"example": "firstname"
|
||||
},
|
||||
"lastname": {
|
||||
"type": "string",
|
||||
"example": "lastname"
|
||||
},
|
||||
"room": {
|
||||
"type": "string",
|
||||
"example": "room"
|
||||
},
|
||||
"token": {
|
||||
"type": "string",
|
||||
"example": "username"
|
||||
},
|
||||
"resultDescription": {
|
||||
"type": "string",
|
||||
"example": "Successful"
|
||||
},
|
||||
"resultCode": {
|
||||
"type": "string",
|
||||
"example": "00"
|
||||
}
|
||||
},
|
||||
"xml": {
|
||||
"name": "LoginResponse"
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user