Search code examples
magentomagento-1.9

Magento order split through observer


I was wondering if we can split the order on onepage checkout before placing the order? And I want to do it Through observer.

I am using sales_order_place_before event to get the quote and split order.

I have tried to do it in observer like:

$productids=array(1,2);
         $websiteId = Mage::app()->getWebsite()->getId();
         $store = Mage::app()->getStore();
         // Start New Sales Order Quote
         $quote = Mage::getModel('sales/quote')->setStoreId($store->getId());

         // Set Sales Order Quote Currency
         $quote->setCurrency($order->AdjustmentAmount->currencyID);
         $customer = Mage::getModel('customer/customer')
                     ->setWebsiteId($websiteId)
                     ->loadByEmail($email);
         if($customer->getId()==""){
             $customer = Mage::getModel('customer/customer');
             $customer->setWebsiteId($websiteId)
                     ->setStore($store)
                     ->setFirstname('Jhon')
                     ->setLastname('Deo')
                     ->setEmail($email)
                     ->setPassword("password");
             $customer->save();
         }

         // Assign Customer To Sales Order Quote
         $quote->assignCustomer($customer);

             // Configure Notification
         $quote->setSendCconfirmation(1);
         foreach($productsids as $id){
             $product=Mage::getModel('catalog/product')->load($id);
             $quote->addProduct($product,new Varien_Object(array('qty'   => 1)));
         }

         // Set Sales Order Billing Address
         $billingAddress = $quote->getBillingAddress()->addData(array(
             'customer_address_id' => '',
             'prefix' => '',
             'firstname' => 'john',
             'middlename' => '',
             'lastname' =>'Deo',
             'suffix' => '',
             'company' =>'',
             'street' => array(
                     '0' => 'Noida',
                     '1' => 'Sector 64'
                 ),
             'city' => 'Noida',
             'country_id' => 'IN',
             'region' => 'UP',
             'postcode' => '201301',
             'telephone' => '78676789',
             'fax' => 'gghlhu',
             'vat_id' => '',
             'save_in_address_book' => 1
         ));

         // Set Sales Order Shipping Address
        $shippingAddress = $quote->getShippingAddress()->addData(array(
             'customer_address_id' => '',
             'prefix' => '',
             'firstname' => 'john',
             'middlename' => '',
             'lastname' =>'Deo',
             'suffix' => '',
             'company' =>'',
             'street' => array(
                     '0' => 'Noida',
                     '1' => 'Sector 64'
                 ),
             'city' => 'Noida',
             'country_id' => 'IN',
             'region' => 'UP',
             'postcode' => '201301',
             'telephone' => '78676789',
             'fax' => 'gghlhu',
             'vat_id' => '',
             'save_in_address_book' => 1
         ));
         if($shipprice==0){
             $shipmethod='freeshipping_freeshipping';
         }

         // Collect Rates and Set Shipping & Payment Method
         $shippingAddress->setCollectShippingRates(true)
                         ->collectShippingRates()
                         ->setShippingMethod('flatrate_flatrate')
                         ->setPaymentMethod('checkmo');

         // Set Sales Order Payment
         $quote->getPayment()->importData(array('method' => 'checkmo'));

         // Collect Totals & Save Quote
         $quote->collectTotals()->save();

         // Create Order From Quote
         $service = Mage::getModel('sales/service_quote', $quote);
         $service->submitAll();
         $increment_id = $service->getOrder()->getRealOrderId();

         // Resource Clean-Up
         $quote = $customer = $service = null;

         // Finished
         return $increment_id;

But it is not proceeding further.

Any help with the observer code will be appreciated.

thanks


Solution

  • Here is what i have achieved until now created new module installation file

        <?xml version="1.0"?>
    <config>
      <modules>
        <PMTECH_Splitorder>
          <active>true</active>
          <codePool>local</codePool>
          <version>0.1.0</version>
        </PMTECH_Splitorder>
      </modules>
    </config>
    

    and here is the config.xml

    <?xml version="1.0"?>
    <config>
      <modules>
        <PMTECH_Splitorder>
          <version>0.1.0</version>
        </PMTECH_Splitorder>
      </modules>
      <global>
        <helpers>
          <splitorder>
            <class>PMTECH_Splitorder_Helper</class>
          </splitorder>
        </helpers>
        <models>
          <splitorder>
            <class>PMTECH_Splitorder_Model</class>
            <resourceModel>splitorder_mysql4</resourceModel>
          </splitorder>
                <checkout>
                    <rewrite>
                        <type_onepage>PMTECH_Splitorder_Model_Checkout_Type_Onepage</type_onepage>
                    </rewrite>
                </checkout>
        </models>
      </global>
    </config> 
    

    look at the rewrite

    <checkout>
                        <rewrite>
                            <type_onepage>PMTECH_Splitorder_Model_Checkout_Type_Onepage</type_onepage>
                        </rewrite>
                    </checkout>
    

    Bellow is the final thing, the extended function

    <?php
    class PMTECH_Splitorder_Model_Checkout_Type_Onepage extends Mage_Checkout_Model_Type_Onepage
    {
        /**
         * Create order based on checkout type. Create customer if necessary.
         *
         * @return Mage_Checkout_Model_Type_Onepage
         */
        public function saveOrder()
        {
            $this->validate();
            $isNewCustomer = false;
            switch ($this->getCheckoutMethod()) {
                case self::METHOD_GUEST:
                    $this->_prepareGuestQuote();
                    break;
                case self::METHOD_REGISTER:
                    $this->_prepareNewCustomerQuote();
                    $isNewCustomer = true;
                    break;
                default:
                    $this->_prepareCustomerQuote();
                    break;
            }
    
            $cart = $this->getQuote();
            $key=0;
          foreach ($cart->getAllItems() as $item) 
          {
            $key= $key+1;
            $temparray[$key]['product_id']=  $item->getProduct()->getId();
            $temparray[$key]['qty']= $item->getQty();
            $cart->removeItem($item->getId());
            $cart->setSubtotal(0);
            $cart->setBaseSubtotal(0);
            $cart->setSubtotalWithDiscount(0);
            $cart->setBaseSubtotalWithDiscount(0);
            $cart->setGrandTotal(0);
            $cart->setBaseGrandTotal(0);
    
            $cart->setTotalsCollectedFlag(false);
            $cart->collectTotals();
            }
             $cart->save();
    
            foreach ($temparray as $key => $item) 
            {
            $customer_id = Mage::getSingleton('customer/session')->getId();
            $store_id = Mage::app()->getStore()->getId();
            $customerObj = Mage::getModel('customer/customer')->load($customer_id);
            $quoteObj = $cart;
            $storeObj = $quoteObj->getStore()->load($store_id);
            $quoteObj->setStore($storeObj);
            $productModel = Mage::getModel('catalog/product');
            $productObj = $productModel->load($item['product_id']);
            $quoteItem = Mage::getModel('sales/quote_item')->setProduct($productObj);
            $quoteItem->setBasePrice($productObj->getFinalPrice());
            $quoteItem->setPriceInclTax($productObj->getFinalPrice());
            $quoteItem->setData('original_price', $productObj->getPrice());
            $quoteItem->setData('price', $productObj->getPrice());
            $quoteItem->setRowTotal($productObj->getFinalPrice());
            $quoteItem->setQuote($quoteObj);
            $quoteItem->setQty($item['qty']);
            $quoteItem->setStoreId($store_id);
            $quoteObj->addItem($quoteItem);
            $quoteObj->setBaseSubtotal($productObj->getFinalPrice());
            $quoteObj->setSubtotal($productObj->getFinalPrice());
            $quoteObj->setBaseGrandTotal($productObj->getFinalPrice());
            $quoteObj->setGrandTotal($productObj->getFinalPrice());
    
            $quoteObj->setStoreId($store_id);
            $quoteObj->collectTotals();
            $quoteObj->save();
            $this->_quote=$quoteObj;
    
            $service = Mage::getModel('sales/service_quote', $quoteObj);
            $service->submitAll();
            if ($isNewCustomer) {
                try {
                    $this->_involveNewCustomer();
                } catch (Exception $e) {
                    Mage::logException($e);
                }
            }
            $this->_checkoutSession->setLastQuoteId($quoteObj->getId())
                ->setLastSuccessQuoteId($quoteObj->getId())
                ->clearHelperData();
            $order = $service->getOrder();
            if ($order) {
                Mage::dispatchEvent('checkout_type_onepage_save_order_after',
                    array('order'=>$order, 'quote'=>$quoteObj));
                $quoteObj->removeAllItems();
                $quoteObj->setTotalsCollectedFlag(false);
                $quoteObj->collectTotals();
    }
                /**
                 * a flag to set that there will be redirect to third party after confirmation
                 * eg: paypal standard ipn
                 */
                $redirectUrl = $this->getQuote()->getPayment()->getOrderPlaceRedirectUrl();
                /**
                 * we only want to send to customer about new order when there is no redirect to third party
                 */
                if (!$redirectUrl && $order->getCanSendNewEmailFlag()) {
                    try {
                        $order->sendNewOrderEmail();
                    } catch (Exception $e) {
                        Mage::logException($e);
                    }
                }
                // add order information to the session
                $this->_checkoutSession->setLastOrderId($order->getId())
                    ->setRedirectUrl($redirectUrl)
                    ->setLastRealOrderId($order->getIncrementId());
                // as well a billing agreement can be created
                $agreement = $order->getPayment()->getBillingAgreement();
                if ($agreement) {
                    $this->_checkoutSession->setLastBillingAgreementId($agreement->getId());
                }
            }
            // add recurring profiles information to the session
            $profiles = $service->getRecurringPaymentProfiles();
            if ($profiles) {
                $ids = array();
                foreach ($profiles as $profile) {
                    $ids[] = $profile->getId();
                }
                $this->_checkoutSession->setLastRecurringProfileIds($ids);
                // TODO: send recurring profile emails
            }
            Mage::dispatchEvent(
                'checkout_submit_all_after',
                array('order' => $order, 'quote' => $this->getQuote(), 'recurring_profiles' => $profiles)
            );
            return $this;
        }
    }
    

    NOTE this script still fails to split the order total, which i am working on and will update you once done Here is the code on github, you are welcome to contribute