-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshop_management.py
More file actions
1538 lines (1356 loc) · 52.9 KB
/
Copy pathshop_management.py
File metadata and controls
1538 lines (1356 loc) · 52.9 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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ─── Modules To Import ────────────────────────────────────────────────────────
import mysql.connector as sql
from pwinput import pwinput
import bcrypt
import os
from InquirerPy import inquirer, get_style
import datetime
import time
import csv
from rich.progress import track
from rich.panel import Panel
from rich.text import Text
from rich.console import Console
from rich.theme import Theme
from rich.prompt import IntPrompt, FloatPrompt, Prompt
from rich.columns import Columns
from rich import box
from rich.table import Table
from rich.spinner import Spinner
from rich.live import Live
# ──────────────────────────────────────────────────────────────────────────────
style = get_style(
{
"questionmark": "bold red",
"question": "bold red",
"answered_question": "red",
"answer": "green",
"input": "yellow",
"options": "yellow",
"pointer": "blue",
"amark": "red",
},
style_override=False,
)
custom_theme = Theme(
{
"success": "bold #76B947",
"error": "bold #FF004D",
"border": "#DA0037",
"heading": "bold #EDEDED",
"menu": "purple",
"input": "yellow",
"background": "#171717",
"pass": "#DA0037 blink",
"table": "cyan",
},
inherit=False,
)
console = Console(theme=custom_theme)
# ─── Connecting To Mysql Database ──────────────────────────────────────────────────────────────────────────────────────────
try:
conobj = sql.connect(
host=os.environ.get("DB_HOST"),
user=os.environ.get("DB_USER"),
passwd=os.environ.get("DB_PASSWD"),
database=os.environ.get("DB_DATABASE"),
)
cursor = conobj.cursor()
except Exception as e:
console.print(f"Could not connect to MySQL database \n{e}", style="error")
spinner = Spinner(
"point", text=Text("Terminating the Program", style="error"), style="error"
)
with Live(spinner, refresh_per_second=20) as live:
for i in range(7):
time.sleep(0.2)
exit()
# ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
# ─── Declaring Global Variables ────────────────────────────────────────────────────────────────────────────────────────────
email = ""
cart = []
itemnos_in_cart = []
items_table = []
cart_table = []
items = []
items_no = []
# ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
def sign_in(user: str = "customer" or "employee") -> bool:
global email
while True:
email = console.input("[input]Enter your email : ")
q = f"SELECT {user}_name, passwd FROM {user}_table WHERE email = %s"
v = (email,)
cursor.execute(q, v)
rec = cursor.fetchall()
if len(rec) == 0:
console.print(f"{email} does not exist in our database", style="error")
ch = inquirer.confirm(
message="Do you want to register ?", style=style
).execute()
if ch:
if user == "customer":
customer_register()
console.print(
"\nYou can sign in with your credentials now\n", style="success"
)
elif user == "employee":
employee_register()
console.print(
"\nYou can sign in with your credentials now\n", style="success"
)
else:
hashed = (rec[0][1]).encode("utf-8")
c = 3
while c > 0:
console.print("Enter your password : ", end="", style="pass")
password = pwinput(prompt="").encode("utf-8")
if bcrypt.checkpw(password, hashed):
console.print(
f"\nWelcome {rec[0][0].title()} !!! \n", style="success"
)
spinner = Spinner(
"point",
text=Text(f"Continuing to {user} screen", style="green"),
style="green",
)
with Live(spinner, refresh_per_second=20) as live:
for i in range(5):
time.sleep(0.2)
return (email, True)
else:
c -= 1
console.print(
"Password Incorrect \nPlease Try again", style="error"
)
console.print(f"You have {c} more chances", style="error")
else:
console.print("Chances Over", style="error")
return (email, False)
def customer_register():
try:
console.clear()
console.print(
Panel.fit(
Text("CUSTOMER REGISTRATION", style="heading", justify="center"),
style="border",
),
justify="center",
)
print()
name = console.input("[input]Enter your name : ")
cursor.execute("SELECT email FROM customer_table")
emails = cursor.fetchall()
while True:
email = console.input("[input]Enter your email id : ")
flag = 0
for i in emails:
if i[0] == email:
flag = 1
if flag == 1:
console.print("Email already exists", style="error")
else:
break
while True:
console.print("Enter your password : ", end="", style="pass")
password = pwinput(prompt="").encode("utf-8")
console.print("Confirm your password : ", end="", style="pass")
con_password = pwinput(prompt="").encode("utf-8")
if password == con_password:
console.print("Passwords Match", style="success")
break
else:
console.print("Password are not matching \n", style="error")
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
q = "INSERT INTO customer_table (customer_name, email, passwd, items) VALUES (%s, %s, %s, '[]')"
v = (name, email, hashed)
cursor.execute(q, v)
conobj.commit()
console.print("Registered Successfully", style="success")
console.input("[yellow]Enter a key to continue")
except Exception as e:
console.print(
f"Failed to Register \nPlease try again later \n{e}", style="error"
)
console.input("[yellow]Enter a key to continue")
def employee_register():
try:
console.clear()
console.print(
Panel.fit(
Text("EMPLOYEE REGISTRATION", style="heading", justify="center"),
style="border",
),
justify="center",
)
print()
name = console.input("[input]Enter your name : ")
cursor.execute("SELECT email FROM employee_table")
emails = cursor.fetchall()
while True:
email = console.input("[input]Enter your email id : ")
flag = 0
for i in emails:
if i[0] == email:
flag = 1
if flag == 1:
console.print("Email already exists", style="error")
else:
break
while True:
console.print("Enter your password : ", end="", style="pass")
password = pwinput(prompt="").encode("utf-8")
console.print("Confirm your password : ", end="", style="pass")
con_password = pwinput(prompt="").encode("utf-8")
if password == con_password:
console.print("Passwords Match", style="success")
break
else:
console.print("Password are not matching \n", style="error")
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
des = console.input("[input]Enter your designation : ")
sal = FloatPrompt.ask("[yellow]Enter your salary")
q = "INSERT INTO employee_table (employee_name, email, designation, salary, passwd) VALUES (%s, %s, %s, %s, %s)"
v = (name, email, des, sal, hashed)
cursor.execute(q, v)
conobj.commit()
console.print("Registered Successfully", style="success")
console.input("[yellow]Enter a key to continue")
except Exception as e:
console.print(
f"Failed to Register \nPlease try again later \n{e}", style="error"
)
console.input("[yellow]Enter a key to continue")
def cart_table_create(cart):
global cart_table
cart_table = Table(header_style="bold red", box=box.SIMPLE_HEAD, title="Your Cart")
cart_table.add_column("Item No", justify="center")
cart_table.add_column("Item Name", justify="left")
cart_table.add_column("Category", justify="left")
cart_table.add_column("Price", justify="right")
cart_table.add_column("Quantity", justify="right")
for item in cart:
cart_table.add_row(str(item[0]), item[1], item[2], str(item[3]), str(item[4]))
return cart_table
def full_table_create(items):
full_table = Table(
header_style="bold red", box=box.SIMPLE_HEAD, title="Items Table"
)
full_table.add_column("Item No", justify="center")
full_table.add_column("Item Name", justify="left")
full_table.add_column("Category", justify="left")
full_table.add_column("Price", justify="right")
full_table.add_column("Stock", justify="right")
for i in range(len(items)):
full_table.add_row(
str(items[i][0]),
items[i][1],
items[i][2],
str(items[i][3]),
str(items[i][4]),
)
return full_table
def items_table_create(items):
items_table = Table(
header_style="bold red", box=box.SIMPLE_HEAD, title="Items Table"
)
items_table.add_column("Item No", justify="center")
items_table.add_column("Item Name", justify="left")
items_table.add_column("Category", justify="left")
items_table.add_column("Price", justify="right")
for i in range(len(items)):
items_table.add_row(
str(items[i][0]), items[i][1], items[i][2], str(items[i][3])
)
items[i] = list(items[i])
return items_table
def bill_table_create(cart):
table = Table(header_style="bold red", box=box.SIMPLE_HEAD)
table.add_column("S No", justify="center")
table.add_column("Item Name", justify="left")
table.add_column("Quantity", justify="center")
table.add_column("Price", justify="right")
table.add_column("Total", justify="right")
for i in range(len(cart)):
table.add_row(
str(i + 1),
cart[i][1],
str(cart[i][4]),
str(cart[i][3]),
str(cart[i][3] * cart[i][4]),
)
return table
def bill(cart, dt, sub_total, tax, total_cost):
try:
console.clear()
console.print(f"{'Your Bill': ^60}", style="BOLD RED")
q = "SELECT customer_name FROM customer_table WHERE email = '{}'".format(email)
cursor.execute(q)
name = cursor.fetchall()[0][0]
console.print(f"Customer Name : [blue]{name}", style="success")
console.print(f"Email Address : [blue]{email}", style="success")
console.print(
f"Date and Time of Purchase : [blue]{dt.day}/{dt.month}/{dt.year} - {dt.hour}:{dt.minute}",
style="success",
)
console.print(bill_table_create(cart))
console.print(f"SubTotal : [blue]{sub_total} Rs", style="success")
console.print("Shipping : [blue]100 Rs", style="success")
console.print(f"Taxes : [blue]{tax} Rs", style="success")
console.print(f"Total : [blue] {total_cost} \n", style="success")
ch = inquirer.confirm(
message="Do you want to save the bill as a csv file ?", style=style
).execute()
if ch:
bill_csv(name, email, dt, cart, sub_total, tax, total_cost)
console.print(
"Thank you for shopping at our online supermarket!", style="success"
)
except Exception as e:
console.print(
f"Your Bill could not be generated \nPlease try again later \n{e}",
style="error",
)
def bill_csv(name, email, dt, cart, sub_total, tax, total_cost):
try:
file_name = console.input("[yellow]Enter File name : ") + ".csv"
file_object = open(file_name, "w", newline="")
wobj = csv.writer(file_object)
wobj.writerows(
[
["", "", "BILL"],
["Name", name],
["Email", email],
["Date", f"{dt.day}/{dt.month}/{dt.year} - {dt.hour}:{dt.minute}"],
[
"",
],
["S No", "Item Name", "Quantity", "Price", "Total"],
]
)
for i in range(len(cart)):
wobj.writerow(
[i + 1, cart[i][1], cart[i][4], cart[i][3], cart[i][3] * cart[i][4]]
)
wobj.writerows(
[
[
"",
],
["", "", "", "Sub Total", sub_total],
["", "", "", "Shipping", 100],
["", "", "", "Taxes", tax],
["", "", "", "Total", total_cost],
]
)
console.print(
f"CSV FILE {file_name} has been generated \nPlease check in the program folder \n",
style="success",
)
file_object.close()
ch = inquirer.confirm(
message="Do you want to open the csv file on your system now ?", style=style
).execute()
if ch:
try:
os.startfile(file_name)
console.print("File opened", style="success")
except Exception as e:
console.print(
f"Could not open the file \nPlease make sure a default app is set for opening csv files on your system \n{e}",
style="error",
)
except Exception as e:
console.print(
f"CSV File was not generated \nPlease Try again \n{e}", style="error"
)
console.input("[yellow]Enter a key to continue ")
def search_buy():
global items, itemnos_in_cart
q = "SELECT item_no, item_name, category, price, stock FROM items_table WHERE stock > 0"
cursor.execute(q)
items = cursor.fetchall()
item_names = []
for item in items:
item_names.append(item[1])
try:
while True:
console.clear()
console.print(
Panel.fit(
Text("SEARCH AND BUY", style="heading", justify="center"),
style="border",
),
justify="center",
)
search = inquirer.fuzzy(
message="Search for products",
choices=item_names,
style=style,
border=True,
).execute()
while True:
flag = False
qty = IntPrompt.ask("[yellow]Enter quantity")
if qty == 0:
console.print(
"Quantity cannot be zero \nPlease Enter a non-zero number",
style="error",
)
else:
for item in items:
if item[1] == search:
if item[4] < qty:
console.print(
f"Limited Stock left \nPlease enter a value less than {item[4] + 1}",
style="error",
)
flag = True
break
if not flag:
break
for item in items:
if item[1] == search:
console.print(
f"\n[success][i]ITEM DETAILS : [/i][/success]\n Item no : {item[0]} \n Item name : {item[1]} \n Category : {item[2]} \n Price : {item[3]}",
style="blue",
)
brought = list(item)[0:-1]
brought.append(qty)
break
itemnos_in_cart.append(str(brought[0]))
cart.append(brought)
item_names.remove(search)
console.print("\nItem added to your cart", style="success")
ch = inquirer.confirm(message="Continue Shopping ? ", style=style).execute()
if not ch:
console.print(
"All items successfully added to your cart", style="success"
)
spinner = Spinner(
"point",
text=Text(f"Continuing to confirm purchase", style="green"),
style="green",
)
with Live(spinner, refresh_per_second=20) as live:
for i in range(7):
time.sleep(0.2)
break
except Exception as e:
console.print(f"Could not perform the action \n{e}", style="error")
console.input("[yellow]Enter a key to continue ")
def confirm_purchase():
global items, cart, itemnos_in_cart
console.clear()
console.print(
Panel.fit(
Text("CONFIRMATION MENU", style="heading", justify="center"), style="border"
),
justify="center",
)
console.print(cart_table_create(cart))
sub_total = 0
for i in cart:
sub_total += i[3] * i[4]
tax = sub_total / 10
total_cost = sub_total + tax + 100
console.print(f"Total Bill = [blue]{sub_total}", style="success")
ch = inquirer.confirm(message="Confirm your purchase ", style=style).execute()
if ch:
try:
q = "SELECT * FROM customer_table WHERE email = %s"
v = (email,)
cursor.execute(q, v)
userinfo = cursor.fetchall()
db_purchase = userinfo[0][4]
db_purchase += total_cost
db_points = userinfo[0][5]
db_points += (total_cost / 100) * 5
current_order = []
dt = datetime.datetime.now()
current_order.append(
f"{dt.day}/{dt.month}/{dt.year} - {dt.hour}:{dt.minute}"
)
for i in itemnos_in_cart:
current_order.append(int(i))
items = eval(userinfo[0][3])
items.append(current_order)
for item in cart:
q = "UPDATE items_table SET stock = stock - %s where item_no = %s"
v = (item[4], item[0])
cursor.execute(q, v)
conobj.commit()
q = "UPDATE customer_table SET total_purchase = %s, points = %s, items = %s WHERE email = %s"
v = (db_purchase, db_points, str(items), email)
cursor.execute(q, v)
conobj.commit()
console.print("Purchase Confirmed \n", style="success")
console.print("Generating your bill")
bill(cart, dt, sub_total, tax, total_cost)
console.input("[success]Enter a key to continue")
except Exception as e:
console.print(
f"Failed to Confirm your Purchase \nPlease try again later \n{e}",
style="error",
)
console.input("[success]Enter a key to continue")
else:
console.print("Purchase cancelled", style="error")
console.input("[success]Enter a key to continue")
cart = []
itemnos_in_cart = []
def edit_quantity(items, cart):
console.clear()
console.print(
Panel.fit(
Text("EDIT QUANTITY", style="heading", justify="center"), style="border"
),
justify="center",
)
try:
console.print(cart_table_create(cart))
item_no = IntPrompt.ask(
"[yellow]Enter the item no to edit",
choices=itemnos_in_cart,
show_choices=False,
)
for i in range(len(items)):
if items[i][0] == item_no:
stock = items[i][4]
while True:
qty = IntPrompt.ask("[yellow]Enter new quantity")
if qty < stock:
for i in range(len(cart)):
if cart[i][0] == item_no:
cart[i][4] = qty
console.print("Quantity changed successfully", style="success")
console.print(cart_table_create(cart))
console.input("[yellow]Enter a key to continue")
break
else:
console.print("Limited Stock Left", style="error")
console.print(
f"Please Enter a value less than {stock + 1}", style="error"
)
console.input("[yellow]Enter a key to continue")
except Exception as e:
console.print(f"\nQuantity was not changed \n{e}", style="error")
console.input("[yellow]Enter a key to continue")
def remove_cart(cart, itemnos_in_cart):
try:
console.print(cart_table_create(cart))
item_no = IntPrompt.ask(
"[yellow]Enter item no to remove",
choices=itemnos_in_cart,
show_choices=False,
)
ch = inquirer.confirm(
message=f"Confirm to remove item no {item_no}", style=style
).execute()
if ch:
for item in cart:
if item[0] == item_no:
cart.remove(item)
itemnos_in_cart.remove(str(item_no))
print()
console.print(cart_table_create(cart))
console.print("Item removed from your cart", style="success")
console.input("[yellow]Enter a key to continue")
except Exception as e:
console.print(f"\nItem was not removed from your cart \n{e}", style="error")
console.input("[yellow]Enter a key to continue")
def buy():
try:
global cart, itemnos_in_cart
search_buy()
while True:
console.clear()
console.print(
Panel.fit(
Text("SHOPPING MENU", style="heading", justify="center"),
style="border",
),
justify="center",
)
ch = inquirer.select(
message="Select your choice",
style=style,
choices=["Confirm Purchase", "Edit your cart", "Cancel Purchase"],
).execute()
if ch == "Confirm Purchase":
confirm_purchase()
break
elif ch == "Edit your cart":
while True:
console.clear()
console.print(
Panel.fit(
Text("EDIT CART", style="heading", justify="center"),
style="border",
),
justify="center",
)
ch = inquirer.select(
message="Select your choice",
style=style,
choices=[
"Change Quantity",
"Remove an Item",
"Return to Shopping Menu",
],
).execute()
if ch == "Change Quantity":
edit_quantity(items, cart)
elif ch == "Remove an Item":
remove_cart(cart, itemnos_in_cart)
elif ch == "Return to Shopping Menu":
break
elif ch == "Cancel Purchase":
console.print("Purchase Cancelled", style="error")
cart = []
itemnos_in_cart = []
break
except Exception as e:
console.print(
f"Could not access buy menu \nPlease try again later \n{e}", style="error"
)
console.input("[yellow]Enter a key to continue ")
def item_insert():
console.clear()
console.print(
Panel.fit(
Text("INSERT ITEM", style="heading", justify="center"), style="border"
),
justify="center",
)
item_name = console.input("[input]Enter item name : ").title()
category = console.input("[input]Enter category : ").title()
price = FloatPrompt.ask("[yellow]Enter your price")
stock = IntPrompt.ask("[yellow]Enter stock")
try:
q = "INSERT INTO items_table (item_name, category, price, stock) VALUES (%s, %s, %s, %s)"
v = (item_name, category, price, stock)
cursor.execute(q, v)
conobj.commit()
console.print("Item inserted", style="success")
console.input("[success]Enter a key to continue")
except Exception as e:
console.print(
f"\nCould not insert item \nPlease try again later\n{e}", style="error"
)
console.input("[yellow]Enter a key to continue ")
def remove_item():
try:
cursor.execute("SELECT * FROM items_table")
items = cursor.fetchall()
console.print(full_table_create(items))
item_nos = []
for i in items:
item_nos.append(str(i[0]))
item_no = IntPrompt.ask(
"Enter item no to remove", choices=item_nos, show_choices=False
)
q = "DELETE FROM items_table WHERE item_no = %s"
v = (item_no,)
cursor.execute(q, v)
conobj.commit()
console.print("Item Removed", style="success")
console.input("[yellow]Enter a key to continue ")
except Exception as e:
console.print(
"Could not remove the item \nPlease try again later \n", e, style="error"
)
console.input("[yellow]Enter a key to continue ")
def view_items():
try:
while True:
console.clear()
console.print(
Panel.fit(
Text("VIEW MENU", style="heading", justify="center"), style="border"
),
justify="center",
)
ch = inquirer.select(
message="Select your choice",
style=style,
choices=[
"Sort by Price",
"Group by Category",
"View items out of stock",
"Return to Customer Menu",
],
).execute()
if ch == "Sort by Price":
q = "SELECT item_no, item_name, category, price FROM items_table ORDER BY price"
cursor.execute(q)
items = cursor.fetchall()
console.print(items_table_create(items))
console.input("[success]Press any key to continue ")
elif ch == "Group by Category":
q = "SELECT distinct category FROM items_table"
cursor.execute(q)
cats = []
for i in cursor.fetchall():
cats.append(i[0])
ch = inquirer.select(
message="Select your category",
multiselect=True,
style=style,
choices=cats,
).execute()
selected = str(ch)
selected = selected[1:-1]
selected = "(" + selected + ")"
q = "SELECT item_name, category, price FROM items_table WHERE category IN {}".format(
selected
)
cursor.execute(q)
rec = cursor.fetchall()
def get_content(x):
name = rec[x][0].title()
category = rec[x][1].title()
price = rec[x][2]
return f"[bold red]{name}[/bold red] - [yellow]₹{price}\n{category}"
item_renderables = [
Panel(get_content(x), expand=True) for x in range(len(rec))
]
console.print(Columns(item_renderables))
console.input("[success]Press any key to continue ")
elif ch == "View items out of stock":
q = "SELECT item_no, item_name, category, price FROM items_table WHERE stock = 0"
cursor.execute(q)
items = cursor.fetchall()
console.print(items_table_create(items))
console.input("[success]Press any key to continue ")
elif ch == "Return to Customer Menu":
break
except Exception as e:
console.print(
f"Could not view items \nPlease try again later \n{e}", style="error"
)
console.input("[success]Press any key to continue ")
def edit_items():
console.clear()
console.print(
Panel.fit(Text("EDIT ITEM", style="heading", justify="center"), style="border"),
justify="center",
)
q = "SELECT * FROM items_table"
cursor.execute(q)
items = cursor.fetchall()
console.print(full_table_create(items))
item_nos = []
for i in items:
item_nos.append(str(i[0]))
item_no = IntPrompt.ask(
"[yellow]Enter item no you want to edit", choices=item_nos, show_choices=False
)
try:
item_name = console.input("[input]Enter new item name : ").title()
category = console.input("[input]Enter new category : ").title()
price = FloatPrompt.ask("[yellow]Enter new price")
stock = IntPrompt.ask("[yellow]Enter new stock")
q = "UPDATE items_table SET item_name = %s, category = %s, price = %s, stock = %s WHERE item_no = %s"
v = (item_name, category, price, stock, item_no)
cursor.execute(q, v)
conobj.commit()
console.print("Item info edited !!!", style="success")
console.input("[success]Enter a key to continue")
except Exception as e:
console.print(
f"Failed to edit item info \nPlease Try again later \n{e}", style="error"
)
console.input("[success]Enter a key to continue")
def search():
try:
q = "SELECT item_name FROM items_table"
cursor.execute(q)
items_names = []
for i in cursor.fetchall():
items_names.append(i[0])
while True:
console.clear()
console.print(
Panel.fit(
Text("SEARCH", style="heading", justify="center"), style="border"
),
justify="center",
)
search = inquirer.fuzzy(
message="Enter search query : ", style=style, choices=items_names
).execute()
cursor.execute(
"SELECT * FROM items_table WHERE item_name = '{}'".format(search)
)
search_result = cursor.fetchall()
item = search_result[0]
console.print(
f"\n[success][i]ITEM DETAILS : [/i][/success]\n Item no : {item[0]} \n Item name : {item[1]} \n Category : {item[2]} \n Price : {item[3]} \n",
style="blue",
)
ch = inquirer.confirm(
message="Continue Searching ? ", style=style
).execute()
if not ch:
break
except Exception as e:
console.print(
"Could not search at the moment \nPlease try again later \n",
e,
style="error",
)
console.input("[success]Enter a key to continue")
def edit_customer(rec):
global email
console.clear()
console.print(
Panel.fit(
Text("EDIT CUSTOMER ACCOUNT", style="heading", justify="center"),
style="border",
),
justify="center",
)
try:
f = 0
cid = rec[0]
while True:
name = console.input("[yellow]Enter your new name : ")
while True:
if f == 1:
break
email = console.input("[yellow]Enter your new email : ")
q = "SELECT email FROM customer_table"
cursor.execute(q)
for i in cursor.fetchall():
if i[0] == email:
console.print(
"An account with this email already exists \nPlease provide a new email",
style="error",
)
spinner = Spinner(
"point",
text=Text(
f"Going back to customer account page", style="red"
),
style="red",
)
with Live(spinner, refresh_per_second=20) as live:
for i in range(7):
time.sleep(0.2)
f = 1
break
else:
break
if f == 1:
break
q = "UPDATE customer_table SET customer_name = %s, email = %s WHERE customer_id = %s"
v = (name, email, cid)
cursor.execute(q, v)
conobj.commit()
console.print("User Details Updated !!", style="success")
spinner = Spinner(
"point",
text=Text(f"Going back to customer account page", style="green"),
style="green",
)
with Live(spinner, refresh_per_second=20) as live:
for i in range(7):
time.sleep(0.2)
break
except Exception as e:
console.print(
"Could not update customer details \nPlease try again later \n",
e,
style="error",
)