Untitled

mail@pastecode.io avatarunknown
plain_text
2 months ago
1.6 kB
5
Indexable
Never
# Assume that you have already defined your domain entities and domain services.

# Domain entities
class Account:
    def __init__(self, account_id, balance):
        self.account_id = account_id
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

    def withdraw(self, amount):
        if self.balance >= amount:
            self.balance -= amount
            return True
        return False

# Domain services
class AccountRepository:
    def __init__(self):
        self.accounts = {}

    def get_account_by_id(self, account_id):
        return self.accounts.get(account_id)

    def save_account(self, account):
        self.accounts[account.account_id] = account

# Application service
class TransferService:
    def __init__(self, account_repository):
        self.account_repository = account_repository

    def transfer_money(self, source_account_id, target_account_id, amount):
        source_account = self.account_repository.get_account_by_id(source_account_id)
        target_account = self.account_repository.get_account_by_id(target_account_id)

        if not source_account or not target_account:
            return "Invalid account IDs."

        if source_account.withdraw(amount):
            target_account.deposit(amount)
            self.account_repository.save_account(source_account)
            self.account_repository.save_account(target_account)
            return "Money transferred successfully."
        else:
            return "Insufficient balance for the transfer."