I'm using Magento 2.4.4 and I would like to understand if this code is correct about the automatic online item refund.
private function createCreditMemoByRma($rma, $order) {
$totalQty = 0;
$orderItems = self::retrieveOrderItemsData($order);
$creditmemo = $this->_convertor->toCreditmemo($order);
// Return \Amasty\Rma\Api\Data\RequestItemInterface[]
$rmaItems = $rma->getRequestItems();
foreach ($rmaItems as $r => $rmaItem) {
$itemData = $orderItems[$rmaItem->getOrderItemId()];
$item = $this->_convertor->itemToCreditmemoItem($itemData);
$qty = $rmaItem->getQty();
$item->setQty($qty);
$creditmemo->addItem($item);
$totalQty += $qty;
}
$creditmemo->setTotalQty($totalQty);
$creditmemo->collectTotals();
$taxAmount = 0;
$baseTaxAmount = 0;
foreach($creditmemo->getData('items') as $cmitem) {
$taxAmount += $cmitem->getTaxAmount();
$baseTaxAmount += $cmitem->getTaxAmount();
}
$creditmemo->setTaxAmount($taxAmount);
$creditmemo->setBaseTaxAmount($baseTaxAmount);
$creditmemo->setGrandTotal($creditmemo->getSubtotalInclTax());
$creditmemo->setBaseGrandTotal($creditmemo->getBaseSubtotalInclTax());
return $creditmemo;
}
private static function retrieveOrderItemsData($order) {
$orderItemsMap = array();
$orderItems = $order->getAllItems();
foreach ($orderItems as $item) {
$orderItemsMap[$item->getItemId()] = $item;
}
return $orderItemsMap;
}
This code seems to work fine for some orders but sometimes I noticed a strange behaviour. In these scenarios I noticed that, when I'll retrieve the order items I found two contained items:
- One (configurable) item that it contains all the prices info (no parent item id is filled);
- One (simple) item that it dasn't contains any prices and it has, as item-parent id, the id of the configurable item at the point above;
Please note that, from my posted code, the rmaItems ($rmaItems = $rma->getRequestItems()) conatins the id of the 'simple' item order.
This, obviously, will generate a refund request with 0 amount. If I check the order info, this contains the correct amounts with all the correct info.
I also checked the DB sales_order_item and, for these orders, I see the two items (one simple and one configurable) that present the properties that I explained above.
When my code seems works fine, into the sales_order_item I see only one item (simple) without the parent_item_id and it contains all prices info.
I'm not able to understand if this behaviour is correct and which is the difference on the products that generates this difference.
Any ideas?