Reputation: 1397
I am trying to create a Magento Credit Memo programmatically but Magento shows me a credit memo with zero totals.
$incrementID = "100000016";
$orderMagento = Mage::getModel('sales/order')->loadByIncrementId($incrementID);
$convertOrder = new Mage_Sales_Model_Convert_Order ();
$creditmemo = $convertOrder->toCreditmemo ( $orderMagento );
$items = $orderMagento->getAllItems();
foreach ( $items as $item ) {
$_eachCreditMemoItem = $convertOrder->itemToCreditmemoItem ( $item );
$_eachCreditMemoItem->setQty ($item->getQtyInvoiced());
$_eachCreditMemoItem->register ();
$creditmemo->addItem ( $_eachCreditMemoItem );
$totalQty += $item->getQtyInvoiced ();
}
$creditmemo->refund();
$creditmemo->setTotalQty ( $totalQty );
$creditmemo->collectTotals();
$orderCreditMemoStatusCode = Mage_Sales_Model_Order::STATE_CLOSED;
$orderCreditMemoStatusComment = $comment;
$saveTransaction = Mage::getModel('core/resource_transaction')->addObject ($creditmemo )->addObject ( $orderMagento )->save ();
$orderMagento->addStatusToHistory ( $orderCreditMemoStatusCode, $orderCreditMemoStatusComment, false );
$orderMagento->save ();
I have find this code in StackOverflow and I am trying to use it but it doesn't work as well.
Why the totals are not updated? Which is the right way to create it?
thanks
Upvotes: 3
Views: 6322
Reputation: 166
You can easily make credit memo from paid invoices. So first you need to get all paid invoices from your order:
$invoices = array();
foreach ($order->getInvoiceCollection() as $invoice) {
if ($invoice->canRefund()) {
$invoices[] = $invoice;
}
}
Then go throughout the invoices and make credit memo:
$service = Mage::getModel('sales/service_order', $order);
foreach ($invoices as $invoice) {
$creditmemo = $service->prepareInvoiceCreditmemo($invoice);
$creditmemo->refund();
}
Hope it works for you.
Upvotes: 2