def printPilotsByLicence(self): #fetch employee info employeePackage = IOAPI().opener(self.dataFiles['CREW_FILE']) #get all the pilots in one list pilotPackage = [] for employee in employeePackage: if employee['role'] == "Pilot": pilotPackage.append(employee) #fetch plane info planePackage = IOAPI().opener(self.dataFiles['AIRCRAFT_FILE']) #gets a list of unique plane types from the planePackage planetypeList = [] for plane in planePackage: if plane['planeTypeId'] not in planetypeList: planetypeList.append(plane['planeTypeId']) planetypeList.sort() #goes through all the plane types and finds all the pilots with a licence for that plane type #and compiles them in a list pilotPlaneList = [] for planeType in planetypeList: for pilot in pilotPackage: if pilot[ 'licence'] == planeType and pilot not in pilotPlaneList: pilotPlaneList.append(pilot) #returns relevant info return self.printData(pilotPlaneList, header="Pilots sorted by licence:")
def licenceByCount(self): #fetch employee info employeePackage = IOAPI().opener(self.dataFiles['CREW_FILE']) #get all the pilots in one list pilotPackage = [] for employee in employeePackage: if employee['role'] == "Pilot": pilotPackage.append(employee) #fetch plane info planePackage = IOAPI().opener(self.dataFiles['AIRCRAFT_FILE']) #gets a list of unique plane types from the planePackage planetypeList = [] for plane in planePackage: if plane['planeTypeId'] not in planetypeList: planetypeList.append(plane['planeTypeId']) planetypeList.sort() #list comprehension to make a list of dicts with the planetype and the count as the dict licenceCountList = [{ "planeTypeId": planetype, "count": 0 } for planetype in planetypeList] #count how many licences of each planetype the pilots have for combo in licenceCountList: for pilot in pilotPackage: if pilot['licence'] == combo["planeTypeId"]: combo["count"] += 1 #need to change it to string cause otherwise Displayscreen will Error for combo in licenceCountList: combo['count'] = str(combo['count']) return self.printData(licenceCountList, header="Licences by count:")
def createDestination(self): """Create destination. Get destinationLand, destinationAirport, destinationFlightTime, destinationDistance, destinationContactPerson and destinationEmergencyPhone.""" print("\nCreating new destination") destination_dict = {} self.destination = InputHandler().country( "Input the city where the new destination is located: ") # Airports # Get a list of dictionaties containing airports and destiations we currently fly to airport_data_list = IOAPI().opener(self.dataFiles["DESTINATIONS_FILE"]) #Creates a list of airports NaN Air flyes to airport_list = [] for a_line_dict in airport_data_list: airport_list.append(a_line_dict["id"]) self.airport = InputHandler().airport( airport_list, "\nInput the ID (3 letters) of the new airport: ") self.flightTime = InputHandler().timeOnly( "\nInput the time it takes to fly to {} from Iceland (HH:MM): ". format(self.airport)) self.distanceFromIceland = InputHandler().distance( "\nInput the distace from Iceland to {} (in km): ".format( self.airport)) self.contactPerson = InputHandler().fullName( "\nInput the full name of the contact person for the new destination, {}: " .format(self.airport)) self.emergencyPhone = InputHandler().phoneNumber( "\nInput the emergency phone number (7 digits) for the new destination, {}: " .format(self.airport)) destination_dict["id"] = self.airport destination_dict["destination"] = self.destination destination_dict["flightDuration"] = self.flightTime destination_dict["distance"] = self.distanceFromIceland destination_dict["contactPerson"] = self.contactPerson destination_dict["emergencyPhone"] = self.emergencyPhone #Displays the input information and check if the user is happy with the info DisplayScreen().printList( [destination_dict], header="Creating new destination, check if info correct", frame=True) confirmation_bool = InputHandler().yesOrNoConfirmation( "Is this information correct (y/n)? ") if confirmation_bool: IOAPI().appender(self.dataFiles["DESTINATIONS_FILE"], destination_dict)
def getVoyages(self): #fetch voyage info #fetch voyage info voyagePackage = IOAPI().opener(self.dataFiles["UPCOMING_FLIGHTS_FILE"]) #fetch plane info planePackage = IOAPI().opener(self.dataFiles["AIRCRAFT_FILE"]) list_to_print = [] for voyage in voyagePackage: planeId = voyage["aircraftID"] temp_dict = voyage for plane in planePackage: if plane["planeInsignia"] == planeId: temp_dict["capacity"] = plane["capacity"] list_to_print.append(temp_dict) return self.printData(list_to_print, header="Voyages:")
def getWorking(self): #fetch employee info employeePackage = IOAPI().opener(self.dataFiles['CREW_FILE']) #fetch Voyage info voyagePackage = IOAPI().opener(self.dataFiles["UPCOMING_FLIGHTS_FILE"]) #fetch destination info destinationPackage = IOAPI().opener( self.dataFiles['DESTINATIONS_FILE']) #ask for datetime from user user_input = InputHandler().dateOnly() user_date = DateUtil(user_input).date combo_list = [] #goes through all flights, finds flights of the chosen date and compiles a list of tuples with the SSN and 3 letter arrival for line in voyagePackage: departure = DateUtil(line['departure']).date if user_date == departure: if line['captain'] != "" and line['captain'] not in combo_list: combo_list.append((line['captain'], line["arrivingAt"])) if line['copilot'] != "" and line['copilot'] not in combo_list: combo_list.append((line['copilot'], line["arrivingAt"])) if line['fsm'] != "" and line['fsm'] not in combo_list: combo_list.append((line['fsm'], line["arrivingAt"])) if line['fa1'] != "" and line['fa1'] not in combo_list: combo_list.append((line['fa1'], line["arrivingAt"])) if line['fa2'] != "" and line['fa2'] not in combo_list: combo_list.append((line['fa2'], line["arrivingAt"])) if len(combo_list) == 0: self.printData([], "No employee is working on the specified day") return False working_list = [] #finds the employees who were on the flights and finds the destination name based on the 3 letter arrival for employee in employeePackage: for x in combo_list: if x[0] == employee['ssn']: #puts all the info together in one dict and adds to the list temp_dict = employee dest_dict = next( (item for item in destinationPackage if item["id"] == x[1]), None) if dest_dict: temp_dict["destination"] = dest_dict["destination"] working_list.append(temp_dict) else: break return self.printData( working_list, header="employees working and their destination:")
def getSingleEmployee(self): #fetches employee info filePackage = IOAPI().opener(self.dataFiles['CREW_FILE']) #asks for the SSN of the employee ssn_of_employee_str = InputHandler().ssn( "Enter the SSN of the employee you\'re looking for: ") #Validity check for SSN while ssn_of_employee_str == False: print("Invalid input") ssn_of_employee_str = InputHandler().ssn( "Enter the SSN of the employee you\'re looking for: ") #Check for if the SSN is in crew file ssn_in_file_bool = True list_to_print = [] while ssn_in_file_bool: #goes through all the lines in the employee info for x in filePackage: #checks the SSN of the employee if x['ssn'] == ssn_of_employee_str: list_to_print = [x] if list_to_print != []: ssn_in_file_bool = False else: print("No employee found with this SSN") ssn_of_employee_str = InputHandler().ssn( "Enter the SSN of the employee you\'re looking for: ") return DisplayScreen().printList(list_to_print, "Chosen employee:")
def flightData(direction: str): """Creates a data dictionary""" startLocation = self.__departingFrom endLocation = self.__destination["id"] departure = self.__departure duration = self.__destination["flightDuration"] flightDict = {} flightNumber = self.createFlightNumber(self.latestFlight) # swap locations depending on direction of flight if direction == "in": startLocation, endLocation = endLocation, startLocation departure = self.__return flightDict["flightNumber"] = flightNumber flightDict["departingFrom"] = startLocation flightDict["arrivingAt"] = endLocation flightDict["departure"] = departure flightDict["arrival"] = self.calculateArrival( departure, duration) #departure + flightTime flightDict["aircraftID"] = self.__aircraftID flightDict["captain"] = self.__captain flightDict["copilot"] = self.__copilot flightDict["fsm"] = self.__fsm flightDict["fa1"] = self.__fa1 flightDict["fa2"] = self.__fa2 #update the latest flightnumber self.latestFlight = flightNumber IOAPI().appender(self.dataFiles["UPCOMING_FLIGHTS_FILE"], flightDict.copy()) return flightDict.copy()
def getWeekWork(self): #fetch employee info employeePackage = IOAPI().opener(self.dataFiles['CREW_FILE']) #fetch Voyage info voyagePackage = IOAPI().opener(self.dataFiles["UPCOMING_FLIGHTS_FILE"]) #ask for SSN user_ssn = InputHandler().ssn( "Please input the SSN of the Employee you want a schedule of: ") for employee in employeePackage: if user_ssn == employee['ssn']: ssn_exists = True if ssn_exists: pass else: print("An employee with that SSN does not exist") return False #ask for datetime from user refDate_str = InputHandler().dateOnly("Input starting date of week: ") refDate_obj = DateUtil(refDate_str).createObject() #collect the days of a week checkWeek_list = [] checkWeek_list.append(refDate_str) #@ts-ignore for day in range(7): refDate_obj = refDate_obj + datetime.timedelta(days=1) checkWeek_list.append(refDate_obj.isoformat()) schedule_list = [] #find all the flights that are in the range of the week and check those flights for the employee ssn and add the flight to the schedule if so for flight in voyagePackage: departure = DateUtil(flight['departure']).date for date in checkWeek_list: if date[:10] == departure: if user_ssn == flight['captain'] or user_ssn == flight[ 'copilot'] or user_ssn == flight[ 'fsm'] or user_ssn == flight[ 'fa1'] or user_ssn == flight['fa2']: schedule_list.append(flight) return self.printData(schedule_list, header="Chosen employee work schedule:")
def createFlights(self): """Creates a pair of flights that make up the voyage, requires the last flightNumber created (for reference when creating new flightNumbers)""" # get the latest flightNumber created, for reference allFlights_list = IOAPI().opener( self.dataFiles["UPCOMING_FLIGHTS_FILE"]) self.latestFlight = allFlights_list[len(allFlights_list) - 1]["flightNumber"] def flightData(direction: str): """Creates a data dictionary""" startLocation = self.__departingFrom endLocation = self.__destination["id"] departure = self.__departure duration = self.__destination["flightDuration"] flightDict = {} flightNumber = self.createFlightNumber(self.latestFlight) # swap locations depending on direction of flight if direction == "in": startLocation, endLocation = endLocation, startLocation departure = self.__return flightDict["flightNumber"] = flightNumber flightDict["departingFrom"] = startLocation flightDict["arrivingAt"] = endLocation flightDict["departure"] = departure flightDict["arrival"] = self.calculateArrival( departure, duration) #departure + flightTime flightDict["aircraftID"] = self.__aircraftID flightDict["captain"] = self.__captain flightDict["copilot"] = self.__copilot flightDict["fsm"] = self.__fsm flightDict["fa1"] = self.__fa1 flightDict["fa2"] = self.__fa2 #update the latest flightnumber self.latestFlight = flightNumber IOAPI().appender(self.dataFiles["UPCOMING_FLIGHTS_FILE"], flightDict.copy()) return flightDict.copy() #create the flight out flightOut_dict = flightData("out") self.__flightOut = [flightOut_dict["flightNumber"], flightOut_dict] #create the flight in flightIn_dict = flightData("in") self.__flightIn = [flightIn_dict["flightNumber"], flightIn_dict] #give the IOAPI the flight data to save return [flightOut_dict, flightIn_dict]
def updateFlights(allFlights, updatedFlights, voyageData): """Sends the updated list to the updater""" departingIndex = voyageData["out"][0] returningIndex = voyageData["in"][0] #update departing allFlights[departingIndex] = updatedFlights[0] allFlights[returningIndex] = updatedFlights[1] #update returning IOAPI().updater(self.dataFiles["UPCOMING_FLIGHTS_FILE"], allFlights)
def getAway(self, date: str = "", noPrint: bool = False): #fetch employee info employeePackage = IOAPI().opener(self.dataFiles['CREW_FILE']) #fetch Voyage info voyagePackage = IOAPI().opener(self.dataFiles["UPCOMING_FLIGHTS_FILE"]) #if no date is given in arguments, then ask for input if date == "": #ask for datetime from user user_input = InputHandler().dateOnly() else: user_input = date user_date = DateUtil(user_input).date ssn_list = [] #goes through all flights, finds flights at the chosen date and compiles a unique list of SSN for line in voyagePackage: departure = DateUtil(line['departure']).date if user_date == departure: if line['captain'] != "" and line['captain'] not in ssn_list: ssn_list.append(line['captain']) if line['copilot'] != "" and line['copilot'] not in ssn_list: ssn_list.append(line['copilot']) if line['fsm'] != "" and line['fsm'] not in ssn_list: ssn_list.append(line['fsm']) if line['fa1'] != "" and line['fa1'] not in ssn_list: ssn_list.append(line['fa1']) if line['fa2'] != "" and line['fa2'] not in ssn_list: ssn_list.append(line['fa2']) #everybody who isn't working is everyone who isn't in the ssn_list away_list = [] for employee in employeePackage: if employee['ssn'] not in ssn_list: away_list.append(employee) if noPrint != True: self.printData(away_list, header="Employees not working:") return away_list
def getDayVoyages(self): #fetch Voyage info voyagePackage = IOAPI().opener(self.dataFiles["UPCOMING_FLIGHTS_FILE"]) #ask for datetime from user user_input = InputHandler().dateOnly() user_date = DateUtil(user_input).date schedule_list = [] #goes through all flights, finds flights of the chosen date and compiles a list of tuples with the SSN and 3 letter arrival for line in voyagePackage: departure = DateUtil(line['departure']).date if user_date == departure: schedule_list.append(line) return self.printData(schedule_list, header="Voyages of chosen day:")
def getFlightAttendants(self, data: list = []): #fetches employee info if len(data) == 0: filePackage = IOAPI().opener(self.dataFiles['CREW_FILE']) else: filePackage = data #goes through all the lines in the employee info list_to_print = [] for x in filePackage: #checks the SSN of the employee if x['role'] == "Cabincrew": list_to_print.append(x) self.printData(list_to_print, header="All Flight Attendants:") return list_to_print
def createPlane(self): """Method that creates new plane, requests input for planeName, and planeType. Adds the plane to the registry""" plane_dict = {} #Takes in input for plane insignia and puts it under "planeInsignia" key in plane_dict plane_dict["planeInsignia"] = InputHandler().planeInsignia( "Input plane insignia (e.g. TF-XXX): ") #Creates a list of airplane types in the list airplane_data_list = IOAPI().opener( self.dataFiles["AIRCRAFT_TYPE_FILE"]) airplaneType_list = [] for a_line_dict in airplane_data_list: airplaneType_list.append(a_line_dict["planeTypeId"]) #Turns the list into a list of dictionaries plane_list = [] for x in airplaneType_list: planeType_dict = {} planeType_dict["Plane Type IDs: "] = x plane_list.append(planeType_dict) DisplayScreen().printOptions(plane_list, header="") #Input for plane Type ID plane_dict["planeTypeId"] = InputHandler().multipleNumChoices( plane_list, "Choose Plane Type ID: ") plane_dict["manufacturer"] = InputHandler().strNoCheck( "Input plane manufacturer: ") plane_dict["capacity"] = InputHandler().digit( "Input plane seating capacity: ") #Input confirmation DisplayScreen().printList([plane_dict], header="") confirmation_bool = InputHandler().yesOrNoConfirmation( "Is this information correct? (y/n)") if confirmation_bool: #Appending the input info to aircraft file IOAPI().appender(self.dataFiles["AIRCRAFT_FILE"], plane_dict)
def selectDepartureTime(self, questionDate: str, questionTime: str, errorMessage: str): """Prompts the user to input date and time""" #ERROR Check if there is any departing from Iceland at this dateTime departingFlights_list = IOAPI().opener( self.dataFiles["UPCOMING_FLIGHTS_FILE"]) departingOnDate_list = [] selectedDate = InputHandler().dateOnly(questionDate) # just collect the flights departing on same day for flight in departingFlights_list: if flight['departingFrom'] == self.__departingFrom: if flight['departure'][:10] == selectedDate[:10]: departingOnDate_list.append(flight) # print the list of flights departing on that day headerDepartingOnDate_str = "List of other flights departing on same day" if len(departingOnDate_list) == 0: DisplayScreen().printText(["No departing flights"], headerDepartingOnDate_str) else: DisplayScreen().printList(departingOnDate_list, headerDepartingOnDate_str) #ask the user for a time before entering the loop selectedDepartureTime_str = InputHandler().timeOnly(questionTime) while True: #check through list of flights and check their departure time if len(departingOnDate_list) != 0: for flight in departingOnDate_list: flightDeparture = flight['departure'] timeCheckDate = DateUtil().updateTime( selectedDate, selectedDepartureTime_str) #if airport was occupied, then print the list again and ask for time input if flightDeparture == timeCheckDate: DisplayScreen().printList( departingOnDate_list, "Departure time not available, please try again") selectedDepartureTime_str = InputHandler().timeOnly( "Please select a different time, " + questionTime) continue else: #if everything is alright, then return the dateTime return timeCheckDate else: return DateUtil().updateTime(selectedDate, selectedDepartureTime_str)
def getPilotsByLicence(self): #fetch employee info employeePackage = IOAPI().opener(self.dataFiles['CREW_FILE']) #get all the pilots in one list pilotPackage = [] for employee in employeePackage: if employee['role'] == "Pilot": pilotPackage.append(employee) #show the planes to user #License #Gets a list of dictionaries containing aircraft type specifications airplane_data_list = IOAPI().opener( self.dataFiles["AIRCRAFT_TYPE_FILE"]) #Creates a list of airplane types in the list airplaneType_list = [] for a_line_dict in airplane_data_list: airplaneType_list.append(a_line_dict["planeTypeId"]) user_input = InputHandler().license("Pilot", airplaneType_list, "Choose license: ") #set a flag to false here and then go through and try to find all pilots with the licence the user asked for #if no such pilots are found then the flag is never set to true anyone_found_flag = False licence_pilots = [] for pilot in pilotPackage: if pilot['licence'] == user_input: anyone_found_flag = True licence_pilots.append(pilot) #if anyone is found it returns the relevant info if anyone_found_flag: return self.printData(licence_pilots, header="Pilots with chosen licence:") #else it alerts the user and returns false else: self.printData([], header="No pilots were found with that licence") return False
def selectAircraft(self): """Displays list of available aircrafts and selects one from input""" #Get and print list of available aircrafts aircrafts_list = IOAPI().opener(self.dataFiles["AIRCRAFT_FILE"]) #needs to check if plane is actually available at selected timeframe available_planes = aircrafts_list # print the available aircrafts DisplayScreen().printOptions(available_planes, "planes") # Select a aircraft from list inputAircraft_str = "Enter the number of the plane you want to use in this voyage from the plane list: " selectedAircraft = InputHandler().numChoices(len(available_planes), inputAircraft_str) self.__aircraftID = available_planes[int(selectedAircraft) - 1]["planeInsignia"]
def getWeekVoyages(self): #fetch Voyage info voyagePackage = IOAPI().opener(self.dataFiles["UPCOMING_FLIGHTS_FILE"]) #ask for datetime from user refDate_str = InputHandler().dateOnly("Input starting date of week: ") refDate_obj = DateUtil(refDate_str).createObject() #collect the days of a week checkWeek_list = [] checkWeek_list.append(refDate_str) #@ts-ignore for day in range(7): refDate_obj = refDate_obj + datetime.timedelta(days=1) checkWeek_list.append(refDate_obj.isoformat()) schedule_list = [] #find all the flights that are in the range of the week for flight in voyagePackage: departure = DateUtil(flight['departure']).date for date in checkWeek_list: if date[:10] == departure: schedule_list.append(flight) return self.printData(schedule_list, header="Voyages of chosen week:")
def createEmployee(self): """Assigns and holds onto the values given by input handler until all information is fullfilled. Asks for confirmation. Turns the information into dict format and returns it #Should also write it into data""" employee_dict = {} #Personal information name_str = InputHandler().fullName("Input full name: ") ssn_str = InputHandler().ssn("Input SSN: ") address_str = InputHandler().address("Input address: ") phonenumber_str = InputHandler().phoneNumber( "Input a 7-digit phone number:") email_str = InputHandler().email("Input e-mail address: ") #Role role_str = InputHandler().role("Choose role: ") #Rank rank_str = InputHandler().rank(role_str, "Choose rank: ") #License #Gets a list of dictionaries containing aircraft type specifications airplane_data_list = IOAPI().opener( self.dataFiles["AIRCRAFT_TYPE_FILE"]) #Creates a list of airplane types in the list airplaneType_list = [] for a_line_dict in airplane_data_list: airplaneType_list.append(a_line_dict["planeTypeId"]) #Gets input for license if relevant, sets to "N/A" if role = Cabin Crew license_str = InputHandler().license(role_str, airplaneType_list, "Choose license: ") #Turns the inputs into a dict employee_dict["ssn"] = ssn_str employee_dict["name"] = name_str employee_dict["role"] = role_str employee_dict["rank"] = rank_str employee_dict["licence"] = license_str employee_dict["address"] = address_str employee_dict["phonenumber"] = phonenumber_str employee_dict["email"] = email_str #Displays the input information DisplayScreen().printList([employee_dict], header="Employee info: ") #Asks for confirmation. If negative starts the editing process if InputHandler().yesOrNoConfirmation( "Is this information correct? (y/n): "): edit_bool = False else: edit_bool = True #Runs editing as long as the user confirmation is negative while edit_bool: #Creates a list of editing options options_list = [{ "Edit choices:": "SSN" }, { "Edit choices:": "Name" }, { "Edit choices:": "Role" }, { "Edit choices:": "Rank" }, { "Edit choices:": "Licence" }, { "Edit choices:": "Address" }, { "Edit choices:": "Phone" }, { "Edit choices:": "Email" }] #Prints the beforementioned list of options DisplayScreen().printOptions(options_list, header="") #Asks user to choose what he wants to edit choice_str = InputHandler().multipleNumChoices( options_list, "Choose data to edit: ") if choice_str == "SSN": employee_dict[choice_str.lower()] = InputHandler().ssn( "Input SSN: ") elif choice_str == "Name": employee_dict[choice_str.lower()] = InputHandler().fullName( "Input full name: ") elif choice_str == "Address": employee_dict[choice_str.lower()] = InputHandler().address( "Input address: ") elif choice_str == "Phone": employee_dict["phonenumber"] = InputHandler().phoneNumber( "Input a 7-digit phone number: ") elif choice_str == "Email": employee_dict[choice_str.lower()] = InputHandler().email( "Input e-mail address: ") elif choice_str == "Role": employee_dict["role"], employee_dict["rank"], employee_dict[ "licence"] = InputHandler().roleUpdate(airplaneType_list) elif choice_str == "Rank": employee_dict[choice_str.lower()] = InputHandler().rank( employee_dict["role"], "Choose rank: ") elif choice_str == "Licence": employee_dict[choice_str.lower()] = InputHandler().license( employee_dict["role"], airplaneType_list, "Input licence: ") #Prints the results of editing and asks for confirmation DisplayScreen().printList([employee_dict], header="Employee info: ", frame=True) if InputHandler().yesOrNoConfirmation( "Is this information correct? (y/n): "): edit_bool = False #Adds the employee to the crew file IOAPI().appender(self.dataFiles["CREW_FILE"], employee_dict) #Sorts the crew file alphabetically by name crewPackage = IOAPI().opener(self.dataFiles["CREW_FILE"]) crewPackage = sorted(crewPackage, key=lambda i: i["name"]) IOAPI().updater(self.dataFiles["CREW_FILE"], crewPackage)
def updateVoyage(self): """ Updates the crew on a voyage """ departingFlights_data = IOAPI().opener( self.dataFiles["UPCOMING_FLIGHTS_FILE"]) allEmployees_data = IOAPI().opener(self.dataFiles["CREW_FILE"]) def findVoyage(flightData: list): """Find the voyage""" #get the list departingFlights_list = [] for flight in departingFlights_data: if flight['departingFrom'] == 'KEF': departingFlights_list.append(flight) #give user option to choose how the list is sorted: sortOptions = [{ "sortBy": "departure" }, { "sortBy": "arrivingAt" }, { "sortBy": "flightNumber" }] DisplayScreen().printOptions(sortOptions, header="Search for voyages from list") sortedChoice_int = int(InputHandler().numChoices( len(sortOptions), "How would you like the voyages to be sorted? :")) sortedBy_str = sortOptions[sortedChoice_int - 1]["sortBy"] #sort the list by departure time sortedDepartures_list = sorted(departingFlights_list, key=lambda i: i[sortedBy_str]) #print the upcoming voyages DisplayScreen().printOptions(sortedDepartures_list) # ask user to select a flight from the list representing the voyage selectedFlight_int = int(InputHandler().numChoices( len(sortedDepartures_list), "Select a voyage from the list: ")) selectedFlight_dict = sortedDepartures_list[selectedFlight_int - 1] # find the two connecting flights, by finding the index of selected flight flightIndex = departingFlights_data.index(selectedFlight_dict) return { "out": [flightIndex, departingFlights_data[flightIndex]], "in": [flightIndex + 1, departingFlights_data[flightIndex + 1]] } # Find the currently listed crew and roles (for printOptions) def selectRoleForUpdate(flightPair: list): currentVoyage = Voyage(flightPair) rolesForUpdate_list = [] for role, employee in currentVoyage.addCrew().items(): #find the employee info, should find name crewInRole = {"role": role, "employee": employee} rolesForUpdate_list.append(crewInRole.copy()) DisplayScreen().printOptions(rolesForUpdate_list, "Crew assigned to this voyage") selectedRole = InputHandler().numChoices( len(rolesForUpdate_list), "Select a role to update: ") return rolesForUpdate_list[int(selectedRole) - 1]["role"] #======================== def assignCrew(availableCrew_list: list, selectedRole_str: str, flightPair: list): """Finds the crew to """ currentVoyage = Voyage(flightPair) currentCrew = currentVoyage.addCrew() #get the available employees for current voyage roleList = { "captain": { "rank": "Captain" }, "copilot": { "rank": "Copilot" }, "fsm": { "rank": "Flight Service Manager" }, "fa1": { "rank": "Flight Attendant" }, "fa2": { "rank": "Flight Attendant" }, } # filter out only of right rank rankOnlyList = [] for employee in availableCrew_list: if employee["rank"] == roleList[selectedRole_str]["rank"]: rankOnlyList.append(employee) #ask what employee they wish to assign to role if len(availableCrew_list) != 0: DisplayScreen().printOptions(rankOnlyList) inputChoice = InputHandler().numChoices( len(rankOnlyList), "Select an employee: ") selectedEmployee = rankOnlyList[int(inputChoice) - 1] currentCrew[selectedRole_str] = selectedEmployee["ssn"] else: DisplayScreen().printText( ["No available crew for this role during this voyage"], "Finding {} for voyage".format( roleList[selectedRole_str]["rank"])) return flightPair #update the voyage info currentVoyage.addCrew(currentCrew) #get the flights with updated info newFlights = currentVoyage.getFlights() return newFlights #======================== #find the days that the crew would be occupied during voyage def findDaysDuration(departureFlight, arrivalFlight): """Finds the days that the voyage will cover""" departureDate = departureFlight["departure"] returnDate = arrivalFlight["arrival"] departureDate_obj = DateUtil(departureDate).createObject() returnDate_obj = departureDate_obj + datetime.timedelta(days=1) compiledDates_list = [departureDate, returnDate_obj.isoformat()] return compiledDates_list # Find available employees def findAvailableCrew(daysOfWoyage, employeeList): """Just loops through the given days to return available staff""" availableCrew = [] availablePerDay = [] availableForVoyage = [] #make list of all employees availeble on these days for date in daysOfVoyage: availablePerDay.append( self.getLogic.getAway(date, noPrint=True)) #make a list of all employees that appear on these lists for day in availablePerDay: for employee in day: if employee not in availableCrew: availableCrew.append(employee) # #check if employee is available all days of voyage # for employee in availableCrew: # freeForAll = [] # for day in availablePerDay: # if employee in day: # freeForAll.append(True) # else: # freeForAll.append(False) # if all(freeForAll) = True: # availableForVoyage.append(employee) # check if they are free for the duration return availableCrew def updateFlights(allFlights, updatedFlights, voyageData): """Sends the updated list to the updater""" departingIndex = voyageData["out"][0] returningIndex = voyageData["in"][0] #update departing allFlights[departingIndex] = updatedFlights[0] allFlights[returningIndex] = updatedFlights[1] #update returning IOAPI().updater(self.dataFiles["UPCOMING_FLIGHTS_FILE"], allFlights) #voyage data, keeping index for later references voyageData = findVoyage(departingFlights_data) #get the flight data voyageFlightPair = [voyageData["out"][1], voyageData["in"][1]] # create instance of VoyageHandler using the two connected flights daysOfVoyage = findDaysDuration(voyageFlightPair[0], voyageFlightPair[1]) #find list of employees available for work availableCrew_list = findAvailableCrew(daysOfVoyage, allEmployees_data) #get the role to update selectedRole = selectRoleForUpdate(voyageFlightPair) #get the updated flights after assigning a role newFlights = assignCrew(availableCrew_list, selectedRole, voyageFlightPair) # then find the flights that were updated and replace them updateFlights(departingFlights_data, newFlights, voyageData)
def getDestinations(self): #fetches destination info filePackage = IOAPI().opener(self.dataFiles['DESTINATIONS_FILE']) return self.printData(filePackage, header="Destinations:")
def getPlanes(self): #fetches aircraft info filePackage = IOAPI().opener(self.dataFiles['AIRCRAFT_FILE']) return self.printData(filePackage, header="Planes:")
def getAllCrew(self): #fetches employee info filePackage = IOAPI().opener(self.dataFiles['CREW_FILE']) return self.printData(filePackage, header="All crew:")
def updateEmployee(self): """choose a employee (get a list and choose from the list). Get the info about the chosen employee and then choose what info you want to change. Then the user will be asked if he wants to save the changes. Save the new information about the employee to the list about all employees """ #Show list GetLogic(self.dataFiles).getAllCrew() #Choose Employee #Show employee info #Ask what the m**********r wants to change for f***s sake #Change some shit or f**k off #Confirm whether the f****r is co ntent with the f*****g changes #f**k the f**k off #Show employee info filePackage = IOAPI().opener(self.dataFiles["CREW_FILE"]) #asks for the SSN of the employee ssn_of_employee_str = InputHandler().ssn( "Enter the SSN of the employee you\'re looking for: ") #Sets it to True so that the while runs at least once employee_in_file_bool = True employee_info_list = [] #goes through all the lines in the employee info while employee_in_file_bool: for x in filePackage: #checks the SSN of the employee if x['ssn'] == ssn_of_employee_str: employee_index = filePackage.index(x) employee_info_dict = x employee_info_list = [x] if employee_info_list != []: employee_in_file_bool = False else: print("Employee not found!") ssn_of_employee_str = InputHandler().ssn( "Enter the SSN of the employee you\'re looking for: ") DisplayScreen().printList(employee_info_list, "Chosen employee:", frame=True) #Creates a list of editing options options_list = [{ "Edit choices:": "Role" }, { "Edit choices:": "Rank" }, { "Edit choices:": "License" }, { "Edit choices:": "Address" }, { "Edit choices:": "Phone" }, { "Edit choices:": "Email" }] #Prints the beforementioned list of options DisplayScreen().printOptions(options_list, header="") #Asks user to choose what he wants to edit choice_str = InputHandler().multipleNumChoices( options_list, "Choose data to update: ") #Creates a list of airplane types airplane_data_list = IOAPI().opener( self.dataFiles["AIRCRAFT_TYPE_FILE"]) airplaneType_list = [] for a_line_dict in airplane_data_list: airplaneType_list.append(a_line_dict["planeTypeId"]) #Changes the requested data if choice_str == "Address": employee_info_dict[choice_str.lower()] = InputHandler().address( "Input address: ") elif choice_str == "Phone": employee_info_dict["phonenumber"] = InputHandler().phoneNumber( "Input a 7-digit phone number: ") elif choice_str == "Email": employee_info_dict[choice_str.lower()] = InputHandler().email( "Input e-mail address: ") elif choice_str == "Role": employee_info_dict["role"], employee_info_dict[ "rank"], employee_info_dict["licence"] = InputHandler( ).roleUpdate(airplaneType_list) elif choice_str == "Rank": employee_info_dict[choice_str.lower()] = InputHandler().rank( employee_info_dict["role"], "Choose rank: ") elif choice_str == "Licence": employee_info_dict[choice_str.lower()] = InputHandler().license( employee_info_dict["role"], airplaneType_list, "Input licence: ") #Prints the data and asks for confirmation DisplayScreen().printList([employee_info_dict], header="") continue_bool = InputHandler().yesOrNoConfirmation( "Do you want to change anything else? (y/n): ") while continue_bool: #Prints out editing options DisplayScreen().printOptions(options_list, header="") #Asks to choose what the user wants to edit choice_str = InputHandler().multipleNumChoices( options_list, "Choose data to update: ") #Changes the requested data if choice_str == "Address": employee_info_dict[choice_str.lower()] = InputHandler( ).address("Input address: ") elif choice_str == "Phone": employee_info_dict["phonenumber"] = InputHandler().phoneNumber( "Input a 7-digit phone number: ") elif choice_str == "Email": employee_info_dict[choice_str.lower()] = InputHandler().email( "Input e-mail address: ") elif choice_str == "Role": employee_info_dict["role"], employee_info_dict[ "rank"], employee_info_dict["licence"] = InputHandler( ).roleUpdate(airplaneType_list) elif choice_str == "Rank": employee_info_dict[choice_str.lower()] = InputHandler().rank( employee_info_dict["role"], "Choose rank: ") elif choice_str == "Licence": employee_info_dict[ choice_str.lower()] = InputHandler().license( employee_info_dict["role"], airplaneType_list, "Input licence: ") #Prints the results of editing and asks for confirmation DisplayScreen().printList([employee_info_dict], header="") continue_bool = InputHandler().yesOrNoConfirmation( "Do you want to change anything else? (y/n): ") else: if InputHandler().yesOrNoConfirmation( "Do you want to save the changes? (y/n): "): #Updates the Crew file with the edited employee info filePackage[employee_index] = employee_info_dict IOAPI().updater(self.dataFiles["CREW_FILE"], filePackage) print("Data has been updated")
def createVoyage(self): '''Create a new voyage, voyage contains of two flights with different flight numbers. have to get destination that we already fly to, date that the voyage will occur and than when the flight back home to Iceland is ''' # Get and print list of available destinations destination_list = IOAPI().opener(self.dataFiles["DESTINATIONS_FILE"]) DisplayScreen().printOptions(destination_list, "destinations") # Seect a destination destination_str = InputHandler().numChoices( len(destination_list), "Select index of destination for this voyage: ") self.__destination = destination_list[int(destination_str) - 1] # Departure messages for inputHandler inputDepartureDate_str = "Enter departure date from Iceland to {} (DD/MM/YYYY): ".format( self.__destination["destination"]) inputDepartureTime_str = "Enter departure time (HH:MM): " ErrorDepartureTime_str = "ERROR: Airport is occupied at selected time \nplease input a new departure time: " # get the departure time from inputHandler self.__departure = self.selectDepartureTime(inputDepartureDate_str, inputDepartureTime_str, ErrorDepartureTime_str) # Find a date and time for arrival departingDate_obj = DateUtil(self.__departure).createObject() flightDuration = self.__destination["flightDuration"].split(":") durationHours = flightDuration[0] durationMinutes = flightDuration[1] minReturnDate_obj = departingDate_obj + datetime.timedelta( hours=int(durationHours), minutes=int(durationMinutes)) minReturnDate_util = DateUtil(minReturnDate_obj.isoformat()) inputArrivalDate_str = "Enter return date to Iceland from {} (DD/MM/YYYY): ".format( self.__destination["destination"]) inputArrivalTime_str = "Enter time for return (HH:MM): " while True: try: returnDate_str = InputHandler().dateTime( inputArrivalDate_str, inputArrivalTime_str) returnDate_obj = DateUtil(returnDate_str).createObject() #return date/time needs to be greater than departure date/time if returnDate_obj > departingDate_obj: #return needs to be at least departure + flightduration if returnDate_obj >= minReturnDate_obj: self.__return = returnDate_str break raise Exception else: raise Exception except Exception: returnDate_str = "{}/{}/{}".format(minReturnDate_util.day, minReturnDate_util.month, minReturnDate_util.year) errorMessage_list = [ "Return needs to be at least {}h and {}m after departure". format(durationHours, durationMinutes), "That would be at least {} and {}".format( returnDate_str, minReturnDate_util.time) ] DisplayScreen().printText( errorMessage_list, "Choose a date and time for return flight from {}".format( self.__destination["destination"])) # Find available aircraft self.selectAircraft() # print all the info about the voyage for the user and ask if the info is correct, if not than edit info, else save to data # Make a flightnumber for both flights, the flight numbers are different depending on the destination and how many other flights have gone to the destination on this same day self.createFlights()
def updateDestination(self): """The user chooses a destination (get a list of all the destinations and then choose the airport id fromt the list). Get the info about the chosen destination and then choose what info the user wnat to change. Then the user will be asked if he wants to save the changes. Save the new info about the destination to the list of all destinations. (if the user does not want to save then the old info about the destination will be kept in the list of all destinations)""" #get and show the user the list of all destinations GetLogic(self.dataFiles).getDestinations() #choose a destination the user wants to change #GetLogic(self.dataFiles).getOneDestination() #fetches destinations info filePackage = IOAPI().opener(self.dataFiles['DESTINATIONS_FILE']) #Creates a list of airports NaN Air flyes to airport_list = [] for a_line_dict in filePackage: airport_list.append(a_line_dict["id"]) #asks for the ID of the destination id_of_destination_str = InputHandler().destinationID( airport_list, "Enter the ID of the airport you want to change: ") #Set id_in_file_bool to True so that the while runs at least once id_in_file_bool = True airport_info_list = [] #goes through all the lines in the destination info while id_in_file_bool: for x in filePackage: #checks the ID of the destinations airport_index = filePackage.index(x) if x["id"] == id_of_destination_str: airport_info_dict = x airport_info_list = [x] if airport_info_list != []: id_in_file_bool = False else: print("Airport not found!") id_of_destination_str = InputHandler().destinationID( airport_list, "Enter the ID of the airport you want to change: ") DisplayScreen().printList(airport_info_list, "Chosen airport: ", frame=True) #creates a list of editing optins options_list = [{ "Edit choices:": "Contact Person" }, { "Edit choices:": "Emergency number" }] #Prints the before mentioned list of options DisplayScreen().printOptions(options_list, header="") #Asks the user to choose what he/she wants to edit choice_str = InputHandler().multipleNumChoices( options_list, "Choose data you want to update: ") #Changes the requested data if choice_str == "Contact Person": airport_info_dict["contactPerson"] = InputHandler().fullName( "Enter the name of the new contact person: ") elif choice_str == "Emergency number": airport_info_dict["emergencyPhone"] = InputHandler().phoneNumber( "Input a 7 digit phone number for the new emergency phone number: " ) #Prints the data and asks for confirmation DisplayScreen().printList([airport_info_dict], header="") continue_bool = InputHandler().yesOrNoConfirmation( "Do you want to change anything else? (y/n): ") while continue_bool: #Prints out editing options again DisplayScreen().printOptions(options_list, header="") #Asks the user to choose what he/she wants to edit choice_str = InputHandler().multipleNumChoices( options_list, "Choose data you want to update: ") #Changes the requested data if choice_str == "Contact Person": airport_info_dict["contactPerson"] = InputHandler.fullName( "Enter the name of the new contact person: ") elif choice_str == "Emergency number": airport_info_dict["emergencyPhone"] = InputHandler.phoneNumber( "Input a 7 digit phone number for the new emergency phone number: " ) #Prints the results of editing and asks for confirmation DisplayScreen().printList([airport_info_dict], header="") continue_bool = InputHandler().yesOrNoConfirmation( "Do you want to change anything else? (y/n): ") else: #Updates the Destination file with the edited destion info filePackage[airport_index] = airport_info_dict IOAPI().updater(self.dataFiles["DESTINATIONS_FILE"], filePackage) print("Data has been updated")