1"""Bank Account System: savings and current accounts with transfers, interest and statements.
2
3Commands:
4 open savings|current <id> <name> <opening-deposit>
5 deposit <id> <amount>
6 withdraw <id> <amount>
7 transfer <from-id> <to-id> <amount>
8 interest <annual-rate-%> adds one month's interest to every savings account
9 statement <id>
10 accounts
11 quit
12Money is handled with Decimal so paise are exact.
13"""
14import sys
15from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
16
17PAISE = Decimal("0.01")
18
19
20class BankError(Exception):
21 """Base class for all banking errors."""
22
23
24class InsufficientFunds(BankError):
25 pass
26
27
28class AccountNotFound(BankError):
29 pass
30
31
32def ask(prompt: str) -> str | None:
33 try:
34 line = input(prompt)
35 except EOFError:
36 print()
37 return None
38 if not sys.stdin.isatty():
39 print(line)
40 return line.strip()
41
42
43def money(text: str) -> Decimal:
44 try:
45 value = Decimal(text.replace(",", ""))
46 except InvalidOperation:
47 raise BankError(f"'{text}' is not an amount") from None
48 if value <= 0 or value != value.quantize(PAISE):
49 raise BankError("amounts must be positive with at most two decimals")
50 return value
51
52
53def rs(value: Decimal) -> str:
54 return f"Rs {value:,.2f}"
55
56
57class Account:
58 kind = "account"
59
60 def __init__(self, number: str, owner: str, opening: Decimal):
61 self.number, self.owner = number, owner
62 self.balance = Decimal("0")
63 self.history: list[tuple[str, Decimal, Decimal]] = []
64 self.deposit(opening, "opening deposit")
65
66 def limit(self) -> Decimal:
67 """The lowest balance this account may reach."""
68 return Decimal("0")
69
70 def _record(self, description: str, amount: Decimal) -> None:
71 self.balance += amount
72 self.history.append((description, amount, self.balance))
73
74 def deposit(self, amount: Decimal, description: str = "deposit") -> None:
75 self._record(description, amount)
76
77 def withdraw(self, amount: Decimal, description: str = "withdrawal") -> None:
78 if self.balance - amount < self.limit():
79 available = self.balance - self.limit()
80 raise InsufficientFunds(f"{self.number}: only {rs(max(available, Decimal(0)))} available")
81 self._record(description, -amount)
82
83 def __str__(self) -> str:
84 return f"{self.number:<6}{self.kind:<9}{self.owner:<8}{rs(self.balance):>15}"
85
86
87class SavingsAccount(Account):
88 kind = "savings"
89 MINIMUM = Decimal("1000")
90
91 def limit(self) -> Decimal:
92 return self.MINIMUM
93
94 def add_interest(self, annual_rate: Decimal) -> Decimal:
95 interest = (self.balance * annual_rate / 100 / 12).quantize(PAISE, rounding=ROUND_HALF_UP)
96 if interest > 0:
97 self._record(f"interest @ {annual_rate}% p.a.", interest)
98 return interest
99
100
101class CurrentAccount(Account):
102 kind = "current"
103 OVERDRAFT = Decimal("5000")
104
105 def limit(self) -> Decimal:
106 return -self.OVERDRAFT
107
108
109class Bank:
110 TYPES = {"savings": SavingsAccount, "current": CurrentAccount}
111
112 def __init__(self):
113 self.accounts: dict[str, Account] = {}
114
115 def get(self, number: str) -> Account:
116 try:
117 return self.accounts[number.upper()]
118 except KeyError:
119 raise AccountNotFound(f"no account {number}") from None
120
121 def open(self, kind: str, number: str, owner: str, opening: Decimal) -> Account:
122 if kind not in self.TYPES:
123 raise BankError("account type must be savings or current")
124 if number.upper() in self.accounts:
125 raise BankError(f"account {number} already exists")
126 if kind == "savings" and opening < SavingsAccount.MINIMUM:
127 raise BankError(f"savings accounts need an opening deposit of at least {rs(SavingsAccount.MINIMUM)}")
128 account = self.TYPES[kind](number.upper(), owner, opening)
129 self.accounts[account.number] = account
130 return account
131
132 def transfer(self, src: str, dst: str, amount: Decimal) -> None:
133 a, b = self.get(src), self.get(dst)
134 if a is b:
135 raise BankError("can't transfer to the same account")
136 a.withdraw(amount, f"transfer to {b.number}")
137 b.deposit(amount, f"transfer from {a.number}")
138
139
140def run(bank: Bank, words: list[str]) -> None:
141 command = words[0].lower()
142 if command == "open":
143 account = bank.open(words[1].lower(), words[2], words[3], money(words[4]))
144 print(f"Opened {account.kind} account {account.number} for {account.owner}: {rs(account.balance)}")
145 elif command == "deposit":
146 account = bank.get(words[1])
147 account.deposit(money(words[2]))
148 print(f"{account.number}: deposited {rs(money(words[2]))}, balance {rs(account.balance)}")
149 elif command == "withdraw":
150 account = bank.get(words[1])
151 account.withdraw(money(words[2]))
152 print(f"{account.number}: withdrew {rs(money(words[2]))}, balance {rs(account.balance)}")
153 elif command == "transfer":
154 amount = money(words[3])
155 bank.transfer(words[1], words[2], amount)
156 print(f"Transferred {rs(amount)} from {words[1].upper()} to {words[2].upper()}")
157 elif command == "interest":
158 rate = Decimal(words[1].rstrip("%"))
159 for account in bank.accounts.values():
160 if isinstance(account, SavingsAccount):
161 print(f"{account.number}: interest {rs(account.add_interest(rate))}")
162 elif command == "statement":
163 account = bank.get(words[1])
164 print(f"Statement for {account.number} ({account.kind}, {account.owner})")
165 for description, amount, balance in account.history:
166 print(f" {description:<26}{amount:>+12,.2f}{balance:>14,.2f}")
167 elif command == "accounts":
168 for account in bank.accounts.values():
169 print(f" {account}")
170 print(f" Net balance of all accounts: {rs(sum((a.balance for a in bank.accounts.values()), Decimal(0)))}")
171 else:
172 raise BankError("unknown command")
173
174
175def main() -> None:
176 bank = Bank()
177 print("Bank Account System")
178 while True:
179 line = ask("> ")
180 if line is None or line.lower() == "quit":
181 break
182 if not line:
183 continue
184 try:
185 run(bank, line.split())
186 except InsufficientFunds as error:
187 print(f"Declined: {error}")
188 except BankError as error:
189 print(f"Error: {error}")
190 except (IndexError, InvalidOperation):
191 print("Error: missing or invalid arguments")
192
193
194if __name__ == "__main__":
195 main()