Monday, November 26, 2012

Automatically shipment and invoice order in Magento

>> In magento to complete an order from admin you need to create an Invoice then a Shipment. If you want to make it by once click on shipment button. you can easily try this code to get the result.

     $order = $orderObj;                  // get your order object.

     if ($order->getState() == Mage_Sales_Model_Order::STATE_NEW) {
            
            try {
                if(!$order->canInvoice()) {
                    $order->addStatusHistoryComment('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.', 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.', false);

                $transactionSave = Mage::getModel('core/resource_transaction')
                    ->addObject($shipment)
                    ->addObject($shipment->getOrder())
                    ->save();
                //END Handle Shipment
            } catch (Exception $e) {
                $order->addStatusHistoryComment('Exception occurred during automaticallyInvoiceShipCompleteOrder action. Exception message: '.$e->getMessage(), false);
                $order->save();
            }              
     }

Now see I've implemented it in shipment save action, means when you'll click on the shipment button to create the shipment, it'll automatically generate the invoice also. Go to app/code/core/Mage/Adminhtml/controllers/Sales/Order/ShipmentController.php
find the saveAction() method and replace it with the following code :

        public function saveAction()
        {
            $data = $this->getRequest()->getPost('shipment');
            if (!empty($data['comment_text'])) {
                Mage::getSingleton('adminhtml/session')->setCommentText($data['comment_text']);
            }
       
            try {
                $shipment = $this->_initShipment();
                if (!$shipment) {
                    $this->_forward('noRoute');
                    return;
                }
       
                $shipment->register();
               
                $order = $shipment->getOrder();
                if(!$order->canInvoice()) {
                    $order->addStatusHistoryComment('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.', false);
       
                $transactionSave = Mage::getModel('core/resource_transaction')
                    ->addObject($invoice)
                    ->addObject($invoice->getOrder());
       
                $transactionSave->save();
                //END Handle Invoice
               
                $comment = '';
                if (!empty($data['comment_text'])) {
                    $shipment->addComment(
                        $data['comment_text'],
                        isset($data['comment_customer_notify']),
                        isset($data['is_visible_on_front'])
                    );
                    if (isset($data['comment_customer_notify'])) {
                        $comment = $data['comment_text'];
                    }
                }
       
                if (!empty($data['send_email'])) {
                    $shipment->setEmailSent(true);
                }
       
                $shipment->getOrder()->setCustomerNoteNotify(!empty($data['send_email']));
                $responseAjax = new Varien_Object();
                $isNeedCreateLabel = isset($data['create_shipping_label']) && $data['create_shipping_label'];
       
                if ($isNeedCreateLabel && $this->_createShippingLabel($shipment)) {
                    $responseAjax->setOk(true);
                }
       
                $this->_saveShipment($shipment);
       
                $shipment->sendEmail(!empty($data['send_email']), $comment);
       
                $shipmentCreatedMessage = $this->__('The shipment has been created.');
                $labelCreatedMessage    = $this->__('The shipping label has been created.');
       
                $this->_getSession()->addSuccess($isNeedCreateLabel ? $shipmentCreatedMessage . ' ' . $labelCreatedMessage
                    : $shipmentCreatedMessage);
                Mage::getSingleton('adminhtml/session')->getCommentText(true);
            } catch (Mage_Core_Exception $e) {
                if ($isNeedCreateLabel) {
                    $responseAjax->setError(true);
                    $responseAjax->setMessage($e->getMessage());
                } else {
                    $this->_getSession()->addError($e->getMessage());
                    $this->_redirect('*/*/new', array('order_id' => $this->getRequest()->getParam('order_id')));
                }
            } catch (Exception $e) {
                Mage::logException($e);
                if ($isNeedCreateLabel) {
                    $responseAjax->setError(true);
                    $responseAjax->setMessage(
                        Mage::helper('sales')->__('An error occurred while creating shipping label.'));
                } else {
                    $this->_getSession()->addError($this->__('Cannot save shipment.'));
                    $this->_redirect('*/*/new', array('order_id' => $this->getRequest()->getParam('order_id')));
                }
       
            }
            if ($isNeedCreateLabel) {
                $this->getResponse()->setBody($responseAjax->toJson());
            } else {
                $this->_redirect('*/sales_order/view', array('order_id' => $shipment->getOrderId()));
            }
        }

Hope it'll help you..........   :)


2 comments:

  1. where do I put the code?

    ReplyDelete
    Replies
    1. Hello, friend..

      Thanks for your comment. see the post I've updated it. hope it'll help you.........

      Delete