Jump to content

Unable to add stock qty when listing a product via API .. pls help


Birdee

Recommended Posts

# --- PRESTASHOP FUNCTION ---
def create_prestashop_product(title, description, keywords, watermarked_img_path, storage_url):
    print("[PRESTASHOP] Starting product creation process...")
    try:
        # 1. Create the Product
        product_schema = prestashop.get("products", options={"schema": "blank"})
        product_data = product_schema["product"]

        def to_multilang(value):
            return {"language": [{"attrs": {"id": "1"}, "value": value}]}

        short_title = truncate(title, 128)
        product_data.update({
            "name": to_multilang(short_title),
            "id_manufacturer": "2",
            "description": to_multilang(description),
            "description_short": to_multilang(f"Digital Download: {os.path.splitext(os.path.basename(storage_url))[0]}"),
            "link_rewrite": to_multilang(re.sub(r'[^a-z0-9]+', '-', short_title.lower()).strip("-")[:128]),
            "meta_keywords": to_multilang(truncate_keywords(keywords, 255)),
            "state": "1", "active": "1", "is_virtual": "1",
            "price": "1.00", "id_tax_rules_group": "1",
            "id_category_default": "2", "position_in_category": "1", 
            "associations": {"categories": {"category": [{"id": "2"}]}},
        })
        new_product = prestashop.add("products", {"product": product_data})
        new_product_id = new_product["prestashop"]["product"]["id"]
        print(f"[PRESTASHOP] SUCCESS: Product created with ID: {new_product_id}")

        # 2. Upload the Image
        with open(watermarked_img_path, "rb") as img_file:
            prestashop.add(f"images/products/{new_product_id}", files=[("image", os.path.basename(watermarked_img_path), img_file.read())])
        print(f"[PRESTASHOP] SUCCESS: Display image uploaded for product ID: {new_product_id}")

        # 3. Robust Stock Update for PrestaShop 8+
        print("[PRESTASHOP] Attempting to update stock quantity...")

        stock_id = None
        for _ in range(5):
            stock_search = prestashop.search(
                "stock_availables",
                options={"filter[id_product]": new_product_id, "filter[id_product_attribute]": "0"},
            )
            if stock_search and stock_search.get("stock_availables"):
                stock_id = stock_search["stock_availables"]["stock_available"]["attrs"]["id"]
                break
            time.sleep(1)

        if stock_id:
            print(f"[PRESTASHOP] Found stock record with ID: {stock_id}. Updating it.")
            stock_schema = prestashop.get("stock_availables", stock_id)
            stock_schema["stock_available"]["quantity"] = "999"
            stock_schema["stock_available"]["out_of_stock"] = "1"
            prestashop.edit(
                "stock_availables",
                stock_id,
                {"stock_available": stock_schema["stock_available"]},
            )
            print(f"[PRESTASHOP] SUCCESS: Stock updated for product ID: {new_product_id}")
        else:
            print("[PRESTASHOP] ERROR: Could not locate stock record. Quantity not updated.")

    except PrestaShopWebServiceError as e:
        print(f"[PRESTASHOP API ERROR] During product creation/update: {e}")
    except Exception as e:
        print(f"[PRESTASHOP UNEXPECTED ERROR] {e}")

I get this error.. 

[PRESTASHOP] SUCCESS: Product created with ID: 124
[PRESTASHOP] SUCCESS: Display image uploaded for product ID: 124
[PRESTASHOP] Attempting to update stock quantity...
[PRESTASHOP UNEXPECTED ERROR] 'list' object has no attribute 'get' i have spent 20 hours and i dont get it !! pls help me !! 

Link to comment
Share on other sites

HI, I am trying to download stock movements but the API request returns a 404 error. 
Namely when the request goes mydomain/api/stocks/4 (for instance) it returns a 404 error.
Do you know how to overcome this? Is the htaccess need to be reconfigured or other parameters?

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...