def listWizzard(argsString): args = getArgsBy(argsString, ',|=') if args == [''] or not args: try: bookings = getBookings({}) except sqlite3.Error as e: print("Sqlite error occured: {}".format(e)) elif len(args) % 2 != 0: # If args length is an uneven length then there is a argument without a pair # value and will mean the sql statement will get messed up print("Odd number of arguments supplied") print("Each argument must have a value eg. \n") print("lb key=value or") print("lb key=value,key2=value2\n") print("There can be no lone keys or values") else: # Check the arguments are valid then put them into a dictionary to be passed # to getBookings() searchableArgs = getArgsBy(getConfPart('listBy','bookings').strip(),',') argsDict = makeArgsDict(args,searchableArgs) try: bookings = getBookings(argsDict) except sqlite3.Error as e: print("Sqlite error occured: {}".format(e)) print(tabulate(bookings, headers=['Booking id','Customer id','Time','Reason'], tablefmt="fancy_grid")) outputs.decideWhatToDo()
def list(argsString): # Get args args = getArgsBy(argsString,',|=') if args == [''] or not args: try: customers = getCustomers({}) except sqlite3.Error as e: print("Sqlite error occured: {}".format(e)) else: searchableArgs = getArgsBy(getConfPart('listBy','customers').strip(),',') # Declare base statement then add to it if more args found argsDict = {} for i in range(0,len(args),2): if args[i] in searchableArgs: argsDict[args[i]] = args[i+1] else: print("Invalid argument: {}".format(args[i])) outputs.decideWhatToDo() try: customers = getCustomers(argsDict) except sqlite3.Error as e: print("Sqlite error occured: {}".format(e)) print(tabulate(customers, headers=['customerId','name','address','telephone'], tablefmt="fancy_grid")) # Return to start outputs.decideWhatToDo()
def wizzard(): name = input("What is their name: ") address = input("What is their address: ") telephone = input("What is their phone number: ") makeCustomer(name,address,telephone) outputs.decideWhatToDo()
def removeWizzard(argsString): if argsString == "" or not argsString: print("No arguments provided") outputs.decideWhatToDo() args = getArgsBy(argsString,',|=') print(args) if len(args) % 2 != 0: print("Insuficient arguments providied, odd number") outputs.decideWhatToDo() searchableArgs=getArgsBy(getConfPart('removeBy','customers').strip(),',') try: #Remove LIMIT from argsDict argsDict = makeArgsDict(args,searchableArgs) for i in range(0,len(args),2): if args[i].lower() == "limit": limit = int(args[i+1]) print(limit) #Limit is in argsDict so remove it argsDict.pop('limit',0) else: limit = 1 except ValueError as e: print("Value error: {}".format(e)) outputs.decideWhatToDo() try: remove(argsDict,limit) except ValueError as e: print("Value error: {}".format(e)) except TypeError as e: print("Type error: {}".format(e)) except LookupError as e: print("Lookup error: {}".format(e)) outputs.decideWhatToDo()
def removeWizzard(argsString): if argsString == '' or not argsString: print("No arguments provided") outputs.decideWhatToDo() args = getArgsBy(argsString,',|=') if len(args) % 2 != 0: print("Insufficient arguments provided, odd number") outputs.decideWhatToDo() searchableArgs=getArgsBy(getConfPart('removeBy','bookings').strip(),',') #makeArgsDict includes LIMIT as an argument so that needs to be removed #so it can be used properly argsDict = makeArgsDict(args,searchableArgs) for i in range(0,len(args),2): if args[i].lower() == "limit": limit = int(args[i+1]) #limit is would be in argsDict so remove it argsDict.pop('limit',0) else: limit = 1 try: if remove(argsDict,limit): print("Succesfully removed booking") except ValueError as e: print("Value error: {}".format(e)) except TypeError as e: print("Type error: {}".format(e)) except LookupError as e: print("Lookup error: {}".format(e)) outputs.decideWhatToDo()
def listAvailable(argsString): # If args is blank then assume that today was wanted args = getArgsBy(argsString,',|=| ') conn = dbConnection.connect() openTimes = getArgsBy(getConfPart('openTimes'),',') bookingLength = getConfPart('bookingLength') try: #Sets both variable to be equal to the original dateTime openTime, absOpenTime = (datetime.strptime(openTimes[0],'%H:%M'),)*2 closeTime, absCloseTime = (datetime.strptime(openTimes[1],'%H:%M'),)*2 #If 'today' is supplied as an argument then change it to be equal to the actual date if 'today' in args: args = [arg.replace('today',datetime.today().strftime('%d/%m/%Y')) for arg in args] if args == ['']: date = datetime.today() elif len(args) == 1: #Use date from args, ValueError will be made if invalid date is used date = datetime.strptime(args[0],'%d/%m/%Y').date() elif len(args) == 2: #Just 'times' supplied, so use that and todays date date = datetime.today() if args[0] == 'times': openTime = datetime.strptime(getArgsBy(args[1],'-')[0],'%H:%M') closeTime = datetime.strptime(getArgsBy(args[1],'-')[1],'%H:%M') else: print("Invalid argument '{}' supplied, was expecting times".format(args[0])) outputs.decideWhatToDo() elif len(args) == 3: #Use date from args and get and use time args if args[1] == 'times': # In form `lba 1/1/1970 times=0:00-5:00` date = datetime.strptime(args[0],'%d/%m/%Y').date() openTime = datetime.strptime(getArgsBy(args[2],'-')[0],'%H:%M') closeTime = datetime.strptime(getArgsBy(args[2],'-')[1],'%H:%M') elif args[0] == 'times': # In form `lba times=0:00-5:00 1/1/1970` date = datetime.strptime(args[2],'%d/%m/%Y').date() openTime = datetime.strptime(getArgsBy(args[1],'-')[0],'%H:%M') closeTime = datetime.strptime(getArgsBy(args[1],'-')[1],'%H:%M') else: print("Expected times argument, none given") outputs.decideWhatToDo() else: #If nothing usable was supplied then give an error print("Invalid arguments supplied") outputs.decideWhatToDo() except ValueError as e: print("Error getting date: {}".format(e)) outputs.decideWhatToDo() print(date.strftime('%Y-%m-%d')) #timeStampBook is to be queried by LIKE hence the [0] as it's the first elem in the dict bookings = getBookings({'timeStampBook':str(date.strftime('%Y-%m-%d'))+'%'},[0]) bookingTimes = [] for i in range(0,len(bookings)): #Remove date and append to booking times bookingTimes.append(bookings[i-1][2][11:]) curTime = openTime if openTime <= absOpenTime: curTime = absOpenTime if closeTime >= absCloseTime: closeTime = absCloseTime while curTime <= closeTime: #Loop through bookings, increment 1 bookingLength at a time #If it matches a booking then don't add that time to the list if str(curTime.time()) not in bookingTimes: print("Aavailable: {}".format(curTime.time())) curTime = curTime + timedelta(minutes=int(bookingLength)) outputs.decideWhatToDo()
def wizzard(name=None, address=None): nameInput = input("Customer name: ") if name != None and nameInput == "": print("Using name '{}' from previous add booking".format(name)) print("And any address from previous add booking") elif nameInput != "": name = nameInput address = None else: print("No name provided") wizzard(name, address) # Use address here as it may be from a previous run of # the function where the user may have put in an invalid date for example try: customerId = helpers.getCustomerId(name, address) except LookupError as e: print("Lookup error: {}".format(e)) outputs.decideWhatToDo() except sqlite3.Error as e: print("Sqlite error: {}".format(e)) outputs.decideWhatToDo() except Exception as e: print("An unexpected error occured: {}".format(e)) outputs.decideWhatToDo() if len(customerId) > 1: # Get address input as well, as name is not unique addressInput = input("Customer address: ") if address != None: print("Using address {} from previous add booking".format(address)) elif addressInput != "": address = addressInput else: print("No address provided") wizzard(name, address) try: customerId = helpers.getCustomerId(name, address) except LookupError as e: print("Lookup error: {}".format(e)) outputs.decideWahtToDo() except sqlite3.Error as e: print("Sqlite error: {}".format(e)) outputs.decideWhatToDo() except Exception as e: print("An unexpected error occured: {}".format(e)) outputs.decideWhatToDo() date = input("What day would you like to book (dd/mm/yyyy): ") try: bookingDate = datetime.strptime(date, "%d/%m/%Y") except ValueError: print("Invalid date") # Keep the same name and address values, # If input is blank then these values will be checked for wizzard(name, address) time = input("When would you like to book: ") try: bookingTime = datetime.strptime(time, "%H:%M").time() except ValueError: print("Invalid time") wizzard(name, address) # Concatenate date and time for easier storage timeDate = datetime.combine(bookingDate, bookingTime) # Check if a booking at the same time has already been made if listBookings.getBookings({"timeStampBook": timeDate}) != []: print("A booking already exists at this time") doubleBookVerif = input("Would you like to double book this time?(y/n)") if doubleBookVerif.lower() != "y": wizzard(name, address) reason = input("Booking reason: ") makeBooking(customerId[0][0], timeDate, reason) # Go back to start outputs.decideWhatToDo()
def remove(argsDict,limit=1,confirm=True): #Deletes bookings matching parameters given, if the amount of bookings matching the #parameters exceedes the limit then a ValueError will be thrown #Also by defualt a confirm message will come up i = 0 whereClause = "" valsList = [] #First check generate a where clause that can be used across both the select and #remove statements for key,value in argsDict.items(): if i >=1: whereClause += "AND " + key + "=? " else: whereClause += key + "=? " valsList.append(value) i += 1 #Append limit +1 to check if too many results are returned valsList.append(str(limit+1)) conn = dbConnection.connect() statement = "SELECT customerId FROM customers WHERE " + whereClause + " LIMIT ?" print(statement) #print(valsList) try: cursor = conn.execute( statement, valsList ) customerIds = cursor.fetchall() print(customerIds) #outputs.decideWhatToDo() if len(customerIds) > limit: raise LookupError("More customers found than specified limit") elif len(customerIds) == 0: raise LookupError("No customers found") else: confirmDelete=None #Loop through all the bookings returned and as it's a nested tuple list #it's in the form customerIds[i][0] for i in range(0,len(customerIds)): # By defualt this will happen as confirm defualts to True # However in the future this may not be desired and so can # be set to remove without customer detail confrimation if confirm: try: #Loop through customerInfo = getCustomerInfoFromId(customerIds[i][0]) except ValueError as e: print("Value error: {}".format(e)) outputs.decideWhatToDo() except LookupError as e: print("Lookup error: {}".format(e)) outputs.decideWhatToDo() except Exception as e: print("Unexpected error: {}".format(e)) outputs.decideWhatToDo() print("Delete customer {}, address {}".format(customerInfo[0],customerInfo[1])) confirmDelete = input("(y/n): ") if confirmDelete.lower() == "y" or (confirm==False and confirmDelete==None): print(customerIds[i][0]) whereClause = "customerId=?" statement = "DELETE FROM customers WHERE " + whereClause print(statement) conn.execute( statement, (str(customerIds[i][0]),) ) conn.commit() else: print("Booking not deleted") return 1 except sqlite3.Error as e: raise sqlite3.Error(e)