Various merchants, various demands. Imagine you have a private on site
sale or something like that, where your checkout requirements are pretty
simply: create invoice / ship and complete the order all at once. For
example, you are doing the checkout for bunch of people standing in
front of you, paying you money right on the spot. In such scenario
overload of manually creating an invoice and shipment can be too much.
Thus, having your Magento automatically invoice/ship/complete orders can be a logical request. So how do we do that?
Easy! All you need to do is to observe the sales_order_save_after event or observe the controller_action_predispatch event and target the Mage_Checkout_OnepageController::successAction() catching the Mage::getSingleton(‘checkout/session’)->getLastOrderId(). In this example I decided to demonstrate the possible (not ideal, or not even the best) “sales_order_save_after event” approach.
And here is the code for our observer model.
$order = $observer->getEvent()->getOrder();
$orders = Mage::getModel('sales/order_invoice')->getCollection()
->addAttributeToFilter('order_id', array('eq'=>$order->getId()));
$orders->getSelect()->limit(1);
if ((int)$orders->count() !== 0) {
return $this;
}
if ($order->getState() == Mage_Sales_Model_Order::STATE_NEW) {
try {
if(!$order->canInvoice()) {
$order->addStatusHistoryComment('Inchoo_Invoicer: Order cannot be invoiced.', false);
$order->save();
}
//START Handle Invoice
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
$invoice->register();
$invoice->getOrder()->setCustomerNoteNotify(false);
$invoice->getOrder()->setIsInProcess(true);
$order->addStatusHistoryComment('Automatically INVOICED by Invoicer.', false);
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transactionSave->save();
//END Handle Invoice
//START Handle Shipment
$shipment = $order->prepareShipment();
$shipment->register();
$order->setIsInProcess(true);
$order->addStatusHistoryComment('Automatically SHIPPED by Invoicer.', false);
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($shipment)
->addObject($shipment->getOrder())
->save();
//END Handle Shipment
} catch (Exception $e) {
$order->addStatusHistoryComment('Inchoo_Invoicer: Exception occurred during automaticallyInvoiceShipCompleteOrder action. Exception message: '.$e->getMessage(), false);
$order->save();
}
}