예제 #1
0
 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')
예제 #2
0
 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')
예제 #3
0
    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"]}
예제 #4
0
 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')
예제 #5
0
    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')
예제 #6
0
 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')
예제 #7
0
 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')
예제 #8
0
 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')
예제 #9
0
 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')
예제 #10
0
    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')
예제 #11
0
 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')
예제 #12
0
 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')
예제 #13
0
    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')
예제 #14
0
 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')
예제 #15
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', "")
예제 #16
0
 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')
예제 #17
0
 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!", "")
예제 #19
0
 def get_buy_states():
     return Responses.success(
         "Estados posibles de las compras satisfactoriamente",
         ResourceTransactions.get_buys_states())
예제 #20
0
 def get_payments():
     return Responses.success("Formas de pago obtenidas satisfactoriamente",
                              ResourceTransactions.get_payments())
예제 #21
0
 def get_categories():
     return Responses.success("Categorias obtenidas satisfactoriamente",
                              ResourceTransactions.get_categories())
예제 #22
0
 def getAllQuestions(postId):
     response = QuestionTransactions.getQuestions(postId)
     return Responses.success('Preguntas obtenidas satisfactoriamente',
                              response)
예제 #23
0
 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')
예제 #24
0
 def getAllPosts(request_data):
     response = PostTransactions.getPosts(request_data)
     return Responses.success('Post obtenidos satisfactoriamente', response)