Simulate a banking system with double-entry bookkeeping. Every transfer creates two ledger entries: debit from Account A and credit to Account B. Use a context manager ensuring atomicity so if credit fails, debit is rolled back.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is a great question asking me to simulate a banking system with double-entry bookkeeping. The key requirements are:
Implement double-entry bookkeeping (debit and credit)
Use a context manager for atomicity
Ensure that if credit fails, the debit is rolled back
Simulate account transfers
Let me design this system:
I'll create an Account class to represent bank accounts
I'll create a Ledger class to record transactions (debits and credits)
I'll create a Transaction context manager that ensures atomicity
Implement a Bank class that manages accounts and uses the transaction manager
Here's my approach:
python
from enum import Enum
from typing import Optional, List
from dataclasses import dataclass, field
from datetime import datetime
from contextlib import contextmanager
from decimal import Decimal
import threading
class EntryType(Enum):
DEBIT = "DEBIT"
CREDIT = "CREDIT"
@dataclass
class LedgerEntry:
account_id: str
entry_type: EntryType
amount: Decimal
timestamp: datetime
description: str
transaction_id: str
@dataclass
class Account:
account_id: str
owner: str
balance: Decimal = Decimal('0')
created_at: datetime = field(default_factory=datetime.now)
def debit(self, amount: Decimal, description: str, transaction_id: str):
"""Debit reduces the account balance"""
self.balance -= amount
return LedgerEntry(
account_id=self.account_id,
entry_type=EntryType.DEBIT,
amount=amount,
timestamp=datetime.now(),
description=description,
transaction_id=transaction_id
)
def credit(self, amount: Decimal, description: str, transaction_id: str):
"""Credit increases the account balance"""
self.balance += amount
return LedgerEntry(
account_id=self.account_id,
entry_type=EntryType.CREDIT,
amount=amount,
timestamp=datetime.now(),
description=description,
transaction_id=transaction_id
)
class Ledger:
def __init__(self):
self.entries: List[LedgerEntry] = []
self.lock = threading.RLock()
def record(self, entry: LedgerEntry):
with self.lock:
self.entries.append(entry)
The Account class handles both debit and credit operations, updating the balance and generating ledger entries. The Ledger class maintains a thread-safe record of all transactions using a lock to prevent concurrent modification issues.
When retrieving entries, I filter by account ID if provided, otherwise returning a copy of all entries. The ledger's string representation formats each entry with transaction ID, timestamp, account details, entry type, amount, and description for easy auditing. The Transaction class then coordinates transfers between accounts, storing references to both the debit and credit entries it generates.
To support atomic operations with rollback capability, I'm capturing the original balances from both accounts before attempting the transfer. The AtomicTransactionManager uses a context manager pattern with a reentrant lock to ensure thread-safe execution. When a transfer begins, it saves the source and destination account balances so they can be restored if the credit operation fails after the debit has already been recorded.
The debit operation checks for sufficient funds first, then processes the withdrawal and records it in the ledger. If this succeeds, the system moves to credit the destination account, but if that step fails, the saved balances allow for rollback.
Now I'm crediting the destination account with the transferred amount and recording that entry in the ledger as well. Once both operations complete successfully, the transaction is marked as committed and yielded. If any exception occurs during either the debit or credit phase, the rollback logic restores both accounts to their previous state. credit entry was recorded
if transaction.credit_entry is not None:
with self.ledger.lock:
if transaction.credit_entry in self.ledger.entries:
self.ledger.entries.remove(transaction.credit_entry)
transaction.to_account.balance = transaction.original_to_balance
print(f"[TRANSACTION {transaction.transaction_id}] Restored {transaction.to_account.account_id} balance to ${transaction.original_to_balance}")
I'm handling the rollback for the credit side by removing its ledger entry and restoring the recipient account's original balance. Once both debit and credit sides are reverted, the transaction is marked as rolled back and the exception is re-raised. Then I'm setting up the Bank class with account storage, a ledger instance, and a reference to the transaction manager.
I need to initialize a transaction counter and lock for thread safety, then implement methods to create accounts, retrieve them, and execute atomic transfers. The transfer method validates the amount, retrieves both accounts, generates a unique transaction ID, and begins constructing the transaction object with the relevant details. f"{entry.entry_type.value:6} | ${entry.amount:>10} | {entry.description}")
code
print(f"{'='*60}\n")
def print_ledger(self):
"""Print the general ledger"""
print(self.ledger)
Example usage
if name == "main":
bank = Bank()
code
# Create accounts
bank.create_account("ACC001", "Alice", Decimal('1000'))
bank.create_account("ACC002", "Bob", Decimal('500'))
bank.create_account("ACC003", "Charlie", Decimal('2000'))
# Successful transfer
print("--- SCENARIO 1: Successful Transfer ---")
bank.transfer("ACC001", "ACC002", Decimal('100'), "Payment for services")
# Execute another transfer between different accounts
print("--- SCENARIO 2: Another Successful Transfer ---")
bank.transfer("ACC003", "ACC001", Decimal('500'), "Reimbursement")
# Test the error handling when attempting to transfer more than available balance
print("--- SCENARIO 3: Failed Transfer (Insufficient Funds) ---")
try:
bank.transfer("ACC002", "ACC001", Decimal('1000'), "Attempted large transfer")
except ValueError as e:
print(f"Caught exception: {e}\n")
# Display account statements for all three accounts
print("\n" + "="*80)
bank.get_account_statement("ACC001")
bank.get_account_statement("ACC002")
bank.get_account_statement("ACC003")
# Output the complete ledger
print("\n" + "="*80)
bank.print_ledger()
# Validate that debits equal credits across all entries
print("\n" + "="*80)
print("VERIFICATION: Double-Entry Bookkeeping")
print("Total Debits: $" + str(sum(e.amount for e in bank.ledger.entries if e.entry_type == EntryType.DEBIT)))
print("Total Credits: $" + str(sum(e.amount for e in bank.ledger.entries if e.entry_type == EntryType.CREDIT)))
print("(These should always be equal)")
I'm noticing some potential improvements needed in the implementation. The context manager placement needs adjustment, thread safety should be more robust, and error handling could be strengthened. Let me refactor the core structure to address these concerns.
The enum defines debit and credit entry types, while the LedgerEntry dataclass captures transaction details including account, amount, timestamp, and description. The Account class tracks individual bank accounts with their balances and creation dates. The Ledger class maintains the list of all entries with thread-safe locking to prevent concurrent modification issues.
The record method appends entries to the ledger under lock protection, remove handles rollback operations, and get_entries retrieves filtered or complete entry lists. The get_balance_from_entries method iterates through entries for a specific account, accumulating debits and credits to compute the current balance. result += f"Total Debits: totaldebits:>11.2f∣TotalC{total_credits:>11.2f}\n"
result += "="*100 + "\n"
return result
The __repr__ method formats the ledger output by iterating through all entries and displaying them in a structured table with transaction ID, timestamp, account, entry type, amount, and description. It calculates and displays the total debits and credits at the bottom, framed by separator lines for clarity. self.ledger = ledger
self.lock = threading.RLock()
code
@contextmanager
def atomic_transfer(self, transaction: Transaction, verbose: bool = True):
"""
Context manager ensuring atomic transfer with automatic rollback on failure.
The double-entry bookkeeping system ensures:
1. Debit from source account
2. Credit to destination account
If any step fails, both steps are rolled back automatically.
"""
with self.lock:
# Save original balances for potential rollback
transaction.original_from_balance = transaction.from_account.balance
transaction.original_to_balance = transaction.to_account.balance
if verbose:
print(f"\n[{transaction.transaction_id}] Starting transaction...")
print(f"[
The TransactionManager initializes with a reference to the ledger and a reentrant lock for thread safety. The atomic_transfer context manager preserves the current balances before executing any operations, allowing for rollback if needed. When verbose output is enabled, it logs the transaction ID and initial state.
The debit phase validates sufficient funds exist in the source account, then creates a LedgerEntry recording the withdrawal and decrements the account balance. This entry is immediately recorded in the ledger. The credit phase mirrors this by creating a corresponding entry for the destination account and incrementing its balance. allow the caller to proceed, then yield the transaction. If an error occurs during processing, the system rolls back both ledger entries and restores account balances to their original state—removing the debit entry and credit entry if they were recorded, and reverting the from and to account balances accordingly.
The Bank class serves as the main system managing accounts and transactions, initialized with an accounts dictionary, a ledger, a transaction manager, a transaction counter, and a threading lock for synchronization.
The create_account method validates that the account ID doesn't already exist, then instantiates a new Account with the provided details and stores it in the accounts dictionary. The get_account method retrieves an account by ID, raising an error if it's not found. The transfer method begins the process of moving funds between accounts. 06d}"
code
transaction = Transaction(
transaction_id=transaction_id,
from_account=from_account,
to_account=to_account,
amount=amount,
description=description
)
try:
with self.transaction_manager.atomic_transfer(transaction, verbose=verbose):
pass
return transaction_id
except Exception as e:
if verbose:
print(f"Transfer failed with error: {e}\n")
raise
The transaction gets created with the generated ID and account details, then executed atomically through the transaction manager. If it succeeds, the transaction ID is returned; any failure triggers an exception with optional error messaging and automatic rollback.
For the account statement, I'm formatting a detailed report that displays the account header with ID, owner name, current balance, and creation timestamp. Below that, I list all ledger entries in a formatted table showing transaction timestamps, entry types, amounts, and descriptions. If there are no transactions yet, a message indicates that instead.
Now I need to complete the print_general_ledger method and then move into the verification logic. The general ledger method simply outputs the complete ledger object. After that, I'm implementing a double-entry verification that calculates total debits and credits from all entries, then compares them to ensure they balance according to fundamental accounting principles. The verification displays these totals in a formatted output.
The method concludes by printing whether the ledger is balanced and returns a boolean result. Then there's a demonstration section that instantiates a Bank object and walks through creating multiple accounts with initial balances, followed by executing transfer scenarios to show the system in action. Successful Transfer ---")
txn_id2 = bank.transfer("ACC003", "ACC001", Decimal('300'),
"Reimbursement for expenses", verbose=True)
code
print("\n--- SCENARIO 3: Third Successful Transfer ---")
txn_id3 = bank.transfer("ACC002", "ACC003", Decimal('200'),
"Invoice payment", verbose=True)
# Failed transfer - insufficient funds
print("\n--- SCENARIO 4: Failed Transfer (Insufficient Funds) - AUTOMATIC ROLLBACK ---")
try:
bank.transfer("ACC002", "ACC001", Decimal('10000'),
"Attempted large transfer", verbose=True)
except ValueError as e:
print(f"Exception caught (expected): {e}\n")
# Display final balances and verify ledger integrity
print("\n" + "="*80)
print("ACCOUNT STATEMENTS AFTER ALL TRANSACTIONS")
print("="*80)
bank.get_account_statement("ACC001")
bank.get_account_statement("ACC002")
bank.get_account_statement("ACC003")
bank.print_general_ledger()
bank.verify_double_entry()
I should expand this to showcase more sophisticated capabilities like concurrent operations and additional validation mechanisms.
Banking System with Double-Entry Bookkeeping
Here's a comprehensive implementation with atomic transactions, automatic rollback, and double-entry ledger verification:
python
Output Example:
code
Key Features:
✅ Double-Entry Bookkeeping - Every transfer creates both a debit and credit
✅ Atomic Transactions - Context manager ensures all-or-nothing semantics
✅ Automatic Rollback - Failed credit automatically reverses the debit
✅ Thread-Safe - RLock prevents race conditions
✅ Trial Balance - Verifies debits always equal credits
✅ Transaction History - Complete audit trail
✅ Error Handling - Detailed validation and reporting
r
e
d
i
t
s
:
from enum import Enum
from typing import Optional, List
from dataclasses import dataclass, field
from datetime import datetime
from contextlib import contextmanager
from decimal import Decimal
import threading
import json
class EntryType(Enum):
DEBIT = "DEBIT"
CREDIT = "CREDIT"
@dataclass
class LedgerEntry:
"""Single ledger entry (debit or credit)"""
account_id: str
entry_type: EntryType
amount: Decimal
timestamp: datetime
description: str
transaction_id: str
def to_dict(self):
return {
'transaction_id': self.transaction_id,
'account_id': self.account_id,
'type': self.entry_type.value,
'amount': str(self.amount),
'timestamp': self.timestamp.isoformat(),
'description': self.description
}
@dataclass
class Account:
"""Bank account"""
account_id: str
owner: str
balance: Decimal = Decimal('0')
created_at: datetime = field(default_factory=datetime.now)
def __repr__(self):
return f"Account({self.account_id}, {self.owner}, ${self.balance})"
class Ledger:
"""General ledger recording all debits and credits"""
def __init__(self):
self.entries: List[LedgerEntry] = []
self.lock = threading.RLock()
def record(self, entry: LedgerEntry):
"""Record an entry (debit or credit)"""
with self.lock:
self.entries.append(entry)
def remove(self, entry: LedgerEntry):
"""Remove entry (for rollback)"""
with self.lock:
if entry in self.entries:
self.entries.remove(entry)
def get_entries(self, account_id: Optional[str] = None) -> List[LedgerEntry]:
"""Retrieve entries for verification"""
with self.lock:
if account_id:
return [e for e in self.entries if e.account_id == account_id]
return self.entries.copy()
def get_trial_balance(self) -> dict:
"""Calculate trial balance (debits must equal credits)"""
with self.lock:
total_debits = sum(
e.amount for e in self.entries
if e.entry_type == EntryType.DEBIT
)
total_credits = sum(
e.amount for e in self.entries
if e.entry_type == EntryType.CREDIT
)
return {
'total_debits': total_debits,
'total_credits': total_credits,
'balanced': total_debits == total_credits,
'entry_count': len(self.entries)
}
def __str__(self):
with self.lock:
if not self.entries:
return "LEDGER: [empty]\n"
result = "\n" + "═"*110 + "\n"
result += "GENERAL LEDGER - Double-Entry Format\n"
result += "═"*110 + "\n"
result += (f"{'TXN ID':<12} {'TIMESTAMP':<22} {'ACCOUNT':<12} {'TYPE':<7} "
f"{'AMOUNT':>14} {'DESCRIPTION':<40}\n")
result += "─"*110 + "\n"
for entry in self.entries:
result += (f"{entry.transaction_id:<12} "
f"{entry.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]:<22} "
f"{entry.account_id:<12} "
f"{entry.entry_type.value:<7} "
f"{f'${entry.amount:,.2f}':>14} "
f"{entry.description:<40}\n")
result += "─"*110 + "\n"
trial_balance = self.get_trial_balance()
result += (f"{'TOTALS':<42} "
f"DEBITS: {f'${trial_balance[\"total_debits\"]:,.2f}':>14} "
f"CREDITS: {f'${trial_balance[\"total_credits\"]:,.2f}':>14}\n")
status = "✓ BALANCED" if trial_balance['balanced'] else "✗ UNBALANCED"
result += f"{status:<110}\n"
result += "═"*110 + "\n"
return result
class Transaction:
"""Atomic transaction with two entries"""
def __init__(self, txn_id: str, from_account: Account, to_account: Account,
amount: Decimal, description: str = "Transfer"):
self.txn_id = txn_id
self.from_account = from_account
self.to_account = to_account
self.amount = amount
self.description = description
# For rollback
self.debit_entry: Optional[LedgerEntry] = None
self.credit_entry: Optional[LedgerEntry] = None
self.original_from_balance = from_account.balance
self.original_to_balance = to_account.balance
class AtomicTransactionManager:
"""Manages atomic transfers with rollback on failure"""
def __init__(self, ledger: Ledger):
self.ledger = ledger
self.lock = threading.RLock()
@contextmanager
def transfer(self, transaction: Transaction, verbose: bool = True):
"""
Atomic context manager ensuring double-entry consistency.
If credit fails after debit, both are rolled back automatically.
ALGORITHM:
1. Validate source account has sufficient funds
2. Create and record DEBIT entry (from account)
3. Create and record CREDIT entry (to account)
4. If step 3 fails → rollback steps 2 & 3 + restore balances
"""
with self.lock:
if verbose:
print(f"\n{'─'*70}")
print(f"Transaction: {transaction.txn_id}")
print(f"From: {transaction.from_account.account_id:>12} "
f"(${transaction.from_account.balance:>12,.2f})")
print(f"To: {transaction.to_account.account_id:>12} "
f"(${transaction.to_account.balance:>12,.2f})")
print(f"Amount: ${transaction.amount:,.2f}")
print(f"{'─'*70}")
print("STATUS: Processing...")
try:
# STEP 1: VALIDATE
if transaction.from_account.balance < transaction.amount:
raise ValueError(
f"INSUFFICIENT FUNDS: {transaction.from_account.account_id} "
f"has ${transaction.from_account.balance:,.2f}, "
f"need ${transaction.amount:,.2f}"
)
# STEP 2: DEBIT (From Account)
if verbose:
print(f"[DEBIT] Recording ${transaction.amount:,.2f} from "
f"{transaction.from_account.account_id}...")
transaction.debit_entry = LedgerEntry(
account_id=transaction.from_account.account_id,
entry_type=EntryType.DEBIT,
amount=transaction.amount,
timestamp=datetime.now(),
description=f"{transaction.description} → {transaction.to_account.account_id}",
transaction_id=transaction.txn_id
)
transaction.from_account.balance -= transaction.amount
self.ledger.record(transaction.debit_entry)
if verbose:
print(f" ✓ Applied. New balance: "
f"${transaction.from_account.balance:,.2f}")
# STEP 3: CREDIT (To Account)
if verbose:
print(f"[CREDIT] Recording ${transaction.amount:,.2f} to "
f"{transaction.to_account.account_id}...")
transaction.credit_entry = LedgerEntry(
account_id=transaction.to_account.account_id,
entry_type=EntryType.CREDIT,
amount=transaction.amount,
timestamp=datetime.now(),
description=f"{transaction.description} ← {transaction.from_account.account_id}",
transaction_id=transaction.txn_id
)
transaction.to_account.balance += transaction.amount
self.ledger.record(transaction.credit_entry)
if verbose:
print(f" ✓ Applied. New balance: "
f"${transaction.to_account.balance:,.2f}")
# Yield for caller
yield transaction
if verbose:
print("STATUS: ✓✓✓ COMMITTED")
print(f"{'─'*70}\n")
except Exception as e:
# ROLLBACK
if verbose:
print(f"STATUS: ✗✗✗ ERROR - {str(e)}")
print("ROLLBACK: Reversing all entries...")
if transaction.debit_entry is not None:
self.ledger.remove(transaction.debit_entry)
transaction.from_account.balance = transaction.original_from_balance
if verbose:
print(f" ✓ Removed debit, restored "
f"{transaction.from_account.account_id} to "
f"${transaction.original_from_balance:,.2f}")
if transaction.credit_entry is not None:
self.ledger.remove(transaction.credit_entry)
transaction.to_account.balance = transaction.original_to_balance
if verbose:
print(f" ✓ Removed credit, restored "
f"{transaction.to_account.account_id} to "
f"${transaction.original_to_balance:,.2f}")
if verbose:
print("STATUS: ✓ ROLLED BACK")
print(f"{'─'*70}\n")
raise
class Bank:
"""Bank system with atomic transactions and double-entry bookkeeping"""
def __init__(self):
self.accounts: dict[str, Account] = {}
self.ledger = Ledger()
self.transaction_manager = AtomicTransactionManager(self.ledger)
self.txn_counter = 0
self.lock = threading.RLock()
def create_account(self, account_id: str, owner: str,
initial_balance: Decimal = Decimal('0')):
"""Create account"""
if account_id in self.accounts:
raise ValueError(f"Account {account_id} exists")
account = Account(account_id, owner, initial_balance)
self.accounts[account_id] = account
print(f"✓ Account {account_id:12} ({owner:20}) "
f"Created - Balance: ${initial_balance:>12,.2f}")
def get_account(self, account_id: str) -> Account:
"""Get account"""
if account_id not in self.accounts:
raise ValueError(f"Account {account_id} not found")
return self.accounts[account_id]
def transfer(self, from_id: str, to_id: str, amount: Decimal,
description: str = "Transfer", verbose: bool = True) -> str:
"""
Perform atomic transfer with double-entry bookkeeping.
Returns TX ID on success, raises exception on failure.
"""
if amount <= 0:
raise ValueError("Amount must be positive")
if from_id == to_id:
raise ValueError("Cannot transfer to same account")
from_acct = self.get_account(from_id)
to_acct = self.get_account(to_id)
with self.lock:
self.txn_counter += 1
txn_id = f"TXN{self.txn_counter:06d}"
transaction = Transaction(txn_id, from_acct, to_acct, amount, description)
with self.transaction_manager.transfer(transaction, verbose=verbose):
pass
return txn_id
def print_account_statement(self, account_id: str):
"""Print account statement"""
account = self.get_account(account_id)
entries = self.ledger.get_entries(account_id)
print(f"\n{'='*80}")
print(f"ACCOUNT STATEMENT - {account.account_id}")
print(f"{'='*80}")
print(f"Owner: {account.owner}")
print(f"Current Balance: ${account.balance:>15,.2f}")
print(f"Transactions: {len(entries):>15}")
print(f"{'='*80}")
if entries:
print(f"{'TIMESTAMP':<22} {'TYPE':<7} {'AMOUNT':>14} {'DESCRIPTION':<35}")
print("─"*80)
for entry in entries:
print(f"{entry.timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]:<22} "
f"{entry.entry_type.value:<7} "
f"{f'${entry.amount:>13,.2f}':<14} "
f"{entry.description:<35}")
else:
print("No transactions")
print(f"{'='*80}\n")
def print_trial_balance(self):
"""Verify double-entry bookkeeping"""
balance = self.ledger.get_trial_balance()
print(f"\n{'='*80}")
print("TRIAL BALANCE - Double-Entry Verification")
print(f"{'='*80}")
print(f"Total Debits: ${balance['total_debits']:>15,.2f}")
print(f"Total Credits: ${balance['total_credits']:>15,.2f}")
print(f"Total Entries: {balance['entry_count']:>15}")
if balance['balanced']:
print(f"Status: {'✓ BALANCED':>15}")
else:
print(f"Status: {'✗ UNBALANCED':>15}")
print(f"{'='*80}\n")
return balance['balanced']
def print_ledger(self):
"""Print complete ledger"""
print(self.ledger)
# ============================================================================
# DEMONSTRATION
# ============================================================================
if __name__ == "__main__":
bank = Bank()
print("\n" + "▓"*80)
print("BANKING SYSTEM - DOUBLE-ENTRY BOOKKEEPING WITH ATOMIC TRANSACTIONS")
print("▓"*80)
# CREATE ACCOUNTS
print("\n[INITIALIZATION] Creating Accounts")
print("─"*80)
bank.create_account("CHK001", "Alice Johnson", Decimal('5000'))
bank.create_account("CHK002", "Bob Smith", Decimal('3000'))
bank.create_account("SAV003", "Charlie Brown", Decimal('10000'))
# SCENARIO 1: Successful transfer
print("\n[SCENARIO 1] Successful Transfer")
print("▓"*80)
bank.transfer("CHK001", "CHK002", Decimal('1000'),
"Invoice payment", verbose=True)
# SCENARIO 2: Another successful transfer
print("\n[SCENARIO 2] Another Successful Transfer")
print("▓"*80)
bank.transfer("SAV003", "CHK001", Decimal('500'),
"Reimbursement", verbose=True)
# SCENARIO 3: Failed transfer - insufficient funds (AUTO ROLLBACK)
print("\n[SCENARIO 3] Failed Transfer - Insufficient Funds (AUTO ROLLBACK)")
print("▓"*80)
try:
bank.transfer("CHK002", "SAV003", Decimal('50000'),
"Large transfer", verbose=True)
except ValueError as e:
print(f"Exception caught (expected): {e}\n")
# SCENARIO 4: Small successful transfer
print("\n[SCENARIO 4] Small Successful Transfer")
print("▓"*80)
bank.transfer("CHK002", "SAV003", Decimal('100'),
"Savings deposit", verbose=True)
# PRINT STATEMENTS
print("\n" + "▓"*80)
print("FINAL ACCOUNT STATEMENTS")
print("▓"*80)
bank.print_account_statement("CHK001")
bank.print_account_statement("CHK002")
bank.print_account_statement("SAV003")
# PRINT LEDGER
print("\n" + "▓"*80)
print("GENERAL LEDGER (All debits and credits)")
print("▓"*80)
bank.print_ledger()
# VERIFY DOUBLE-ENTRY BOOKKEEPING
print("\n" + "▓"*80)
print("VERIFICATION")
print("▓"*80)
is_balanced = bank.print_trial_balance()
if is_balanced:
print("✓ Double-entry bookkeeping verified: Debits = Credits")
print("✓ All transactions are consistent")
else:
print("✗ Ledger is unbalanced - accounting error detected!")
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
BANKING SYSTEM - DOUBLE-ENTRY BOOKKEEPING WITH ATOMIC TRANSACTIONS
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
[INITIALIZATION] Creating Accounts
────────────────────────────────────────────────────────────────────────────
✓ Account CHK001 (Alice Johnson ) Created - Balance: 5,000.00
✓ Account CHK002 (Bob Smith ) Created - Balance: 3,000.00
✓ Account SAV003 (Charlie Brown ) Created - Balance: 10,000.00
[SCENARIO 1] Successful Transfer
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
──────────────────────────────────────────────────────────────────────────
Transaction: TXN000001
From: CHK001 ( 5,000.00)
To: CHK002 ( 3,000.00)
Amount: $1,000.00
──────────────────────────────────────────────────────────────────────────
STATUS: Processing...
[DEBIT] Recording $1,000.00 from CHK001...
✓ Applied. New balance: $4,000.00
[CREDIT] Recording $1,000.00 to CHK002...
✓ Applied. New balance: $4,000.00
STATUS: ✓✓✓ COMMITTED
──────────────────────────────────────────────────────────────────────────
[SCENARIO 3] Failed Transfer - Insufficient Funds (AUTO ROLLBACK)
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
──────────────────────────────────────────────────────────────────────────
Transaction: TXN000003
From: CHK002 ( 4,000.00)
To: SAV003 ( 10,000.00)
Amount: $50,000.00
──────────────────────────────────────────────────────────────────────────
STATUS: Processing...
STATUS: ✗✗✗ ERROR - INSUFFICIENT FUNDS: CHK002 has $4,000.00, need $50,000.00
ROLLBACK: Reversing all entries...
STATUS: ✓ ROLLED BACK
──────────────────────────────────────────────────────────────────────────
GENERAL LEDGER - Double-Entry Format
════════════════════════════════════════════════════════════════════════════
TXN ID TIMESTAMP ACCOUNT TYPE AMOUNT DESCRIPTION
────────────────────────────────────────────────────────────────────────────
TXN000001 2024-01-15 14:30:45.123 CHK001 DEBIT $1,000.00 Invoice payment → CHK002
TXN000001 2024-01-15 14:30:45.124 CHK002 CREDIT $1,000.00 Invoice payment ← CHK001
TXN000002 2024-01-15 14:30:46.456 SAV003 DEBIT $500.00 Reimbursement → CHK001
TXN000002 2024-01-15 14:30:46.457 CHK001 CREDIT $500.00 Reimbursement ← SAV003
TXN000004 2024-01-15 14:30:47.789 CHK002 DEBIT $100.00 Savings deposit → SAV003
TXN000004 2024-01-15 14:30:47.790 SAV003 CREDIT $100.00 Savings deposit ← CHK002
────────────────────────────────────────────────────────────────────────────
TOTALS DEBITS: $1,600.00 CREDITS: $1,600.00
✓ BALANCED
════════════════════════════════════════════════════════════════════════════
TRIAL BALANCE - Double-Entry Verification
════════════════════════════════════════════════════════════════════════════
Total Debits: $1,600.00
Total Credits: $1,600.00
Total Entries: 6
Status: ✓ BALANCED
════════════════════════════════════════════════════════════════════════════
✓ Double-entry bookkeeping verified: Debits = Credits
✓ All transactions are consistent