Showing posts with label import. Show all posts
Showing posts with label import. Show all posts

Wednesday, June 9, 2010

Adding related products, up-sells and cross-sells programmaticly

Problem:
Adding related products, up-sells and cross-sells programmaticly.
http://www.magentocommerce.com/boards/viewthread/195440/

Possible solution:

In order to set related, up-sells and crosssells you need to do the following
Let's assume that the current product is $_product (that you got by doing Mage::getModel('catalog/product')->load(SOME ID))
//for related
$_product->setRelatedLinkData($param);
//for up-sells
$_product->setUpSellLinkData($param);
//for crosssells
$_product->setCrossSellLinkData($param);
$param is an array with the following structure
$param = array(
$associatedProductId=>array(
'position'=>$associatedProductPosition
)
)

Here is an example. Let's say you want to add products with ids 101 and 102 as related products to $_product on positions 3 and 5.
You should do something like this:

$param = array(
101=>array(
'position'=>3
),
102=>array(
'position'=>5
)
);
$_product->setRelatedLinkData($param);
//here ... some other product operations and in the end
$_product->save();

It works the same for up-sells and crosssels.

Monday, May 17, 2010

Import products update

This is an update for http://marius-strajeru.blogspot.com/2009/11/import-simple-products-for-barrmy.html

Starting version 1.4 you can only perform product updates 'programmatic' only if Magento thinks you are in the admin panel.

If you try to do this from a non-admin page make sure you put this

Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
before you call
$product->save();

Thursday, April 1, 2010

Create bulk discount rules

Problem:
Create bulk discount rules with unique coupon codes.
Details found here: http://www.magentocommerce.com/boards/viewthread/177465/
Possible solution:
This is not an extension, it's just a 'quick and dirty' script that I hope some day (when I have the time) will grow up and become an extension.

put the code below into a file (let's call it coupons.php) and follow the instructions below:

<?php
$mageFilename = '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 generateUniqueId($length = null){
$rndId = crypt(uniqid(rand(),1)); 
$rndId = strip_tags(stripslashes($rndId)); 
$rndId = str_replace(array(".", "$"),"",$rndId); 
$rndId = strrev(str_replace("/","",$rndId));
if (!is_null($rndId)){
return strtoupper(substr($rndId, 0, $length));
} 
return strtoupper($rndId);
} 
function getAllCustomerGroups(){
//get all customer groups
$customerGroups = Mage::getModel('customer/group')->getCollection();
$groups = array();
foreach ($customerGroups as $group){
$groups[] = $group->getId();
}
return $groups;
}
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(){
$uniqueId = generateUniqueId(10);
$rule = Mage::getModel('salesrule/rule');
$rule->setName($uniqueId);
$rule->setDescription('Generated by tzyganu');
$rule->setFromDate(date('Y-m-d'));//starting today
//$rule->setToDate('2011-01-01');//if you need an expiration date
$rule->setCouponCode($uniqueId);
$rule->setUsesPerCoupon(1);//number of allowed uses for this coupon
$rule->setUsesPerCustomer(1);//number of allowed uses for this coupon for each customer
$rule->setCustomerGroupIds(getAllCustomerGroups());//if you want only certain groups replace getAllCustomerGroups() with an array of desired ids 
$rule->setIsActive(1);
$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('by_percent');
//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('20');//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(1);//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", //[UPDATE] added quotes on the value. Thanks Aziz Rattani [/UPDATE]
'new_child' => ''
);
//the conditions above are for 'if all of these conditions are true'
//for if any one of the conditions is true set 'aggregator' to 'any'
//for if all of the conditions are false set 'value' to 0.
//for if any one of the conditions is false set 'aggregator' to 'any' and 'value' to 0
$conditions['1--1'] = Array
(
'type' => 'salesrule/rule_condition_address',
'attribute' => 'base_subtotal',
'operator' => '>=',
'value' => 200
);
//the constraints above are for 'Subtotal is equal or grater than 200'
//for 'equal or less than' set 'operator' to '<='... You get the idea other operators for numbers: '==', '!=', '>', '<'
//for 'is one of' set operator to '()';
//for 'is not one of' set operator to '!()';
//in this example the constraint is on the subtotal
//for other attributes you can change the value for 'attribute' to: 'total_qty', 'weight', 'payment_method', 'shipping_method', 'postcode', 'region', 'region_id', 'country_id'

//to add an other constraint on product attributes (not cart attributes like above) uncomment and change the following:
/*
$conditions['1--2'] = array
(
'type' => 'salesrule/rule_condition_product_found',//-> means 'if all of the following are true' - same rules as above for 'aggregator' and 'value'
//other values for type: 'salesrule/rule_condition_product_subselect' 'salesrule/rule_condition_combine'
'value' => 1,
'aggregator' => 'all',
'new_child' => '', 
);

$conditions['1--2--1'] = array
(
'type' => 'salesrule/rule_condition_product',
'attribute' => 'sku',
'operator' => '==',
'value' => '12',
);
*/
//$conditions['1--2--1'] means sku equals 12. For other constraints change 'attribute', 'operator'(see list above), 'value'

$rule->setData('conditions',$conditions);
$rule->loadPost($rule->getData());
$rule->save();
//[UPDATE]if you work with Mangento EE and you want to link banners to your rule uncomment the line of code below
//Mage::getResourceModel('enterprise_banner/banner')->bindBannersToSalesRule($rule->getId(), array(1,2));//the array(1,2, ...) is the array with all the banners you want to link to the rule.
//[/UPDATE]
}
?>


[UPDATE]. This was made for Magento 1.3 and lower. For versions >= 1.4 you have to add a new line
$rule->setCouponType(2);
Add it just before
$rule->save();
(Thanks Raj for pointing this out).
[/UPDATE]

[UPDATE 1.1]
For Magento 1.4 and later there are store labels for the discount rules.
To add this construct the following array
$labels = array();
$labels[0] = 'Default store label';//default store label
$labels[1] = 'Label for store with id 1';
//....
$labels[n] = 'Label for store with id n';
//add one line for each store view you have. The key is the store view ID

and before calling $rule->save(); add this line
$rule->setStoreLabels($labels);

(Thanks Sigmund for the update)
[/UPDATE 1.1]

Put the newly created file in the root of your magento installation (same level as index.php)
Walk through the file read all the comments and configure your discount settings (some programming skills are requred)
After everything is done add the following code at the end of the file (before php closing tag)

for ($i=1;$i<=200;$i++){//replace 200 with the number of coupons you want
generateRule();
}
[UPDATE 1.2]
If you want a nice script to import coupons using csv files with code, description and discount check this out: http://www.gielberkers.com/bulk-import-coupon-codes-in-magento/
Nice job Giel :). [/UPDATE 1.2]
call the page in you browser (http://your.magento.root/coupons.php) or run it from the command line.
Now check your admin for the new added rules.
PS (this does not work yet for 'Actions' tab).

Wednesday, November 25, 2009

Import Simple Products (for barrmy)

You don't need to import the data directly in the into the tables. My suggestion is to use the models provided by magento (that's why it's a MVC).

Create an product instance like this:

$product = Mage::getModel('catalog/product');

set the data you need
$product->setName('PRODUCT NAME');
$product->setDescription('PRODUCT DESCRIPTION');
and so on.
To add stock to this:
$stock_data=array(
'use_config_manage_stock' => 1,
'qty' => 998,
'min_qty' => 0,
'use_config_min_qty'=>1,
'min_sale_qty' => 0,
'use_config_min_sale_qty'=>1,
'max_sale_qty' => 9999,
'use_config_max_sale_qty'=>1,
'is_qty_decimal' => 0,
'backorders' => 0,
'notify_stock_qty' => 0,
'is_in_stock' => 1
);
$product->setData('stock_data',$stock_data);

If you have more that 1 website you must specify on which website to appear
$product->setWebsiteIds(array(1,2));
To add categories:
$product->setCategoryIds(array(7,10));
Set status
$product->setStatus(1);//1=Enabled; 2=Disabled;
Set visibility
$product->setVisibility(4);//4 = catalog & search.
For photos:
$product->addImageToMediaGallery('path/to/photo', array('image', 'small_image', 'thumbnail'), false, false);

second parameter can be replaced by null for a regular image. You can test the difference :)

After all the attributes are set just call
$product->save();
and Magento will put all the attributes in the right table.
If you want to update a product, do the same but instead of creating an "empty" instance of a product, load one.
$product = Mage::getModel('catalog/product')->load(PRODUCT ID);

This will work if you want to modify the default values. If you want to modify the values for a specific store do this.
$product = Mage::getModel('catalog/product')->setStoreId(STORE ID)->load(PRODUCT ID);
These are the basics. If you want a "fine tuned" product creation you just have to play around with the attributes setData() method.

It's not easy. You need some programming skills, but it can be done.

You can find an update to this post here:
http://marius-strajeru.blogspot.com/2010/05/import-products-update.html