· 4 years ago · Feb 21, 2021, 08:22 PM
1from MainClient import other_commands
2from MainClient import s
3from PrintFunction import *
4import re, json, string, datetime
5import matplotlib.pyplot as plt
6import numpy as np
7
8
9def Orders(request, StaffID, LoggedIn):
10 ####Orders####
11 # Parameters :- request:dictionary, StaffID:Integer, LoggedIn:Integer #
12 # Return Type :- request:dictionary #
13 # Purpose:- This table handles all of the requests, data input and SQL operations #
14 # for the 'Orders' table. The user navigates a Command Line Interface till they get #
15 # to the option they like and then enter the required data, their request is passed #
16 # over to the server and then the server carries out its operations and return the #
17 # result which is printed on the client program using the print_function function. #
18 ##############
19 print("ORDERS MENU:")
20 request["table"] = "Orders"
21 choice2 = ""
22 print('''Do you want to:
231. View Orders
242. Add New Order
253. Change Existing Order
264. Delete an Order
275. Return to Main Menu''')
28 choice = input("> ")
29 choice = validate_an_input(Identifier="A", Range=["1", "5"],
30 Statement="Do you want to:\n1. View Orders\n2. Add New Order\n3. Change Existing Order\n4. Delete an Order\n5. Return to Main Menu",
31 Input=choice)
32
33 if choice == "1":
34 request["command"] = "SELECT"
35 print('''What orders do you want to view:
36A. Non-completed orders
37B. Orders from the past week
38C. Orders from the past month
39D. Orders from a specific date
40E. Orders by Customer Name
41F. All orders''')
42 choice2 = input("> ").upper()
43 choice2 = validate_an_input(Identifier="A", Range=["A", "F"],
44 Statement='''What orders do you want to view:\nA. All non-completed orders\nB. All orders from the past week\nC. All orders from the past month\nD. All orders from a specific date\nE. Orders by Customer Name\nF. All orders''',
45 Input=choice2)
46
47 if choice2 == "D":
48 print("- - " * 40)
49 print("What date do you want:\nEnter in the form xxxx-xx-xx, year-month-day")
50 request["date"] = input("> ")
51 request["date"] = validate_an_input(Identifier="B",
52 Statement="What date do you want:\nEnter in the form xxxx-xx-xx, year-month-day",
53 Input=request["date"])
54
55 elif choice2 == "E":
56 print("- - " * 40)
57 print("Enter the Customer's Name")
58 request["CustomerName"] = input("> ")
59 request["CustomerName"] = validate_an_input(Identifier="C", Statement="Enter the Customer's Name",
60 Input=request["CustomerName"])
61
62 elif choice == "2":
63 product_names = other_commands(request, "A")
64 sub_cats = other_commands(request, "D")
65 sub_cat_keys = list(sub_cats.keys())
66 sub_cat_values = list(sub_cats.values())
67 request["command"] = "INSERT"
68 request["ADDORDER"] = {}
69 l_p_c = print_function(product_names, "B")
70 text = ["Commands:", str(len(product_names)) + ") View order", str(len(product_names) + 1) + ") Edit",
71 str(len(product_names) + 2) + ") Finish"]
72 for num in range(0, len(text)):
73 print("-" * sum(i + 5 for i in l_p_c.values()))
74 print(text[num])
75 print("- - " * 40)
76 while True:
77 print(
78 "Type the number of the product you want to add to the order, \nor the number that corresponds to the action you want to perform:")
79 choice2 = input("> ")
80 choice2 = validate_an_input(Identifier="A", Range=["1", str(len(product_names) + 2)],
81 Statement="Type the number of the product you want to add to the order, \nor the number that corresponds to the action you want to perform:",
82 Input=choice2)
83 if choice2 == str(len(product_names)):
84 index2 = 1
85 print(" Product Name \t\t\t\t\t Quantity")
86 for key, value in request["ADDORDER"].items():
87 print(str(index2) + ") {0:<35} {1:<20} ".format(key, value))
88 index2 += 1
89 elif choice2 == str(len(product_names) + 1):
90 print("- - " * 15)
91 print("Order so far:")
92 index2 = 1
93 print(" Product Name \t\t\t\t\t Quantity")
94 for key, value in request["ADDORDER"].items():
95 print(str(index2) + ") {0:<35} {1:<20} ".format(key, value))
96 index2 += 1
97 print("- - " * 15)
98 print("Do you want to:\nA. Edit a quantity\nB. Remove an item:")
99 choice3 = input("> ").upper()
100 choice3 = validate_an_input(Input=choice3, Range=["A", "B"],
101 Statement="Do you want to:\nA. Edit a quantity\nB. Remove an item:",
102 Identifier="A")
103 if choice3 == "A":
104 print("Type the number of the product you want to edit:")
105 choice4 = input("> ")
106 choice4 = validate_an_input(Identifier="A", Range=["1", str(len(product_names))],
107 Statement="Type the number of the product you want to add to the order, \nor the number that corresponds to the action you want to perform:",
108 Input=choice4)
109 print("Type the new quantity for this product:")
110 quantity = input("> ")
111 name = product_names[int(choice4)][0]
112 request["ADDORDER"][name] = quantity
113 elif choice3 == "B":
114 print("Type the number of the product you want to remove:")
115 choice4 = input("> ")
116 choice4 = validate_an_input(Identifier="A", Range=["1", str(len(product_names))],
117 Statement="Type the number of the product you want to add to the order, \nor the number that corresponds to the action you want to perform:",
118 Input=choice4)
119 keys = list(request["ADDORDER"].keys())
120 try:
121 del request["ADDORDER"][keys[int(choice4) - 1]]
122 except IndexError as e:
123 print("Error - " + str(e))
124 print("Please enter a valid option")
125
126 elif choice2 == str(len(product_names) + 2):
127 break
128
129 else:
130 if choice2 not in [str(len(product_names)), str(len(product_names) + 1),
131 str(len(product_names) + 2)] and product_names[int(choice2)][0] in list(
132 request["ADDORDER"].keys()):
133 print(
134 "Product already in order. To edit quantity or remove item, type the number corresponding to 'Edit'")
135 else:
136 print("What quantity of this product do you want to add to the order:")
137 quantity = input("> ")
138 while (quantity.isnumeric() != True or (int(quantity) < 0)) or int(quantity) > \
139 product_names[int(choice2)][1]:
140 print("There is not enough stock to add this amount.")
141 print("What quantity of this product do you want to add to the order:")
142 quantity = input("> ")
143 name = product_names[int(choice2)][0]
144 request["ADDORDER"][name] = quantity
145 print("- - " * 40)
146
147 if request["ADDORDER"] != {}:
148 print("Is the Order:\n"
149 "A. Collection\n"
150 "B. Delivery")
151 request["CollectionOrDelivery"] = input("> ").upper()
152 request["CollectionOrDelivery"] = validate_an_input(Input=request["CollectionOrDelivery"],
153 Statement="Is the Order:\nA. Collection\nB. Delivery",
154 Range=["A", "B"], Identifier="A")
155
156 print("Enter the Date of Collection/Delivery in the Form xxxx-xx-xx, year-month-date:")
157 request["DateOfCollectionDelivery"] = input("> ")
158 request["DateOfCollectionDelivery"] = validate_an_input(Identifier="B",
159 Statement="Enter the Date of Collection/Delivery in the Form xxxx-xx-xx, year-month-date:",
160 Input=request["DateOfCollectionDelivery"])
161
162 print("Has the Order Been Collected/Delivered Already:\nA. Yes\nB. No")
163 request["Completed"] = input("> ").upper()
164 request["Completed"] = validate_an_input(Input=request["Completed"],
165 Statement="Has the Order Been Collected/Delivered Already:\nA. Yes\nB. No",
166 Range=["A", "B"], Identifier="A")
167
168 if request["CollectionOrDelivery"] == "A":
169 request["CollectionOrDelivery"] = "Collection"
170 elif request["CollectionOrDelivery"] == "B":
171 request["CollectionOrDelivery"] = "Delivery"
172
173 if request["Completed"] == "A":
174 request["Completed"] = "Yes"
175 elif request["Completed"] == "B":
176 request["Completed"] = "No"
177
178 request["StaffID"] = StaffID
179
180 print("Is it an Existing Customer: \nA. Yes \nB. No")
181 existing_cust = input("> ").upper()
182 existing_cust = validate_an_input(Input=existing_cust,
183 Statement="Is it an Existing Customer: \nA. Yes \nB. No",
184 Range=["A", "B"], Identifier="A")
185
186 if existing_cust == "A":
187 print("What is the Customer's Name:")
188 request["CustomerName"] = string.capwords(input("> "))
189 request["CustomerName"] = validate_an_input(Identifier="C", Input=request["CustomerName"],
190 Statement="What is the Customer's Name:")
191
192 request["EXISTINGCUST"] = True
193 details = other_commands(request, "C")
194 print("- - " * 10)
195 l_p_c = print_function(details, "B")
196 print("- - " * 10)
197 print("Enter the Number which Corresponds to the Customer:")
198 option1 = input("> ")
199 option1 = validate_an_input(Input=option1, Range=["1", str(len(details))], Identifier="A",
200 Statement="Enter the Number which Corresponds to the Customer:")
201 if option1 == str(len(details)):
202 existing_cust = "B"
203 else:
204 request["CustomerIDIndex"] = str(option1)
205
206 if existing_cust == "B":
207 request["EXISTINGCUST"] = False
208 print("Create a New Customer Profile:")
209 if "CustomerName" not in request:
210 print("What is the Customer's Name:")
211 request["CustomerName"] = string.capwords(input("> "))
212 request["CustomerName"] = validate_an_input(Statement="What is the Customer's Name:",
213 Identifier="C", Input=request["CustomerName"])
214
215 print("What is the Customer's Postcode:")
216 request["CustomerPostcode"] = input("> ").upper()
217 request["CustomerPostcode"] = validate_an_input(Input=request["CustomerPostcode"], Identifier="D",
218 Statement="What is the Customer's Postcode:")
219
220 print("What is the Customer's Address:")
221 request["CustomerAddress"] = input("> ")
222 while (request["CustomerAddress"] == "") or (
223 all(x.isnumeric() or x.isspace() for x in request["CustomerAddress"]) is True):
224 print("Please enter a valid input")
225 print("What is the Customer's Address:")
226 request["CustomerAddress"] = input("> ")
227 print("- - "*40)
228
229 print("What is the Customer's Email:")
230 request["CustomerEmail"] = input("> ")
231 match = re.findall(r"^[A-Z|a-z|0-9|.]+[@][A-Z|a-z|0-9]+[.][A-Z|a-z|0-9]+",
232 request["CustomerEmail"])
233 while True:
234 try:
235 if match == []:
236 print("Please enter a valid email address")
237 request["CustomerEmail"] = input("> ")
238 match = re.findall(r"^[A-Z|a-z|0-9|.]+[@][A-Z|a-z|0-9]+[.][A-Z|a-z|0-9]+",
239 request["CustomerEmail"])
240 break
241 except:
242 pass
243
244 else:
245 request = {}
246 request["command"] = "INSERT"
247 choice2 = ""
248
249 elif choice == "3":
250 print("What is the Customer's Name:")
251 request["CustomerName"] = input("> ")
252 request["CustomerName"] = validate_an_input(Identifier="C", Input=request["CustomerName"],
253 Statement="What is the Customer's Name:")
254 print("What is the Customer's Postcode:")
255 request["CustomerPostcode"] = input("> ").upper()
256 request["CustomerPostcode"] = validate_an_input(Identifier="D", Input=request["CustomerPostcode"],
257 Statement="What is the Customer's Postcode:").upper()
258 results = other_commands(request, "B")
259 if results[1][0] == "None Pending":
260 print("The Customer " + request["CustomerName"] + " has no Pending Orders")
261 else:
262 l_p_c = print_function(results, "B")
263 print("-" * sum(i + 5 for i in l_p_c.values()))
264 print("Enter the Number which Corresponds to the Order:")
265 change_order_id = input("> ")
266 change_order_id = validate_an_input(Identifier="A", Range=["1", str(len(results) - 1)],
267 Input=change_order_id,
268 Statement="Enter the Number which Corresponds to the Order:")
269
270 product_column_id = results[0].index("Product")
271 quantity_column_id = results[0].index("Amount Ordered")
272 price_when_sale_id = results[0].index("Price Of Item When Sale Made")
273
274 new_results = results
275 new_results[int(change_order_id)][product_column_id] = new_results[int(change_order_id)][
276 product_column_id].split(",")
277 new_results[int(change_order_id)][quantity_column_id] = new_results[int(change_order_id)][
278 quantity_column_id].split(",")
279 new_results[int(change_order_id)][price_when_sale_id] = new_results[int(change_order_id)][
280 price_when_sale_id].split(",")
281
282 products_changed, added_products, removed_products = edit_order(new_results, change_order_id)
283 request["command"] = "UPDATE"
284 request["table"] = "Orders"
285 request["CUSTOMERSORDERID"] = int(change_order_id)
286 request["PRODUCTSCHANGED"] = products_changed
287 request["ADDEDPRODUCTS"] = added_products
288 request["REMOVEDPRODUCTS"] = removed_products
289
290 elif choice == "4":
291 request["command"] = "DELETE"
292 print("What is the Customer's Name:")
293 request["CustomerName"] = input("> ")
294 request["CustomerName"] = validate_an_input(Input=request["CustomerName"],
295 Statement="What is the Customer's Name:", Identifier="C")
296 print("What is the Customer's Postcode")
297 request["CustomerPostcode"] = input("> ").upper()
298 request["CustomerPostcode"] = validate_an_input(Input=request["CustomerPostcode"],
299 Statement="What is the Customer's Postcode:", Identifier="D")
300 results = other_commands(request, "B")
301 if results[1][0] == "None Pending":
302 print("The Customer " + request["CustomerName"] + " has no Orders to be deleted.")
303 else:
304 l_p_c = print_function(results, "B")
305 print("Which of the Customer's Order(s) do you want to delete:")
306 delete_id = input("> ")
307 delete_id = validate_an_input(Input=delete_id,
308 Statement="Which of the Customer's Order(s) do you want to delete:",
309 Identifier="A", Range=["1", str(len(results))])
310 print("-" * sum(i + 5 for i in l_p_c.values()))
311 request["DELETEINDEX"] = delete_id
312 request["REMOVEDPRODUCTS"] = {}
313 product_column_id = results[0].index("Product")
314 number_ordered_column_id = results[0].index("Amount Ordered")
315
316 index = 0
317 for item in results[int(delete_id)][int(product_column_id)].split(","):
318 request["REMOVEDPRODUCTS"][item] = results[int(delete_id)][int(number_ordered_column_id)].split(",")[index]
319 index += 1
320 request["command"] = "DELETE"
321
322 request["options"] = choice + choice2
323
324 if choice == "5":
325 request = {}
326
327 return request
328
329
330def Check_Off_Orders(request):
331 request["command"] = "CHECKOFFORDERS"
332 request["SELECT_UNCOMPLETED"] = []
333 uncompleted_orders = other_commands(request, "L")
334 del request["SELECT_UNCOMPLETED"]
335 request["UPDATE_UNCOMPLETED"] = []
336 order_id = ""
337 finished = False
338 while finished != True:
339 print("Type a Number Corresponding to a Completed Order:")
340 l_p_c = print_function(uncompleted_orders, "B")
341 print("-" * sum(i + 5 for i in l_p_c.values()))
342 print(str(len(uncompleted_orders)) + ") Finish")
343 order_id = input("> ")
344 order_id = validate_an_input(Statement="Type the Numbers Corresponding to the Completed Orders:",
345 Input=order_id, Identifier="A", Range=["1", str(len(uncompleted_orders))])
346 try:
347 request["UPDATE_UNCOMPLETED"].append(uncompleted_orders[int(order_id)][0])
348 info = uncompleted_orders.pop(int(order_id))
349 except IndexError:
350 finished = True
351 if request["UPDATE_UNCOMPLETED"] == []:
352 request = {}
353
354 return request
355
356
357def ProductsAndStock(request, StaffID, LoggedIn):
358 ####ProductsAndStock####
359 # Parameters :- request:dictionary, StaffID:Integer, LoggedIn:Integer #
360 # Return Type :- request:dictionary #
361 # Purpose:- This table handles all of the requests, data input and SQL operations #
362 # for the 'Stock' table. The user navigates a Command Line Interface till they get #
363 # to the option they like and then enter the required data, their request is passed #
364 # over to the server and then the server carries out its operations and return the #
365 # result which is printed on the client program using the print_function function. #
366 ########################
367 no_option = False
368 print("- - " * 40)
369 print("PRODUCTS AND STOCK MENU:")
370 request["table"] = "Stock"
371 choice2 = ""
372 choice3 = ""
373 print('''Do you want to:
3741. View Products and Stock Levels
3752. Add New Item of Stock
3763. Change Stock Levels or Product Info
3774. Return to Main Menu''')
378 choice = input("> ")
379 choice = validate_an_input(Identifier="A", Range=["1", "4"],
380 Statement='''Do you want to:\n1. View Products and Stock Levels\n2. Add New Item of Stock\n3. Change Stock Levels or Product Info\n4. Return to Main Menu''',
381 Input=choice)
382 print("- - " * 40)
383
384 if choice == "1":
385 request = display_product_types2(request, "B")
386 request["command"] = "SELECT"
387
388 elif choice == "2":
389 no_option = False
390 if LoggedIn < 3:
391 print("You do not have a high enough access level to access this")
392 no_option = True
393 else:
394 request["command"] = "INSERT"
395 request["ADDNEWPRODUCT"] = {}
396 stock_categories = dict(other_commands(request, "D")).keys()
397 valid_name = False
398 name_exist = False
399 while valid_name != True:
400 print("What is the Product Name:")
401 request["ADDNEWPRODUCT"]["ProductName"] = string.capwords(input("> "))
402 product_names = other_commands(request, "A")
403 for item in product_names:
404 if item[0] == request["ADDNEWPRODUCT"]["ProductName"]:
405 print("Product Already Exists in the Database, Please enter a Valid Input.")
406 name_exist = True
407 if name_exist == False:
408 valid_name = True
409 print("- - " * 40)
410
411 print("What is the Current Amount in Stock:")
412 request["ADDNEWPRODUCT"]["AmountInStock"] = input("> ")
413 request["ADDNEWPRODUCT"]["AmountInStock"] = validate_an_input(
414 Input=request["ADDNEWPRODUCT"]["AmountInStock"], Statement="What is the Current Amount in Stock:",
415 Identifier="G")
416
417 print("What is the Cost Per Pack for the Business:")
418 request["ADDNEWPRODUCT"]["BusinessCostPerPack"] = input("> ")
419 request["ADDNEWPRODUCT"]["BusinessCostPerPack"] = validate_an_input(
420 Input=request["ADDNEWPRODUCT"]["BusinessCostPerPack"],
421 Statement="What is the Cost Per Pack for the Business:", Identifier="H")
422 request["ADDNEWPRODUCT"]["BusinessCostPerPack"] = float(request["ADDNEWPRODUCT"]["BusinessCostPerPack"])
423
424 print("How Many are There in a Pack:")
425 request["ADDNEWPRODUCT"]["NumberInAPack"] = input("> ")
426 request["ADDNEWPRODUCT"]["NumberInAPack"] = validate_an_input(
427 Input=request["ADDNEWPRODUCT"]["NumberInAPack"], Identifier="F",
428 Statement="How Many are There in a Pack:")
429
430 print("What is the Customer Cost Per Item:")
431 request["ADDNEWPRODUCT"]["CustomerCostPerItem"] = input("> ")
432 request["ADDNEWPRODUCT"]["CustomerCostPerItem"] = validate_an_input(Identifier="H",
433 Input=request["ADDNEWPRODUCT"][
434 "CustomerCostPerItem"],
435 Statement="What is the Customer Cost Per Item:")
436 request["ADDNEWPRODUCT"]["CustomerCostPerItem"] = float(request["ADDNEWPRODUCT"]["CustomerCostPerItem"])
437
438 request = display_product_types2(request, "A")
439 request["ADDNEWPRODUCT"]["TypeOfProduct"] = request["TypeOfProduct"]
440 del (request["TypeOfProduct"])
441
442 print("Who is the Supplier of this Product:")
443 suppliers = other_commands(request, "E")
444 suppliers = print_function(suppliers, "B")
445 request["ADDNEWPRODUCT"]["SupplierID"] = input("> ")
446 request["ADDNEWPRODUCT"]["SupplierID"] = int(request["ADDNEWPRODUCT"]["SupplierID"])
447 request["command"] = "INSERT"
448
449
450 elif choice == "3":
451 request["command"] = "UPDATE"
452 product_names = other_commands(request, "G")
453 id_in_list = ""
454 request["UPDATEQUERY"] = {}
455 valid = False
456 while valid == False:
457 print_function(product_names, "B")
458 change_dict = {}
459 print("Which Product would you like to change information about\nOr type '-1' to Cancel/Finish:")
460 id_in_list = input("> ")
461 while (id_in_list != "-1") and ((int(id_in_list) > len(product_names) - 1) or (int(id_in_list) < 1)):
462 print("Please enter a valid input")
463 id_in_list = input("> ")
464 if id_in_list != "-1":
465 index = 1
466 for item in product_names[0]:
467 print(str(index) + ") " + item)
468 index += 1
469 print("What would you like to edit about the Product")
470 edit_column_id = input("> ")
471 edit_column_id = validate_an_input(Input=edit_column_id, Identifier="A",
472 Range=["1", str(len(product_names[0]))],
473 Statement="What would you like to edit about the Product")
474
475 if edit_column_id == "1":
476 no_option = False
477 if LoggedIn < 5:
478 print("You do not have the permissions to access this")
479 no_option = True
480 else:
481 print("What is the New Name for the Product:")
482 new = input("> ")
483 valid_name = False
484 name_exist = False
485 while valid_name != True:
486 product_names = other_commands(request, "A")
487 for item in product_names:
488 if item[0] == new:
489 print("Product Already Exists in the Database, Please enter a Valid Input.")
490 name_exist = True
491 if name_exist == False:
492 valid_name = True
493 break
494 print("What is the New Name for the Product:")
495 new = string.capwords(input("> "))
496 request["UPDATEQUERY"]["ProductName"] = new
497
498 elif edit_column_id == "2":
499 print("What is the New Amount in Stock:")
500 new = input("> ")
501 new = validate_an_input(Identifier="G", Input=new, Statement="What is the New Amount in Stock:")
502 request["UPDATEQUERY"]["AmountInStock"] = new
503
504 elif edit_column_id == "3":
505 no_option = False
506 if LoggedIn < 3:
507 print("You do not have the permissions to access this")
508 no_option = True
509 else:
510 print("What is the Business Cost Per Pack:")
511 new = input("> ")
512 new = validate_an_input(Identifier="H", Input=new,
513 Statement="What is the Business Cost Per Pack:")
514 request["UPDATEQUERY"]["BusinessCostPerPack"] = new
515
516 elif edit_column_id == "4":
517 no_option = False
518 if LoggedIn < 3:
519 print("You do not have the permissions to access this")
520 no_option = True
521 else:
522 print("What is the New Amount per Pack:")
523 new = input("> ")
524 new = validate_an_input(Identifier="F", Input=new, Statement="What is the New Amount per Pack:")
525 request["UPDATEQUERY"]["NumberInAPack"] = new
526
527 elif edit_column_id == "5":
528 no_option = False
529 if LoggedIn < 3:
530 print("You do not have the permissions to access this")
531 no_option = True
532 else:
533 print("What is the New Customer Cost Per Item:")
534 new = input("> ")
535 new = validate_an_input(Identifier="H", Input=new,
536 Statement="What is the New Customer Cost Per Item:")
537 request["UPDATEQUERY"]["CustomerCostPerItem"] = float(new)
538
539 elif edit_column_id == "6":
540 if LoggedIn < 5:
541 print("You do not have the permissions to access this")
542 request = {}
543 else:
544 product_types = other_commands(request, "D")
545 product_types = [[x] for x in (list(product_types.keys()))]
546 product_types.insert(0, ["Product Types:"])
547 print("What Type of Product Would you like to Change it to:")
548 l_p_c = print_function(product_types, "B")
549 print("-" * sum(i + 5 for i in l_p_c.values()))
550 print(str(len(product_types)) + ") Add New Product Type")
551 option = input("> ")
552 option = validate_an_input(Identifier="A",
553 Statement="What Type of Product Would you like to Change it to:",
554 Input=option, Range=["1", str(len(product_types))])
555 if option == str(len(product_types)):
556 print("What is the New Type Of Product:")
557 new = input("> ")
558 while True:
559 in_dbase = False
560 for item in product_types:
561 if item[0] == new:
562 in_dbase = True
563 print("Product Type already exists in Database.")
564 print("What is the New Type Of Product:")
565 new = input("> ")
566 if in_dbase == False and new != "":
567 break
568 request["UPDATEQUERY"]["TypeOfProduct"] = new
569 else:
570 request["UPDATEQUERY"]["TypeOfProduct"] = product_types[int(option)][0]
571
572 elif edit_column_id == "7":
573 no_option = False
574 if LoggedIn < 5:
575 print("You do not have the permissions to access this")
576 no_option = True
577 else:
578 print("Who is the New Supplier:")
579 suppliers = other_commands(request, "E")
580 operations = True
581 while operations == True:
582 supplier_in_dbase = False
583 l_p_c = print_function(suppliers, "B")
584 print("-" * sum(i + 5 for i in l_p_c.values()))
585 print(str(len(suppliers)) + ") Add New Supplier")
586 option = input("> ")
587 option = validate_an_input(Identifier="A", Statement="Who is the New Supplier:",
588 Input=option, Range=["1", str(len(suppliers))])
589 if option == str(len(suppliers)):
590 print("HI")
591 request["table"] = "Suppliers"
592 request["command"] = "INSERT"
593 request["ADDNEWDETAILS"] = {}
594 valid = False
595 while not valid:
596 supplier_in_dbase = False
597 print("What is the Supplier Name\nEnter '-1' to Choose an Existing Supplier:")
598 request["ADDNEWDETAILS"]["SupplierName"] = input("> ")
599 if request["ADDNEWDETAILS"]["SupplierName"] == "":
600 print("Please enter a valid name.")
601 elif request["ADDNEWDETAILS"]["SupplierName"] == "-1":
602 valid = True
603 else:
604 for supplier in suppliers:
605 if supplier[0] == request["ADDNEWDETAILS"]["SupplierName"]:
606 print("Supplier Already Exists in Database")
607 supplier_in_dbase = True
608 if supplier_in_dbase == False:
609 print("What is the Supplier's Contact Number:")
610 request["ADDNEWDETAILS"]["SupplierContactNumber"] = input("> ")
611 request["ADDNEWDETAILS"]["SupplierContactNumber"] = validate_an_input(
612 Input=request["ADDNEWDETAILS"]["SupplierContactNumber"],
613 Statement="What is the Supplier's Contact Number:", Identifier="E")
614 valid = True
615 s.send((json.dumps(request) + "!EOF!").encode())
616 response1 = ""
617 while "!EOF!" not in response1:
618 response1 = response1 + s.recv(1024).decode()
619 response1 = response1.replace("!EOF!", "")
620 response1 = json.loads(response1)
621 print(response1)
622 operations = False
623 else:
624 operations = False
625
626 if option == str(len(suppliers) + 1):
627 suppliers = other_commands(request, "E")
628 l_p_c = print_function(request, "B")
629 print("Who is the New Supplier")
630 option = input("> ")
631 option = validate_an_input(Identifier="A", Statement="Who is the New Supplier:",
632 Input=option, Range=["1", str(len(suppliers))])
633 request["UPDATEQUERY"]["SupplierID"] = int(option)
634
635
636 request["command"] = "UPDATE"
637 request["table"] = "Stock"
638 request["clause"] = "ProductName = '" + str(product_names[int(id_in_list)][0]) + "'"
639 if edit_column_id in ["1", "3", "4", "5", "6", "7"]:
640 no_option = False
641 if LoggedIn < 3:
642 no_option = True
643 else:
644 valid = True
645
646 else:
647 break
648
649 print("- -" * 40)
650
651 request["options"] = choice + choice2 + choice3
652
653 if choice == "4" or no_option == True:
654 request = {}
655 return request
656
657
658def StaffAndLoginDetails(request):
659 ####StaffAndLoginDetails####
660 # Parameters :- request:dictionary #
661 # Return Type :- request:dictionary #
662 # Purpose:- This table handles all of the requests, data input and SQL operations #
663 # for the 'Staff' table. The user navigates a Command Line Interface till they get #
664 # to the option they like and then enter the required data, their request is passed #
665 # over to the server and then the server carries out its operations and return the #
666 # result which is printed on the client program using the print_function function. #
667 ############################
668 print("- - " * 40)
669 print("STAFF AND LOGIN DETAILS MENU:")
670 request["table"] = "Staff"
671 choice2 = ""
672 choice3 = ""
673 print('''Do you want to:
6741. View Staff and Login Details
6752. Add New Staff Details
6763. Change Existing Staff/Login Details
6774. Return to Main Menu''')
678 choice = input("> ")
679 choice = validate_an_input(Input=choice,
680 Statement="Do you want to:\n1. View Staff and Login Details\n2. Add New Staff Details\n3. Change Existing Staff/Login Details\n4. Return to Main Menu",
681 Identifier="A", Range=["1", "4"])
682 print("- - " * 40)
683
684 if choice == "1":
685 request["command"] = "SELECT"
686 print('''Do you want to:
687A. Get Staff Details
688B. Get Login Details
689C. Get Both''')
690 choice2 = input("> ").upper()
691 choice2 = validate_an_input(Identifier="A", Range=["A", "C"],
692 Statement="Do you want to:\nA. Get Staff Details\nB. Get Login Details\nC. Get Both",
693 Input=choice2)
694
695 print('''Do you want to:
696A. Get Information for a Certain Staff Member
697B. Get Information for all Staff Members''')
698 choice3 = input("> ").upper()
699 choice3 = validate_an_input(Input=choice3, Identifier="A",
700 Statement="Do you want to:\nA. Get Information for a Certain Staff Member\nB. Get Information for all Staff Members",
701 Range=["A", "B"])
702
703 if choice3 == "A":
704 print("Enter the Staff Member's Name:")
705 request["StaffName"] = string.capwords(input("> "))
706 request["StaffName"] = validate_an_input(Identifier="C", Input=request["StaffName"],
707 Statement="Enter the Staff Member's Name:")
708
709 elif choice == "2":
710 request["ADDSTAFFDETAILS"] = {}
711
712 print("What is the Staff Member's Name:")
713 request["ADDSTAFFDETAILS"]["StaffName"] = input("> ")
714 request["ADDSTAFFDETAILS"]["StaffName"] = validate_an_input(Input=request["ADDSTAFFDETAILS"]["StaffName"],
715 Statement="What is the Staff Member's Name:",
716 Identifier="C")
717
718 print(
719 "What is the Staff Member's Position:\nEither: Boss, Yard Manager, Yard Staff, Office Manager, or Office Staff")
720 request["ADDSTAFFDETAILS"]["StaffPosition"] = input("> ").capitalize()
721 while request["ADDSTAFFDETAILS"]["StaffPosition"] not in ["Boss", "Yard manager", "Yard staff", "Office staff",
722 "Office manager"]:
723 print("Please enter a valid option")
724 request["ADDSTAFFDETAILS"]["StaffPosition"] = input("> ").capitalize()
725 print("- -" * 40)
726
727 print("What is the Staff Member's Contact Number:")
728 request["ADDSTAFFDETAILS"]["StaffContactNo"] = input("> ")
729 request["ADDSTAFFDETAILS"]["StaffContactNo"] = validate_an_input(
730 Input=request["ADDSTAFFDETAILS"]["StaffContactNo"], Statement="What is the Staff Member's Contact Number:",
731 Identifier="E")
732
733 print("What is the Staff Member's Emergency Contact Number:")
734 request["ADDSTAFFDETAILS"]["StaffEmergencyContactNo"] = input("> ")
735 request["ADDSTAFFDETAILS"]["StaffEmergencyContactNo"] = validate_an_input(
736 Input=request["ADDSTAFFDETAILS"]["StaffEmergencyContactNo"],
737 Statement="What is the Staff Member's Emergency Contact Number:", Identifier="E")
738
739 print("What is the Staff Member's Date of Birth in the format xxxx-xx-xx, year-month-date:")
740 request["ADDSTAFFDETAILS"]["StaffBirthDate"] = input("> ")
741 request["ADDSTAFFDETAILS"]["StaffBirthDate"] = validate_an_input(Identifier="B",
742 Input=request["ADDSTAFFDETAILS"][
743 "StaffBirthDate"],
744 Statement="What is the Staff Member's Date of Birth in the format xxxx-xx-xx, year-month-date:")
745
746 print("What is the Staff Member's Postcode:")
747 request["ADDSTAFFDETAILS"]["StaffPostcode"] = input("> ").upper()
748 request["ADDSTAFFDETAILS"]["StaffPostcode"] = validate_an_input(
749 Input=request["ADDSTAFFDETAILS"]["StaffPostcode"], Statement="What is the Staff Member's Postcode:",
750 Identifier="D").upper()
751
752 print("What is the Staff Member's Address:")
753 request["ADDSTAFFDETAILS"]["StaffAddress"] = input("> ")
754 while (request["ADDSTAFFDETAILS"]["StaffAddress"] == "") or (
755 all(x.isnumeric() or x.isspace() for x in request["ADDSTAFFDETAILS"]["StaffAddress"]) is True):
756 print("Please enter a valid input")
757 print("What is the Staff Member's Address:")
758 request["ADDSTAFFDETAILS"]["StaffAddress"] = input("> ")
759 print("- - " * 40)
760
761 request["ADDSTAFFDETAILS"]["AmountOfSales"] = 0
762
763 request["ADDSTAFFDETAILS"]["DateEmployed"] = ""
764
765 print("What is the Staff Members Username")
766 request["ADDSTAFFDETAILS"]["Username"] = input("> ")
767 usernames = other_commands(request, "J")
768 while True:
769 counter = 0
770 for username in usernames:
771 if username[0] == request["ADDSTAFFDETAILS"]["Username"]:
772 counter += 1
773 if counter == 0 and request["ADDSTAFFDETAILS"]["Username"] != "":
774 break
775 else:
776 print("Username already exists in Database Please enter a new one")
777 request["ADDSTAFFDETAILS"]["Username"] = input("> ")
778
779 print("Create a Password for the Employee:")
780 request["ADDSTAFFDETAILS"]["Password"] = input("> ")
781 while (len(request["ADDSTAFFDETAILS"]["Password"]) > 1) == False:
782 print("Please enter a valid option")
783 request["ADDSTAFFDETAILS"]["Password"] = input("> ")
784
785 print("What is the Employee's Level Of Access: (1-5), (Lowest-Highest)")
786 request["ADDSTAFFDETAILS"]["LevelOfAccess"] = input("> ")
787 request["ADDSTAFFDETAILS"]["LevelOfAccess"] = validate_an_input(
788 Input=request["ADDSTAFFDETAILS"]["LevelOfAccess"],
789 Statement="What is the Employee's Level Of Access: (1-5), (Lowest-Highest)", Identifier="A",
790 Range=["1", "5"])
791 request["command"] = "INSERT"
792
793
794 elif choice == "3":
795 request["command"] = "SELECT"
796 print("What is the Staff Member's Name:")
797 request["StaffName"] = input("> ")
798 request["StaffName"] = validate_an_input(Input=request["StaffName"],
799 Statement="What is the Staff Member's Name:", Identifier="C")
800 staff_members = other_commands(request, "I")
801 print("Which Staff Member do you mean:")
802 l_p_c = print_function(staff_members, "B")
803 print("-" * sum(i + 5 for i in l_p_c.values()))
804 print(str(len(staff_members)) + ") None of the above")
805 staffid = input("> ")
806 staffid = validate_an_input(Statement="Which Staff Member do you mean:", Identifier="A",
807 Range=["1", str(len(staff_members))], Input=staffid)
808 if staffid == str(len(staff_members)):
809 request = {}
810 print("You can add a new Staff Member in the Customers Menu")
811 else:
812 print("What about this Staff Member do you want to edit:")
813 staff_columns = [[x] for x in staff_members[0]]
814 staff_columns.insert(0, ["Categories"])
815 l_p_c = print_function(staff_columns, "B")
816 print("-" * sum(i + 5 for i in l_p_c.values()))
817 index = input("> ")
818 index = validate_an_input(Input=index, Statement="What about this Staff Member do you want to edit:",
819 Identifier="A", Range=["1", str(len(staff_members[0]))])
820 request["UPDATEQUERY"] = {}
821 if index == "1":
822 print("What do you want to change the Staff Member's Name to:")
823 request["UPDATEQUERY"]["StaffName"] = input("> ")
824 request["UPDATEQUERY"]["StaffName"] = validate_an_input(Identifier="C",
825 Input=request["UPDATEQUERY"]["StaffName"],
826 Statement="What do you want to change the Staff Member's Name to:")
827 elif index == "2":
828 print(
829 "What do you want to change the Staff Member's Position to:\nEither: Boss, Yard Manager, Yard Staff, Office Manager, or Office Staff")
830 request["UPDATEQUERY"]["StaffPosition"] = input("> ").capitalize()
831 while request["UPDATEQUERY"]["StaffPosition"] not in ["Boss", "Yard manager", "Yard staff",
832 "Office staff", "Office manager"]:
833 print("Please enter a valid input.")
834 request["UPDATEQUERY"]["StaffPosition"] = input("> ").capitalize()
835 elif index == "3":
836 print("What do you want to change the Staff Member's Contact Number to:")
837 request["UPDATEQUERY"]["StaffContactNo"] = input("> ")
838 request["UPDATEQUERY"]["StaffContactNo"] = validate_an_input(Identifier="E",
839 Input=request["UPDATEQUERY"][
840 "StaffContactNo"],
841 Statement="What do you want to change the Staff Member's Contact Number to:")
842 elif index == "4":
843 print("What do you want to change the Staff Member's Emergency Contact Number to:")
844 request["UPDATEQUERY"]["StaffEmergencyContactNo"] = input("> ")
845 request["UPDATEQUERY"]["StaffEmergencyContactNo"] = validate_an_input(Identifier="E",
846 Input=request["UPDATEQUERY"][
847 "StaffEmergencyContactNo"],
848 Statement="What do you want to change the Staff Member's Emergency Contact Number to:")
849 elif index == "5":
850 print("What do you want to change the Staff Member's Postcode to:")
851 request["UPDATEQUERY"]["StaffPostcode"] = input("> ").upper()
852 request["UPDATEQUERY"]["StaffPostcode"] = validate_an_input(Identifier="D",
853 Statement="What do you want to change the Staff Member's Postcode to:",
854 Input=request["UPDATEQUERY"][
855 "StaffPostcode"]).upper()
856 elif index == "6":
857 print("What do you want to change the Staff Member's Address to:")
858 request["UPDATEQUERY"]["StaffAddress"] = input("> ")
859 while (request["UPDATEQUERY"]["StaffAddress"] == "") or (
860 all(x.isnumeric() or x.isspace() for x in request["UPDATEQUERY"]["StaffAddress"]) is True):
861 print("Please enter a Valid Input")
862 print("What do you want to change the Staff Member's Address to:")
863 request["UPDATEQUERY"]["StaffAddress"] = input("> ")
864 elif index == "7":
865 print(
866 "What do you want to change the Staff Member's Unemployed Date to\nIn the form xxxx-xx-xx (year-month-date):")
867 request["UPDATEQUERY"]["DateUnemployed"] = input("> ")
868 request["UPDATEQUERY"]["DateUnemployed"] = validate_an_input(Identifier="B",
869 Statement="What do you want to change the Staff Member's Unemployed Date to\nIn the form xxxx-xx-xx (year-month-date):",
870 Input=request["UPDATEQUERY"][
871 "DateUnemployed"])
872 elif index == "8":
873 print("What do you want to change the Staff Member's Username to:")
874 request["UPDATEQUERY"]["Username"] = input("> ")
875 usernames = other_commands(request, "J")
876 print(usernames)
877 while True:
878 counter = 0
879 for username in usernames:
880 if username[0] == request["UPDATEQUERY"]["Username"]:
881 counter += 1
882 if counter == 0 and request["UPDATEQUERY"]["Username"] != "":
883 break
884 else:
885 print("Username already exists in Database Please enter a new one")
886 request["UPDATEQUERY"]["Username"] = input("> ")
887 elif index == "9":
888 print("What do you want to change the Staff Member's Password to:")
889 request["UPDATEQUERY"]["Password"] = input("> ")
890 while request["UPDATEQUERY"]["Username"] == "":
891 print("Please enter a Password")
892 request["UPDATEQUERY"]["Password"] = input("> ")
893 elif index == "10":
894 print("What do you want to change the Staff Member's Level Of Access to: (1-5), (Lowest-Highest)")
895 request["UPDATEQUERY"]["LevelOfAccess"] = input("> ")
896 request["UPDATEQUERY"]["LevelOfAccess"] = validate_an_input(Identifier="A",
897 Statement="What do you want to change the Staff Member's Level Of Access to: (1-5), (Lowest-Highest)",
898 Input=request["UPDATEQUERY"][
899 "LevelOfAccess"], Range=["1", "5"])
900 request["clause"] = "StaffName = '" + staff_members[int(staffid)][0] + "' AND StaffAddress = '" + staff_members[int(staffid)][5] + "'"
901 request["command"] = "UPDATE"
902
903 elif choice == "4":
904 request = {}
905
906 request["options"] = choice + choice2 + choice3
907
908 return request
909
910
911def Customers(request, StaffID, LoggedIn):
912 ####Customers####
913 # Parameters :- request:dictionary, StaffID:Integer, LoggedIn:Integer #
914 # Return Type :- request:dictionary #
915 # Purpose:- This table handles all of the requests, data input and SQL operations #
916 # for the 'Customers' table. The user navigates a Command Line Interface till they get #
917 # to the option they like and then enter the required data, their request is passed #
918 # over to the server and then the server carries out its operations and return the #
919 # result which is printed on the client program using the print_function function. #
920 #################
921 no_option = False
922 print("- - " * 40)
923 print("CUSTOMERS MENU:")
924 request["table"] = "Customers"
925 choice2 = ""
926 print('''Do you want to:
9271. View Customer Details and Pending Orders
928 (Pending Orders Only Applies when Searching for Specific Customers)
9292. Add Customer Details
9303. Change Existing Customers Details
9314. Delete Customer Details
9325. Return to Main Menu''')
933 choice = input("> ")
934 choice = validate_an_input(Input=choice,
935 Statement="Do you want to:\n1. View Customer Details and Pending Orders \n (Pending Orders Only Applies when Searching for Specific Customers)\n2. Add Customer Details\n3. Change Existing Customers Details\n4. Delete Customer Details\n5. Return to Main Menu",
936 Identifier="A", Range=["1", "5"])
937 print("- - " * 40)
938
939 if choice == "1":
940 request["command"] = "SELECT"
941 print('''Do you want to:
942A. Search for a Specific Customers Details
943B. Get all Customer Details''')
944 choice2 = input("> ").upper()
945 choice2 = validate_an_input(Input=choice2, Identifier="A", Range=["A", "B"],
946 Statement="Do you want to:\nA. Search for a Specific Customers Details\nB. Get all Customer Details")
947
948 if choice2 == "A":
949 print("Enter the Customers Name:")
950 request["CustomerName"] = string.capwords(input("> "))
951 request["CustomerName"] = validate_an_input(Input=request["CustomerName"],
952 Statement="Enter the Customers Name:", Identifier="C")
953 print("Enter the Customers Postcode:")
954 request["CustomerPostcode"] = input("> ").upper()
955 request["CustomerPostcode"] = validate_an_input(Input=request["CustomerPostcode"],
956 Statement="Enter the Customers Postcode:", Identifier="D").upper()
957
958 elif choice == "2":
959 request["command"] = "INSERT"
960 request["ADDNEWCUSTOMER"] = {}
961
962 print("What is the Customer's Name:")
963 request["ADDNEWCUSTOMER"]["CustomerName"] = input("> ").capitalize()
964 request["ADDNEWCUSTOMER"]["CustomerName"] = validate_an_input(Input=request["ADDNEWCUSTOMER"]["CustomerName"],
965 Statement="What is the Customer's Name:",
966 Identifier="C")
967
968 print("What is the Customer's Postcode:")
969 request["ADDNEWCUSTOMER"]["CustomerPostcode"] = input("> ").upper()
970 request["ADDNEWCUSTOMER"]["CustomerPostcode"] = validate_an_input(
971 Input=request["ADDNEWCUSTOMER"]["CustomerPostcode"], Statement="What is the Customer's Postcode:",
972 Identifier="D").upper()
973
974 print("What is the Customer's Address:")
975 request["ADDNEWCUSTOMER"]["CustomerAddress"] = input("> ")
976 while (request["ADDNEWCUSTOMER"]["CustomerAddress"] == "") or (
977 all(x.isnumeric() or x.isspace() for x in request["ADDNEWCUSTOMER"]["CustomerAddress"]) is True):
978 print("Please enter a valid input")
979 print("What is the Customer's Address:")
980 request["ADDNEWCUSTOMER"]["CustomerAddress"] = input("> ")
981 print("- -" * 40)
982
983 print("What is the Customer's Email:")
984 request["ADDNEWCUSTOMER"]["CustomerEmail"] = input("> ")
985 match = re.findall(r"^[A-Z|a-z|0-9|.]+[@][A-Z|a-z|0-9]+[.][A-Z|a-z|0-9]+",
986 request["ADDNEWCUSTOMER"]["CustomerEmail"])
987 while True:
988 try:
989 while match[0] != request["ADDNEWCUSTOMER"]["CustomerEmail"]:
990 print("Please enter a valid email address")
991 request["ADDNEWCUSTOMER"]["CustomerEmail"] = input("> ")
992 match = re.findall(r"^[A-Z|a-z|0-9|.]+[@][A-Z|a-z|0-9]+[.][A-Z|a-z|0-9]+",
993 request["ADDNEWCUSTOMER"]["CustomerEmail"])
994 break
995 except:
996 pass
997
998 elif choice == "3":
999 request["command"] = "SELECT"
1000 print("What is the Customer's Name:")
1001 request["CustomerName"] = input("> ")
1002 request["CustomerName"] = validate_an_input(Input=request["CustomerName"],
1003 Statement="What is the Customer's Name:", Identifier="C")
1004 customers = other_commands(request, "C")
1005 print("Which Customer Member do you mean:")
1006 l_p_c = print_function(customers, "B")
1007 print("-" * sum(i + 5 for i in l_p_c.values()))
1008 print(str(len(customers)) + ") None of the above")
1009 customerid = input("> ")
1010 customerid = validate_an_input(Statement="Which Customer do you mean:", Identifier="A",
1011 Range=["1", str(len(customers))], Input=customerid)
1012 if customerid == str(len(customers)):
1013 request = {}
1014 print("You can add a New Customer in the Customers Menu")
1015 else:
1016 request["CustomerIDIndex"] = customerid
1017 request["UPDATEQUERY"] = {}
1018 request["CustomerPostcode"] = customers[int(customerid)][1].upper()
1019 print("Customer Details:")
1020 specific_cust_details = other_commands(request, "K")
1021 l_p_c = print_function(specific_cust_details, "A")
1022 print("-" * sum(i + 5 for i in l_p_c.values()))
1023 print("")
1024 customer_columns = [[x] for x in specific_cust_details[0]]
1025 customer_columns.insert(0, ["Columns:"])
1026 l_p_c_2 = print_function(customer_columns, "B")
1027 print("-" * sum(i + 5 for i in l_p_c_2.values()))
1028 print("What about the Customer do you want to edit")
1029 column = input("> ")
1030 column = validate_an_input(Input=column, Statement="What about the Customer do you want to edit",
1031 Identifier="A", Range=["1", str(len(customer_columns))])
1032
1033 request["CustomerID"] = other_commands(request, "R")
1034
1035 if column == "1":
1036 print("What is the Customer's New Name:")
1037 request["UPDATEQUERY"]["CustomerName"] = input("")
1038 request["UPDATEQUERY"]["CustomerName"] = validate_an_input(Input=request["UPDATEQUERY"]["CustomerName"],
1039 Statement="What is the Customer's New Name:",
1040 Identifier="C")
1041 elif column == "2" or column == "3": # Check if they have ordered before
1042 customers_orders = other_commands(request, "F")
1043 if customers_orders == []: # Make Changes
1044 if column == "2":
1045 print("What is the Customer's New Postcode")
1046 request["UPDATEQUERY"]["CustomerPostcode"] = input("").upper()
1047 request["UPDATEQUERY"]["CustomerPostcode"] = validate_an_input(
1048 Input=request["UPDATEQUERY"]["CustomerPostcode"],
1049 Statement="What is the Customer's New Postcode:", Identifier="D").upper()
1050 elif column == "3":
1051 print("What is the Customer's New Address")
1052 request["UPDATEQUERY"]["CustomerAddress"] = input("> ")
1053 while (request["UPDATEQUERY"]["CustomerAddress"] == "") or (all(
1054 x.isnumeric() or x.isspace() for x in
1055 request["UPDATEQUERY"]["CustomerAddress"]) is True):
1056 print("Please enter a Valid Input.")
1057 print("What is the Customer's New Address")
1058 request["UPDATEQUERY"]["CustomerAddress"] = input("> ")
1059 else:
1060 print(
1061 "Cannot change Customer Details to maintain data integrity in their previous orders.\nYou could add them as a New Customer in the Customers Menu.")
1062 no_option = True
1063
1064 elif column == "4":
1065 print("What is the Customer's New Email:")
1066 request["UPDATEQUERY"]["CustomerEmail"] = input("")
1067 match = re.findall(r"^[A-Z|a-z|0-9|.]+[@][A-Z|a-z|0-9]+[.][A-Z|a-z|0-9]+",
1068 request["UPDATEQUERY"]["CustomerEmail"])
1069 while True:
1070 try:
1071 while match[0] != request["UPDATEQUERY"]["CustomerEmail"]:
1072 print("Please enter a valid email address")
1073 request["UPDATEQUERY"]["CustomerEmail"] = input("> ")
1074 match = re.findall(r"^[A-Z|a-z|0-9|.]+[@][A-Z|a-z|0-9]+[.][A-Z|a-z|0-9]+",
1075 request["UPDATEQUERY"]["CustomerEmail"])
1076 break
1077 except:
1078 pass
1079
1080 request["command"] = "UPDATE"
1081 request["clause"] = "Customers.CustomerID = " + str(request["CustomerID"])
1082
1083 request["options"] = choice + choice2
1084
1085 if choice == "4" or no_option == True:
1086 request = {}
1087
1088 return request
1089
1090
1091def Suppliers(request):
1092 ####Suppliers####
1093 # Parameters :- request:dictionary #
1094 # Return Type :- request:dictionary #
1095 # Purpose:- This table handles all of the requests, data input and SQL operations #
1096 # for the 'Suppliers' table. The user navigates a Command Line Interface till they get #
1097 # to the option they like and then enter the required data, their request is passed #
1098 # over to the server and then the server carries out its operations and return the #
1099 # result which is printed on the client program using the print_function function. #
1100 ##############
1101 print("- - " * 40)
1102 print("SUPPLIERS MENU:")
1103 request["table"] = "Suppliers"
1104 choice2 = ""
1105 print('''Do you want to:
11061. View Supplier Details
11072. Add New Supplier Details
11083. Change Existing Supplier Details
11094. Delete Supplier Details
11105. Return to Main Menu''')
1111 choice = input("> ")
1112 choice = validate_an_input(Identifier="A", Range=["1", "5"],
1113 Statement="Do you want to:\n1. View Supplier Details\n2. Add New Supplier Details\n3. Change Existing Supplier Details\n4. Delete Supplier Details\n5. Return to Main Menu",
1114 Input=choice)
1115 print("- - " * 40)
1116
1117 if choice == "1":
1118 request["command"] = "SELECT"
1119 print('''Do you want to:
1120A. Search for a Specific Supplier Details
1121B. Get all Supplier Details''')
1122 choice2 = input("> ").upper()
1123 choice2 = validate_an_input(Input=choice2,
1124 Statement="Do you want to:\nA. Search for a Specific Supplier Details\nB. Get all Supplier Details",
1125 Identifier="A", Range=["A", "B"])
1126
1127 if choice2 == "A":
1128 print("Enter the Suppliers Name:")
1129 request["SupplierName"] = string.capwords(input("> "))
1130 request["SupplierName"] = validate_an_input(Input=request["SupplierName"],
1131 Statement="Enter the Suppliers Name:", Identifier="C")
1132
1133 elif choice == "2":
1134 request["command"] = "INSERT"
1135 request["ADDNEWSUPPLIER"] = {}
1136 print("What is the Supplier's Company Name:")
1137 request["ADDNEWSUPPLIER"]["SupplierName"] = input("> ").capitalize()
1138 print("What is the Supplier's Phone Number:")
1139 request["ADDNEWSUPPLIER"]["SupplierContactNumber"] = input("> ")
1140 request["ADDNEWSUPPLIER"]["SupplierContactNumber"] = validate_an_input(
1141 Input=request["ADDNEWSUPPLIER"]["SupplierContactNumber"], Statement="What is the Supplier's Phone Number:",
1142 Identifier="E")
1143
1144 elif choice == "3":
1145 supplier_names = other_commands(request, "E")
1146 l_p_c = print_function(supplier_names, "B")
1147 print("-" * sum(i + 5 for i in l_p_c.values()))
1148 print(str(len(supplier_names)) + ") None of the above")
1149 print("-" * sum(i + 5 for i in l_p_c.values()))
1150 print("Which Supplier would you like to change details about:")
1151 supplier_id = input("> ")
1152 supplier_id = validate_an_input(Input=supplier_id,
1153 Statement="Which Supplier would you like to change details about:",
1154 Identifier="A", Range=["1", str(len(supplier_names))])
1155 supplier_columns = [[x] for x in supplier_names[0]]
1156 if supplier_id == str(len(supplier_names)):
1157 print("You can add a New Supplier in the Supplier Menu:")
1158 request = {}
1159 else:
1160 request["UPDATEQUERY"] = {}
1161 supplier_columns.insert(0, ["Columns"])
1162 l_p_c_2 = print_function(supplier_columns, "B")
1163 print("-" * sum(i + 5 for i in l_p_c_2.values()))
1164 print("Which column would you like to edit:")
1165 column_id = input("> ")
1166 column_id = validate_an_input(Input=column_id, Statement="Which column would you like to edit:",
1167 Identifier="A", Range=["1", str(len(supplier_columns) - 1)])
1168 if column_id == "1":
1169 valid = False
1170 while not valid:
1171 supplier_in_dbase = False
1172 print("What is the Supplier Name\n Or type '-1' to cancel:")
1173 request["UPDATEQUERY"]["SupplierName"] = input("> ")
1174 if request["UPDATEQUERY"]["SupplierName"] == "":
1175 print("Please enter a valid name.")
1176 elif request["UPDATEQUERY"]["SupplierName"] == "-1":
1177 request = {}
1178 valid = True
1179 else:
1180 for supplier in supplier_names:
1181 if supplier[0] == request["UPDATEQUERY"]["SupplierName"]:
1182 print("Supplier Already Exists in Database")
1183 supplier_in_dbase = True
1184 if supplier_in_dbase == False:
1185 valid = True
1186
1187 elif column_id == "2":
1188 print("What is the Supplier's Contact Number:")
1189 request["UPDATEQUERY"]["SupplierContactNumber"] = input("> ")
1190 request["UPDATEQUERY"]["SupplierContactNumber"] = validate_an_input(
1191 Input=request["UPDATEQUERY"]["SupplierName"], Statement="What is the Supplier's Contact Number:",
1192 Identifier="E")
1193
1194 request["command"] = "UPDATE"
1195 request["clause"] = "Suppliers.SupplierID = " + str(supplier_id)
1196
1197
1198
1199 elif choice == "4":
1200 supplier_count = other_commands(request, "M")
1201 supplier_ids_stock = []
1202 number_per_supplier = []
1203 supplier_ids = list(supplier_count.pop(-1))
1204 for supplier_details in supplier_count:
1205 supplier_ids_stock.append(supplier_details[0])
1206 number_per_supplier.append(supplier_details[1])
1207 can_delete = list(set(supplier_ids) - set(supplier_ids_stock))
1208 if can_delete == []:
1209 print(
1210 "There are no Suppliers that can be Deleted.\nTo Delete a Supplier they must be Supplying no Products.")
1211 request = {}
1212 else:
1213 info = []
1214 for supplier in can_delete:
1215 request["SupplierID"] = supplier
1216 results = other_commands(request, "N")
1217 for part in results:
1218 info.append(part)
1219 l_p_c = print_function(info, "A")
1220 print("-" * sum(i + 5 for i in l_p_c.values()))
1221 print("These Suppliers will be removed.")
1222 request["CANDELETE"] = can_delete
1223 request["command"] = "DELETE"
1224
1225 if request != {}:
1226 request["options"] = choice + choice2
1227
1228 if choice == "5":
1229 request = {}
1230
1231 return request
1232
1233
1234def Profit_Loss_Calculations(request):
1235 ####Profit_Loss_Calculations####
1236 # Parameters :- request:dictionary #
1237 # Return Type :- request:dictionary #
1238 # Purpose:- This table does all of the calculations to work out the profits #
1239 # of the business for every day between a given range and then plots that #
1240 # information on a graph and displays it. #
1241 ################################
1242 print(
1243 "From how long ago do you want to see profits:\n1. Past Week\n2. Past Month\n3. Past Year\n4. Choose Own Date")
1244 choice = input("> ")
1245 choice = validate_an_input(Identifier="A", Range=["1", "4"],
1246 Statement="From how long ago do you want to see profits:\n1. Past Week\n2. Past Month\n3. Past Year\n4. Choose Own Date",
1247 Input=choice)
1248 if choice == "4":
1249 print("From what Date do you want to see the Profits: xxxx-xx-xx (year-month-date)")
1250 request["Date"] = input("> ")
1251 request["Date"] = validate_an_input(Input=request["Date"],
1252 Statement="From what Date do you want to see the Profits: xxxx-xx-xx (year-month-date)",
1253 Identifier="D")
1254 else:
1255 request["choice"] = choice
1256 results = other_commands(request, "O")
1257 date_dict = {}
1258 for order in results:
1259 if order[0] not in date_dict.keys():
1260 date_dict[order[0]] = [[order[1], order[2], order[3]]]
1261 else:
1262 date_dict[order[0]] += [[order[1], order[2], order[3]]]
1263 x = list(date_dict.keys())
1264 y = []
1265 for date in x:
1266 values = date_dict[date]
1267 total = 0
1268 for order in values:
1269 subtotal = 0
1270 difference = order[1] - order[2]
1271 total_difference = difference * order[0]
1272 total += total_difference
1273 y.append(total)
1274
1275 x = [datetime.datetime.strptime(d, '%Y-%m-%d') for d in x]
1276 plt.plot(x, y, label=("Profit"))
1277 plt.xticks(rotation=270)
1278 plt.xlabel("Date")
1279 plt.ylabel("Profit Per Day")
1280 plt.title("A Graph Showing Profit Over Time")
1281 plt.legend()
1282 plt.show()
1283 request = {}
1284 return request
1285
1286
1287def See_Staff_Performance():
1288 ####See_Staff_Performance####
1289 # Parameters :- None #
1290 # Return Type :- request:dictionary #
1291 # Purpose:- This table plots a bar chart of the amount of sales for all of the #
1292 # staff members in the business over the past month. This is so that the boss/ #
1293 # someone with a high access level could monitor staff performances. #
1294 #############################
1295 request = {}
1296 staff_performance = other_commands(request, "Q")
1297 staff_performance = [list(x) for x in staff_performance]
1298 x_list = []
1299 y_list = []
1300 my_xticks = []
1301 index = 1
1302 for staff_member in staff_performance:
1303 x_list.append(index)
1304 staff_name = staff_member[0]
1305 my_xticks.append(staff_name)
1306 amount_of_sales = staff_member[1]
1307 y_list.append(amount_of_sales)
1308 index += 1
1309 x = np.array(x_list)
1310 y = np.array(y_list)
1311 plt.xticks(x, my_xticks)
1312 plt.bar(x, y, label=("Number of Sales"))
1313 plt.xlabel("Staff Name")
1314 plt.ylabel("Amount Of Sales in the Past Month")
1315 plt.title("A Graph Staff Members Sale Amounts")
1316 plt.legend()
1317 plt.show()
1318 print("Sales in the past month:")
1319 return request
1320
1321
1322def edit_order(results, change_order_id):
1323 ####edit_order####
1324 # Parameters :- results:list, change_order_id:integer #
1325 # Return Type :- products_changed:dictionary, added_products:dictionary, removed_products:dictionary #
1326 # Purpose:- This table manages all of the data inputs and updates for when the client wants to edit an order, #
1327 # it segments the changes they want to make into three dictionaries so it is easier for the server to process. #
1328 #################
1329 # results = the customers orders
1330 # change_order_id = the order id index number index number
1331 product_column_id = results[0].index("Product")
1332 quantity_column_id = results[0].index("Amount Ordered")
1333 price_when_sale_id = results[0].index("Price Of Item When Sale Made")
1334 change_order_id = int(change_order_id)
1335 edit_id = ""
1336 added_products = {}
1337 removed_products = {}
1338 request = {}
1339 products_changed = {}
1340 product_names = other_commands(request, "A")
1341 # product_names = the list of all the products and their quantities
1342
1343 while edit_id != len(results[change_order_id]) + 3:
1344 print("To Remove a Product, Change the Products Quantity to 0")
1345 for num in range(0, len(results[int(change_order_id)][product_column_id])):
1346 print(str(num + 1) + ") {0:<35} {1:<20} {2:<30}".format(
1347 results[int(change_order_id)][product_column_id][num],
1348 results[int(change_order_id)][quantity_column_id][num],
1349 results[int(change_order_id)][price_when_sale_id][num]))
1350 print(str(num + 2) + ") Add New Item")
1351 print(str(num + 3) + ") Finish Editing")
1352
1353 print("Choose which item you would like to edit:")
1354 edit_id = input("> ")
1355 edit_id = validate_an_input(Identifier="A",
1356 Range=["1", str(len(results[change_order_id][product_column_id]) + 2)],
1357 Statement="Choose which item you would like to edit:", Input=edit_id)
1358 edit_id = int(edit_id)
1359 # edit_id = the index of the item that will be edited
1360
1361 if edit_id == len(results[change_order_id][product_column_id]) + 2:
1362 break
1363
1364 elif edit_id == len(results[change_order_id][product_column_id]) + 1: # add new item
1365 l_p_c = print_function(product_names, "B")
1366 print("Choose which item you would like to add\nOr -1 to cancel:")
1367 item_id = input("> ")
1368 while (item_id.isdecimal() != True or int(item_id) <= 0 or int(item_id) > len(
1369 product_names)) and item_id != "-1":
1370 print("Please enter a valid input")
1371 item_id = input("")
1372 if item_id != "-1":
1373 # item_id = the index of the item in product_names that will be added to the order
1374 print("What quantity of this item would you like to add:")
1375 quantity = input("> ")
1376 # quantity = the quantity of the new item that will be added to the order
1377 while quantity.isdecimal() == False or int(quantity) <= 0 or int(quantity) > int(
1378 product_names[int(item_id)][1]):
1379 print("Please enter a valid input.")
1380 quantity = input("> ")
1381
1382 results[change_order_id][product_column_id].append(product_names[int(item_id)][0])
1383 results[change_order_id][quantity_column_id].append(int(quantity))
1384 results[change_order_id][price_when_sale_id].append(product_names[int(item_id)][2])
1385 added_products[product_names[int(item_id)][0]] = int(quantity)
1386 product_names[int(item_id)][1] -= int(quantity)
1387 else:
1388 print("- - " * 40)
1389 else:
1390 existing_item_id = -1
1391 index = 0
1392 for row in product_names:
1393 try:
1394 temp_item_index = row.index(str(results[int(change_order_id)][product_column_id][int(edit_id) - 1]))
1395 if temp_item_index > existing_item_id:
1396 existing_item_id = temp_item_index
1397 break
1398 except:
1399 index += 1
1400 print("Current Stock Levels for this Item:")
1401 print(str(product_names[int(index)][existing_item_id]) + " = " + str(
1402 product_names[int(index)][existing_item_id + 1]))
1403 print("- - " * 40)
1404 print("What is the New Quantity for this Product.\nEnter 0 to remove the product or '-1' to Cancel:")
1405 new_quantity = input("> ")
1406 print("- - " * 40)
1407
1408 while (new_quantity.isnumeric() != True or (int(new_quantity) < 0 and (
1409 int(new_quantity) - int(results[int(change_order_id)][quantity_column_id][edit_id - 1])) > int(
1410 product_names[int(index)][existing_item_id + 1]))) and new_quantity != "-1":
1411 if ((int(new_quantity) - int(results[int(change_order_id)][quantity_column_id][edit_id - 1])) > int(
1412 product_names[int(index)][existing_item_id + 1])):
1413 print("There is not enough stock to update to this amount.")
1414 print("The Stock Level for - " + str(product_names[int(index)][existing_item_id]) + ", is = " + str(
1415 product_names[int(index)][existing_item_id + 1]))
1416 print("- - " * 40)
1417 else:
1418 print("Please enter a valid input")
1419 print("What is the New Quantity for this Product.\nEnter 0 to remove the product\nOr -1 to cancel:")
1420 new_quantity = input("> ")
1421
1422 if int(new_quantity) == 0:
1423 removed_products[results[change_order_id][product_column_id][int(edit_id) - 1]] = int(
1424 results[int(change_order_id)][quantity_column_id][edit_id - 1])
1425 del (results[change_order_id][product_column_id][int(edit_id) - 1])
1426 del (results[change_order_id][quantity_column_id][int(edit_id) - 1])
1427 del (results[change_order_id][price_when_sale_id][int(edit_id) - 1])
1428 elif str(new_quantity) == "-1":
1429 pass
1430 else:
1431 product_names[int(index)][existing_item_id + 1] -= (
1432 int(new_quantity) - int(results[int(change_order_id)][quantity_column_id][edit_id - 1]))
1433 if str(product_names[int(index)][existing_item_id]) in list(products_changed.keys()):
1434 products_changed[str(product_names[int(index)][existing_item_id])] = \
1435 products_changed[str(product_names[int(index)][existing_item_id])].split("=>")[
1436 0] + "=>" + new_quantity
1437 else:
1438 products_changed[str(product_names[int(index)][existing_item_id])] = str(
1439 int(results[int(change_order_id)][quantity_column_id][edit_id - 1])) + "=>" + new_quantity
1440 results[int(change_order_id)][quantity_column_id][int(edit_id) - 1] = new_quantity
1441
1442 return products_changed, added_products, removed_products
1443
1444def display_product_types2(request, identifier):
1445 stock_categories = dict(other_commands(request, "D")).keys()
1446 print("Choose a Main Category")
1447 main_categories = []
1448 for category in stock_categories:
1449 index2 = category.find(" -")
1450 if index2 != -1:
1451 main_cat = category[:index2]
1452 else:
1453 main_cat = category
1454 if main_cat not in main_categories:
1455 main_categories.append(main_cat)
1456 index2 = 0
1457 for category in main_categories:
1458 index2 += 1
1459 print(str(index2) + ")", category)
1460 if identifier == "A":
1461 index2 += 1
1462 print(str(index2) + ") Create New Main Category")
1463 main_cat_choice = input("> ")
1464 while main_cat_choice.isdecimal == False or int(main_cat_choice) <= 0 or int(main_cat_choice) > index2:
1465 print("Please enter a valid option")
1466 main_cat_choice = input("> ")
1467 index = 0
1468 if identifier == "A":
1469 if str(index2) == main_cat_choice:
1470 print("What is the New Category Name")
1471 request["TypeOfProduct"] = input("> ")
1472 print("What is the New Sub-Category Name")
1473 sub_cat = input(request["TypeOfProduct"] + " - ")
1474 request["TypeOfProduct"] = request["TypeOfProduct"] + " - " + sub_cat
1475 else:
1476 print("What is the New Sub-Category Name")
1477 request["TypeOfProduct"] = input(main_categories[index])
1478 else:
1479 print("Choose a Sub-Category")
1480 specific_cat = []
1481 for category in stock_categories:
1482 if (category.split(" - ")[0]) == main_categories[int(main_cat_choice) - 1]:
1483 index += 1
1484 print(str(index) + ") " + category)
1485 specific_cat.append(category)
1486 sub_cat = input("> ")
1487 if identifier == "A":
1488 while all(x.isalpha() or x.isspace() for x in sub_cat) == False:
1489 print("Please enter a valid option")
1490 sub_cat = input(request["TypeOfProduct"] + " - ")
1491 elif identifier == "B":
1492 while sub_cat.isnumeric() == False:
1493 print("Please enter a valid option")
1494 sub_cat = input("> ")
1495
1496 stock_categories = [k for k in stock_categories]
1497 if identifier != "A":
1498 position = specific_cat.index(specific_cat[int(sub_cat) - 1])
1499 request["TypeOfProduct"] = specific_cat[position]
1500 return request
1501
1502
1503# Maybe use *kwargs with identifiers as keys as what to validate against e.g. "A" : 1-7 with 1 to 7 beijng the range of inputs
1504
1505def validate_an_input(**kwargs):
1506 ####validate_an_inpput####
1507 # Parameters :- **kwargs:dictionary #
1508 # Return Type :- Input:string/integer/float #
1509 # Purpose:- This function validates all of the inputs. Until an input meets #
1510 # a certain criteria the program keeps asking for a new input. **kwargs is used as #
1511 # it allows for a varying amount of paramters making the function more flexible. #
1512 #########################
1513 identifier = kwargs["Identifier"]
1514 Input = kwargs["Input"]
1515 Statement = kwargs["Statement"]
1516 valid = False
1517 while valid != True:
1518 if identifier == "A": # Range of Numbers / Letters
1519 letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
1520 "T", "U", "V", "W", "X", "Y", "Z"]
1521 Range = kwargs["Range"]
1522 if ((Range[0].isdecimal() and Range[1].isdecimal()) == True) or (
1523 isinstance(Range[0], int) and isinstance(Range[1], int) == True):
1524 if Input in [str(i + 1) for i in range(int(Range[1]))]:
1525 valid = True
1526 elif (Range[0].isalpha() and Range[1].isalpha()) == True: #
1527 Input = str(Input.upper())
1528 index1 = letters.index(Range[0])
1529 index2 = letters.index(Range[1])
1530 if Input in letters[index1:index2 + 1]:
1531 valid = True
1532
1533 elif identifier == "B": # Days
1534 try:
1535 year, month, day = Input.split("-")
1536 datetime.datetime(int(year), int(month), int(day))
1537 valid = True
1538 except ValueError:
1539 pass
1540
1541 elif identifier == "C": # Names?
1542 Input = string.capwords(Input)
1543 if all(x.isalpha() or x.isspace() for x in Input) is True and Input != "":
1544 valid = True
1545
1546 elif identifier == "D": # Postcode
1547 try:
1548 match = re.findall(
1549 r"([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\s?[0-9][A-Za-z]{2})",
1550 Input)
1551 if Input in match[0]:
1552 valid = True
1553 except:
1554 pass
1555
1556 elif identifier == "E": # Phone Numbers
1557 if all(character.isnumeric() for character in Input) is True and Input != "" and len(Input) >= 10:
1558 valid = True
1559
1560 elif identifier == "F": # Positive numbers
1561 if Input.isnumeric() == True and Input != "0":
1562 if int(Input) > 0:
1563 valid = True
1564
1565 elif identifier == "G": # Positive Nummbers inc 0
1566 if Input.isnumeric() == True:
1567 if int(Input) >= 0:
1568 valid = True
1569
1570 elif identifier == "H": # Float
1571 try:
1572 Input = float(Input)
1573 except TypeError:
1574 pass
1575 if isinstance(Input, float) == True or isinstance(Input, float) == True:
1576 valid = True
1577
1578 if valid != True:
1579 print("- - " * 40)
1580 print("Please enter a valid option.")
1581 print(Statement)
1582 Input = input("> ")
1583
1584 print("- - " * 40)
1585 return Input