Your IP : 216.73.216.220


Current Path : /var/www/html/app/code/FlipsDigital/TextbookList/Controller/Adminhtml/TextbookList/
Upload File :
Current File : /var/www/html/app/code/FlipsDigital/TextbookList/Controller/Adminhtml/TextbookList/Export.php

<?php
/**
 * Delete
 *
 * @copyright Copyright © 2021 FlipsDigital. All rights reserved.
 * @author    calvin.so@flipsdigital.com
 */
namespace FlipsDigital\TextbookList\Controller\Adminhtml\TextbookList;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use FlipsDigital\TextbookList\Model\TextbookListFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class Export extends Action
{
    /** @var textbooklistFactory $objectFactory */
    protected $objectFactory;

    /**
     * @param Context $context
     * @param TextbookListFactory $objectFactory
     */
    public function __construct(
        Context $context,
        TextbookListFactory $objectFactory,
        \Psr\Log\LoggerInterface $logger,
        \FlipsDigital\CustomerTextbookList\Model\CustomerTextbookListFactory $customerTextbookListFactory,
        \FlipsDigital\EducationInstitution\Model\EducationInstitutionFactory $educationInstitutionFactory,
        \FlipsDigital\TextbookList\Model\TextbookListFactory $textbookListFactory,
        \FlipsDigital\TextbookListBook\Model\TextbookListBookFactory $textbookListBookFactory,
        \FlipsDigital\TextbookListStudent\Model\TextbookListStudentFactory $textbookListStudentFactory,
        \Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
        \Magento\Sales\Api\OrderItemRepositoryInterface $orderItemRepository,
        \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezoneInterface,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface
    ) {
        $this->objectFactory = $objectFactory;
        parent::__construct($context);
        $this->_logger = $logger;
        $this->_ctlFactory = $customerTextbookListFactory;
		$this->_eiFactory = $educationInstitutionFactory;
		$this->_tlFactory = $textbookListFactory;
		$this->_tlbFactory = $textbookListBookFactory;
		$this->_tlsFactory = $textbookListStudentFactory;
        $this->orderRepository = $orderRepository;
        $this->orderItemRepository = $orderItemRepository;
        $this->timezoneInterface = $timezoneInterface;
        $this->_customerRepositoryInterface = $customerRepositoryInterface;
    }

    /**
     * {@inheritdoc}
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('FlipsDigital_TextbookList::textbooklist');
    }

    /**
     * Delete action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $resultRedirect = $this->resultRedirectFactory->create();
        $entity_id = $this->getRequest()->getParam('entity_id', null);

        $objCTL = $this->_ctlFactory->create();
        $objEI = $this->_eiFactory->create();
        $objTL = $this->_tlFactory->create();
        $objTLB = $this->_tlbFactory->create();
        $objTLS = $this->_tlsFactory->create();

        $collectionTLB = $objTLB->getCollection();
        $collectionTLB->addAttributeToSelect('*');
        $collectionTLB->addFieldToFilter('booklist_id', $entity_id);

        $table_head = array('Identifier', 'Order ID', 'Sync Order ID', 'Order Amount', 'Payment Method 7-11', 'Payment Amount 7-11');   
        $books = array();

        if ($collectionTLB->count()){
            foreach ($collectionTLB->getItems() as $key => $value) {
                $table_head[] = $value['name'];
                $books['product_id_'.$value['product_id']] = 0;
            }
        }

        $collectionCTL = $objCTL->getCollection();
        $collectionCTL->addAttributeToSelect('*');
        $collectionCTL->addFieldToFilter('booklist_id', $entity_id);
        
        if ($collectionCTL->count()){
            $arrayData = array();
            $arrayData[] = $table_head;
            date_default_timezone_set('Asia/Hong_Kong');
            
            foreach ($collectionCTL->getItems() as $key => $value) {
                $order_id = '';
                $order = '';
                $orderItems = '';
                $table_body = array();

                if($value['order_id'] <> ''){
                    $order_id = $value['order_id'];
                    $order = $this->orderRepository->get($order_id);
                    $orderItems = $order->getAllItems();
                }

                $table_body[] = $value['identifier'];
                $table_body[] = $order_id == '' ? '' : $order_id;
                $table_body[] = $value['mers_stock_sync_g_magento_order_id'] == '' ? '' : $value['mers_stock_sync_g_magento_order_id'];
                $table_body[] = $order_id == '' ? '0' : $order->getGrandTotal();
                $table_body[] = $value['payment_method'] == '' ? '' : '1';
                $table_body[] = $value['payment_amount'] == '' ? '0' : $value['payment_amount'];
                
                if($orderItems <> ''){
                    foreach ($orderItems as $key2 => $value2) {
                        $books['product_id_'.$value2['product_id']] = $value2['qty_ordered'];
                    }
                }else{
                    foreach ($books as $key3 => $value3) {
                        $books[$key3] = '0';
                    }
                }
                foreach ($books as $key3 => $value3) {
                    $table_body[] = $value3;
                }
                $arrayData[] = $table_body;
            }

            // Export data to excel
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            $sheet->setTitle('Textbook List - '.$entity_id);
            $sheet->fromArray(
                $arrayData,  // The data to set
                NULL,        // Array values with this value will not be set
                'A1'         // Top left coordinate of the worksheet range where
                             // we want to set these values (default is A1)
            );
            //Create Styles Array
            $styleArrayFirstRow = [
                'font' => [
                    'bold' => true,
                ]
            ];
            $styleArrayLastRow = [
                'font' => [
                    'bold' => true,
                ],
                'borders' => [
                    'top' => [
                        'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                    ],
                ]
            ];
            //Retrieve Highest Column And Row
            $highestRow = $sheet->getHighestRow();
            $highestColumn = $sheet->getHighestColumn();
            $sheet->getStyle('A1:' . $highestColumn . '1' )->applyFromArray($styleArrayFirstRow);
            
            $highestColumn++;
            $lastRow = (int)($highestRow+1);
            for($col='A'; $col != $highestColumn; $col++) {
                $rang = $col.'2:'.$col.$highestRow;
                switch($col) {
                    case 'A':
                        $sheet->setCellValue($col.$lastRow, '');
                        break;
                    case 'B':
                    case 'C':
                        $sheet->setCellValue($col.$lastRow, '=COUNTA(' . $rang . ')');
                        break;
                    default:
                        $sheet->setCellValue($col.$lastRow, '=SUM(' . $rang . ')');
                }
                $sheet->getColumnDimension($col)->setAutoSize(true);
            }
            $sheet->getStyle('A'.$lastRow.':' . $sheet->getHighestColumn() . $lastRow )->applyFromArray($styleArrayLastRow);

            $writer = new Xlsx($spreadsheet);
            $response = new StreamedResponse(
                function () use ($writer) {
                    $writer->save('php://output');
                }
            );

            $excel_name = 'Textbook List - '.$entity_id.'_'.date('YmdHi');
            $response->headers->set('Content-Type', 'application/vnd.ms-excel');
            $response->headers->set('Content-Disposition', 'attachment;filename="'.$excel_name.'.xlsx"');
            $response->headers->set('Cache-Control','max-age=0');
            $response->send();

        }else{
            $this->messageManager->addErrorMessage(__('Record does not exist.'));
            return $resultRedirect->setPath('*/*');
        }
    }
}