Beispiel #1
0
 def delete_review(id_article):
     if flask.request.data:
         parameters = json.body_to_dic(flask.request.data)
         if "id_user" in parameters:
             security.validateAdminRole(flask.request.headers.get("Authorization"))
             common_service.get_article(id_article)
             return json.dic_to_json(service.disable_review(id_article, parameters['id_user']))
     user = security.isValidToken(flask.request.headers.get("Authorization"))
     common_service.get_article(id_article)
     common_service.get_order(flask.request.headers.get("Authorization"), id_article)
     result = service.disable_review(id_article, user['id'])
     return json.dic_to_json(result)
Beispiel #2
0
 def getScore(userId):
     try:
         security.validateAdminRole(
             flask.request.headers.get("Authorization"))
         return json.dic_to_json(crud.getScore(userId))
     except Exception as err:
         return errors.handleError(err)
Beispiel #3
0
def postPaymentsFailed(paymentId):
    """
    payment-failed : 

    @api {fanout} payments/payments-failed Payment Failed 

    @apiGroup RabbitMQ POST

    @apiDescription Postea eventos sobre pagos fallidos

    @apiExample {json} Mensaje
      {
        "type": "payment-failed",
        "exchange" : "{payments-failed}"
        "queue" : ""
        "message" : {
            "paymentId": "{paymentId}",
        }
    """
    try:
        connection = pika.BlockingConnection(
            pika.ConnectionParameters(host='localhost'))
        channel = connection.channel()
        channel.exchange_declare(exchange='payments-failed',
                                 exchange_type='fanout')
        message = {"paymentId": paymentId}
        channel.basic_publish(exchange='payments-failed',
                              routing_key='',
                              body=json.dic_to_json(message))

        connection.close()

    except Exception:
        print("Error enviando payments-failed")
Beispiel #4
0
def handleUnknown(err):
    """
    Cualquier otro error.
    err: Exception
    result json error a enviar al cliente
    """
    return json.dic_to_json({"error": "Unknown error"}), 500
Beispiel #5
0
def handleMultipleArgumentException(err):
    """
    Multiples argumentos con errores.
    err: MultipleArgumentException
    result json error a enviar al cliente
    """
    return json.dic_to_json({"messages": [{"path": k, "message": v} for k, v in err.errors.items()]}), 400
Beispiel #6
0
def handleInvalidRequest(err):
    """
    Request con errores.
    err: InvalidRequest
    result json error a enviar al cliente
    """
    return json.dic_to_json({"error": err.error}), 400
Beispiel #7
0
def handleInvalidAccessLevel(err):
    """
    Usuario no autorizado.
    err: InvalidAuth
    result json error a enviar al cliente
    """
    return json.dic_to_json({"error": "Insufficient access level"}), 401
Beispiel #8
0
def postPayments(paymentId):
    """
    payment-complete : 

    @api {fanout} payments/payment-complete Payment Complete 

    @apiGroup RabbitMQ POST

    @apiDescription Postea eventos sobre pagos a ordenes completos con exito

    @apiExample {json} Mensaje
      {
        "type": "payment-complete",
        "exchange" : "{payments}"
        "queue" : ""
        "message" : {
            "paymentId": "{paymentId}",
        }
    """
    try:
        connection = pika.BlockingConnection(
            pika.ConnectionParameters(host='localhost'))
        channel = connection.channel()
        channel.exchange_declare(exchange='payments', exchange_type='fanout')
        message = {"paymentId": paymentId}
        channel.basic_publish(exchange='payments',
                              routing_key='',
                              body=json.dic_to_json(message))

        connection.close()

    except Exception:
        print("Error posteando payment completado")
Beispiel #9
0
def send_is_article_valid(exchange, queue, type, price):

    connection = pika.BlockingConnection(
        pika.ConnectionParameters(host=config.get_rabbit_server_url())
    )

    channel = connection.channel()
    channel.exchange_declare(exchange=exchange, exchange_type='fanout')
    channel.queue_declare(queue = queue)

    article = {}
    article["articleId"] = price["article_id"]
    article["referenceId"] = price["_id"]

    message = {
        "exchange": exchange,
        "queue": queue,
        "type": type,
        "message": article
    }

    channel.basic_publish(
        exchange=exchange,
        routing_key=queue,
        body=json_serializer.dic_to_json(message)
    )
    print("RabbitMQ Catalog GET article-exist catalogId: {}, articleId: {}".format(article["referenceId"], article["articleId"]))
    connection.close()
Beispiel #10
0
def handleInvalidArgument(err):
    """
    Argumento con errores.
    err: InvalidArgument
    result json error a enviar al cliente
    """
    return json.dic_to_json({"path": err.path, "message": err.error}), 400
Beispiel #11
0
 def getPayment(paymentId):
     try:
         token = flask.request.headers.get("Authorization")
         user = security.isValidToken(token)
         return json.dic_to_json(payments_crud.getPayment(paymentId))
     except Exception as err:
         return errors.handleError(err)
Beispiel #12
0
def handleUnauthorized(err):
    """
    Usuario no autorizado.
    err: InvalidAuth
    result json error a enviar al cliente
    """
    return json.dic_to_json({"error": "Unauthorized"}), 401
Beispiel #13
0
 def delete_score(id_article):
     user = security.isValidToken(
         flask.request.headers.get("Authorization"))
     common_service.get_article(id_article)
     common_service.get_order(flask.request.headers.get("Authorization"),
                              id_article)
     result = service.disable_score(id_article, user['id'])
     return json.dic_to_json(result)
Beispiel #14
0
 def create_review(id_article):
     user = security.isValidToken(flask.request.headers.get("Authorization"))
     parameters = json.body_to_dic(flask.request.data)
     parameters.update({'id_article': id_article})
     parameters = rest_validator.validateAddorEditReview(parameters)
     common_service.get_article(id_article)
     common_service.get_order(flask.request.headers.get("Authorization"), id_article)
     result = service.add_review(parameters, user["id"])
     return json.dic_to_json(result)
Beispiel #15
0
    def deleteLevel(levelId):
        try:
            security.validateAdminRole(
                flask.request.headers.get("Authorization"))
            result = crud.deleteLevel(levelId)

            return json.dic_to_json(result)
        except Exception as err:
            return errors.handleError(err)
Beispiel #16
0
 def get_discounts_by_article_id(article_id):
     try:
         offset = int(flask.request.args.get(
             'offset')) if flask.request.args.get('offset') else MAX_OFFSET
         page = int(flask.request.args.get(
             'page')) if flask.request.args.get('page') else PAGE
         return json.dic_to_json(
             crud.get_discounts_by_article_id(article_id, offset, page))
     except Exception as err:
         return errors.handleError(err)
Beispiel #17
0
    def modifyLevel(levelId):
        try:
            security.validateAdminRole(
                flask.request.headers.get("Authorization"))
            params = json.body_to_dic(flask.request.data)
            result = crud.modifyLevel(levelId, params)

            return json.dic_to_json(result)
        except Exception as err:
            return errors.handleError(err)
Beispiel #18
0
def sendArticleData(exchange, queue, referenceId, articleId, valid, stock,
                    price):
    """
    Envía eventos al Cart

    article-data : Es una validación solicitada por Cart para validar si el articulo puede incluirse en el cart


    @api {direct} cart/article-data Validación de Articulos

    @apiGroup RabbitMQ POST

    @apiDescription Enviá de mensajes article-exist desde cart. Valida articulos

    @apiSuccessExample {json} Mensaje
      {
        "type": "article-exist",
        "message" : {
            "referenceId": "{referenceId}",
            "articleId": "{articleId}",
            "valid": True|False,
            "stock": {stock},
            "price": {price}
        }
      }
    """
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(host=config.get_rabbit_server_url()))
    channel = connection.channel()

    channel.exchange_declare(exchange=exchange, exchange_type='direct')

    channel.queue_declare(queue=queue)

    message = {
        "type": "article-data",
        "message": {
            "referenceId": referenceId,
            "articleId": articleId,
            "valid": valid,
            "stock": stock,
            "price": price,
        }
    }

    channel.basic_publish(exchange=exchange,
                          routing_key=queue,
                          body=json.dic_to_json(message))

    connection.close()

    print(
        "RabbitMQ Cart POST article-data catalogId:%r , articleId:%r , valid:%r",
        referenceId, articleId, valid)
Beispiel #19
0
 def cancelPayment(paymentId):
     try:
         security.isValidToken(flask.request.headers.get("Authorization"))
         params = json.body_to_dic(flask.request.data)
         params = restValidator.validateCancelPaymentParams(params)
         params['status'] = 'cancelled'
         # aca hago el crud yo pero tendria que hacerse cuando llegue la notificacion de mp
         # llamo a mp y cancelo
         updated_payment = payments_crud.addStatus(paymentId, params)
         res = payments_crud.updatePayment(paymentId, updated_payment)
         return json.dic_to_json(res)
     except Exception as err:
         return errors.handleError(err)
Beispiel #20
0
    def updateArticle(articleId):
        try:
            security.validateAdminRole(flask.request.headers.get("Authorization"))

            params = json.body_to_dic(flask.request.data)

            params = restValidator.validateEditArticleParams(articleId, params)

            result = crud.updateArticle(articleId, params)

            return json.dic_to_json(result)
        except Exception as err:
            return errors.handleError(err)
Beispiel #21
0
    def add_discount():
        try:
            security.validateAdminRole(
                flask.request.headers.get("Authorization"))
            token = flask.request.headers.get("Authorization")
            params = json.body_to_dic(flask.request.data)

            validated_discount = restValidator.validateAddDiscountParams(
                params)

            result = crud.add_discount(validated_discount)

            return json.dic_to_json(result)
        except Exception as err:
            return errors.handleError(err)
Beispiel #22
0
def get_article(id_article):
    conn = http.client.HTTPConnection(
        socket.gethostbyname(config.get_catalog_server_url()),
        config.get_catalog_server_port(),
    )

    try:
        conn.request("GET", "/v1/articles/{}".format(id_article), {})
        response = conn.getresponse()
        if response.status != 200 or (not json.body_to_dic(
                response.read().decode('utf-8'))['enabled']):
            raise errors.InvalidArgument('id_article', 'Invalido')
        return json.dic_to_json(response.read().decode('utf-8'))
    except Exception:
        raise Exception
Beispiel #23
0
    def add_price():
        try:
            security.validateAdminRole(
                flask.request.headers.get("Authorization"))
            token = flask.request.headers.get("Authorization")
            params = json.body_to_dic(flask.request.data)
            responses = []

            for price in params:
                validated_price = restValidator.validateAddPriceParams(price)
                result = crud.add_price(validated_price)
                responses.append(result.copy())

            return json.dic_to_json(responses)
        except Exception as err:
            return errors.handleError(err)
Beispiel #24
0
    def addPayment():
        try:
            # TODO Duda : Como sacar las busquedas order y user en otro lado? se puede hacer?
            token = flask.request.headers.get("Authorization")
            user = security.isValidToken(token)
            params = json.body_to_dic(flask.request.data)
            params = restValidator.validateAddPaymentParams(params)

            order = orders.getOrder(params['id_order'], token)

            # se comunica con un servicio externo
            result = payments_crud.addPayment(params, order, user)

            return json.dic_to_json(result)
        except Exception as err:
            return errors.handleError(err)
Beispiel #25
0
def sendLevelNotice(userId, levelId):
    print("entra a rabbit_service")
    """
    Envía notificacion a Auth (User si existise) para informar que hay un cambio en el nivel

    level-data : Es una notificación al perfil del usuario informando el estado de su puntaje y su estado actual


    @api {direct} rewards/level-data Informar Cambio de Nivel

    @apiGroup RabbitMQ POST

    @apiDescription Enviá de mensajes level-updated. Informa el Nivel del Usuario

    @apiSuccessExample {json} Mensaje
      {
        "type": "level-updated",
        "message" : {
            "userId": "{userId}",
            "levelId": "{levelId}"
        }
      }
    """
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(host=config.get_rabbit_server_url()))
    channel = connection.channel()
    exchange = "rewards"
    channel.exchange_declare(exchange="rewards", exchange_type='direct')
    result = channel.queue_declare('', exclusive=True)
    queue_name = result.method.queue
    queue = queue_name
    message = {
        "type": "level-updated",
        "message": {
            "userId": userId,
            "levelId": levelId
        }
    }

    channel.basic_publish(exchange=exchange,
                          routing_key="level-update",
                          body=json.dic_to_json(message))

    connection.close()

    print("RabbitMQ Cart POST level-updated uderId:%r , levelId:%r ")
Beispiel #26
0
def send_new_score(id_article, score):
    """
    Envía eventos cuando hay un nuevo score para un artículo

    @api {fanout} score/new_score Nuevo Score

    @apiGroup RabbitMQ POST

    @apiDescription Enviá mensajes de nuevo score

    @apiSuccessExample {json} Mensaje
      {
        "type": "new_score",
        "message" : {
            "id_article": "{id del articulo}",
            "score": {score promedio del articulo}
        }
      }
    """
    exchange = "score"
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(host=config.get_rabbit_server_url()))
    channel = connection.channel()

    channel.exchange_declare(exchange=exchange, exchange_type='fanout')

    message = {
        "type": "new_score",
        "message": {
            "id_article": id_article,
            "score": score,
        }
    }

    validator.validateSchema(MSG_NEW_SCORE, message)

    channel.basic_publish(exchange=exchange,
                          routing_key='',
                          body=json.dic_to_json(message))

    connection.close()

    print("RabbitMQ Cart POST new_score id_article:%r", id_article)
Beispiel #27
0
def postTransactions(message):
    """
    Postea eventos de notificacion acerca de transacciones de pagos

    @api {fanout} transactions/transaction_task_queue Post New Transaction

    @apiGroup RabbitMQ POST

    @apiDescription Postea transacciones recibidas a procesar 

    @apiExample {json} Mensaje
      {
        "type": "transaction",
        "exchange" : "{''}"
        "queue" : ""
        "message" : {
            "amount":{Float},
            "id_payment":{String},
            "status":{String},
            "external_reference":{String}
        }
    """

    QUEUE = "transaction_task_queue"

    try:
        connection = pika.BlockingConnection(
            pika.ConnectionParameters(host=config.get_rabbit_server_url()))
        channel = connection.channel()

        channel.queue_declare(queue=QUEUE, durable=False)

        channel.basic_publish(exchange='',
                              routing_key=QUEUE,
                              body=json.dic_to_json(message),
                              properties=pika.BasicProperties(delivery_mode=2))

        connection.close()

    except Exception as err:
        print(err)
        print("Error enviando mensaje a " + QUEUE)
Beispiel #28
0
def send_new_discount(exchange, queue, type, discounts):

    connection = pika.BlockingConnection(pika.ConnectionParameters(host=config.get_rabbit_server_url()))
    channel = connection.channel()

    channel.exchange_declare(exchange=exchange, exchange_type='fanout')
    channel.queue_declare(queue = queue)

    message = {
        "type": type,
        "message": discounts
    }

    channel.basic_publish(
        exchange=exchange,
        routing_key=queue,
        body=json_serializer.dic_to_json(message)
    )

    connection.close()
Beispiel #29
0
def sendStats():

    EXCHANGE = "stats"
    QUEUE = "stats"
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(host=config.get_rabbit_server_url()))
    channel = connection.channel()

    channel.exchange_declare(exchange=EXCHANGE, exchange_type='topic')

    channel.queue_declare(queue=QUEUE)

    channel.queue_bind(exchange=EXCHANGE, queue=QUEUE)

    message = service.sendRabbit()

    channel.basic_publish(exchange=EXCHANGE,
                          routing_key=QUEUE,
                          body=json.dic_to_json(message))

    print("MENSAJE ENVIADO a la cola de stats")

    connection.close()
Beispiel #30
0
def send_msg_delete_article(articleId):
    """
    Envía eventos a category
    """
    """
    Delete_article : Es un mensaje que avisa a category de la eliminación de un artículo.
    @api {direct} category/mensaje de eliminación de artículos

    @apiGroup RabbitMQ POST

    @apiDescription Enviá de mensajes Delete_article

    @apiSuccessExample {json} Mensaje
      {
        "type": "article-exist",
        "message" : {
            "articleId": "{articleId}",
                    
      }
    """

    connection = pika.BlockingConnection(
        pika.ConnectionParameters(host=config.get_rabbit_server_url()))
    channel = connection.channel()
    channel.exchange_declare(exchange='category', exchange_type='direct')
    channel.queue_declare(queue='category')
    message = {
        "type": "Delete_article",
        "message": {
            "articleId": articleId,
        }
    }
    channel.basic_publish(exchange='category',
                          routing_key='category',
                          body=json.dic_to_json(message))
    print("RabbitMQ Category DELETE article , articleId:%r", articleId)
    connection.close()