-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathATM.py
More file actions
242 lines (198 loc) · 7.09 KB
/
Copy pathATM.py
File metadata and controls
242 lines (198 loc) · 7.09 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
import json
import os
import time
from datetime import datetime
from getpass import getpass
DATA_FILE = "accounts.json"
HISTORY_FILE = "history.json"
RATES = {
"GEL": (1.0, "₾"),
"USD": (2.68, "$"),
"EUR": (3.08, "€"),
}
COMMISSION = 0.015
LOCKOUT_SECONDS = 60
C = {
"r": "\033[91m", "g": "\033[92m", "y": "\033[93m",
"b": "\033[94m", "m": "\033[95m", "c": "\033[96m",
"w": "\033[97m", "x": "\033[0m", "bold": "\033[1m",
}
DEFAULT_ACCOUNTS = {
"card": {"pin": "1111", "balance": 10000.0, "locked_until": 0},
"demo": {"pin": "0000", "balance": 500.0, "locked_until": 0},
}
def load_json(path, default):
if not os.path.exists(path):
return default
try:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
except (json.JSONDecodeError, OSError):
return default
def save_json(path, data):
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
def banner():
print(f"{C['c']}{C['bold']}")
print(" ┌─────────────────────────────────────┐")
print(" │ PINNACLE BANK ATM v2 │")
print(" │ insert card to begin │")
print(" └─────────────────────────────────────┘")
print(C["x"])
def log(card, kind, detail):
history = load_json(HISTORY_FILE, [])
history.append({
"time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"card": card,
"type": kind,
"detail": detail,
})
save_json(HISTORY_FILE, history)
def authenticate(accounts):
for attempt in range(3):
card = input(f"\n{C['b']}card name: {C['x']}").strip().lower()
if card not in accounts:
print(f"{C['r']}unknown card{C['x']}")
continue
acc = accounts[card]
if acc.get("locked_until", 0) > time.time():
wait = int(acc["locked_until"] - time.time())
print(f"{C['r']}card locked. try again in {wait}s{C['x']}")
return None, None
for pin_try in range(3):
pin = getpass(f"{C['b']}pin: {C['x']}")
if pin == acc["pin"]:
print(f"{C['g']}welcome back{C['x']}")
return card, acc
print(f"{C['r']}wrong pin ({2 - pin_try} left){C['x']}")
acc["locked_until"] = time.time() + LOCKOUT_SECONDS
save_json(DATA_FILE, accounts)
print(f"{C['r']}too many wrong pins. card locked for {LOCKOUT_SECONDS}s{C['x']}")
return None, None
print(f"{C['r']}three bad cards. goodbye{C['x']}")
return None, None
def show_balance(acc):
bal = acc["balance"]
print(f"\n{C['y']}balance:{C['x']}")
for code, (rate, sym) in RATES.items():
print(f" {sym} {bal/rate:>10,.2f} ({code})")
def withdraw(acc, card):
print(f"\n{C['c']}1) GEL 2) USD 3) EUR 0) back{C['x']}")
pick = input("currency: ").strip()
codes = {"1": "GEL", "2": "USD", "3": "EUR"}
if pick not in codes:
return
code = codes[pick]
rate, sym = RATES[code]
raw = input(f"amount in {code}: ").strip()
try:
amt = float(raw)
except ValueError:
print(f"{C['r']}not a number{C['x']}")
return
if amt <= 0 or amt % 5 != 0:
print(f"{C['r']}amount must be a positive multiple of 5{C['x']}")
return
cost_gel = amt * rate
fee = cost_gel * COMMISSION
total = cost_gel + fee
if total > acc["balance"]:
print(f"{C['r']}insufficient funds (need {total:.2f}₾){C['x']}")
return
acc["balance"] -= total
log(card, "withdraw", f"{amt}{sym} (fee {fee:.2f}₾)")
print(f"{C['g']}dispensed {amt}{sym}. fee {fee:.2f}₾. new balance {acc['balance']:.2f}₾{C['x']}")
def deposit(acc, card):
raw = input("deposit amount in GEL: ").strip()
try:
amt = float(raw)
except ValueError:
print(f"{C['r']}not a number{C['x']}")
return
if amt <= 0:
print(f"{C['r']}must be positive{C['x']}")
return
acc["balance"] += amt
log(card, "deposit", f"+{amt:.2f}₾")
print(f"{C['g']}deposited {amt:.2f}₾. new balance {acc['balance']:.2f}₾{C['x']}")
def transfer(accounts, acc, card):
target = input("send to which card: ").strip().lower()
if target == card:
print(f"{C['r']}cant send to yourself{C['x']}")
return
if target not in accounts:
print(f"{C['r']}no such card{C['x']}")
return
raw = input("amount in GEL: ").strip()
try:
amt = float(raw)
except ValueError:
print(f"{C['r']}not a number{C['x']}")
return
if amt <= 0 or amt > acc["balance"]:
print(f"{C['r']}invalid amount{C['x']}")
return
acc["balance"] -= amt
accounts[target]["balance"] += amt
log(card, "transfer-out", f"-{amt:.2f}₾ to {target}")
log(target, "transfer-in", f"+{amt:.2f}₾ from {card}")
print(f"{C['g']}sent {amt:.2f}₾ to {target}{C['x']}")
def change_pin(acc, card):
old = getpass("current pin: ")
if old != acc["pin"]:
print(f"{C['r']}wrong pin{C['x']}")
return
new = getpass("new pin (4+ digits): ")
if not (new.isdigit() and len(new) >= 4):
print(f"{C['r']}pin must be 4+ digits{C['x']}")
return
if getpass("confirm: ") != new:
print(f"{C['r']}pins dont match{C['x']}")
return
acc["pin"] = new
log(card, "pin-change", "ok")
print(f"{C['g']}pin updated{C['x']}")
def show_history(card):
history = [h for h in load_json(HISTORY_FILE, []) if h["card"] == card]
if not history:
print(f"{C['y']}no history yet{C['x']}")
return
print(f"\n{C['c']}--- last 10 transactions ---{C['x']}")
for row in history[-10:]:
print(f" {row['time']} {row['type']:<13} {row['detail']}")
def session(accounts, card, acc):
while True:
show_balance(acc)
print(f"\n{C['m']}menu:{C['x']}")
print(" 1) withdraw")
print(" 2) deposit")
print(" 3) transfer")
print(" 4) history")
print(" 5) change pin")
print(" 0) eject card")
pick = input("> ").strip()
if pick == "1": withdraw(acc, card)
elif pick == "2": deposit(acc, card)
elif pick == "3": transfer(accounts, acc, card)
elif pick == "4": show_history(card)
elif pick == "5": change_pin(acc, card)
elif pick == "0":
print(f"{C['c']}take your card. goodbye 👋{C['x']}")
break
else:
print(f"{C['r']}pick a number from the menu{C['x']}")
save_json(DATA_FILE, accounts)
def main():
if os.name == "nt":
os.system("") # enable ANSI on windows
accounts = load_json(DATA_FILE, DEFAULT_ACCOUNTS)
save_json(DATA_FILE, accounts)
banner()
try:
card, acc = authenticate(accounts)
if card:
session(accounts, card, acc)
except KeyboardInterrupt:
print(f"\n{C['y']}session aborted. take your card{C['x']}")
if __name__ == "__main__":
main()