Follow by Email

Monday, February 24, 2014

Reorder via Code in magennto

I have create a extension for reorder please find the following code for it


<?php class Cdotsys_ScheduleOrder_ScheduleorderController extends Mage_Core_Controller_Front_Action{
private $_storeId = '1';
private $_groupId = '1';
private $shipping_methord = 'flatrate_flatrate';
private $_sendConfirmation = '0';
private $orderData = array();
private $_sourceCustomer;

public function IndexAction() {

              $this->loadLayout();   
              $this->getLayout()->getBlock("head")->setTitle($this->__("Scheduleorder"));
                    $breadcrumbs = $this->getLayout()->getBlock("breadcrumbs");
              $breadcrumbs->addCrumb("home", array(
                        "label" => $this->__("Home Page"),
                        "title" => $this->__("Home Page"),
                        "link"  => Mage::getBaseUrl()
                   ));

              $breadcrumbs->addCrumb("scheduleorder", array(
                        "label" => $this->__("Scheduleorder"),
                        "title" => $this->__("Scheduleorder")
                   ));

        $scheduleorders = Mage::getModel('scheduleorder/scheduleorder')->getCollection();    
        foreach($scheduleorders as $scheduleorder){             
            $personsOrder = Mage::getModel('sales/order')->load($scheduleorder->getOrderId());              
            //$personsOrder->setReordered(true);
            $items = $personsOrder->getAllItems();  
            foreach($items as $item){                   
                $products[$item->getProductId()] = array('qty' => $item->getQtyOrdered());                  
            } 
            $this->shipping_methord = $personsOrder->getShippingMethod()
            $customer = Mage::getModel('customer/customer')->load($personsOrder->getCustomerId());
            $this->setOrderInfo($customer,$products);
            $this->create();
            $personsOrder->setPaymentMethod('cashondelivery');

            $order_model = Mage::getSingleton('adminhtml/sales_order_create');
            /*$order_model->setPaymentData('cashondelivery');
            $order_model->getQuote()->getPayment()->addData('cashondelivery');
            $order_model->setShipping('flatrate_flatrate');
            $order_model->getQuote()->getShipping()->addData('flatrate_flatrate');
            $order_model->getQuote()->setShipping(array('method' => 'flatrate_flatrate'));
            $order_model->getQuote()->setPayment(array('method' => 'cashondelivery'));

            $order_model->initFromOrder($personsOrder);             
            $order_model->createOrder();*/
        }

              $this->renderLayout(); 

    }

public function setOrderInfo(Mage_Customer_Model_Customer $sourceCustomer,$products){
        $this->_sourceCustomer = $sourceCustomer;
        //You can extract/refactor this if you have more than one product, etc.
        $Billingaddress = Mage::getModel('customer/address')->load($this->_sourceCustomer->getDefaultBilling());
        $Shippingaddress = Mage::getModel('customer/address')->load($this->_sourceCustomer->getDefaultShipping());
        $this->orderData = array(
        'session'       => array(
                            'customer_id'   => $this->_sourceCustomer->getId(),
                            'store_id'      => $this->_storeId,
                            ),
        'payment'       => array(
                            'method'    => 'checkmo',
                            ),  
        'add_products'  =>$products,
        'order' => array(
                        'currency' => 'USD',
                        'account' => array(
                                'group_id' => $this->_groupId,
                                'email' => $this->_sourceCustomer->getEmail()
                                ),
                        'billing_address' => array(
                                                'customer_address_id' => $this->_sourceCustomer->getDefaultBilling(),
                                                'prefix' => '',
                                                'firstname' => $this->_sourceCustomer->getFirstname(),
                                                'middlename' => '',
                                                'lastname' => $this->_sourceCustomer->getLastname(),
                                                'suffix' => '',
                                                'company' => '',
                                                'street' => array($Billingaddress->getStreet(),''),
                                                'city' => $Billingaddress->getCity(),
                                                'country_id' => $Billingaddress->getCountryId(),
                                                'region' => '',
                                                'region_id' => $Billingaddress->getRegionId(),
                                                'postcode' => $Billingaddress->getPostcode(),
                                                'telephone' => $Billingaddress->getTelephone(),
                                                'fax' => '',
                                                ),
                        'shipping_address' => array(
                                                'customer_address_id' => $this->_sourceCustomer->getDefaultShipping(),
                                                'prefix' => '',
                                                'firstname' => $this->_sourceCustomer->getFirstname(),
                                                'middlename' => '',
                                                'lastname' => $this->_sourceCustomer->getLastname(),
                                                'suffix' => '',
                                                'company' => '',
                                                'street' => array($Shippingaddress->getStreet(),''),
                                                'city' => $Shippingaddress->getCity(),
                                                'country_id' => $Shippingaddress->getCountryId(),
                                                'region' => '',
                                                'region_id' => $Shippingaddress->getRegionId(),
                                                'postcode' => $Shippingaddress->getPostcode(),
                                                'telephone' => $Shippingaddress->getTelephone(),
                                                'fax' => '',
                                                ),
                                                'shipping_method' => $shipping_methord,
                                                'comment' => array(
                                                'customer_note' => 'This order has been created by scheduler order script.',
                                                ),
                            'send_confirmation' => $this->_sendConfirmation
        ),
        );
}   

protected function _getOrderCreateModel()
{
    return Mage::getSingleton('adminhtml/sales_order_create');
}
/**
* Retrieve session object
*
* @return Mage_Adminhtml_Model_Session_Quote
*/
protected function _getSession()
{
    return Mage::getSingleton('adminhtml/session_quote');
}
/**
* Initialize order creation session data
*
* @param array $data
* @return Mage_Adminhtml_Sales_Order_CreateController
*/
protected function _initSession($data)
{
/* Get/identify customer */
    if (!empty($data['customer_id'])) {
        $this->_getSession()->setCustomerId((int) $data['customer_id']);
    }
/* Get/identify store */
    if (!empty($data['store_id'])) {
        $this->_getSession()->setStoreId((int) $data['store_id']);
    }
  return $this;
}

public function create(){
    $orderData = $this->orderData;

    if (!empty($orderData)) {
            $this->_initSession($orderData['session']);
        try {
                $this->_processQuote($orderData);
                if (!empty($orderData['payment'])) {
                    $this->_getOrderCreateModel()->setPaymentData($orderData['payment']);
                    $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($orderData['payment']);
                }

                Mage::app()->getStore()->setConfig(Mage_Sales_Model_Order::XML_PATH_EMAIL_ENABLED, "0");
                $_order = $this->_getOrderCreateModel()->importPostData($orderData['order'])->createOrder();
                $this->_getSession()->clear();
                Mage::unregister('rule_data');
                return $_order;
        }
        catch (Exception $e){
            Mage::log("Order save error...");
        }
    }
    return null;
}

protected function _processQuote($data = array()){
    /* Saving order data */
    if (!empty($data['order'])) {
        $this->_getOrderCreateModel()->importPostData($data['order']);
    }
    $this->_getOrderCreateModel()->getBillingAddress();
    $this->_getOrderCreateModel()->setShippingAsBilling(true);
    /* Just like adding products from Magento admin grid */
    if (!empty($data['add_products'])) {
        $this->_getOrderCreateModel()->addProducts($data['add_products']);
    }
    /* Collect shipping rates */
    $this->_getOrderCreateModel()->collectShippingRates();
    /* Add payment data */
    if (!empty($data['payment'])) {
        $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($data['payment']);
    }
    $this->_getOrderCreateModel()->initRuleData()->saveQuote();

    if (!empty($data['payment'])) {
        $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($data['payment']);
    }
    return $this;
}

}


Monday, February 17, 2014

How to send email in Magento and add custom template to it

While creating a local module you may sometimes required to add the send mail functionality on success of your task.
Below is the code and description on how to create a send mail and loading it with a custom template..
 
As my module is based on sending a mail on successfully creating a duplicate order. So I am adding my code in the model folder when the duplicate order is created.

Step1:
At location app/code/local/Namespace/Module/Model/order.php

Add the following code:
//Here I am passing the order object and a payment object as my requirements is to show the product and price details
 public function sendMail(Varien_Object $order, Varien_Object $paymentObj) {

        $email = $order->getCustomerEmail();
        $fName = $order->getCustomerFirstname();
        $lName = $order->getCustomerLastname();

        $customerNote = $order->getCustomerNote();
        $paymentmethod = $paymentObj->getMethod();
      
        try {

            $storeObj = Mage::getModel('core/store')->load($order->getStoreId());
            $customerEmailId = $email;
            $customerFName = $fName;
            $customerLName = $lName;

            //load the custom template to the email 
            $emailTemplate = Mage::getModel('core/email_template')
                    ->loadDefault('custom_template');
           
            // it depends on the template variables
            $emailTemplateVariables = array();
            $emailTemplateVariables['order'] = $order;
            $emailTemplateVariables['store'] = $storeObj;
            $emailTemplateVariables['payment_html'] = $method;
      

            $emailTemplate->setSenderName('Magento');
            $emailTemplate->setSenderEmail('sender.com');
            $emailTemplate->setType('html');
            $emailTemplate->setTemplateSubject('Add a subject');
            $emailTemplate->send($customerEmailId, $customerFName . $customerLName, $emailTemplateVariables);
            return true;
        } catch (Exception $e) {
            $errorMessage = $e->getMessage();
            return $errorMessage;
        }
    }
 
Step2:
At location app/code/local/Namespace/Module/etc/config.xml, add the following block of code
<config>
   <global>
       <template>
            <email>
                <custom_template  module="modulename">
                    <label>any desired  name</label>
                    <file>custom_template.html</file>  // this specifies the path where the custom template is located
                    <type>html</type>
                </custom_template>
            </email>
        </template>
     </global>
</config>
 
Step3:
At location app/locale/template/email/sales
Place your custom template file

Note: If your template file is at location app/locale/template/email, then in your config change the code:         <file>custom_template.html</file>