Your IP : 216.73.216.220


Current Path : /var/www/magento.test.indacotrentino.com/www/app/code/Torresani/SiWeGO/Model/Carrier/
Upload File :
Current File : /var/www/magento.test.indacotrentino.com/www/app/code/Torresani/SiWeGO/Model/Carrier/Siwego.php

<?php
/**
 * Torresani
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * Torresani SiWeGO
 *
 * @category Torresani
 * @package Torresani_SiWeGO
 * @copyright Copyright (c) 2014 Zowta LLC (http://www.Torresani.com)
 * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
 * @author Torresani Team sales@torresani.com
 *
 */
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Torresani\SiWeGO\Model\Carrier;

use Magento\Framework\Exception\LocalizedException;
use Magento\Quote\Model\Quote\Address\RateRequest;
use DateInterval;

class Siwego extends \Magento\Shipping\Model\Carrier\AbstractCarrier implements
    \Magento\Shipping\Model\Carrier\CarrierInterface
{
    /**
     * @var string
     */
    protected $_code = 'siwego';

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

    /**
     * @var string
     */
    protected $defaultConditionName = 'package_weight';

    /**
     * @var array
     */
    protected $conditionNames = [];

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

    /**
     * @var \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory
     */
    protected $resultMethodFactory;

    /**
     * @var \Torresani\SiWeGO\Model\ResourceModel\Carrier\SiwegoFactory
     */
    protected $siwegoFactory;

    /**
     * @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 $resultMethodFactory
     * @param \Torresani\SiWeGO\Model\ResourceModel\Carrier\SiwegoFactory $siwegoFactory
     * @param array $data
     * @SuppressWarnings(PHPMD.UnusedLocalVariable)
     */
    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory,
        \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $resultMethodFactory,
        \Torresani\SiWeGO\Model\ResourceModel\Carrier\SiwegoFactory $siwegoFactory,
        array $data = []
    ) {
        $this->rateResultFactory = $rateResultFactory;
        $this->resultMethodFactory = $resultMethodFactory;
        $this->siwegoFactory = $siwegoFactory;
        parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data);
        foreach ($this->getCode('condition_name') as $k => $v) {
            $this->conditionNames[] = $k;
        }
    }

    /**
     * @param RateRequest $request
     * @return \Magento\Shipping\Model\Rate\Result
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function collectRates(RateRequest $request)
    {
        if (!$this->getConfigFlag('active')) {
            return false;
        }

        /** @var \Magento\Shipping\Model\Rate\Result $result */
        $result = $this->rateResultFactory->create();

        date_default_timezone_set('UTC');
        $currentDateTime = new \DateTime();
        $currentDateTime->modify('+24 hours');
        $nextValidDateTime = $this->findNextValidDateTime($currentDateTime);
        $date = $nextValidDateTime->format('Y-m-d\TH:i:s.u\Z');

        $username='indacostaging';
        $password='Fa_R^7.2@jfqD&zDbS4';
        $URL='https://stagingapi.siwego.app/routes/availability';
        $sessionId = 'indaco-'. $request->getDestRegionCode() . '-' . time();
        $type = 'carry';
        $from = urlencode('Via Vienna, 7, Spini di Gardolo, TN, 38121, Trento, Italia');
        $to = urlencode($request->getDestStreet() . ', ' . $request->getDestCity() . ', ' . $request->getDestPostcode() . ', ' . $request->getDestRegionId() . ', ' . $request->getDestRegionCode());
        $packageWeight = 1000;

        $URL = "$URL?sessionId=$sessionId&type=$type&from=$from&to=$to&date=$date&packageWeight=$packageWeight";

        $ch = curl_init();
        $headers = array(
            'Content-Type:application/json',
            'Authorization: Basic '. base64_encode("$username:$password")
        );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_URL,$URL);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

        if( ! $resultJson = curl_exec($ch)) {
            trigger_error(curl_error($ch));
        }
        curl_close($ch);
        $r = json_decode($resultJson, true);
        if (is_array($r) && count($r) > 0) {
            /** @var \Magento\Quote\Model\Quote\Address\RateResult\Method $method */
            $method = $this->resultMethodFactory->create();

            $method->setCarrier('siwego');
            $method->setCarrierTitle('Contrattazione su sito partner');

            $method->setMethod('siwego_' . 'nonso');
            $method->setMethodTitle('SiWeGO (' . $sessionId . ')');
            $method->setPrice('0');
            $method->setCost('0');

            $result->append($method);
        }
        return $result;
    }

    /**
     * @param \Magento\Quote\Model\Quote\Address\RateRequest $request
     * @param bool $zipRange
     * @return array|bool
     */
    public function getRate(\Magento\Quote\Model\Quote\Address\RateRequest $request, $zipRange)
    {
        return $this->siwegoFactory->create()->getRate($request, $zipRange);
    }

    /**
     * @param string $type
     * @param string $code
     * @return array
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function getCode($type, $code = '')
    {
        $codes = $this->getRawCodes();

        if (!isset($codes[$type])) {
            throw new LocalizedException(__('Please correct Matrix Rate code type: %1.', $type));
        }

        if ('' === $code) {
            return $codes[$type];
        }

        if (!isset($codes[$type][$code])) {
            throw new LocalizedException(__('Please correct Matrix Rate code for type %1: %2.', $type, $code));
        }

        return $codes[$type][$code];
    }

    /**
     * Thanks to https://github.com/JeroenVanLeusden for this user submitted enhancement
     *
     * @return array
     */
    public function getRawCodes(): array
    {
        return [
            'condition_name' => [
                'package_weight' => __('Weight vs. Destination'),
                'package_value' => __('Order Subtotal vs. Destination'),
                'package_qty' => __('# of Items vs. Destination')
            ],
            'condition_name_short' => [
                'package_weight' => __('Weight'),
                'package_value' => __('Order Subtotal'),
                'package_qty' => __('# of Items')
            ]
        ];
    }

    /**
     * Get allowed shipping methods
     *
     * @return array
     */
    public function getAllowedMethods()
    {
        return ['siwego' => $this->getConfigData('name')];
    }

    public function findNextValidDateTime($dateTime) {
        $startTime1 = 8;
        $endTime1 = 12;
        $startTime2 = 13;
        $endTime2 = 18;
        if ($dateTime->format('N') >= 1 && $dateTime->format('N') <= 5) {
            if ($dateTime->format('H') >= $startTime1 && $dateTime->format('H') < $endTime1) {
                return $dateTime;
            } elseif ($dateTime->format('H') >= $endTime1 && $dateTime->format('H') < $startTime2) {
                $dateTime->setTime(13, 0);
            } elseif ($dateTime->format('H') >= $endTime2) {
                $dateTime->add(new DateInterval('P1D'));
                $dateTime->setTime($startTime1, 0);
            }
        } else {
            $nextWeekday = 1 + (7 - $dateTime->format('N'));
            $dateTime->add(new DateInterval('P' . $nextWeekday . 'D'));
            $dateTime->setTime($startTime1, 0);
        }
        return $dateTime;
    }
}