Search code examples
phpmagentomagento-1.9

Programmatically import configurable products


I use cron to import products in the database. Products are imported but the association between configurable products and simple products is not done correctly. The association is done every new product but at the end, only the last product imported remains. Please find the function I use below.

==EDIT==

This function is under community>Bmservices>Polaris>Model>Observer

It is called by a cron defined in config.xml that work. I am sure that the function is called as I am logging in it and the log is filling with the proper information.

==END OF EDIT==

I get the $line from csv.

private function _importProduct($line){
    $utf8bom = "\xef\xbb\xbf";
    $rayon = $this->_checkCategory($line[21]+2, $line[22]);
    $famille = $this->_checkCategory($line[23], $line[24], $rayon);
    $sousfamille = $this->_checkCategory($line[25], $line[26], $famille);
    $idManu = $this->_checkAttribute($line[5], $line[27], $this->_attributManufacturer);
    $idSais = $this->_checkAttribute($line[15], $line[28], $this->_attributSaison);
    $idColl = $this->_checkAttribute($line[16], $line[29], $this->_attributCollection);
    $idMati = $this->_checkAttribute($line[11], $line[35], $this->_attributMatiere);
    $idCoul = $this->_checkAttribute($line[3], $line[20], $this->_attributCouleur);
    $idTail = $this->_checkAttribute($line[4], $line[42], $this->_attributTaille, $line[43]);
    $idAttS = $this->_checkAttributeSet($line[49], $line[50]);
    $product = Mage::getModel('catalog/product');
    $sku = trim($line[0], $utf8bom);
    $sku = trim($sku, '"');
    $product->loadByAttribute('sku',$sku);
    $id = $product->getId();
    if (empty($id)){
        Mage::log("nouveau produit avec le sku $sku");
        $product->setStoreId(1);
        $product->setSku($sku);
        $product->setAttributeSetId($idAttS);
        $product->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
    }
    if ($line!=''){
        $product->setName($line[18]);
    } else {
        $product->setName($line[17]);
    }
    $product->setDescription($line[19]);
    $product->setCreatedAt($line[41]);
    $product->setShortDescription($line[19]);
    $product->setData('collecannee', $idColl);
    $product->setData('matiere', $idMati);
    $product->setData('manufacturer', $idManu);
    $product->setData('saison', $idSais);    
    $product->setMetaKeyword($line[22].','.$line[24].','.$line[26].','.$line[27].','.$line[28]);
    $product->setMetaTitle($line[18]);
    $product->setMetaDescription($line[19]);
    $product->setWeight(0);
    $product->setData('price',$line[47]);
    $product->setCategoryIds(array($rayon, $famille, $sousfamille));
    $product->setFinalPrice($line[47])        
        ->setMediaGallery(array('images' => array(), 'values' => array())) //media gallery initialization
        ->setMsrpEnabled(0) //enable MAP
        ->setMsrpDisplayActualPriceType(4) //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
        ->setMsrp($line[47]); //Manufacturer's Suggested Retail Price
    if ($line[48]!=''){
        $product->setSpecialPrice($line[48]);
        $product->setSpecialFromDate('2014-08-01');
        $product->setSpecialFromDateIsFormated(true);
        $product->setSpecialToDate('2014-08-30');
        $product->setSpecialToDateIsFormated(true);
    } else {
        $product->setSpecialPrice(null);
    }
    $product->setTaxClassId(2);
    if ((!isset($this->_productConf))||($this->_productConf->getSku()!='C-'.$line[2])){
        if ((isset($this->_productConf))&&($this->_productConf->getSku()!='C-'.$line[2])){
            $this->_productConf->setConfigurableProductsData($this->_configurableProductsData);
            $this->_productConf->save();
        }
        $this->_productConf = Mage::getModel('catalog/product');
        $skuConf = 'C-'.$line[2];
        $this->_productConf->loadByAttribute('sku',$skuConf);
        $this->_configurableProductsData = array();
        $idConf = $this->_productConf->getId();
        if (empty($idConf)){
            Mage::log('Création d\'un produit configurable : '.$skuConf);
            $this->_productConf->setData($product->getData());
            $this->_productConf->setTypeId('configurable');
            $this->_productConf->setData('size', NULL);
            $this->_productConf->setData('color', NULL);
            $attribute_ids = array($this->_attributTaille, $this->_attributCouleur);
            $this->_productConf->getTypeInstance()->setUsedProductAttributeIds($attribute_ids);
            $configurableAttributesData = $this->_productConf->getTypeInstance()->getConfigurableAttributesAsArray();
            $this->_productConf->setCanSaveConfigurableAttributes(true);
            $this->_productConf->setConfigurableAttributesData($configurableAttributesData);
            $StockData['manage_stock'] = 1;
            $StockData['is_in_stock'] = 1;
            $StockData['use_config_manage_stock'] = 0;
            $StockData['use_config_min_qty'] = 0;
            $this->_productConf->setStockData($StockData);
            $this->_productConf->setCanSaveConfigurableAttributes(true);
            $this->_productConf->setCanSaveCustomOptions(true);
            $this->_productConf->setSku($skuConf);
            $this->_productConf->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
        }
    }
    $StockData['qty'] = floatval($line[46]);
    $StockData['is_in_stock'] = ($StockData['qty']>0) ? 1 : 0;
    $StockData['manage_stock'] = 1;
    $StockData['use_config_manage_stock'] = 0;
    $StockData['use_config_min_qty'] = 0;
    $product->setStockData($StockData);
    $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
    $product->setData('size', $idTail);
    $product->setData('color', $idCoul);
    Mage::log("sauvegarde du produit");
    $product->validate();
    $product->save();

    /**
     * mise à jour du prix et de la classe de taxe
     */
    Mage::getSingleton('catalog/product_action')->updateAttributes(
        array($product->getId()),
        array(121 => 2, 75 => $line[47]),
        0
    );

    /**
     * gestion du stock
     */
    $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId());
    $stockItemId = $stockItem->getId();
    $stock = array();

    if (!$stockItemId) {
        $stockItem->setData('product_id', $product->getId());
        $stockItem->setData('stock_id', 1);
    } else {
        $stock = $stockItem->getData();
    }

    foreach($StockData as $field => $value) {
        $stockItem->setData($field, $value?$value:0);
    }
    $stockItem->save();
    $this->_configurableProductsData[$product->getId()] = array( //['920'] = id of a simple product associated with this configurable
        '0' => array(
            'label' => $line[20], //attribute label
            'attribute_id' => $this->_attributCouleur, //attribute ID of attribute 'color' in my store
            'value_index' => $idCoul, //value of 'Green' index of the attribute 'color'
            'is_percent' => '0', //fixed/percent price for this option
            'pricing_value' => $line[47] //value for the pricing
        ),
        '1' => array(
            'label' => $line[42], //attribute label
            'attribute_id' => $this->_attributTaille, //attribute ID of attribute 'color' in my store
            'value_index' => $idTail, //value of 'Green' index of the attribute 'color'
            'is_percent' => '0', //fixed/percent price for this option
            'pricing_value' => $line[47] //value for the pricing
        )
    );
}

Is there something I miss.


Solution

  • I found my mistake and I could not believe it got me stuck for more than a week. In case somebody encounter the same issue, the answer lies in the website ids. I did not affect any so the product did not exist in any store so it was affected but not visible on the product page. I can not explain why I had it on admin and in the database but now everything is ok.