Daily Inventory Update through remote FTP file - magento

It’s been 2 days and I came across many tutorials, videos, extension which explains how to do daily updates on my products but none of them seem to work.
I have a website which has around 3,000 products with attributes and all. My supplier updates the inventory file on daily basis and the updated inventory file is kept on a remote ftp to which I have access to.
What I need is the following:
Daily inventory update which will include, prices, quantity, etc
Remove items which has quantity 0
Add new items as per the updated inventory file
I am sure someone out there has answer to my questions. So please get back to me asap.

Fisrt, by "Remove items which has quantity 0", I think you mean to set products as "out of stock" when the inventory is decreased to 0. This is handled automatically by Magento after you update the inventory.
The built-in import/export function should fulfill your requirements.
Some more tutorials if you don't mind:
Tutorial: Using Magento’s Import/Export Profiles
How to add/edit/remove products using the import/export tool

Here, I will share just inventory update ( but this is not good way ). You should create "tab delimited" file as follows :
SKU QTY
978 34
633 0
Then you can create cron job to run this script.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
set_time_limit(0);
ini_set('memory_limit','1024M');
include('app/Mage.php');
Mage::App('default');
//get magento db connection for query
$db_query = Mage::getSingleton('core/resource')->getConnection('core_read');
//get magento db connection for update, add, delete sql statements
$db_update = Mage::getSingleton('core/resource')->getConnection('core_write');
//mail receipent
$to = 'youremail#yoursite.com';
if ($handle = opendir('./var/export'))
{
while (false !== ($file = readdir($handle)))
{
$sku_success = '';
if ($file != '.' && $file != '..')
{
$filename = './var/export/'.$file;
$handle_file = fopen($filename,'r');
$counter = 1;
while (($data = fgetcsv($handle_file, 1000, '\t'))!== FALSE) //read tab delimited
{
if($counter!=1)
{
$sku= $data[0];
$qty = $data[1];
$exists = $db_query->query("SELECT COUNT(sku) cnt FROM catalog_product_entity WHERE sku = '$sku' LIMIT 1");
$found = (($exists->fetchObject()->cnt) > 0) ? true : false;
if ($found == true) //product found, update
{
$entity_id = getEntityIdBySku($db_query, $sku);
updateStockQty ($db_update, $entity_id, $qty);
echo 'product $sku inventory updated?';
$sku_success.= $sku;
} else {
//sku not found, notify by email
$body = "SKU#:".$sku." of ".$file." with a qty of ".$qty." was not found in the the inventory";
sendMsg("SKU#:".$sku." not found!",$to,$body);
}
}
$counter++;
}
fclose($handle_file);
$body = "<strong>SKU?S IMPORTED</strong>".$sku_success."<br/>";
sendMsg($file." successfully imported!",$to,$body);
}
}
closedir($handle);
}
function getEntityIdBySku($db_connection, $sku) //get entity id by its sku
{
$entity_row = $db_connection->query("SELECT entity_id FROM catalog_product_entity p_e WHERE p_e.sku = '$sku'")->fetchObject();
$entity_id = $entity_row->entity_id;
return $entity_id;
}
function updateStockQty($db_connection, $entity_id, $qty) //updates the stock quantity
{
$db_connection->query("UPDATE cataloginventory_stock_item s_i, cataloginventory_stock_status s_s
SET s_i.qty = '$qty', s_i.is_in_stock = IF('$qty'>0, 1,0),
s_s.qty = '$qty', s_s.stock_status = IF('$qty'>0, 1,0)
WHERE s_i.product_id = '$entity_id' AND s_i.product_id = s_s.product_id ");
}
function sendMsg($subject, $to, $body)//sends email
{
$headers = 'MIME-Version: 1.0' . '\n';
$headers .= 'Content-type: text/html; charset=iso-8859-1'. '\n';
$headers .= 'To: '.$to. '\n';
$headers .= 'From: webmaster#yoursite.com'. '\n';
if (mail($to, $subject, $body,$headers))
{
echo('Message sent!');
} else {
echo('Message failed.');
}
}
?>
The script by courtesy of the Deepcodeonline

Related

Magento - Should I do mass update about 5k in mid night or separate multiple times in a day

I'm using magento EE 1.14.2.1.I have about 50k products in databases.I just want some useful advice about updating products.
As I mentioned in title , in everyday I have about 5k product need to be update stock and price.So,should I do it in midnight then reindex them all in one time or turn on the enterprise refresh index cron and update product in many times in a day ( about 100 product per times ).The most important thing which I concerted is the website performance and avoiding MySQL deadlock.
Here's an option for you. I have an import.php script that I use to import or update large numbers of products and their attributes. It will let you either update or create a product based on SKU. You would have to check the constants to see if they match your Magento.
This is a script for Community Edition so you would have to test for Enterprise.
<?php
include_once("app/Mage.php");
Mage::app();
umask(0);
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
$counter = 0;
function GetProduct($sku)
{
global $counter;
echo $sku;
$p = Mage::getModel('catalog/product');
$productId = $p -> getIdBySku($sku);
if($productId)
{
echo "!";
$p -> load( $productId );
}
else
{
$p->setTypeId('simple');
$p->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$p->setStatus(1);
$p->setTaxClassId(7);
$p->setWebsiteIDs(array(1));
$p->setStoreIDs(array(1));
$p->setAttributeSetId(4);
$p->setSku($sku);
}
echo "...";
$counter++;
echo " ".$counter;
return $p;
}
function SaveProduct($p)
{
try
{
if (is_array($errors = $p->validate()))
{
$strErrors = array();
foreach($errors as $code=>$error)
{
$strErrors[] = ($error === true)? Mage::helper('catalog')->__('Attribute "%s" is invalid.', $code) : $error;
echo $strErrors[0];
}
$this->_fault('data_invalid', implode("\n", $strErrors));
}
$p->save();
echo "\n";
}
catch (Mage_Core_Exception $e)
{
$this->_fault('data_invalid', $e->getMessage());
}
}
$product = GetProduct('SKU01'); $product->setData('upc', '013051388461'); SaveProduct($product); unset($product);
$product = GetProduct('SKU02'); $product->setData('special_price', null); $product->setData('special_from_date', null); SaveProduct($product); unset($product);
$product = GetProduct('SKU03'); $product->setData('cardboard_height_cm', 28.5); $product->setData('cardboard_width_cm', 37); SaveProduct($product); unset($product);
?>
I often get Excel to create the lines like $product = GetProduct('SKU03'); $product->setData('cardboard_height_cm', 28.5); $product->setData('cardboard_width_cm', 37); SaveProduct($product); unset($product); and then just copy and paste into the script. I can edit before running.
This is much faster than importing a CSV and it calls all of the correct observers.
Just run this from a SSH shell.

how do i programaticly delete duplicate images? in magento

I manage a big web store with alot of products, and some of the products weren't correctly imported and the images got duplicated.
the products just have 2 of the same images.
i know that you can delete them by hand but that would take up all my life of time.
i have searched the internet for some of the codes that can do it but they dont work for me.
is there anybody who know a solution for this?
I have tried to examine the codes that i got from the internet but i really can make them work.
this is one of the solutions that didn't work for me:
http://dltr.org/blog/magento/556/Magento-product-images-duplicate-issue-with-CSV-product-importer
i have tried to test this query in the sql database but that does not give any result:
SELECT * FROM `catalog_product_entity_media_gallery` WHERE value_id != value_id AND value=value
Here is a little script to find and delete all duplicate images in Magento.
//Mage::App(‘default’);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
error_reporting(E_ALL | E_STRICT);
Mage::setIsDeveloperMode(true);
ini_set(‘display_errors’, 1);
ob_implicit_flush (1);
$mediaApi = Mage::getModel(“catalog/product_attribute_media_api”);
$_products = Mage::getModel(‘catalog/product’)->getCollection();
$i =0;
$total = count($_products);
$count = 0;
foreach($_products as $_prod)
{
$_product = Mage::getModel(‘catalog/product’)->load($_prod->getId());
$_md5_values = array();
//protect base image
$base_image = $_product->getImage();
if($base_image != ‘no_selection’)
{
$filepath = Mage::getBaseDir(‘media’) .’/catalog/product’ . $base_image ;
if(file_exists($filepath))
$_md5_values[] = md5(file_get_contents($filepath));
}
$i ++;
echo “\r\n processing product $i of $total “;
// Loop through product images
$_images = $_product->getMediaGalleryImages();
if($_images)
{
foreach($_images as $_image)
{
//protected base image
if($_image->getFile() == $base_image)
continue;
$filepath = Mage::getBaseDir(‘media’) .’/catalog/product’ . $_image->getFile();
if(file_exists($filepath))
$md5 = md5(file_get_contents($filepath));
else
continue;
if( in_array( $md5, $_md5_values ))
{
$mediaApi->remove($_product->getId(), $_image->getFile());
echo “\r\n removed duplicate image from “.$_product->getSku();
$count++;
}
else
{
$_md5_values[] = $md5;
}
}
}
}
http://www.aadil.co/how-to-delete-duplicate-product-images-in-magento/
Below is a snippet I have used earlier, this works like a charm
Actual link : http://blueclawecommerce.co.uk/blog/removing-duplicate-product-images-in-magento/
include('app/Mage.php'); 
//Mage::App('default');
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
error_reporting(E_ALL | E_STRICT);
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
ob_implicit_flush (1);
 
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$_products = Mage::getModel('catalog/product')->getCollection();
$i =0;
$total = count($_products);
$count = 0;
foreach($_products as $_prod)
{
    $_product = Mage::getModel('catalog/product')->load($_prod->getId());
    $_md5_values = array();
     
    //protected base image
    $base_image = $_product->getImage();
    if($base_image != 'no_selection')
    {
        $filepath =  Mage::getBaseDir('media') .'/catalog/product' . $base_image  ;
        if(file_exists($filepath))
            $_md5_values[] = md5(file_get_contents($filepath));
    }
             
     
    $i ++;
    echo "\r\n processing product $i of $total ";
 
    // Loop through product images
    $_images = $_product->getMediaGalleryImages();
    if($_images){
        foreach($_images as $_image){
            //protected base image
            if($_image->getFile() == $base_image)
                continue;
             
            $filepath =  Mage::getBaseDir('media') .'/catalog/product' . $_image->getFile()  ;
            if(file_exists($filepath))
                $md5 = md5(file_get_contents($filepath));
            else
                continue;
             
 
            if(in_array($md5, $_md5_values))
            {
                $mediaApi->remove($_product->getId(),  $_image->getFile());
                echo "\r\n removed duplicate image from ".$_product->getSku();
                $count++;
            } else {
                $_md5_values[] = $md5;
            }   
 
        }
    }
     
}
echo "\r\n\r\n finished removed $count duplicated images";
I have a solution that you can adapt.
To delete them physically you need to run it with an import to be sure to have the good images at the end.
$_images = $product->getMediaGalleryImages();
if($_images){
foreach($_images as $_image){
$filepath = Mage::getBaseDir('media') .'/catalog/product' . $_image->getFile() ;
check if the both images (the one to import and the one that is present on the server) have the same size else
}
}
To delete from the database the image linked to a product (still during an import).
$query = "select value_id from catalog_product_entity_media_gallery where entity_id = ?";
$st = $cnx->prepare($query);
$st->execute(array($productId));
$row = $st->fetch();
while ($row !== false) {
$values2delete[] = $row['value_id'];
$row = $st->fetch();
}
$query = "delete from catalog_product_entity_media_gallery where value_id IN (". implode(',',$values2delete).")";
$st = $cnx->prepare($query);
$st->execute();
I do not use this two things in the same import so you need to marry them together. You can also fill the values2delete array during the check of the bad files.
I hope it helps

how to import discount coupon csv file in magento admin

I have a csv of coupon codes, i want to import it in magento.
please help me to how import it.
i have a script but its not working:-
<?php
$mageFilename = '/opt/bitnami/apps/magento/htdocs/app/Mage.php';
require_once $mageFilename;
Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app('default');
Mage::register('isSecureArea', 1);
function getAllWbsites(){
//get all wabsites
$websites = Mage::getModel('core/website')->getCollection();
$websiteIds = array();
foreach ($websites as $website){
$websiteIds[] = $website->getId();
}
return $websiteIds;
}
//read comments for each line
function generateRule($rulename, $desc, $status, $customerGroups, $couponCode, $fromDate, $toDate, $discountType, $discountAmount){
$couponCheck = Mage::getModel('salesrule/rule')->getCollection()
->addFieldToFilter('code',$couponCode)
->load();
$couponCheckArr = $couponCheck->getData();
if(count($couponCheckArr)>0) {
return false;
}
$rule = Mage::getModel('salesrule/rule');
$rule->setName($rulename);
$rule->setDescription($desc);
$rule->setFromDate($fromDate);//starting today
if($toDate!="") {
$rule->setToDate($toDate);//if you need an expiration date
}
$rule->setCouponCode($couponCode);
$rule->setUsesPerCoupon(1);//number of allowed uses for this coupon
$rule->setUsesPerCustomer(1);//number of allowed uses for this coupon for each customer
$customerGroups = explode(',',$customerGroups);
$rule->setCustomerGroupIds($customerGroups);//if you want only certain groups replace getAllCustomerGroups() with an array of desired ids
$rule->setIsActive($status);
$rule->setStopRulesProcessing(0);//set to 1 if you want all other rules after this to not be processed
$rule->setIsRss(0);//set to 1 if you want this rule to be public in rss
$rule->setIsAdvanced(1);//have no idea what it means :)
$rule->setProductIds('');
$rule->setSortOrder(0);// order in which the rules will be applied
$rule->setSimpleAction($discountType);
//all available discount types
//by_percent - Percent of product price discount
//by_fixed - Fixed amount discount
//cart_fixed - Fixed amount discount for whole cart
//buy_x_get_y - Buy X get Y free (discount amount is Y)
$rule->setDiscountAmount($discountAmount);//the discount amount/percent. if SimpleAction is by_percent this value must be <= 100
$rule->setDiscountQty(0);//Maximum Qty Discount is Applied to
$rule->setDiscountStep(0);//used for buy_x_get_y; This is X
$rule->setSimpleFreeShipping(0);//set to 1 for Free shipping
$rule->setApplyToShipping(0);//set to 0 if you don't want the rule to be applied to shipping
$rule->setWebsiteIds(getAllWbsites());//if you want only certain websites replace getAllWbsites() with an array of desired ids
$conditions = array();
$conditions[1] = array(
'type' => 'salesrule/rule_condition_combine',
'aggregator' => 'all',
'value' => 1,
'new_child' => ''
);
$rule->setData('conditions',$conditions);
$rule->loadPost($rule->getData());
$rule->setCouponType(2);
if($rule->save()) {
return true;
}
else {
return false;
}
}
$fp = fopen('coupons-feed.csv','r') or die("can't open file");
$count = 0;
$countNotImpt = 0;
$i = 0;
while($csv_line = fgetcsv($fp,1024,"\t")) {
if($i>0) {
$OneTime = $csv_line[0];
$Name = $csv_line[1];
$AlternateCode = $csv_line[2];
$DiscountType = $csv_line[3];
$MinCartValue = $csv_line[4];
$ProductsAssigned = $csv_line[5];
$Limitedtoone = $csv_line[6];
$ExcludeProducts = $csv_line[7];
$ExpirationDate = $csv_line[8];
$DateCreated = $csv_line[9];
if(generateRule($OneTime,$Name,$AlternateCode,$DiscountType,$MinCartValue,$ProductsAssigned,$Limitedtoone,$ExcludeProducts $ExpirationDate,$DateCreated )) {
$count++;
}
else{
$countNotImpt++;
}
}
$i++;
}
fclose($fp) or die("can't close file");
echo $count.' coupon successfully added.<br>';
echo $countNotImpt.' coupon already exits.<br>';
?>
i upload this script and csv on root . but its not working. please tell me about this beacause i am new in magento.
#Brar Kirmal, you can try the below script, I created this script for one of my project you can try in your project.
$mageFilename = 'Mage.php'; // it may different as per the location of this file
require_once $mageFilename;
Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app('default');
Mage::register('isSecureArea', 1);
function getAllWbsites(){
//get all wabsites
$websites = Mage::getModel('core/website')->getCollection();
$websiteIds = array();
foreach ($websites as $website){
$websiteIds[] = $website->getId();
}
return $websiteIds;
}
//read comments for each line
function generateRule($rulename, $desc, $status, $customerGroups, $couponCode, $fromDate, $toDate, $discountType, $discountAmount){
$couponCheck = Mage::getModel('salesrule/rule')->getCollection()
->addFieldToFilter('code',$couponCode)
->load();
$couponCheckArr = $couponCheck->getData();
if(count($couponCheckArr)>0) {
return false;
}
$rule = Mage::getModel('salesrule/rule');
$rule->setName($rulename);
$rule->setDescription($desc);
$rule->setFromDate($fromDate);//starting today
if($toDate!="") {
$rule->setToDate($toDate);//if you need an expiration date
}
$rule->setCouponCode($couponCode);
$rule->setUsesPerCoupon(1);//number of allowed uses for this coupon
$rule->setUsesPerCustomer(1);//number of allowed uses for this coupon for each customer
$customerGroups = explode(',',$customerGroups);
$rule->setCustomerGroupIds($customerGroups);//if you want only certain groups replace getAllCustomerGroups() with an array of desired ids
$rule->setIsActive($status);
$rule->setStopRulesProcessing(0);//set to 1 if you want all other rules after this to not be processed
$rule->setIsRss(0);//set to 1 if you want this rule to be public in rss
$rule->setIsAdvanced(1);//have no idea what it means :)
$rule->setProductIds('');
$rule->setSortOrder(0);// order in which the rules will be applied
$rule->setSimpleAction($discountType);
//all available discount types
//by_percent - Percent of product price discount
//by_fixed - Fixed amount discount
//cart_fixed - Fixed amount discount for whole cart
//buy_x_get_y - Buy X get Y free (discount amount is Y)
$rule->setDiscountAmount($discountAmount);//the discount amount/percent. if SimpleAction is by_percent this value must be <= 100
$rule->setDiscountQty(0);//Maximum Qty Discount is Applied to
$rule->setDiscountStep(0);//used for buy_x_get_y; This is X
$rule->setSimpleFreeShipping(0);//set to 1 for Free shipping
$rule->setApplyToShipping(0);//set to 0 if you don't want the rule to be applied to shipping
$rule->setWebsiteIds(getAllWbsites());//if you want only certain websites replace getAllWbsites() with an array of desired ids
$conditions = array();
$conditions[1] = array(
'type' => 'salesrule/rule_condition_combine',
'aggregator' => 'all',
'value' => 1,
'new_child' => ''
);
$rule->setData('conditions',$conditions);
$rule->loadPost($rule->getData());
$rule->setCouponType(2);
if($rule->save()) {
return true;
}
else {
return false;
}
}
$fp = fopen('coupon.csv','r') or die("can't open file");// replace it with your file name and location
$count = 0;
$countNotImpt = 0;
$i = 0;
while($csv_line = fgetcsv($fp,1024,"\t")) {
if($i>0) {
$rulename = $csv_line[0];
$desc = $csv_line[1];
$status = $csv_line[2];
$customerGroups = $csv_line[3];
$couponCode = $csv_line[4];
$fromDate = $csv_line[5];
$toDate = $csv_line[6];
$discountType = $csv_line[7];
$discountAmount = $csv_line[8];
if(generateRule($rulename, $desc, $status, $customerGroups, $couponCode, $fromDate, $toDate, $discountType, $discountAmount)) {
$count++;
}
else{
$countNotImpt++;
}
}
$i++;
}
fclose($fp) or die("can't close file");
echo $count.' coupon successfully added.<br>';
echo $countNotImpt.' coupon already exits.<br>';

How to create custom script for import products in magento

I am working on magento 1.8 version.
I need to create custom script or extenson for import product from my custom csv file which have some different fields.
Any help would be much appriciated.
Thanks
Best way is to use OS Magmi, is much more faster than script an is simple to configure and periodical run.
http://sourceforge.net/projects/magmi/
You can also create a script which can you run.
you need to get data from csv file to memory
2 convert them to array
3 list array for each product
4 in foreach loop save or update product.
Some basic script:
<?php
$max_i = 20000; // maximal ammount
chdir(dirname(__FILE__)); /
//error_reporting(E_ALL | E_STRICT);
//ini_set("display_errors", 1);
ini_set("memory_limit","1024M");
ini_set('max_execution_time', 3600000);
date_default_timezone_set('Europe/Prague');
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$time_start = microtime_float();
//////// SKU from CSV
$csv = file_get_contents ('yourcsvfile.csv');
function parse_csv ($csv_string, $delimiter = ";", $skip_empty_lines = true, $trim_fields = true)
{
$enc = preg_replace('/(?<!")""/', '!!Q!!', $csv_string);
$enc = preg_replace_callback(
'/"(.*?)"/s',
function ($field) {
return urlencode(utf8_encode($field[1]));
},
$enc
);
$lines = preg_split($skip_empty_lines ? ($trim_fields ? '/( *\R)+/s' : '/\R+/s') : '/\R/s', $enc);
return array_map(
function ($line) use ($delimiter, $trim_fields) {
$fields = $trim_fields ? array_map('trim', explode($delimiter, $line)) : explode($delimiter, $line);
return array_map(
function ($field) {
return str_replace('!!Q!!', '"', utf8_decode(urldecode($field)));
},
$fields
);
},
$lines
);
}
// list to array
$vystup = parse_csv($csv);
$seznamsku = array();
foreach ($vystup as $sku) {
array_push($seznamsku, $sku[0]);
unset($seznamsku[0]);
$seznamskufin = array_filter($seznamsku, 'strlen');
};
require("../../app/Mage.php");
echo "START ".date('h:i:s')."\n\n";
Mage::init();
// Set an Admin Session
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
Mage::getSingleton('core/session', array('name' => 'adminhtml'));
$userModel = Mage::getModel('admin/user');
$userModel->setUserId(1);
$session = Mage::getSingleton('admin/session');
$session->setUser($userModel);
$session->setAcl(Mage::getResourceModel('admin/acl')->loadAcl());
$pocet = 1;
foreach ($seznamskufin as $item) {
echo "\n number(".$pocet.")..sku(".$item.")..";
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$item);
if(is_object($product)) { //if is product exist in Magento
if (empty($product->getShortDescription())) { // if is value empty
$product->setShortDescription($ZboziDetail['info']); // write to magento
echo "..(importing)..";
}
else
{
echo "..(skipped).."; // exists
};
$product->save(); // save to magento
echo "..saved";
} else { echo ".(skiped)"; };
unset($item);
unset($product);
unset($ZboziDetail);
unset($product_imageUrl);
unset($newimage);
unset($e);
$pocet++;
};
$time_end = microtime_float();
$time = $time_end - $time_start;
echo " \n\n All done in ".$time." seconds.";
$logfile = fopen('log.txt', 'a');
fwrite($logfile, $seznamskufin);
fclose($logfile);
unset($response);
unset($vystup);
unset($seznamsku);
unset($seznamskufin);
?>
I think the easiest and safest way is to create a simple script (outside Magento) that transforms your csv to the csv structure used for import in System->Import/Export->Import.
TO see the format of the csv you need go to System->Import/Export->Export and export your current products.

Creating Configurable product on import csv

When a new simple product is added (via CSV or manually) we need to check if the appropriate configurable product has been added (where SKU = "item_number-item_colour_code" e.g. BLEA2606B-BK001). If the configurable product exists then associate the simple product. If the configurable product does not exist then create using the data in the simple product AND then associate the simple product.
I found some help from HERE but don't know how check if configurable product already exists, and if not how to create one.
Here is the script file that I downloaded. Can anybody advice if this will work with my scenario?
EDITED
I have scraped the idea of creating configurable product in import. I am doing it by capturing the catalog_product_save_after event now. Hopefully that will get me somewhere.
EDITED 2
OK, Finally, I have it working. I'm doing it in the observer. I know it slows down the product save process but couldn't think of any other way. Thats what I'm doing:
public function productSave($observer)
{
$p = $observer->getProduct();
$pr = Mage::getModel('catalog/product')->load($p->getId());
$attributeValue = Mage::getResourceModel('catalog/product')->getAttributeRawValue($pr->getId(), 'size'); //loads attribute option value
$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($pr)->getQty();
Mage::log('Qty: '.$qtyStock.$pr->getId(), null, 'test.txt');
if ($pr->getTaxClassId() == '0' || !isset($pr->getTaxClassId)) {
$taxClass = 'None';
} elseif ($pr->getTaxClassId() == '2') {
$taxClass = 'Taxable Goods';
} elseif ($pr->getTaxClassId() == '4') {
$taxClass = 'Shipping (not used by AvaTax)';
} elseif ($pr->getTaxClassId() == '5') {
$taxClass = 'General';
}
$_configSku = $pr->getItemNumber().'-'.$pr->getItemColourCode();
$category = array();
$categoryCollection = $pr->getCategoryCollection();
foreach ($categoryCollection as $cat) {
$category[] = $cat->getId();
}
$_configExist = Mage::getModel('catalog/product')->loadByAttribute('sku',$_configSku);
if($_configExist && $_configSku != '-') {
//Mage::log($_configExist, null, 'test.txt');
//Mage::log($_configSku, null, 'test.txt');
$new_ids = array();
$current_ids = $_configExist->getTypeInstance()->getUsedProductIds();
foreach($current_ids as $temp_id)
{
$new_ids[] = $temp_id;
}
}
if(!$_configExist && $_configSku != '-') {
$att_size = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product','size');
$att_sizes = $this->__getAttList('size');
$confProduct = Mage::getModel('catalog/product');
$confProduct->setAttributeSetId('10');
$confProduct->setSku($_configSku);
$confProduct->setTypeId('configurable');
$confProduct->setName($pr->getName());
$confProduct->setDescription($pr->getDescription());
$confProduct->setShortDescription($pr->getShortDescription());
$confProduct->setCreatedAt(strtotime('now'));
$confProduct->setPrice($pr->getPrice());
$confProduct->setStatus(1);
$confProduct->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$confProduct->setWebsiteIDs(array(1));
$confProduct->setStockData(array(
'is_in_stock' => 1,
'qty' => 9999
));
$confProduct->setTaxClassId( $taxClass );
$confProduct->setCategoryIds( $category );
/* Set Configurable Attributes */
$confProduct->setConfigurableAttributesData($tmp = array(
array_merge($att_size->getData(), array('label' => '', 'values' => $size_values))
));
$simpleProducts = array(
$pr->getId()=>array( 'attribute_id'=>'145', 'label'=>'size', 'value_index'=>$attributeValue, 'is_percent'=>0, 'pricing_value'=>'' )
);
/* Set Associated Products */
$confProduct->setConfigurableProductsData( $simpleProducts );
//print_r( get_class_methods( $confProduct ) );
$confProduct->save();
}
elseif ($_configExist && !in_array($pr->getId(), $new_ids)) {
$new_ids = array();
$current_ids = $_configExist->getTypeInstance()->getUsedProductIds();
$current_ids[] = $pr->getId();
$current_ids = array_unique($current_ids);
foreach($current_ids as $temp_id)
{
parse_str("position=", $new_ids[$temp_id]);
}
Mage::log('inside', null, 'test.txt');
Mage::log($current_ids, null, 'test.txt');
$_configExist->setConfigurableProductsData($new_ids)->save();
}
All works fine with manual product save/update and import csv (it is slow but works). The only thing is, in configurable product, the Attribute Name field is empty. How to set attribute name there?
with magmi you can easily create configurable products, and more awesome stuff
I have found the way. See EDITED 2 section in the question for the solution.

Resources