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 update_buy_by_tracking_id(request_data): response = BuyTransactions.update_buy_by_tracking_id(request_data) if response != "Estado Invalido": return Responses.success('Compra actualizada satisfactoriamente', "") else: return Responses.badRequest('Estado Invalido')
def get(self): """Endpoint for checking requests stats""" try: pipeline = [ { '$group': { '_id': {'route': '$route', 'method': '$method', 'day': '$day', 'hour': '$hour'}, 'totalRequests': {'$sum': 1}, 'averageTimeElapsed': {'$avg': '$time_elapsed_ms'} } }, {'$sort': { '_id.day': 1, '_id.hour': 1} } ] aware_colection = monitor_collection.with_options( codec_options=CodecOptions(tz_aware=True, tzinfo=pytz.timezone('America/Argentina/Buenos_Aires'))) cursor = aware_colection.aggregate(pipeline) data = {} for row in cursor: request_string = row['_id']['method'] + ": " + row['_id']['route'] if request_string not in data: data[request_string] = [] data[request_string].append({ 'daytime': str(row['_id']['day']) + ' - ' + str(row['_id']['hour']) + ' hs', 'avg_time_elapsed': row['averageTimeElapsed'], 'totalRequests': row['totalRequests'] }) return_data = Responses.success('Stats obtenidos satisfactoriamente', data) return return_data["data"], return_data["status"], {'message': return_data["message"]} except Exception: return_data = Responses.internalServerError('Error al obtener los stats') return return_data["data"], return_data["status"], {'message': return_data["message"]}
def getPostByUser(request_data): response = PostTransactions.find_post_by_user_id( request_data["userId"]) if response is not None: return Responses.success('Post obtenidos satisfactoriamente', response) else: return Responses.badRequest('Usuario sin Posts')
def getBuysByUser(request_data): response = BuyTransactions.findBuyByUserId(request_data["userId"]) if not response is None: return Responses.success('Compras obtenidas satisfactoriamente', response) else: return Responses.badRequest('Usuario sin Compras')
def getQuestion(request_data): response = QuestionTransactions.findQuestion( request_data["questionId"]) if not response is None: return Responses.success('Pregunta obtenida satisfactoriamente', response) else: return Responses.badRequest('Pregunta inexistente')
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 getScoreByScoredId(request_data): response = ScoreTransactions.find_score_by_scored_id( request_data["facebookId"]) if response is not None: return Responses.success( 'Calificaciones obtenidas satisfactoriamente', response) else: LOGGER.warn("El usuario no fue ninguna calificacion") return Responses.badRequest('Usuario sin scores')
def getScore(request_data): response = ScoreTransactions.find_score(request_data) if response is not None: return Responses.success( 'Calificacion obtenida satisfactoriamente', response) else: LOGGER.warn("El usuario no a calificado la compra") return Responses.badRequest( 'El usuario no a calificado dicha compra')
def getBuysBySeller(request_data): response = BuyTransactions.find_buy_by_seller_id( request_data["seller_id"]) if not response is None: return Responses.success('Compras obtenidas satisfactoriamente', response) else: return Responses.badRequest('Usuario sin Compras')
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 getBuy(request_data): response = BuyTransactions.findBuyById(request_data["buyId"]) if not response is None: #response["name"] = UserTransactions.getUserName(response["_id"]["facebookId"]) return Responses.success('Compras obtenidas satisfactoriamente', response) else: return Responses.badRequest('Compras inexistente')
def updateBuy(request_data): LOGGER.debug("Req data:" + str(request_data)) if BuyServices.__validate_buy(request_data): return Responses.badRequest('Compra inexistente') try: response = BuyTransactions.updateBuyData(request_data) return Responses.success('Compra actualizada satisfactoriamente', "") except Exception: return Responses.badRequest('Estado Invalido')
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 checkLogin(request_data): facebook_id = request_data["facebookId"] if FacebookCommunication.ValidateUser(facebook_id, request_data["token"]): if UserServices.__checkUserExistance(facebook_id): response = { 'token': UserServices.__generateToken(facebook_id, UserServices.__getDateTime()) } return Responses.success('Token generado correctamente', response) else: return Responses.badRequest('Usuario no registrado') else: return Responses.badRequest('FacebookId Invalido')
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 calculateShipping(shipping_data): try: headers = (SharedServerRequests.__auth()) request_data = SharedServerRequests.__parseEstimation( shipping_data) response = requests.post(SHARED_SERVER_URL + '/api/deliveries/estimate', headers=headers, data=json.dumps(request_data)) if response.status_code == 200: return Responses.success( 'Estimacion realizada satisfactoriamente', { "ShipmentCost": json.loads( response.text)['ShipmentCost'] }) else: return Responses.internalServerError( 'Error en la comunicacion con el Shared Server', "") except Exception: return Responses.badRequest("Direccion invalida!", "")
def get_buy_states(): return Responses.success( "Estados posibles de las compras satisfactoriamente", ResourceTransactions.get_buys_states())
def get_payments(): return Responses.success("Formas de pago obtenidas satisfactoriamente", ResourceTransactions.get_payments())
def get_categories(): return Responses.success("Categorias obtenidas satisfactoriamente", ResourceTransactions.get_categories())
def getAllQuestions(postId): response = QuestionTransactions.getQuestions(postId) return Responses.success('Preguntas obtenidas satisfactoriamente', response)
def updatePost(request_data): response = PostTransactions.update_post_data(request_data) if response is not None: return Responses.success('Post actualizado satisfactoriamente', "") else: return Responses.badRequest('Estado Invalido')
def getAllPosts(request_data): response = PostTransactions.getPosts(request_data) return Responses.success('Post obtenidos satisfactoriamente', response)