Thursday, January 5, 2012

Apply coupon discount on Original Price not on special price in magento programmatically

Hi,

In Magento Default coupon code will apply to special price if special price is there else it will apply to original price ,
but in some case we need to apply coupon code discount to original price and then apply to special price
EX:- Special price 1000
Original Price :- 2000
Coupon discount is 10%

Then in cart page it will show special price- discountamount( acc to special price) i't 1000-100 = 900

but we need special price- discountamount( acc to Original price) i'e 1000- 200 =800

for that we need to create a event

add this xml code in config.xml in side events tag i'e <events></events>




<!-- event for default coupon but discount will apply for MRP-->
            <salesrule_validator_process>
                <observers>
                    <new_dicount_coupon>
                        <type>singleton</type>
                        <class>Namespcae_Modulename_Model_Observer</class>
                        <method>newcoupondiscountcal</method>
                    </new_dicount_coupon>
                </observers>
            </salesrule_validator_process>



And created Observer.php inside your module/model if not exists else add only this function newcoupondiscountcal($observer) in side Observer class



class Namespcae_Modulename_Model_Observer
{


//event for default coupon but discount will apply for MRP
public function newcoupondiscountcal($observer)
{

$item=$observer['item'];
$rule=$observer['rule'];
$rulePercent = max(0, 100-$rule->getDiscountAmount());
//print_r($rule->getData()); exit;

if($rule->getSimpleAction()=='by_percent') {
$disPer=$rule->getDiscountAmount();
$product=Mage::getModel('catalog/product')->load($item->getProductId());
$ratdisc=($product->getPrice()*$disPer)/100;
$DiscountAmount=$ratdisc+$item->getDiscountAmount();
$BaseDiscountAmount=$ratdisc+$item->setBaseDiscountAmount();

$result = $observer['result'];
$result->setDiscountAmount($DiscountAmount);
$result->setBaseDiscountAmount($BaseDiscountAmount);

}
}


clear cache and apply the code

Tuesday, January 3, 2012

Creating or Calling deafult Soap or Webservice API in magento programmatically

Hi,

As you all know in magneto we can create web services by using soap in magento
Magento as set of default API, i am using one default api writing code please check it

First Create web service user and role in magneto back end (system->Web Service) and assign roles to user

Enable soap dll i'e extension=php_soap.dll from your php.ini file

Paste this code in file and place this file in root folder or as you wish and run this file through browser




<?php
$proxy = new SoapClient('http://yourdomine/index.php/api/soap/?wsdl');

$sessionId = $proxy->login('USERNAME', 'API_Key');  // you will get this when you create web service user in admin side
     
   $filters = array(
    'sku' => array('like'=>'test%')
);
 
$products = $proxy->call($sessionId, 'product.list', array($filters));
 
var_dump($products);

?>

Monday, December 26, 2011

Creating a new attribute and adding to attribute set with groups in magento programmatically

Hi,

We can create new attribute and adding to attribute set with particular groups in magento programmatically




$attribute_set_name="Default";  //attribute set name
 $group_name="New Attribute";  //  Inside attribue set you will get groups  ex:- General, prices etc
  //My "simple product only" attribute
createAttribute(strtolower(str_replace(" ", "_", 'Cable Functionality')), "Cable Functionality", "select", "simple",$attribute_set_name,$group_name);

function createAttribute($code, $label, $attribute_type, $product_type, $attribute_set_name, $group_name )
{
    $_attribute_data = array(
        'attribute_code' => $code,
        'is_global' => '1',
        'frontend_input' => $attribute_type, //'boolean',
        'default_value_text' => '',
        'default_value_yesno' => '0',
        'default_value_date' => '',
        'default_value_textarea' => '',
        'is_unique' => '0',
        'is_required' => '0',
        'apply_to' => array($product_type), //array('grouped')
        'is_configurable' => '0',
        'is_searchable' => '0',
        'is_visible_in_advanced_search' => '0',
        'is_comparable' => '0',
        'is_used_for_price_rules' => '0',
        'is_wysiwyg_enabled' => '0',
        'is_html_allowed_on_front' => '1',
        'is_visible_on_front' => '0',
        'used_in_product_listing' => '0',
        'used_for_sort_by' => '0',
        'frontend_label' => array($label)
    );
 
    $model = Mage::getModel('catalog/resource_eav_attribute');
 
    if (!isset($_attribute_data['is_configurable'])) {
        $_attribute_data['is_configurable'] = 0;
    }
    if (!isset($_attribute_data['is_filterable'])) {
        $_attribute_data['is_filterable'] = 0;
    }
    if (!isset($_attribute_data['is_filterable_in_search'])) {
        $_attribute_data['is_filterable_in_search'] = 0;
    }
 
    if (is_null($model->getIsUserDefined()) || $model->getIsUserDefined() != 0) {
        $_attribute_data['backend_type'] = $model->getBackendTypeByInput($_attribute_data['frontend_input']);
    }
 
    $defaultValueField = $model->getDefaultValueByInput($_attribute_data['frontend_input']);
    if ($defaultValueField) {
      //  $_attribute_data['default_value'] = $this->getRequest()->getParam($defaultValueField);
    }
 
    $model->addData($_attribute_data);
 
    $model->setEntityTypeId(Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId());
    $model->setIsUserDefined(1);
    try {
        $model->save();
  $setup = new Mage_Eav_Model_Entity_Setup('core_setup');
   //-------------- add attribute to set and group

   $attribute_code = $code;

            $attribute_set_id=$setup->getAttributeSetId('catalog_product', $attribute_set_name);
            $attribute_group_id=$setup->getAttributeGroupId('catalog_product', $attribute_set_id, $group_name);
            $attribute_id=$setup->getAttributeId('catalog_product', $attribute_code);

            $setup->addAttributeToSet($entityTypeId='catalog_product',$attribute_set_id, $attribute_group_id, $attribute_id);
  
    } catch (Exception $e) { echo '<p>Sorry, error occured while trying to save the attribute. Error: '.$e->getMessage().'</p>'; }
}

Sunday, December 25, 2011

Adding images from third party server or external server to product in magneto programmatically

Hi,

We can add images to product from 3ed party server programmatically in magneto

thing you will have images URL in array



$product=Mage::getModel('catalog/product')->load($productId);

$images=array('http://p.imgci.com/db/PICTURES/CMS/140500/140554.icon.jpg','http://p.imgci.com/db/PICTURES/CMS/140500/140553.icon.jpg');
for($j=0;$j<count($images);$j++){
  $image_url  =$images[$j]; //get external image url from csv
    
  $image_url  =str_replace("https://", "http://", $image_url); // repalce https tp http
  //echo $image_url;
  $image_type = substr(strrchr($image_url,"."),1); //find the image extension
  $filename   = $sku.$j.'.'.$image_type; //give a new name, you can modify as per your requirement
  $filepath   = Mage::getBaseDir('media') . DS . 'import'. DS . $filename; //path for temp storage folder: ./media/import/
  file_put_contents($filepath, file_get_contents(trim($image_url))); //store the image from external url to the temp storage folder
  //echo $filepath; exit;

  $filepath_to_image=$filepath;
  $mediaAttribute = array (
    'thumbnail',
    'small_image',
    'image'
  );
 $product->addImageToMediaGallery($filepath_to_image, $mediaAttribute, true, false);

   }

Friday, December 23, 2011

Adding product from fornt-end with image in mangento programmatically

Hi,

We can add a product from frond end in magneto Paste this code in file and place the file in root folder of project run this file in browser product will created and also give image correct path the image also uploaded




<?php
 define('MAGENTO', realpath(dirname(__FILE__)));
 require_once MAGENTO . '/app/Mage.php';
 Mage::app();
 $storename='default';
 
  

//$product = Mage::getModel('catalog/product');
$product = new Mage_Catalog_Model_Product();
echo time();
// Build the product
$product->setAttributeSetId(4);// #4 is for default
$product->setTypeId('simple');

$product->setName('Some cool product name');
$product->setDescription('Full description here');
$product->setShortDescription('Short description here');
$product->setSku(time());
$product->setWeight(4.0000);
$product->setStatus(1);
$filepath_to_image='image.jpg';
$mediaAttribute = array (
                'thumbnail',
                'small_image',
                'image'
        );
$product->addImageToMediaGallery($filepath_to_image, $mediaAttribute, true, false);
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);//4
print_r(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);

$product->setPrice(39.99);// # Set some price
$product->setTaxClassId(0);// # default tax class

$product->setStockData(array(
'is_in_stock' => 1,
'qty' => 99999
));

$product->setCategoryIds(array(27));// # some cat id's,

$product->setWebsiteIDs(array(1));// # Website id, 1 is default

//Default Magento attribute

$product->setCreatedAt(strtotime('now'));


//print_r($product);
try {
    $product->save();
    echo "Product Created";
}
catch (Exception $ex) {
    //Handle the error
    echo "Product Creation Failed";
}

?>

Tuesday, December 20, 2011

Applying Custom discount amount in magento

Hi,

In few case you have to write a code so that custom discount as to apply to cart

either you can ave discount amount in Db or static i am showing the cod for static one

in your custom module etc/config.xml add this code in side global tag
<?xml version="1.0"?>
<config>
    <modules>
        <Sugarcode_Customdiscount>
            <version>1.0.10</version>
        </Sugarcode_Customdiscount>
    </modules>
    
    
    <global>
 
        <events>
        <!-- Création éventuelle du lien de parrainage lors de la commande -->
            <sales_quote_collect_totals_after>
                <observers>
                    <set_custom_discount_suagrcode>
                        <type>singleton</type>
                        <class>Sugarcode_Customdiscount_Model_Observer</class>
                        <method>setDiscount</method>
                    </set_custom_discount_suagrcode>
                </observers>
            </sales_quote_collect_totals_after>             
   
  </events>
        
    </global>

   
</config>

and inside model folder create file called Observer.php
(if only custom discount)

 <?php
/**
 * @category   Sugarcode
 * @package    Sugarcode_Customdiscount
 * @author     pradeep.kumarrcs67@gmail.com
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */
class Sugarcode_Customdiscount_Model_Observer
{

    
 public function setDiscount($observer)
    {
       $quote=$observer->getEvent()->getQuote();
       $quoteid=$quote->getId();
       $discountAmount=10;
    if($quoteid) {
       
       
      
        if($discountAmount>0) {
  $total=$quote->getBaseSubtotal();
   $quote->setSubtotal(0);
   $quote->setBaseSubtotal(0);

   $quote->setSubtotalWithDiscount(0);
   $quote->setBaseSubtotalWithDiscount(0);

   $quote->setGrandTotal(0);
   $quote->setBaseGrandTotal(0);
  
    
   $canAddItems = $quote->isVirtual()? ('billing') : ('shipping'); 
   foreach ($quote->getAllAddresses() as $address) {
    
   $address->setSubtotal(0);
            $address->setBaseSubtotal(0);

            $address->setGrandTotal(0);
            $address->setBaseGrandTotal(0);

            $address->collectTotals();

            $quote->setSubtotal((float) $quote->getSubtotal() + $address->getSubtotal());
            $quote->setBaseSubtotal((float) $quote->getBaseSubtotal() + $address->getBaseSubtotal());

            $quote->setSubtotalWithDiscount(
                (float) $quote->getSubtotalWithDiscount() + $address->getSubtotalWithDiscount()
            );
            $quote->setBaseSubtotalWithDiscount(
                (float) $quote->getBaseSubtotalWithDiscount() + $address->getBaseSubtotalWithDiscount()
            );

            $quote->setGrandTotal((float) $quote->getGrandTotal() + $address->getGrandTotal());
            $quote->setBaseGrandTotal((float) $quote->getBaseGrandTotal() + $address->getBaseGrandTotal());
 
   $quote ->save(); 
 
      $quote->setGrandTotal($quote->getBaseSubtotal()-$discountAmount)
      ->setBaseGrandTotal($quote->getBaseSubtotal()-$discountAmount)
      ->setSubtotalWithDiscount($quote->getBaseSubtotal()-$discountAmount)
      ->setBaseSubtotalWithDiscount($quote->getBaseSubtotal()-$discountAmount)
      ->save(); 
      
    
    if($address->getAddressType()==$canAddItems) {
    //echo $address->setDiscountAmount; exit;
     $address->setSubtotalWithDiscount((float) $address->getSubtotalWithDiscount()-$discountAmount);
     $address->setGrandTotal((float) $address->getGrandTotal()-$discountAmount);
     $address->setBaseSubtotalWithDiscount((float) $address->getBaseSubtotalWithDiscount()-$discountAmount);
     $address->setBaseGrandTotal((float) $address->getBaseGrandTotal()-$discountAmount);
     if($address->getDiscountDescription()){
     $address->setDiscountAmount(-($address->getDiscountAmount()-$discountAmount));
     $address->setDiscountDescription($address->getDiscountDescription().', Custom Discount');
     $address->setBaseDiscountAmount(-($address->getBaseDiscountAmount()-$discountAmount));
     }else {
     $address->setDiscountAmount(-($discountAmount));
     $address->setDiscountDescription('Custom Discount');
     $address->setBaseDiscountAmount(-($discountAmount));
     }
     $address->save();
    }//end: if
   } //end: foreach
   //echo $quote->getGrandTotal();
  
  foreach($quote->getAllItems() as $item){
                 //We apply discount amount based on the ratio between the GrandTotal and the RowTotal
                 $rat=$item->getPriceInclTax()/$total;
                 $ratdisc=$discountAmount*$rat;
                 $item->setDiscountAmount(($item->getDiscountAmount()+$ratdisc) * $item->getQty());
                 $item->setBaseDiscountAmount(($item->getBaseDiscountAmount()+$ratdisc) * $item->getQty())->save();
                
               }
            
                
            }
            
    }
 }

}