def updateUser(request_data): facebook_id = request_data["facebookId"] if UserServices.__checkUserExistance(facebook_id): UserTransactions.updateUserData(request_data) return Responses.success('Usuario actualizado correctamente', "") else: return Responses.badRequest('Usuario no registrado')
def __registerNonExistingUser(data): exp_date = UserServices.__getDateTime() UserTransactions.newUser(data["facebookId"], data["firstName"], data["lastName"], data["photoUrl"], data["email"]) token = UserServices.__generateToken(data["facebookId"], exp_date) return token
def test_new_score_as_seller(self): response = ScoreServices.createNewScore(new_score_seller) assert response["message"] == 'Calificado correctamente' assert response["status"] == 201 assert len( UserTransactions.getUserActivities( new_score_seller["facebookId"])["activities"]) != 0 assert len(UserTransactions.getUserActivities("99")) != 0
def test_update_question_answer(self): response = QuestionServices.updateQuestion(new_answer) assert response["status"] == 200 assert response["message"] == 'Pregunta actualizada satisfactoriamente' logging.debug( str(UserTransactions.getUserActivities(new_answer["facebookId"]))) assert len( UserTransactions.getUserActivities( new_answer["facebookId"])["activities"]) != 0
def test_new_question(self): response = QuestionServices.createNewQuestion(new_question) assert response["status"] == 201 assert response["message"] == 'Pregunta creada satisfactoriamente' logging.debug( str(UserTransactions.getUserActivities( new_question["facebookId"]))) assert len( UserTransactions.getUserActivities( new_question["facebookId"])["activities"]) != 0
def updateQuestion(request_data): response = QuestionTransactions.updateQuestion(request_data) if response is not None: UserTransactions.pushUserActivitiy(request_data["facebookId"], "Has respondido una pregunta") UserTransactions.pushUserActivitiy( response["userId"], "Te han respondido una pregunta") FirebaseCommunication.send_notification( response["userId"], "Recibiste una respuesta!", "") return Responses.success('Pregunta actualizada satisfactoriamente', "") else: return Responses.badRequest('Pregunta inexistente', "")
def createNewQuestion(request_data): post_data = PostTransactions.find_post_by_post_id( request_data["postId"]) if post_data is None: return Responses.badRequest('Post inexistente', "") QuestionTransactions.newQuestion(request_data) UserTransactions.pushUserActivitiy(request_data["facebookId"], "Has realizado una pregunta") UserTransactions.pushUserActivitiy(post_data["_id"]["facebookId"], "Te han realizado una pregunta") FirebaseCommunication.send_notification(post_data["_id"]["facebookId"], "Recibiste una pregunta", post_data["title"]) return Responses.created('Pregunta creada satisfactoriamente', "")
def __parseEstimation(data): tracking_data = {"userId": data["facebookId"]} post_data = PostTransactions.find_post_by_post_id(data["postId"]) user_data = UserTransactions.findUserById(data["facebookId"]) end_coordenates = GeolocationServiceCommunication.getCoordenates( data["street"], data["city"]) tracking_data["distance"] = str( SharedServerRequests.__calulateDistance(post_data["coordenates"], end_coordenates)) tracking_data["price"] = str(post_data["price"]) tracking_data["points"] = UserTransactions.get_user_points( data["facebookId"]) tracking_data["userMail"] = user_data["email"] return tracking_data
def __get_calificado(data): buy = BuyTransactions.find_buy(data["buyId"]) LOGGER.debug("buy id" + str(buy)) seller_facebook_id = PostTransactions.find_post_by_post_id(buy["postId"])["_id"]["facebookId"] buyer_facebook_id = buy["_id"]["facebookId"] if data["rol"] == "Vendedor": data["estado"] = ESTADO_COMPLETADO UserTransactions.updateUserSellPoints(seller_facebook_id) BuyTransactions.updateBuyData(data) return buyer_facebook_id else: data["estado"] = ESTADO_CALIFICADO UserTransactions.updateUserBuyPoints(buyer_facebook_id, "Efectivo") BuyTransactions.updateBuyData(data) return seller_facebook_id
def validateAuthorization(*args, **kwargs): user = UserTransactions.findUserById(request.headers.get('facebookId')) if user is None: return_data = Responses.unauthorized('FacebookId not found') return return_data["data"], return_data["status"], { 'message': return_data["message"] } token = request.headers.get('token') if token != user['token']: return_data = Responses.unauthorized('Invalid token') return return_data["data"], return_data["status"], { 'message': return_data["message"] } current_date_seconds = time.mktime( datetime.datetime.utcnow().timetuple()) exp_date_seconds = time.mktime(user['exp_date'].timetuple()) if current_date_seconds > exp_date_seconds: return_data = Responses.unauthorized('Expirated token') return return_data["data"], return_data["status"], { 'message': return_data["message"] } return function(*args, **kwargs)
def updateScore(request_data): scored_user_id = ScoreTransactions.update_score(request_data) if scored_user_id is None: LOGGER.warn("El usuario no a calificado la compra") return Responses.badRequest('Usuario sin scores para esa compra') try: score_average = ScoreTransactions.find_scored_user_average( scored_user_id) UserTransactions.updateUserScorePoints(scored_user_id, score_average) return Responses.success( 'Calificacion actualizada satisfactoriamente', "") except Exception as e: LOGGER.error("No se pudo actualizar la calificacion! Error: " + str(e)) return Responses.badRequest('Error al actualizar los puntos', "")
def get_puntos(request_data): facebook_id = request_data["facebookId"] if UserServices.__checkUserExistance(facebook_id): response = UserTransactions.get_user_points(facebook_id) return Responses.success('Puntaje obteindo correctamente', response) else: return Responses.badRequest('Usuario no registrado')
def createNewBuy(request_data): try: BuyTransactions.newBuy(request_data) except Exception: return Responses.internalServerError( 'Error en la comunicacion con el sharedServer') post_data = PostTransactions.find_post_by_post_id( request_data['postId']) FirebaseCommunication.new_chat(request_data['facebookId'], post_data) UserTransactions.pushUserActivitiy(request_data['facebookId'], "Has realizado una compra") UserTransactions.pushUserActivitiy(post_data['_id']['facebookId'], "Has realizado una venta") FirebaseCommunication.send_notification(post_data['_id']['facebookId'], "Has realizado una venta", post_data["title"]) return Responses.created('Compra creada satisfactoriamente', "")
def getActivities(request_data): facebook_id = request_data["facebookId"] if UserServices.__checkUserExistance(facebook_id): response = UserTransactions.getUserActivities( request_data["facebookId"]) return Responses.success('Actividades obtenidas correctamente', response) else: return Responses.badRequest('Usuario no registrado')
def getPost(request_data): response = PostTransactions.find_post_by_post_id( request_data["postId"]) if response is not None: response["name"] = UserTransactions.getUserName( response["_id"]["facebookId"]) return Responses.success('Post obtenidos satisfactoriamente', response) else: return Responses.badRequest('Post inexistente')
def createNewScore(request_data): if request_data["rol"] in ["Comprador", "Vendedor"]: try: scored_user_id = ScoreTransactions.create_new_score( request_data) except Exception as e: LOGGER.error("No se pudo crear la calificacion! Error: " + str(e)) return Responses.internalServerError('Error al calificar', "") if scored_user_id == "Calificado": LOGGER.warn("No se pudo crear la calificacion, ya existe") return Responses.badRequest('Ya calificado', "") if scored_user_id is None: LOGGER.warn("No se puede calificar a si mismo") return Responses.badRequest('No se puede calificar a si mismo', "") score_average = ScoreTransactions.find_scored_user_average( scored_user_id) UserTransactions.updateUserScorePoints(scored_user_id, score_average) UserTransactions.pushUserActivitiy( request_data["facebookId"], "Has calificado una publicacion") UserTransactions.pushUserActivitiy( scored_user_id, "Has sido calificado por una publicacion") FirebaseCommunication.send_notification(scored_user_id, "Has recibido una calificacion: " + \ str(request_data["value"]) + " puntos.", "") return Responses.created('Calificado correctamente', "") else: LOGGER.warn("No se pudo crear la calificacion, Rol invalido") return Responses.badRequest('Rol invalido')
def __checkUserExistance(facebook_id): user = UserTransactions.findUserById(facebook_id) return not (user is None)
def __generateToken(facebook_id, exp_date): payload = {"user": facebook_id, "exp": exp_date} token = jwt.encode(payload, secret_key) UserTransactions.updateUserToken(facebook_id, token.decode('UTF-8'), exp_date) return token.decode('UTF-8')