-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBank.py
More file actions
121 lines (109 loc) · 4.44 KB
/
Bank.py
File metadata and controls
121 lines (109 loc) · 4.44 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
# Bank.py
import json
import os
import random
import hashlib
class BankLogic:
def __init__(self, db_file="bank_users.json"):
self.db_file = db_file
self.users = {}
self.current_user = None
self.load_users()
# ---------------- File Handling ----------------
def load_users(self):
"""Load users from JSON file (persistent storage)."""
if os.path.exists(self.db_file):
try:
with open(self.db_file, "r") as f:
self.users = json.load(f)
except (json.JSONDecodeError, IOError):
# Backup corrupted file
try:
os.rename(self.db_file, self.db_file + ".corrupt")
except Exception:
pass
self.users = {}
else:
self.users = {}
def save_users(self):
"""Save users to JSON file (persistent storage)."""
try:
with open(self.db_file, "w") as f:
json.dump(self.users, f, indent=4)
except Exception as e:
return False, f"Failed to save users: {str(e)}"
return True, "Saved successfully"
# ---------------- Account Handling ----------------
def _generate_account_number(self):
"""Generate a unique 8-digit account number starting with 0010."""
while True:
acc_no = "0010" + str(random.randint(1000, 9999))
if acc_no not in self.users:
return acc_no
def _hash_pin(self, pin):
return hashlib.sha256(pin.encode()).hexdigest()
def create_account(self, name, age, pin):
"""Create a new account and return its number and user data."""
if not pin.isdigit() or len(pin) != 4:
return False, "PIN must be a 4-digit number.", None, None
try:
age = int(age)
except ValueError:
return False, "Age must be an integer.", None, None
if age < 18:
return False, "Age must be 18 or older.", None, None
account_no = self._generate_account_number()
hashed_pin = self._hash_pin(pin)
self.users[account_no] = {
"account_no": account_no,
"name": name,
"age": age,
"pin": hashed_pin,
"balance": 0.0,
"transactions": []
}
self.save_users()
return True, "Account created successfully.", account_no, self.users[account_no]
def login(self, account_no, pin):
"""Login with account number and PIN."""
hashed_input = self._hash_pin(pin)
user = self.users.get(account_no)
if user and user["pin"] == hashed_input:
self.current_user = account_no
return True, "Login successful.", user
else:
return False, "Invalid account number or PIN.", None
def logout(self):
"""Logout current user."""
self.current_user = None
# ---------------- Banking Operations ----------------
def deposit(self, amount):
"""Deposit amount, update balance, return result."""
if not self.current_user:
return False, "No user logged in.", None
if amount is None or amount <= 0:
return False, "Invalid deposit amount.", None
self.users[self.current_user]["balance"] += amount
entry = f"Deposited: {amount:.2f}"
self.users[self.current_user]["transactions"].append(entry)
self.save_users()
return True, entry, self.users[self.current_user]["balance"]
def withdraw(self, amount):
"""Withdraw amount, update balance, return result."""
if not self.current_user:
return False, "No user logged in.", None
if amount is None or amount <= 0:
return False, "Invalid withdrawal amount.", None
if self.users[self.current_user]["balance"] < amount:
return False, "Insufficient balance.", None
self.users[self.current_user]["balance"] -= amount
entry = f"Withdrawn: {amount:.2f}"
self.users[self.current_user]["transactions"].append(entry)
self.save_users()
return True, entry, self.users[self.current_user]["balance"]
def get_transaction_log(self):
"""Return transactions for the current user."""
if not self.current_user:
return False, "No user logged in.", []
transactions = self.users[self.current_user]["transactions"]
return True, "Log retrieved.", transactions