Magento – Programmatically create new orders from multiple existing orders

magento-1.6magento-1.9ordersprogrammatically

I would like to programmatically create new orders from existing orders by their id and send new order confirmations by mail. The new orders need to contain all the information the old ones had (Items, Customer, Shipping Information etc.):

<?php
include_once 'app/Mage.php';
Mage::app();

//some existing order ids
$orderIds= array('911', '1106', '926');

foreach($orderIds as $orderId){
    Mage::unregister('rule_data');
    Mage::getModel('adminhtml/session_quote')
        ->clear();

    /* @var Mage_Sales_Model_Order $order */
    $order = Mage::getModel('sales/order')->load($orderId)
        ->setReordered(true);

    /* @var Mage_Sales_Model_Quote $quote */
    $quote = Mage::getModel('sales/quote')
        ->setStoreId($order->getStoreId())
        ->assignCustomer(Mage::getModel('customer/customer')->load($order->getCustomerId()))
        ->setUseOldShippingMethod(true);

    /* @var Mage_Adminhtml_Model_Sales_Order_Create $model */
    $model = Mage::getModel('adminhtml/sales_order_create')
        ->initFromOrder($order)
        ->setQuote($quote);

    /* @var Mage_Sales_Model_Order $newOrder */
    $newOrder = $model->createOrder();
    $newOrder->setQuoteId($quote->getId())
        ->sendNewOrderEmail();

    $model->getSession()
        ->clear();
}

Unfortunately Magento keeps the Customer information while looping through the order IDs, so the emails are all sent to the customer of the first order (in this case the one with the id 911). Also, the order items seem to add up in the cart, so the last order which is placed contains all the order items of the previous orders… What am I doing wrong?

Best Answer

Magento uses lots of singletons and assumes that certain actions are only executed once.

If you take a look at Mage_Adminhtml_Model_Sales_Order_Create, you will find this one:

public function __construct()
{
    $this->_session = Mage::getSingleton('adminhtml/session_quote');
}

You can reset singletons like this:

Mage::unregister('_singleton/adminhtml/session_quote');

If it still does not work, walk through the code, there might be other relevant singletons.

Related Topic