client = new SoapClient('http://www.le-fix.com/webshop/api/?wsdl=1');
//setup session
$this->session = $this->client->login('pandiweb', 'MIGRATE');
}
public function processCategories(){
$result = $this->client->call($this->session, 'catalog_category.tree');
$this->iterateCategories($result['children']);
}
public function processCategoryByName($name){
$cat = Mage::getModel('catalog/category')->loadByAttribute('name', $name);
$cat->setStoreId(0);
$cat->setParentId(2);
$cat->setPath('1/2/'.$cat->getId());
$cat->save();
}
public function processProducts(){
$categories = $this->client->call($this->session, 'catalog_category.tree');
$this->skus = $this->getAllSKU();
$this->processProductsByCategory($categories['children']);
}
public function processUncategorizedProducts($start = 0){
$apiProduct = $this->client->call($this->session, 'catalog_product.list');
$count = 0; $calls = $callsImg = $callsStock = array();
for($i = $start; $i < count($apiProduct); $i++){
if(count($apiProduct[$i]['category_ids']) == 0){
if($count < 500){
$calls[] = array('catalog_product.info', $apiProduct[$i]['product_id']);
$callsImg[] = array('catalog_product_attribute_media.list', $apiProduct[$i]['product_id']);
$callsStock[] = array('cataloginventory_stock_item.list', $apiProduct[$i]['product_id']);
}else{
break;
}
$count++;
}
}
echo 'Index: '.$i.'
';
if(count($calls) > 0){
$list = $this->client->multiCall($this->session, $calls);
$images = $this->client->multiCall($this->session, $callsImg);
$stock = $this->client->multiCall($this->session, $callsStock);
for($idx = 0; $idx < count($list); $idx++){
$this->createProduct($list[$idx], $images[$idx], $stock[$idx]);
echo $list[$idx]['name'].' created
';
}
}
}
public function associateProducts($products){
foreach($products as $p){
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $p->sku);
if($product != null){
$this->associate($product, $p->products);
echo $p->id.' attached
';
}else{
echo 'Product with SKU: '.$p->sku.'('.$p->id.') not found
';
}
}
}
private function flattenCategories($categoryList, $created = array()){
foreach($categoryList as $category){
$created['category_'.$category['category_id']] = $category['name'];
if(count($category['children']) > 0){
$created = $this->flattenCategories($category['children'], $created);
}
}
return $created;
}
private function mapCategories(){
$apiCategories = $this->flattenCategories($this->client->call($this->session, 'catalog_category.tree')['children']);
$categories = Mage::getModel('catalog/category')->getCollection()->addAttributeToSelect('id')->addAttributeToSelect('name');
$cMapping = array();
foreach($categories as $category){
$cname = $category->getName();
if(in_array($cname, $apiCategories)){
$cid = str_replace('category_', '', array_search($cname, $apiCategories));
$cMapping[$cid] = $category->getId();
}
}
return $cMapping;
}
public function addMissingProducts(){
$skus = $this->getAllSKU();
$apiProducts = $this->client->call($this->session, 'catalog_product.list');
$missing = array(); //get all missing products
foreach($apiProducts as $p){
if(!in_array($p['sku'], $skus)){
$missing[] = $p['product_id'];
}
}
//process 300 products on every run
$calls = $callsImg = $callsStock = array();
for($i = 0; $i < 300; $i++){
if(!empty($missing[$i])){
$calls[] = array('catalog_product.info', $missing[$i]);
$callsImg[] = array('catalog_product_attribute_media.list', $missing[$i]);
$callsStock[] = array('cataloginventory_stock_item.list', $missing[$i]);
}
}
if(count($calls) > 0){
$list = $this->client->multiCall($this->session, $calls);
$images = $this->client->multiCall($this->session, $callsImg);
$stock = $this->client->multiCall($this->session, $callsStock);
$categories = $this->mapCategories();
for($i = 0; $i < count($list); $i++){
$catData = array();
foreach($list[$i]['category_ids'] as $cat){
if(!empty($categories[$cat])){
$catData[] = $categories[$cat];
}
}
$this->createProduct($list[$i], $images[$i], $stock[$i], $catData);
echo $list[$i]['name'].', '.$list[$i]['product_id'].', '.$list[$i]['type'].' created
';
}
}else{
echo 'All products created';
}
}
private function associate($product, $associated){
$configurableProductsData = array();
foreach($associated as $p){
$temp = Mage::getModel('catalog/product')->loadByAttribute('sku', $p->sku);
if($temp != null){
if(!empty($p->clothes_size)){
$label = Attributes::$clothes_size[$p->clothes_size][1];
$value_index = Attributes::$clothes_size[$p->clothes_size][0];
$attribute_id = 148;
$temp->setData('clothes_size', $value_index);
$temp->save();
}else if(!empty($p->pants_size)){
$label = Attributes::$pants_size[$p->pants_size][1];
$value_index = Attributes::$pants_size[$p->pants_size][0];
$attribute_id = 147;
$temp->setData('pants_size', $value_index);
$temp->save();
}else if(!empty($p->shoe_size)){
$label = Attributes::$shoe_size[$p->shoe_size][1];
$value_index = Attributes::$shoe_size[$p->shoe_size][0];
$attribute_id = 149;
$temp->setData('shoe_size', $value_index);
$temp->save();
}
$configurableProductsData[(string) $temp->getId()] = array(
'0' => array(
'label' => $label,
'attribute_id' => $attribute_id,
'value_index' => $value_index,
'is_percent' => '0',
'pricing_value' => ''
)
);
}
}
if(!empty($attribute_id)){
//clear old association
$resource = Mage::getSingleton('core/resource');
$write = $resource->getConnection('core_write');
$table = $resource->getTableName('catalog/product_super_attribute');
$write->delete($table,"product_id = " . $product->getId());
$product->getTypeInstance()->setUsedProductAttributeIds(array($attribute_id));
$configurableAttributesData = $product->getTypeInstance()->getConfigurableAttributesAsArray();
$product->setCanSaveConfigurableAttributes(true);
$product->setConfigurableAttributesData($configurableAttributesData);
$product->setConfigurableProductsData($configurableProductsData);
$product->save();
}
}
private function processProductsByCategory($categoryList){
foreach($categoryList as $category){
if($category['name'] != 'LE-FIXB2B'){
$this->processCategoryProducts($category);
if(count($category['children']) > 0 && !in_array($category['category_id'], array(70, 122, 123))){
$this->processProductsByCategory($category['children']);
}
}
}
}
private function iterateCategories($categoryList, $parent = null){
foreach($categoryList as $category){
$created = $this->processCategory($category, $parent);
if(count($category['children']) > 0){
$this->iterateCategories($category['children'], $created);
}
}
}
private function processCategory($category, $parent = null){
$info = $this->client->call($this->session, 'catalog_category.info', $category['category_id']);
echo $category['category_id'].'
';
$mCategory = Mage::getModel('catalog/category');
$mCategory->setStoreId(0);
$mCategory->load($category['category_id']);
$attributes = $this->setCatAttributes($info);
$mCategory->addData($attributes);
if(!$mCategory->getId()) $mCategory->save();
if($parent != null){
$mCategory->setParentId($parent->getId());
$mCategory->setPath($parent->getPath().'/'.$mCategory->getId());
}
$mCategory->save();
return $mCategory;
}
private function setCatAttributes($info){
$general = array();
$general['name'] = $info['name'];
$general['description'] = $info['description'];
$general['meta_title'] = $info['meta_title'];
$general['meta_keywords'] = $info['meta_keywords'];
$general['meta_description'] = $info['meta_description'];
$general['display_mode'] = $info['display_mode'];
$general['landing_page'] = $info['landing_page'];
$general['is_active'] = $info['is_active'];
$general['is_anchor'] = $info['is_anchor'];
$general['include_in_menu'] = $info['include_in_menu'];
$general['url_key'] = $info['url_key'];
$general['image'] = $info['image'];
$general['thumbnail'] = $info['thumbnail'];
return $general;
}
public function categoryProducts($category){
$this->skus = $this->getAllSKU();
$this->processCategoryProducts($category);
}
private function processCategoryProducts($category){
$processed = array();
if(!in_array($category['name'], $processed)){
$result = $this->client->call($this->session, 'catalog_category.assignedProducts', $category['category_id']);
if(count($result) > 0){
$catTmp = Mage::getModel('catalog/category')->loadByAttribute('name', $category['name']);
if($catTmp != null){
$_category = $catTmp->getId();
foreach($result as $r){
if(!in_array($r['product_id'], array(14782, 14776, 14779))){
$calls[] = array('catalog_product.info', $r['product_id']);
$callsImg[] = array('catalog_product_attribute_media.list', $r['product_id']);
$callsStock[] = array('cataloginventory_stock_item.list', $r['product_id']);
}
}
//get the necessary information
$list = $this->client->multiCall($this->session, $calls);
$images = $this->client->multiCall($this->session, $callsImg);
$stock = $this->client->multiCall($this->session, $callsStock);
//process the products
for($i = 0; $i < count($list); $i++){
if(!in_array($list[$i]['sku'], $this->skus)){
$_product = Mage::getModel('catalog/product');
$this->saveProductData($_product, $list[$i], $images[$i], $stock[$i], $_category);
}else{
$_product = Mage::getModel('catalog/product')->loadByAttribute('sku', $list[$i]['sku']);
if($_product != null){
$categories = $_product->getCategoryIds();
if(!in_array($_category, $categories)){
$categories[] = $_category;
$_product->setCategoryIds($categories);
$_product->save();
}
}
}
}
echo 'Category '.$category['name'].'('.$_category.'), '.$category['category_id'].' processed!
';
}else{
echo 'Category '.$category['name'].', '.$category['category_id'].' not found!
';
}
}
}
}
private function saveProductData($_product, $apiProduct, $images, $stock, $catId){
$taxId = ($apiProduct['tax_class_id'] == 1) ? 5 : $apiProduct['tax_class_id'];
$_product->setWebsiteIds(array(1))
->setAttributeSetId(4)
->setTypeId($apiProduct['type'])
->setCreatedAt(strtotime('now'))
->setName($apiProduct['name'])
->setSku($apiProduct['sku'])
->setStatus($apiProduct['status'])
->setTaxClassId($taxId)
->setVisibility($apiProduct['visibility'])
->setColor($apiProduct['color'])
->setNewsFromDate(date('d/m/Y', strtotime($apiProduct['news_from_date'])))
->setNewsToDate(date('d/m/Y', strtotime($apiProduct['news_to_date'])))
->setCountryOfManufacture($apiProduct['country_of_manufacture'])
->setPrice($apiProduct['price'])
->setMsrpEnabled($apiProduct['msrp_enabled'])
->setMsrpDisplayActualPriceType($apiProduct['msrp_display_actual_price_type'])
->setMsrp($apiProduct['msrp'])
->setMetaTitle($apiProduct['meta_title'])
->setMetaKeyword($apiProduct['meta_keyword'])
->setMetaDescription($apiProduct['meta_description'])
->setDescription($apiProduct['description'])
->setShortDescription($apiProduct['short_description']);
if(count($images) > 0){
$_product->setMediaGallery(array('images'=>array(), 'values'=>array()));
foreach($images as $img){
try{
$_product->addImageToMediaGallery('../media/catalog/product'.$img['file'], $img['types'], false, $img['exclude']);
}catch(Exception $e){
//echo $e->getMessage().'
';
}
}
}
if(!empty($apiProduct['special_price'])){
$_product->setSpecialPrice($apiProduct['special_price'])
->setSpecialFromDate(date('d/m/Y', strtotime($apiProduct['special_from_date'])))
->setSpecialToDate(date('d/m/Y', strtotime($apiProduct['special_to_date'])));
}
$_product->setCategoryIds(array($catId));
if(count($stock) > 0){
$_product->save();
$_product->setStockData(array(
'use_config_manage_stock' => 1,
'manage_stock'=>1,
'min_sale_qty'=>0,
'max_sale_qty'=>10000,
'is_in_stock' => $stock[0]['is_in_stock'],
'qty' => $stock[0]['qty']
)
);
}
try{
$_product->save();
}catch(Exception $e){
echo $e->getMessage().'
';
}
}
private function getAllSKU(){
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$data = $readConnection->fetchAll("SELECT `sku` FROM `catalog_product_entity`");
foreach($data as $item){
$final[] = $item['sku'];
}
return $final;
}
private function createProduct($apiProduct, $images, $stock, $categories = array()){
$_product = Mage::getModel('catalog/product');
$taxId = ($apiProduct['tax_class_id'] == 1) ? 5 : $apiProduct['tax_class_id'];
$_product->setWebsiteIds(array(1))
->setAttributeSetId(4)
->setTypeId($apiProduct['type'])
->setCreatedAt(strtotime('now'))
->setName($apiProduct['name'])
->setSku($apiProduct['sku'])
->setStatus($apiProduct['status'])
->setTaxClassId($taxId)
->setVisibility($apiProduct['visibility'])
->setColor($apiProduct['color'])
->setNewsFromDate(date('d/m/Y', strtotime($apiProduct['news_from_date'])))
->setNewsToDate(date('d/m/Y', strtotime($apiProduct['news_to_date'])))
->setCountryOfManufacture($apiProduct['country_of_manufacture'])
->setPrice($apiProduct['price'])
->setMsrpEnabled($apiProduct['msrp_enabled'])
->setMsrpDisplayActualPriceType($apiProduct['msrp_display_actual_price_type'])
->setMsrp($apiProduct['msrp'])
->setWeight($apiProduct['weight'])
->setMetaTitle($apiProduct['meta_title'])
->setMetaKeyword($apiProduct['meta_keyword'])
->setMetaDescription($apiProduct['meta_description'])
->setDescription($apiProduct['description'])
->setShortDescription($apiProduct['short_description']);
//set product images
$_product->setMediaGallery(array('images'=>array(), 'values'=>array()));
foreach($images as $img){
try{
$_product->addImageToMediaGallery('../media/catalog/product'.$img['file'], $img['types'], false, $img['exclude']);
}catch(Exception $e){
echo $e->getMessage().'
';
}
}
if(!empty($apiProduct['special_price'])){
$_product->setSpecialPrice($apiProduct['special_price'])
->setSpecialFromDate(date('d/m/Y', strtotime($apiProduct['special_from_date'])))
->setSpecialToDate(date('d/m/Y', strtotime($apiProduct['special_to_date'])));
}
$_product->setCategoryIds($categories);
if(count($stock) > 0){
$_product->setStockData(array(
'use_config_manage_stock' => 1,
'manage_stock'=>1,
'min_sale_qty'=>0,
'max_sale_qty'=>10000,
'is_in_stock' => $stock[0]['is_in_stock'],
'qty' => $stock[0]['qty']
)
);
}
//try{
$_product->save();
//}catch(Exception $e){
//}
}
private function updateProduct($product, $apiProduct, $stock){
$product->setStatus($apiProduct['status'])
->setNewsFromDate(date('m/d/Y', strtotime($apiProduct['news_from_date'])))
->setNewsToDate(date('m/d/Y', strtotime($apiProduct['news_to_date'])))
->setPrice($apiProduct['price'])
->setMsrpEnabled($apiProduct['msrp_enabled'])
->setMsrpDisplayActualPriceType($apiProduct['msrp_display_actual_price_type'])
->setMsrp($apiProduct['msrp'])
->setWeight($apiProduct['weight'])
->setMetaTitle($apiProduct['meta_title'])
->setMetaKeyword($apiProduct['meta_keyword'])
->setMetaDescription($apiProduct['meta_description'])
->setDescription($apiProduct['description'])
->setShortDescription($apiProduct['short_description']);
/*if(count($stock) > 0){
$stock_item = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId());
if(!$stock_item->getId()){
$product->setStockData(array(
'use_config_manage_stock' => 1,
'manage_stock'=>1,
'min_sale_qty'=>0,
'max_sale_qty'=>10000,
'is_in_stock' => $stock[0]['is_in_stock'],
'qty' => $stock[0]['qty']
)
);
}else{
$stock_item->setData('use_config_manage_stock', 1);
$stock_item->setData('manage_stock', 1);
$stock_item->setData('min_sale_qty', 0);
$stock_item->setData('max_sale_qty', 10000);
$stock_item->setData('is_in_stock', $stock[0]['is_in_stock']);
$stock_item->setData('qty', $stock[0]['qty']);
$stock_item->save();
}
}*/
$product->save();
}
public function updateProductInfo($page, $pageSize = 300){
$collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*')
->setCurPage($page)->setPageSize($pageSize);
$skus = $products = array();
foreach($collection as $product){
if(!in_array($product->getId(), array(20015, 20018, 20019, 20024, 20025, 20026, 20027, 20028, 20029, 20030, 20031, 20032))){
$skus[] = $product->getSku();
$products[] = $product;
}
}
$calls = $callsStock = array();
for($i = 0; $i < count($skus); $i++){
$calls[] = array('catalog_product.info', $skus[$i]);
$callsStock[] = array('cataloginventory_stock_item.list', $skus[$i]);
}
if(count($calls) > 0){
/*for($i = 0; $i < count($calls); $i++){
echo '
'; print_r($calls[$i]); echo ''; try{ $this->client->call($this->session, $calls[$i][0], $calls[$i][1]); }catch(Exception $e){ echo $e->getMessage().'