Monday, May 7

How to add Order Profit column in Magento

here is the step by step tutorial to get order profit column in magento backend.

This column will show the profit gained per order (i.e, the difference between Cost and Selling Price)
1) Copy the app/code/core/Mage/Adminhtml/Block/Sales/Order/Grid.php file to app/code/local/Mage/Adminhtml/Block/Sales/Order/Grid.php, by maintaining the directory structure
2) There is a protected function _prepareColumns, kindly paste the below code inside it

//below code for showing profit
//start
 $this->addColumn('entity_id', array(
    'header' => Mage::helper('sales')->__('Profit'),
    'index' => 'entity_id',
    'type'  => 'currency',
    'currency' => 'order_currency_code',
    'renderer'  => new Mage_Adminhtml_Block_Sales_Order_Renderer_Profit() //for the value
));
//end

3) Create a file app/code/local/Mage/Adminhtml/Block/Sales/Order/Renderer/Profit.php (directory structure should be maintained).
Copy the following code as it is in it.
class Mage_Adminhtml_Block_Sales_Order_Renderer_Profit extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
    public function render(Varien_Object $row)
    {
        $order_id = $row->getData($this->getColumn()->getIndex());
 
        if(!empty($order_id))
        {
            $sales_model = Mage::getModel('sales/order')->load($order_id);
            $subtotal = $sales_model->getSubtotal();//get order subtotal (without shipping)
            $items = $sales_model->getAllItems(); //get all order items
            $base_cost = array();
            if(!empty($items))
            {
                foreach ($items as $itemId => $item)
                {
                    $qty = intval($item->getQtyOrdered()); //get items quantity
                    if(empty($qty))
                    {
                        $qty = 1;
                    }
                    $b_cost = $item->getBaseCost();//get item cost
                    $base_cost[] = ($b_cost*$qty); //get all items cost
                }
            }
            $total_order_cost = '';
            if(!empty($base_cost))
            {
                $total_order_cost = array_sum($base_cost); //get sum of all items cost
            }
            $profit = '';
            if(!empty($total_order_cost))
            {
                $profit = ($subtotal-$total_order_cost); //get profit , subtraction of order subtotal
            }
 
            $_coreHelper = $this->helper('core');
            $profit = $_coreHelper->currency($profit);
 
            return $profit;
        }
 
    }
}
And you are done, now a Profit column will be seen in Sales > Orders in adminend.


How to get Table Name in Magento

Here is the small snippet of code to get the table name of the particular module.

let us assume my module name is "dckapbanner".

here is the script to get the table name of the "dckapbanner" module.

<?php
 
$resource = Mage::getSingleton('core/resource');
$tableName = $resource->getTableName('dckapbanner/dckapbanner');
 
?>

Thursday, March 29

How to install SSL Certificate in Magento


Here we will see how to install SSL certificate in Magento. Before we go to Magento SSL certificate we have to know all what is SSL and why we need SSL in our website.

What is SSL?

SSL is an acronym for Secure Sockets Layer, an encryption technology that was created by Netscape. SSL creates an encrypted connection between your web server and your visitors’ web browser allowing for private information to be transmitted without the problems of eavesdropping, data tampering, or message forgery. Once you have done the SSL install, you can access a site securely by changing the URL from http:// to https://. When an SSL certificate is installed on a website, you can be sure that the information you enter (credit card or any other information), is secured and only seen by the organization that owns the website.

Why need SSL?

If you are transmitting sensitive information on a web site, such as credit card numbers or personal information, you need to secure it with SSL encryption. It is possible for every piece of data to be seen by others unless it is secured by an SSL certificate.

 Add SSL certificate magento: Please follow the below steps for add SSL certificate in magento Here I show you with example of SSL Certificate add into cpanel.

Step1: Open your CPanel and Goto ssl-tls manager menu. 


Step2: Select Activate SSL on Your Web Site (HTTPS).


Step3: And enter the CRT and KEY for certificate and press install certificate button and install it. 


Step4: After this go to magento admin panel in System->Configuration->web in base url and set https where write http and set Use Secure URLs in Frontend = yes. 



Now you can have ssl certification in your magento site. you can see this in near by your address bar.

Thank You : Just Web Development 

Sunday, March 25

How to print coupon code and gift certificate on magento Invoice PDF

In this article we will see how to print the coupon code and gift certificate while invoice the magento order

here is the complete step by step procedure

Step 1 : Copy /app/code/core/Mage/Sales/Model/Order/Pdf/Invoice.php to /app/code/local/Mage/Sales/Model/Order/Pdf/Invoice.php

Step 2 : Find the line $page = $this->insertTotals($page, $invoice); in the getPdf function. This was line 107 for me.

Step 3 : Add the following in the above and save the file
/* added by Wright Creative Labs */
/* print coupon code on invoice */
if($order->getCouponCode()!=""){
    $this->y -=12;
    $page->drawText('Coupon Used: '.$order->getCouponCode(), 450, $this->y, 'UTF-8');    
}
/* print gift certificate code on invoice */
if($order->getGiftcertCode()!=""){
    $this->y -=12;
    $page->drawText('Coupon Used: '.$order->getGiftcertCode(), 450, $this->y, 'UTF-8');    
}

thats it. now you can able to print the coupon and gift certificate in backend sales order.

Monday, March 5

How to Search the product within the top lovel category in Magento

The default magento supports to search the products based the search keyword. if we want to search the products within the specific category we need to change the catalog search template under teample/catalogsearch/form.mini.html

here is the script to search the products within the specific category
<?php
$category = Mage::getModel('catalog/category');
if(is_object(Mage::registry('current_category'))){
    $current_category_path=Mage::registry('current_category')->getPathIds();
}else{
    $current_category_path = array();
}
$category->load(Mage::app()->getStore()->getRootCategoryId());
$children_string = $category->getChildren();
$children = explode(',',$children_string);
$extra_options='';
foreach($children as $c){
    $selected = (in_array($c, $current_category_path))?'SELECTED':'';
    $extra_options.= '<option value="' . $c . '" ' . $selected . '>' . $category->load($c)->getName() . '</option>' . "\n";
}
?>
<form id="search_mini_form" action="<?php echo $this->helper('catalogSearch')->getResultUrl() ?>" method="get">
    <fieldset>
        <legend><?php echo $this->__('Search Site') ?></legend>
        <div class="mini-search">
            <input id="search" type="text" class="input-text" name="<?php echo $this->helper('catalogSearch')->getQueryParamName() ?>" value="<?php echo $this->helper('catalogSearch')->getEscapedQueryText() ?>" />
            <select name="cat" id="cat" class="input-text">
            <option value="">All Categories</option>
            <?= $extra_options ?>
           </select>
            <input type="submit" value="Go" style="border: 1px solid #808080;" alt="<?php echo $this->__('Search') ?>" />
            <div id="search_autocomplete" class="search-autocomplete"></div>
            <script type="text/javascript">
            //<![CDATA[
                var searchForm = new Varien.searchForm('search_mini_form', 'search', '<?php echo $this->__('search site...') ?>');
                searchForm.initAutocomplete('<?php echo $this->helper('catalogSearch')->getSuggestUrl() ?>', 'search_autocomplete');
            //]]>
            </script>
        </div>
    </fieldset>
</form>

Monday, February 27

Magento Form Validation

By default Magento uses a file called form.js (js/varien/form.js) to provide abstract Javascript functions for forms. The most useful application of this class - in my opinion - is the form validation. To achieve this validation, form.js uses the Validation class which is part of the Prototype Javascript library. It works by checking form inputs for certain class names. Each class name tells the validator to perform certain checks on the value inside the input.

Custom Form Validation

Adding Javascript validation to your own forms is extremely simple. First, you need to create a Form (form.js) object to represent your form.

<script type="text/javascript">
//< ![CDATA[
  var myForm= new VarienForm('formId', true);
//]]>
</script>

Magento Javascript Validation Classes

There are many more validation classes you can assign and I list them here as a reference. For more information on this please use Google, experiment with the code or contact me via my email or the contact form.


validate-select

Please select an option


required-entry

This is a required field

 validate-number

Please enter a valid number in this field


validate-digits

Please use numbers only in this field. please avoid spaces or other characters such as dots or commas


validate-alpha

Please use letters only (a-z or A-Z) in this field.

 validate-code

Please use only letters (a-z), numbers (0-9) or underscore(_) in this field, first character should be a letter.

 validate-alphanum

Please use only letters (a-z or A-Z) or numbers (0-9) only in this field. No spaces or other characters are allowed


validate-street

Please use only letters (a-z or A-Z) or numbers (0-9) or spaces and # only in this field


validate-phoneStrict

Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890


validate-phoneLax

Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890


validate-fax

Please enter a valid fax number. For example (123) 456-7890 or 123-456-7890


validate-date

Please enter a valid date


validate-email

Please enter a valid email address. For example johndoe@domain.com.



validate-emailSender

Please use only letters (a-z or A-Z), numbers (0-9) , underscore(_) or spaces in this field.



validate-password

Please enter 6 or more characters. Leading or trailing spaces will be ignored


validate-admin-password

Please enter 7 or more characters. Password should contain both numeric and alphabetic characters


validate-cpassword

Please make sure your passwords match


validate-url

Please enter a valid URL. http:// is required


validate-clean-url

Please enter a valid URL. For example http://www.example.com or www.example.com


validate-identifier

Please enter a valid Identifier. For example example-page, example-page.html or anotherlevel/example-page


validate-xml-identifier

Please enter a valid XML-identifier. For example something_1, block5, id-4


validate-ssn

Please enter a valid social security number. For example 123-45-6789


validate-zip

Please enter a valid zip code. For example 90602 or 90602-1234


validate-zip-international

Please enter a valid zip code


validate-date-au

Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006


validate-currency-dollar

Please enter a valid $ amount. For example $100.00


validate-one-required

Please select one of the above options.


validate-one-required-by-name

Please select one of the options.


validate-not-negative-number

Please enter a valid number in this field


validate-state

Please select State/Province


validate-new-password

Please enter 6 or more characters. Leading or trailing spaces will be ignored


validate-greater-than-zero

Please enter a number greater than 0 in this field


validate-zero-or-greater

Please enter a number 0 or greater in this field


validate-cc-number

Please enter a valid credit card number.


validate-cc-type

Credit card number doesn't match credit card type


validate-cc-type-select

Card type doesn't match credit card number


validate-cc-exp

Incorrect credit card expiration date


validate-cc-cvn

Please enter a valid credit card verification number.


validate-data

Please use only letters (a-z or A-Z), numbers (0-9) or underscore(_) in this field, first character should be a letter.


validate-css-length

Please input a valid CSS-length. For example 100px or 77pt or 20em or .5ex or 50%


validate-length

Maximum length exceeded

Tuesday, February 14

How to get Current page url in Magento

current page url in magento

<?php
$current_page = '';
/*
* Check to see if its a CMS page
* if it is then get the page identifier
*/
if(Mage::app()->getFrontController()->getRequest()->getRouteName() == 'cms'):
$current_page = Mage::getSingleton('cms/page')->getIdentifier();
endif;
/*
* If its not CMS page, then just get the route name
*/
if(empty($current_page)):
$current_page = Mage::app()->getFrontController()->getRequest()->getRouteName();
endif;
/*
* What if its a catalog page?
* Then we can get the category path <img src="http://www.justwebdevelopment.com/blog/wp-includes/images/smilies/icon_smile.gif" alt=":)" class="wp-smiley">
*/
 
/*
* Or you can check all values
* $current_page_array = Mage::registry('current_category');
* $current_page_array['url_path']
*/
 
if($current_page == 'catalog'):
$current_page = 'path-' . preg_replace('#[^a-z0-9]+#', '-', strtolower(Mage::registry('current_category')->getUrlPath()));
endif;
?>

Also if you want Full Current Page URL in Magento you can do so with this one line.
<?php
    $currentUrl = $this->helper('core/url')->getCurrentUrl();
?>

Another way to get current url
<?php
$urlRequest = Mage::app()->getFrontController()->getRequest();
$urlPart = $urlRequest->getServer('ORIG_PATH_INFO');
if(is_null($urlPart))
{
    $urlPart = $urlRequest->getServer('PATH_INFO');
}
$urlPart = substr($urlPart, 1 );
$currentUrl = $this->getUrl($urlPart);
?>

Also you can check current page or catalog page is product page or not with “Mage::registry”.
<?php
    $onCatalogFlag = false;
    if(Mage::registry('current_product')) {
        $onCatalogFlag = true;
    }
?>


And also try to something like below code
<?php
echo $this->getRequest()->getControllerName();
if($this->getRequest()->getControllerName()=='product') //do something
if($this->getRequest()->getControllerName()=='category') //do others
?>

Hope it Helps... Thanks....

Wednesday, January 25

Magento : How to redirect customer to login page if not logged in

If you are developing a module which needs to give access to its content only to logged in user then the preDispatch function will be very useful. This dispatches event before action.

Just write the following function in your module’s controller and customer log in is checked before each of your controller action.

/**
 * Checking if user is logged in or not
 * If not logged in then redirect to customer login
 */
public function preDispatch()
{
    parent::preDispatch();
 
    if (!Mage::getSingleton('customer/session')->authenticate($this)) {
        $this->setFlag('', 'no-dispatch', true);
    }
}

Ref : http://blog.chapagain.com.np/magento-redirect-customer-to-login-page-if-not-logged-in

Friday, January 20

Magento Admin Login problem

Problem:

I had a new installation of magento. But I was unable to login as an administrator. I went

to the admin login page, entered correct username and password but was redirected to the

same login page. I could not enter the dashboard page. Error message is displayed when I

enter wrong username or password. But nothing is displayed and I am redirected to the same

login page when I insert correct username and password.

Solution:

I googled and found these solutions:-

1) Use 127.0.0.1 instead of localhost in your url, i.e. using

http://127.0.0.1/magento/index.php/admin instead of
http://localhost/magento/index.php/admin . But this didn’t solve my problem.

2) Since I am using Windows XP, I was suggested to open “host” file from
C:\WINDOWS\system32\drivers\etc and have 127.0.0.1 point to something like magento.localhost

or even 127.0.0.1 point to http://www.localhost.com . But this also didn’t work either.

3) This solution finally helped me out of this problem. The solution was to modify the core

Magento code. Open

app/code/core/Mage/Core/Model/Session/Abstract/Varien.php. Comment out the

lines 80 to 83. The line number may vary according to the Magento version. But these lines

are present somewhere near line 80. You have to comment the comma (,) in line: $this-

>getCookie()->getPath()//,

// set session cookie params
session_set_cookie_params(
$this->getCookie()->getLifetime(),
$this->getCookie()->getPath()//,
//$this->getCookie()->getDomain(),
//$this->getCookie()->isSecure(),
//$this->getCookie()->getHttponly()
);

Well, I am out of this problem. Hope, this solution you also help you.

Update (For Magento 1.4.*)

In Magento 1.4, you have to comment code from line 86 to 98 in

app/code/core/Mage/Core/Model/Session/Abstract/Varien.php. Like this:-

/*  if (!$cookieParams['httponly']) {
    unset($cookieParams['httponly']);
    if (!$cookieParams['secure']) {
        unset($cookieParams['secure']);
        if (!$cookieParams['domain']) {
            unset($cookieParams['domain']);
        }
    }
} 
 
if (isset($cookieParams['domain'])) {
    $cookieParams['domain'] = $cookie->getDomain();
} */

Ref : http://blog.chapagain.com.np/magento-admin-login-problem/

Enable Cookies problem in Magento

Problem:

When I try to add products to shopping cart, I get redirected to enable-cookies CMS page. Similarly, when I try to login as customer from customer account login, I get redirected to the same (enable-cookies) page.

The enable-cookies page asks me to enable cookies in my browser. The message says “Please enable cookies in your web browser to continue“. The page describes about Cookies and shows step-by-step instruction to enable cookies in browsers like Internet Explorer, Mozilla Firefox, and Opera. :)

When I check my browser options, I see that Cookies are enabled in my browser.

Solution:

I googled the web and found two solutions. Here are they:-

1) Increase Cookie Lifetime

– Go to System –> Configuration –> General –> Web –> Session Cookie Management –> Cookie Lifetime = 5400
– By default, Cookie Lifetime = 3600. You can make it more than 5400 and try if it works.

2) Disable redirect to enable-cookies CMS page

– Go to System –> Configuration –> General –> Web –> Browser Capabilities Detection –> Redirect to CMS-page if cookies are disabled = No

The second one has helped me. After implementing the second solution, I was able to add products to shopping cart page and was also able to login as customer.

Ref : http://blog.chapagain.com.np/magento-enable-cookies-problem

Friday, January 13

How to get list of all special offer products in Magento

Here is the complete details to get display the list of all specila offer products in Magento

There’s a few different attributes that we need to filter to get the proper results.

1. The products visibility must NOT be set to 1. This means that the product is going to be visible individually. If we tried to link to a product that was not visible individually we might get a 404 or even worse, the mage error screen! See this post for a list of visibility options ->addAttributeToFilter(‘visibility’, array(‘neq’=>1))
2. In my case I don’t want to show products that have an empty special price field. ->addAttributeToFilter(‘special_price’, array(‘neq’=>”))
4. I want to set the number of products returned to 8. ->setPageSize(8)
5. Finally I set up my date filters.

<?php
$todayDate  = Mage::app()->getLocale()->date()->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
$special= Mage::getResourceModel('reports/product_collection')
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('visibility', array('neq'=>1))
    ->addAttributeToFilter('special_price', array('neq'=>''))
    ->setPageSize(8) // Only return 4 products
    ->addAttributeToFilter('special_from_date', array('date' => true, 'to' => $todayDate))
    ->addAttributeToFilter('special_to_date', array('or'=> array(
           0 => array('date' => true, 'from' => $todayDate),
           1 => array('is' => new Zend_Db_Expr('null')))
           ), 'left')
    ->addAttributeToSort('special_from_date', 'desc');
$special->load();
?>
 
<ul class="list clearfix clear" id="special">
    <?php $x = 1; ?>
    <?php foreach ($special as $product): ?>
        <li class="span-1 left a-center <?php if ($x ==8) : echo 'last'; endif; ?>">
            <a href="<?php echo $product->getProductUrl() ?>" title="<?php echo $product->getName() ?>"><img class="a-center" src="<?php echo $this->helper('catalog/image')->init($product, 'small_image')->resize(120); ?>"/></a>
            <a href="<?php echo $product->getProductUrl() ?>" title="<?php echo $product->getName() ?>"><h2><?php echo $product->getName(); ?></h2></a>
            <strong><?php echo $this->getPriceHtml($product, true); ?></strong>
        </li>
<?php $x++;
    endforeach; ?>
</ul>

Hope it Helps.... Thanks....

Fatal Error : call to a member function addMessages() on a non-object app/code/core/mage/cms/helper/page.php on line no 125

Here is the step by step to resolve the problem in Magento

Go to System->Tools ->Compilation
Disable the compilation mode

if the above method will not resolve your problem follow the another method

open the includes/config.php in magento root folder. and comment the following lines

#define('COMPILER_INCLUDE_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR.'src');
#define('COMPILER_COLLECT_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR.'stat');

now your problem solved...

for more details contact nmohanswe@gmail.com


hope it helps..... Thanks...

Wednesday, January 4

How to Create custom Reports in Magento Admin

I was looking to generate the Report for the Products sold along with the name of the Artist to whom the product belongs to.

These are the steps to be followed.

1. The title of the report is: ‘Artist Sold Works’. To add the new item under the Reports -> Products.

Open the ‘app/code/core/Mage/Reports/etc/config.xml’

Add the followind code in the ‘children of ‘products’ (near line 221).
<title>Artist Sold Works</title>
adminhtml/report_product/artistsold

Add the followind code in the line (near line 370).
<title>Artists Sold Works</title>

2. Copy files

app/code/core/Mage/Adminhtml/Block/Report/Product/Sold.php to app/code/core/Mage/Adminhtml/Block/Report/Product/Artistsold.php.

3. Copy directories

app/code/core/Mage/Adminhtml/Block/Report/Product/Sold to

app/code/core/Mage/Adminhtml/Block/Report/Product/Artistsold

app/code/core/Mage/Reports/Model/Mysql4/Product/Sold to

app/code/core/Mage/Reports/Model/Mysql4/Product/Artistsold

4. In the file Artistsold.php, change the class name from

Mage_Adminhtml_Block_Report_Product_Sold to Mage_Adminhtml_Block_Report_Product_Artistsold.

Change the lines
$this->_controller = 'report_product_sold';
$this->_headerText = Mage::helper('reports')->__('Products Ordered');
to
$this->_controller = 'report_product_artistsold';
$this->_headerText = Mage::helper('reports')->__('Artist Sold Works');

5. Add/Modify the columns in the

app/code/core/Mage/Adminhtml/Block/Report/Product/Artistsold/Grid.php

Here in my case:
$this->addColumn('artistId', array(
    'header'    =>Mage::helper('reports')->__('Artist'),
    'width'     =>'120px',
    'index'     =>'artistname',
));  

$this->addColumn('sale_percentage', array(
    'header'    =>Mage::helper('reports')->__('Artist Share'),
    'width'     =>'60px',
    'index'     =>'sale_percentage',
    'align'     =>'right'
));

$this->addColumn('base_price_total', array(
    'header'    =>Mage::helper('reports')->__('Total Product Base Price ($)'),
    'width'     =>'60px',
    'index'     =>'base_price_total',
    'align'     =>'right',
    'total'     =>'sum',
    'type'      =>'number'

));

$this->addColumn('artist_earned', array(
    'header'    =>Mage::helper('reports')->__('Artist Earned ($)'),
    'width'     =>'60px',
    'index'     =>'artist_earned',
    'align'     =>'right',
    'total'     =>'sum',
    'type'      =>'number'
));
6. Add new functions to

app/code/core/Mage/Adminhtml/controllers/Report/ProductController.php
public function artistsoldAction()
{
    $this->_initAction()
        ->_setActiveMenu('report/product/artistsold')
        ->_addBreadcrumb(Mage::helper('reports')->__('Artists Sold Works'), Mage::helper('reports')->__('Artists Sold Works'))
        ->_addContent($this->getLayout()->createBlock('adminhtml/report_product_artistsold'))
        ->renderLayout();
}

7. Open the file

app/code/core/Mage/Reports/Model/Mysql4/Product/Artistsold/Collection.php.

Rename the class name from

Mage_Reports_Model_Mysql4_Product_Sold_Collection to

Mage_Reports_Model_Mysql4_Product_Artistsold_Collection

Customize the function setDateRange() in the as per your need.
public function setDateRange($frmdate, $todate)
  {
      $this->_reset()
          ->addAttributeToSelect('*')
          ->addOrderedQtyForArtistSold($frmdate,$todate);
return $this;
  }

8. To get the new fields, to alter the sql query I copied the function addOrderedQty() to addOrderedQtyForArtistSold() in the file

app/code/core/Mage/Reports/Model/Mysql4/Product/Collection.php

And I did changes in the functions as per my need to get the extra columns.

Here in my case:

public function addOrderedQtyForArtistSold($frm = '', $to = '')
   {
 if(key_exists('report',$_SESSION)) {
     $artistId = $_SESSION['report']['artistid'];
 }
 else {
  $artistId ='';
 }

       $qtyOrderedTableName = $this->getTable('sales/order_item');
       $qtyOrderedFieldName = 'qty_ordered';

       $productIdTableName = $this->getTable('sales/order_item');
       $productIdFieldName = 'product_id';

 $productEntityIntTable = (string)Mage::getConfig()->getTablePrefix() . 'catalog_product_entity_varchar';
 $adminUserTable = $this->getTable('admin_user');
 $artistsTable = $this->getTable('appartists');
 $eavAttributeTable = $this->getTable('eav/attribute');

       $compositeTypeIds = Mage::getSingleton('catalog/product_type')->getCompositeTypes();

       # This was added by Dev1 to get the configurable items in the list & not to get the simple products
       $compositeTypeIds = Array (
         '0' => 'grouped',
         '1' => 'simple',
         '2' => 'bundle'
      );

       $productTypes = $this->getConnection()->quoteInto(' AND (e.type_id NOT IN (?))', $compositeTypeIds);

       if ($frm != '' && $to != '') {
           $dateFilter = " AND `order`.created_at BETWEEN '{$frm}' AND '{$to}'";
       } else {
           $dateFilter = "";
       }

       $this->getSelect()->reset()->from(
          array('order_items' => $qtyOrderedTableName),
          array('ordered_qty' => "SUM(order_items.{$qtyOrderedFieldName})",'base_price_total' => "SUM(order_items.price)")
       );

       $order = Mage::getResourceSingleton('sales/order');

       $stateAttr = $order->getAttribute('state');
       if ($stateAttr->getBackend()->isStatic()) {

           $_joinCondition = $this->getConnection()->quoteInto(
               'order.entity_id = order_items.order_id AND order.state<>?', Mage_Sales_Model_Order::STATE_CANCELED
           );
           $_joinCondition .= $dateFilter;

           $this->getSelect()->joinInner(
               array('order' => $this->getTable('sales/order')),
               $_joinCondition,
               array()
           );
       } else {

           $_joinCondition = 'order.entity_id = order_state.entity_id';
           $_joinCondition .= $this->getConnection()->quoteInto(' AND order_state.attribute_id=? ', $stateAttr->getId());
           $_joinCondition .= $this->getConnection()->quoteInto(' AND order_state.value<>? ', Mage_Sales_Model_Order::STATE_CANCELED);

           $this->getSelect()
               ->joinInner(
                   array('order' => $this->getTable('sales/order')),
                   'order.entity_id = order_items.order_id' . $dateFilter,
                   array())
               ->joinInner(
                   array('order_state' => $stateAttr->getBackend()->getTable()),
                   $_joinCondition,
                   array());
       }

       $this->getSelect()
           ->joinInner(array('e' => $this->getProductEntityTableName()),
               "e.entity_id = order_items.{$productIdFieldName}")
            ->group('e.entity_id')
           ->having('ordered_qty > 0');

       $artistIdConcat = $artistId != '' ? " AND artistId=$artistId" : "";

       $this->getSelect()
           ->joinInner(
               array('pei' => $productEntityIntTable),
               "e.entity_id = pei.entity_id",
               array())
           ->joinInner(
               array('ea' => $eavAttributeTable),
               "pei.attribute_id=ea.attribute_id AND ea.attribute_code='artistid'",
               array())
           ->joinInner(
               array('au' => $adminUserTable),
               "au.user_id=pei.value",
               array("artistname" => "CONCAT(firstname, ' ',lastname)"))
           ->joinInner(
               array('ar' => $artistsTable),
               "ar.artistId=au.user_id".$artistIdConcat,
               array("sale_percentage" => "CONCAT(sale_percentage,'%')","artist_earned" => "((SUM(order_items.price)) * (sale_percentage)) / 100"));

       return $this;
   }



Hope it Helps... Thanks...