1

I can create Credit Memo for invoice as given in this link.

Can anyone please help me to create Credit Memo with partial products and not returning all the products in invoice.

0

In Magento, if you want to create a credit memo, then you need to use below class:

  • \Magento\Sales\Api\RefundOrderInterface
  • \Magento\Sales\Api\InvoiceRepositoryInterface
  • \Magento\Sales\Api\Data\CreditmemoItemCreationInterfaceFactory

Example:

<?php


namespace {namespace};

class {ClassName}  
{

    /**
     * @var \Magento\Sales\Api\Data\CreditmemoItemCreationInterfaceFactory
     */
    private $CreditmemoItemCreationFactory;

    /**
     * @var \Magento\Sales\Api\InvoiceRepositoryInterface
     */
    private $invoiceRepository;

    /**
     * @var \Magento\Sales\Api\RefundOrderInterface
     */
    private $refundOrder;



    public function __construct(
         \Magento\Sales\Api\RefundOrderInterface $refundOrder,
         \Magento\Sales\Api\InvoiceRepositoryInterface $invoiceRepository,
         \Magento\Sales\Api\Data\CreditmemoItemCreationInterfaceFactory $CreditmemoItemCreationFactory 
        ) {
        $this->refundOrder = $refundOrder;
        $this->invoiceRepository = $invoiceRepository;
        $this->CreditmemoItemCreationFactory = $CreditmemoItemCreationFactory;
    }
    public function execute() 
    {
        $invoiceId = 5;
        try{

            $invoice= $this->invoiceRepository->get($invoiceId);
        } catch (\Magento\Framework\Exception\NoSuchEntityException $ex) {
            return ;
        }

        $invoiceItems = $invoice->getItems();
        $items = [];
        $orderId = $invoice->getOrderId();

        foreach ($invoiceItems as $invoiceItem) {


            if($invoiceItem->getOrderItem()->getParentItem()){
                continue;
            }

            $productId = $invoiceItem->getProductId();
            $invoiceSku = $invoiceItem->getSku();

            /**
             * If product id match then create Credit memo for that order
             */
            if($productId === 2030){
                $creditmemoItemCreation = $this->CreditmemoItemCreationFactory->create();
                $items[] = $creditmemoItemCreation->setQty($invoiceItem->getQty())
                         ->setOrderItemId($invoiceItem->getOrderItemId());                
            }





        }



        /**
         * Create Credit Memo
         */

        $this->refundOrder->execute($orderId, $items, true, false);
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.