Zend certified PHP/Magento developer

Magento2 Item order refund programmatically

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 AmastyRmaApiDataRequestItemInterface[]
    $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;
  • 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 the 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.

Any ideas?