remove simbrell int

This commit is contained in:
CHIEFSOFT\ameye
2025-08-23 15:05:56 -04:00
parent b363303fad
commit b1d79d87a3
6 changed files with 29 additions and 227 deletions
-1
View File
@@ -1,3 +1,2 @@
from .simbrella import SimbrellaIntegration
from .kafka import KafkaIntegration
from .merms_stripe import StripeIntegration
+18
View File
@@ -46,3 +46,21 @@ class StripeIntegration:
expand=["latest_invoice.payment_intent"], # To get details for payment confirmation
)
@staticmethod
def create_checkout_session_subscription(price_id):
try:
checkout_session = stripe.checkout.Session.create(
line_items=[
{
'price': price_id, # Use a pre-defined Stripe Price ID
'quantity': 1,
},
],
mode='subscription',
success_url='https://example.com/success?session_id={CHECKOUT_SESSION_ID}',
cancel_url='https://example.com/cancel',
)
return checkout_session.url
except stripe.error.StripeError as e:
print(f"Error creating subscription Checkout Session: {e}")
return None
-45
View File
@@ -1,45 +0,0 @@
import httpx
import json
from app.utils.logger import logger
from app.config import settings
import logging
class SimbrellaIntegration:
BASE_URL = settings.SIMBRELLA_BASE_URL
ENDPOINT_RAC_CHECKS = settings.SIMBRELLA_ENDPOINT_RAC_CHECKS
@staticmethod
def rac_check(customer_id, account_id, transaction_id):
"""
Calls the RACCheck endpoit
"""
url = f"{SimbrellaIntegration.BASE_URL}/{SimbrellaIntegration.ENDPOINT_RAC_CHECKS}"
logger.info(f"Contacting Rack Checks EndPoint: {str(url)}", exc_info=True)
payload = {
"customerId": customer_id,
"accountId": account_id,
"transactionId": str(transaction_id),
"fbnTransactionId": str(transaction_id),
"countryCode": "NG",
"channel": "USSD"
}
headers = {
"Content-Type": "application/json",
"x-api-key": f"{settings.VALID_API_KEY}",
"App-Id": f"{settings.VALID_APP_ID}",
}
try:
response = httpx.post(url, json=payload, headers=headers, timeout=10.0)
logger.info(f"This is Response: {str(response)}", exc_info=True)
return response
except Exception as e:
logger.error(f"RACCheck API call failed: {str(e)}", exc_info=True)
raise Exception(f"RACCheck API call failed: {str(e)}")
+3 -3
View File
@@ -1,11 +1,11 @@
from flask import session, jsonify
from app.models.loan import Loan
# 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.api.enums import TransactionType
# from app.api.integrations import SimbrellaIntegration
from app.extensions import db
from app.models import MembersProducts, Products, Members
+7 -178
View File
@@ -2,14 +2,14 @@ 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 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.api.integrations import SimbrellaIntegration
# from app.extensions import db
from app.models import Offer, RACCheck
from app.api.services.offer_analysis import OfferAnalysis
from app.api.helpers.response_helper import ResponseHelper
# from app.api.services.offer_analysis import OfferAnalysis
# from app.api.helpers.response_helper import ResponseHelper
import random
@@ -19,180 +19,9 @@ class EligibilityCheckService(BaseService):
@staticmethod
def process_request(data):
"""
Process the EligibilityCheck request.
pass
Args:
data (dict): The request data.
Returns:
dict: A standardized response.
"""
try:
with db.session.begin():
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)
if (EligibilityCheckService.validate_account_ownership(account_id = account_id, customer_id = customer_id)):
transaction = EligibilityCheckService.log_transaction(validated_data = validated_data)
if not transaction:
logger.error(f"Failed to log transaction")
return ResponseHelper.error(result_description="Failed to log transaction.")
else:
return ResponseHelper.error(result_description="Invalid Customer or Account")
db.session.flush()
# Determine Loan count
is_eligible = EligibilityCheckService.check_loan_limits(customer_id)
if not is_eligible:
return ResponseHelper.error(result_description="Max loan count reached")
# Call RACCheck
response = SimbrellaIntegration.rac_check(
customer_id = customer_id,
account_id = account_id,
transaction_id = transaction.transaction_id,
)
# this chek for error is not valid
if response.status_code != 200:
return ResponseHelper.error(result_description="RACCheck failed")
response = response.json()
logger.info(f"This is Response (from Eligibility Check): {str(response)}", exc_info=True)
if not response or response['responseCode'] != '00':
if response:
logger.error(f"{response['responseMessage']}")
return ResponseHelper.error(result_description=f"RACCheck failed")
rack_checks_response = response['data']['racResponse']
rac_check = RACCheck.add_rac_check(
customer_id = customer_id,
account_id = account_id,
transaction_id = transaction.transaction_id,
data = rack_checks_response
)
if not rac_check:
logger.error(f"Failed to save RACCheck")
return ResponseHelper.error(result_description="Failed to save RACCheck.")
# -----------------TIME FOR ANALYSIS TO REGISTER OFFER ----------------------
# eligible_offers = []
try:
eligible_offers = OfferAnalysis.decide_offer(
transaction_id=transactionId,
rac_check=rac_check,
validated_data=validated_data,
customer_id=customer_id,
rack_checks_response =rack_checks_response
)
except ValueError as ve:
logger.error(str(ve))
return ResponseHelper.error(result_description= str(ve))
# -----------------------------------------------------------------------
# s = Offer.get_all_offers()
# eligible_offers = []
# for offer in offers:
# # Determine an approved amount
# random_float = random.random() # temporary to play data
# approved_amount = min(offer.max_amount, offer.max_amount * random_float) #temporary for now
# approved_amount = round(approved_amount, 2)
#
# transaction_offer = TransactionOffer.create_transaction_offer(
# customer_id = customer.id,
# transaction_id = transaction.transaction_id,
# offer_id = offer.id,
# min_amount = offer.min_amount,
# max_amount = offer.max_amount,
# eligible_amount = approved_amount,
# product_id = offer.product_id,
# tenor = offer.tenor
# )
#
# # Visible offer ID: offer_id + padded(transaction_offer.id)
# padded_id = str(transaction_offer.id).zfill(6)
# public_offer_id = f"{offer.id}{padded_id}"
#
# eligible_offers.append({
# "offerId": public_offer_id,
# "product_id": offer.product_id,
# "min_amount": offer.min_amount,
# "max_amount": approved_amount,
# "tenor": offer.tenor
# })
# Simulate processing
response_data = {
"customerId": customer_id,
"transactionId": transactionId,
"countryCode": "NG",
"msisdn": msisdn,
"eligibleOffers": eligible_offers,
"accountId": account_id
}
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
pass
+1
View File
@@ -123,6 +123,7 @@ class SubscriptionService(BaseService):
],
"next_payment": '2025-10-15 11:00:07.47214'
},
'stripe_customer_id': member_data.stripe_customer_id,
"options": res_options
}