2

I have set an attribute validity_date for each product. When I order the items. I want to separate the single order into multiple orders grouped by validity_date. I found some code to create an order and I used that one, but it is not creating the order. I supposed that after the function diversify gets called that there is 1 order for each items of a single day and the overall order, but there is just the overall order. Can you help me why the function createOrder is not creating orders.

<?php    
class AAA_OrderDiversify_Model_Observer {

    /**
     * Gets Called after the first order got created
     */
    public function diversify(Varien_Event_Observer $observer) {
        $event = $observer->getEvent();
        $quote = $event->getQuote();
        $quote_id = $quote->getId();
        $order = $event->getOrder();

        $customer = Mage::getModel('customer/customer')->load($order->getCustomerId());

        $orderProductArray = $this->getProductsOrderedByValidityDate($order);

        Mage::log($orderProductArray);

        foreach ($orderProductArray as $validityDate => $productCollection) {
          $this->createOrder($customer, $order, $productCollection, $validityDate);
        }


    }

    public function getProductsOrderedByValidityDate($order) {

        // get all products
        $productCollection = $order->getAllItems();

        // sort all products for each day
        $orderProductArray = array();
        foreach ($productCollection as $product) {
            $validityDate = $product->getProduct()->getData('validity_date');
            if ( !array_key_exists($validityDate, $orderProductArray) ) {
                $orderProductArray[$validityDate] = array();
            }

            array_push($orderProductArray[$validityDate], array(
              'product' => $product->getProduct()->getData('entity_id'),
              'qty' => $product->getQtyOrdered()
            ));

        }
        return $orderProductArray;
    }

    protected function createOrder($customer, $baseOrder, $products, $validityDate)
    {
        $transaction = Mage::getModel('core/resource_transaction');
        $storeId = $customer->getStoreId();
        $reservedOrderId = Mage::getSingleton('eav/config')
            ->getEntityType('order')
            ->fetchNewIncrementId($storeId);

        $subTotal = 0;
        $currencyCode  = Mage::app()->getBaseCurrencyCode();
        $order = Mage::getModel('sales/order')
            ->setIncrementId($reservedOrderId)
            ->setStoreId($storeId)
            ->setQuoteId(0)
            ->setGlobalCurrencyCode($currencyCode)
            ->setBaseCurrencyCode($currencyCode)
            ->setStoreCurrencyCode($currencyCode)
            ->setOrderCurrencyCode($currencyCode);


        $order->setCustomerEmail($customer->getEmail())
            ->setCustomerFirstname($customer->getFirstname())
            ->setCustomerLastname($customer->getLastname())
            ->setCustomerGroupId($customer->getGroupId())
            ->setCustomerIsGuest(0)
            ->setCustomer($customer);

        $order->setBillingAddress($baseOrder->getBillingAddress());
        $order->setShippingAddress($baseOrder->getShippingAddress());
              // -setShippingMethod();

        $order->setPayment($baseOrder->getPayment());

        foreach ($products as $requestData) {
            $request = new Varien_Object();
            $request->setData($requestData);

            $product = Mage::getModel('catalog/product')->load($request['product']);

            $cartCandidates = $product->getTypeInstance(true)
                ->prepareForCartAdvanced($request, $product);


            if (is_string($cartCandidates)) {
                throw new Exception($cartCandidates);
            }

            if (!is_array($cartCandidates)) {
                $cartCandidates = array($cartCandidates);
            }

            $parentItem = null;
            $errors = array();
            $items = array();

            foreach ($cartCandidates as $candidate) {

                $item = $this->_productToOrderItem($candidate, $candidate->getCartQty());

                $subTotal += $candidate->getFinalPrice() * $candidate->getCartQty();


                $items[] = $item;

                //
                // As parent item we should always use the item of first added product
                //
                if (!$parentItem) {
                    $parentItem = $item;
                }
                if ($parentItem && $candidate->getParentProductId()) {
                    $item->setParentItem($parentItem);
                }
                //
                // We specify qty after we know about parent (for stock)
                //
                $item->setQty($item->getQty() + $candidate->getCartQty());

                // collect errors instead of throwing first one
                if ($item->getHasError()) {
                    $message = $item->getMessage();
                    if (!in_array($message, $errors)) { // filter duplicate messages
                        $errors[] = $message;
                    }
                }

            }

            if (!empty($errors)) {
                Mage::throwException(implode("\n", $errors));
            }
            foreach ($items as $item){
                $order->addItem($item);
            }


        }

        $order->setSubtotal($subTotal)
            ->setBaseSubtotal($subTotal)
            ->setGrandTotal($subTotal)
            ->setBaseGrandTotal($subTotal);

        $transaction->addObject($order);
        $transaction->addCommitCallback(array($order, 'place'));
        $transaction->addCommitCallback(array($order, 'save'));
        $transaction->save();

    }

    protected function _productToOrderItem(Mage_Catalog_Model_Product $product, $qty = 1)
    {
        $rowTotal = $product->getFinalPrice() * $qty;

        $options = $product->getCustomOptions();

        $optionsByCode = array();

        foreach ($options as $option)
        {
            $quoteOption = Mage::getModel('sales/quote_item_option')->setData($option->getData())
                ->setProduct($option->getProduct());

            $optionsByCode[$quoteOption->getCode()] = $quoteOption;
        }

        $product->setCustomOptions($optionsByCode);

        $options = $product->getTypeInstance(true)->getOrderOptions($product);

        $orderItem = Mage::getModel('sales/order_item')
            ->setStoreId($this->_storeId)
            ->setQuoteItemId(0)
            ->setQuoteParentItemId(NULL)
            ->setProductId($product->getId())
            ->setProductType($product->getTypeId())
            ->setQtyBackordered(NULL)
            ->setTotalQtyOrdered($product['rqty'])
            ->setQtyOrdered($product['qty'])
            ->setName($product->getName())
            ->setSku($product->getSku())
            ->setPrice($product->getFinalPrice())
            ->setBasePrice($product->getFinalPrice())
            ->setOriginalPrice($product->getFinalPrice())
            ->setRowTotal($rowTotal)
            ->setBaseRowTotal($rowTotal)

            ->setWeeeTaxApplied(serialize(array()))
            ->setBaseWeeeTaxDisposition(0)
            ->setWeeeTaxDisposition(0)
            ->setBaseWeeeTaxRowDisposition(0)
            ->setWeeeTaxRowDisposition(0)
            ->setBaseWeeeTaxAppliedAmount(0)
            ->setBaseWeeeTaxAppliedRowAmount(0)
            ->setWeeeTaxAppliedAmount(0)
            ->setWeeeTaxAppliedRowAmount(0)

            ->setProductOptions($options);

        return $orderItem;
    }


}
?>
2
  • Do you get any errors, or can you tell us where the code actually breaks? – simonthesorcerer Oct 23 '15 at 16:16
  • You are creating the order object but, to add the items to the order, you will need to create a quote instance and add items to that. – Taral Patoliya Oct 24 '15 at 13:00
1

after digging around for a while. I found in the apache logs an error that says that the payment is not set. so I changed the set Payment part to:

    $orderPayment = Mage::getModel('sales/order_payment')
        ->setStoreId($storeId)
        ->setCustomerPaymentId(0)
        ->setMethod($paymentMethod) 
        ->setPoNumber(' – ');

Now it seems to work. no idea why "copying" an payment object doesnt work, but ok

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.