Magento 1.9 – How to Send Invoice Mail to Customer

magento-1.9transactional-mail

We are using Marketplace Extension, so seller can also process their order from their end it's working fine

public function saveTrackingNumberAction(){
            try{
                if($this->getRequest()->isPost()){
                    $orderid=$this->getRequest()->getParam('order_id');
                    $trackingid=$this->getRequest()->getParam('tracking_id');
                    $carrier=$this->getRequest()->getParam('carrier');
                    $order=Mage::getModel('sales/order')->load($orderid);
                    $partnerid=Mage::getSingleton('customer/session')->getCustomer()->getId();
                    $items=array();
                    $shippingAmount=0;
                    $trackingsdata=Mage::getModel('mpshippingmanager/tracking')->getCollection()
                                                     ->addFieldToFilter('order_id',array('eq'=>$orderid))
                                                     ->addFieldToFilter('seller_id',array('eq'=>$partnerid));
                    $product=Mage::getModel('catalog/product')->load($itemid);
                    foreach($trackingsdata as $tracking){
                        $tracking->setTrackingNumber($trackingid);
                        $tracking->setCarrierName($carrier);
                        $tracking->save();
                        $product_name="";
                        $shippingAmount=$tracking->getShippingCharges();
                        $items=explode(',',$tracking->getItemIds());
                        foreach($order->getAllItems() as $item){
                            if(in_array($item->getId(),$items)){
                                $product_name =$product_name.$product->getName()." ,";
                            }
                        }

                        $product_name = $product->getName();
                        $to = $order->getCustomerEmail();

                        $emailTemp = Mage::getModel('core/email_template')->loadDefault('trackingnopartner');
                        $emailTempVariables = array();              
                        $adminEmail=Mage::getStoreConfig('trans_email/ident_general/email');
                        $emailTempVariables['myvar1'] = $order->getIncrementId();
                        $emailTempVariables['myvar2'] = $product_name;
                        $emailTempVariables['myvar3'] = $order->getIncrementId();
                        $emailTempVariables['myvar4'] = $trackingid;
                        $processedTemplate = $emailTemp->getProcessedTemplate($emailTempVariables);
                        $emailTemp->setSenderName('Admin');
                        $emailTemp->setSenderEmail($adminEmail);
                        $emailTemp->send($to,'Admin',$emailTempVariables);
                    }

                        /**/
                    $itemsarray = $this->_getItemQtys($order,$items);

                    if(count($itemsarray)>0){
                        if($order->canInvoice()) { 
                            $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice($itemsarray['data']);
                            $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
                            $invoice->setShippingAmount($shippingAmount);
                            $invoice->setSubtotal($itemsarray['subtotal']);
                            $invoice->setBaseSubtotal($itemsarray['baseSubtotal']);
                            $invoice->setGrandTotal($itemsarray['subtotal']+$shippingAmount);
                            $invoice->setBaseGrandTotal($itemsarray['subtotal']+$shippingAmount);
                            $invoice->register();

                            $transactionSave = Mage::getModel('core/resource_transaction')
                                        ->addObject($invoice)
                                        ->addObject($invoice->getOrder());
                            $transactionSave->save();
                            $order->sendNewOrderEmail()->addStatusHistoryComment(
                                Mage::helper('mpshippingmanager')->__('Notified customer about invoice #%s.', $invoice->getId())
                            )
                            ->setIsCustomerNotified(true)
                            ->save();
                            $seller_invoice_id = $invoice->getId();
                        }else{
                            if($order->hasInvoices()) {
                                foreach ($order->getInvoiceCollection() as $inv) { 
                                    foreach ($inv->getAllItems() as $item) { 
                                        $product_id = $item->getProductId();
                                        $seller_pro_coll=Mage::getModel('marketplace/product')->getCollection()
                                                                ->addFieldToFilter('mageproductid',array('eq'=>$product_id))
                                                                ->addFieldToFilter('userid',array('eq'=>$partnerid));
                                        foreach ($seller_pro_coll as $value) {
                                            if($value->getMageproductid()){
                                                $seller_invoice_id = $inv->getId();
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }


                        $shipment = false;              
                        $shipmentId = $this->getRequest()->getParam('shipment_id');         
                        $orderId = $orderid;    
                        if($shipmentId){
                            $shipment = Mage::getModel('sales/order_shipment')->load($shipmentId);
                        }elseif($orderId){
                            $order  = Mage::getModel('sales/order')->load($orderId);
                            if (!$order->getId()) {
                                $this->_getSession()->addError($this->__('The order no longer exists.'));
                                return false;
                            }
                            if($order->getForcedDoShipmentWithInvoice()){
                                $this->_getSession()->addError($this->__('Cannot do shipment for the order separately from invoice.'));
                                return false;
                            }
                            if(!$order->canShip()){
                                $this->_getSession()->addError($this->__('Cannot do shipment for the order.'));
                                return false;
                            }

                            $savedQtys = $this->_getItemQtys($order,$items);
                            $shipment = Mage::getModel('sales/service_order', $order)->prepareShipment($savedQtys['data']);
                        }
                        $shipment->register();
                        $comment = '';
                        $shipment->getOrder()->setCustomerNoteNotify(1);
                        $responseAjax = new Varien_Object();
                        $isNeedCreateLabel = isset($data['create_shipping_label']) && $data['create_shipping_label'];
                        if ($isNeedCreateLabel && true) {
                            $responseAjax->setOk(true);
                        }

                        /* Custom Code */
                        $shipment->getOrder()->setState('Invoice');


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

                        /* Custom Code */


                        /*sale list status update*/
                        $partnerid=Mage::getSingleton('customer/session')->getCustomer()->getId();
                        $collection = Mage::getModel('marketplace/saleslist')->getCollection()
                                    ->addFieldToFilter('mageproownerid', array('eq' => $partnerid))
                                    ->addFieldToFilter('mageorderid', array('eq' => $orderid));
                        foreach($collection as $saleproduct){
                            $saleproduct->setCpprostatus(1);
                            $saleproduct->save();
                        }
                        /*sale list status update*/
                        $shipment->sendEmail(1, $comment);
                        $shipmentCreatedMessage = $this->__('The Invoice has been created.');
                        $labelCreatedMessage    = $this->__('The Invoice lable and Shipping label has been created.');
                        $this->_getSession()->addSuccess($isNeedCreateLabel ? $shipmentCreatedMessage . ' ' . $labelCreatedMessage
                            : $shipmentCreatedMessage); 

                        $trackingcol1=Mage::getModel('mpshippingmanager/tracking')->getCollection()
                                    ->addFieldtoFilter('order_id',array('eq'=>$orderid))
                                    ->addFieldtoFilter('seller_id ',array('in'=>$partnerid));
                        $courrier="custom";
                        foreach($trackingcol1 as $row) {
                            if($shipment->getId() != '') { 
                                $row->setShipmentId($shipment->getId());
                                $row->setInvoiceId($seller_invoice_id)->save();
                                $track = Mage::getModel('sales/order_shipment_track')
                                 ->setShipment($shipment)
                                 ->setData('title',  $row->getCarrierName())
                                 ->setData('number', $row->getTrackingNumber())
                                 ->setData('carrier_code',  $courrier)
                                 ->setData('order_id', $shipment->getData('order_id'))
                                 ->save();
                            }
                        }
                    }
                    $trackingcol=Mage::getModel('mpshippingmanager/tracking')->getCollection()
                                    ->addFieldtoFilter('order_id',array('eq'=>$orderid))
                                    ->addFieldtoFilter('tracking_number',array('eq'=>''));
                    if(count($trackingcol)==0){
                        $trackingcol=Mage::getModel('mpshippingmanager/tracking')->getCollection()
                                    ->addFieldtoFilter('order_id',array('eq'=>$orderid))
                                    ->addFieldtoFilter('tracking_number',array('eq'=>'canceled'));
                        $order = Mage::getModel('sales/order')->load($orderid);
                        if(count($trackingcol)==0){
                            $product_order_id = $order->getIncrementId();
                            $order->setStatus('Invoice');
                            $order->save();
                        }else{
                            $order->setStatus('Invoice');
                            $order->save();
                        }
                        $order->sendNewOrderEmail();
                        $historyItem = Mage::getResourceModel('sales/order_status_history_collection')
                            ->getUnnotifiedForInstance($order, Mage_Sales_Model_Order::HISTORY_ENTITY_NAME);
                        if ($historyItem) {
                            $historyItem->setIsCustomerNotified(1);
                            $historyItem->save();
                        }       
                    }
                    if(count($trackingsdata)==0)
                        Mage::getSingleton('core/session')->addError("This Order has been Invoiced Successfully");
                    else
                        Mage::getSingleton('core/session')->addSuccess('This Order has been Invoiced Successfully');
                    $this->_redirect('mpshippingmanager/shipping/invoice/id/',array('id'=>$orderid));
                }
            }catch(Exception $e){
                Mage::getSingleton('core/session')->addError($e->getMessage());
                $this->_redirect('mpshippingmanager/shipping/invoice/id/',array('id'=>$orderid));
            }
        }

if i use this customer got Shipment mail not a Invoice mail How to send Invoice mail to customer?

Best Answer

$transactionSave->save();

after that add this line to send invoice email

$invoice->sendEmail(true, '');

Related Topic