def multiple_users(db_session): data1 = get_dummy_user(name='John', surname='Doe', email='*****@*****.**') data2 = get_dummy_user(name='Jane', surname='Doe', email='*****@*****.**') user1 = FoodieUser(id=1, **data1) user2 = FoodieUser(id=2, **data2) db_session.add_all([user1, user2]) db_session.commit()
def post(self, post_data): from utils.custom_logging import MyLogger # Import circular email = post_data['email'] new_user = FoodieUser(**post_data) models.Session.add(new_user) models.Session.commit() user = FoodieUser.get_by_email(email) MyLogger.info("Se creó el usuario %s", user.email) return user.as_dict(), 201
def get_all_available_distance(cls, shop_location, deliveries_only=False): from models.users import FoodieUser """ Obtengo todos los deliveries que se encuentan disponibles, junto con la distancia hacia la ubicación """ available = cls.get_all_available() locations = [x.location for x in available] distances = distance_between(locations, shop_location) data = [] for pos, delivery in enumerate(available): distance_data = distances[pos] if distance_data['status'] is False: # Hay un problema con la ubicacion del delivery continue else: distance = distance_data['distance'] d = delivery.as_dict() user = FoodieUser.get_by_id(delivery.user_id) if user.is_user() and deliveries_only: # El usuario no es delivery, y queremos sólo deliveries continue d.update(user.public_info()) d['distance'] = distance data.append(d) return data
def post(self, post_data): order = Order(**post_data) order.save_to_db() shop_location = order.shop_location deliveries_only = not order.favor available_deliveries = DeliveryStatus.get_all_available_distance( shop_location, deliveries_only=deliveries_only) """ for d in available_deliveries: distance = d['distance'] price = PricingEngine.get_distance_price(distance) d['price'] = price """ if available_deliveries: closest_delivery = min(available_deliveries, key=lambda x: x['distance']) user = FoodieUser.get_by_id(order.user_id) price = PricingEngine.get_distance_price(order.distance, user) order.price = price order.save_to_db() data = { 'order_id': order.id, 'available': [x for x in available_deliveries], 'closest': closest_delivery['user_id'] if available_deliveries else None, 'delivery_price': price, 'order_price': order.product_prices, } return data, 200
def delete(self, user_id): MyLogger.info("Se inhabilitó al user %d", user_id) user = FoodieUser.get_by_id(user_id) user.active = False user.save_to_db() return user.as_dict(), 200
def one_user(db_session): user_data = get_dummy_user(name='Single', surname='User', email='*****@*****.**') user = FoodieUser(id=1, **user_data) db_session.add(user) db_session.commit() return user
def get(self): available = DeliveryStatus.get_all_available() available = [x.as_dict() for x in available] for delivery in available: user = FoodieUser.get_by_id(delivery.get('user_id')) delivery.update(user.public_info()) return available, 200
def post(self): try: user_email = ForgottenPasswordSchema().load(request.get_json(force=True)) except ValidationError as e: return e.messages, 400 user = FoodieUser.get_by_email(user_email['email']) token = PasswordRecoveryToken.generate_token(user.id) send_token_to_mail(token.token, user.email, token.expiration) return token.token, 200
def post(self, post_data): user = FoodieUser.get_by_email(post_data['email']) token = post_data['token'] password = post_data['password'] if not PasswordRecoveryToken.validate_user_token(user.id, token): return 'Invalid Token', 403 else: token_obj = PasswordRecoveryToken.get_user_token(user.id) user.password = password token_obj.used = True user.save_to_db() token_obj.save_to_db() return 'Password Changed', 200
def post(self, post_data): access_token = post_data['fb_access_token'] email = facebook_get_email(access_token) if not email: # Puede que el token sea invalido return "Token invalido", 400 user = FoodieUser.get_by_email(email) if not user: return "Usuario inexistente", 404 firebase_token = post_data.get('firebase_token') if firebase_token: FirebaseToken.set_token(user.id, firebase_token) return AuthToken.get_user_token(user.id)._as_dict(), 200
def post(self, post_data): order_id = post_data.get('order_id') user_id = post_data.get('user_id') review = post_data.get('review') order = Order.get_by_id(order_id) if not (order.user_id == user_id or order.delivery_id == user_id): """ The user wanting to perform the action, is not the user nor the delivery of the order. Therefore should not be able to add a review to the order. """ return { 'user_id': ["User is not allowed to perform the action"] }, 403 if not order.has_finished(): return "Order must be finished before performing a review", 400 user = FoodieUser.get_by_id(user_id) """ El usuario puede ser tanto el `cliente` como el `delivery` de una orden, independientemente de su rol de usuario Por ejemplo, en una orde que es un favor, tanto el `cliente` como el `delivery` pueden ser usuarios. """ review_role = 'delivery' if user_id == order.user_id else 'user' other_user_id = order.delivery_id if user_id == order.user_id else order.user_id order_review = OrderReview.get_by_id(order.id) if not order_review: order_review = OrderReview.new_review(order_id=order.id, role=review_role, review=review) Reputation.add_user_review(user_id=other_user_id, review=review) else: current_review = order_review.get_role_review(review_role) if current_review is not None: return "The order has already a review", 400 else: order_review.add_user_review(review_role, review) Reputation.add_user_review(user_id=other_user_id, review=review) return 'Ok', 200
def loaded_data(db_session): # Agrego Usuarios user1 = get_dummy_user(name='User1', surname='Perez', email='*****@*****.**') user2 = get_dummy_user(name='User2', surname='Perez', email='*****@*****.**') user3 = get_dummy_user(name='User3', surname='Perez', email='*****@*****.**') deli1 = get_dummy_user(name='Deli1', surname='Perez', email='*****@*****.**', role='delivery') deli2 = get_dummy_user(name='Deli2', surname='Perez', email='*****@*****.**', role='delivery') deli3 = get_dummy_user(name='Deli3', surname='Perez', email='*****@*****.**', role='delivery') data = [user1, user2, user3, deli1, deli2, deli3] users = [FoodieUser(**d) for d in data] db_session.add_all(users) db_session.commit() # Agrego Shops shop1 = FoodieShop(**get_dummy_shop(name='Shop1')) shop2 = FoodieShop(**get_dummy_shop(name='Shop2')) shop3 = FoodieShop(**get_dummy_shop(name='Shop3')) db_session.add_all([shop1, shop2, shop3]) db_session.commit() # Agrego Productos prod1 = Product(**get_dummy_product(shop_id=1, name='prod1', price='10')) prod2 = Product(**get_dummy_product(shop_id=1, name='prod1', price='10')) prod3 = Product(**get_dummy_product(shop_id=2, name='prod1', price='10')) # El shop 3 no tiene productos db_session.add_all([prod1, prod2, prod3]) db_session.commit()
def put(self, user_id, post_data): user = FoodieUser.get_by_id(user_id) if not user: return f"User with id {user_id} was not found", 404 new_email = post_data.get('email') try: if new_email and new_email != user.email: email_not_existing(new_email) user.update_from_dict(**post_data) if user.is_delivery and not user.photo_url: return {'photo_url': ["Delivery user must have photo"]}, 400 except ValidationError as e: return e.messages, 400 user.save_to_db() return user.as_dict(), 200
def test_delivery_accept_order(mocked_order_selected_delivery, testing_app): # El delivery 4 posee una orden para aceptar r = testing_app.get('/api/orders/available/4') assert r.status_code == 200 assert r.json == [{ 'id': 1, 'shop_id': 1, 'user_id': 1, 'user_location': "-34.572259,-58.4843497", 'shop_location': 'foo', 'distance': 1500, 'favor': False, 'products': [{ 'id': 1, 'quantity': 1 }], 'address': None, 'distance_to_shop': 1000, 'total_distance': 2500, 'user_data': { 'name': 'User1', 'surname': 'Perez', 'reputation': None }, 'revenue': 377.4 # .85 * 444 }] # Acepto la orden r = testing_app.put('/api/orders/available/4', data=json.dumps({ 'status': 'accepted', 'order_id': 1 })) assert r.status_code == 200 assert r.json is True # Valido que la orden cambio de estado r = testing_app.get('/api/orders/1/status') assert r.status_code == 200 assert r.json == { 'delivery_data': { 'name': 'Deli1', 'reputation': None, 'surname': 'Perez' }, 'delivery_location': 'Fooo', 'status_id': 2, 'status': 'accepted' } testing_app.put('/api/orders/available/4', data=json.dumps({ 'status': 'in_shop', 'order_id': 1 })) testing_app.put('/api/orders/available/4', data=json.dumps({ 'status': 'out_shop', 'order_id': 1 })) testing_app.put('/api/orders/available/4', data=json.dumps({ 'status': 'delivered', 'order_id': 1 })) r = testing_app.post('/api/orders/confirm', data=json.dumps({ 'user_id': 1, 'order_id': 1 })) assert r.status_code == 200 user = FoodieUser.get_by_id(1) deli = FoodieUser.get_by_id(4) assert user.cash_balance == -444 assert deli.cash_balance == 377.4
def user_id_exists(user_id): if not FoodieUser.get_by_id(user_id): raise ValidationError(f'User {user_id} doesnt exist', field_name='user_id')
def email_exists(email): exists = FoodieUser.get_by_email(email) if not exists: raise ValidationError('Email not found')
def email_not_existing(email): exists = FoodieUser.get_by_email(email) if exists: raise ValidationError('Email already exists')
def get(self, user_id): user = FoodieUser.get_by_id(user_id) orders = Order.get_available_deliveries(user_id) return [order.data_for_delivery() for order in orders], 200