-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathATM_System.py
More file actions
413 lines (325 loc) · 15.1 KB
/
Copy pathATM_System.py
File metadata and controls
413 lines (325 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
from abc import ABC, abstractmethod
from datetime import datetime
import random
# ==========================================
# 1. CUSTOM EXCEPTIONS
# ==========================================
class InvalidPINError(Exception): pass
class CardBlockedError(Exception): pass
class InsufficientBalanceError(Exception): pass
class InsufficientATMFundsError(Exception): pass
class InvalidAmountError(Exception): pass
class AccountInactiveError(Exception): pass
class DailyLimitExceededError(Exception): pass
class InvalidAccountError(Exception): pass
# ==========================================
# 2. TRANSACTION CLASSES (Inheritance & Abstraction)
# ==========================================
class Transaction(ABC):
"""Abstract base class representing a generic financial transaction."""
def __init__(self, amount: float, account):
self.txn_id = f"TXN-{random.randint(10000, 99999)}"
self.timestamp = datetime.now()
self.amount = amount
self.account = account
self.status = "PENDING"
@abstractmethod
def execute(self) -> bool:
pass
class DepositTransaction(Transaction):
"""Handles deposit transactions."""
def execute(self) -> bool:
self.account._balance += self.amount
self.status = "SUCCESS"
self.account.add_transaction(self)
return True
class WithdrawalTransaction(Transaction):
"""Handles withdrawal transactions."""
def execute(self) -> bool:
self.account._balance -= self.amount
self.status = "SUCCESS"
self.account.add_transaction(self)
return True
class TransferTransaction(Transaction):
"""Handles transfer transactions between two accounts."""
def __init__(self, amount: float, account, recipient_account):
super().__init__(amount, account)
self.recipient_account = recipient_account
def execute(self) -> bool:
self.account._balance -= self.amount
self.recipient_account._balance += self.amount
self.status = "SUCCESS"
self.account.add_transaction(self)
# Recipient transaction record
recipient_record = TransferTransaction(self.amount, self.recipient_account, self.account)
recipient_record.txn_id = self.txn_id
recipient_record.status = "SUCCESS"
self.recipient_account.add_transaction(recipient_record)
return True
# ==========================================
# 3. ACCOUNT CLASSES (Encapsulation, Inheritance, Polymorphism)
# ==========================================
class Account(ABC):
"""Abstract base class for all bank account types."""
def __init__(self, account_number: str, initial_balance: float):
self._account_number = account_number
self._balance = initial_balance
self._is_active = True
self._transaction_history = []
self._daily_withdrawn = 0.0
@property
def account_number(self):
return self._account_number
@property
def balance(self):
return self._balance
@property
def is_active(self):
return self._is_active
def add_transaction(self, transaction: Transaction):
self._transaction_history.append(transaction)
def get_mini_statement(self):
return self._transaction_history[-5:]
@abstractmethod
def validate_withdrawal(self, amount: float):
pass
class SavingsAccount(Account):
"""Savings Account implementation with minimum balance and daily limit constraints."""
MIN_BALANCE = 5000.0
PER_TXN_LIMIT = 50000.0
DAILY_LIMIT = 100000.0
def validate_withdrawal(self, amount: float):
if not self._is_active:
raise AccountInactiveError("Account is currently inactive.")
if amount <= 0:
raise InvalidAmountError("Withdrawal amount must be positive.")
if amount > self.PER_TXN_LIMIT:
raise InvalidAmountError(f"Exceeds max per-transaction limit of Rs. {self.PER_TXN_LIMIT:,.2f}")
if self._daily_withdrawn + amount > self.DAILY_LIMIT:
raise DailyLimitExceededError("Daily withdrawal limit reached.")
if (self._balance - amount) < self.MIN_BALANCE:
raise InsufficientBalanceError(f"Must maintain a minimum balance of Rs. {self.MIN_BALANCE:,.2f}")
class CurrentAccount(Account):
"""Current Account implementation allowing overdraft up to a defined limit."""
OVERDRAFT_LIMIT = 50000.0
def validate_withdrawal(self, amount: float):
if not self._is_active:
raise AccountInactiveError("Account is currently inactive.")
if amount <= 0:
raise InvalidAmountError("Withdrawal amount must be positive.")
if (self._balance - amount) < -self.OVERDRAFT_LIMIT:
raise InsufficientBalanceError(f"Exceeds maximum allowed overdraft limit of Rs. {self.OVERDRAFT_LIMIT:,.2f}")
# ==========================================
# 4. CARD, CUSTOMER, & BANK CLASSES
# ==========================================
class Card:
"""Represents a customer's ATM Card with PIN protection and blocking capabilities."""
def __init__(self, card_number: str, pin: str):
self._card_number = card_number
self.__pin = pin # Double underscore for private protection
self._failed_attempts = 0
self._is_blocked = False
@property
def card_number(self):
return self._card_number
@property
def is_blocked(self):
return self._is_blocked
def verify_pin(self, pin: str) -> bool:
if self._is_blocked:
raise CardBlockedError("This card is blocked due to excessive failed PIN attempts.")
if self.__pin == pin:
self._failed_attempts = 0
return True
else:
self._failed_attempts += 1
if self._failed_attempts >= 3:
self._is_blocked = True
raise CardBlockedError("3 incorrect PIN attempts. Card has been BLOCKED.")
raise InvalidPINError(f"Invalid PIN. Remaining attempts: {3 - self._failed_attempts}")
def change_pin(self, old_pin: str, new_pin: str):
if self.verify_pin(old_pin):
if len(new_pin) != 4 or not new_pin.isdigit():
raise InvalidPINError("New PIN must be a 4-digit number.")
self.__pin = new_pin
class Customer:
"""Represents a bank customer owning accounts and cards."""
def __init__(self, customer_id: str, name: str, phone: str, card: Card):
self.customer_id = customer_id
self.name = name
self.phone = phone
self.card = card
self.accounts = []
def add_account(self, account: Account):
self.accounts.append(account)
class Bank:
"""Manages system-wide operations, account routing, and customer storage."""
def __init__(self, name: str):
self.name = name
self.customers = {}
self.accounts = {}
def register_customer(self, customer: Customer):
self.customers[customer.card.card_number] = customer
def register_account(self, account: Account):
self.accounts[account.account_number] = account
def get_customer_by_card(self, card_number: str) -> Customer:
return self.customers.get(card_number)
def get_account(self, account_number: str) -> Account:
return self.accounts.get(account_number)
# ==========================================
# 5. ATM ENGINE & CASH MANAGEMENT
# ==========================================
class ATM:
"""Manages Cash Denominations and core hardware operations."""
def __init__(self, bank: Bank, notes_500: int, notes_1000: int, notes_5000: int):
self.bank = bank
self.inventory = {
5000: notes_5000,
1000: notes_1000,
500: notes_500
}
def get_total_cash(self) -> float:
return sum(denom * count for denom, count in self.inventory.items())
def can_dispense(self, amount: int) -> tuple[bool, dict]:
"""Greedy approach to check if amount can be dispensed using available notes."""
if amount > self.get_total_cash():
return False, {}
remaining = amount
dispense_plan = {}
for denom in sorted(self.inventory.keys(), reverse=True):
notes_needed = remaining // denom
notes_to_use = min(notes_needed, self.inventory[denom])
if notes_to_use > 0:
dispense_plan[denom] = notes_to_use
remaining -= notes_to_use * denom
if remaining == 0:
return True, dispense_plan
return False, {}
def dispense_cash(self, amount: int):
possible, plan = self.can_dispense(amount)
if not possible:
raise InsufficientATMFundsError("ATM cannot dispense the exact amount with available note denominations.")
# Deduct notes from inventory
for denom, count in plan.items():
self.inventory[denom] -= count
print(f"\n[ATM DISPENSED]: Cash successfully dispensed: {plan}")
# ==========================================
# 6. CONSOLE INTERFACE & DRIVER PROGRAM
# ==========================================
def main():
# Setup Bank System
my_bank = Bank("National Tech Bank")
# Create Accounts
savings_acc = SavingsAccount("10002345", initial_balance=75000.0)
current_acc = CurrentAccount("20002345", initial_balance=20000.0)
my_bank.register_account(savings_acc)
my_bank.register_account(current_acc)
# Create Card & Customer
card = Card("1234-5678-9012-3456", "1234")
customer = Customer("CUST-101", "Alex Mercer", "555-0199", card)
customer.add_account(savings_acc)
customer.add_account(current_acc)
my_bank.register_customer(customer)
# Initialize ATM with cash inventory (Rs. 120,000 total)
# 500x20 = 10,000 | 1000x30 = 30,000 | 5000x16 = 80,000
atm = ATM(my_bank, notes_500=20, notes_1000=30, notes_5000=16)
# --- ATM Authentication Loop ---
print("========================================")
print(" WELCOME TO NATIONAL TECH ATM ")
print("========================================")
card_input = input("Insert Card (Enter Card Number) [Demo: 1234-5678-9012-3456]: ")
current_customer = my_bank.get_customer_by_card(card_input)
# Ensure customer actually has accounts registered
if not current_customer.accounts:
print("No active bank accounts found for this customer.")
return
# Select Active Account safely
print("\nSelect Account:")
for idx, acc in enumerate(current_customer.accounts, 1):
acc_type = "Savings" if isinstance(acc, SavingsAccount) else "Current"
print(f"{idx}. {acc_type} Account ({acc.account_number})")
# Loop until the user inputs a valid choice
while True:
try:
choice_input = int(input("Choice: "))
if 1 <= choice_input <= len(current_customer.accounts):
active_account = current_customer.accounts[choice_input - 1]
break
else:
print(f"Please enter a number between 1 and {len(current_customer.accounts)}.")
except ValueError:
print("Invalid input. Please enter a valid integer.")
# --- ATM Main Menu Loop ---
while True:
print("\n" + "="*10 + " ATM MENU " + "="*10)
print("1. Check Balance")
print("2. Deposit")
print("3. Withdraw")
print("4. Transfer Money")
print("5. Change PIN")
print("6. Mini Statement")
print("7. Exit")
choice = input("Select an option (1-7): ")
try:
if choice == "1":
print(f"\nAccount Balance: Rs. {active_account.balance:,.2f}")
elif choice == "2":
amount = float(input("Enter deposit amount: Rs. "))
if amount <= 0:
raise InvalidAmountError("Deposit amount must be positive.")
txn = DepositTransaction(amount, active_account)
txn.execute()
print(f"Successfully deposited Rs. {amount:,.2f}")
print(f"Transaction ID: {txn.txn_id}")
print(f"New Balance: Rs. {active_account.balance:,.2f}")
elif choice == "3":
amount = float(input("Enter withdrawal amount (Multiples of 500): Rs. "))
if amount < 500:
raise InvalidAmountError("Minimum withdrawal amount is Rs. 500.")
# Check business logic validation
active_account.validate_withdrawal(amount)
# Execute cash & account balance updates
atm.dispense_cash(int(amount))
txn = WithdrawalTransaction(amount, active_account)
txn.execute()
active_account._daily_withdrawn += amount
print(f"Withdrawal Successful! Transaction ID: {txn.txn_id}")
print(f"New Balance: Rs. {active_account.balance:,.2f}")
elif choice == "4":
recipient_acc_num = input("Enter recipient account number: ")
recipient_account = my_bank.get_account(recipient_acc_num)
if not recipient_account:
raise InvalidAccountError("Target account not found.")
if recipient_account.account_number == active_account.account_number:
raise InvalidAccountError("Cannot transfer funds to the same account.")
amount = float(input("Enter transfer amount: Rs. "))
active_account.validate_withdrawal(amount)
txn = TransferTransaction(amount, active_account, recipient_account)
txn.execute()
print(f"Transferred Rs. {amount:,.2f} to Account {recipient_acc_num}")
print(f"Transaction ID: {txn.txn_id}")
elif choice == "5":
old_pin = input("Enter Old PIN: ")
new_pin = input("Enter New 4-Digit PIN: ")
current_customer.card.change_pin(old_pin, new_pin)
print("PIN changed successfully!")
elif choice == "6":
print(f"\n========== MINI STATEMENT ==========")
print(f"Account: {active_account.account_number}")
print(f"{'Date/Time':<20} | {'Type':<12} | {'Amount':<10}")
print("-" * 48)
for txn in active_account.get_mini_statement():
sign = "+" if isinstance(txn, DepositTransaction) else "-"
txn_type = type(txn).__name__.replace("Transaction", "")
date_str = txn.timestamp.strftime("%d-%b %H:%M")
print(f"{date_str:<20} | {txn_type:<12} | {sign}Rs.{txn.amount:,.0f}")
print(f"Current Balance: Rs. {active_account.balance:,.2f}")
elif choice == "7":
print("\nThank you for using National Tech ATM. Goodbye!")
break
else:
print("Invalid selection. Please choose an option from 1 to 7.")
except Exception as e:
print(f"\n[ERROR]: {e}")
if __name__ == "__main__":
main()