Пример #1
0
def addStatus(paymentId, params):
    '''
    Crea un nuevo objeto payment_status y lo agrega al payment especificado
    param paymentId : string ObjectId
    param params : dict<propiedad, valor> 
    return: dict<propiedad, valor> Payment    
    '''
    payment = getPayment(paymentId)
    if payment['total_paid_amount'] != 0:
        raise errors.InvalidRequest('Payment cannot be cancelled')
    for status in payment['payment_status']:
        if status['status'] == 'cancelled':
            raise errors.InvalidRequest('Payment cannot be cancelled')

    status = schema.new_payment_status()
    status.update(params)

    payment['payment_status'].append(status)

    return payment
Пример #2
0
def searchCategory(text):
    """
    Busca category por nombre o descripción.\n
    test string Texto a buscar
    """
    """
    @api {get} /v1/category/search/: Buscar Categoría Por Criterio
    @apiName Buscar Categoría Por Criterio
    @apiGroup Categorias
    @apiDescription Busca categoría por nombre o descripción

    @apiSuccessExample {json} Respuesta
        HTTP/1.1 200 OK
        [
            {
                "_id": "{id de categoría}"
                "nameCategory": "{nombre de la categoría}",
                "categoryParent": "{id de la categoría padre}",
                "isParent": "{indica si la categoria tiene categorías hijas o subcategoría}",
                "articlesCategory": "{lista de los artículos en categoría}",
                "subCategory": "{lista de las subCategorías que tiene la categoría}",
                "updated": "{fecha ultima actualización}",
                "creation": "{fecha creación}",
                "valido": "{activo}"
            },

            ...
        ]

    @apiUse Errors
    """
    try:
        regx = re.compile(text, re.IGNORECASE)
        results = []

        cursor = db.category.find({
            "$and": [{
                "validation": True
            }, {
                "$or": [{
                    "nameCategory": regx
                }, {
                    "categoryParent": regx
                }]
            }]
        })
        for doc in cursor:
            results.append(doc)
        return results
    except Exception:
        raise error.InvalidRequest("Invalid search criterio")
Пример #3
0
def get_order(token, id_article):
    conn = http.client.HTTPConnection(
        socket.gethostbyname(config.get_order_server_url()),
        config.get_order_server_port())

    try:
        headers = {"Authorization".encode("utf-8"): token.encode("utf-8")}

        conn.request("GET", "/v1/orders", {}, headers)
        response = conn.getresponse()
    except Exception:
        raise Exception

    if response.status == 200:
        for obj in json.body_to_dic(response.read().decode('utf-8')):
            if obj['status'] == 'PAYMENT_DEFINED':
                order = get_specific_order(token, obj['id'], id_article)
                if order != "":
                    return order
        raise errors.InvalidRequest(
            'No existen ordenes pagadas para este articulo')
    else:
        raise errors.InvalidRequest("Invalid Request")
Пример #4
0
def disable_review(id_article, id_user):
    """
    @api {delete} /v1/reviews/<string:id_article> Borrar Review
    @apiName Borrar Review
    @apiGroup Reviews

    @apiDescription Le permite a un usuario borrar su propia review de un artículo. Si el usuario es admin, puede mandar el id de otro usuario en el body para borrar la review de dicho usuario

    @apiUse AuthHeader

    @apiExample {json} Body
        {
            "id_user": "******"
        }

    @apiSuccessExample {json} Respuesta
        HTTP/1.1 200 OK
        {
            "deleted": true
        }

    @apiUse Errors

    @apiErrorExample 403 Forbidden
            HTTP/1.1 401 Forbidden
            {
                "error" : "{Motivo del error}"
            }

    """

    result = db.review.find_one({
        "id_article": id_article,
        "id_user": id_user,
        "active": True
    })
    if not result:
        raise error.InvalidRequest("No hay reviews activas para este producto")
    result["active"] = False
    result["updated"] = datetime.datetime.utcnow()

    schema.validate_schema(result)

    id_review = result['_id']
    del result['_id']
    r = db.review.replace_one({'_id': bson.ObjectId(id_review)}, result)

    return {"deleted": True}
Пример #5
0
def calculate_score(id_article):
    r = [
        score for score in db.score.find({
            'id_article': id_article,
            'active': True
        })
    ]
    if not r:
        raise errors.InvalidRequest(
            "Nadie le ha dado un score a este articulo")

    count = 0
    accum = 0
    for item in r:
        accum += item['value']
        count += 1

    return accum / count
Пример #6
0
def get_specific_order(token, id_order, id_article):
    headers = {"Authorization".encode("utf-8"): token.encode("utf-8")}
    conn = http.client.HTTPConnection(
        socket.gethostbyname(config.get_order_server_url()),
        config.get_order_server_port())

    try:
        conn.request("GET", "/v1/orders/{}".format(id_order), {}, headers)
        response = conn.getresponse()
        if response.status != 200:
            raise errors.InvalidRequest('No existe una orden con ese id')
        else:
            order = json.body_to_dic(response.read().decode('utf-8'))
            for article in order['articles']:
                if article['id'] == id_article:
                    return order
            return ""
    except Exception:
        raise Exception
Пример #7
0
def get_article_reviews(id_article):
    """
        @api {get} /v1/reviews/<string:id_article> Ver Reviews de un Artículo
        @apiName Ver Reviews de un Artículo
        @apiGroup Reviews

        @apiUse AuthHeader

        @apiSuccessExample {json} Respuesta
            HTTP/1.1 200 OK
            [
                {
                    "_id": "{id del review}",
                    "id_article": "{id del artículo}",
                    "id_user": "******",
                    "title": "{título del review}",
                    "description": "{comentario del review}",
                    "updated": {fecha ultima actualización},
                    "created": {fecha creación}
                },...
            ]

        @apiUse Errors

        """

    result = [
        article for article in db.review.find({
            "id_article": id_article,
            'active': True
        })
    ]
    if not result:
        raise error.InvalidRequest("No hay reviews activas para este producto")

    for f in result:
        del f['active']

    return result
Пример #8
0
def disable_score(id_article, id_user):
    """
        @api {delete} /v1/scores/<string:id_article> Borrar Score
        @apiName Borrar Score
        @apiGroup Scores

        @apiUse AuthHeader

        @apiSuccessExample {json} Respuesta
            HTTP/1.1 200 OK
            {
                "deleted": true
            }

        @apiUse Errors

    """

    r = db.score.find_one({
        'id_user': id_user,
        'id_article': id_article,
        'active': True
    })
    if r:
        r.update({"active": False, "updated": datetime.datetime.utcnow()})
        db.score.replace_one(
            {
                'id_user': id_user,
                'id_article': id_article,
                'active': True
            }, r)

        rabbit.send_new_score(id_article, calculate_score(id_article))

        return {"deleted": True}
    else:
        raise errors.InvalidRequest(
            "No existe un score activo para este articulo")