def test_park_single_car(self): #prepare park = Park(3) expectedPark = [Car('xxx', 'red'), None, None] #execute park.addCar(Car('xxx', 'red')) #assert self.equalPark(park.park, expectedPark)
def action4(): print("-" * 80) print("New Car:") licence_Plate = input('Enter The Licence Plate: ') licence_Plate = licence_Plate.upper() while len( licence_Plate ) != 5: # if the licence plate is invalid, the user is asked to try again print('Invalid Input, Try Again!') licence_Plate = input('Enter The Licence Plate: ') licence_Plate = licence_Plate.upper() category_inp = input( 'Enter The Category (M = Mini Car, S = Station Car, J = Jeep): ' ).lower() category = self.__CarService.check_Category(category_inp) manufacturer = input('Enter The Manufacturer: ') the_Type = input('Enter The Type: ') transmission_inp = input( 'Enter The Transmission (S = Stick Shift, M = Manual): ' ).lower() transmission = self.__CarService.check_Transmission( transmission_inp) price_inp = input('Enter Price: ') price = self.__CarService.check_Price(price_inp) new_Car = Car(licence_Plate, category, manufacturer, the_Type, transmission, price) self.__CarService.add_car(new_Car) print('\nCar Added!')
def test_find_slot_number_with_colour_not_found(self): #prepare park = Park(5) park.park = [ Car('xxx', 'red'), Car('yyy', 'blue'), Car('zzz', 'green'), Car('aaa', 'blue'), Car('bbb', 'red') ] expectedSlotNumbers = [] #execute regNumbers = park.findSlotNumberWithColor('white') #assert self.assertListEqual(regNumbers, expectedSlotNumbers)
def test_find_slot_number_with_reg_number(self): #prepare park = Park(5) park.park = [ Car('xxx', 'red'), Car('yyy', 'blue'), Car('zzz', 'green'), Car('aaa', 'blue'), Car('bbb', 'red') ] expectedSlotNumbers = ['2'] #execute regNumbers = park.findSlotNumberWithRegNumber('yyy') #assert self.assertListEqual(regNumbers, expectedSlotNumbers)
def test_find_reg_number_with_colour_multi(self): #prepare park = Park(5) park.park = [ Car('xxx', 'red'), Car('yyy', 'blue'), Car('zzz', 'green'), Car('aaa', 'blue'), Car('bbb', 'red') ] expectedRegNumbers = ['xxx', 'bbb'] #execute regNumbers = park.findRegNumberWithColor('red') #assert self.assertListEqual(regNumbers, expectedRegNumbers)
def generate_repairing_event(): time = datetime.datetime(year=ri(2000, 2018), month=ri(1, 12), day=ri(1, 28), hour=ri(0, 23), minute=ri(0, 59), second=ri(0, 59)) RepairingEvent.create( time=time, customer=Customer.get_by_id(ri(1, Customer.select().count())), workshop=Workshop.get_by_id(ri(1, Workshop.select().count())), car=Car.get_by_id(ri(1, Car.select().count())), part=Part.get_by_id(ri(1, Part.select().count())), price=ri(100, 10000))
def get(self): Utils.reset(self) # reset/clean standard variables # validate and assign parameters passwd = Utils.required(self, 'passwd') version = config.data_version['building'] if self.request.get('version'): version = self.request.get('version') lang = config.server["defaultLanguage"] if self.request.get('lang'): lang = self.request.get('lang') uuid = Utils.required(self, 'uuid') guid = self.request.get('guid') # check password if self.error == '' and passwd != config.testing['passwd']: self.error = 'passwd is incorrect.' start_time = time.time() # start count # logical variables player = None mycars = None # if error, skip this if self.error == '': player = Player.getplayer(self, uuid) if self.error == '' and player is not None and guid != '': if guid != player.state_obj['guid']: player = None self.error = config.error_message['dup_login'] if self.error == '' and player is not None: mycars = Car.list(self, uuid) self.respn = '[' for _car in mycars: self.respn += Car.compose_mycar('', _car) + ',' self.respn = self.respn.rstrip(',') + ']' # calculate time taken and return the result time_taken = time.time() - start_time self.response.headers['Content-Type'] = 'text/html' self.response.write(Utils.RESTreturn(self, time_taken))
def make_car(self, prompt): ''' Þetta fall býr til bíl með grunn uppl. síðan sendir það í car_change_info fallið að breyta uppl. um hverjn hlut sem þarf að vita um bílin síðan spyr fallið hvort allt í rétt slegið inn, ef ekki sendir fallið notanda í fallið change_car_info, þar sem notandi getur breytt viðeigandi uppl.''' new_car = Car() for step in range(1,6): quit_info = new_car.car_change_info(str(step), self._all_cars_list, prompt) if type(quit_info) == str: return quit_info new_car.set_availability(self.get_date_dict()) print_header(prompt) print(new_car) print("="*70) continue_q = input("\nEr allt rétt? (j/n): ").lower() if continue_q != "j": self.change_car_info(new_car, True, prompt) else: self.car_register(new_car) return new_car
def generate_charging_event(): # time = datetime.datetime(year=ri(2000, 2018), month=ri(1, 12), day=ri(1, 28), hour=ri(0, 23), minute=ri(0, 59), # second=ri(0, 59)) time = datetime.datetime(year=2018, month=5, day=ri(1, 10), hour=ri(0, 23), minute=ri(0, 59), second=ri(0, 59)) ChargingEvent.create(time=time, car=Car.get_by_id(ri(1, Car.select().count())), customer=Customer.get_by_id( ri(1, Customer.select().count())), charging_station=ChargingStation.get_by_id( ri(1, ChargingStation.select().count())), price=ri(100, 10000))
def addCar(): name = request.args.get('name') engine = request.args.get('engine') gas_type = request.args.get('gas_type') response = "" if name and engine and gas_type: new_car = Car(name=name, engine=engine, gas_type=gas_type) db.session.add(new_car) db.session.commit() response = make_response("Added!") else: response = make_response("Error while adding!") return response
def generate_car(): i = ri(0, 10) colour = [ "red", "white", "blue", "green", "yellow", "black", "brown", "orange", "pink", "gray" ] mark = [ "Tesla", "HipsterCar", "Lambargingi", "LADA", "BMW", "Audi", "Mersedes", "YoYoMobil", "SashaGrayCar", "ElectroZaporozhec" ] plate = '' plate += chr(ord('A') + ri(0, 25)) plate += chr(ord('A') + ri(0, 25)) for i in range(4): plate += chr(ord('0') + ri(0, 9)) name = mark[ri(0, len(mark) - 1)] + "Special electic edition " + str(i) power = ri(50, 500) color = colour[ri(0, len(colour) - 1)] location = [str(i) + "room" for i in range(100, 131)] loc = location[ri(0, 30)] Car.create(location=loc, name=name, power=power, color=color, plate=plate)
def generate_trip_event(): pickup_time = datetime.datetime(year=ri(2015, 2018), month=ri(1, 12), day=ri(1, 28), hour=ri(0, 23), minute=ri(0, 59), second=ri(0, 59)) end_time = (pickup_time + datetime.timedelta(hours=int(ri(1, 1000)))) location = [str(i) + " street" for i in range(100, 131)] pickup_location = location[ri(0, 30)] destination_location = location[ri(0, 30)] distance_to_user = ri(0, 30000) trip_duration = ri(0, 2400) TripEvent.create(pickup_location=pickup_location, pickup_time=pickup_time, end_time=end_time, destination_location=destination_location, car=Car.get_by_id(ri(1, Car.select().count())), distance_to_user=distance_to_user, trip_duration=trip_duration, customer=Customer.get_by_id( ri(1, Customer.select().count())))
def test_leave_single_car(self): #prepare park = Park(5) park.park = [ Car('xxx', 'red'), Car('yyy', 'blue'), Car('zzz', 'green'), Car('aaa', 'blue'), Car('bbb', 'red') ] expectedPark = [ Car('xxx', 'red'), None, Car('zzz', 'green'), Car('aaa', 'blue'), Car('bbb', 'red') ] #execute park.leaveCar(2) #assert self.equalPark(park.park, expectedPark)
def populate_car_list(self): """ Opens the database (csv) file and reads its contents. If the file doesn't exist it is created with the columns of the file. """ try: with open("./data/cars.csv", "r") as cars_db: csv_dict = csv.DictReader(cars_db) for line in csv_dict: new_car = Car(line["reg_num"], line["brand"], line["model"], line["category"], line["category_price"], line["registration_date"], line["mileage"]) self.__cars.append(new_car) except FileNotFoundError: with open("./data/cars.csv", "w") as cars_db: cars_db.write( "reg_num,brand,model,category,category_price,registration_date,mileage" )
def test_park_and_leave(self): #prepare park = Park(5) expectedPark = [ Car('bbb', 'red'), Car('yyy', 'blue'), None, Car('aaa', 'blue'), None ] #execute park.addCar(Car('xxx', 'red')) park.addCar(Car('yyy', 'blue')) park.addCar(Car('zzz', 'green')) park.addCar(Car('aaa', 'blue')) park.leaveCar(1) park.leaveCar(3) park.addCar(Car('bbb', 'red')) #assert self.equalPark(park.park, expectedPark)
def test_park_full(self): #prepare park = Park(3) expectedPark = [ Car('xxx', 'red'), Car('yyy', 'blue'), Car('zzz', 'green') ] #execute park.addCar(Car('xxx', 'red')) park.addCar(Car('yyy', 'blue')) park.addCar(Car('zzz', 'green')) park.addCar(Car('aaa', 'red')) #assert self.equalPark(park.park, expectedPark)
def get_data_information(data): cars = {} for car in data['cars']: cars[car['id']] = Car(car['id'], car['price_per_day'], car['price_per_km']) options = {} for option in data['options']: if option['rental_id'] in options: options[option['rental_id']].add(option['type']) else: options[option['rental_id']] = {option['type']} rentals = [] for rental in data['rentals']: rentals.append( Rental(rental['id'], rental['car_id'], rental['distance'], rental['start_date'], rental['end_date'], options.get(rental['id'], set()))) return cars, options, rentals
def test_park_multi_car(self): #prepare park = Park(5) expectedPark = [ Car('xxx', 'red'), Car('yyy', 'blue'), Car('zzz', 'green'), None, None ] #execute park.addCar(Car('xxx', 'red')) park.addCar(Car('yyy', 'blue')) park.addCar(Car('zzz', 'green')) #assert self.equalPark(park.park, expectedPark)
def remove_car(self, car): """Tekur við bíl og eyðit honum úr viðeigandi skrá.""" self.__cars.remove(car) self.update_car_list(Car())
def get(self): Utils.reset(self) # reset/clean standard variables # validate and assign parameters passwd = Utils.required(self, 'passwd') version = config.data_version['building'] if self.request.get('version'): version = self.request.get('version') lang = config.server["defaultLanguage"] if self.request.get('lang'): lang = self.request.get('lang') uuid = Utils.required(self, 'uuid') guid = self.request.get('guid') cuid = Utils.required(self, 'cuid') upid = Utils.required(self, 'upid') # check password if self.error == '' and passwd != config.testing['passwd']: self.error = 'passwd is incorrect.' start_time = time.time() # start count # logical variables player = None upgrades = None upgrade = None mycar = None qualify = False # if error, skip this if self.error == '': player = Player.getplayer(self, uuid) if self.error == '' and player is not None and guid != '': if guid != player.state_obj['guid']: player = None self.error = config.error_message['dup_login'] if self.error == '' and player is not None: mycar = Car.get(self, cuid) if self.error == '' and mycar is not None: upgrades = Data.getupgrades(self, lang, version) if self.error == '' and upgrades is not None: found = False for _type in upgrades.as_obj: for _upgrade in upgrades.as_obj[_type]: if _upgrade['id'] == upid: upgrade = _upgrade found = True break if found is False: self.error = 'Upgrade id=' + upid + ' was not found.' if self.error == '' and upgrade is not None: # validate existing upgrade already_have = False for _upgrade in mycar.data_obj['upgrades']: if _upgrade == upid: already_have = True # validate building buildings = Building.list(self, player.uuid) for building in buildings: if building.itid == upgrade[ 'shop'] and building.level >= upgrade['shop_level']: qualify = True break if qualify is False: self.respn = '{"warning":' + GCWarnings.building_not_owned + '}' if self.error == '' and qualify is True: # validate cash if already_have is False: # then you need to buy it, dude! if player.state_obj['cash'] >= upgrade['cost']: player.state_obj['cash'] -= upgrade['cost'] player.state_obj['updated'] = start_time if Player.setplayer(self, player): mycar.data_obj['upgrades'].append(upgrade['id']) else: self.respn = '{"warning":"not enough cash!"}' qualify = False if self.error == '' and qualify is True: mycar.data_obj['equip'][upgrade['type']] = upgrade['id'] if Car.update(self, mycar): self.respn = '{"state":' + player.state + ',' self.respn += '"car":[' self.respn += Car.compose_mycar('', mycar) + ',' self.respn = self.respn.rstrip(',') + ']' self.respn += '}' # calculate time taken and return the result time_taken = time.time() - start_time self.response.headers['Content-Type'] = 'text/html' self.response.write(Utils.RESTreturn(self, time_taken))
def get(self): Utils.reset(self) # reset/clean standard variables # validate and assign parameters passwd = Utils.required(self, 'passwd') uuid = Utils.required(self, 'uuid') guid = self.request.get('guid') # check password if self.error == '' and passwd != config.testing['passwd']: self.error = 'passwd is incorrect.' start_time = time.time() # start count # if error, skip this if self.error == '': # query player state for given uuid players = Player.all().filter('uuid =', uuid).ancestor( db.Key.from_path('Player', config.db['playerdb_name'])).fetch(1) didDelete = False # we have not delete anything yet for player in players: # we might have duplicate data, just delete them all # query scores for this player and delete them all scores = Score.all().filter('uuid =', player.uuid).ancestor( db.Key.from_path('Score', config.db['scoredb_name'])) for score in scores: score.delete() # query items for this player and delete them all items = Item.all().filter('uuid =', player.uuid).ancestor( db.Key.from_path('Item', config.db['itemdb_name'])) for item in items: item.delete() # query records for this player and delete them all records = Record.all().filter('uuid =', player.uuid).ancestor( db.Key.from_path('Record', config.db['recorddb_name'])) for record in records: record.delete() # query buildings for this player and delete them all buildings = Building.all().filter( 'uuid =', player.uuid).ancestor( db.Key.from_path('Building', config.db['buildingdb_name'])) for building in buildings: building.delete() cars = Car.all().filter('uuid =', player.uuid).ancestor( db.Key.from_path('Car', config.db['cardb_name'])) for car in cars: car.delete() # delete all this user's challenge Challenge.DeleteByUserId(self, player.uuid) # and finally, delete this player player.delete() didDelete = True # compose result if didDelete == True: self.respn = '"' + uuid + ' was deleted successfully."' else: self.error = uuid + ' does not exist in Database.' # calculate time taken and return the result time_taken = time.time() - start_time self.response.headers['Content-Type'] = 'text/html' self.response.write(Utils.RESTreturn(self, time_taken))
def parkCar(self, regNumber, colour): i = self.park.addCar(Car(regNumber, colour)) if (i == -1): output.parkedFail() else: output.parkedSuccessful(i)
def get(self): Utils.reset(self) # reset/clean standard variables # validate and assign parameters passwd = Utils.required(self, 'passwd') uuid = self.request.get('uuid') guid = self.request.get('guid') fbid = self.request.get('fbid') self.game = self.request.get('game') or '' version = config.data_version['building'] token = self.request.get('token') or '' lang = self.request.get('lang') or config.server["defaultLanguage"] name = self.request.get('name') or '' image = 'Textures/profile-pic.png' if fbid != '': image = 'https://graph.facebook.com/' + fbid + '/picture?width=200&height=200' # TODO : Get defaults from Data gold = 10 cash = 50000 total_wins = 0 total_races = 0 advice_checklist = '' player = None # defaultitems = None if self.error == '' and passwd != config.testing[ 'passwd']: # if password is incorrect self.error = 'passwd is incorrect.' # inform user via error message start_time = time.time() # start count Utils.LogRequest(self) # if error, skip this if self.error == '': if fbid != '': player = Player.getplayerByFbid(self, fbid) if player is None and uuid != '': player = Player.getplayer(self, uuid) # get player from Player model # class helper, specified by uuid # TODO : Only get defaultItems if needed, ie a new player defaultitems = Data.getDataAsObj( self, 'defaultitems', config.data_version['defaultitems']) if defaultitems is not None: if player is None: # if no player data # returned or doesn't exist ################################################################################################ ## Create new player data player = Player(parent=db.Key.from_path( 'Player', config.db['playerdb_name']) ) # create a new player state data uuid = Utils.genanyid(self, 'u') #if fbid == '': # fbid = uuid player.uuid = uuid # assign uuid player.fbid = fbid # and assign all player info and state player.info_obj = { 'uuid': player.uuid, 'fbid': player.fbid, 'token': token, 'name': 'Guest ' + str(random.randint(1000, 9999)), 'image': image, 'lang': lang } player.state_obj = { 'guid': guid, 'cash': cash, 'gold': gold, 'current_car': 'xxx', 'total_wins': total_wins, 'total_races': total_races, 'advice_checklist': advice_checklist, 'updated': start_time } logging.debug("New Player Created") ################################################################################################# ## Init default item for new player buildings = Data.getbuildings(self, lang, float(version)) cars = Data.getcars(self, lang, float(version)) upgrades = Data.getupgrades(self, lang, float(version)) if buildings is not None and cars is not None and upgrades is not None: logging.debug("building default stuff") for item in defaultitems.obj: if item['type'] == 'state': player.state_obj[item['id']] = item['value'] elif item['type'] == 'building': try: building = buildings.as_obj[item['id']][0] if building is not None: new_building = Building.newbuilding( self) new_building.uuid = player.uuid new_building.itid = item['id'] new_building.inid = Utils.genanyid( self, 'b') new_building.level = building['level'] new_building.status = Building.BuildingStatus.DELIVERED new_building.location = item['value'] new_building.amount = 0 new_building.timestamp = int( start_time) Building.setmybuilding( self, new_building) except KeyError: logging.warning('KeyError, key not found!') elif item['type'] == 'car' and cars is not None: type = '' car = None for _car in cars.as_obj: if _car['id'] == item['id']: car = _car break mycar = Car.create(self, player.uuid) mycar.data_obj['info'] = {'crid': car['id']} mycar.data_obj['upgrades'] = [] mycar.data_obj['equip'] = {} player.state_obj['current_car'] = mycar.cuid default_upgrades = car[ 'default_upgrades'].replace(' ', '').split(',') for default_upgrade in default_upgrades: mycar.data_obj['upgrades'].append( default_upgrade) for _type in upgrades.as_obj: try: mycar.data_obj['equip'][type] except KeyError: for upgrade in upgrades.as_obj[ _type]: if upgrade[ 'id'] == default_upgrade: mycar.data_obj['equip'][ _type] = default_upgrade break break Car.update(self, mycar) else: logging.warning("cant build default stuff") else: # but if player does exist ##################################################################################################################### ## Found existing user uuid = player.uuid if token: # if token is provided from # apple player.state_obj[ 'token'] = token # assign token to player state if fbid != '': player.fbid = fbid player.info_obj['fbid'] = fbid player.info_obj['image'] = image # assign image url if name != '': player.info_obj['name'] = name # assign name try: updated = player.state_obj['updated'] except KeyError: player.state_obj['updated'] = start_time if self.request.get('lang'): player.info_obj['lang'] = lang # Additional things that have been added and neeed checking for old players # TODO : Remove try catch, or see performance impact in Python try: if guid: player.state_obj['guid'] = guid except KeyError: player.state_obj['guid'] = '' # try .. cash and assign new property try: cash = player.state_obj['cash'] except KeyError: player.state_obj['cash'] = cash try: total_wins = player.state_obj['total_wins'] except KeyError: player.state_obj['total_wins'] = total_wins try: advice_checklist = player.state_obj['advice_checklist'] except KeyError: player.state_obj['advice_checklist'] = advice_checklist if Player.setplayer(self, player): # then obviously, no error # compose JSON for frontend response type = '' for item in config.playerdata: type += item + ',' type = type.rstrip(',') self.respn = '{"uuid":"' + uuid + '",' types = type.split(',') for item in types: if item == 'info': self.respn += '"info":' + player.info + ',' elif item == 'state': self.respn += '"state":' + player.state + ',' elif item == 'building': buildings = Data.getbuildings(self, lang, version) mybuildings = Building.getmybuildings(self, uuid) if buildings is not None and mybuildings is not None: self.respn += '"building":[' # loop through my buildings to find out which need their pending status updating for new_building in mybuildings: # update building status, determine production _upd = False if new_building.status == Building.BuildingStatus.PENDING: if new_building.timestamp + ( buildings.as_obj[ new_building.itid][ new_building.level - 1] ['build_time'] * 60) <= start_time: new_building.timestamp = int( start_time) new_building.status = Building.BuildingStatus.DELIVERED _upd = True elif new_building.status == Building.BuildingStatus.DELIVERED: new_building.status = Building.BuildingStatus.OWNED _upd = True if _upd is True: Building.setmybuilding( self, new_building) self.respn = Building.compose_mybuilding( self.respn, new_building) self.respn = self.respn.rstrip(',') + '],' elif item == 'car': mycars = Car.list(self, player.uuid) self.respn += '"car":[' for _car in mycars: self.respn += Car.compose_mycar('', _car) + ',' self.respn = self.respn.rstrip(',') + '],' elif item == 'challenge': Challenge.ComposeChallenges(self, player) self.respn = self.respn.rstrip(',') + '}' ################################################################################################### ## Add to recent player list recentplayerlist = Data.GetRecentPlayerList(self) _add = True # check if this user hasn't reached the maximum set challengers # we don't add players to the recent list if they are stacked num = 0 challengers = Challenge.GetChallengers( self, player.info_obj['uuid']) if challengers is None: Challenge.GetChallengers(self, player.info_obj['fbid']) if challengers is not None: for challenger in challengers: obj = json.loads(challenger.data) if obj['friend'] is False: num += 1 if num > config.recentplayer['maxchallengers']: logging.warn( 'Recent player list exceeded for ' + uuid) _add = False break # find if it already exists? num = 0 _deletelist = [] for recentplayer in recentplayerlist.obj: if recentplayer['uuid'] == player.info_obj['uuid']: if _add is False: # this player reach the maximum of challengers _deletelist.append( num ) # we should delete him from the list, so nobody can challenge him else: _add = False # if the list is longer than maxlist, delete the rest if num >= config.recentplayer['maxlist']: _deletelist.append(num) # remove if player does not exist any more else: someplayer = Player.getplayer( self, recentplayer['uuid']) if someplayer is None: self.error = '' _deletelist.append(num) num += 1 num = len(_deletelist) for i in range(0, num): del recentplayerlist.obj[num - 1 - i] if _add is True: recentplayerlist.obj.append({ 'fbid': player.info_obj['fbid'], 'name': player.info_obj['name'], 'uuid': player.info_obj['uuid'], 'image': player.info_obj['image'], 'total_wins': player.state_obj['total_wins'], 'updated': player.state_obj['updated'] }) Data.SetRecentPlayerList(self, recentplayerlist) else: # but if write down to database was failed self.error = 'unable to insert/update player data.' # inform user bia error message logging.warn('unable to insert/update player data.') # calculate time taken and return the result time_taken = time.time() - start_time self.response.headers['Content-Type'] = 'text/html' self.response.write(Utils.RESTreturn(self, time_taken))
def reset(self): self.car = Car()
import json from collections import OrderedDict from models.Car import Car from models.Rental import Rental from models.Commission import calculate_commissions with open('data/input.json') as json_file: data = json.load(json_file) cars = {} rentals = [] for car in data['cars']: cars[car['id']] = Car(car['id'], car['price_per_day'], car['price_per_km']) for rental in data['rentals']: rentals.append( Rental(rental['id'], rental['car_id'], rental['distance'], rental['start_date'], rental['end_date'])) rentals_data = [] for rental in rentals: price = rental.calculate_price(cars[rental.car_id].price_per_day, cars[rental.car_id].price_per_km) commission = calculate_commissions(price, rental.duration) rentals_data.append({ 'id': rental.id, 'price': price, 'commission': commission }) output_data = {'rentals': rentals_data}
def main_menu(self): if self.access != "user" and self.access != "admin": self.access = login() action = "" while (action != "q"): os.system("cls") print(9 * "-", " Main Menu ", 9 * "-") print(" You can do the following:\n") print(indent, "1 | Cars") print(indent, "2 | Orders") print(indent, "3 | Customers") print(indent, "q | Quit") print() action = input(" Input number/letter: ").lower() if action == "1": # Goes to Cars menu os.system("cls") print(10 * "-", " Cars Menu ", 10 * "-") print(" You can do the following:\n") print(indent, "1 | See Available cars") print(indent, "2 | See Unavailable cars") print(indent, "3 | See List of all cars") print(indent, "4 | See Details of a car") print(indent, "5 | See Prices") if self.access == "admin": print(indent, "6 | Register new car") print(indent, "7 | Change price list") action = self.print_options() #action = input(" Input number/letter: ").lower() if action == "1": # See available cars os.system("cls") action = "" self.__car_service.available_cars() print() promt = input(" Press enter to go to main menu ") action = "m" elif action == "2": # See unavailable cars os.system("cls") action = "" self.__car_service.unavailable_cars() print() promt = input(" Press enter to go to main menu ") action = "m" elif action == "3": # List of all cars os.system("cls") action = "" self.__car_service.get_cars_list() print() promt = input(" Press enter to go to main menu ") action = "m" elif action == "4": # See Details of a car while (action != "q"): lp_number = input("Licence plate number: ").upper() while not len(lp_number) == 5: lp_number = input( "Please enter a valid license plate number: ") a = self.__car_service.details_of_car(lp_number) print() if a == True: action = self.print_options() self.additional_options(action) if a == False: continue elif action == "5": # See price list os.system("cls") action = "" while (action != "q"): print(9 * "-", "Price Menu", 9 * "-") print(" You can do the following:\n") print(indent, "1 | See price list") print(indent, "2 | Calculate prices") action = self.print_options() if action == "1": self.__price_service.get_price_list() print() print("Press enter to go back") action = input(" ") if action == "2": print(10 * "-", "Calculate prices", 10 * "-") print("Choose class: \n") print(indent, "A | Class A") print(indent, "B | Class B") print(indent, "C | Class C") print("") class_filter = input(" Input letter: ").upper() while class_filter not in ["A", "B", "C"]: class_filter = input( " Please enter a valid class (a, b, or c): " ) days = input(" Input number of days: ") while not days.isdigit(): days = input( " Please enter valid number of days: ") days_int = int(days) self.__price_service.calculate_price( class_filter, days_int) #os.system("cls") print() print("Press enter to go back") action = input(" ") self.additional_options(action) elif action == "6" and self.access == "admin": # Register new car os.system("cls") lp_number = input(" Licence plate number: ").upper() while not len(lp_number) == 5: lp_number = input( "Invalid Licence plate number. License plate format examples: ABC12, AB123.\n Please enter a valid licence plate number: " ) category = input(" Category: ").upper() while category not in ["A", "B", "C"]: category = input( "Invalid input. Valid categories are 'A', 'B', and 'C'.\n Please enter a valid category: " ).upper() brand = input(" Brand: ").capitalize() while not brand.isalpha(): brand = input( "Invalid brand name.\n Please enter a valid brand name: " ).capitalize() model = input(" Model: ") colour = input(" Colour: ").capitalize() while colour not in [ "Yellow", "Red", "Green", "Blue", "Black", "White", "Gray" ]: colour = input( "Invalid color. Valid colours are yellow, red, green, blue, white, and gray.\n Please enter a valid colour: " ).capitalize() year = input(" Year: ") while not len(year) == 4: year = input( "Invalid year.\n Please enter a valid year.") kilometers = input(" Kilometers: ") while not kilometers.isdigit(): kilometers = input( "Invalid input. Please enter only digits.\n Kilometers: " ) status = input(" Status: ").capitalize() while status not in ["Available", "Unavailable"]: status = input( "Invalid status. Valid inputs are 'Available' and 'Unavailable'.\n Status: " ) new_car = Car(lp_number, category, brand, model, colour, year, kilometers, status) self.__car_service.add_car(new_car) print("") print(" You have registered a new car!") print("") self.print_options() print("") if action == "m".lower(): self.main_menu() elif action == "7" and self.access == "admin": #Change price list action = "" os.system("cls") class_filter = input("Class: ") key = "Price" self.__price_service.change_price(key, class_filter) action = self.print_options() self.additional_options(action) self.additional_options(action) elif action == "2": # Goes to Orders menu while (action != "q"): os.system("cls") print(8 * "-", " Orders Menu ", 9 * "-") print(" You can do the following:\n") print( indent, "1 | Rent cars" ) # ætti að koma valmöguleik að register new customers OR choose customers print(indent, "2 | Calculate Cost of rent") print(indent, "3 | Return cars") print(indent, "4 | Cancel Reservation") print(indent, "5 | See list of all orders") print(indent, "6 | Find an order") action = self.print_options() if action == "1": #Rent cars and ther under number = 0 price = 0 lp_number = " " actual_return_date = "" customer_id = input("Input customer id: ") category = input("Input category: ").upper() pickup_date = input("Input pickup date (dd.mm.yyyy): ") return_date = input("Input return date (dd.mm.yyyy): ") insurance = input( "Do you want extra insurance? Y/N? :").upper() new_order = Order(number, customer_id, lp_number, category, pickup_date, return_date, price, insurance, actual_return_date) self.__order_service.rent_car(new_order) action = self.print_options() self.additional_options(action) #Hér þarf að taka til hendinni og laga virknina. #Skref 1 er að stimpla inn kennitölu, ef hún er ekki á skrá þá þarf að skrá viðskiptavin # action = "" # while(action != "q"): # os.system("cls") # print("You can do the following:\n") # print("1 | Register new customers") # print("2 | Choose customers") # print("m | Go to Main menu") # print() # action = input("Input number/letter: ").lower() # print(" You can do the following:\n") # print(indent,"1 | Register new customers") # print(indent,"2 | Choose customers") # self.print_options() # print() # action = input(" Input number/letter: ").lower() # if action == "1": # self.__order_service.return_car() # # Register new customer # os.system("cls") # id_number = input(" Customer ID: ") # while len(id_number) != 10: # id_number = input(" Invalid Customer ID. Customer ID is either Icelandic SSN or Passport number of length 10.\n Please enter a valid Customer ID: ") # first_name = input(" First name: ") # while not first_name.isalpha(): # first_name = input(" Invalid first name.\n Please enter a valid first name: ") # last_name = input(" Last name: ") # while not last_name.isalpha(): # last_name = input(" Invalid last name.\n Please enter a valid last name: ") # age = input(" Age: ") # while not age.isdigit(): # age = input(" Invalid input, only digits allowed.\n Age: ") # country = input(" Country: ") # while not country.isalpha(): # country = input(" Invalid input. \n Please enter a valid country: ") # email = input(" E-mail: ") # while ("@" and ".")not in email: # email = input(" Invalid E-mail address.\n Please enter a valid E-mail address: ") # if len(email) <= 6: # email = input(" Invalid E-mail address.\n Please enter a valid E-mail address: ") # phone = input(" Phone number: ") # while not phone.isdigit() and len(phone) <= 9: # phone = input(" Invalid phone number. Phone number should only be digits on and must contain country code.\n Please enter a valid Phone number: ") # dl_number = input(" Drivers license number: ") # while len(dl_number) <= 8: # dl_number = input("Invalid drivers license number, must me at least 9 letters/digits long.\n Please enter a valid drivers license number: ") # cc_number = input(" Credit card number: ") # while not cc_number.isdigit(): # cc_number = input("Invalid creditcard number.\n Please enter a valid creditcard number: ") # new_customer = Customer(id_number, first_name, last_name, age, country, email, phone, dl_number, cc_number) # #new_customer = customer(id_number, first_name) # self.__customer_service.add_customer(new_customer) # #######print(new_customer) # if action == "2": # #Choos customers # pass # self.additional_options(action) # # #Rent a car # # self.__order_service.rent_car() elif action == "2": #Calculate Cost of rent print(8 * "-", "Calculate prices", 8 * "-") print("Choose class: \n") print(indent, "A | Class A") print(indent, "B | Class B") print(indent, "C | Class C") print("") class_filter = input(" Input letter: ").upper() days = input(" Input number of days: ") days_int = int(days) self.__price_service.calculate_price( class_filter, days_int) print() action = self.print_options() self.additional_options(action) elif action == "3": #Return Cars order_number = input('Enter Order Number: ') self.__order_service.return_car(order_number) action = self.print_options() self.additional_options(action) pass # elif action == "4": # #Change Reservation # order_filter = input("Enter Order Number: ") # while not order_filter.isdigit(): # order_filter = input("Please enter valid order number: ") # print("You can change:\n") # print(indent,"1 | Pick-up Date") # print(indent,"2 | Return Date") # print(indent,"c | Cancel") # print(indent,"q | Quit") # action = input("What do you want to change?: ") # while action not in ["1", "2"]: # action = input("Invalid input. Enter 1 or 2: ") # key_filter = "Number" # if action == "1": # key = "Pick-up Date" # elif action == "2": # key = "Return Date" # if (action != "") and ((action != "m") or (action != "c")): # self.__order_service.change_order(key, key_filter, order_filter) # self.print_options() # action = input("Input letter: ") # self.additional_options(action) elif action == "4": #Cancel Reservation order_number = input("Enter Order Number: ") self.__order_service.cancel_order(order_number) elif action == "5": #See list of all orders os.system("cls") action = "" self.__order_service.get_orders() print() action = input(" Press enter to go back ") if action == "b": self.main_menu() self.additional_options(action) elif action == "6": #Details of order os.system("cls") order_number = input("Order number: ") while not order_number.isdigit(): order_number = input( "Please enter a valid order number: ") self.__order_service.find_order(order_number) print() action = self.print_options() self.additional_options(action) self.additional_options(action) elif action == "3": # Goes to Customers menu while (action != "q"): os.system("cls") print(7 * "-", " Customers Menu ", 7 * "-") print(" You can do the following:\n") print(indent, "1 | Register new customer") print(indent, "2 | Find customer") print(indent, "3 | List all customers") print(indent, "4 | Change customer information") if self.access == "admin": print(indent, "5 | Remove customer from system") print(indent, "m | Go to Main menu") print(indent, "q | Quit") print() action = input(" Input number/letter: ").lower() if action == "1": # Register new customer os.system("cls") id_number = input(" Customer ID: ") while len(id_number) != 10: id_number = input( " Invalid Customer ID. Customer ID is either Icelandic SSN or Passport number of length 10.\n Please enter a valid Customer ID: " ) first_name = input(" First name: ") while not first_name.isalpha(): first_name = input( " Invalid first name.\n Please enter a valid first name: " ) last_name = input(" Last name: ") while not last_name.isalpha(): last_name = input( " Invalid last name.\n Please enter a valid last name: " ) age = input(" Age: ") while not age.isdigit(): age = input( " Invalid input, only digits allowed.\n Age: ") country = input(" Country: ") while not country.isalpha(): country = input( " Invalid input. \n Please enter a valid country: " ) email = input(" E-mail: ") while ("@" and ".") not in email: email = input( " Invalid E-mail address.\n Please enter a valid E-mail address: " ) if len(email) <= 6: email = input( " Invalid E-mail address.\n Please enter a valid E-mail address: " ) phone = input(" Phone number: ") while not phone.isdigit() and len(phone) <= 9: phone = input( " Invalid phone number. Phone number should only be digits on and must contain country code.\n Please enter a valid Phone number: " ) dl_number = input(" Drivers license number: ") while len(dl_number) <= 8: dl_number = input( "Invalid drivers license number, must me at least 9 letters/digits long.\n Please enter a valid drivers license number: " ) cc_number = input(" Credit card number: ") while not cc_number.isdigit(): cc_number = input( "Invalid creditcard number.\n Please enter a valid creditcard number: " ) new_customer = Customer(id_number, first_name, last_name, age, country, email, phone, dl_number, cc_number) self.__customer_service.add_customer(new_customer) break elif action == "2": # Find customer action = "" while (action != "q"): os.system("cls") customer_id = input("Customer ID: ") while not len(customer_id) == 10: customer_id = input( "Please enter a valid customer ID: ") a = self.__customer_service.find_customer( customer_id) if a == True: break if a == False: continue print() action = self.print_options() self.additional_options(action) elif action == "3": # List all customers os.system("cls") self.__customer_service.get_customers() print() self.print_options() action = input(" Input letter: ").lower() self.additional_options(action) elif action == "4": # Change customer information action = "" while (action != "q"): os.system("cls") customer_filter = input("Customer ID: ") action = "" key_filter = "Customer ID" print(" You can change the following:\n ") print(indent, "1 | First name") print(indent, "2 | Last name") print(indent, "3 | Date of birth") print(indent, "4 | Country") print(indent, "5 | E-mail address") print(indent, "6 | Phone number") print(indent, "7 | Drivers License number") print(indent, "8 | Credit card number") print(indent, "c | Cancel") print(indent, "q | Quit") action = input(" Input number/letter: ").lower() if action == "1": key = "First Name" elif action == "2": key = "Last Name" elif action == "3": key = "Age" elif action == "4": key = "Country" elif action == "5": key = "Email" elif action == "6": key = "Phone" elif action == "7": key = "Drivers License Number" elif action == "8": key = "Credit Card Number" elif action == "c": break if (action != "") and ((action != "m") or (action != "c")): self.__customer_service.change_customer_info( key, key_filter, customer_filter) self.print_options() action = input("Input letter:") self.additional_options(action) elif action == "5" and self.access == "admin": #Remove Customer from system action = "" while (action != "q"): os.system("cls") print( " You are about to remove a customer from the system.\n" ) customer_filter = input(" Enter customers ID: ") if customer_filter != []: key_filter = "Customer ID" a = self.__customer_service.remove_customer( key_filter, customer_filter) if a == True: break if a == False: continue # back er ekki alveg að virka, en það virkar ef það hefur break... self.print_options() action = input(" Input letter: ").lower self.additional_options(action) elif action == "": action = 1 elif action == "b": self.main_menu() elif action != 1: self.additional_options(action) if action == "q": return SystemExit
def get(self): Utils.reset(self) # reset/clean standard variables # validate and assign parameters passwd = Utils.required(self, 'passwd') version = config.data_version['building'] if self.request.get('version'): version = self.request.get('version') lang = config.server["defaultLanguage"] if self.request.get('lang'): lang = self.request.get('lang') uuid = Utils.required(self, 'uuid') guid = self.request.get('guid') crid = Utils.required(self, 'crid') # check password if self.error == '' and passwd != config.testing['passwd']: self.error = 'passwd is incorrect.' start_time = time.time() # start count # logical variables player = None cars = None upgrades = None car = None #mycars = None Utils.LogRequest(self) # if error, skip this if self.error == '': player = Player.getplayer(self, uuid) if self.error == '' and player is not None and guid != '': if guid != player.state_obj['guid']: player = None self.error = config.error_message['dup_login'] if self.error == '' and player is not None: cars = Data.getcars(self, lang, float(version)) if self.error == '' and cars is not None: found = False for _car in cars.as_obj: if _car['id'] == crid: car = _car found = True break if found is False: self.error = crid + " was not found!" if self.error == '' and car is not None: mycars = Car.list(self, uuid) for _car in mycars: data_obj = json.loads(_car.data) try: if data_obj['info']['crid'] == crid: # already own this car type, and you can only 1 of each type #self.respn = '{"warning":"You have already purchased this car."}' player.state_obj['current_car'] = _car.cuid player.state_obj['updated'] = start_time if Player.setplayer(self, player): self.respn = '{"state":' + player.state + ',' self.respn += '"car":[' self.respn = Car.compose_mycar(self.respn, _car) self.respn = self.respn.rstrip(',') + ']' self.respn += '}' car = None break except KeyError: self.error = 'Cannot find crid (KeyError issue), please report admin!' if self.error == '' and car is not None: upgrades = Data.getupgrades(self, lang, float(version)) if self.error == '' and upgrades is not None: # good to go as we have a car if player.state_obj['cash'] >= car['cost']: player.state_obj['cash'] -= car['cost'] player.state_obj[ 'updated'] = start_time # update timestamp for player mycar = Car.create(self, player.uuid) mycar.data_obj['info'] = {'crid': car['id']} mycar.data_obj['upgrades'] = [] mycar.data_obj['equip'] = {} player.state_obj['current_car'] = mycar.cuid default_upgrades = car['default_upgrades'].replace( ' ', '').split(',') for default_upgrade in default_upgrades: mycar.data_obj['upgrades'].append(default_upgrade) for _type in upgrades.as_obj: try: mycar.data_obj['equip'][type] except KeyError: for upgrade in upgrades.as_obj[_type]: if upgrade['id'] == default_upgrade: mycar.data_obj['equip'][ _type] = default_upgrade break break player.state = json.dumps(player.state_obj) if Player.setplayer(self, player): if Car.update(self, mycar): self.respn = '{"state":' + player.state + ',' self.respn += '"car":[' self.respn = Car.compose_mycar(self.respn, mycar) self.respn = self.respn.rstrip(',') + ']' self.respn += '}' else: self.respn = '{"warning":"not enough cash!"}' logging.warn("not enough cash") else: logging.warn("Error with car upgrades") # calculate time taken and return the result time_taken = time.time() - start_time self.response.headers['Content-Type'] = 'text/html' self.response.write(Utils.RESTreturn(self, time_taken))
def get(self): Utils.reset(self) # reset/clean standard variables # validate and assign parameters passwd = Utils.required(self, 'passwd') uuid = Utils.required(self, 'uuid') guid = self.request.get('guid') type = Utils.required(self, 'type') version = config.data_version['building'] if self.request.get('version'): version = self.request.get('version') lang = config.server["defaultLanguage"] if self.request.get('lang'): lang = self.request.get('lang') if self.error == '' and passwd != config.testing[ 'passwd']: # if password is incorrect self.error = 'passwd is incorrect.' # inform user via error message Utils.LogRequest(self) start_time = time.time() # start count # if error, skip this if self.error == '': player = Player.getplayer( self, uuid ) # get player state from Player helper class, specified by uuid if self.error == '' and player is not None and guid != '': if guid != player.state_obj['guid']: player = None self.error = config.error_message['dup_login'] if self.error == '' and player is not None: # if have some data returned self.respn = '{' if type == 'all': type = '' for item in config.playerdata: type += item + ',' type = type.rstrip(',') types = type.split(',') for item in types: if item == 'info': self.respn += '"info":' + player.info + ',' elif item == 'state': self.respn += '"state":' + player.state + ',' elif item == 'building': buildings = Data.getbuildings(self, lang, version) mybuildings = Building.getmybuildings(self, uuid) if buildings is not None and mybuildings is not None: self.respn += '"building":[' for mybuilding in mybuildings: # update building status, determine production _upd = False if mybuilding.status == Building.BuildingStatus.PENDING: if mybuilding.timestamp + ( buildings.as_obj[mybuilding.itid] [mybuilding.level - 1]['build_time'] * 60) <= start_time: mybuilding.timestamp = int(start_time) mybuilding.status = Building.BuildingStatus.DELIVERED _upd = True elif mybuilding.status == Building.BuildingStatus.DELIVERED: mybuilding.status = Building.BuildingStatus.OWNED _upd = True if _upd is True: Building.setmybuilding(self, mybuilding) self.respn = Building.compose_mybuilding( self.respn, mybuilding) self.respn = self.respn.rstrip(',') + '],' elif item == 'car': mycars = Car.list(self, uuid) if mycars is not None: self.respn += '"car":[' for _car in mycars: self.respn += Car.compose_mycar('', _car) + ',' self.respn = self.respn.rstrip(',') + '],' elif item == 'challenge': Challenge.ComposeChallenges(self, player) self.respn = self.respn.rstrip(',') + '}' # calculate time taken and return result time_taken = time.time() - start_time self.response.headers['Content-Type'] = 'text/html' self.response.write(Utils.RESTreturn(self, time_taken))