Your IP : 216.73.216.43


Current Path : /home/rtorresani/www/app/code/Torresani/AggregateOrder/Model/Carrier/
Upload File :
Current File : //home/rtorresani/www/app/code/Torresani/AggregateOrder/Model/Carrier/Aggregateshipping.php

<?php

namespace Torresani\AggregateOrder\Model\Carrier;

use Magento\Quote\Model\Quote\Address\RateRequest;
use Magento\Shipping\Model\Carrier\AbstractCarrier;
use Magento\Shipping\Model\Carrier\CarrierInterface;

/**
 * Aggregate shipping model
 */
class Aggregateshipping extends AbstractCarrier implements CarrierInterface
{
    /**
     * @var string
     */
    protected $_code = 'aggregateshipping';

    /**
     * @var bool
     */
    protected $_isFixed = true;

    /**
     * @var \Magento\Shipping\Model\Rate\ResultFactory
     */
    private $rateResultFactory;

    /**
     * @var \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory
     */
    private $rateMethodFactory;

    protected $orderCollectionFactory;
    protected $dateTime;
    protected $customerRepository;
    protected $storeManager;

    /**
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory
     * @param \Psr\Log\LoggerInterface $logger
     * @param \Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory
     * @param \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Framework\Stdlib\DateTime\DateTime $dateTime,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
        \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
        \Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory,
        \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        array $data = []
    ) {
        parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data);

        $this->rateResultFactory = $rateResultFactory;
        $this->rateMethodFactory = $rateMethodFactory;
        $this->orderCollectionFactory = $orderCollectionFactory;
        $this->dateTime = $dateTime;
        $this->customerRepository = $customerRepository;
        $this->customerSession = $customerSession;
        $this->storeManager = $storeManager;
    }

    /**
     * Aggregate Shipping Rates Collector
     *
     * @param RateRequest $request
     * @return \Magento\Shipping\Model\Rate\Result|bool
     */
    public function collectRates(RateRequest $request)
    {
        if (!$this->getConfigFlag('active')) {
            return false;
        }

        $currentDate = $this->dateTime->gmtDate();
        $daysAgo = $this->dateTime->gmtDate(null, strtotime('-70 days'));
        $storeId = $this->storeManager->getStore()->getId();

        $orderCollection = $this->orderCollectionFactory->create()
            ->addFieldToSelect('*')
            ->addFieldToFilter('store_id', $storeId)
            ->addFieldToFilter('status', ['in' => ['pending', 'processing']])
            ->addFieldToFilter('created_at', ['gteq' => $daysAgo])
            ->addAttributeToFilter('customer_email', $this->customerSession->getCustomer()->getEmail())
            ->addAttributeToSort('created_at', 'desc');


        if ($orderCollection->getSize() <= 0) {
            return false;
        }
        $aggregateOrder = false;
        $referenceOrder = '';
        foreach ($orderCollection as $otherOrder) {
            $otherShippingAddress = $otherOrder->getShippingAddress();
            if ($otherShippingAddress->getStreet()[0] == $request->getDestStreet() &&
                $otherShippingAddress->getCity() == $request->getDestCity() &&
                $otherShippingAddress->getPostcode() == $request->getDestPostcode()
//              &&  $otherShippingAddress->getRegion() == $request->getDestRegionCode()
            ) {
                $aggregateOrder = true;
                $referenceOrder = 'numero ' . $otherOrder->getIncrementId() . ' del ' . date('d-m-Y h:i', strtotime($otherOrder->getCreatedAt()));
                break;
            }
        }
        if ($aggregateOrder) {
            /** @var \Magento\Shipping\Model\Rate\Result $result */
            $result = $this->rateResultFactory->create();

            /** @var \Magento\Quote\Model\Quote\Address\RateResult\Method $method */
            $method = $this->rateMethodFactory->create();

            $method->setCarrier($this->_code);
            $method->setCarrierTitle($this->getConfigData('name')." ".$referenceOrder);

            $method->setMethod($this->_code);
            $method->setMethodTitle($this->getConfigData('title'));

            $shippingCost = (float)$this->getConfigData('shipping_cost');

            $method->setPrice($shippingCost);
            $method->setCost($shippingCost);

            $result->append($method);

            return $result;
        }
        return false;
    }

    /**
     * @return array
     */
    public function getAllowedMethods()
    {
        return [$this->_code => $this->getConfigData('name')];
    }
}