Custom shipment export magento2

<?php
namespace Codes\Bug\Controller\Adminhtml\Shipment;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use Magento\Backend\App\Action\Context;
use Magento\Sales\Model\ResourceModel\Order\Invoice\CollectionFactory;
use Magento\Ui\Component\MassAction\Filter;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\App\DeploymentConfig;
use Magento\Framework\Config\ConfigOptionsListConstants;
use Magento\Framework\App\Filesystem\DirectoryList;
class Shipmentexport extends \Magento\Sales\Controller\Adminhtml\Order\AbstractMassAction
{
  const ENCLOSURE = '"';
  const DELIMITER = ',';
  protected $_directoryList;
  public $_resource;
  private $deploymentConfig;
  private $objectManager;
  public function __construct(Context $context,
  ResourceConnection $resource,
  Filter $filter, CollectionFactory $collectionFactory,DeploymentConfig $deploymentConfig,DirectoryList $directory_list)
    {
    $this->_resource = $resource;
    parent::__construct($context , $filter);
    $this->deploymentConfig = $deploymentConfig;
    $this->collectionFactory = $collectionFactory;
    $this->_directoryList = $directory_list;
    $this->objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  }

    /**
     * Cancel selected orders
     *
     * @param AbstractCollection $collection
     * @return \Magento\Backend\Model\View\Result\Redirect
     */

    protected function massAction(AbstractCollection $collection)
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $shipmentCollection = $objectManager->create('Magento\Sales\Model\ResourceModel\Order\Shipment\CollectionFactory');
        $data = $this->getRequest()->getParams();
        if (array_key_exists("excluded", $data)) {
            $collection = $shipmentCollection->create()->load();
        } else {
            $collection = $shipmentCollection->create()
                    ->addFieldToFilter('entity_id', array('in' => $data['selected']))
                    ->load();
        }
        if (!file_exists($this->_directoryList->getRoot().'/pub/media/orderexport')) {
            mkdir($this->_directoryList->getRoot().'/pub/media/orderexport', 0777, true);
        }
        $todayDate = date('Y_m_d_H_i_s', time());
        $fileName = $this->_directoryList->getRoot().'/pub/media/orderexport/mainifest-'.$todayDate.'.csv';
        $fp = fopen($fileName, 'w');

   $this->writeHeadRow($fp);
   $countOrderExport = 0;
        foreach ($collection as $key => $value) {
             $order = $value->getOrder();
             $this->writeOrder($order,$fp);
             $countOrderExport++;
         }       

  fclose($fp);
        $this->downloadCsv($fileName);
        $this->messageManager->addSuccess(__('We Exported %1 Sale(s).', $countOrderExport));
    }

    public function downloadCsv($file)
    {
        if (file_exists($file)) {
            //set appropriate headers
            header('Content-Description: File Transfer');
            header('Content-Type: application/csv');
            header('Content-Disposition: attachment; filename='.basename($file));
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            ob_clean();flush();
            readfile($file);
        }
    }

  protected function writeHeadRow($fp)
    {
        fputcsv($fp, $this->getHeadRowValues(), self::DELIMITER, self::ENCLOSURE);
    }
  protected function getHeadRowValues()
    {
        // Shipment #  Date Shipped    Order # Order Date  Ship to Name    Total Qty   Brand Box   Shipper AWB NO. Weight

        return array(
            // 'parent_id',
            'Shipment #',
            'Date Shipped',
            'Order #',
            'Order Date',
            'Ship to Name',
            'Total Qty',
            'Brand Box',
            'Shipper',
            'AWB NO.',
            'Weight'
     );
    }

protected function writeOrder($order, $fp)
    {   $record = $this->getOrderItemValues($order);
        fputcsv($fp, $record, self::DELIMITER, self::ENCLOSURE);
    }

 protected function getOrderItemValues($order)
    {     
        $shipper = $order->getCustomerFirstname().' '.$order->getCustomerLastname();
        $shipmentCollection = $order->getShipmentsCollection();
        $shipmentData = [];
        foreach ($shipmentCollection as $shipment) {  
            $shipmentData['id'] = $shipment->getId();
            $shipmentData['Date'] = $shipment->getCreatedAt();   
        }
        $_orderAllVisibleItems = $order->getAllVisibleItems();
        $shipmentqty = 0;        
        foreach($_orderAllVisibleItems as $_item ) {
            $shipmentqty+= $_item->getData('qty_shipped');        

        }
        $track = $order->getTracksCollection()->getFirstItem()->getData('track_number');
        $shipid = $order->getTracksCollection()->getFirstItem()->getData('increment_id');
        $data_array = array($shipmentData['id'],$shipmentData['Date'],$order->getIncrementId(),$order->getCreatedAt(),$shipper,$shipmentqty,$order->getBrandBox(),$shipper,$track,$order->getShipWeight());
        return $data_array;
    }


  protected function getTotalQtyItemsOrdered($order,$invoice)
 {
        $qty = 0;
        $orderedItems = $invoice->getAllItems();
        foreach ($orderedItems as $qitem)
        {
            if($qitem->getData('base_row_total')!=null && $qitem->getData('base_row_total')!=''){
                $qty += (int)$qitem->getQty();
            }
        }
        return $qty;
    }
}

Comments