Skip to content

Instantly share code, notes, and snippets.

@thiagolima-bm
Forked from trabulium/orderCreate.php
Last active September 8, 2015 18:36
Show Gist options
  • Save thiagolima-bm/b13b3b3c1a6d1928ddf2 to your computer and use it in GitHub Desktop.
Save thiagolima-bm/b13b3b3c1a6d1928ddf2 to your computer and use it in GitHub Desktop.
Magento: Create Order from a Previous Order Programmatically
<?php
define('MAGENTO_ROOT', "/var/www/web");
$mageFilename = MAGENTO_ROOT . '/app/Mage.php';
require_once $mageFilename;
umask(0);
Mage::app();
//class Company_Module_Model_HandleOrderCreate extends Mage_Core_Model_Abstract
class Company_Module_Model_HandleOrderCreate extends Mage_Adminhtml_Model_Sales_Order_Create
{
private $_storeId = '1';
private $_groupId = '1';
private $_sendConfirmation = '0';
private $orderData = array();
private $_product;
private $_sourceCustomer;
private $_sourceOrder;
public function setOrderInfo(Varien_Object $sourceOrder, Mage_Customer_Model_Customer $sourceCustomer)
{
$this->_sourceOrder = $sourceOrder;
$this->_sourceCustomer = $sourceCustomer;
$billingAddress = Mage::getModel('customer/address')->load($sourceCustomer->default_billing);
$shippingAddress = Mage::getModel('customer/address')->load($sourceCustomer->default_shipping);
//Build the Products for the new Order
$ordered_items = $sourceOrder->getAllVisibleItems();
foreach($ordered_items as $item){
$quote_item = Mage::getModel('catalog/product')->getIdBySku($item->getSku());
$products[$quote_item] = array('qty' => 1);
}
//Load full product data to product object
$quote = $this->getQuote();
$service = Mage::getModel('sales/service_quote', $quote);
$oldOrder = $sourceOrder;
$originalId = $oldOrder->getOriginalIncrementId();
echo $originalId."\n";
if (!$originalId) {
$originalId = $oldOrder->getIncrementId();
echo $originalId."\n";
}
$orderData = array(
'original_increment_id' => $originalId,
'relation_parent_id' => $oldOrder->getId(),
'relation_parent_real_id' => $oldOrder->getIncrementId(),
'edit_increment' => $oldOrder->getEditIncrement()+1,
'increment_id' => $originalId.'-'.($oldOrder->getEditIncrement()+1)
);
$quote->setReservedOrderId($orderData['increment_id']);
$service->setOrderData($orderData);
$this->orderData = array(
'increment_id' => $originalId.'-'.($oldOrder->getEditIncrement()+1),
'session' => array(
'customer_id' => $this->_sourceCustomer->getId(),
'store_id' => $this->_storeId,
),
'payment' => array(
'method' => 'checkmo',
),
'add_products' => $products,
'order' => array(
'original_increment_id' => $originalId,
'relation_parent_id' => $oldOrder->getId(),
'relation_parent_real_id' => $oldOrder->getIncrementId(),
'edit_increment' => $oldOrder->getEditIncrement()+1,
'increment_id' => $originalId.'-'.($oldOrder->getEditIncrement()+1),
'currency' => 'AUD',
'account' => array(
'group_id' => $this->_groupId,
'email' => $this->_sourceCustomer->getEmail()
),
'billing_address' => array(
'customer_address_id' => $billingAddress->getId(),
'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' => $shippingAddress->getId(),
'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' => 'flatrate4_flatrate4',
'comment' => array(
'customer_note' => 'This order has been programmatically created via import script.',
),
'send_confirmation' => $this->_sendConfirmation
),
);
$quote->setReservedOrderId($orderData['increment_id']);
$service->setOrderData($orderData);
}
/**
* Retrieve order create model
*
* @return Mage_Adminhtml_Model_Sales_Order_Create
*/
protected function _getOrderCreateModel()
{
return Mage::getSingleton('adminhtml/sales_order_create');
}
/**
* Retrieve quote object model
*
* @return Mage_Sales_Model_Quote
*/
public function getQuote()
{
if (!$this->_quote) {
$this->_quote = $this->_getSession()->getQuote();
}
return $this->_quote;
}
/**
* Retrieve session object
*
* @return Mage_Adminhtml_Model_Session_Quote
*/
protected function _getSession()
{
return Mage::getSingleton('adminhtml/session_quote');
}
public function getOrderCustomer($incrementId){
$order = Mage::getModel('sales/order')->loadByIncrementId($incrementId);
$customer_id = $order->getCustomerId();
$customer = Mage::getModel('customer/customer')->load($customer_id);
return $customer;
}
/**
* Prepare options array for info buy request
*
* @param Mage_Sales_Model_Quote_Item $item
* @return array
*/
protected function _prepareOptionsForRequest($item)
{
$newInfoOptions = array();
if ($optionIds = $item->getOptionByCode('option_ids')) {
foreach (explode(',', $optionIds->getValue()) as $optionId) {
$option = $item->getProduct()->getOptionById($optionId);
$optionValue = $item->getOptionByCode('option_'.$optionId)->getValue();
$group = Mage::getSingleton('catalog/product_option')->groupFactory($option->getType())
->setOption($option)
->setQuoteItem($item);
$newInfoOptions[$optionId] = $group->prepareOptionValueForRequest($optionValue);
}
}
return $newInfoOptions;
}
/**
* 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;
}
function getOrder($incrementId)
{
//$isNewCustomer = $this->_prepareCheckoutMethodCustomerQuote();
$orderOriginal = Mage::getModel('sales/order')->loadByIncrementId($incrementId);
//$service = Mage::getModel('sales/service_quote', $orderOriginal);
//$service->submitAllMultiple();
//$orders = $service->getOrders();
/*if ($isNewCustomer) {
try {
$this->_involveNewCustomer();
} catch (Exception $e) {
Mage::logException($e);
}
}*/
$ordered_items = $orderOriginal->getAllVisibleItems();
foreach($ordered_items as $item){ //Here is where we can scrutinise warehouse?
echo "</br>Warehouse: ".$item->getStockId()."</br>";
echo "SKU: ".$item->getSku()."</br>";
echo "QuoteId: ".$orderOriginal->getQuoteId()."</br>";
echo "Customer Id: ".$orderOriginal->getCustomerId()."</br>";
}
$quoteId = $orderOriginal->getQuoteId();
return $orderOriginal;
}
/**
* Creates order
*/
public function createOrder()
{
$orderData = $this->orderData;
$originalOrderData = $this->orderData;
$quote = $this->getQuote();
$this->_prepareQuoteItems();
$service = Mage::getModel('sales/service_quote', $quote);
$oldOrder = $this->getOrder(100055681);
$originalId = $oldOrder->getOriginalIncrementId();
echo $originalId."\n";
if (!$originalId) {
$originalId = $oldOrder->getIncrementId();
echo $originalId."\n";
}
$orderData = array(
'original_increment_id' => $originalId,
'relation_parent_id' => $oldOrder->getId(),
'relation_parent_real_id' => $oldOrder->getIncrementId(),
'edit_increment' => $oldOrder->getEditIncrement()+1,
'increment_id' => $originalId.'-'.($oldOrder->getEditIncrement()+1)
);
$quote->setReservedOrderId($orderData['increment_id']);
$service->setOrderData($orderData);
$orderData = $this->orderData;
if (!empty($orderData)) {
$this->_initSession($orderData['session']);
try {
//$orderData = $originalOrderData;
$this->_processQuote($orderData);
if (!empty($orderData['payment'])) {
$this->_getOrderCreateModel()->setPaymentData($orderData['payment']);
$this->_getOrderCreateModel()->getQuote()->getPayment()->addData($orderData['payment']);
}
$orderOriginal = Mage::getModel('sales/order')->loadByIncrementId('100055642');
$ordered_items = $orderOriginal->getAllVisibleItems();
foreach($ordered_items as $item){
$item = $this->_getOrderCreateModel()->getQuote()->getItemByProduct($item);
}
Mage::app()->getStore()->setConfig(Mage_Sales_Model_Order::XML_PATH_EMAIL_ENABLED, "1");
$_order = $this->_getOrderCreateModel()
->importPostData($orderData['order'])
->createOrder();
$this->_getSession()->clear();
Mage::unregister('rule_data');
return $_order;
}
catch (Exception $e){
Mage::log("Order save error...". $e);
}
}
return null;
}
public function createInvoice($order)
{
//echo $order->getIncrementId();
//$last_order = Mage::getModel("sales/order")->getCollection()->getLastItem()->getIncrementId();
$order = Mage::getModel("sales/order")->loadByIncrementId('100055668');
try {
if(!$order->canInvoice())
{
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
}
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}
//$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transactionSave->save();
}
catch (Mage_Core_Exception $e) {
}
}
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;
}
}
function deleteOrderItem(){
/* Need to add some checks / information about Warehouses
Including not just if but which order item to delete
Be able to re-add the one we're removing from stock back into stock?*/
$base_grand_total = $order->getBaseGrandTotal();
$base_subtotal = $order->getBaseSubtotal();
$grand_total = $order->getGrandTotal();
$subtotal = $order->getSubtotal();
$base_subtotal_incl_tax = $order->getBaseSubtotalInclTax();
$subtotal_incl_tax = $order->getSubtotalInclTax();
$total_item_count = $order->getTotalIteoriginalOrderData;
$items = $order->getAllItems();
foreach($items as $item){
if($item->getParentItemId() == '' || $item->getParentItemId() == null){
$product_id = $item->getProductId();
if($product_id == $booking_product_id){ //What is $booking_product_id ??
//remove item price from total price of order
$item_price = $item->getPrice();
$item->delete();
$order->setBaseGrandTotal($base_grand_total-$item_price);
$order->setBaseSubtotal($base_subtotal-$item_price);
$order->setGrandTotal($grand_total-$item_price);
$order->setSubtotal($subtotal-$item_price);
$order->setBaseSubtotalInclTax($base_subtotal_incl_tax-$item_price);
$order->setSubtotalInclTax($subtotal_incl_tax-$item_price);
$order->setTotalItemCount($total_item_count-1);
$order->save();
}
}
}
}
$order = new Company_Module_Model_HandleOrderCreate();
$orderData = $order->getOrder(100055681);
$customer = $order->getOrderCustomer(100055681);
$order->setOrderInfo($orderData, $customer);
$order->createOrder();
$order->createInvoice($order);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment