Question

I have used the code

if ($order->getInvoiceCollection()->count()) {
    $_invoices = $order->getInvoiceCollection();

    if ($_invoices) {
        foreach ($_invoices as $invoice) {
            $invoice->delete();
        }
    }
}

This is deleting invoice, but invoice button was not reappearing although invoice is deleted.

So, I have go through the database table and turns out order_items has item_invoiced column, I have used this code to set item invoiced value to 0

$items = $order->getAllItems();
foreach ($items as $k => $item) {
    echo $item->getId() . "\n";
    $item->setQtyInvoiced(0);
    $item->save();
}

After this code invoice button is appearing, but when I am creating invoice it is setting subtotal to negative like -1000

Was it helpful?

Solution

Looking at your code, I guess you miss the trick. You have to set order items fields to 0 which are effected by creating invoice. Replace your item foreach with this.

$items = $order->getAllItems();
    foreach ($items as $k => $item) {
        echo $item->getId() . "\n";
        $item->setBaseRowInvoiced(0);
        $item->setRowInvoiced(0);
        $item->setQtyInvoiced(0);
        $item->setDiscountInvoiced(0);
        $item->setBaseDiscountInvoiced(0);
        $item->save();
    }

You also have to add some order fields to 0 as well. for this you have to add following code in your script.

$order->setTotalPaid(0)
        ->setBaseTotalPaid(0)
        ->setBaseTotalInvoiced(0)
        ->setTotalInvoiced(0)
        ->setBaseSubtotalInvoiced(0)
        ->setSubtotalInvoiced(0)
        ->setBaseShippingInvoiced(0)
        ->setShippingInvoiced(0)
        ->setBaseDiscountInvoiced(0)
        ->setDiscountInvoiced(0);

I hope this will help, let me know once you tried my answer

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top