Get All Orders for a Specific Customer with Grand Total Larger Than Certain Amount

Get all orders for specific customer and get the manufacturer for certain product in the order.

Posted on April 13, 2016 in Magento

After creating a new Module for your magento, you need to define the helper class Data.php as following:


<?php
class Jeff_Newmodule_Helper_Data extends Mage_Core_Helper_Abstract {

    //get order collection for a customer with certain grand total
    protected function getCustomerOrderCollection($customerId, $grandTotal = null) {
        $orderCollection = Mage::getResourceModel('sales/order_collection')
            ->addFieldToSelect('*')
            ->addFieldToFilter('customer_id', $customerId)
            ->addFieldToFilter('status', array('neq'=>'canceled'))
            ->addFieldToFilter('state', array('in' => Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates()))
            ->setOrder('created_at', 'asc');

        if($grandTotal && $grandTotal > 0) {
            $orderCollection->addFieldToFilter('base_grand_total', array('gteq'=>$grandTotal));
        }

        return $orderCollection;
    }

    protected function getOrderDetails($order) {
        $prodIdSkus = [];
        $items = $order->getAllVisibleItems();

        foreach($items as $item) {
            $prodIdSkus[$item->getProductId()] =  $item->getSku();
        }

        return $prodIdSkus;
    }

    public function getOption($customerId, $productId) {
        $collection = $this->getCustomerOrderCollection($customerId);
        $finalSku = '';
        $idArray = array();

        foreach($collection as $order) {
            $prodIdSkus = $this->getOrderDetails($order);
            reset($prodIdSkus);
            while(list($id, $sku) = each($prodIdSkus)) {
                $idArray[$id] = $sku;
            }

        }

        if(in_array($productId, array_keys($idArray))) {
            $sku = $idArray[$productId];
            $skuArray = explode('-', $sku); 

            if(count($skuArray) > 2) {
                $finalSku = $skuArray[2];
            }
        }
        
        if(strlen($finalSku) > 0) {
            //Get the resource model
            $resource = Mage::getSingleton('core/resource');
            
            //Retrieve the read connection
            $readConnection = $resource->getConnection('core_red');
            
            $query = "SELECT EAOV.option_id FROM eav_attribute EA LEFT JOIN eav_attribute_option EAO ON EAO.attribute_id = EA.attribute_id 
                       LEFT JOIN eav_attribute_option_value EAOV ON EAOV.option_id = EAO.option_id WHERE EA.attribute_code = 'manufacturer' AND EAOV.store_id = 0 AND EAOV.value = '".$finalSku."'";
            $result = $readConnection->fetchOne($query);

            return $result;
        }
        else {
            return '';
        }

    }

}


comments powered by Disqus