Repository navigation
Expand file tree
/
Copy pathuser_interface.py
More file actions
411 lines (339 loc) · 14.3 KB
/
Copy pathuser_interface.py
File metadata and controls
411 lines (339 loc) · 14.3 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
import sys
import jwt_utils as utils
import os
import questionary as quest
from api_client import ApiClient
from questionary import Choice
from menu_type import MenuType
from session_manager import SessionManager
from errors import UnauthorizedError
from rich.table import Table
from rich.console import Console
class UserInterface:
def __init__(self, client: ApiClient):
self.sm = SessionManager()
self.client = client
def __get_products(self):
response = self.client.get("/api/products")
data = response.json()
table = Table(title="Products")
if len(data) > 0:
table.add_column("ID", style="cyan", justify="center")
table.add_column("Name", style="cyan", justify="center")
table.add_column("Description", style="cyan", justify="center")
table.add_column("Price", style="green", justify="center")
table.add_column("Status", style="green", justify="center")
for product in data:
table.add_row(
str(product["id"]),
str(product["name"]),
str(product["description"]),
str(product["price"]),
str(product["status"])
)
return table, data
def __get_orders(self):
print("Get orders...")
response = self.client.get("/api/orders")
data = response.json()
table = Table(title="Order Details")
print(len(data))
if len(data) > 0:
table.add_column("Order ID", style="cyan", justify="center", footer="Total Price")
table.add_column("Delivery Address", style="cyan", justify="center")
table.add_column("Status", style="green", justify="center")
table.add_column("Total Price", style="cyan", justify="center")
table.add_column("Order Date", style="blue", justify="center")
table.add_column("Items", style="cyan", justify="center")
for order in data:
items = order.get("items", [])
item_info = ""
for item in items:
item_info += f"Name: {item['productName']} Quantity: {item['quantity']}\n"
table.add_row(
str(order["orderId"]),
str(order["deliveryAddress"]),
str(order["status"]),
str(order["totalAmount"]),
str(order["orderDate"]),
item_info
)
return table, data
def __add_product(self):
table, p_data = self.__get_products()
if len(p_data) > 0:
console = Console()
console.print(table)
else:
print("There is no product yet.")
return MenuType.CART_PAGE
product_choice_list = []
for p in p_data:
product_choice = Choice(
title = f"{p['name'].capitalize()}",
value = p["id"]
)
product_choice_list.append(product_choice)
which_product = quest.select(
"Which product do you want to add to your cart?",
choices= product_choice_list
).ask()
how_many = quest.select(
"How many?",
choices= [
Choice(title="1 piece", value = 1),
Choice(title="2 pieces", value = 2),
Choice(title="3 pieces", value = 3),
Choice(title="4 pieces", value = 4),
Choice(title="5 pieces", value = 5),
Choice(title="Cancel", value = "cancel"),
]
).ask()
if how_many != "cancel":
item_info = {"productId": which_product, "quantity": how_many}
post_response = self.client.post("/api/cart/items", json=item_info)
if post_response.status_code == 200:
print("Product added successfully.")
elif post_response.status_code == 400:
print(post_response.json().get("message"))
return MenuType.CART_PAGE
else:
return MenuType.MAIN_MENU
def __remove_product(self, data):
item_choice_list = []
for i in data:
item_choice = Choice(
title = f"{i['productName'].capitalize()}",
value = i["productId"]
)
item_choice_list.append(item_choice)
item_id = quest.select(
"Which product do you want to remove from your cart?",
choices= item_choice_list
).ask()
del_response = self.client.delete(f"/api/cart/items/{item_id}")
if del_response.status_code == 200:
print("Product removed successfully.")
else:
print(del_response.json().get('message'))
return MenuType.CART_PAGE
def __clear_products(self):
is_confirmed = quest.confirm("Are you sure to clear your cart?").ask()
if is_confirmed:
del_response = self.client.delete("/api/cart")
if del_response.status_code == 200:
print("Cart cleared successfully.")
else:
print(del_response.json().get('message'))
else:
print("Cart not cleared.")
return MenuType.CART_PAGE
def __checkout(self):
address = quest.text("Enter your address: ").ask().strip()
if not address:
print("Address cannot be empty.")
quest.press_any_key_to_continue().ask()
return MenuType.MAIN_MENU
request_json = {
"deliveryAddress": address
}
post_response = self.client.post("/api/orders", json=request_json)
data = post_response.json()
if post_response.status_code == 201:
items = data["items"]
print()
print("Your order has been received and will be delivered as soon as possible.")
print()
table = Table(title="Order Details")
table.add_column("Order ID", style="cyan", justify="center", footer="Total Price")
table.add_column("Delivery Address", style="cyan", justify="center")
table.add_column("Status", style="green", justify="center")
table.add_column("Total Price", style="cyan", justify="center")
table.add_column("Order Date", style="blue", justify="center")
table.add_column("Items", style="cyan", justify="center")
item_info = ""
for item in items:
item_info += f"Name: {item['productName']} | Quantity: {item['quantity']}\n"
table.add_row(
str(data["orderId"]),
str(data["deliveryAddress"]),
str(data["status"]),
str(data["totalAmount"]),
str(data["orderDate"]),
item_info
)
console = Console()
console.print(table)
quest.press_any_key_to_continue().ask()
return MenuType.MAIN_MENU
else:
print(data.get('message'))
return MenuType.CART_PAGE
def _start_menu(self):
choice = quest.select(
"Please make a choice:",
choices=[
Choice(title="Register", value="reg"),
Choice(title="Login", value="log"),
Choice(title="Exit", value="ex")
]
).ask()
match choice:
case "reg":
return MenuType.REGISTER_PAGE
case "log":
return MenuType.LOGIN_PAGE
case "ex":
return MenuType.EXIT
return None
def _register_page(self):
inputs = quest.form(
firstName=quest.text("First name:"),
lastName=quest.text("Last name:"),
email=quest.text("Email: "),
password=quest.password("Password: ")
).ask()
response = self.client.post("api/auth/register", json=inputs)
if response.status_code == 201:
print("You have been registered successfully.")
return MenuType.LOGIN_PAGE
else:
return MenuType.START_MENU
def _login_page(self):
inputs = quest.form(
email=quest.text("Email: "),
password=quest.password("Password: ")
).ask()
response = self.client.post("api/auth/login", json=inputs)
if response.status_code == 200:
data = response.json()
self.sm.write_sessions(data)
return MenuType.MAIN_MENU
else:
return MenuType.START_MENU
def _main_menu(self):
choice = quest.select(
"Please make a choice:",
choices=[
Choice(title="Product Catalog", value="catalog"),
Choice(title="Your Cart", value="cart"),
Choice(title="Order History", value="order_history"),
Choice(title="Exit", value="ex")
]
).ask()
match choice:
case "catalog":
return MenuType.CATALOG_PAGE
case "cart":
return MenuType.CART_PAGE
case "order_history":
return MenuType.ORDERS_PAGE
case "ex":
return MenuType.EXIT
def _catalog_page(self):
table, data = self.__get_products()
if len(data) > 0:
console = Console()
console.print(table)
else:
print("There is no product yet.")
quest.press_any_key_to_continue("Press any key to main menu").ask()
return MenuType.MAIN_MENU
def _cart_page(self):
response = self.client.get("/api/cart")
data = response.json()
items = data["cartItems"]
total_price=data["cartTotalPrice"]
table = Table(title="Your Cart", show_footer=True)
if len(items) > 0:
table.add_column("ID", style="cyan", justify="center", footer="Total Price")
table.add_column("Name", style="cyan", justify="center")
table.add_column("Price", style="green", justify="center")
table.add_column("Quantity", style="cyan", justify="center")
table.add_column("Total Price", style="blue", justify="right", footer=f"{total_price:.2f} TL")
for item in items:
table.add_row(
str(item["productId"]),
str(item["productName"]),
str(item["unitPrice"]),
str(item["quantity"]),
str(item["quantity"] * item["unitPrice"])
)
console = Console()
console.print(table)
choice = quest.select(
"Please make a choice:",
choices=[
Choice(title="Add Product To Cart", value="add"),
Choice(title="Remove Product From Cart", value="remove"),
Choice(title="Clear Cart", value="clear"),
Choice(title="Checkout", value="checkout"),
Choice(title="Return To Main Menu", value="return")
]
).ask()
else:
print("Your cart is empty.")
choice = quest.select(
"Please make a choice:",
choices=[
Choice(title="Add Product To Cart", value="add"),
Choice(title="Return To Main Menu", value="return")
]
).ask()
match choice:
case "add":
return self.__add_product()
case "remove":
return self.__remove_product(data=items)
case "clear":
return self.__clear_products()
case "checkout":
return self.__checkout()
case "return":
return MenuType.MAIN_MENU
return None
def _orders_page(self):
table, data = self.__get_orders()
if len(data) > 0:
console = Console()
console.print(table)
else:
print("There is no order yet.")
quest.press_any_key_to_continue("Press any key to main menu").ask()
return MenuType.MAIN_MENU
def get_main_loop(self):
data = self.sm.read_sessions()
if "token" in data:
token = data["token"]
is_valid = utils.is_token_valid(token)
else:
is_valid = False
if is_valid:
next_page = MenuType.MAIN_MENU
else:
next_page = MenuType.START_MENU
while True:
os.system('cls' if os.name == 'nt' else 'clear')
try:
match next_page:
case MenuType.START_MENU:
next_page = self._start_menu()
case MenuType.REGISTER_PAGE:
next_page = self._register_page()
case MenuType.LOGIN_PAGE:
next_page = self._login_page()
case MenuType.MAIN_MENU:
next_page = self._main_menu()
case MenuType.CATALOG_PAGE:
next_page = self._catalog_page()
case MenuType.CART_PAGE:
next_page = self._cart_page()
case MenuType.ORDERS_PAGE:
next_page = self._orders_page()
case MenuType.EXIT:
sys.exit(1)
case _:
pass
except UnauthorizedError:
print("Your session was expired.")
next_page = MenuType.START_MENU