how to set order status as 'complete' in magento - magento

how do i set order status as 'complete' manually.
I am using the following code, but its giving error saying,
The Order State 'complete' must not be set manually.
$order = Mage::getModel('sales/order')->loadByIncrementId($order_id);
$order->setState(Mage_Sales_Model_Order::STATE_COMPLETE);
$order->save();

i found a solution for my self,
$order = Mage::getModel('sales/order')->loadByIncrementId($order_id);
$order->setData('state', "complete");
$order->setStatus("complete");
$history = $order->addStatusHistoryComment('Order was set to Complete by our automation tool.', false);
$history->setIsCustomerNotified(false);
$order->save();

well, the actual way to make order state COMPLETE is to create invoice and shipment, after which the order state auto gets COMPLETE state. Like:
//create invoice for the order
$invoice = $order->prepareInvoice()
->setTransactionId($order->getId())
->addComment("Invoice created from cron job.")
->register()
->pay();
$transaction_save = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transaction_save->save();
//now create shipment
//after creation of shipment, the order auto gets status COMPLETE
$shipment = $order->prepareShipment();
if( $shipment ) {
$shipment->register();
$order->setIsInProcess(true);
$transaction_save = Mage::getModel('core/resource_transaction')
->addObject($shipment)
->addObject($shipment->getOrder())
->save();
}

kindly change object manager to di
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$orderRepository = $objectManager->create('\Magento\Sales\Api\OrderRepositoryInterface');
$order = $orderRepository->get($orderId);
$order->setState('awaiting_stock');
$order->setStatus('awaiting_stock');
$orderRepository->save($order);

Set order status programmatically:
http://blog.chapagain.com.np/magento-how-to-change-order-status-programmatically/
change order status to 'Completed'
$orderIncrementId = YOUR_ORDER_INCREMENT_ID;
$order = Mage::getModel('sales/order')
->loadByIncrementId($orderIncrementId);
$order->setState(Mage_Sales_Model_Order::STATE_COMPLETE,true)->save();

Related

Magento Order total not updating after creating invoice programmatically

I am creating invoice programmatically. As we are using using Fishbowl inventory and from that we directly generate shipment for orders in magento. So i am creating invoice automatically based on shipment.Now the invoice created successfully but order totals are not updating based on invoice amount.
Here is my code to create invoice from shipment items. I am using this function in sales_order_shipment_save_after event and using Purchase Order as payment method for the order so no capture for invoice.
public function autoInvoiceGenerate(Varien_Event_Observer $observer){
$shipment = $observer->getEvent()->getShipment();
$shipment = Mage::getModel('sales/order_shipment')->loadByIncrementId($shipment->getIncrementId());
$shippedItems = $shipment->getAllItems();
$order = $shipment->getOrder();
$order = Mage::getModel('sales/order')->load($order->getId());
try{
if(!$order->canInvoice()) {
//$order->addStatusHistoryComment('Order cannot be invoiced.', false);
//$order->save();
return $this;
}
$invoiceQtys = array();
foreach($shippedItems as $item){
$invoiceQtys[$item->getOrderItemId()] = $item->getQty();
}
if(empty($invoiceQtys)){
return $this;
}
//START Handle Invoice
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice($invoiceQtys);
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
$invoice->register();
$invoice->getOrder()->setCustomerNoteNotify(false);
$invoice->getOrder()->setIsInProcess(true);
$invoice->sendEmail(true, '');
$order->addStatusHistoryComment('Invoice created for shipment #'.$shipment->getData('increment_id').'.', false);
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transactionSave->save();
}
A bit late but if you are still having this problem here my suggestion:
Save the order associated with the invoice.
Save the invoice at the end.
This works for me:
$order = Mage::getModel('sales/order')->load($orderId);
$invoice = Mage::getModel('sales/service_order', $order)
->prepareInvoice($itemsarray);
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
$invoice->register();
$invoice->getOrder()->setCustomerNoteNotify(true);
$invoice->getOrder()->setIsInProcess(true);
$order->save();
Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder())
->save();
$invoice->save();

Magento - Mage_Core_Exception: Please select a valid payment method

I create order promatically with below code
function createSaleOrderForMagento()
{
$customer_id = $this->sale_lib->get_customer();
$items = $this->sale_lib->get_cart();
if($customer_id==-1)
{
return;
}
$cust_info = $this->Customer->get_info($customer_id);
$primaryAddress = $cust_info->getPrimaryShippingAddress();
require_once '../app/Mage.php';
Mage::init();
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
// Start New Sales Order Quote
$storeId=$store->getId();
$quote = Mage::getModel('sales/quote')->setStoreId($storeId);
// Set Sales Order Quote Currency
$baseCurrencyCode = Mage::app()->getStore($storeId)->getBaseCurrencyCode();
$currentCurrencyCode = Mage::app()->getStore($storeId)->getCurrentCurrencyCode();
$quote->setCurrency('VND');
$customer = Mage::getModel('customer/customer')->load($customer_id);
// Assign Customer To Sales Order Quote
$quote->assignCustomer($customer);
// Configure Notification
$quote->setSendCconfirmation(0);
foreach($items as $line=>$item)
{
$product=Mage::getModel('catalog/product')->load($item['item_id']);
$quote->addProduct($product,new Varien_Object(array('qty' => 1)));
}
// Set Sales Order Billing Address
// set Billing Address
$billing = $customer->getDefaultBillingAddress();
$billingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultBilling())
->setCustomer_address_id($billing->getEntityId())
->setPrefix($billing->getPrefix())
->setFirstname($billing->getFirstname())
->setMiddlename($billing->getMiddlename())
->setLastname($billing->getLastname())
->setSuffix($billing->getSuffix())
->setCompany($billing->getCompany())
->setStreet($billing->getStreet())
->setCity($billing->getCity())
->setCountry_id($billing->getCountryId())
->setRegion($billing->getRegion())
->setRegion_id($billing->getRegionId())
->setPostcode($billing->getPostcode())
->setTelephone($billing->getTelephone())
->setFax($billing->getFax());
$quote->setBillingAddress($billingAddress);
// Set Sales Order Shipping Address
$shipping = $customer->getDefaultShippingAddress();
$shippingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultShipping())
->setCustomer_address_id($shipping->getEntityId())
->setPrefix($shipping->getPrefix())
->setFirstname($shipping->getFirstname())
->setMiddlename($shipping->getMiddlename())
->setLastname($shipping->getLastname())
->setSuffix($shipping->getSuffix())
->setCompany($shipping->getCompany())
->setStreet($shipping->getStreet())
->setCity($shipping->getCity())
->setCountry_id($shipping->getCountryId())
->setRegion($shipping->getRegion())
->setRegion_id($shipping->getRegionId())
->setPostcode($shipping->getPostcode())
->setTelephone($shipping->getTelephone())
->setFax($shipping->getFax())->setShippingMethod('freeshipping_freeshipping');
$quote->setShippingAddress($shippingAddress)
->setShipping_method('freeshipping_freeshipping')
->setPaymentMethod('checkmo');
$quote->save();
$quote->getShippingAddress()
->setShippingMethod('freeshipping_freeshipping')
->setCollectShippingRates(true)
->setPaymentMethod('checkmo')
->collectTotals();
$quote->save();
// Create Order From Quote
$service = Mage::getModel('sales/service_quote', $quote);
//var_dump($service);
$service->submitAll();
$increment_id = $service->getOrder()->getRealOrderId();
// Resource Clean-Up
$quote = $customer = $service = null;
// Finished
return $increment_id;
}
But I got an error :
( ! ) Fatal error: Uncaught exception 'Mage_Core_Exception' with
message 'Please select a valid payment method.' in
C:\wamp\www\pmc\app\Mage.php on line 595
( ! ) Mage_Core_Exception: Please select a valid payment method. in C:\wamp\www\pmc\app\Mage.php on line 595
Please help me to solve this problem
If you check the condition of this error outputting, you will see next:
if (!($this->getQuote()->getPayment()->getMethod())) {
Mage::throwException(Mage::helper('sales')->__('Please select a valid payment method.'));
}
Which means that you need to initialize you Mage_Sales_Model_Quote_Payment model and set there your payment method:
$quote->getPayment()->setMethod('checkmo');

How to change payment method from one to another of the existing order in magento by programming way?

I need change the payment method of an existing order, programically, what you can suggest?
$quote = $order->getQuote();
$payment = $quote->getPayment();
$payment->importData($data);
$quote->save();
the correct solution is here, which is based upon the solution from Rajiv, the payment method in the order details of customer account in the frontend and the payment method in the order details in the order management of admin panel both changed after the following codes snippet, thanks to Rajiv!
$orderId = '100000009'; // Incremented Order Id
$order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
$payment = $order->getQuote()->getPayment();
$payment->setMethod('test'); // Assuming 'test' is updated payment method
$payment->save();
$order->save();
$payment = $order->getPayment();
$payment->setMethod('test'); // Assuming 'test' is updated payment method
$payment->save();
$order->save();
Try below code to update payment method of existing order:
$orderId = '100000009'; // Incremented Order Id
$order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
$payment = $order->getPayment();
$payment->setMethod('test'); // Assuming 'test' is updated payment method
$payment->save();
$order->save();
Hope it will help!

Magento: Increase "Qty" upon cancel a shipped order

I'm on Magento 1.7.0.2. I'm using "Cash On Delivery" as my payment method.I'll tell you exactly the steps That i follow on any order. When an order is placed(Qty decreased 1 item), I create a shipment for it and if customer paid the order grand total price. I create an invoice for that order.
My problem, If an order is placed(Qty decreased 1 item), I create a shipment for this order. If the customer refused to pay, I open this order and "Cancel" it and on this case the "Qty" doesn't increase so How can I make it increase?
If order status is Processing
Create a custom module with observer for 'order_cancel_before' (see example # Change Magento default status for duplicated products change <catalog_model_product_duplicate> to <order_cancel_before>
since <order_cancel_before> is not defined in app/code/core/Mage/Sales/Model/Order.php
You could override/rewrite order model class see e.g http://phprelated.myworks.ro/how-to-override-rewrite-model-class-in-magento/
In your local module do
public function cancel()
{
if ($this->canCancel()) {
Mage::dispatchEvent('order_cancel_before', array('order' => $this));
$this->getPayment()->cancel();
$this->registerCancellation();
Mage::dispatchEvent('order_cancel_after', array('order' => $this));
}
return $this;
}
Or you could create a new method increaseProductQty() in your model and copy the code below into it (this way you would not need an observer). Then replace the line Mage::dispatchEvent('order_cancel_before'... with $this->increaseProductQty()
In your observer method (pseudo code)
$curr_date = date('Y-m-d H:i:s');
$order = $observer->getEvent()->getOrder();
foreach ($order->getItemsCollection() as $item)
{
$productId = $item->getProductId();
$qty = $item->getQty();
// you need to check order status to make sure it processing
//$order->getStatus() (assuming you are canceling entire order)
//$order->getPayment();
$product = Mage::getModel('catalog/product')->load($product_id);
$stock_obj = Mage::getModel('cataloginventory/stock_item')->load($product_id);
$stockData = $stock_obj->getData();
$product_qty_before = (int)$stock_obj->getQty();
$product_qty_after = (int)($product_qty_before + $qty);
$stockData['qty'] = $product_qty_after;
$productInfoData = $product->getData();
$productInfoData['updated_at'] = $curr_date;
$product->setData($productInfoData);
$product->setStockData($stockData);
$product->save();
}
If you have issue with updating stock see Set default product values when adding new product in Magento 1.7
Reference http://pragneshkaria.com/programatically-change-products-quantity-after-order-cancelled-magento/
If order status is Pending
Take a look at System > Configuration > Inventory
Set Items’ Status to be In Stock When Order is Cancelled — Controls whether products in pending orders automatically return to the stock if orders are cancelled. Scope: STORE VIEW.
Read more #
How to Manage Magento Store Inventory?
ADMIN: System → Configuration → Inventory Tab
Thanks to R.S as he helped me more & more.
I followed all instructions on R.S's reply https://stackoverflow.com/a/13330543/1794834 and I've only changed the observer code. Here is the observer code that worked with me on Magento 1.7.0.2.
$curr_date = date('Y-m-d H:i:s');
$order = $observer->getEvent()->getOrder();
foreach ($order->getItemsCollection() as $item)
{
$productId = $item->getProductId();
$qty = (int)$item->getQtyOrdered();
$product = Mage::getModel('catalog/product')->load($productId);
$stock_obj = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
$stockData = $stock_obj->getData();
$product_qty_before = (int)$stock_obj->getQty();
$product_qty_after = (int)($product_qty_before + $qty);
$stockData['qty'] = $product_qty_after;
/*
* it may be case that admin has enabled product add in stock, after product sold,
* he set is_in_stock = 0 and if order cancelled then we need to update only qty not is_in_stock status.
* make a note of it
*/
if($product_qty_after != 0) {
$stockData['is_in_stock'] = 1;
}else{
$stockData['is_in_stock'] = 0;
}
$productInfoData = $product->getData();
$productInfoData['updated_at'] = $curr_date;
$product->setData($productInfoData);
$product->setStockData($stockData);
$product->save();
}

Magento 1.5 How to programmaticaly change custom order status after creating an invoice

I Try to update the order status by an observer after creating an invoice on Magento CE 1.5.
I use the event sales_order_invoice_save_after. I've created some specific status for the state processed. My code works BUT Magento always put an order status after mine, so it cancels mine. I Don't know which event use to avoid this issue.
Here is the code of my observer :
public function updateStatusFacture($observer)
{
$event = $observer->getEvent();
$invoice = $observer->getEvent()->getInvoice();
$order_update = Mage::getModel('sales/order')->load($orderid);
$order = Mage::getModel('sales/order')->loadByIncrementId($order_update->getIncrementId());
$state = 'processing';
$status = 'expedier';
$comment = 'Changing state to Processing and status to expedier Status';
$isCustomerNotified = false;
$order->setState($state, $status, $comment, $isCustomerNotified);
$order->save();
}
Ok I've found what was wrong in my code.
To avoid Magento to save status after me. I have to use this event : sales_order_invoice_save_commit_after in place of sales_order_invoice_save_after
Hope this helps.

Resources