I am creating a module for refunds and I have an error using the method
<?php
namespace CrediYaCrediYaControllerCrediYa;
use MagentoFrameworkAppActionAction;
use MagentoFrameworkAppActionContext;
use MagentoFrameworkAppRequestHttp;
use MagentoSalesModelOrderCreditmemoCreationArgumentsFactory;
class Refund extends Action
{
/** @var MagentoFrameworkAppRequestHttp */
protected $request;
public function __construct(
Context $context,
Http $request,
MagentoSalesApiRefundInvoiceInterface $invoiceRefunder,
CreationArgumentsFactory $creationArguments
)
{
$this->request = $request;
$this->invoiceRefunder = $invoiceRefunder;
$this->creationArguments = $creationArguments;
parent::__construct($context);
}
public function execute()
{
$items = [];
$order_id = $this->request->getParam('order_id');
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$order = $objectManager->create('MagentoSalesModelOrder')->load($order_id);
foreach ($order->getAllVisibleItems() as $item)
{
$items[$item->getId()] = array(
'qty' => $item->getQtyOrdered()
);
// $object['order_item_id'] = $item->getId();
// $object['qty'] = $item->getQtyOrdered();
}
$invoiceId = null;
foreach ($order->getInvoiceCollection() as $invoice)
{
// this will always point to the latest invoice id
$invoiceId = $invoice->getId();
}
$this->invoiceRefunder->execute(
$invoiceId, // Invoice ID (NOTE: not increment ID)
$items, // Items array (default all)
false // false = offline / true = online
);
}
}
This is the code of my class
In other questions they said that the $ items argument, if it was sent empty, the method would take it as a total return of the order, but when doing this it gives me this error Exception #0 (MagentoSalesExceptionDocumentValidationException): Creditmemo Document Validation Error(s): We can't create creditmemo for the invoice.
On the other hand, if I send something in $ items, this error no longer appears, but it gives another error, which originates from the magento vendor, specifically in this code area.
foreach ($items as $item) {
$data['qtys'][$item->getOrderItemId()] = $item->getQty();
}
This is in the file CredimemoDocumentFactory.php
, What I suppose is that I am sending the articles in the array wrong, because it is trying to call a function on each item getOrderItemId()
and getQty()
How should I send the data structure of my $ items array, to solve this error and can magento execute the necessary methods on each element?