2015-11-20 4 views
2

Мне было интересно, можем ли мы разделить заказ на одну страницу, прежде чем размещать заказ? И я хочу сделать это через наблюдателя.Magento order split through observer

Я использую sales_order_place_before событие, чтобы получить котировку и разделить заказ.

Я попытался сделать это в наблюдателя, как:

$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; 

Но это не идет дальше.

Любая помощь с кодом наблюдателя будет оценена по достоинству.

благодаря

+0

Требуется ли выполнение задачи на наблюдателе событий? У меня есть одно и то же требование, но я пытаюсь сделать это, переписывая функцию saveorder() – Haris

+0

Да, что может работать, если мы можем переписать saveorder(), но будет ли он работать нормально? –

ответ

3

Вот что я достиг до сих не создан новый модуль установочный файл

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

и вот 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> 

взгляд на переписывание

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

пыльник является завершающим вещь, расширенная функция

<?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; 
    } 
} 

Примечание этот сценарий все еще не удается разделить общий порядок, который я сейчас работаю и обновит вы когда-то сделали Here is the code on github, вы можете внести свой вклад

+0

Ваш код замечательный. Он отлично работает :) –