Exemplo n.º 1
0
def postProduct(id):
    new_product = json.loads(request.data)
    product_name = None
    # start new code to fix to discriminate between new and old product.. I am doing with the name because if not I will need to set de sku_id on the front to the backend.
    # I think this code for name I should do it on models
    name_by_product = Product.query.filter_by(supplier_id=id).all()
    for item in name_by_product:
        if item.name == new_product["name"]:
            product_name = item.name
        else:
            product_name = new_product["name"]
    
    # finish new code to fix to discriminate between new and old product

    sku_id = new_product['sku_id'] if product_name == new_product["name"] else random.randint(1,999999) 
    
    # sku_id = new_product['sku_id'] if "sku_id" in new_product else random.randint(1,999999) 

    product_old = Product.query.filter_by(sku_id=sku_id).filter_by(supplier_id=id).first()

    if product_old is None:
        product = Product(
            category=new_product["category"],
            sku_id=sku_id, 
            name=new_product["name"], 
            description=new_product["description"],
            quantity_in=new_product["quantity_in"],
            price=new_product["price"],
            supplier_id=id
        )
        
        inventory = Inventory()
        inventory.total_supplier_stock = new_product['quantity_in']
        db.session.add(product)
        db.session.commit()
        return jsonify(product.serialize()), 200

    if product_old is not None:
        stock_old_product= product_old.quantity_in + new_product['quantity_in']
        inventory_query = Inventory.query.filter_by(product_id=product_old.id).first()
        inventory_query.total_supplier_stock = stock_old_product
        db.session.commit()
        return jsonify(inventory_query.serialize()), 200