diff --git a/app/api/services/offer_analysis.py b/app/api/services/offer_analysis.py index 17736e7..212546d 100644 --- a/app/api/services/offer_analysis.py +++ b/app/api/services/offer_analysis.py @@ -34,14 +34,8 @@ class OfferAnalysis: return transaction_offer, offer, eligible_amount, original_transaction @staticmethod - def decide_offer(transaction_id, rac_check, validated_data,customer): - # if we have active offers - we have to feed off it - - # we can now find the origin transactions - last_customer_loan = Loan.get_customer_last_loan(customer.id) #Find the last loan - it will have original_transaction - logger.info(f"{last_customer_loan}") - - """ + def decide_offer(transaction_id, rac_check, validated_data, customer): + """ Find the last loan - it will have original_transaction This loan is part of the original approval where transaction_id = original_transaction for this account @@ -61,16 +55,37 @@ class OfferAnalysis: No need for fresh construct """ + # if we have active offers - we have to feed off it + # we can now find the origin transactions + last_customer_loan = Loan.get_customer_last_loan(customer.id) #Find the last loan - it will have original_transaction + logger.info(f"{last_customer_loan}") + new_eligible_amount = 0 + + if last_customer_loan: + original_transaction = last_customer_loan.original_transaction or last_customer_loan.transaction_id + + real_eligible_amount = last_customer_loan.eligible_amount + + active_loans = Loan.get_active_loans_by_original_transaction(original_transaction) + + sum_active_loans = sum(loan.current_loan_amount for loan in active_loans) + + new_eligible_amount = max(real_eligible_amount - sum_active_loans, 0) + + logger.info(f"Real eligible: {real_eligible_amount}, Sum of active: {sum_active_loans}, New eligible: {new_eligible_amount}") + + # Construct eligible_offers - # Do this if no active loan or registered offers offers = Offer.get_all_offers() eligible_offers = [] + for offer in offers: - # Determine an approved amount + # Get 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 = new_eligible_amount if new_eligible_amount > 0 else min(offer.max_amount, offer.max_amount * random_float) approved_amount = round(approved_amount, 2) transaction_offer = TransactionOffer.create_transaction_offer( diff --git a/app/models/loan.py b/app/models/loan.py index e8188f2..9b77415 100644 --- a/app/models/loan.py +++ b/app/models/loan.py @@ -158,6 +158,20 @@ class Loan(db.Model): return loan + @classmethod + def get_active_loans_by_original_transaction(cls, original_transaction_id): + """ + Get all active loans with the same original_transaction ID. + """ + + active_loans = cls.query.filter_by( + original_transaction=original_transaction_id, + # status='active' + ).all() + + return active_loans + + @classmethod def update_status(cls, loan_id, status): """