def post(self, client_id = None): #Creamos el request parser, que nos ayudará a manejar la informacion de entrada parser = reqparse.RequestParser() #Definimos que esperamos como entrada parser.add_argument('nombre', type=str,required=True, help="Name field cannot be left blanck") parser.add_argument('email', type=str,required=True, help="Email field cannot be left blanck") parser.add_argument('iban', type=str,required=True, help="IBAN field cannot be left blanck") parser.add_argument('dni_nie', type=str,required=True, help="DNI/NIE field cannot be left blanck") parser.add_argument('password', type=str, required=True, help="Password field cannot be left blanck") #Tomamos la información del parser en un diccionario (data) data = parser.parse_args() c = ClientModel.query.filter_by(email=data['email']).first() if c: return {'message': 'A client with same email [{}] already exists'.format(data['email'])}, 409 c = ClientModel.query.filter_by(dni_nie=data['dni_nie']).first() if c: return {'message': 'A client with same DNI/NIE [{}] already exists'.format(data['dni_nie'])}, 409 entry = ClientModel(data['nombre'],data['iban'],data['dni_nie'],data['email'],data['password']) entry.save_to_db() return entry.json(), 201
def delete(self, email_client): parser = reqparse.RequestParser() parser.add_argument('password', type=str, required=True, help="Password cannot be left blanck") data = parser.parse_args() password = data['password'] c = ClientModel.find_by_email(email_client) if c: # Si existe el cliente if c.password == password: # Si la password coincide con la del cliente rr = ReservedRunningModel.find_by_client(c.client_id) if(rr is not None): # Si existe una reserva o start afiliada al cliente, indagamos moto = MotoModel.find_by_id(rr.moto.id) if(moto.state == "RESERVED"): # Si la moto esta reservada # Borramos la fila de rr rr.delete_from_db() # Actualizamos el estado de la moto moto.state = "AVAILABLE" moto.save_to_db() # Borramos el cliente c.delete_from_db() return {"message": "Client DELETED successfully"}, 200 if(moto.state == "ACTIVE"): # No podemos borrar el cliente porque antes tiene que finalizar el trayecto return {'message': 'The account cannot be deleted because you have a journey started'}, 401 else: # Si no existe reserva o start, podemos borrarlo directamente c.delete_from_db() return {"message": "Client DELETED successfully"}, 200 else: # Password erronea return {'message': 'ERROR: The password is not correct.'}, 400 else: # Si no existe el cliente return {'message': 'ERROR: There is no client with email [{}] .'.format(email_client)}, 404
def get(self, client_email): try: client = ClientModel.find_by_email(client_email) if client is not None: rr = ReservedRunningModel.find_by_client(client.client_id) # Compruebo si ha encontrado la reserva del ciente if rr is not None: # Compruebo si el estado de la moto es el correcto (ACTIVE) if rr.isActive(): # Compruebo que no se ha superado el tiempo limite para el start moto desde la reserva if rr.check_remaining_time(): coord_client = (23.44333, 23.4433) moto = rr.moto moto_json = [moto.json_clientMoto()] result = MotoModel.compute_distance(moto_json, coord_client, "distance") # los cambios de keyname de jsons es para coordinar con frontend return {'start_moto': result['motos'][0]}, 201 else: ReservedRunningModel.update_state_available(rr) ReservedRunningModel.delete_from_db(rr) return {"message": "The time limit for the start has expired"}, 500 else: return {'message': "Error Moto state isn't active"}, 500 else: return {'message': "Error Client haven't start moto"}, 404 else: return {'message': "Error Client Not Found"}, 404 except: return {"message": "Error Get Start Moto"}, 500
def delete(self, client_email, moto_id): try: moto = MotoModel.find_by_id(moto_id) client = ClientModel.find_by_email(client_email) # En caso de que tanto la moto y el cliente existan en sus respectivas tablas if moto is not None and client is not None: moto = MotoModel.find_by_id(moto_id) client = ClientModel.find_by_email(client_email) # Compruebo si existe el cliente segun el email recibido y si existe la moto segun el id recibido if moto is not None and client is not None: reserve = ReservedRunningModel.query.filter(and_( ReservedRunningModel.clientId == client.client_id, ReservedRunningModel.motoId == moto_id )).first() # Si no se encuentra la reserva con esas características... if reserve is None: return {"message": "DELETE ERROR. Moto reserved with id {} and client {} not found.".format( moto_id, client_email)}, 404 # En caso de que si que exista una fila en la tabla RR... else: # Comprobamos cual es el auténtico estado de la moto. # una reserva(state =="RESERVED"), if moto.state == 'RESERVED': # Borramos la fila de rr reserve.delete_from_db() # Actualizamos el estado de la moto moto.state = "AVAILABLE" moto.save_to_db() return {"message": "Reserved Moto DELETED successfully"}, 200 # una running (state =="ACTIVE") elif moto.state == 'ACTIVE': # No se puede cancelar la reserva si no está reservada, sinó running(ACTIVE) return {"message": "DELETE ERROR Moto Reserve: Moto is ACTIVE"}, 500 # un DESASTRE (state ==otra cosa, que no debería). else: # ¡¡¡¡ERROR FATAL!!!! # Si entramos en este else es que la moto no debería estar en esta tabla. # TODO Revisar si deberíamos borrarlo igualmente return {"message": "FATAL Error. DELETE Moto Reserve: Moto is {}.".format(moto.state)}, 500 # En caso de que o la moto o el cliente NO EXISTAN en sus respectivas tablas else: return {"message": "DELETE ERROR Moto Reserve. Moto with id [{}] or client with email [{}] not found." .format(moto_id, client_email)}, 404 except: return {"message": "DELETE ERROR Reserved Moto. Internal Failure."}, 500
def test_profile_modify_correct(client): c = client c.get("/clients") # Cogemos un cliente random de la base de datos. client_old = ClientModel.query.filter(ClientModel.client_id == 1).first() # Nos inventamos datos new_email = "*****@*****.**" new_dni_nie = "000000000000" new_name = "Inventado" new_iban = "0000000000000000000000" # Nos aseguramos de que no exista ese email en la base de datos assert ClientModel.find_by_email(new_email) is None # Nos aseguramos de que no exista ese dni en la base de datos assert ClientModel.find_by_dni(new_dni_nie) is None # Hacemos el put con datos inventados path = '/profile/' + client_old.email params = { 'name': new_name, 'iban': new_iban, 'dni_nie': new_dni_nie, 'email': new_email } r = c.put(path, json=params) assert r.status_code == 200 # Antes de nada comprobamos si realmente se han modificado el email o el dni assert ClientModel.find_by_email(new_email) is not None assert ClientModel.find_by_dni(new_dni_nie) is not None # Ahora comprobaremos los otros datos new_client = ClientModel.find_by_email(new_email) assert new_client.nombre == new_name assert new_client.iban == new_iban assert new_client.dni_nie == new_dni_nie assert new_client.email == new_email
def put(self, email): parser = reqparse.RequestParser() parser.add_argument('name', type=str, required=False) parser.add_argument('iban', type=str, required=False) parser.add_argument('dni_nie', type=str, required=False) parser.add_argument('email', type=str, required=False) data = parser.parse_args() try: client = ClientModel.find_by_email(email) if client is not None: if data['name']: client.set_name(data['name']) if data['iban']: client.set_iban(data['iban']) if data['dni_nie']: if ClientModel.find_by_dni(data['dni_nie']) is None: client.set_dni_nie(data['dni_nie']) else: if ClientModel.find_by_dni(data['dni_nie']).client_id == client.client_id: client.set_dni_nie(data['dni_nie']) else: return {"message": "The new DNI/NIE is already in use"}, 406 if data['email']: if ClientModel.find_by_email(data['email']) is None: client.set_email(data['email']) else: if ClientModel.find_by_email(data['email']) == client: client.set_email(data['email']) else: return {"message": "The new email is already in use"}, 405 return {"message": "Client profile modified successfully"}, 200 else: return {"message": "Client with this email doesn't exist"}, 404 except: return {"message": "Error Modify client profile"}, 500
def get(self, client_email): try: client = ClientModel.find_by_email(client_email) # Compruebo si ha encontrado el cliente con ese email if client is not None: rr = ReservedRunningModel.find_by_client(client.client_id) # Compruebo si ha encontrado la reserva del ciente if rr is not None: # Compruebo el estado de la moto if rr.isReserved(): # Compruebo que no se ha superado el tiempo limite para el start moto desde la reserva if rr.check_remaining_time(): coord_client = (23.44333, 23.4433) moto = rr.moto moto_json = [moto.json_clientMoto()] result = MotoModel.compute_distance(moto_json, coord_client, "distance") # los cambios de keyname de jsons es para coordinar con frontend remaining_time = rr.make_remaining_time() if remaining_time.minute < 10: time_min = "0" + str(remaining_time.minute) else: time_min = str(remaining_time.minute) if remaining_time.hour < 10: time_h = "0" + str(remaining_time.hour) else: time_h = str(remaining_time.hour) return {'reserved_moto': result['motos'][0], "message": "You have until {}:{}h to start the motorbike".format(time_h, time_min), "remaining_time": time_h + ":" + time_min}, 201 else: ReservedRunningModel.update_state_available(rr) ReservedRunningModel.delete_from_db(rr) return {"message": "The time limit for the start has expired"}, 500 else: return {"message": "ERROR RESERVED MOTO. Moto state isn't RESERVED, moto state = [{}]".format( rr.moto.state)}, 500 else: return {"message": "ERROR RESERVED MOTO. Error Client [{}] haven't reserved moto".format( client.client_id)}, 404 else: return {"message": "ERROR RESERVED MOTO. Error Client Not Found"}, 404 except: return {"message": "ERROR RESERVED MOTO. Error Get Reserved Moto"}, 500
def post(self): parser = reqparse.RequestParser() parser.add_argument('email', type=str, required=True, help="Email cannot be left blank") parser.add_argument('password', type=str, required=True, help="Password cannot be left blank") data = parser.parse_args() try: email_aux = data['email'].split("@") #print(email_aux) if "mooving.com" in email_aux: #print("entramos mecanico") mechanic = MechanicModel.find_by_email(data['email']) if mechanic: if mechanic.verify_password(data['password']): return { 'message': "Login succesfull", 'mechanic': mechanic.json(), 'type': "mechanic" }, 200 else: return {"message": "Wrong password"}, 400 else: return {"message": "Mechanic not found"}, 404 else: #print("entramos cliente") client = ClientModel.find_by_email(data['email']) if client: if client.verify_password(data['password']): return { 'message': "Login succesfull", 'client': client.json(), 'type': "client" }, 200 else: return {"message": "Wrong password"}, 400 else: return {"message": "User not found"}, 404 except: return {"message": "Error Post Login"}, 500
def post(self): parser = reqparse.RequestParser() parser.add_argument('client_email', type=str, required=True, help="Client email cannot be left blank") parser.add_argument('moto_id', type=int, required=True, help="Moto id cannot be left blank") data = parser.parse_args() client_email = data['client_email'] moto_id = data['moto_id'] moto = MotoModel.find_by_id(moto_id) client = ClientModel.find_by_email(client_email) # Compruebo si existe el cliente segun el email recibido y si existe la moto segun el id recibido if moto is not None and client is not None: # Compruebo si el estado de la moto es el correcto (AVAILABLE) if moto.state == 'AVAILABLE': # Compruebo si el cliente no tiene motos reservadas if ReservedRunningModel.find_by_client(client.client_id) is None: rr = ReservedRunningModel(client, moto) ReservedRunningModel.save_to_db(rr) ReservedRunningModel.update_state_reserved(rr) remaining_time = rr.make_remaining_time() if remaining_time.minute < 10: time_min = "0" + str(remaining_time.minute) else: time_min = str(remaining_time.minute) if remaining_time.hour < 10: time_h = "0" + str(remaining_time.hour) else: time_h = str(remaining_time.hour) return {"message": "You have until {}:{}h to start the motorbike".format(time_h, time_min), "remaining_time": time_h + ":" + time_min}, 201 else: return {"message": "ERROR RESERVED MOTO. Customer [{}] already has a reserved motorcycle".format( client.client_id)}, 500 else: return {"message": "ERROR RESERVED MOTO. Moto state isn't AVAILABLE, moto state = [{}]".format( moto.state)}, 500 else: return {"message": "ERROR RESERVED MOTO. Motorcycle error or client not found for Reserved Moto post"}, 404
def post(self): try: parser = reqparse.RequestParser() parser.add_argument('client_email', type=str, required=True, help="Client email cannot be left blank") parser.add_argument('moto_id', type=int, required=True, help="Moto id cannot be left blank") data = parser.parse_args() client_email = data['client_email'] moto_id = data['moto_id'] moto = MotoModel.find_by_id(moto_id) client = ClientModel.find_by_email(client_email) rr = ReservedRunningModel.find_by_client_moto(client.client_id, moto_id) # Compruebo si existe el cliente segun el email recibido y si existe la moto segun el id recibido if moto is not None and client is not None: # Compruebo si el estado de la moto es el correcto (RESERVED) if moto.state == 'RESERVED': # Compruebo si ha encontrado la reserva del ciente y la moto if rr is not None: # Compruebo que no se ha superado el tiempo limite para el start moto desde la reserva if rr.check_remaining_time(): ReservedRunningModel.make_star_moto(rr) ReservedRunningModel.update_state_start(rr) return {"message": "Start successfully"}, 200 else: ReservedRunningModel.update_state_available(rr) ReservedRunningModel.delete_from_db(rr) return {"message": "The time limit for the start has expired"}, 500 else: return {"message": "Reservation error with that id_client and id_moto does not exist"}, 500 else: return {"message": "Error state moto isn't RESERVED"}, 500 else: return {"message": "Motorcycle or client not found error for POST Start Moto"}, 404 except: return {"message": "Error POST Start Moto"}, 500
def init_db(): db.drop_all() db.create_all() new_moto1 = MotoModel(state="AVAILABLE", matricula="1111-MMM", date_estreno="28/10/2020", model_generic="basic", last_coordinate_latitude=41.403193, last_coordinate_longitude=2.175004, km_restantes=34.0, km_totales=300.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto1) new_moto2 = MotoModel(state="AVAILABLE", matricula="2222-MMM", date_estreno="28/10/2020", model_generic="basic", last_coordinate_latitude=41.403719, last_coordinate_longitude=2.189128, km_restantes=3.0, km_totales=23.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto2) new_moto3 = MotoModel(state="AVAILABLE", matricula="3333-MMM", date_estreno="28/10/2020", model_generic="premium", last_coordinate_latitude=41.386399, last_coordinate_longitude=2.164143, km_restantes=120.0, km_totales=500.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto3) new_moto = MotoModel(state="AVAILABLE", matricula="4444-MMM", date_estreno="28/10/2020", model_generic="premium", last_coordinate_latitude=41.348788, last_coordinate_longitude=2.132925, km_restantes=45.0, km_totales=203.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto) new_moto = MotoModel(state="LOW_BATTERY_FUEL", matricula="5555-MMM", date_estreno="08/10/2020", model_generic="premium", last_coordinate_latitude=41.413273, last_coordinate_longitude=2.152931, km_restantes=2.0, km_totales=100.0, date_last_check="18/10/2020", km_last_check=100.0) db.session.add(new_moto) new_moto = MotoModel(state="LOW_BATTERY_FUEL", matricula="6666-MMM", date_estreno="08/10/2020", model_generic="premium", last_coordinate_latitude=41.427691, last_coordinate_longitude=2.166293, km_restantes=4.0, km_totales=100.0, date_last_check="18/10/2020", km_last_check=100.0) db.session.add(new_moto) new_moto = MotoModel(state="AVAILABLE", matricula="7777-MMM", date_estreno="28/10/2020", model_generic="premium", last_coordinate_latitude=41.387818, last_coordinate_longitude=2.169647, km_restantes=23.0, km_totales=203.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto) new_moto = MotoModel(state="AVAILABLE", matricula="8888-MMM", date_estreno="28/10/2020", model_generic="basic", last_coordinate_latitude=41.375960, last_coordinate_longitude=2.177455, km_restantes=35.0, km_totales=203.0, date_last_check="18/10/2020", km_last_check=100.0) db.session.add(new_moto) new_moto = MotoModel(state="AVAILABLE", matricula="5454-MMM", date_estreno="28/11/2020", model_generic="premium", last_coordinate_latitude=41.384223, last_coordinate_longitude=2.160337, km_restantes=35.0, km_totales=403.0, date_last_check="28/10/2020", km_last_check=100.0) db.session.add(new_moto) new_moto = MotoModel(state="AVAILABLE", matricula="4545-MMM", date_estreno="28/11/2020", model_generic="premium", last_coordinate_latitude=41.359768, last_coordinate_longitude=2.084035, km_restantes=35.0, km_totales=403.0, date_last_check="28/10/2020", km_last_check=100.0) db.session.add(new_moto) new_moto9 = MotoModel(state="AVAILABLE", matricula="9999-MMM", date_estreno="28/10/2020", model_generic="basic", last_coordinate_latitude=41.591158, last_coordinate_longitude=1.520865, km_restantes=34.0, km_totales=300.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto9) new_moto10 = MotoModel(state="AVAILABLE", matricula="1010-MMM", date_estreno="28/10/2020", model_generic="basic", last_coordinate_latitude=41.591158, last_coordinate_longitude=1.5209, km_restantes=999.0, km_totales=300.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto10) client1 = ClientModel(nombre="Juana", iban="2223462362665251w", dni_nie="11111111J", email="*****@*****.**", password="******") db.session.add(client1) client2 = ClientModel(nombre="Camila", iban="22462362665251w", dni_nie="14441111J", email="*****@*****.**", password="******") db.session.add(client2) client3 = ClientModel(nombre="Sofia", iban="2223332362665251w", dni_nie="11188881J", email="*****@*****.**", password="******") db.session.add(client3) client = ClientModel(nombre="Ramona", iban="225554362665251w", dni_nie="12341111J", email="*****@*****.**", password="******") db.session.add(client) articulo = ArticleModel( titulo="¡Motos más nuevas y potentes que nunca!", texto="Las nuevas motos de Mooving están batiendo todos los" "récord habidos y por haber. Tenemos más de 400 motos eléctricas" "con una autonomía de más de 100KM.", fecha_creacion="2020/10/29", visible=True) db.session.add(articulo) articulo = ArticleModel( titulo="¡Motos más rápidas !", texto= "Las nuevas motos de Mooving son más rápidas que las de la competencia." " Tenemos más de 400 motos eléctricas" " con una velocidad punta de más de 100KM/H .", fecha_creacion="2020/10/28", visible=True) db.session.add(articulo) new_mechanic = MechanicModel(name="Jose", subname="De carglass", dni="11111111J", password="******", date_registration="23/02/2020") db.session.add(new_mechanic) new_mechanic = MechanicModel(name="Pepe", subname="De marcota", dni="22222222J", password="******", date_registration="24/02/2020") db.session.add(new_mechanic) db.session.commit() print('Success in adding items to database')
def get(self, email): try: client = ClientModel.find_by_email(email) return {'client_profile': client.json_profile()}, 200 except: return {"message": "Error Get Client Pofile"}, 500
def add_data(db=db): new_moto1 = MotoModel( state="AVAILABLE", matricula="1111-MMM", date_estreno="28/10/2020", model_generic="basic", last_coordinate_latitude=41.40181444604073, last_coordinate_longitude=2.1602937877348554, km_restantes=80.0, km_totales=300.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto1) new_moto2 = MotoModel( state="AVAILABLE", matricula="2222-MMM", date_estreno="28/10/2020", model_generic="basic", last_coordinate_latitude=41.40514485607213, last_coordinate_longitude=2.1587408287276393, km_restantes=80.0, km_totales=23.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto2) new_moto3 = MotoModel( state="AVAILABLE", matricula="3333-MMM", date_estreno="28/10/2020", model_generic="premium", last_coordinate_latitude=41.40396129395845, last_coordinate_longitude=2.1672429122257184, km_restantes=120.0, km_totales=500.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto3) new_moto = MotoModel( state="AVAILABLE", matricula="4444-MMM", date_estreno="28/10/2020", model_generic="premium", last_coordinate_latitude=41.403205972568855, last_coordinate_longitude=2.155472976562771, km_restantes=120.0, km_totales=203.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto) new_moto = MotoModel( state="LOW_BATTERY_FUEL", matricula="5555-MMM", date_estreno="08/10/2020", model_generic="premium", last_coordinate_latitude=41.40510495456656, last_coordinate_longitude=2.166668308564227, km_restantes=30.0, km_totales=100.0, date_last_check="18/10/2020", km_last_check=100.0) db.session.add(new_moto) new_moto = MotoModel( state="LOW_BATTERY_FUEL", matricula="6666-MMM", date_estreno="08/10/2020", model_generic="premium", last_coordinate_latitude=41.40551322372631, last_coordinate_longitude=2.163830433113226 , km_restantes=30.0, km_totales=100.0, date_last_check="18/10/2020", km_last_check=100.0) db.session.add(new_moto) client1 = ClientModel( nombre="Juana", iban="2223462362665251w", dni_nie="11111111J", email="*****@*****.**", password="******" ) db.session.add(client1) client2 = ClientModel( nombre="Camila", iban="22462362665251w", dni_nie="14441111J", email="*****@*****.**", password="******" ) db.session.add(client2) client3 = ClientModel( nombre="Sofia", iban="2223332362665251w", dni_nie="11188881J", email="*****@*****.**", password="******" ) db.session.add(client3) client = ClientModel( nombre="Ramona", iban="225554362665251w", dni_nie="12341111J", email="*****@*****.**", password="******" ) db.session.add(client) articulo = ArticleModel( titulo="¡Motos más nuevas y potentes que nunca!", texto="Las nuevas motos de Mooving están batiendo todos los" "récord habidos y por haber. Tenemos más de 400 motos eléctricas" "con una autonomía de más de 100KM.", fecha_creacion="2020/10/29", visible=True) db.session.add(articulo) articulo = ArticleModel( titulo="¡Motos más rápidas !", texto="Las nuevas motos de Mooving son más rápidas que las de la competencia." " Tenemos más de 400 motos eléctricas" " con una velocidad punta de más de 100KM/H .", fecha_creacion="2020/10/28", visible=True) db.session.add(articulo) new_mechanic = MechanicModel( name="Jose", subname="De carglass", dni="11111111J", password="******", date_registration="23/02/2020") db.session.add(new_mechanic) new_mechanic = MechanicModel( name="Pepe", subname="De marcota", dni="22222222J", password="******", date_registration="24/02/2020") db.session.add(new_mechanic) db.session.commit() print('Success in adding items to database')