Spamworldpro Mini Shell
Spamworldpro


Server : Apache
System : Linux server2.corals.io 4.18.0-348.2.1.el8_5.x86_64 #1 SMP Mon Nov 15 09:17:08 EST 2021 x86_64
User : corals ( 1002)
PHP Version : 7.4.33
Disable Function : exec,passthru,shell_exec,system
Directory :  /home/corals/old/vendor/extmag/shiplab/Helper/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/corals/old/vendor/extmag/shiplab/Helper/Request.php
<?php
/**
 * Copyright © Extmag. All rights reserved.
 */

namespace Extmag\Shiplab\Helper;

use DateTimeImmutable;
use DateTimeZone;
use Exception;
use Extmag\Shiplab\Model\AddressRepository;
use Extmag\Shiplab\Model\Logs;
use Extmag\Shiplab\Model\LogsFactory;
use Extmag\Shiplab\Model\LogsRepository;
use Extmag\Shiplab\Model\ShipperAccountRepository;
use Extmag\Shiplab\Model\Source\AllShippingMethods;
use Extmag\Shiplab\Model\Source\ProvinceCodes;
use Extmag\Shiplab\Model\ThirdPartyRepository;
use IntlDateFormatter;
use Magento\Catalog\Model\CategoryRepository;
use Magento\Directory\Model\CountryFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\Framework\Locale\ResolverInterface;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\Framework\Stdlib\DateTime\Timezone;

class Request
{
    protected $data;
    protected $requestData = [];
    protected $route = 'shipment';

    protected $carrier;
    protected $requestType;

    /**
     * @var Connector
     */
    protected $connector;

    /**
     * @var Manager
     */
    protected $manager;

    /**
     * @var DateTime
     */
    protected $date;

    /**
     * @var ThirdPartyRepository
     */
    protected $thirdPartyRepository;

    /**
     * @var AddressRepository
     */
    protected $addressRepository;

    /**
     * @var AllShippingMethods
     */
    protected $allShippingMethods;

    /**
     * @var Timezone
     */
    protected $timezone;

    /**
     * @var LogsFactory
     */
    protected $logs = null;

    /**
     * @var LogsRepository
     */
    protected $logsRepository = null;

    /**
     * Extmag Model Saver
     *
     * @var DataSave
     */
    public $modelSaver;
    /**
     * @var ProvinceCodes
     */
    protected $provinceCodes;
    /**
     * @var CountryFactory
     */
    protected $countryFactory;
    /**
     * @var ShipperAccountRepository
     */
    protected $shipperAccountRepository;
    /**
     * @var Filesystem
     */
    protected $filesystem;
    /**
     * @var Filesystem\Driver\File
     */
    protected $driver;
    /**
     * @var CategoryRepository
     */
    protected $categoryRepository;
    /**
     * @var ResolverInterface
     */
    protected $localeResolver;

    /**
     * Ups constructor.
     *
     * @param Connector $connector
     * @param Manager $manager
     * @param DateTime $date
     * @param ThirdPartyRepository $thirdPartyRepository
     * @param AddressRepository $addressRepository
     * @param AllShippingMethods $allShippingMethods
     * @param Timezone $timezone
     * @param LogsFactory $logs
     * @param LogsRepository $logsRepository
     * @param DataSave $modelSaver
     * @param ProvinceCodes $provinceCodes
     * @param CountryFactory $countryFactory
     * @param ShipperAccountRepository $shipperAccountRepository
     * @param Filesystem $filesystem
     * @param Filesystem\Driver\File $driver
     * @param CategoryRepository $categoryRepository
     * @param ResolverInterface $localeResolver
     */
    public function __construct(
        Connector $connector,
        Manager $manager,
        DateTime $date,
        ThirdPartyRepository $thirdPartyRepository,
        AddressRepository $addressRepository,
        AllShippingMethods $allShippingMethods,
        Timezone $timezone,
        LogsFactory $logs,
        LogsRepository $logsRepository,
        DataSave $modelSaver,
        ProvinceCodes $provinceCodes,
        CountryFactory $countryFactory,
        ShipperAccountRepository $shipperAccountRepository,
        Filesystem $filesystem,
        Filesystem\Driver\File $driver,
        CategoryRepository $categoryRepository,
        ResolverInterface $localeResolver
    ) {
        $this->connector = $connector;
        $this->manager = $manager;
        $this->date = $date;
        $this->thirdPartyRepository = $thirdPartyRepository;
        $this->addressRepository = $addressRepository;
        $this->allShippingMethods = $allShippingMethods;
        $this->timezone = $timezone;
        $this->logs = $logs;
        $this->logsRepository = $logsRepository;
        $this->modelSaver = $modelSaver;
        $this->provinceCodes = $provinceCodes;
        $this->countryFactory = $countryFactory;
        $this->shipperAccountRepository = $shipperAccountRepository;
        $this->filesystem = $filesystem;
        $this->driver = $driver;
        $this->categoryRepository = $categoryRepository;
        $this->localeResolver = $localeResolver;
    }

    /**
     * @param $route
     * @return void
     */
    public function addRequest($route = null /* ex. shipment, inverse, refund */)
    {
        $this->route = $route ?? ($this->data['route'] ?? 'shipment');
        $this->formRequest();
    }

    /**
     * @return void
     */
    protected function setRequestType()
    {
    }

    /**
     * @return void
     */
    public function formRequest()
    {
        $this->setRequestType();
        if ($this->route != 'refund') {
            $nativeScheme = $this->formNativeScheme();
            $httpHeaders = $this->getHttpHeaders();
            $this->formHeaderRequest($this->requestType, $nativeScheme, null, null, $httpHeaders);
        } else {
            $countPackages = count($this->data['packages']);
            for ($i = 0; $i < $countPackages; $i++) {
                $nativeScheme = $this->formNativeScheme($i);
                $httpHeaders = $this->getHttpHeaders();
                $this->formHeaderRequest($this->requestType, $nativeScheme, null, $i, $httpHeaders);
            }
        }
    }

    /**
     * @return mixed
     */
    public function send()
    {
        return $this->connector->send($this->requestData);
    }

    /**
     * @param      $type
     * @param      $nativeScheme
     * @param null $liveMode
     * @param null $currentPackage
     * @param array $additionalData
     */
    public function formHeaderRequest(
        $type,
        $nativeScheme,
        $liveMode = null,
        $currentPackage = null,
        $additionalData = []
    ) {
        if ($type == 'Ship' || $type == 'FreightShip') {
            if (!empty($currentPackage)) {
                $cloneData = $this->data;
                unset($cloneData['packages']);
                $cloneData['packages'][0] = $this->data['packages'][$currentPackage];
                $this->modelSaver->preSave($cloneData);
            } else {
                $this->modelSaver->preSave($this->data);
            }
        } elseif ($type == 'PickupCreation') {
            $this->modelSaver->preSavePickup($this->data);
        }

        $data = [
            'Carrier' => $this->data['carrier'],
            'Context' => $this->data['context'],
            'Type' => $type,
            'LiveMode' => $liveMode ?? $this->data['mode'],
            'NativeScheme' => $nativeScheme,
            'NativeData' => $this->data,
        ];

        if (!empty($this->data['master_id'])) {
            $data['ShipmentIdentification'] = $this->data['master_id'];
        }

        if (!empty($additionalData)) {
            $data['AdditionalData'] = $additionalData;
        }

        $this->requestData['Request'][] = $data;
    }

    /**
     * @return array
     */
    public function getRequestData()
    {
        return $this->requestData;
    }

    /**
     * @return array
     */
    public function getNativeData()
    {
        $nativeData = [];
        if (!empty($this->requestData['Request'])) {
            foreach ($this->requestData['Request'] as $item) {
                $nativeData[] = $item['NativeData']['packages'] ?? [];
            }
        }

        return $nativeData;
    }

    /**
     * @param $data
     * @return void
     */
    public function addRequestData($data)
    {
        $this->requestData['Request'][] = $data;
    }

    /**
     * @return bool
     */
    public function checkRequestData()
    {
        return !empty($this->requestData);
    }

    /**
     * @param $data
     * @return void
     */
    public function setData($data)
    {
        $this->data = $data;
    }

    /**
     * @return void
     */
    public function clearRequestData()
    {
        $this->requestData = [];
    }

    /**
     * @param $rates
     * @param $shippingMethodCode
     * @param $isRates
     *
     * @return array
     * @throws LocalizedException
     */
    public function parseResponse($rates, $shippingMethodCode, $isRates)
    {
        $nameErrors = 'rate_error';
        $respData = [];
        if (!empty($rates['result']) && is_array($rates['result']) && !empty($rates['request'])) {
            $requestData = json_decode($rates['request'], true)['Request'];
            foreach ($rates['result'] as $i => $response) {
                $nameService = 'service_code';
                $nameServices = 'service_codes';

                $data = $requestData[$i]['NativeData'] ?? [];

                if (!empty($response['Status']) && $response['Status'] == 1) {
                    $serviceCodes = [];
                    foreach ($response['Rates'] as $key => $rate) {
                        if ($rate['TimeInTransit']['Saturday'] != 1 || $data['saturday_delivery'] == 1) {
                            $label = $this->allShippingMethods
                                ->getNameByCode(
                                    $response['Carrier'],
                                    $rate['ServiceCode'],
                                    $data['ship_from_country_code'],
                                    $data['ship_to_country_code']
                                );
                            if ($isRates !== true) {
                                $label .= '  '
                                    . round((float)$rate['TotalCharge'], 2) . $rate['Currency']
                                    . (
                                    (isset($rate['TotalDiscount'])
                                        && $rate['TotalDiscount'] != 0)
                                        ? ' (' . __('discount:') . ' ' . round(
                                            (float)$rate['TotalDiscount'])
                                        . $rate['Currency'] . ')' : ''
                                    ) . (
                                    (isset($rate['TotalTax'])
                                        && $rate['TotalTax'] != 0)
                                        ? ' (' . __('tax:') . ' ' . round(
                                            (float)$rate['TotalTax'])
                                        . $rate['Currency'] . ')' : ''
                                    );
                            }

                            if ($isRates !== true) {
                                if (!empty($rate['TimeInTransit']['Arrival'])) {
                                    $date = $rate['TimeInTransit']['Arrival']['Date'];
                                    $time = $rate['TimeInTransit']['Arrival']['Time'];
                                    if (!empty($rate['TimeInTransit']['Pickup']['Date'])) {
                                        $pickupDate = $rate['TimeInTransit']['Pickup']['Date'];
                                        $pickupTime = $rate['TimeInTransit']['Pickup']['Time'];
                                        $dateFormatFrom = $pickupDate['Y']
                                            . '-' . $pickupDate['m']
                                            . '-' . $pickupDate['d']
                                            . ' ' . $pickupTime['H']
                                            . ':' . $pickupTime['i'];
                                        if ($pickupDate['Y'] == $date['Y']) {
                                            $formatDate = $this->timezone->formatDateTime(
                                                $dateFormatFrom, IntlDateFormatter::NONE, IntlDateFormatter::NONE, null,
                                                null, $this->getDateFormatWithoutYear());
                                        } else {
                                            $formatDate = $this->timezone
                                                ->formatDate($dateFormatFrom, IntlDateFormatter::MEDIUM, true);
                                        }

                                        $label .= ' (' . $formatDate;
                                    }
                                    $dateFormatTo = $date['Y']
                                        . '-' . $date['m']
                                        . '-' . $date['d']
                                        . ' ' . $time['H']
                                        . ':' . $time['i'];
                                    if (($pickupDate['Y'] ?? null) == $date['Y']) {
                                        $formatDate = $this->timezone->formatDateTime(
                                            $dateFormatTo, IntlDateFormatter::NONE, IntlDateFormatter::NONE, null, null,
                                            $this->getDateFormatWithoutYear());
                                    } else {
                                        $formatDate = $this->timezone
                                            ->formatDate($dateFormatTo, IntlDateFormatter::MEDIUM, true);
                                    }
                                    if (!empty($rate['TimeInTransit']['Pickup']['Date'])) {
                                        $label .= ' - ' . $formatDate . ')';
                                    } else {
                                        $label .= '  ' . $formatDate;
                                    }
                                }

                                $serviceCodes[$response['Carrier']][] = [
                                    'carrier' => $response['Carrier'],
                                    'value' => $rate['ServiceCode'],
                                    'label' => $label,
                                    'price' => $rate['TotalCharge'],
                                    'price_with_discount' => $rate['TotalDiscount'] ?? 0,
                                    'price_without_tax' => $rate['TotalTax'] ?? 0,
                                    'tit' => ($rate['TimeInTransit'] ?? []),
                                    'currency' => $rate['Currency'],
                                ];
                            } else {
                                $serviceCodes[$response['Carrier']][$rate['ServiceCode']] = [
                                    'carrier' => $response['Carrier'],
                                    'label' => $label,
                                    'key' => $rate['ServiceCode'],
                                    'price' => $rate['TotalCharge'],
                                    'price_with_discount' => $rate['TotalDiscount'] ?? 0,
                                    'price_without_tax' => $rate['TotalTax'] ?? 0,
                                    'tit' => ($rate['TimeInTransit'] ?? []),
                                    'currency' => $rate['Currency'],
                                ];
                            }

                            if ($shippingMethodCode !== null && $shippingMethodCode == $rate['ServiceCode']) {
                                $data[$nameService] = $shippingMethodCode;
                            }
                        }
                    }
                    $data[$nameServices] = $serviceCodes;
                    /**
                     * @var $log Logs
                     */
                    $log = $this->logs->create();
                    $log->setRow(
                        'success',
                        'rate',
                        $response['Carrier'],
                        __("Shipping cost was received successfully."),
                        $data['route'],
                        0,
                        $rates['request'] ?? "",
                        $rates['result'] ?? ""
                    );
                    $this->logsRepository->save($log);
                } elseif (!empty($response['Errors'])
                    && is_array($response['Errors'])
                ) {
                    $errors = [];
                    foreach ($response['Errors'] as $error) {
                        $errors[] = $error['Description'];
                    }

                    $data[$nameErrors] = $errors;
                    if (!empty($data[$nameErrors])) {
                        foreach ($data[$nameErrors] as $err) {
                            /**
                             * @var $log Logs
                             */
                            $log = $this->logs->create();
                            $log->setRow(
                                'error',
                                'rate',
                                $response['Carrier'],
                                $err,
                                $data['route'],
                                0,
                                $rates['request'] ?? "",
                                $rates['result'] ?? ""
                            );
                            $this->logsRepository->save($log);
                        }
                    }
                }

                $respData[] = $data;
            }
        }

        return $respData;
    }

    /**
     * @return int|string
     */
    protected function getTotalWeight()
    {
        $packages = $this->data['packages'] ?? [];
        $weight = 0;
        if (is_array($packages) && count($packages) > 0) {
            foreach ($packages as $package) {
                $packageWeight = str_replace(",", ".", $package['weight']);
                if (!empty($packageWeight) && is_numeric($packageWeight)) {
                    $weight += $packageWeight;
                }
            }
        }

        // TODO will be exception if packages is not exist

        return $weight;
    }

    /**
     * @return float
     */
    protected function getTotalPrice()
    {
        $packages = $this->data['packages'] ?? [];
        $price = 0;
        if (is_array($packages) && count($packages) > 0) {
            foreach ($packages as $package) {
                $declaredValue = str_replace(",", ".", $package['declared_value']);
                if (!empty($declaredValue) && is_numeric($declaredValue)) {
                    $price += $declaredValue;
                }
            }
        }

        // TODO will be exception if packages is not exist

        return round($price, 2);
    }

    /**
     * @param $type
     *
     * @return array
     */
    protected function getAddressLines($type)
    {
        $addressLines = [];
        if (!empty($this->data[$type . 'street_1'])) {
            $addressLines[] = $this->data[$type . 'street_1'];
        }
        if (!empty($this->data[$type . 'street_2'])) {
            $addressLines[] = $this->data[$type . 'street_2'];
        }
        if (!empty($this->data[$type . 'street_3'])) {
            $addressLines[] = $this->data[$type . 'street_3'];
        }

        return $addressLines;
    }

    /**
     * @return DateTimeImmutable|null
     * @throws Exception
     */
    public function getTimezoneByAccount()
    {
        if (!empty($this->data['account_timezone'])) {
            return (new DateTimeImmutable())->setTimezone(new DateTimeZone($this->data['account_timezone']));
        }

        return null;
    }

    /**
     * @return bool
     */
    protected function isInternational()
    {
        return ($this->data['ship_to_country_code'] != $this->data['ship_from_country_code']
            || (
                $this->data['ship_to_country_code'] == 'GB'
                &&
                (
                    (substr(trim($this->data['ship_to_postal_code']), 0, 2) == 'BT'
                        && substr(trim($this->data['ship_from_postal_code']), 0, 2) != 'BT')
                    ||
                    (substr(trim($this->data['ship_to_postal_code']), 0, 2) != 'BT'
                        && substr(trim($this->data['ship_from_postal_code']), 0, 2) == 'BT')
                )
            )
        );
    }

    /**
     * @return float|int
     */
    protected function getFreightCharges()
    {
        if (!empty($this->data['service_codes'][$this->carrier])) {
            foreach ($this->data['service_codes'][$this->carrier] as $datum) {
                if (!empty($datum['value']) && $datum['value'] == $this->data['service_code']) {
                    return round(
                        (float)$this->manager->convertBaseToCurrency(
                            $datum['price_with_discount'],
                            $datum['currency'],
                            $this->data['currency']
                        ), 2);
                }
            }
        }

        return 0;
    }

    /**
     * @return array|string|string[]|null
     */
    protected function getDateFormatWithoutYear()
    {
        return preg_replace(
            ['/[^a-zA-z\s]*y[^a-zA-z\s]*/', '/[^a-zA-z\s]*Y[^a-zA-z\s]*/', '/[^a-zA-z\s]*s[^a-zA-z\s]*/'],
            ['', '', ''],
            (new IntlDateFormatter(
                $this->localeResolver->getLocale(),
                IntlDateFormatter::MEDIUM,
                IntlDateFormatter::MEDIUM
            ))->getPattern()
        );
    }

    /**
     * Get Volumes
     *
     * @param $weight
     * @return float
     * @throws Exception
     */
    protected function getVolumeWeight($weight)
    {
        $rate = $this->data['volumetric_metric_coefficient'] ?? 1;
        if ($this->data['unit_dimension_for_shipper'] == "IN") {
            $rate = $this->data['volumetric_imperial_coefficient'] ?? 1;
        }

        return round(((float)$weight) / (float)$rate, 1);
    }

    /**
     * @return array
     */
    public function getHttpHeaders(): array
    {
        return [];
    }
}

Spamworldpro Mini