Search This Blog

Showing posts with label boosting magento site. Show all posts
Showing posts with label boosting magento site. Show all posts

Aug 16, 2011

Magento: How to Get Product Collection by Type

Magento composed of 5 product type named as the following: simple, configurable, bundle, grouped, and virtual. Each product type has its own corresponding features that suit on every products that you’re planning to sell. Choosing though, must be done carefully in order to have an easy product management and enable wide range product marketing plan.

To get the collection of product according to their type, do the following code.

Simple Product

$collectionSimple = Mage::getResourceModel('catalog/product_collection')
                ->addAttributeToFilter('type_id', array('eq' => 'simple'));
 

Configurable Product

$collectionConfigurable = Mage::getResourceModel('catalog/product_collection')
                ->addAttributeToFilter('type_id', array('eq' => 'configurable'));

 

Bundle Product

$collectionBundle = Mage::getResourceModel('catalog/product_collection')
                ->addAttributeToFilter('type_id', array('eq' => 'bundle'));
 
 

Grouped Product

$collectionGrouped = Mage::getResourceModel('catalog/product_collection')
                ->addAttributeToFilter('type_id', array('eq' => 'grouped'));
  

Virtual Product

$collectionVirtual = Mage::getResourceModel('catalog/product_collection')
                ->addAttributeToFilter('type_id', array('eq' => 'virtual'));

 

May 23, 2011

Magento: Dummy Credit Card Numbers for Testing

It is necessary for magento developers to test magento processes such as customer login, buying products, taxes and shipping computation and so on.

Testing credit card in your payment is the most important one, since it involves money. I will give you some dummy test credit card numbers which are easy and safe to use. These credit card numbers validate properly but discourage using in production site.

American Express:
378282246310005
3111111111111117
343434343434343
370000000000002
340000000000009
371449635398431
378734493671000
Visa:
4111111111111111
4007000000027
4222222222222
4012888888881881
MasterCard:
5105105105105100
5111111111111118
5454545454545454
5500000000000004
5555555555551111
5555555555554444
Discover:
6011111111111117
6011000000000004
6011000990139424
6011601160116611
6111111111111116

May 22, 2011

Creating Batch Shipment in Magento via API

How the process goes?


I successfully created a daily order importation script from Magento database to the fulfillment center last week as part of client requirements. The script dumped a csv file containing daily orders and passed it in fulfillment in a daily basis. Since it is a one way process, client also want me to create a script which will update the order status based on the fulfillment confirmation file. The fulfillment is sending back an confirmation file which formated in comma separated value (csv) that contains completed orders. Base on that file, the script will update the order status in Magento automatically(of course by setting up a cron job).


Preparing the script


The whole process need two files:
1. Confirmation file (csv or a text file)
2. php script

Confirmation file – it comma separated format, where order and tracking numbers is include.
Example.
InvoiceNumber,ShipCharge,ShipWeight,ShipDate,TrackingNumber,ShipMethod
100000222,8.8200,2.0,2010-09-22 14:40:02.000,01805213907832456279,upsprt
The first line is your csv header, and next lines onward are their values.
php script - a script which will do the process. The script use Magento api.

Step 1 - create a database connection

function sql_connect($server_host, $mysql_user, $mysql_password,$own_db){
$link = mysql_connect($server_host, $mysql_user, $mysql_password);
if (!$link) {
  die('Could not connect: ' . mysql_error());
}
 $db_selected = mysql_select_db($own_db, $link);
 if (!$db_selected) {
   die ('Can\'t use ' . $own_db . ' : ' . mysql_error());
 }else{
  echo 'Connect Successfully'." <br>"; 
 } 
}

Step 2 - Call the sql_connect function and replace the credentials variable with the correct one.

/*
* prepare credentials - 
* then connect through sql_connect function
*/

$server_host  = '';

$sql_username = '';
$sql_password = '';
$own_db    = '';

sql_connect($server_host, $sql_username,$sql_password,$own_db);


Step 3 - include the mage.php in order to use Magento api

/*
* include the mage.php file and the app() class
* set default value for email and comment
*/

require_once("../store/app/Mage.php");  // please change with correct path...

Mage::app();

$comment     = null;
$email      = false;
$includeComment = false;


Step 4 - make sure you have standard naming for your csv file.

Example

shipment20110521.csv
shipment20110520.csv

Notice that the name is change only in date. In that case you can apply the following code. The code is setup to get yesterdays order.
/*
* get the date of the yesterday orders
* this is the basis of the order file name
* shipment.$last_order is the standard name of csv file.
*/

$last_order = date('Ymd', strtotime('yesterday'));

$source = "shipment".$last_order.".csv";

Step 5 - do a looping for each order in the csv and create shipment for each order.

/*
* get information from the csv file
* declare variables 
* look for the order no., tracking no., and method
*/

$row = 1;
$row_info  = array();

if (($handle = fopen($source, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        
       if ($row > 1){
          for ($c=0; $c < $num; $c++) {
         
      switch ($c) {
         case 0:
             $row_info['invoice_no'] = $data[$c]; 
             $order_id = trim($row_info['invoice_no']);
             break;
         case 1:
             $row_info['ship_charge'] = $data[$c]; 
             break;
         case 2:
             $row_info['ship_weight'] = $data[$c]; 
             break;
         case 3:
             $row_info['ship_date'] = $data[$c]; 
             break;
          case 4:
             $row_info['tracking_no'] = $data[$c]; 
             $tracking_no = $row_info['tracking_no'];
             break;
        
         case 5:
             $row_info['ship_method'] = $data[$c]; 
             
                if (preg_match("/ups/", $row_info['ship_method']))
             {
              $row_ship_method = "United Parcel Service";
              $row_carrier_code = "ups";
             }
            if (preg_match("/USP/", $row_info['ship_method']))
             {
              $row_ship_method = "United States Postal Service";
              $row_carrier_code = "usps";
             } 
             
         break;
        
      } //end of switch
               
          }  //end of for
          
          /*
          * query the customer email based on the order number
          * found on the csv file.
          */
          
           $sql = "SELECT  sfo.customer_email FROM sales_flat_order as sfo WHERE sfo.increment_id = $order_id "; 
      $result = mysql_query($sql);
      
      $sfo_row = mysql_fetch_assoc($result);
      $email = $sfo_row['customer_email'];
      
            
      /*
      * magento api coding start
      * load the sales order model by $order_id defined in the csv
      * then evaluate if it can ship the order.
      */
      
      $order = Mage::getModel('sales/order')->loadByIncrementId($order_id);
      
      if($order->canShip()){
      $convertor = Mage::getModel('sales/convert_order');
      $shipment = $convertor->toShipment($order);
      
      /*
      * load all the items in specified order.
      * then ship it. 
      */
      
      foreach ($order->getAllItems() as $orderItem) {
          
          if (!$orderItem->getQtyToShip()) {
              continue;
          }
          if ($orderItem->getIsVirtual()) {
              continue;
          }
          
          $item = $convertor->itemToShipmentItem($orderItem);
      
          $qty = $orderItem->getQtyToShip();
      
          $item->setQty($qty);
          $shipment->addItem($item);
      } //end of foreach
      
      /*
      * prepare for adding the carrier code, title and number.
      * save the shipment and send an email confirmation.
      */
      
      $data = array();
      
      $data['carrier_code'] = $row_carrier_code;
      $data['title']     = $row_ship_method;
      $data['number']    = $tracking_no;
      
      $track = Mage::getModel('sales/order_shipment_track')->addData($data);
      $shipment->addTrack($track);
      
      Mage::register('current_shipment', $shipment);
      
      $shipment->register();
      $shipment->addComment($comment, $email && $includeComment);
      $shipment->setEmailSent(true);
      $shipment->getOrder()->setIsInProcess(true);
      
      
      $transactionSave = Mage::getModel('core/resource_transaction')
          ->addObject($shipment)
          ->addObject($shipment->getOrder())
          ->save();
      
      $send = $shipment->sendEmail($email, ($includeComment ? $comment : ''));
      
       if(!$send){
         echo "Sending of confirmation email failed.!";
       }
       else{
         echo "Shipment for Order Number:" . $order_id . "is successfully created.";
       }
      
       }else{
        
         echo "can't create order";
       }
      
     } //end of second if
     
     $row++;
   
  }  // end of while 
 
  fclose($handle);
}
else{
 
  echo "Shipping CSV Information not found!"; 
 
/*
* send an email notification if shipment file was not found
* send this to janzell1989@gmail.com
*/
          
   $headers  = "From: info@ownproducts.com \r\n";
   $headers .= "Reply-To: name@domain.com \r\n";
    $headers .= "MIME-Version: 1.0\r\n";
   $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
   
   $email_to ='youremail@email.com' ; 
   
   $email_subject = "Shipping CSV Information Failure";
  
   
   $email_message  = $source .' Not Found!!! <br> <br><br>  CSV Information Failed!!! Please check the file in FTP directory <br><br> Directory : own/shipping <br><br><br><br>';
   $email_message .= 'Possible: Failure of uploading the file in specified directory. <br><br><br><br>Thank you!';

   $ok = mail($email_to, $email_subject, $email_message, $headers);
} 


You can download the full script here. If there's any problem, please feel free to comment below

May 10, 2011

Speeding up your Magento Site

Most of Magento developers faces the loading problem of their site for several reasons. Some of these are messy external css and javascript setup, large number of template files, untidy template customization and  a lot more. But looking with this issue, I decided to look for some alternatives to speed up the performance of your magento site. Here are some helpful tips that I compiled, hope it will help lot of magento developers out there.

For Magento Configuration:


1. Uninstall extensions which are not really needed in your store. When installing extension make sure that you install a reasonable extension.
2. Enabled Magento Cache especially in production site System -> Cache Management.
3. Minify Javascript and CSS Files.
4. Use Magento Compilation feature. It gives a 25%-50% performance boost. System > Tools > Compilation.
5. For production site, make sure you disabled the log setting in System -> Configuration -> Advanced -> Developer -> Log Settings and other developer tools.
6. It is also best practice to limit the number of products that can be seen in your product list page.
7. Select only attributes that you want to visible in the frontend such as size, color etc.
8. Look for some magento extensions and check if it is boosting performance.

Customizing Template


1. Don’t overuse javascript files – make sure you didn’t use too much script to run your store. It is much safe to stay simple yet performing well that fancy but too slow.
2. Minify CSS files, compress and check for unused selector.
3. Use simple template if you don’t want to customize. There are lots of free simple themes out there.
4. Apply loader for javascript.
5. Optimize your images (ALL if possible)
a. Use PNG8 or GIF and don’t use transparency if not really need.
b. Use image compression.
c. Use CSS sprites for those images that apply in CSS file.
d. Specify image dimensions.

Maybe it’s not complete list but I hope it will give you an idea on how to optimize you magento site.

If you have tips to share. Please post it in comment and I will add it in the list. Enjoy :)