Exemple #1
0
def getArticle(articleId):
    """
    Obtiene un articulo. \n
    articleId: string ObjectId\n
    return dict<propiedad, valor> Articulo\n
    """
    """
    @api {get} /v1/articles/:articleId Buscar Artículo
    @apiName Buscar Artículo
    @apiGroup Articulos

    @apiSuccessExample {json} Respuesta
        HTTP/1.1 200 OK
        {
            "_id": "{id de articulo}"
            "name": "{nombre del articulo}",
            "description": "{descripción del articulo}",
            "image": "{id de imagen}",
            "price": {precio actual},
            "stock": {stock actual}
            "updated": {fecha ultima actualización}
            "created": {fecha creación}
            "enabled": {activo}
        }

    @apiUse Errors

    """
    try:
        result = db.articles.find_one({"_id": bson.ObjectId(articleId)})
        if (not result):
            raise error.InvalidArgument("_id", "Document does not exists")
        return result
    except Exception:
        raise error.InvalidArgument("_id", "Invalid object id")
def increaseStock(articleId, quantity):
    """
    Registra una compra de stock para un articulo.
    Esto significa que se va a incrementar el stock del articulo en la cantidad indicada.
    articleId: string ObjectId del articulo
    quantity: int Cantidad a incrementar
    """

    if (not isinstance(quantity, numbers.Integral) or quantity <= 0):
        raise errors.InvalidArgument("quantity", "Invalid quantity")

    result = db.articles.find_one_and_update(
        {"$and": [{
            '_id': bson.ObjectId(articleId)
        }, {
            'enabled': True
        }]}, {'$inc': {
            'stock': quantity
        }},
        return_document=pymongo.ReturnDocument.AFTER)

    if (not result):
        raise errors.InvalidArgument("quantity", "Invalid quantity")

    return result
Exemple #3
0
def getCategory(categoryId):
    try:
        result = db.category.find_one({"_id": bson.ObjectId(categoryId)})
        if (not result):
            raise error.InvalidArgument("_id", "Document does not exists")
        return result
    except Exception:
        raise error.InvalidArgument("_id", "Invalid object id")
Exemple #4
0
def getPayment(paymentId):
    '''
    Obtiene un payment con id = paymentId
    paymentId : string ObjectId
    return dict(propiedad, valor) Payment
    '''
    try:
        result = db.payments.find_one({'_id': bson.ObjectId(paymentId)})
        if (not result):
            raise errors.InvalidArgument('_id', 'Payment does not exist')
        return result
    except Exception:
        raise errors.InvalidArgument('_id', 'Invalid object id')
def getTransactions(paymentId):
    '''
    Obtiene todas las transacciones de un payment con id = paymentId
    paymentId : string ObjectId
    return [dict(propiedad, valor)] Transaction
    '''
    '''
    
    @api {get} /v1/payments/:paymentId/transactions Get Transactions
    @apiName Get Transactions
    @apiGroup Payments

    @apiSuccessExample {json} Response
        HTTP/1.1 200 OK
        {
            "paymentId": "{id del pago}"
        }
        @apiUse Errors
    '''
    try:
        results = []
        cursor = db.transactions.find({'id_payment': paymentId})
        for doc in cursor:
            results.append(doc)
        return results
    except Exception:
        raise errors.InvalidArgument('id_payment', 'Invalid object id')
Exemple #6
0
def validateEditScoreParams(userId, params):
    """
    Valida los parametros para actualizar un objeto.\n
    params: dict<action, valor> Score
    """
    if (not userId):
        raise error.InvalidArgument("_id", "Inválido")
Exemple #7
0
def updateValuePoint(params):
    """
    Modificar valor del puntaje. \n
    params: dict<propiedad, valor> Valor Puntaje\n
    return dict<propiedad, valor> Valor Puntaje\n
    """
    """
    @api {post} /v1/rewards/update-points-value Modificar Valor de Puntaje
    @apiName Valor de Puntaje
    @apiGroup Puntaje

    @apiUse AuthHeader

    @apiSuccessExample {json} Respuesta
        HTTP/1.1 200 OK
        {
            “pointValue” : “{pointValue}”
        }

    @apiUse Errors

    """
    try:
        pointValue = int(params['pointValue'])
        if (pointValue < 0):
            raise error.InvalidArgument('pointValue',
                                        'pointValue cannot be negative')
        db.scores.find_one_and_update({'name': 'cotizacion'},
                                      {'$set': {
                                          'pointValue': pointValue
                                      }})
        return "Points value updated"
    except Exception as err:
        raise err
Exemple #8
0
def manageScore(userID, params):
    """
    Gestionar puntaje. \n
    userId: string ObjectId\n
    params: dict<propiedad, valor> Usuario\n
    return dict<propiedad, valor> Usuario\n
    """
    """
    @api {post} /v1/rewards/:userId/manage Gestionar Puntaje
    @apiName Gestionar Puntaje
    @apiGroup Puntaje

    @apiUse AuthHeader

    @apiSuccessExample {json} Respuesta
        HTTP/1.1 200 OK
        {
            “action” : “SUMAR|RESTAR”,
            “valor” : “{valor}” 

        }

    @apiUse Errors
    
    """
    try:
        rawresults = db.scores.find_one({"_id": bson.ObjectId(userID)})
        if (params["action"] == "SUMAR"):
            updatedValue = int(rawresults['score']) + int(params['valor'])
        else:
            if (params["action"] == "RESTAR"):
                if (int(rawresults['score']) - int(params['valor']) < 0):
                    raise error.InvalidArgument('score', 'Value not valid')
                updatedValue = int(rawresults['score']) - int(params['valor'])
            else:
                raise error.InvalidArgument('action', 'Action not valid')
        if (not rawresults):
            raise error.InvalidArgument("_id", "Document does not exists")
        db.scores.find_one_and_update({'_id': bson.ObjectId(userID)},
                                      {'$set': {
                                          'score': int(updatedValue)
                                      }})
        checkLevel(userID)
        return str(updatedValue)
    except Exception as err:
        raise err
def validateEditPaymentParams(paymentId, params):
    """
    Valida los parametros para cancelar un payment.\n
    params: dict<propiedad, valor> Article
    """
    if (not paymentId):
        raise error.InvalidArgument("_id", "Invalido")

    return schemaValidator.validateAndClean(PAYMENT_CANCEL_SCHEMA, params)
def validateEditArticleParams(articleId, params):
    """
    Valida los parametros para actualizar un objeto.\n
    params: dict<propiedad, valor> Article
    """
    if (not articleId):
        raise error.InvalidArgument("_id", "Inválido")

    return schemaValidator.validateAndClean(ARTICLE_UPDATE_SCHEMA, params)
def validateAddArticleParams(params):
    """
    Valida los parametros para crear un objeto.\n
    params: dict<propiedad, valor> Article
    """
    if ("_id" in params):
        raise error.InvalidArgument("_id", "Inválido")

    return schemaValidator.validateAndClean(ARTICLE_UPDATE_SCHEMA, params)
Exemple #12
0
def validateEditCategoryParams(categoryId, params):
    """
    Valida los parametros para actualizar un objeto.\n
    params: dict<propiedad, valor> Article
    """
    if (not categoryId):
        raise error.InvalidArgument("_id", "Inválido")

    return schemaValidator.validateAndClean(CATEGORY_UPDATE_SCHEMA, params)
Exemple #13
0
def validateAddCategoryParams(params):
    """
    valida los parametros para crear un objeto cateogría.\n
    params:dict<propiedad, valor> Category
    """
    if ("_id" in params):
        raise error.InvalidArgument("_id", "Inválido")

    return schemaValidator.validateAndClean(CATEGORY_UPDATE_SCHEMA, params)
def validateAddorEditScore(params):
    """
    Valida los parametros para crear un objeto.\n
    params: dict<propiedad, valor> Review
    """
    if ("_id" in params):
        raise error.InvalidArgument("_id", "Inválido")

    return schemaValidator.validateAndClean(SCORE_ADD_UPDATE_SCHEMA, params)
Exemple #15
0
def getScore(userId):
    """
    Consultar puntaje. \n
    userId: string ObjectId\n
    params: dict<propiedad, valor> Usuario\n
    return dict<propiedad, valor> Usuario\n
    """
    """
    @api {get} /v1/rewards/:userId Consultar Puntaje
    @apiName Consultar Puntaje
    @apiGroup Puntaje

    @apiUse AuthHeader

    @apiSuccessExample {json} Respuesta
        HTTP/1.1 200 OK
        {
            "_id":":userId"
            “score” : “{score}”,
            “levelName” : “{levelName}” 
        }

    @apiUse Errors

    """
    try:

        result = db.scores.find_one({"_id": bson.ObjectId(userId)})
        levelId = result["level"]
        level = db.levels.find_one({"_id": bson.ObjectId(levelId)})
        resultReady = {
            "_id": userId,
            "score": result["score"],
            "levelName": level["levelName"]
        }
        if (not result):
            raise error.InvalidArgument("_id", "Document does not exists")
        return resultReady

    except Exception:
        raise error.InvalidArgument("_id", "Invalid object id")
Exemple #16
0
def get_price(article_id):
    """
    Return a price. \n
    articleId: string ObjectId\n
    return dict<key, value> Price\n
    """
    """
    @api {get} /v1/pricing/:article_id Get Price
    @apiName Get Price
    @apiGroup Price

    @apiSuccessExample {json} Response
        HTTP/1.1 200 OK
        {
            "price_id": "{Price Id}"
            "created": {Creation Date}
            "state": {Price State}
            "max_price": {Max Price}
            "min_price": {Min Price}
            "price": {Current price},
            "price_currency": {Price Currency}
            "formated_price": {Formated Price}
            "article_id": "{Article Id}"
        }

    @apiUse Errors
    """
    try:
        result = db.prices.find({"article_id": article_id}).sort([('_id', -1)]).limit(1)
        response = {}

        for res in result:
            if res['state'] == ACTIVE:
                response = res

        if (not result):
            raise errors.InvalidArgument("_id", "Document does not exists")
        return response
    except Exception:
        raise errors.InvalidArgument("_id", "Invalid object id")
Exemple #17
0
def get_discount(discount_id):
    """
    Return a price. \n
    articleId: string ObjectId\n
    return dict<key, value> Price\n
    """
    """
    @api {get} /v1/pricing/:article_id Get Price
    @apiName Get Price
    @apiGroup Price

    @apiSuccessExample {json} Response
        HTTP/1.1 200 OK
        {
            “discount_id”: “{ID del descuento}”,
            “discount_name”: “{Nombre del descuento}”,
            “discount_value”: “{Porcentaje de descuento}”,
            “discount_code”: “{Codigo de descuento}”,
            “visibility”: “{Si es publico, privado, etc}”,
            “validFrom”: “{Fecha de inicio de validez}”,
            “validTo”: “{Fecha de fin de validez}”,
            created: “{Fecha de creacion}”,
        }

    @apiUse Errors
    """
    try:
        results = db.discounts.find({"_id": bson.ObjectId(discount_id)})

        for result in results:
            response = result

        if (not result):
            raise errors.InvalidArgument("_id", "Document does not exists")
        return response
    except Exception:
        raise errors.InvalidArgument("_id", "Invalid object id")
Exemple #18
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
def getOrder(orderId, authKey):
    """
    Obtiene el order desde el servicio orders
    orderId: string id de order enviado por el cliente
    authKey: string El header Authorization enviado por el cliente
    return dict<property, value> Order
    """
    headers = {"Authorization".encode("utf-8"): authKey.encode("utf-8")}
    conn = http.client.HTTPConnection(
        socket.gethostbyname(config.get_orders_server_url()),
        config.get_orders_server_port(),
    )

    conn.request("GET", "/v1/orders/"+orderId,{}, headers)
    response = conn.getresponse()
    if (response.status != 200):
        raise errors.InvalidAuth()

    result = json.body_to_dic(response.read().decode('utf-8'))
    if result == None:
        raise errors.InvalidArgument('orderId', 'No order with that id')
    # for res in result:
        # if orderId == res['id']:
    return result
Exemple #20
0
def validateCategoryExist(categoryId):
    category = cud.getCategory(categoryId)
    if ("valido" not in category or not category["valido"]):
        raise error.InvalidArgument("id", "Inválido")
def validateCurrency(currency):
    '''
    Valida que la denominacion solicitada pertenezca a las que maneja el servicio
    '''
    if (currency not in VALID_CURRENCIES):
        raise error.InvalidArgument("currency", "Invalida")
def validateArticleExist(articleId):
    article = crud.getArticle(articleId)
    if ("enabled" not in article or not article["enabled"]):
        raise error.InvalidArgument("_id", "Inválido")
def validateAddPaymentParams(params):
    if ("_id" in params):
        raise error.InvalidArgument("_id", "Inválido")
    res = schemaValidator.validateAndClean(PAYMENT_ADD_SCHEMA, params)
    validateCurrency(res['payment_preference']['currency'])
    return res
def validateAddDiscountParams(params):
    if ("_id" in params):
        raise errors.InvalidArgument("_id", "Inválido")

    return schema_validator.validateAndClean(DISCOUNT_VALID_SCHEMA, params)
def validateEditDiscountParams(discount_id, params):
    if (not discount_id):
        raise errors.InvalidArgument("_id", "Inválido")

    return schema_validator.validateAndClean(DISCOUNT_VALID_SCHEMA, params)
Exemple #26
0
def get_discounts_by_article_id(article_id, offset, page):
    """
    Return a discount. \n
    articleId: string ObjectId\n
    offset: int
    """
    """
    @api {get} /v1/pricing/:article_id Discount Price
    @apiName Get Discount
    @apiGroup Discount

    @apiSuccessExample {json} Response
        HTTP/1.1 200 OK
        {
        "pagination": {
            "object_count": “{Numero de objetos en todas las paginas}”,
            "page_count": “{Numero de total de paginas}”,
            "page_size": “{Numero maximo de objetos en una response}”,
            "has_more_items": “{Si se puede seguir pidiendo valores a la API}”,
            "page_number": “{Numero de pagina actual}”,
            "article_id": "{ID del producto}"
            "discounts": [
            {
                “id_discount”: “{ID del descuento}”,
                “discount_name”: “{Nombre del descuento}”,
                “discount_value”: “{Porcentaje de descuento}”,
                “discount_code”: “{Codigo de descuento}”,
                “visibility”: “{Si es publico, privado, etc}”,
                “validFrom”: “{Fecha de inicio de validez}”,
                “validTo”: “{Fecha de fin de validez}”,
            }, ….
            ]
        }
    @apiUse Errors
    """
    try:
        offset, page = validate_offset_page(offset, page)

        response = {}
        response['pagination'] = {}
        response['pagination']['object_count'] = db.discounts.find({"article_id": article_id}).count()
        response['pagination']['page_count'] = round(response['pagination']['object_count'] / page)
        response['pagination']['has_more_items'] = 'False'

        if response['pagination']['object_count'] > offset:
            response['pagination']['page_size'] = offset
            response['pagination']['has_more_items'] = 'True'

        response['pagination']['page_number'] = page
        response['pagination']['article_id'] = article_id
        response['pagination']['discounts'] = []

        results = db.discounts.find({"article_id": article_id}).skip(offset * (page - 1)).limit(offset)

        if (not results):
            raise errors.InvalidArgument("_id", "Document does not exists")

        for result in results:
            discount = {}
            discount['id_discount'] = str(result['_id'])
            discount['discount_name'] = result['discount_name']
            discount['discount_value'] = result['discount_value']
            discount['discount_code'] = result['discount_code']
            discount['visibility'] = result['visibility']
            discount['discount_value'] = result['discount_value']
            discount['validFrom'] = result['validFrom']
            discount['validTo'] = result['validTo']

            response['pagination']['discounts'].append(discount)

        return response

    except Exception:
        raise errors.InvalidArgument("article_id", "Invalid object id")
Exemple #27
0
def validateAddPriceParams(params):
    if ("_id" in params):
        raise errors.InvalidArgument("_id", "Inválido")

    return schema_validator.validateAndClean(PRICE_ADD_SCHEMA, params)
Exemple #28
0
def validateEditPriceParams(priceId, params):
    if (not priceId):
        raise errors.InvalidArgument("_id", "Inválido")

    return schema_validator.validateAndClean(PRICE_UPDATE_SCHEMA, params)
Exemple #29
0
def get_price_history(article_id, offset, page):
    """
    Return a all prices of an article. \n
    articleId: string ObjectId\n
    return list(dict<key, value>) Price\n
    """
    """
    @api {get} /v1/pricing/:article_id Get Price History
    @apiName Get Price History
    @apiGroup Price

    @apiSuccessExample {json} Response
        HTTP/1.1 200 OK
        {
        "pagination": {
            "object_count": “{Numero de objetos en todas las paginas}”,
            "page_count": “{Numero de total de paginas}”,
            "page_size": “{Numero maximo de objetos en una response}”,
            "has_more_items": “{Si se puede seguir pidiendo valores a la API}”,
            "page_number": “{Numero de pagina actual}”,
            "article_id": "{ID del producto}"
            "price_schema": [
            {
                "_id": "{Price Id}"
                "created": {Creation Date}
                "state": {Price State}
                "max_price": {Max Price}
                "min_price": {Min Price}
                "price": {Current price},
                "price_currency": {Price Currency}
                "formated_price": {Formated Price}
            }, ….
            ]
        }
    @apiUse Errors
    """
    try:
        offset, page = validate_offset_page(offset, page)

        response = {}
        response['pagination'] = {}
        response['pagination']['object_count'] = db.prices.find({"article_id": article_id}).count()
        response['pagination']['page_count'] = round(response['pagination']['object_count'] / page)
        response['pagination']['has_more_items'] = 'False'

        if response['pagination']['object_count'] > offset:
            response['pagination']['page_size'] = offset
            response['pagination']['has_more_items'] = 'True'

        response['pagination']['page_number'] = page
        response['pagination']['article_id'] = article_id
        response['pagination']['prices'] = []

        results = db.prices.find({"article_id": article_id}).skip(offset * (page - 1)).limit(offset)

        if (not results):
            raise errors.InvalidArgument("_id", "Document does not exists")

        for result in results:
            price = {}
            price['price_id'] = str(result['_id'])
            price['created'] = result['created']
            price['state'] = result['state']
            price['max_price'] = result['max_price']
            price['min_price'] = result['min_price']
            price['price'] = result['price']
            price['price_currency'] = result['price_currency']
            price['formated_price'] = result['formated_price']

            response['pagination']['prices'].append(price)

        return response

    except Exception:
        raise errors.InvalidArgument("article_id", "Invalid object id")