Take a look at the Magento\Sales\Api\CreditmemoManagementInterface::cancel
method and at the Magento\Sales\Api\CreditmemoRepositoryInterface::delete
methods. First you should get your creditmemo using Magento\Sales\Api\CreditmemoRepositoryInterface::get($id)
method. Then use Magento\Sales\Api\CreditmemoManagementInterface::cancel($id)
method to cancel it and Magento\Sales\Api\CreditmemoRepositoryInterface::delete(\Magento\Sales\Api\Data\CreditmemoInterface $entity)
to delete. In theory your code should looks like this:
class DeleteCreditmemo
{
public function __construct(
\Magento\Sales\Api\CreditmemoManagementInterface $creditmemoManagement,
\Magento\Sales\Api\CreditmemoRepositoryInterface $creditmemoRepository
) {
$this->creditmemoManagement = $creditmemoManagement;
$this->creditmemoRepository = $creditmemoRepository;
}
public function deleteById($id)
{
try {
$creditMemo = $this->creditmemoRepository->get($id);
$this->creditmemoManagement->cancel($id);
$this->creditmemoRepository->delete($creditMemo);
} catch (\Exception $e) {
// something went wrong
}
}
}
UPDATE:
As I see magento team restrict deletion of creditmemos right in their code:/**
* Cancel an existing creditmemo
*
* @param int $id Credit Memo Id
* @return bool
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function cancel($id)
{
throw new \Magento\Framework\Exception\LocalizedException(__('You can not cancel Credit Memo'));
try {
$creditmemo = $this->creditmemoRepository->get($id);
$creditmemo->setState(\Magento\Sales\Model\Order\Creditmemo::STATE_CANCELED);
foreach ($creditmemo->getAllItems() as $item) {
$item->cancel();
}
$this->eventManager->dispatch('sales_order_creditmemo_cancel', ['creditmemo' => $creditmemo]);
$this->creditmemoRepository->save($creditmemo);
} catch (\Exception $e) {
throw new \Magento\Framework\Exception\LocalizedException(__('Could not cancel creditmemo'), $e);
}
return true;
}
So you can reproduce & use same logic as in the method in your own model, but this is not a right way... In any case, I hope this information will be useful to you.