0

Hi I have created a custom invoice.Its saving in one of the magento root folder.How to send the file as attachment in mail.

1
0
    <?php
    /**
     *
     * Copyright © 2016 Magento. All rights reserved.
     * See COPYING.txt for license details.
     */
    namespace Magento\Sales\Controller\Adminhtml\Invoice\AbstractInvoice;
    use Magento\Framework\App\Action\Context;
    use Magento\Framework\View\Result\PageFactory;
    use Magento\Store\Model\StoreManagerInterface;
    use Magento\Framework\Controller\ResultFactory;
    use Sm\Customerprice\Model\Customerprice;
    use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;
    use \Magento\Framework\App\Filesystem\DirectoryList;


    require_once BP . '/lib/internal/Phpexcel/PHPExcel.php';
    require_once BP . '/lib/internal/Phpexcel/PHPExcel/IOFactory.php';
    require_once BP . '/lib/internal/Phpexcel/PHPExcel/Writer/Excel2007.php';
    abstract class Email extends \Magento\Backend\App\Action
    {



    protected $resultForwardFactory;


    public function __construct(

        \Magento\Backend\App\Action\Context $context,
        //\Magento\Framework\App\Response\Http\FileFactory $fileFactory,
       \Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory,
       PageFactory $resultPageFactory,
        CollectionFactory $salesOrderCollectionFactory,
       Customerprice $customerPrice
    ) {
        $this->resultPageFactory = $resultPageFactory;
        //$this->_fileFactory = $fileFactory;
        $this->resultForwardFactory = $resultForwardFactory;
        $this->salesOrderCollectionFactory = $salesOrderCollectionFactory;
        $this->customerPrice = $customerPrice;
        parent::__construct($context,$resultForwardFactory);

    }

    /**
     * Notify user
     *
     * @return \Magento\Backend\Model\View\Result\Forward|\Magento\Backend\Model\View\Result\Redirect
     */
    public function execute()
    {
      $invoiceId = $this->getRequest()->getParam('invoice_id'); 
      if ($invoiceId) {
            $invoice = $this->_objectManager->create('Magento\Sales\Api\InvoiceRepositoryInterface')->get($invoiceId);
            if ($invoice) {


               $excelPath = $this->createExcel($invoice);

                $storeManager = $this->_objectManager->create('Magento\Store\Model\StoreManagerInterface');
                $baseUrl = $storeManager->getStore()->getBaseUrl();
                $filePath =  $baseUrl . $excelPath; 
                header("Location: $filePath");
                die();

            }
            else {
            return $this->resultForwardFactory->create()->forward('noroute');
        }



            }

    }
          public function createExcel(\Magento\Sales\Model\Order\Invoice $invoice)
          {

                      $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
                      $objPHPExcel = $objReader->load("//var/www/html/magento/app/code/Sm/Templates/KlauzInvoicePdf.xlsx");
                      $xlsName = $invoice->getIncrementId().'.xlsx';

                      $orderId = $invoice->getOrderId();


                                          $invoiceNumber = $invoice->getInvoiceNumber();
                      //echo "Invoice number ".$invoiceNumber ;
                      $createdAt = $invoice->getCreatedAt();
                      //echo "Created datetime ".$createdAt;
                      $billingAddress = $invoice->getBillingAddress();
                      //echo "billing address";
                      //echo "first name ". $billingAddress['firstname'];
                      if ($billingAddress){
                         $billName = 'M/s '.$billingAddress['firstname']. ' '.$billingAddress['lastname'];
                    $billAddr1 = $billingAddress['street']. ' '. $billingAddress['city'];
                    $billAddr2 = $billingAddress['region']. ' '. $billingAddress['postcode'];
                      }
                      $shippingAddress = $invoice->getShippingAddress();
                      if ($shippingAddress){
                         $shipName = 'M/s '.$shippingAddress['firstname']. ' '.$shippingAddress['lastname'];
                    $shipAddr1 = $shippingAddress['street']. ' '. $shippingAddress['city'];
                    $shipAddr2 = $shippingAddress['region']. ' '. $shippingAddress['postcode'];
                      }
                      //echo "shipping address";
                      //echo "lastname ". $shippingAddress['lastname'];
                      $order = $this->_objectManager->create('Magento\Sales\Model\Order')->load($orderId);

                      $dateCreateAt=date_create($createdAt);
                      $dateFormatted=date_format($dateCreateAt,"d.m.Y");
                      $timeFormatted = date_format($dateCreateAt,"H:i");
                      $objPHPExcel->setActiveSheetIndex(0)
                                ->setCellValue('K3', $invoiceNumber)
                                ->setCellValue('I4', "Date: ".date("d.m.Y"))
                                ->setCellValue('G6', $dateFormatted)
                                ->setCellValue('J6', $timeFormatted)
                    ->setCellValue('F11', $billName)
                    ->setCellValue('F12', $billAddr1)
                    ->setCellValue('F13', $billAddr2)
                    ->setCellValue('F16', $shipName)
                    ->setCellValue('F17', $shipAddr1)
                    ->setCellValue('F18', $shipAddr2);


                      if ($order) {

                    //echo " get dispatch method ".$order->getdispatchMethod();
                    $dispatchMethod = $order->getdispatchMethod();
                    //echo " Lorry number ".$order -> getLrNumber();
                    $lrNumber = $order -> getLrNumber();
                    //echo " CT3 Form number" .$order -> getCtForm();
                    //echo " customer id " .$order-> getCustomerId();
                    $customerRepository = $this->_objectManager->get('Magento\Customer\Api\CustomerRepositoryInterface');
                    $customerId = $order-> getCustomerId();
                    $customer = $customerRepository->getById($order-> getCustomerId());
                    $cattrValue = $customer->getCustomAttribute('tin_number');
                    //print_r($cattrValue);
                    if ($cattrValue){
                    //echo "tin ".$cattrValue -> getValue();
                    $customerTIN = $cattrValue -> getValue();
                    }
                    $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('H20', 'Mode of transport')
                    ->setCellValue('H21', $lrNumber)
                    ->setCellValue('H19', ucwords($dispatchMethod,"_"))
                    //->setCellValue('B44', 'CT3 number')
                    ->setCellValue('D51',$customerTIN);
                    //print the order lines
                    $orderItems = $order->getAllItems();
                    $productCollection = $this->_objectManager->get('Magento\Catalog\Model\Product');
                    $index = 1;
                    $weight = 0;
                    $qtyOrdered = 0;
                    $productName = "";
                    $unitBasePrice = 0;
                    foreach ($orderItems as $oItem){
                    $productType = $oItem->getProductType();
                    if ($productType == 'simple'){
                    $qtyOrdered = $oItem->getQtyOrdered();

                    $productName = $oItem->getName();

                    $weight = $oItem->getWeight();

                    /*$qtyInKgs = $oItem->getQtyInKgs();
                    echo "qtyInKgs ordered" .$qtyInKgs;
                    */
                    $productId = $oItem->getProductId();

                    $_product = $this->_objectManager->create('Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable')->getParentIdsByChild($productId);
                                $_productCollection = $this->_objectManager->get('Magento\Catalog\Model\Product');
                    $_productParent = $_productCollection -> load($_product[0]);
                    $parentProductSku = $_productParent->getSku();
                    $productChild = $productCollection->load($productId);
                    $optionId = $productChild->getData('packing_box');
                    $attribute = $productChild->getResource()->getAttribute('packing_box');
                    $packing = $attribute->getSource()->getOptionText($optionId);
                    $customerBasePrice = $this->customerPrice->getCollection()->addFieldToFilter('customer_id',$customerId)
                                                                                                      ->                    addFieldToFilter('product_sku',$parentProductSku)
                     ->addFieldToFilter('start_time',array("lteq" => $createdAt))
                     ->addFieldToFilter('end_time',array("gteq" => $createdAt));

                    if (sizeof($customerBasePrice) != 0){
                    foreach($customerBasePrice as $customerBasePrice){
                      switch ($packing) {
                      case "1 Kg/ltr":
                    $unitBasePrice = $customerBasePrice->getUnitPriceOne();
                    break;
                      case "5 Kg";
                    $unitBasePrice = $customerBasePrice->getUnitPriceFive();
                    break;
                      case "20 Kg";
                    $unitBasePrice = $customerBasePrice->getUnitPriceTwenty();
                    break;
                      case "Brl+5 Kg";
                    $unitBasePrice = $customerBasePrice->getUnitPriceBrlFive();
                    break;
                      case "Brl+Brl";
                            $unitBasePrice = $customerBasePrice->getUnitPriceBrlBrl();
                           break;
                                     }
                    }
                    }
                    }
                    //write onto XL


                    $totalWeight = $weight * $qtyOrdered;
                    $vat55 = $order->getTotalVatOne();
                                        $totalAmount = $order->getTotalAmount();
                                        $totalBasePrice = $order->getTotalBasePrice();
                                        $ctNumber = $order->getCtNumber();
                                        $poNumber = $order->getpoNumber();
                        //echo "vat55" . strval($vat55);
                    //print_r($vat55);
                    $vat145 = $order->getTotalVatTwo();
                    //echo "vat145". $vat145;

$number = $totalAmount;
   $no = round($number);
   $point = round($number - $no, 2) * 100;
   $hundred = null;
   $digits_1 = strlen($no);
   $i = 0;
   $str = array();
   $words = array('0' => '', '1' => 'one', '2' => 'two',
    '3' => 'three', '4' => 'four', '5' => 'five', '6' => 'six',
    '7' => 'seven', '8' => 'eight', '9' => 'nine',
    '10' => 'ten', '11' => 'eleven', '12' => 'twelve',
    '13' => 'thirteen', '14' => 'fourteen',
    '15' => 'fifteen', '16' => 'sixteen', '17' => 'seventeen',
    '18' => 'eighteen', '19' =>'nineteen', '20' => 'twenty',
    '30' => 'thirty', '40' => 'forty', '50' => 'fifty',
    '60' => 'sixty', '70' => 'seventy',
    '80' => 'eighty', '90' => 'ninety');
   $digits = array('', 'hundred', 'thousand', 'lakh', 'crore');
   while ($i < $digits_1) {
     $divider = ($i == 2) ? 10 : 100;
     $number = floor($no % $divider);
     $no = floor($no / $divider);
     $i += ($divider == 10) ? 1 : 2;
     if ($number) {
        $plural = (($counter = count($str)) && $number > 9) ? 's' : null;
        $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
        $str [] = ($number < 21) ? $words[$number] .
            " " . $digits[$counter] . $plural . " " . $hundred
            :
            $words[floor($number / 10) * 10]
            . " " . $words[$number % 10] . " "
            . $digits[$counter] . $plural . " " . $hundred;
     } else $str[] = null;
  }
  $str = array_reverse($str);
  $result = implode('', $str);
  $points = ($point) ?
   // "." . $words[$point / 10] . " " . 
          $words[$point = $point % 10] : '';
   echo $result . "Rupees  " . $points . " Paise";




                    $objPHPExcel->setActiveSheetIndex(0) 
                    ->setCellValue('A32', $index)
                    ->setCellValue('B32', $productName)
                    ->setCellValue('E32', round($weight) .' Kg x '.round($qtyOrdered))
                    ->setCellValue('F32', 'Kg')
                    ->setCellValue('H32', round($totalWeight))
                                        ->setCellValue('H43', round($totalWeight))
                    ->setCellValue('J32', $unitBasePrice)
                                        //->setCellValue('B44', "C T-3 No:".$ctNumber)
                    //->setCellValue('I53', 'Sub Total')
                    //->setCellValue('I54', 'VAT 5.5%')
                    ->setCellValue('K53', $vat55)
                                        ->setCellValue('K52', $totalBasePrice)
                                        ->setCellValue('K57', round($totalAmount))
                                        ->setCellValue('C57', ucwords($result. "Rupees only "))
                                        ->setCellValue('K32', $totalBasePrice)
                                        //->setCellValue('D51', 'po:')
                                        ->setCellValue('D50',$poNumber)
                    //->setCellValue('I55', 'VAT 14.5%')
                    ->setCellValue('K54', $vat145);
                    //->setCellValue('I49','C.Ex.  12.50 %');




                    $centralExcise = $order->getTotalCentralExcise();


                    if ($centralExcise ==0 ){
                    $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('D48', "Nill Against Form CT - 3")
                    ->setCellValue('K49', "Nill");
                    } else {
                    $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('K48', $centralExcise);
                    }
                    }
                      }
                    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
                                        $path = "document/attachment/".$invoice->getIncrementId().".xlsx";
                    $objWriter->save($path);
                    return $path;

            }      

}

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.