Magento – Create Invoice Programmatically with Custom Date

admincreate-invoiceextensionsinvoicesales

I had some problems with a payment module and some invoices were not created. But I'm generating the invoices need to create programmatically and the same with the dates of the requests not to lose the billing metrics from my reports.

$orderItems = $order->getAllItems();
$invoiceItems = array();

foreach ($orderItems as $_eachItem) {
    $opid = $_eachItem->getId();
    $opdtId = $_eachItem->getProductId();

    $itemss = Mage::getModel('catalog/product')->load($opdtId);
    $psku = $itemss->getSku();

    $qty = $_eachItem->getQtyOrdered();
    $itemsarray[$opid] = $qty;
}

if($order->canInvoice()) {
    $invoiceId = Mage::getModel('sales/order_invoice_api')
    ->create($order->getIncrementId(), $itemsarray ,'Fatura Criada Manualmente via Script' ,0,0);
}

So, how create invoice with a custom date? Any Idea?

Best Answer

To set a time of your choosing for an invoice, you can add this to your script after the invoice is created. This would be most efficient if you have a csv or array to read with your order numbers or ids and the desired time to set.

EDIT:: I added a function to create the invoice, just in case. Your choice on whether or not to use it.

    $stringTime = '2011/06/01';
    $timeToSet = strtotime($stringTime);
    $orderId = '11111'

    createInvoice($orderId);
    setInvoiceDate($orderId , $timeToSet);    

    function createInvoice($orderId){
       //Create Invoice
       $savedOrder = Mage::getModel('sales/order')->loadByIncrementId($orderId);
       $invoice = Mage::getModel('sales/service_order', $savedOrder)->prepareInvoice();

       $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
       $invoice->register();

       $invoice->getOrder()->setCustomerNoteNotify(false);
       $invoice->getOrder()->setIsInProcess(true);

       $transactionSave = Mage::getModel('core/resource_transaction')
           ->addObject($invoice)
           ->addObject($invoice->getOrder());

       $transactionSave->save();
    }

    function setInvoiceDate($id, $time){
            $order = Mage::getModel('sales/order')->loadByIncrementId($id);
            $invoiceId = $order->getInvoiceCollection()->getFirstItem()->getIncrementId();
            $invoice = Mage::getModel('sales/order_invoice')->loadByIncrementId($invoiceId);
            $invoice->setCreatedAt($time);
            $invoice->save();
    }
Related Topic