I am trying to create an Observer to automatically create and email shipment to the customer whenever a new invoice is created.
I am having trouble created the shipment as the I keep getting an exception when I try to create an invoice.
I am Observer the sales_order_invoice_register
register event.
Here's my code:
public function salesOrderInvoiceShipmentCreate($observer)
{
$orderIncrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order = Mage::getModel('sales/order')->loadByIncrementId($orderIncrementId);
Mage::log($order,Zend_Log::INFO,'order.log',true);
if (!$order->getId()) {
Mage::throwException("Order does not exist, for the Shipment process to complete");
}
if ($order->canShip()) {
try {
$shipment = Mage::getModel('sales/service_order', $order)
->prepareShipment($this->_getItemQtys($order));
$shipmentCarrierCode = '';
$shipmentCarrierTitle = '';
$arrTracking = array(
'carrier_code' => isset($shipmentCarrierCode) ? $shipmentCarrierCode : $order->getShippingCarrier()->getCarrierCode(),
'title' => isset($shipmentCarrierTitle) ? $shipmentCarrierTitle : $order->getShippingCarrier()->getConfigData('title'),
);
$track = Mage::getModel('sales/order_shipment_track')->addData($arrTracking);
$shipment->addTrack($track);
// Register Shipment
$shipment->register();
// Save the Shipment
$this->_saveShipment($shipment, $order, $customerEmailComments);
// Finally, Save the Order
$this->_saveOrder($order);
} catch (Exception $e) {
throw $e;
}
}
}
protected function _getItemQtys(Mage_Sales_Model_Order $order)
{
$qty = array();
foreach ($order->getAllItems() as $_eachItem) {
if ($_eachItem->getParentItemId()) {
$qty[$_eachItem->getParentItemId()] = $_eachItem->getQtyOrdered();
} else {
$qty[$_eachItem->getId()] = $_eachItem->getQtyOrdered();
}
}
return $qty;
}
The exception is being thrown on but I can't figure out why??
Any help would be appreciated please...