From d3a25098a7456d9f7c1c257e3533427fd26c9100 Mon Sep 17 00:00:00 2001 From: KOSASIH Date: Sat, 11 May 2024 00:01:55 +0700 Subject: [PATCH] Update transaction_processing.py --- banking/transaction_processing.py | 39 ++++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/banking/transaction_processing.py b/banking/transaction_processing.py index c377881d0..21924650b 100644 --- a/banking/transaction_processing.py +++ b/banking/transaction_processing.py @@ -2,7 +2,6 @@ import logging - def deposit(account_id: int, amount: float) -> bool: """ Deposit an amount into an account. @@ -14,7 +13,17 @@ def deposit(account_id: int, amount: float) -> bool: Returns: bool: True if the deposit was successful, False otherwise. """ - + try: + logging.info(f"Depositing {amount} into account {account_id}") + account = get_account_by_id(account_id) + if amount < 0: + raise ValueError("Amount cannot be negative") + account['balance'] += amount + save_account(account) + return True + except Exception as e: + logging.error(f"Error depositing into account {account_id}: {e}") + return False def withdraw(account_id: int, amount: float) -> bool: """ @@ -27,7 +36,19 @@ def withdraw(account_id: int, amount: float) -> bool: Returns: bool: True if the withdrawal was successful, False otherwise. """ - + try: + logging.info(f"Withdrawing {amount} from account {account_id}") + account = get_account_by_id(account_id) + if amount < 0: + raise ValueError("Amount cannot be negative") + if account['balance'] < amount: + raise ValueError("Insufficient balance") + account['balance'] -= amount + save_account(account) + return True + except Exception as e: + logging.error(f"Error withdrawing from account {account_id}: {e}") + return False def transfer(from_account_id: int, to_account_id: int, amount: float) -> bool: """ @@ -41,3 +62,15 @@ def transfer(from_account_id: int, to_account_id: int, amount: float) -> bool: Returns: bool: True if the transfer was successful, False otherwise. """ + try: + logging.info(f"Transferring {amount} from account {from_account_id} to account {to_account_id}") + if not withdraw(from_account_id, amount): + return False + if not deposit(to_account_id, amount): + # Rollback the withdrawal if deposit fails + deposit(from_account_id, amount) + return False + return True + except Exception as e: + logging.error(f"Error transferring between accounts: {e}") + return False