first commit

This commit is contained in:
2024-11-05 12:22:50 +01:00
commit e5682a3912
19641 changed files with 2948548 additions and 0 deletions

View File

@@ -0,0 +1,127 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Adapter;
use Context;
use FrontController;
use InPost\Shipping\PrestaShopContext;
use InPostShipping;
use Validate;
class AssetsManager
{
const GEO_WIDGET_JS_URL = 'https://geowidget.easypack24.net/js/sdk-for-javascript.js';
const GEO_WIDGET_CSS_URL = 'https://geowidget.easypack24.net/css/easypack.css';
protected $module;
protected $shopContext;
protected $controller;
public function __construct(
InPostShipping $module,
PrestaShopContext $shopContext
) {
$this->module = $module;
$this->shopContext = $shopContext;
$this->controller = Context::getContext()->controller;
}
public function registerJavaScripts(array $javaScripts, array $params = [])
{
$uris = array_map([$this, 'getJavaScriptUri'], $javaScripts);
if ($this->controller instanceof FrontController && $this->shopContext->is17()) {
$params['server'] = 'remote';
foreach ($uris as $uri) {
$this->controller->registerJavascript(
$this->getMediaId($uri),
$uri,
$params
);
}
} else {
$this->controller->addJS($uris, false);
}
return $this;
}
public function registerStyleSheets(array $styleSheets, array $params = [])
{
$uris = array_map([$this, 'getStyleSheetUri'], $styleSheets);
if ($this->controller instanceof FrontController && $this->shopContext->is17()) {
$params['server'] = 'remote';
foreach ($uris as $uri) {
$this->controller->registerStylesheet(
$this->getMediaId($uri),
$uri,
$params
);
}
} else {
$this->controller->addCSS(
$uris,
'all',
null,
false
);
}
return $this;
}
protected function getStyleSheetUri($path)
{
return $this->isModuleMedia($path)
? $this->getModuleMediaUri('views/css/' . $path)
: $path;
}
protected function getJavaScriptUri($path)
{
return $this->isModuleMedia($path)
? $this->getModuleMediaUri('views/js/' . $path)
: $path;
}
protected function getModuleMediaUri($path)
{
return $this->module->getPathUri() . $path . '?version=' . $this->module->version;
}
protected function getMediaId($uri)
{
return 'inpost-' . sha1($uri);
}
protected function isModuleMedia($path)
{
return !Validate::isAbsoluteUrl($path)
&& strpos($path, _THEME_DIR_) === false;
}
}

View File

@@ -0,0 +1,72 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Adapter;
use Context;
use InPost\Shipping\PrestaShopContext;
use PrestaShopException;
use Tools;
class LinkAdapter
{
protected $shopContext;
protected $link;
public function __construct(PrestaShopContext $shopContext)
{
$this->shopContext = $shopContext;
$this->link = Context::getContext()->link;
}
/**
* Adapter for getAdminLink from the core Link class
*
* @param string $controller controller name
* @param bool $withToken include the token in the url
* @param array $sfRouteParams Symfony route parameters
* @param array $params query parameters
*
* @return string
*
* @throws PrestaShopException
*/
public function getAdminLink($controller, $withToken = true, $sfRouteParams = [], $params = [])
{
if ($this->shopContext->is17()) {
return $this->link->getAdminLink($controller, $withToken, $sfRouteParams, $params);
}
$paramsAsString = '';
foreach ($params as $key => $value) {
$paramsAsString .= "&$key=$value";
}
return Tools::getShopDomainSsl(true)
. __PS_BASE_URI__
. basename(_PS_ADMIN_DIR_) . '/'
. $this->link->getAdminLink($controller, $withToken)
. $paramsAsString;
}
}

View File

@@ -0,0 +1,68 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Adapter;
use Context;
use Currency;
use InPost\Shipping\PrestaShopContext;
use Tools;
class ToolsAdapter
{
protected $shopContext;
protected $context;
public function __construct(PrestaShopContext $shopContext)
{
$this->shopContext = $shopContext;
$this->context = Context::getContext();
}
public function displayPrice($price, $currency = null)
{
if (!isset($currency)) {
$currency = $this->context->currency;
} elseif (is_int($currency)) {
$currency = Currency::getCurrencyInstance($currency);
}
if ($this->shopContext->is176()) {
$isoCode = is_array($currency) ? $currency['iso_code'] : $currency->iso_code;
return $this->context->getCurrentLocale()->formatPrice($price, $isoCode);
}
return Tools::displayPrice($price, $currency);
}
public function hash($value)
{
if ($this->shopContext->is176()) {
return Tools::hash($value);
}
return Tools::encrypt($value);
}
}

View File

@@ -0,0 +1,139 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Adapter;
use Context;
use Exception;
use InPost\Shipping\PrestaShopContext;
use Module;
use Tools;
use Translate;
class TranslateAdapter
{
protected $shopContext;
public function __construct(PrestaShopContext $shopContext)
{
$this->shopContext = $shopContext;
}
/**
* Adapter for getting module translation for a specific locale on PS 1.6
*
* @param Module|string $module Module instance or name
* @param string $originalString string to translate
* @param string $source source of the original string
* @param string|null $iso locale or language ISO code
*
* @return string
*
* @throws Exception
*/
public function getModuleTranslation(
$module,
$originalString,
$source,
$iso = null
) {
if ($this->shopContext->is17()) {
return Translate::getModuleTranslation($module, $originalString, $source, null, false, $iso);
} elseif ($iso === null) {
return Translate::getModuleTranslation($module, $originalString, $source);
}
static $translations;
static $langCache = [];
static $translationsMerged = [];
$name = $module instanceof Module ? $module->name : $module;
if (empty($iso)) {
$iso = Context::getContext()->language->iso_code;
}
if (!isset($translationsMerged[$name][$iso])) {
$filesByPriority = [
// PrestaShop 1.5 translations
_PS_MODULE_DIR_ . $name . '/translations/' . $iso . '.php',
// PrestaShop 1.4 translations
_PS_MODULE_DIR_ . $name . '/' . $iso . '.php',
// Translations in theme
_PS_THEME_DIR_ . 'modules/' . $name . '/translations/' . $iso . '.php',
_PS_THEME_DIR_ . 'modules/' . $name . '/' . $iso . '.php',
];
foreach ($filesByPriority as $file) {
if (file_exists($file)) {
$_MODULE = null;
include $file;
if (isset($_MODULE)) {
$translations[$iso] = isset($translations[$iso])
? array_merge($translations[$iso], $_MODULE)
: $_MODULE;
}
}
}
$translationsMerged[$name][$iso] = true;
}
$string = preg_replace("/\\\*'/", "\'", $originalString);
$key = md5($string);
$cacheKey = $name . '|' . $string . '|' . $source . '|' . $iso;
if (!isset($langCache[$cacheKey])) {
if (!isset($translations[$iso])) {
return str_replace('"', '&quot;', $string);
}
$currentKey = Tools::strtolower('<{' . $name . '}' . _THEME_NAME_ . '>' . $source) . '_' . $key;
$defaultKey = Tools::strtolower('<{' . $name . '}prestashop>' . $source) . '_' . $key;
if ('controller' == Tools::substr($source, -10, 10)) {
$file = Tools::substr($source, 0, -10);
$currentKeyFile = Tools::strtolower('<{' . $name . '}' . _THEME_NAME_ . '>' . $file) . '_' . $key;
$defaultKeyFile = Tools::strtolower('<{' . $name . '}prestashop>' . $file) . '_' . $key;
}
if (isset($currentKeyFile) && !empty($translations[$iso][$currentKeyFile])) {
$ret = Tools::stripslashes($translations[$iso][$currentKeyFile]);
} elseif (isset($defaultKeyFile) && !empty($translations[$iso][$defaultKeyFile])) {
$ret = Tools::stripslashes($translations[$iso][$defaultKeyFile]);
} elseif (!empty($translations[$iso][$currentKey])) {
$ret = Tools::stripslashes($translations[$iso][$currentKey]);
} elseif (!empty($translations[$iso][$defaultKey])) {
$ret = Tools::stripslashes($translations[$iso][$defaultKey]);
} else {
$ret = Tools::stripslashes($string);
}
$langCache[$cacheKey] = htmlspecialchars($ret, ENT_COMPAT, 'UTF-8');
}
return $langCache[$cacheKey];
}
}

View File

@@ -0,0 +1,32 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,289 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Api;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Query;
use GuzzleHttp\Stream\StreamInterface;
class Request
{
/**
* Guzzle Client.
*
* @var Client
*/
protected $client;
/**
* HTTP method
*
* @var string
*/
protected $method;
/**
* URL path.
*
* @var string
*/
protected $path;
/**
* URL path parameters.
*
* @var array
*/
protected $pathParams = [];
/**
* Request options.
*
* @var array
*/
protected $options = [];
/**
* Query aggregator.
*
* @var callable
*/
protected $queryAggregator;
/**
* @param Client|null $client Guzzle Client
*/
public function __construct(Client $client = null)
{
if (is_null($client)) {
$client = new Client();
}
$this->client = $client;
}
/**
* Set the HTTP method.
*
* @param string $method
*
* @return $this
*/
public function setMethod($method)
{
$this->method = $method;
return $this;
}
/**
* Set the URL path.
*
* @param string $path
*
* @return $this
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Add Path parameter values.
* Path parameters encoded in the route URL as '{key}' will be replaced
* with the appropriate value using the given key/value pairs.
*
* @param array $pathParams
*
* @return $this
*/
public function setPathParams(array $pathParams)
{
$this->pathParams = array_merge($this->pathParams, $pathParams);
return $this;
}
/**
* Add request headers.
*
* @param array $headers
*
* @return $this
*/
public function setHeaders(array $headers)
{
$this->options['headers'] = isset($this->options['headers'])
? array_merge($this->options['headers'], $headers)
: $headers;
return $this;
}
/**
* Add URL-encoded Query parameter values.
*
* @param array $queryParams
*
* @return $this
*/
public function setQueryParams(array $queryParams)
{
$this->options['query'] = isset($this->options['query'])
? array_merge($this->options['query'], $queryParams)
: $queryParams;
return $this;
}
/**
* Set the body value.
*
* @param string|resource|StreamInterface $body
*
* @return $this
*/
public function setBody($body)
{
$this->options['body'] = $body;
return $this;
}
/**
* Add request JSON data.
*
* @param array $data
*
* @return $this
*/
public function setJson(array $data)
{
$this->options['json'] = isset($this->options['json'])
? array_merge($this->options['json'], $data)
: $data;
return $this;
}
/**
* Set additional Request options.
*
* @param array $options
*
* @return $this
*/
public function setOptions(array $options)
{
$this->options = array_merge($this->options, $options);
return $this;
}
/**
* Set query aggregator function.
*
* @param callable $aggregator
*
* @return $this
*/
public function setQueryAggregator(callable $aggregator)
{
$this->queryAggregator = $aggregator;
return $this;
}
/**
* Get the Request HTTP method.
*
* @return string
*/
public function getMethod()
{
return $this->method;
}
/**
* Get the Request URL.
*
* @return string
*/
public function getUrl()
{
$url = $this->path;
foreach ($this->pathParams as $key => $value) {
$url = str_replace("{{$key}}", $value, $url);
}
return $url;
}
/**
* Get Request options.
*
* @return array
*/
public function getOptions()
{
return $this->options;
}
/**
* Get query aggregator.
*
* @return callable|null
*/
public function getQueryAggregator()
{
return $this->queryAggregator;
}
/**
* Send the API Request.
*
* @return Response
*
* @throws RequestException
*/
public function send()
{
$request = $this->client->createRequest(
$this->getMethod(),
$this->getUrl(),
$this->getOptions()
);
if ($aggregator = $this->getQueryAggregator()) {
$request->getQuery()->setAggregator($aggregator);
}
return new Response($this->client->send($request));
}
}

View File

@@ -0,0 +1,39 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Api;
interface RequestFactoryInterface
{
/**
* Create a Request for a given endpoint.
*
* @param string $method HTTP method
* @param string $path URL path
* @param array $options request options
*
* @return Request
*/
public function createRequest($method, $path, array $options = []);
}

View File

@@ -0,0 +1,385 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Api\Resource;
use Carbon\Carbon;
use InPost\Shipping\Api\RequestFactoryInterface;
use stdClass;
abstract class ApiResource
{
/**
* Format accepted by date() used to cast datetime fields.
*
* @const string
*/
const DATE_FORMAT = 'Y-m-d\TH:i:s.uP';
/**
* Resource attributes.
*
* @var array
*/
protected $attributes = [];
/**
* Attribute cast types.
*
* @var string[]
*/
protected static $casts = [];
/**
* @param array $data attributes
*/
public function __construct(array $data = [])
{
$this->mergeAttributes($data);
}
/**
* Dynamically retrieve attributes on the resource.
*
* @param string $key
*
* @return mixed
*/
public function __get($key)
{
return $this->getAttribute($key);
}
/**
* Dynamically set attributes on the resource.
*
* @param string $key
* @param $value
*/
public function __set($key, $value)
{
$this->setAttribute($key, $value);
}
/**
* Determine if the specified key is an attribute for the resource.
*
* @param string $key
*
* @return bool
*/
public function hasAttribute($key)
{
return array_key_exists($key, $this->attributes);
}
/**
* Retrieve an attribute on the resource.
*
* @param string $key
*
* @return mixed
*/
public function getAttribute($key)
{
return isset($this->attributes[$key]) ? $this->attributes[$key] : null;
}
/**
* Set an attribute on the resource.
*
* @param string $key
* @param mixed $value
*
* @return $this
*/
public function setAttribute($key, $value)
{
if ($this->castsAttribute($key)) {
$value = $this->castAs($value, $this->getAttributeCastType($key));
}
$this->attributes[$key] = $value;
return $this;
}
/**
* Overwrite attribute values.
*
* @param array $attributes values to set
* @param bool $clear remove all previous data
*
* @return $this
*/
public function setAttributes(array $attributes, $clear = false)
{
if ($clear) {
$this->attributes = [];
}
return $this->mergeAttributes($attributes);
}
/**
* Merge attribute values into the attributes array.
*
* @param array $attributes
*
* @return $this
*/
public function mergeAttributes(array $attributes)
{
foreach ($attributes as $key => $value) {
$this->setAttribute($key, $value);
}
return $this;
}
/**
* Determine if the specified attribute should be cast.
*
* @param string $key
*
* @return bool
*/
public function castsAttribute($key)
{
return array_key_exists($key, static::$casts);
}
/**
* Get the cast type for the specified attribute.
*
* @param string $key
*
* @return string|null
*/
public function getAttributeCastType($key)
{
return isset(static::$casts[$key]) ? static::$casts[$key] : null;
}
/**
* Cast value as Carbon object (no time component).
*
* @param string|int $value
*
* @return Carbon
*/
protected function castAsDate($value)
{
return $this->castAsDateTime($value)->startOfDay();
}
/**
* Cast value as Carbon object.
*
* @param string|int $value
*
* @return Carbon
*/
protected function castAsDateTime($value)
{
if (is_int($value)) {
return Carbon::createFromTimestamp($value);
} else {
return Carbon::createFromFormat(static::DATE_FORMAT, $value);
}
}
/**
* Cast value to an ApiResource object instance.
*
* @param mixed $value
* @param string $type
*
* @return ApiResource[]|ApiResource|null
*/
protected function castAsClass($value, $type)
{
if (class_exists($type) && is_subclass_of($type, ApiResource::class)) {
$collection = true;
foreach ($value as $key => $item) {
if (!is_int($key) || !is_array($item)) {
$collection = false;
break;
}
}
if ($collection) {
return $type::castMany($value);
} else {
return $type::cast($value);
}
}
return null;
}
/**
* Get ApiResource casted attribute value.
*
* @param mixed $value
* @param string $type
*
* @return mixed
*/
protected function castAs($value, $type)
{
switch ($type) {
case 'bool':
return (bool) $value;
case 'date':
return $this->castAsDate($value);
case 'datetime':
return $this->castAsDateTime($value);
case 'float':
return (float) $value;
case 'int':
return (int) $value;
case 'string':
return (string) $value;
default:
return $this->castAsClass($value, $type);
}
}
/**
* Convert ApiResource instance to JSON string.
*
* @return string
*/
public function toJson()
{
return json_encode($this->toArray());
}
/**
* Create a new ApiResource instance from JSON.
*
* @param string $data
*
* @return static
*/
public static function fromJson($data)
{
return new static(json_decode($data, true));
}
/**
* Get id field key.
*
* @return string
*/
public static function getIdField()
{
return 'id';
}
/**
* Get id field value.
*
* @return string|int
*/
public function getId()
{
return $this->getAttribute(static::getIdField());
}
/**
* Create new ApiResource instance from raw data.
*
* @param array|stdClass $data
*
* @return static
*/
public static function cast($data)
{
return new static((array) $data);
}
/**
* Create new ApiResource instances from raw data.
*
* @param array[]|stdClass[] $data
*
* @return static[]
*/
public static function castMany(array $data)
{
return array_map('static::cast', $data);
}
/**
* Return ApiResource raw data.
*
* @return array
*/
public function toArray()
{
$array = [];
foreach ($this->attributes as $key => $value) {
if ($value instanceof Carbon) {
$value = $value->format(static::DATE_FORMAT);
} elseif (is_object($value) && method_exists($value, 'toArray')) {
$value = $value->toArray();
}
$array[$key] = $value;
}
return $array;
}
/**
* Get the request factory.
*
* @return RequestFactoryInterface
*/
abstract public function getRequestFactory();
/**
* Get class API URI path.
*
* @return string
*/
public static function getBasePath()
{
return static::BASE_PATH;
}
/**
* Get resource API URI path.
*
* @return string
*/
public static function getResourcePath()
{
return rtrim(static::BASE_PATH, '/') . '/{' . static::getIdField() . '}';
}
}

View File

@@ -0,0 +1,63 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Api\Resource\Traits;
use InPost\Shipping\Api\Resource\ApiResource;
/**
* @mixin ApiResource
*/
trait CreateTrait
{
/**
* Create an ApiResource using an array of attributes.
*
* @param array $attributes
* @param array $options
*
* @return static
*/
public static function create(array $attributes, array $options = [])
{
return static::cast($attributes)->store($options);
}
/**
* Create an ApiResource using a constructed instance.
*
* @param array $options
*
* @return $this
*/
public function store(array $options = [])
{
$response = $this->getRequestFactory()
->createRequest('POST', static::getBasePath(), $options)
->setJson($this->toArray())
->send();
return $this->mergeAttributes(is_null($attributes = $response->json()) ? [] : $attributes);
}
}

View File

@@ -0,0 +1,63 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Api\Resource\Traits;
use InPost\Shipping\Api\Resource\ApiResource;
/**
* @mixin ApiResource
*/
trait DeleteTrait
{
/**
* Delete an ApiResource by id.
*
* @param string|int $id
* @param array $options
*
* @return void
*/
public static function delete($id, array $options = [])
{
$instance = static::cast([static::getIdField() => $id]);
$instance->destroy($options);
}
/**
* Delete an ApiResource instance.
*
* @param array $options
*
* @return void
*/
public function destroy(array $options = [])
{
$this->getRequestFactory()
->createRequest('DELETE', static::getResourcePath(), $options)
->setPathParams([static::getIdField() => $this->getId()])
->send();
}
}

View File

@@ -0,0 +1,45 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Api\Resource\Traits;
use InPost\Shipping\Api\Resource\ApiResource;
/**
* @mixin ApiResource
*/
trait GetAllTrait
{
/** @return static[] */
public static function getAll(array $options = [])
{
$instance = static::cast([]);
$response = $instance->getRequestFactory()
->createRequest('GET', static::getBasePath(), $options)
->send();
return static::castMany($response->json());
}
}

View File

@@ -0,0 +1,69 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Api\Resource\Traits;
use InPost\Shipping\Api\Resource\ApiResource;
/**
* @mixin ApiResource
*/
trait GetTrait
{
/**
* Get an ApiResource by id.
*
* @param string|int $id
* @param array $options
*
* @return static
*/
public static function get($id, array $options = [])
{
$response = static::cast([])
->getRequestFactory()
->createRequest('GET', static::getResourcePath(), $options)
->setPathParams([static::getIdField() => $id])
->send();
return static::cast($response->json());
}
/**
* Refresh ApiResource state based on API data.
*
* @param array $options
*
* @return $this
*/
public function refresh(array $options = [])
{
$response = $this->getRequestFactory()
->createRequest('GET', static::getResourcePath(), $options)
->setPathParams([static::getIdField() => $this->getId()])
->send();
return $this->setAttributes($response->json(), true);
}
}

View File

@@ -0,0 +1,70 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Api\Resource\Traits;
use InPost\Shipping\Api\Resource\ApiResource;
/**
* @mixin ApiResource
*/
trait UpdateTrait
{
/**
* Update an ApiResource by id using an array of attributes.
*
* @param int|string $id
* @param array $attributes
* @param array $options
*
* @return static
*/
public static function update($id, array $attributes, array $options = [])
{
$instance = static::cast(array_merge($attributes, [
static::getIdField() => $id,
]));
return $instance->saveChanges($options);
}
/**
* Update an ApiResource using the instance attributes.
*
* @param array $options
*
* @return $this
*/
public function saveChanges(array $options = [])
{
$response = $this->getRequestFactory()
->createRequest('PUT', static::getResourcePath())
->setPathParams([static::getIdField() => $this->getId()])
->setJson($this->toArray())
->setOptions($options)
->send();
return $this->mergeAttributes(is_null($attributes = $response->json()) ? [] : $attributes);
}
}

View File

@@ -0,0 +1,32 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,32 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,72 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Api;
use GuzzleHttp\Message\ResponseInterface;
use stdClass;
class Response
{
/**
* Response from Guzzle.
*
* @var ResponseInterface
*/
protected $response;
public function __construct(ResponseInterface $response)
{
$this->response = $response;
}
/**
* Get response contents as string.
*
* @return string
*/
public function getContents()
{
$this->response->getBody()->seek(0);
return $this->response->getBody()->getContents();
}
/**
* Decode response JSON.
*
* @param bool $associative
*
* @return array|stdClass|null
*/
public function json($associative = true)
{
return json_decode($this->getContents(), $associative);
}
public function getHeader($header)
{
return $this->response->getHeader($header);
}
}

View File

@@ -0,0 +1,32 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,52 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Builder\DispatchOrder;
use InPostDispatchPointModel;
class CreateDispatchOrderPayloadBuilder
{
public function buildPayload(InPostDispatchPointModel $dispatchPoint, array $shipmentIds)
{
$payload = [
'name' => $dispatchPoint->name,
'address' => [
'street' => $dispatchPoint->street,
'building_number' => $dispatchPoint->building_number,
'post_code' => $dispatchPoint->post_code,
'city' => $dispatchPoint->city,
],
'shipments' => $shipmentIds,
];
foreach (['phone', 'email', 'office_hours'] as $field) {
if (!empty($dispatchPoint->{$field})) {
$payload[$field] = $dispatchPoint->{$field};
}
}
return $payload;
}
}

View File

@@ -0,0 +1,32 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,222 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Builder\Shipment;
use Address;
use Country;
use Currency;
use InPost\Shipping\Configuration\CarriersConfiguration;
use InPost\Shipping\Configuration\SendingConfiguration;
use InPost\Shipping\DataProvider\CarrierDataProvider;
use InPost\Shipping\DataProvider\CustomerChoiceDataProvider;
use InPost\Shipping\Helper\DefaultShipmentReferenceExtractor;
use InPost\Shipping\ShipX\Resource\SendingMethod;
use InPost\Shipping\ShipX\Resource\Service;
use Order;
class CreateShipmentPayloadBuilder
{
protected $sendingConfiguration;
protected $customerChoiceDataProvider;
protected $carriersConfiguration;
protected $carrierDataProvider;
protected $referenceExtractor;
protected $parcelPayloadBuilder;
public function __construct(
SendingConfiguration $sendingConfiguration,
CustomerChoiceDataProvider $customerChoiceDataProvider,
CarriersConfiguration $carriersConfiguration,
CarrierDataProvider $carrierDataProvider,
DefaultShipmentReferenceExtractor $referenceExtractor,
ParcelPayloadBuilder $parcelPayloadBuilder
) {
$this->sendingConfiguration = $sendingConfiguration;
$this->customerChoiceDataProvider = $customerChoiceDataProvider;
$this->carriersConfiguration = $carriersConfiguration;
$this->carrierDataProvider = $carrierDataProvider;
$this->referenceExtractor = $referenceExtractor;
$this->parcelPayloadBuilder = $parcelPayloadBuilder;
}
public function buildPayload(Order $order, array $request = [])
{
$currency = Currency::getCurrencyInstance($order->id_currency);
if (!empty($request)) {
$payload = $this->buildPayloadFromRequestData($request, $currency);
} else {
$payload = $this->buildPayloadFromOrderData($order, $currency);
}
if (!empty($payload)) {
$address = new Address($order->id_address_delivery);
$payload['receiver'] = array_merge($payload['receiver'], [
'first_name' => $address->firstname,
'last_name' => $address->lastname,
'address' => [
'line1' => $address->address1,
'line2' => $address->address2,
'city' => $address->city,
'post_code' => $address->postcode,
'country_code' => Country::getIsoById($address->id_country),
],
]);
if ($address->company) {
$payload['receiver']['company_name'] = $address->company;
}
$payload['external_customer_id'] = 'PrestaShop';
if ($sender = $this->sendingConfiguration->getSenderDetails()) {
$sender['phone'] = preg_replace('/\s+/', '', $sender['phone']);
$payload['sender'] = $sender;
}
}
return $payload;
}
protected function buildPayloadFromRequestData(array $request, Currency $currency)
{
$payload = [
'service' => $request['service'],
'receiver' => [
'email' => $request['email'],
'phone' => $request['phone'],
],
'custom_attributes' => [
'sending_method' => $request['sending_method'],
],
'parcels' => [],
];
$lockerService = in_array($request['service'], Service::LOCKER_SERVICES);
if ($request['sending_method'] === SendingMethod::POP && $lockerService) {
$payload['custom_attributes']['dropoff_point'] = $request['dropoff_pop'];
} elseif ($request['sending_method'] === SendingMethod::PARCEL_LOCKER) {
$payload['custom_attributes']['dropoff_point'] = $request['dropoff_locker'];
}
$payload['parcels'][] = $this->parcelPayloadBuilder->buildPayloadFromRequestData($request);
if ($request['service'] === Service::INPOST_LOCKER_STANDARD) {
$payload['custom_attributes']['target_point'] = $request['target_point'];
if ($request['weekend_delivery']) {
$payload['end_of_week_collection'] = true;
}
}
if ($request['reference']) {
if ($lockerService) {
$payload['reference'] = $request['reference'];
} else {
$payload['comments'] = $request['reference'];
}
}
if ($request['cod']) {
$payload['cod'] = [
'amount' => (float) str_replace(',', '.', $request['cod_amount']),
'currency' => $currency->iso_code,
];
}
if ($request['insurance']) {
$payload['insurance'] = [
'amount' => (float) str_replace(',', '.', $request['insurance_amount']),
'currency' => $currency->iso_code,
];
}
return $payload;
}
protected function buildPayloadFromOrderData(Order $order, Currency $currency)
{
if ($customerChoice = $this->customerChoiceDataProvider->getDataByCartId($order->id_cart)) {
$payload = [
'service' => $customerChoice->service,
'receiver' => [
'email' => $customerChoice->email,
'phone' => $customerChoice->phone,
],
'parcels' => [],
];
$reference = $this->referenceExtractor->getShipmentReference($order);
if (in_array($customerChoice->service, Service::LOCKER_SERVICES)) {
$payload['reference'] = $reference;
} else {
$payload['comments'] = $reference;
}
$inPostCarrier = $this->carrierDataProvider->getInPostCarrierByCarrierId($order->id_carrier);
if ($sendingMethod = $this->carriersConfiguration->getDefaultSendingMethods($customerChoice->service)) {
$payload['custom_attributes']['sending_method'] = $sendingMethod;
if ($sendingMethod === SendingMethod::POP &&
($point = $this->sendingConfiguration->getDefaultPOP()) ||
$sendingMethod === SendingMethod::PARCEL_LOCKER &&
$point = $this->sendingConfiguration->getDefaultLocker()
) {
$payload['custom_attributes']['dropoff_point'] = $point['name'];
}
}
$payload['parcels'][] = $this->parcelPayloadBuilder->buildPayloadByOrder($order, $customerChoice->service);
if (null !== $inPostCarrier && $inPostCarrier->cod) {
$payload['cod'] = [
'amount' => $order->total_paid,
'currency' => $currency->iso_code,
];
}
if ($customerChoice->service === Service::INPOST_LOCKER_STANDARD) {
$payload['custom_attributes']['target_point'] = $customerChoice->point;
if (null !== $inPostCarrier && $inPostCarrier->weekend_delivery) {
$payload['end_of_week_collection'] = true;
}
} elseif (null !== $inPostCarrier && $inPostCarrier->cod) {
$payload['insurance'] = [
'amount' => $order->total_paid,
'currency' => $currency->iso_code,
];
}
return $payload;
}
return null;
}
}

View File

@@ -0,0 +1,147 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Builder\Shipment;
use InPost\Shipping\Configuration\CarriersConfiguration;
use InPost\Shipping\DataProvider\CarrierDataProvider;
use InPost\Shipping\DataProvider\OrderDimensionsDataProvider;
use InPost\Shipping\Helper\ParcelDimensionsComparator;
use InPost\Shipping\ShipX\Resource\Service;
use Order;
class ParcelPayloadBuilder
{
protected $carriersConfiguration;
protected $carrierDataProvider;
protected $dimensionsDataProvider;
protected $dimensionsComparator;
public function __construct(
CarriersConfiguration $carriersConfiguration,
CarrierDataProvider $carrierDataProvider,
OrderDimensionsDataProvider $dimensionsDataProvider,
ParcelDimensionsComparator $dimensionsComparator
) {
$this->carriersConfiguration = $carriersConfiguration;
$this->carrierDataProvider = $carrierDataProvider;
$this->dimensionsDataProvider = $dimensionsDataProvider;
$this->dimensionsComparator = $dimensionsComparator;
}
public function buildPayloadFromRequestData(array $request)
{
if ($request['use_template']) {
return [
'template' => $request['template'],
];
} else {
return [
'dimensions' => array_map(function ($dimension) {
return (float) str_replace(',', '.', $dimension);
}, $request['dimensions']),
'weight' => [
'amount' => (float) str_replace(',', '.', $request['weight']),
],
];
}
}
public function buildPayloadByOrder(Order $order, $service)
{
if ($this->shouldUseProductDimensions($order) &&
$parcel = $this->getParcelByProductDimensions($order, $service)
) {
return $parcel;
} elseif ($dimensions = $this->carriersConfiguration->getDefaultShipmentDimensions($service)) {
return [
'weight' => [
'amount' => $order->getTotalWeight() ?: $dimensions['weight'],
],
'dimensions' => array_filter($dimensions, function ($key) {
return $key !== 'weight';
}, ARRAY_FILTER_USE_KEY),
];
} elseif ($template = $this->carriersConfiguration->getDefaultDimensionTemplates($service)) {
return [
'template' => $template,
];
} else {
return [
'weight' => [
'amount' => $order->getTotalWeight(),
],
];
}
}
protected function getParcelByProductDimensions(Order $order, $service)
{
$template = $this->getLargestTemplateByOrder($order, $service);
$orderDimensions = $this->getDimensionsByLargestOrderProduct($order);
if (null !== $template && (
null === $orderDimensions ||
$this->dimensionsComparator->compareTemplateWithDimensions($template, $orderDimensions) >= 0
)) {
return [
'template' => $template,
];
}
return $orderDimensions;
}
protected function getLargestTemplateByOrder(Order $order, $service)
{
if (in_array($service, Service::LOCKER_SERVICES) &&
$templates = $this->dimensionsDataProvider->getProductDimensionTemplatesByOrderId($order->id)
) {
return $this->dimensionsComparator->getLargestTemplate($templates);
}
return null;
}
protected function getDimensionsByLargestOrderProduct(Order $order)
{
if ($dimensions = $this->dimensionsDataProvider->getLargestProductDimensionsByOrderId($order->id)) {
return [
'dimensions' => $dimensions,
'weight' => [
'amount' => $order->getTotalWeight(),
],
];
}
return null;
}
protected function shouldUseProductDimensions(Order $order)
{
$inPostCarrier = $this->carrierDataProvider->getInPostCarrierByCarrierId($order->id_carrier);
return null !== $inPostCarrier && $inPostCarrier->use_product_dimensions;
}
}

View File

@@ -0,0 +1,32 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,32 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,66 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Cache;
use Module;
use PrestaShop\ModuleLibCacheDirectoryProvider\Cache\CacheDirectoryProvider;
class CacheClearer
{
const CONTAINERS = [
'admin',
'front',
];
protected $module;
protected $cacheDirectory;
public function __construct(Module $module)
{
$this->module = $module;
$this->cacheDirectory = new CacheDirectoryProvider(
_PS_VERSION_,
_PS_ROOT_DIR_,
false
);
}
public function clear()
{
foreach (self::CONTAINERS as $containerName) {
$containerFilePath = sprintf(
'%s/%s%sContainer.php',
rtrim($this->cacheDirectory->getPath(), '/'),
ucfirst($this->module->name),
ucfirst($containerName)
);
if (file_exists($containerFilePath)) {
unlink($containerFilePath);
}
}
}
}

View File

@@ -0,0 +1,32 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Location: ../");
exit;

View File

@@ -0,0 +1,96 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping;
use InPost\Shipping\ChoiceProvider\ShippingServiceChoiceProvider;
use InPost\Shipping\Configuration\CarriersConfiguration;
use InPost\Shipping\ShipX\Resource\Service;
use InPost\Shipping\Traits\ErrorsTrait;
use InPost\Shipping\Validator\ShipmentDimensionsValidator;
use InPostShipping;
class CarrierConfigurationUpdater
{
use ErrorsTrait;
const TRANSLATION_SOURCE = 'CarrierConfigurationUpdater';
protected $module;
protected $carriersConfiguration;
protected $serviceChoiceProvider;
protected $dimensionsValidator;
public function __construct(
InPostShipping $module,
CarriersConfiguration $carriersConfiguration,
ShippingServiceChoiceProvider $serviceChoiceProvider,
ShipmentDimensionsValidator $dimensionsValidator
) {
$this->module = $module;
$this->carriersConfiguration = $carriersConfiguration;
$this->serviceChoiceProvider = $serviceChoiceProvider;
$this->dimensionsValidator = $dimensionsValidator;
}
public function update(array $request)
{
$this->resetErrors();
if (!in_array($service = $request['service'], Service::SERVICES)) {
$this->errors['service'] = $this->module->l('Invalid shipping service', self::TRANSLATION_SOURCE);
} else {
$sendingMethod = $request['defaultSendingMethod'];
if (!in_array($sendingMethod, $this->serviceChoiceProvider->getAvailableSendingMethods($service))) {
$this->errors['defaultSendingMethod'] = $this->module->l('This sending method is not available for the selected service', self::TRANSLATION_SOURCE);
}
if (in_array($service, Service::LOCKER_SERVICES) && $template = $request['defaultTemplate']) {
$dimensions = [];
if (!in_array($template, $this->serviceChoiceProvider->getAvailableTemplates($service))) {
$this->errors['defaultTemplate'] = $this->module->l('This template is not available for the selected service', self::TRANSLATION_SOURCE);
}
} else {
$template = null;
$dimensions = array_map(function ($dimension) {
return (float) str_replace(',', '.', $dimension);
}, json_decode($request['defaultDimensions'], true));
if (!$this->dimensionsValidator->validate($dimensions)) {
$this->errors = array_merge($this->errors, $this->dimensionsValidator->getErrors());
}
}
if (!$this->hasErrors()) {
$this->carriersConfiguration->setDefaultDimensionTemplate($service, $template);
$this->carriersConfiguration->setDefaultShipmentDimensions($service, $dimensions);
$this->carriersConfiguration->setDefaultSendingMethod($service, $sendingMethod);
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,306 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping;
use Carrier;
use Context;
use Country;
use Db;
use Exception;
use Group;
use InPost\Shipping\DataProvider\LanguageDataProvider;
use InPost\Shipping\ShipX\Resource\Service;
use InPost\Shipping\Traits\ErrorsTrait;
use InPostShipping;
use Language;
use Module;
use PrestaShopCollection;
use RangeWeight;
use TaxRulesGroup;
use Validate;
class CarrierUpdater
{
use ErrorsTrait;
const TRANSLATION_SOURCE = 'CarrierUpdater';
const TRACKING_URL = 'https://inpost.pl/sledzenie-przesylek?number=@';
protected $module;
protected $languageDataProvider;
protected $groups = [];
protected $id_country;
protected $id_zone;
protected $id_tax_rule_group;
/**
* @var Carrier
*/
protected $carrier;
protected $service;
protected $updateSettings = true;
public function __construct(
InPostShipping $module,
LanguageDataProvider $languageDataProvider
) {
$this->module = $module;
$this->languageDataProvider = $languageDataProvider;
$this->init();
}
protected function init()
{
if ($this->id_country = Country::getByIso('PL', true)) {
$this->id_zone = Country::getIdZone($this->id_country);
}
foreach (TaxRulesGroup::getAssociatedTaxRatesByIdCountry($this->id_country) as $id_tax_rule_group => $rate) {
if ((float) $rate === 23.) {
$this->id_tax_rule_group = $id_tax_rule_group;
break;
}
}
foreach (Group::getGroups(Context::getContext()->language->id) as $group) {
$this->groups[] = $group['id_group'];
}
}
public function update(
Carrier $carrier,
$service,
$cashOnDelivery,
$weekendDelivery = false,
$updateSettings = true
) {
$this->resetErrors();
if (Validate::isLoadedObject($carrier)) {
$this->carrier = $carrier->duplicateObject();
$this->carrier->copyCarrierData($carrier->id);
} else {
$this->carrier = $carrier;
}
$weekendDelivery = $weekendDelivery && $service === Service::INPOST_LOCKER_STANDARD;
$this->service = $service;
$this->updateSettings = $updateSettings;
$this->setCarrierFields($weekendDelivery);
try {
$this->carrier->save();
$this->carrier->id_reference = $this->carrier->id_reference ?: $this->carrier->id;
if ($this->updateSettings) {
$this->carrier->setGroups($this->groups);
if ($this->id_tax_rule_group) {
$this->carrier->setTaxRulesGroup($this->id_tax_rule_group);
}
$this->addRange()
->addZone();
if ($cashOnDelivery) {
$this->limitPaymentModules();
}
}
$this->copyImage($weekendDelivery);
if ($carrier->id !== $this->carrier->id) {
$carrier->deleted = true;
$carrier->update();
}
return $this->carrier;
} catch (Exception $exception) {
$this->addError($exception->getMessage());
$this->carrier->delete();
return false;
}
}
protected function setCarrierFields($weekendDelivery)
{
$this->carrier->is_module = true;
$this->carrier->external_module_name = $this->module->name;
$this->carrier->url = self::TRACKING_URL;
$this->carrier->shipping_external = $weekendDelivery;
$this->carrier->need_range = true;
if ($this->updateSettings) {
$this->carrier->active = true;
$this->carrier->is_free = false;
$this->carrier->shipping_handling = true;
$this->carrier->shipping_method = Carrier::SHIPPING_METHOD_WEIGHT;
$this->carrier->range_behavior = true;
$this->setDelay()
// ->setMaxDimensions()
->setMaxWeight();
}
return $this;
}
protected function setDelay()
{
foreach ($this->languageDataProvider->getLanguages() as $id_lang => $language) {
$this->carrier->delay[$id_lang] = $this->module->l('48 - 72h', self::TRANSLATION_SOURCE, $language['locale']);
}
return $this;
}
protected function setMaxDimensions()
{
switch ($this->service) {
case Service::INPOST_LOCKER_STANDARD:
$this->carrier->max_height = 41;
$this->carrier->max_width = 38;
$this->carrier->max_depth = 64;
break;
case Service::INPOST_COURIER_C2C:
$this->carrier->max_height = 50;
$this->carrier->max_width = 50;
$this->carrier->max_depth = 80;
break;
case Service::INPOST_COURIER_PALETTE:
$this->carrier->max_height = 120;
$this->carrier->max_width = 80;
$this->carrier->max_depth = 180;
break;
default:
$this->carrier->max_height = 350;
$this->carrier->max_width = 240;
$this->carrier->max_depth = 240;
break;
}
return $this;
}
protected function setMaxWeight()
{
switch ($this->service) {
case Service::INPOST_LOCKER_STANDARD:
case Service::INPOST_COURIER_C2C:
$this->carrier->max_weight = 25;
break;
case Service::INPOST_COURIER_STANDARD:
case Service::INPOST_COURIER_EXPRESS_1700:
$this->carrier->max_weight = 50;
break;
case Service::INPOST_COURIER_PALETTE:
$this->carrier->max_weight = 800;
break;
default:
$this->carrier->max_weight = 30;
break;
}
return $this;
}
protected function addZone()
{
foreach ($this->carrier->getZones() as $zone) {
$this->carrier->deleteZone($zone['id_zone']);
}
$this->carrier->addZone($this->id_zone);
return $this;
}
protected function addRange()
{
$ranges = (new PrestaShopCollection(RangeWeight::class))
->where('id_carrier', '=', $this->carrier->id);
/** @var RangeWeight $range */
foreach ($ranges as $range) {
$range->delete();
}
$range = new RangeWeight();
$range->id_carrier = $this->carrier->id;
$range->delimiter1 = $this->service === Service::INPOST_COURIER_PALETTE ? 50 : 0;
$range->delimiter2 = $this->carrier->max_weight;
$range->add();
return $this;
}
protected function limitPaymentModules()
{
if (($module = Module::getInstanceByName('ps_cashondelivery')) ||
($module = Module::getInstanceByName('cashondelivery'))
) {
$paymentModules = [
[
'id_reference' => (int) $this->carrier->id_reference,
'id_module' => (int) $module->id,
],
];
$db = Db::getInstance();
$db->delete('module_carrier', 'id_reference = ' . (int) $this->carrier->id_reference);
$db->insert('module_carrier', $paymentModules);
}
return $this;
}
protected function copyImage($weekendDelivery)
{
switch ($this->service) {
case Service::INPOST_LOCKER_STANDARD:
$logo = $weekendDelivery
? 'logo_weekend.png'
: 'logo_locker.png';
break;
default:
$logo = 'logo.png';
break;
}
copy(
$this->module->getLocalPath() . 'views/img/' . $logo,
_PS_SHIP_IMG_DIR_ . '/' . $this->carrier->id . '.jpg'
);
return $this;
}
}

View File

@@ -0,0 +1,130 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping;
use InPost\Shipping\DataProvider\PointDataProvider;
use InPost\Shipping\Traits\ErrorsTrait;
use InPostCartChoiceModel;
use InPostShipping;
use Validate;
class CartChoiceUpdater
{
use ErrorsTrait;
const TRANSLATION_SOURCE = 'CartChoiceUpdater';
protected $module;
protected $pointDataProvider;
protected $weekendDelivery = false;
protected $cashOnDelivery = false;
protected $service;
/** @var InPostCartChoiceModel */
protected $cartChoice;
public function __construct(
InPostShipping $module,
PointDataProvider $pointDataProvider
) {
$this->module = $module;
$this->pointDataProvider = $pointDataProvider;
}
public function getCartChoice()
{
return $this->cartChoice;
}
public function setCartChoice(InPostCartChoiceModel $cartChoice)
{
$this->cartChoice = $cartChoice;
return $this;
}
public function setCarrierData(array $carrierData)
{
$this->weekendDelivery = $carrierData['weekendDelivery'];
$this->cashOnDelivery = $carrierData['cashOnDelivery'];
$this->service = $carrierData['service'];
return $this;
}
public function setTargetPoint($pointId)
{
if ($pointId && $point = $this->pointDataProvider->getPointData($pointId)) {
if ((!$this->weekendDelivery || $point->location_247) &&
(!$this->cashOnDelivery || $point->payment_available)
) {
$this->cartChoice->point = $point->getId();
} else {
$this->errors['locker'] = $this->module->l('Selected locker is not available for the selected delivery option.', self::TRANSLATION_SOURCE);
}
} else {
$this->errors['locker'] = $this->module->l('Please select a locker.', self::TRANSLATION_SOURCE);
}
return $this;
}
public function setEmail($email)
{
if (!Validate::isEmail($email)) {
$this->errors['email'] = $this->module->l('Provided email is invalid.', self::TRANSLATION_SOURCE);
} else {
$this->cartChoice->email = $email;
}
return $this;
}
public function setPhone($phone)
{
if (preg_match('/^[0-9]{9}$/', $phone = InPostCartChoiceModel::formatPhone($phone))) {
$this->cartChoice->phone = $phone;
} else {
$this->errors['phone'] = $this->module->l('Provided phone number is invalid - should look like XXXXXXXXX (e.g. 123456789).', self::TRANSLATION_SOURCE);
}
return $this;
}
public function saveChoice($id_cart)
{
$this->cartChoice->service = $this->service;
if (!Validate::isLoadedObject($this->cartChoice)) {
$this->cartChoice->id = $id_cart;
$this->cartChoice->add();
} else {
$this->cartChoice->update();
}
return $this;
}
}

View File

@@ -0,0 +1,52 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\ChoiceProvider;
use Carrier;
use Context;
class CarrierChoiceProvider implements ChoiceProviderInterface
{
protected $context;
public function __construct()
{
$this->context = Context::getContext();
}
public function getChoices()
{
$choices = [];
foreach (Carrier::getCarriers($this->context->language->id) as $carrier) {
$choices[$carrier['id_reference']] = [
'value' => $carrier['id_reference'],
'text' => $carrier['name'],
];
}
return $choices;
}
}

View File

@@ -0,0 +1,33 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\ChoiceProvider;
interface ChoiceProviderInterface
{
/**
* @return array
*/
public function getChoices();
}

View File

@@ -0,0 +1,57 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\ChoiceProvider;
use InPost\Shipping\ShipX\Resource\Organization\Shipment;
use InPost\Shipping\Translations\DimensionTemplateTranslator;
class DimensionTemplateChoiceProvider implements ChoiceProviderInterface
{
protected $translator;
public function __construct(DimensionTemplateTranslator $translator)
{
$this->translator = $translator;
}
public function getChoices()
{
$choices = [];
foreach ($this->getAvailableTemplates() as $template) {
$choices[] = [
'value' => $template,
'text' => $this->translator->translate($template),
];
}
return $choices;
}
protected function getAvailableTemplates()
{
return Shipment::DIMENSION_TEMPLATES;
}
}

View File

@@ -0,0 +1,68 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\ChoiceProvider;
use InPost\Shipping\Presenter\DispatchPointPresenter;
use InPostDispatchPointModel;
use PrestaShopCollection;
class DispatchPointChoiceProvider implements ChoiceProviderInterface
{
protected $presenter;
protected $dispatchPoints;
public function __construct(DispatchPointPresenter $dispatchPointPresenter)
{
$this->presenter = $dispatchPointPresenter;
}
public function getChoices()
{
$choices = [];
$this->initCollection();
/** @var InPostDispatchPointModel $dispatchPoint */
foreach ($this->dispatchPoints as $dispatchPoint) {
$choices[] = [
'value' => (int) $dispatchPoint->id,
'text' => $this->presenter->present($dispatchPoint),
];
}
return $choices;
}
protected function initCollection()
{
if (!isset($this->dispatchPoints)) {
$this->dispatchPoints = (new PrestaShopCollection(InPostDispatchPointModel::class))
->where('deleted', '=', 0);
}
return $this;
}
}

View File

@@ -0,0 +1,60 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\ChoiceProvider;
use CarrierModule;
use Module;
use PaymentModule;
use StockManagerModule;
use TaxManagerModule;
class ModuleChoiceProvider implements ChoiceProviderInterface
{
public function getChoices()
{
$choices = [];
foreach (Module::getModulesInstalled() as $module) {
if (($module = Module::getInstanceByName($module['name'])) &&
!$this->shouldSkipModule($module)
) {
$choices[] = [
'value' => $module->name,
'label' => $module->displayName,
];
}
}
return $choices;
}
protected function shouldSkipModule(Module $module)
{
return $module instanceof CarrierModule
|| $module instanceof PaymentModule
|| $module instanceof TaxManagerModule
|| $module instanceof StockManagerModule;
}
}

View File

@@ -0,0 +1,53 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\ChoiceProvider;
use Meta;
class ModulePageChoiceProvider implements ChoiceProviderInterface
{
public function getChoices()
{
$choices = [];
foreach (Meta::getPages() as $page) {
if ($this->isModulePage($page)) {
list(, $moduleName, $controller) = explode('-', $page);
$choices[$moduleName][] = [
'value' => $controller,
'label' => $controller,
];
}
}
return $choices;
}
protected function isModulePage($page)
{
return 0 === strncmp($page, 'module-', 7);
}
}

View File

@@ -0,0 +1,52 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\ChoiceProvider;
use Context;
use OrderState;
class OrderStateChoiceProvider implements ChoiceProviderInterface
{
protected $context;
public function __construct()
{
$this->context = Context::getContext();
}
public function getChoices()
{
$choices = [];
foreach (OrderState::getOrderStates($this->context->language->id) as $orderState) {
$choices[] = [
'value' => $orderState['id_order_state'],
'text' => $orderState['name'],
];
}
return $choices;
}
}

View File

@@ -0,0 +1,47 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\ChoiceProvider;
use InPost\Shipping\ShipX\Resource\Service;
use InPost\Shipping\Translations\DimensionTemplateTranslator;
class ProductTemplateChoiceProvider extends DimensionTemplateChoiceProvider
{
protected $serviceChoiceProvider;
public function __construct(
DimensionTemplateTranslator $translator,
ShippingServiceChoiceProvider $serviceChoiceProvider
) {
parent::__construct($translator);
$this->serviceChoiceProvider = $serviceChoiceProvider;
}
protected function getAvailableTemplates()
{
return $this->serviceChoiceProvider->getAvailableTemplates(Service::INPOST_LOCKER_STANDARD);
}
}

View File

@@ -0,0 +1,63 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\ChoiceProvider;
use InPost\Shipping\ShipX\Resource\Organization\Shipment;
use InPost\Shipping\ShipX\Resource\SendingMethod;
use InPost\Shipping\Translations\SendingMethodTranslator;
class SendingMethodChoiceProvider implements ChoiceProviderInterface
{
protected $translator;
public function __construct(SendingMethodTranslator $translator)
{
$this->translator = $translator;
}
public function getChoices()
{
$choices = [];
foreach (SendingMethod::SENDING_METHODS as $method) {
$choices[] = [
'value' => $method,
'text' => $this->translator->translate($method),
'unavailableTemplates' => $this->getUnavailableTemplates($method),
];
}
return $choices;
}
protected function getUnavailableTemplates($method)
{
if ($method === SendingMethod::PARCEL_LOCKER) {
return [Shipment::TEMPLATE_EXTRA_LARGE];
}
return [];
}
}

View File

@@ -0,0 +1,45 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\ChoiceProvider;
use InPost\Shipping\ShipX\Resource\Organization\Shipment;
use Tools;
class ShipmentLabelFormatChoiceProvider implements ChoiceProviderInterface
{
public function getChoices()
{
$choices = [];
foreach (Shipment::LABEL_FORMATS as $format) {
$choices[] = [
'value' => $format,
'text' => Tools::strtoupper($format),
];
}
return $choices;
}
}

View File

@@ -0,0 +1,44 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\ChoiceProvider;
use InPost\Shipping\ShipX\Resource\Organization\Shipment;
class ShipmentLabelTypeChoiceProvider implements ChoiceProviderInterface
{
public function getChoices()
{
return [
[
'value' => Shipment::TYPE_A6,
'text' => 'A6',
],
[
'value' => Shipment::TYPE_NORMAL,
'text' => 'A4',
],
];
}
}

View File

@@ -0,0 +1,61 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\ChoiceProvider;
use InPost\Shipping\Translations\FieldTranslator;
class ShipmentReferenceFieldChoiceProvider implements ChoiceProviderInterface
{
const TRANSLATION_SOURCE = 'ShipmentReferenceFieldChoiceProvider';
const ORDER_REFERENCE = 'reference';
const ORDER_ID = 'id_order';
const FIELDS = [
self::ORDER_REFERENCE,
self::ORDER_ID,
];
protected $translator;
public function __construct(FieldTranslator $translator)
{
$this->translator = $translator;
}
public function getChoices()
{
$choices = [];
foreach (self::FIELDS as $field) {
$choices[] = [
'value' => $field,
'text' => $this->translator->translate($field),
];
}
return $choices;
}
}

View File

@@ -0,0 +1,116 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\ChoiceProvider;
use InPost\Shipping\DataProvider\OrganizationDataProvider;
use InPost\Shipping\ShipX\Resource\Organization\Shipment;
use InPost\Shipping\ShipX\Resource\SendingMethod;
use InPost\Shipping\ShipX\Resource\Service;
use InPost\Shipping\Translations\ShippingServiceTranslator;
class ShippingServiceChoiceProvider implements ChoiceProviderInterface
{
protected $organizationDataProvider;
protected $translator;
protected $availableServices;
public function __construct(
OrganizationDataProvider $organizationDataProvider,
ShippingServiceTranslator $translator
) {
$this->organizationDataProvider = $organizationDataProvider;
$this->translator = $translator;
}
public function getChoices()
{
$choices = [];
foreach (Service::SERVICES as $service) {
$choices[$service] = [
'value' => $service,
'text' => $this->translator->translate($service),
'disabled' => !$this->isAvailable($service),
'availableTemplates' => $this->getAvailableTemplates($service),
'availableSendingMethods' => $this->getAvailableSendingMethods($service),
];
}
return $choices;
}
protected function isAvailable($service)
{
if (!isset($this->availableServices)) {
if ($organization = $this->organizationDataProvider->getOrganizationData()) {
$this->availableServices = array_flip($organization['services']);
} else {
$this->availableServices = [];
}
}
return isset($this->availableServices[$service]);
}
public function getAvailableTemplates($service)
{
switch ($service) {
case Service::INPOST_LOCKER_STANDARD:
return [
Shipment::TEMPLATE_SMALL,
Shipment::TEMPLATE_MEDIUM,
Shipment::TEMPLATE_LARGE,
];
case Service::INPOST_COURIER_C2C:
return [
Shipment::TEMPLATE_SMALL,
Shipment::TEMPLATE_MEDIUM,
Shipment::TEMPLATE_LARGE,
Shipment::TEMPLATE_EXTRA_LARGE,
];
default:
return [];
}
}
public function getAvailableSendingMethods($service)
{
switch ($service) {
case Service::INPOST_LOCKER_STANDARD:
case Service::INPOST_COURIER_C2C:
return SendingMethod::SENDING_METHODS;
case Service::INPOST_COURIER_LOCAL_STANDARD:
case Service::INPOST_COURIER_LOCAL_EXPRESS:
case Service::INPOST_COURIER_LOCAL_SUPER_EXPRESS:
return [SendingMethod::DISPATCH_ORDER];
default:
return [
SendingMethod::DISPATCH_ORDER,
SendingMethod::POP,
];
}
}
}

View File

@@ -0,0 +1,62 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\ChoiceProvider;
use Carbon\Carbon;
use InPost\Shipping\Translations\WeekdayTranslator;
class WeekdayChoiceProvider implements ChoiceProviderInterface
{
protected $translator;
const WEEKDAYS = [
Carbon::MONDAY,
Carbon::TUESDAY,
Carbon::WEDNESDAY,
Carbon::THURSDAY,
Carbon::FRIDAY,
Carbon::SATURDAY,
Carbon::SUNDAY,
];
public function __construct(WeekdayTranslator $translator)
{
$this->translator = $translator;
}
public function getChoices()
{
$choices = [];
foreach (self::WEEKDAYS as $weekday) {
$choices[] = [
'value' => $weekday,
'text' => $this->translator->translate($weekday),
];
}
return $choices;
}
}

View File

@@ -0,0 +1,32 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,58 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Configuration;
use Configuration;
use ReflectionClass;
abstract class AbstractConfiguration
{
protected function set($key, $value)
{
return Configuration::updateValue($key, $value);
}
protected function get($key)
{
return Configuration::get($key);
}
public function reset()
{
$result = true;
$reflection = new ReflectionClass($this);
foreach ($reflection->getConstants() as $key) {
$result &= Configuration::deleteByName($key);
}
return $result;
}
public function setDefaults()
{
return true;
}
}

View File

@@ -0,0 +1,167 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Configuration;
use Carbon\Carbon;
class CarriersConfiguration extends AbstractConfiguration
{
const WEEKEND_DELIVERY_START_DAY = 'INPOST_SHIPPING_WEEKEND_DELIVERY_START_DAY';
const WEEKEND_DELIVERY_START_HOUR = 'INPOST_SHIPPING_WEEKEND_DELIVERY_START_HOUR';
const WEEKEND_DELIVERY_END_DAY = 'INPOST_SHIPPING_WEEKEND_DELIVERY_END_DAY';
const WEEKEND_DELIVERY_END_HOUR = 'INPOST_SHIPPING_WEEKEND_DELIVERY_END_HOUR';
const SERVICE_DEFAULT_SHIPMENT_DIMENSIONS = 'INPOST_SHIPPING_SERVICE_DEFAULT_SHIPMENT_DIMENSIONS';
const SERVICE_DEFAULT_DIMENSION_TEMPLATES = 'INPOST_SHIPPING_SERVICE_DEFAULT_DIMENSION_TEMPLATES';
const SERVICE_DEFAULT_SENDING_METHODS = 'INPOST_SHIPPING_SERVICE_DEFAULT_SENDING_METHODS';
protected $defaultDimensions;
protected $defaultTemplates;
protected $defaultSendingMethods;
public function getWeekendDeliveryStartDay()
{
return (int) $this->get(self::WEEKEND_DELIVERY_START_DAY);
}
public function setWeekendDeliveryStartDay($day)
{
return $this->set(self::WEEKEND_DELIVERY_START_DAY, (int) $day);
}
public function getWeekendDeliveryStartHour()
{
return (string) $this->get(self::WEEKEND_DELIVERY_START_HOUR);
}
public function setWeekendDeliveryStartHour($hour)
{
return $this->set(self::WEEKEND_DELIVERY_START_HOUR, $hour);
}
public function getWeekendDeliveryEndDay()
{
return (int) $this->get(self::WEEKEND_DELIVERY_END_DAY);
}
public function setWeekendDeliveryEndDay($day)
{
return $this->set(self::WEEKEND_DELIVERY_END_DAY, (int) $day);
}
public function getWeekendDeliveryEndHour()
{
return (string) $this->get(self::WEEKEND_DELIVERY_END_HOUR);
}
public function setWeekendDeliveryEndHour($hour)
{
return $this->set(self::WEEKEND_DELIVERY_END_HOUR, $hour);
}
public function getDefaultShipmentDimensions($service = null)
{
if (!isset($this->defaultDimensions)) {
$this->defaultDimensions = json_decode($this->get(self::SERVICE_DEFAULT_SHIPMENT_DIMENSIONS), true) ?: [];
}
return $service
? (isset($this->defaultDimensions[$service]) ? $this->defaultDimensions[$service] : null)
: $this->defaultDimensions;
}
public function setDefaultShipmentDimensions($service, array $dimensions)
{
$this->defaultDimensions = $this->updateServiceDefaults(
$this->getDefaultShipmentDimensions(),
$service,
$dimensions
);
return $this->set(self::SERVICE_DEFAULT_SHIPMENT_DIMENSIONS, json_encode($this->defaultDimensions));
}
public function getDefaultDimensionTemplates($service = null)
{
if (!isset($this->defaultTemplates)) {
$this->defaultTemplates = json_decode($this->get(self::SERVICE_DEFAULT_DIMENSION_TEMPLATES), true) ?: [];
}
return $service
? (isset($this->defaultTemplates[$service]) ? $this->defaultTemplates[$service] : null)
: $this->defaultTemplates;
}
public function setDefaultDimensionTemplate($service, $template)
{
$this->defaultTemplates = $this->updateServiceDefaults(
$this->getDefaultDimensionTemplates(),
$service,
$template
);
return $this->set(self::SERVICE_DEFAULT_DIMENSION_TEMPLATES, json_encode($this->defaultTemplates));
}
public function getDefaultSendingMethods($service = null)
{
if (!isset($this->defaultSendingMethods)) {
$this->defaultSendingMethods = json_decode($this->get(self::SERVICE_DEFAULT_SENDING_METHODS), true) ?: [];
}
return $service
? (isset($this->defaultSendingMethods[$service]) ? $this->defaultSendingMethods[$service] : null)
: $this->defaultSendingMethods;
}
public function setDefaultSendingMethod($service, $sendingMethod)
{
$this->defaultSendingMethods = $this->updateServiceDefaults(
$this->getDefaultSendingMethods(),
$service,
$sendingMethod
);
return $this->set(self::SERVICE_DEFAULT_SENDING_METHODS, json_encode($this->defaultSendingMethods));
}
public function setDefaults()
{
return $this->setWeekendDeliveryStartDay(Carbon::THURSDAY)
&& $this->setWeekendDeliveryStartHour('16:00:00')
&& $this->setWeekendDeliveryEndDay(Carbon::SATURDAY)
&& $this->setWeekendDeliveryEndHour('10:00:00');
}
private function updateServiceDefaults(array $defaults, $service, $newValue)
{
if (!empty($newValue)) {
$defaults[$service] = $newValue;
} else {
unset($defaults[$service]);
}
return $defaults;
}
}

View File

@@ -0,0 +1,63 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Configuration;
class CheckoutConfiguration extends AbstractConfiguration
{
const USING_CUSTOM_CHECKOUT_MODULE = 'INPOST_SHIPPING_USING_CUSTOM_CHECKOUT_MODULE';
const CUSTOM_CHECKOUT_CONTROLLERS = 'INPOST_SHIPPING_CUSTOM_CHECKOUT_CONTROLLERS';
protected $customCheckoutControllers;
public function isUsingCustomCheckoutModule()
{
return (bool) $this->get(self::USING_CUSTOM_CHECKOUT_MODULE);
}
public function setUsingCustomCheckoutModule($usingCustomCheckout)
{
return $this->set(self::USING_CUSTOM_CHECKOUT_MODULE, (bool) $usingCustomCheckout);
}
public function getCustomCheckoutControllers()
{
if (!isset($this->customCheckoutControllers)) {
$this->customCheckoutControllers = json_decode($this->get(self::CUSTOM_CHECKOUT_CONTROLLERS), true) ?: [];
}
return $this->customCheckoutControllers;
}
public function setCustomCheckoutControllers(array $controllers)
{
if ($this->set(self::CUSTOM_CHECKOUT_CONTROLLERS, json_encode($controllers))) {
$this->customCheckoutControllers = $controllers;
return true;
}
return false;
}
}

View File

@@ -0,0 +1,84 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Configuration;
class OrdersConfiguration extends AbstractConfiguration
{
const ORDER_CONF_DISPLAY_LOCKER = 'INPOST_SHIPPING_ORDER_CONF_DISPLAY_LOCKER';
const CHANGE_OS_SHIPMENT_LABEL_PRINTED = 'INPOST_SHIPPING_CHANGE_OS_SHIPMENT_LABEL_PRINTED';
const SHIPMENT_LABEL_PRINTED_OS_ID = 'INPOST_SHIPPING_SHIPMENT_LABEL_PRINTED_OS_ID';
const CHANGE_OS_SHIPMENT_DELIVERED = 'INPOST_SHIPPING_CHANGE_OS_SHIPMENT_DELIVERED';
const SHIPMENT_DELIVERED_OS_ID = 'INPOST_SHIPPING_SHIPMENT_DELIVERED_OS_ID';
public function shouldDisplayOrderConfirmationLocker()
{
return (bool) $this->get(self::ORDER_CONF_DISPLAY_LOCKER);
}
public function setDisplayOrderConfirmationLocker($display)
{
return $this->set(self::ORDER_CONF_DISPLAY_LOCKER, (bool) $display);
}
public function shouldChangeOrderStateOnShipmentLabelPrinted()
{
return (bool) $this->get(self::CHANGE_OS_SHIPMENT_LABEL_PRINTED);
}
public function setChangeOrderStateOnShipmentLabelPrinted($change)
{
return $this->set(self::CHANGE_OS_SHIPMENT_LABEL_PRINTED, (bool) $change);
}
public function getShipmentLabelPrintedOrderStateId()
{
return (int) $this->get(self::SHIPMENT_LABEL_PRINTED_OS_ID);
}
public function setShipmentLabelPrintedOrderStateId($orderStateId)
{
return $this->set(self::SHIPMENT_LABEL_PRINTED_OS_ID, (int) $orderStateId);
}
public function shouldChangeOrderStateOnShipmentDelivered()
{
return (bool) $this->get(self::CHANGE_OS_SHIPMENT_DELIVERED);
}
public function setChangeOrderStateOnShipmentDelivered($change)
{
return $this->set(self::CHANGE_OS_SHIPMENT_DELIVERED, (bool) $change);
}
public function getShipmentDeliveredOrderStateId()
{
return (int) $this->get(self::SHIPMENT_DELIVERED_OS_ID);
}
public function setShipmentDeliveredOrderStateId($orderStateId)
{
return $this->set(self::SHIPMENT_DELIVERED_OS_ID, (int) $orderStateId);
}
}

View File

@@ -0,0 +1,108 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Configuration;
use InPost\Shipping\ChoiceProvider\ShipmentReferenceFieldChoiceProvider;
class SendingConfiguration extends AbstractConfiguration
{
const SENDER_DETAILS = 'INPOST_SHIPPING_SENDER_DETAILS';
const DEFAULT_SENDING_METHOD = 'INPOST_SHIPPING_DEFAULT_SENDING_METHOD';
const DEFAULT_LOCKER = 'INPOST_SHIPPING_DEFAULT_LOCKER';
const DEFAULT_POP = 'INPOST_SHIPPING_DEFAULT_POP';
const DEFAULT_DISPATCH_POINT_ID = 'INPOST_SHIPPING_DEFAULT_DISPATCH_POINT';
const DEFAULT_SHIPMENT_REFERENCE_FIELD = 'INPOST_SHIPPING_DEFAULT_SHIPMENT_REFERENCE_FIELD';
public function getSenderDetails()
{
return json_decode($this->get(self::SENDER_DETAILS), true);
}
public function setSenderDetails(array $senderDetails)
{
$senderDetails = $senderDetails ? json_encode($senderDetails) : false;
return $this->set(self::SENDER_DETAILS, $senderDetails);
}
public function getDefaultSendingMethod()
{
return (string) $this->get(self::DEFAULT_SENDING_METHOD);
}
public function setDefaultSendingMethod($sendingMethod)
{
return $this->set(self::DEFAULT_SENDING_METHOD, $sendingMethod);
}
public function getDefaultLocker()
{
return json_decode($this->get(self::DEFAULT_LOCKER), true);
}
public function setDefaultLocker($locker)
{
$locker = $locker ? json_encode($locker) : false;
return $this->set(self::DEFAULT_LOCKER, $locker);
}
public function getDefaultPOP()
{
return json_decode($this->get(self::DEFAULT_POP), true);
}
public function setDefaultPOP($pop)
{
$pop = $pop ? json_encode($pop) : false;
return $this->set(self::DEFAULT_POP, $pop);
}
public function getDefaultDispatchPointId()
{
return (int) $this->get(self::DEFAULT_DISPATCH_POINT_ID);
}
public function setDefaultDispatchPointId($dispatchPointId)
{
return $this->set(self::DEFAULT_DISPATCH_POINT_ID, (int) $dispatchPointId);
}
public function getDefaultShipmentReferenceField()
{
return (string) $this->get(self::DEFAULT_SHIPMENT_REFERENCE_FIELD);
}
public function setDefaultShipmentReferenceField($field)
{
return $this->set(self::DEFAULT_SHIPMENT_REFERENCE_FIELD, $field);
}
public function setDefaults()
{
return $this->setDefaultShipmentReferenceField(ShipmentReferenceFieldChoiceProvider::ORDER_REFERENCE);
}
}

View File

@@ -0,0 +1,143 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Configuration;
class ShipXConfiguration extends AbstractConfiguration
{
const API_TOKEN = 'INPOST_SHIPPING_API_TOKEN';
const ORGANIZATION_ID = 'INPOST_SHIPPING_ORGANIZATION_ID';
const SANDBOX_MODE_ENABLED = 'INPOST_SHIPPING_SANDBOX_MODE_ENABLED';
const SANDBOX_API_TOKEN = 'INPOST_SHIPPING_SANDBOX_API_TOKEN';
const SANDBOX_ORGANIZATION_ID = 'INPOST_SHIPPING_SANDBOX_ORGANIZATION_ID';
protected $useSandbox;
protected $apiToken;
protected $organizationId;
public function getProductionApiToken()
{
return (string) $this->get(self::API_TOKEN);
}
public function setProductionApiToken($token)
{
return $this->set(self::API_TOKEN, $token);
}
public function getProductionOrganizationId()
{
return (int) $this->get(self::ORGANIZATION_ID);
}
public function setProductionOrganizationId($organizationId)
{
return $this->set(self::ORGANIZATION_ID, (int) $organizationId);
}
public function isSandboxModeEnabled()
{
return (bool) $this->get(self::SANDBOX_MODE_ENABLED);
}
public function setSandboxModeEnabled($enabled)
{
return $this->set(self::SANDBOX_MODE_ENABLED, (bool) $enabled);
}
public function getSandboxApiToken()
{
return (string) $this->get(self::SANDBOX_API_TOKEN);
}
public function setSandboxApiToken($token)
{
return $this->set(self::SANDBOX_API_TOKEN, $token);
}
public function getSandboxOrganizationId()
{
return (int) $this->get(self::SANDBOX_ORGANIZATION_ID);
}
public function setSandboxOrganizationId($organizationId)
{
return $this->set(self::SANDBOX_ORGANIZATION_ID, (int) $organizationId);
}
public function useSandboxMode()
{
return isset($this->useSandbox)
? $this->useSandbox
: $this->isSandboxModeEnabled();
}
public function setSandboxMode($enabled)
{
$this->useSandbox = null !== $enabled ? (bool) $enabled : null;
return $this;
}
public function getApiToken()
{
if (isset($this->apiToken)) {
return $this->apiToken;
}
return $this->useSandboxMode()
? $this->getSandboxApiToken()
: $this->getProductionApiToken();
}
public function setApiToken($token)
{
$this->apiToken = null !== $token ? (string) $token : null;
return $this;
}
public function getOrganizationId()
{
if (isset($this->organizationId)) {
return $this->organizationId;
}
return $this->useSandboxMode()
? $this->getSandboxOrganizationId()
: $this->getProductionOrganizationId();
}
public function setOrganizationId($organizationId)
{
$this->organizationId = null !== $organizationId ? (int) $organizationId : null;
return $this;
}
public function hasConfiguration()
{
return $this->getOrganizationId() && $this->getApiToken();
}
}

View File

@@ -0,0 +1,54 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Configuration;
class SzybkieZwrotyConfiguration extends AbstractConfiguration
{
const STORE_NAME = 'INPOST_SHIPPING_SZYBKIE_ZWROTY_STORE_NAME';
public function getStoreName()
{
return (string) $this->get(self::STORE_NAME);
}
public function setStoreName($storeName)
{
return $this->set(self::STORE_NAME, $storeName);
}
public function getUrlTemplate()
{
return 'https://szybkiezwroty.pl/%s#navigate-buttons';
}
public function getOrderReturnFormUrl($noStore = false)
{
if (($storeName = $this->getStoreName()) || $noStore) {
return sprintf($this->getUrlTemplate(), $storeName);
}
return '';
}
}

View File

@@ -0,0 +1,32 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,50 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\DataProvider;
use Carrier;
use InPostCarrierModel;
use Validate;
class CarrierDataProvider
{
protected $carriers = [];
/** @return InPostCarrierModel|null */
public function getInPostCarrierByCarrierId($id_carrier)
{
if (!isset($this->carriers[$id_carrier])) {
$carrier = new Carrier($id_carrier);
if (Validate::isLoadedObject($inPostCarrier = new InPostCarrierModel($carrier->id_reference))) {
$this->carriers[$id_carrier] = $inPostCarrier;
} else {
$this->carriers[$id_carrier] = false;
}
}
return $this->carriers[$id_carrier] ?: null;
}
}

View File

@@ -0,0 +1,47 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\DataProvider;
use InPostCartChoiceModel;
use Validate;
class CustomerChoiceDataProvider
{
protected $data = [];
/** @return InPostCartChoiceModel|null */
public function getDataByCartId($id_cart)
{
if (!isset($this->data[$id_cart])) {
if (Validate::isLoadedObject($cartChoice = new InPostCartChoiceModel($id_cart))) {
$this->data[$id_cart] = $cartChoice;
} else {
$this->data[$id_cart] = false;
}
}
return $this->data[$id_cart] ?: null;
}
}

View File

@@ -0,0 +1,68 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\DataProvider;
use InPost\Shipping\PrestaShopContext;
use Language;
class LanguageDataProvider
{
protected $shopContext;
protected $languages;
protected $locales;
public function __construct(PrestaShopContext $shopContext)
{
$this->shopContext = $shopContext;
}
public function getLanguages()
{
$this->initLanguages();
return $this->languages;
}
public function getLocaleById($id_lang)
{
$this->initLanguages();
return isset($this->languages[$id_lang]) ? $this->languages[$id_lang]['locale'] : null;
}
protected function initLanguages()
{
if (!isset($this->languages)) {
foreach (Language::getLanguages(false) as $language) {
if (!$this->shopContext->is17()) {
$language['locale'] = $language['iso_code'];
}
$this->languages[$language['id_lang']] = $language;
}
}
}
}

View File

@@ -0,0 +1,50 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\DataProvider;
use Db;
use DbQuery;
use InPostProductTemplateModel;
class OrderDimensionsDataProvider
{
public function getProductDimensionTemplatesByOrderId($id_order)
{
return InPostProductTemplateModel::getTemplatesByOrderId($id_order);
}
public function getLargestProductDimensionsByOrderId($id_order)
{
$query = (new DbQuery())
->select('(10 * p.depth) AS length, (10 * p.width) AS width, (10 * p.height) AS height')
->from('order_detail', 'od')
->innerJoin('product', 'p', 'p.id_product = od.product_id')
->where('od.id_order = ' . (int) $id_order)
->where('p.depth > 0 OR p.width > 0 OR p.height > 0')
->orderBy('(p.depth + p.width + p.height) DESC');
return Db::getInstance()->getRow($query) ?: null;
}
}

View File

@@ -0,0 +1,61 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\DataProvider;
use InPost\Shipping\Configuration\ShipXConfiguration;
use InPost\Shipping\Presenter\ShipmentPresenter;
use InPostShipmentModel;
use PrestaShopCollection;
class OrderShipmentsDataProvider
{
protected $shipXConfiguration;
protected $shipmentPresenter;
public function __construct(
ShipXConfiguration $shipXConfiguration,
ShipmentPresenter $shipmentPresenter
) {
$this->shipXConfiguration = $shipXConfiguration;
$this->shipmentPresenter = $shipmentPresenter;
}
public function getOrderShipments($id_order)
{
$result = [];
$shipments = (new PrestaShopCollection(InPostShipmentModel::class))
->where('sandbox', '=', $this->shipXConfiguration->useSandboxMode())
->where('id_order', '=', $id_order)
->where('organization_id', '=', $this->shipXConfiguration->getOrganizationId());
/** @var InPostShipmentModel $shipment */
foreach ($shipments as $shipment) {
$result[] = $this->shipmentPresenter->present($shipment);
}
return $result;
}
}

View File

@@ -0,0 +1,69 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\DataProvider;
use Exception;
use InPost\Shipping\Configuration\ShipXConfiguration;
use InPost\Shipping\ShipX\Exception\ResourceNotFoundException;
use InPost\Shipping\ShipX\Exception\TokenInvalidException;
use InPost\Shipping\ShipX\Resource\Organization;
use InPost\Shipping\Traits\ErrorsTrait;
class OrganizationDataProvider
{
use ErrorsTrait;
protected $shipXConfiguration;
protected $organization;
public function __construct(ShipXConfiguration $shipXConfiguration)
{
$this->shipXConfiguration = $shipXConfiguration;
}
public function getOrganizationData()
{
if (!isset($this->organization)) {
$this->organization = false;
if ($organizationId = $this->shipXConfiguration->getOrganizationId()) {
try {
$this->organization = Organization::get($organizationId)->toArray();
} catch (Exception $exception) {
if ($exception instanceof TokenInvalidException ||
$exception instanceof ResourceNotFoundException
) {
$this->errors['authorization'] = $exception->getMessage();
} else {
$this->errors['exception'] = $exception->getMessage();
}
}
}
}
return $this->organization;
}
}

View File

@@ -0,0 +1,53 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\DataProvider;
use Exception;
use InPost\Shipping\ShipX\Exception\ResourceNotFoundException;
use InPost\Shipping\ShipX\Resource\Point;
use InPost\Shipping\Traits\ErrorsTrait;
class PointDataProvider
{
use ErrorsTrait;
/** @var Point[] */
protected $points = [];
public function getPointData($id)
{
if (!isset($this->points[$id])) {
try {
$this->points[$id] = Point::get($id);
} catch (ResourceNotFoundException $exception) {
$this->points[$id] = false;
} catch (Exception $exception) {
$this->addError($exception->getMessage());
}
}
return isset($this->points[$id]) ? $this->points[$id] : null;
}
}

View File

@@ -0,0 +1,82 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\DataProvider;
use InPost\Shipping\ShipX\Resource\Organization\Shipment;
class TemplateDimensionsDataProvider
{
public function getDimensions($template)
{
switch ($template) {
case Shipment::TEMPLATE_SMALL:
return [
'dimensions' => [
'length' => 80.,
'width' => 380.,
'height' => 640.,
],
'weight' => [
'amount' => 25.,
],
];
case Shipment::TEMPLATE_MEDIUM:
return [
'dimensions' => [
'length' => 190.,
'width' => 380.,
'height' => 640.,
],
'weight' => [
'amount' => 25.,
],
];
case Shipment::TEMPLATE_LARGE:
return [
'dimensions' => [
'length' => 410.,
'width' => 380.,
'height' => 640.,
],
'weight' => [
'amount' => 25.,
],
];
case Shipment::TEMPLATE_EXTRA_LARGE:
return [
'dimensions' => [
'length' => 500.,
'width' => 500.,
'height' => 800.,
],
'weight' => [
'amount' => 25.,
],
];
default:
return null;
}
}
}

View File

@@ -0,0 +1,32 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,31 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Exception;
use Exception;
class InvalidActionException extends Exception
{
}

View File

@@ -0,0 +1,32 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Location: ../");
exit;

View File

@@ -0,0 +1,98 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Handler;
use Context;
use InPost\Shipping\Adapter\ToolsAdapter;
use InPost\Shipping\Exception\InvalidActionException;
use InPost\Shipping\Handler\Shipment\UpdateShipmentStatusHandler;
use InPostShipping;
class CronJobsHandler
{
const ACTION_UPDATE_SHIPMENT_STATUS = 'updateShipmentStatus';
const ACTIONS = [
self::ACTION_UPDATE_SHIPMENT_STATUS,
];
protected $module;
protected $context;
protected $tools;
protected $updateShipmentStatusHandler;
public function __construct(
InPostShipping $module,
ToolsAdapter $tools,
UpdateShipmentStatusHandler $updateShipmentStatusHandler
) {
$this->module = $module;
$this->context = Context::getContext();
$this->tools = $tools;
$this->updateShipmentStatusHandler = $updateShipmentStatusHandler;
}
public function handle($action)
{
set_time_limit(0);
switch ($action) {
case self::ACTION_UPDATE_SHIPMENT_STATUS:
$this->updateShipmentStatusHandler->handle();
break;
default:
throw new InvalidActionException();
}
}
public function getAvailableActionsUrls()
{
$urls = [];
foreach (self::ACTIONS as $action) {
$urls[$action] = $this->getActionUrl($action);
}
return $urls;
}
public function checkToken($token)
{
return $token === $this->getToken();
}
protected function getActionUrl($action)
{
return $this->context->link->getModuleLink($this->module->name, 'cron', [
'action' => $action,
'token' => $this->getToken(),
]);
}
protected function getToken()
{
return $this->tools->hash($this->module->name . '_cron');
}
}

View File

@@ -0,0 +1,137 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Handler\DispatchOrder;
use Exception;
use InPost\Shipping\Builder\DispatchOrder\CreateDispatchOrderPayloadBuilder;
use InPost\Shipping\ShipX\Exception\ValidationFailedException;
use InPost\Shipping\ShipX\Resource\Organization\DispatchOrder;
use InPost\Shipping\Traits\ErrorsTrait;
use InPost\Shipping\Translations\ValidationErrorTranslator;
use InPostDispatchOrderModel;
use InPostDispatchPointModel;
use InPostShipping;
use Validate;
class CreateDispatchOrderHandler
{
use ErrorsTrait;
const TRANSLATION_SOURCE = 'CreateDispatchOrderHandler';
const RETRY_NUMBER = 2;
protected $module;
protected $errorTranslator;
protected $payloadBuilder;
public function __construct(
InPostShipping $module,
ValidationErrorTranslator $errorTranslator,
CreateDispatchOrderPayloadBuilder $dispatchOrderPayloadBuilder
) {
$this->module = $module;
$this->errorTranslator = $errorTranslator;
$this->payloadBuilder = $dispatchOrderPayloadBuilder;
}
public function handle(array $shipmentIds, $id_dispatch_point)
{
$this->resetErrors();
try {
$dispatchPoint = new InPostDispatchPointModel($id_dispatch_point);
if (Validate::isLoadedObject($dispatchPoint)) {
$payload = $this->payloadBuilder->buildPayload($dispatchPoint, $shipmentIds);
$this->waitForDispatchOrderNumber(
$dispatchOrder = DispatchOrder::create($payload)
);
return $this->saveDispatchOrder($dispatchOrder, $dispatchPoint);
} else {
$this->addError(
$this->module->l('Invalid dispatch point ID', self::TRANSLATION_SOURCE)
);
}
} catch (ValidationFailedException $exception) {
if ($errors = $exception->getValidationErrors()) {
$this->translateErrors($errors);
} else {
$this->addError($exception->getDetails());
}
} catch (Exception $exception) {
$this->addError($exception->getMessage());
}
return false;
}
protected function saveDispatchOrder(
DispatchOrder $dispatchOrder,
InPostDispatchPointModel $dispatchPoint
) {
$dispatchOrderModel = new InPostDispatchOrderModel();
$dispatchOrderModel->shipx_dispatch_order_id = $dispatchOrder->getId();
$dispatchOrderModel->id_dispatch_point = $dispatchPoint->id;
$dispatchOrderModel->status = $dispatchOrder->status;
if ($number = $dispatchOrder->external_id) {
$dispatchOrderModel->number = $number;
}
if ($price = $dispatchOrder->price) {
$dispatchOrderModel->price = $price;
}
if ($dispatchOrderModel->add()) {
return $dispatchOrderModel;
}
return false;
}
protected function waitForDispatchOrderNumber(DispatchOrder $dispatchOrder)
{
$i = 0;
$number = $dispatchOrder->external_id;
while (empty($number) && $i++ < self::RETRY_NUMBER) {
sleep(1);
$dispatchOrder->refresh();
$number = $dispatchOrder->external_id;
}
}
protected function translateErrors($errors)
{
foreach ($errors as $fieldName => $values) {
foreach ($values as $error) {
$this->addError($this->errorTranslator->translate($error, $fieldName));
}
}
}
}

View File

@@ -0,0 +1,72 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Handler\DispatchOrder;
use InPost\Shipping\Configuration\ShipXConfiguration;
use InPost\Shipping\ShipX\Resource\Organization\DispatchOrder;
use InPostDispatchOrderModel;
class UpdateDispatchOrderHandler
{
protected $shipXConfiguration;
public function __construct(ShipXConfiguration $shipXConfiguration)
{
$this->shipXConfiguration = $shipXConfiguration;
}
public function handle(array $ids = [])
{
$collection = InPostDispatchOrderModel::getDispatchOrders(
$this->shipXConfiguration->useSandboxMode(),
$this->shipXConfiguration->getOrganizationId(),
$ids
);
if (count($collection)) {
$dispatchOrderIds = [];
$collectionKeyIndex = [];
foreach ($collection as $key => $dispatchOrderModel) {
$dispatchOrderIds[] = $dispatchOrderModel->shipx_dispatch_order_id;
$collectionKeyIndex[$dispatchOrderModel->shipx_dispatch_order_id] = $key;
}
/** @var DispatchOrder $dispatchOrder */
foreach (DispatchOrder::getCollection(['id' => $dispatchOrderIds]) as $dispatchOrder) {
$dispatchOrderModel = $collection[$collectionKeyIndex[$dispatchOrder->getId()]];
if ($dispatchOrderModel->number != $dispatchOrder->external_id ||
$dispatchOrderModel->status != $dispatchOrder->status
) {
if ($number = $dispatchOrder->external_id) {
$dispatchOrderModel->number = $number;
}
$dispatchOrderModel->status = $dispatchOrder->status;
$dispatchOrderModel->update();
}
}
}
}
}

View File

@@ -0,0 +1,32 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,88 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Handler;
use InPost\Shipping\ChoiceProvider\ShippingServiceChoiceProvider;
use InPost\Shipping\ShipX\Resource\Service;
use InPost\Shipping\Traits\ErrorsTrait;
use InPostProductTemplateModel;
use InPostShipping;
use Product;
use Validate;
class ProductUpdateHandler
{
use ErrorsTrait;
const TRANSLATION_SOURCE = 'ProductUpdateHandler';
protected $module;
protected $serviceChoiceProvider;
public function __construct(
InPostShipping $module,
ShippingServiceChoiceProvider $serviceChoiceProvider
) {
$this->module = $module;
$this->serviceChoiceProvider = $serviceChoiceProvider;
}
public function update(Product $product, $template)
{
$this->resetErrors();
$productTemplate = new InPostProductTemplateModel($product->id);
if ($template !== null) {
if (!in_array($template, $this->serviceChoiceProvider->getAvailableTemplates(Service::INPOST_LOCKER_STANDARD))) {
$this->addError(
$this->module->l('Selected InPost shipment dimension template is not valid', self::TRANSLATION_SOURCE)
);
} else {
$productTemplate->template = $template;
if (Validate::isLoadedObject($productTemplate)) {
if (!$productTemplate->update()) {
$this->addError(
$this->module->l('Could not update default InPost shipment dimension template', self::TRANSLATION_SOURCE)
);
}
} else {
$productTemplate->id = $product->id;
if (!$productTemplate->add()) {
$this->addError(
$this->module->l('Could not update default InPost shipment dimension template', self::TRANSLATION_SOURCE)
);
}
}
}
} elseif (Validate::isLoadedObject($productTemplate) && !$productTemplate->delete()) {
$this->addError(
$this->module->l('Could not remove default InPost shipment dimension template', self::TRANSLATION_SOURCE)
);
}
return !$this->hasErrors();
}
}

View File

@@ -0,0 +1,140 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Handler\Shipment;
use Exception;
use InPost\Shipping\ShipX\Exception\ValidationFailedException;
use InPost\Shipping\ShipX\Resource\Organization\Shipment;
use InPostShipmentModel;
use Order;
use PrestaShopCollection;
class BulkCreateShipmentHandler extends CreateShipmentHandler
{
const TRANSLATION_SOURCE = 'BulkCreateShipmentHandler';
public function handle(array $request)
{
$this->resetErrors();
if (!empty($request['orderIds'])) {
$orders = (new PrestaShopCollection(Order::class))
->where('id_order', 'IN', $request['orderIds']);
if (count($orders)) {
$shipments = [];
/** @var Order $order */
foreach ($orders as $order) {
try {
if ($payload = $this->payloadBuilder->buildPayload($order)) {
$shipments[] = $this->saveShipment($order, Shipment::create($payload));
}
} catch (ValidationFailedException $exception) {
if ($errors = $exception->getValidationErrors()) {
foreach ($this->translateErrors($errors) as $error) {
$this->addOrderError($order->reference, $error);
}
} else {
$this->addError($exception->getDetails());
}
} catch (Exception $exception) {
$this->addOrderError($order->reference, $exception->getMessage());
}
}
try {
$this->waitForTransactionsData($shipments);
} catch (Exception $exception) {
$this->addError($exception->getMessage());
}
if (empty($shipments) && !$this->hasErrors()) {
$this->addError($this->module->l('None of the selected orders were placed with an InPost carrier as a delivery option', self::TRANSLATION_SOURCE));
}
return $shipments;
} else {
$this->addError($this->module->l('Invalid order IDs', self::TRANSLATION_SOURCE));
}
} else {
$this->addError($this->module->l('No orders selected', self::TRANSLATION_SOURCE));
}
return false;
}
/** @param InPostShipmentModel[] $shipments */
private function waitForTransactionsData(array $shipments)
{
$shipmentIds = [];
$remaining = [];
foreach ($shipments as $shipmentModel) {
$remaining[$shipmentModel->shipx_shipment_id] = $shipmentModel;
$shipmentIds[$shipmentModel->shipx_shipment_id] = $shipmentModel->shipx_shipment_id;
}
$i = 0;
while (!empty($remaining) && $i++ < self::REFRESH_RETRY_NUMBER) {
sleep(1);
/** @var Shipment $shipment */
foreach (Shipment::getCollection(['id' => $shipmentIds]) as $shipment) {
$transactions = $shipment->transactions;
if (!empty($transactions)) {
$shipmentModel = $remaining[$shipment->id];
$transaction = current($transactions);
if ($transaction['status'] !== 'success') {
$this->addOrderError(
$shipmentModel->getOrder()->reference,
$this->getTransactionError($transaction)
);
} else {
$shipmentModel->status = $shipment->status;
$shipmentModel->tracking_number = $shipment->tracking_number;
$shipmentModel->update();
$shipmentModel->updateOrderTrackingNumber();
}
unset(
$remaining[$shipmentModel->shipx_shipment_id],
$shipmentIds[$shipmentModel->shipx_shipment_id]
);
}
}
}
}
protected function addOrderError($reference, $error)
{
return $this->addError(sprintf(
$this->module->l('Order "%s": %s', self::TRANSLATION_SOURCE),
$reference,
$error
));
}
}

View File

@@ -0,0 +1,222 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Handler\Shipment;
use Exception;
use InPost\Shipping\Builder\Shipment\CreateShipmentPayloadBuilder;
use InPost\Shipping\Configuration\ShipXConfiguration;
use InPost\Shipping\ShipX\Exception\ValidationFailedException;
use InPost\Shipping\ShipX\Resource\Organization\Shipment;
use InPost\Shipping\ShipX\Resource\Service;
use InPost\Shipping\Traits\ErrorsTrait;
use InPost\Shipping\Translations\ValidationErrorTranslator;
use InPostShipmentModel;
use InPostShipping;
use Order;
use Validate;
class CreateShipmentHandler
{
use ErrorsTrait;
const TRANSLATION_SOURCE = 'CreateShipmentHandler';
const REFRESH_RETRY_NUMBER = 5;
protected $module;
protected $errorTranslator;
protected $payloadBuilder;
protected $shipXConfiguration;
public function __construct(
InPostShipping $module,
ValidationErrorTranslator $errorTranslator,
CreateShipmentPayloadBuilder $payloadBuilder,
ShipXConfiguration $shipXConfiguration
) {
$this->module = $module;
$this->errorTranslator = $errorTranslator;
$this->payloadBuilder = $payloadBuilder;
$this->shipXConfiguration = $shipXConfiguration;
}
public function handle(array $request)
{
$this->resetErrors();
if (!isset($request['service'])) {
$this->addError($this->module->l('Selected shipping service is invalid or unavailable', self::TRANSLATION_SOURCE));
} elseif (!Validate::isLoadedObject($order = new Order($request['id_order']))) {
$this->addError($this->module->l('Invalid order ID', self::TRANSLATION_SOURCE));
} else {
try {
$payload = $this->payloadBuilder->buildPayload($order, $request);
$transaction = $this->waitForTransactionData($shipment = Shipment::create($payload));
if (!$transaction || $transaction['status'] !== 'success') {
$this->addError(
$this->getTransactionError($transaction)
);
}
return $this->saveShipment($order, $shipment);
} catch (ValidationFailedException $exception) {
if ($errors = $exception->getValidationErrors()) {
foreach ($this->translateErrors($errors) as $error) {
$this->addError($error);
}
} else {
$this->addError($exception->getDetails());
}
} catch (Exception $exception) {
$this->addError($exception->getMessage());
}
}
return false;
}
protected function translateErrors($errors)
{
$result = [];
foreach ($errors as $fieldName => $values) {
foreach ($values as $error) {
$result[] = $this->errorTranslator->translate($error, $fieldName);
}
}
return $result;
}
protected function saveShipment(Order $order, Shipment $shipment)
{
$shipmentModel = new InPostShipmentModel();
$service = $shipment->service;
if (Service::INPOST_LOCKER_CUSTOMER_SERVICE_POINT === $service) {
$service = Service::INPOST_LOCKER_STANDARD;
}
$shipmentModel->setOrder($order);
$shipmentModel->organization_id = $this->shipXConfiguration->getOrganizationId();
$shipmentModel->sandbox = $this->shipXConfiguration->useSandboxMode();
$shipmentModel->shipx_shipment_id = $shipment->getId();
$shipmentModel->reference = in_array($service, Service::LOCKER_SERVICES)
? $shipment->reference
: $shipment->comments;
$shipmentModel->email = $shipment->receiver['email'];
$shipmentModel->phone = $shipment->receiver['phone'];
$shipmentModel->service = $service;
$shipmentModel->tracking_number = $shipment->tracking_number;
$shipmentModel->status = $shipment->status;
if (($selected_offer = $shipment->selected_offer) && $selected_offer['rate']) {
$shipmentModel->price = $selected_offer['rate'];
}
$parcel = current($shipment->parcels);
if (isset($parcel['template']) && $parcel['template']) {
$shipmentModel->template = $parcel['template'];
} else {
$shipmentModel->dimensions = json_encode([
'length' => $parcel['dimensions']['length'],
'width' => $parcel['dimensions']['length'],
'height' => $parcel['dimensions']['height'],
'weight' => $parcel['weight']['amount'],
]);
}
$customAttributes = $shipment->custom_attributes;
if (isset($customAttributes['sending_method'])) {
$shipmentModel->sending_method = $customAttributes['sending_method'];
}
if (isset($customAttributes['dropoff_point'])) {
$shipmentModel->sending_point = $customAttributes['dropoff_point'];
}
if (isset($customAttributes['target_point'])) {
$shipmentModel->target_point = $customAttributes['target_point'];
}
$cod = $shipment->cod;
if (isset($cod['amount'])) {
$shipmentModel->cod_amount = $cod['amount'];
}
$insurance = $shipment->insurance;
if (isset($insurance['amount'])) {
$shipmentModel->insurance_amount = $insurance['amount'];
}
if ($service === Service::INPOST_LOCKER_STANDARD) {
$shipmentModel->weekend_delivery = $shipment->end_of_week_collection;
}
$shipmentModel->add();
$shipmentModel->updateOrderTrackingNumber();
return $shipmentModel;
}
private function waitForTransactionData(Shipment $shipment)
{
$i = 0;
$transactions = $shipment->transactions;
while (empty($transactions) && $i++ < self::REFRESH_RETRY_NUMBER) {
sleep(1);
$shipment->refresh();
$transactions = $shipment->transactions;
}
return $transactions ? current($transactions) : null;
}
protected function getTransactionError($transaction)
{
if (isset($transaction)) {
if ($transaction['details']) {
if ($transaction['details']['error'] === 'validation_failed') {
$details = $transaction['details']['details'];
} else {
$details = $transaction['details']['message'];
}
$message = sprintf(
$this->module->l('Message: %s', self::TRANSLATION_SOURCE),
$details
);
} else {
$message = '';
}
return sprintf(
$this->module->l('Transaction failed. %s', self::TRANSLATION_SOURCE),
$message
);
} else {
return $this->module->l('Shipment has been created, however processing data by the InPost servers takes longer than expected. Please try to refresh the shipment status later.', self::TRANSLATION_SOURCE);
}
}
}

View File

@@ -0,0 +1,106 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Handler\Shipment;
use InPost\Shipping\Configuration\OrdersConfiguration;
use InPost\Shipping\ShipX\Resource\Organization\Shipment;
use InPostShipmentModel;
use OrderState;
use Validate;
class PrintShipmentLabelHandler
{
protected $ordersConfiguration;
protected $labelPrintedOrderState;
public function __construct(OrdersConfiguration $ordersConfiguration)
{
$this->ordersConfiguration = $ordersConfiguration;
}
public function handle(InPostShipmentModel $shipmentModel, array $options = [])
{
$label = Shipment::getLabel($shipmentModel->shipx_shipment_id, $options);
$this->updateShipment($shipmentModel);
return $label;
}
/** @param InPostShipmentModel[] $shipmentModels */
public function handleMultiple(array $shipmentModels, array $options = [])
{
$shipmentIds = [];
foreach ($shipmentModels as $shipmentModel) {
$shipmentIds[] = $shipmentModel->shipx_shipment_id;
}
$labels = Shipment::getMultipleLabels($shipmentIds, $options);
foreach ($shipmentModels as $shipmentModel) {
$this->updateShipment($shipmentModel);
}
return $labels;
}
protected function updateShipment(InPostShipmentModel $shipmentModel)
{
if (!$shipmentModel->label_printed) {
$shipmentModel->label_printed = true;
$shipmentModel->update();
$this->updateOrderStatus($shipmentModel);
}
}
protected function updateOrderStatus(InPostShipmentModel $shipmentModel)
{
if ($this->ordersConfiguration->shouldChangeOrderStateOnShipmentLabelPrinted() &&
$orderState = $this->getLabelPrintedOrderState()
) {
$currentState = $shipmentModel->getOrder()->getCurrentOrderState();
if (null === $currentState || $currentState->id !== $orderState->id) {
$shipmentModel->getOrder()->setCurrentState($orderState->id);
}
}
}
protected function getLabelPrintedOrderState()
{
if (!isset($this->labelPrintedOrderState)) {
$orderStateId = $this->ordersConfiguration->getShipmentLabelPrintedOrderStateId();
if (Validate::isLoadedObject($orderState = new OrderState($orderStateId))) {
$this->labelPrintedOrderState = $orderState;
} else {
$this->labelPrintedOrderState = false;
}
}
return $this->labelPrintedOrderState ?: null;
}
}

View File

@@ -0,0 +1,118 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Handler\Shipment;
use InPost\Shipping\Configuration\OrdersConfiguration;
use InPost\Shipping\Configuration\ShipXConfiguration;
use InPost\Shipping\ShipX\Resource\Organization\Shipment;
use InPost\Shipping\ShipX\Resource\Status;
use InPostShipmentModel;
use OrderState;
use PrestaShopCollection;
use Validate;
class UpdateShipmentStatusHandler
{
protected $shipXConfiguration;
protected $ordersConfiguration;
protected $shipmentDeliveredOrderState;
public function __construct(
ShipXConfiguration $shipXConfiguration,
OrdersConfiguration $ordersConfiguration
) {
$this->shipXConfiguration = $shipXConfiguration;
$this->ordersConfiguration = $ordersConfiguration;
}
public function handle(array $ids = [])
{
$collection = (new PrestaShopCollection(InPostShipmentModel::class))
->where('status', '<>', Status::FINAL_STATUSES)
->where('sandbox', '=', $this->shipXConfiguration->useSandboxMode())
->where('organization_id', '=', $this->shipXConfiguration->getOrganizationId());
if (!empty($ids)) {
$collection->where('id_shipment', '=', $ids);
}
if (count($collection)) {
$shipmentIds = [];
$collectionKeyIndex = [];
/** @var InPostShipmentModel $shipmentModel */
foreach ($collection as $key => $shipmentModel) {
$shipmentIds[] = $shipmentModel->shipx_shipment_id;
$collectionKeyIndex[$shipmentModel->shipx_shipment_id] = $key;
}
/** @var Shipment $shipment */
foreach (Shipment::getCollection(['id' => $shipmentIds]) as $shipment) {
$shipmentModel = $collection[$collectionKeyIndex[$shipment->getId()]];
if ($shipmentModel->status != $shipment->status) {
$updateOrder = empty($shipmentModel->tracking_number);
$shipmentModel->tracking_number = $shipment->tracking_number;
$shipmentModel->status = $shipment->status;
$shipmentModel->update();
$this->updateOrderStatus($shipmentModel);
if ($updateOrder) {
$shipmentModel->updateOrderTrackingNumber();
}
}
}
}
}
protected function updateOrderStatus(InPostShipmentModel $shipmentModel)
{
if (Status::STATUS_DELIVERED === $shipmentModel->status &&
$this->ordersConfiguration->shouldChangeOrderStateOnShipmentDelivered() &&
$orderState = $this->getShipmentDeliveredOrderState()
) {
$currentState = $shipmentModel->getOrder()->getCurrentOrderState();
if (null === $currentState || $currentState->id !== $orderState->id) {
$shipmentModel->getOrder()->setCurrentState($orderState->id);
}
}
}
protected function getShipmentDeliveredOrderState()
{
if (!isset($this->shipmentDeliveredOrderState)) {
$orderStateId = $this->ordersConfiguration->getShipmentDeliveredOrderStateId();
if (Validate::isLoadedObject($orderState = new OrderState($orderStateId))) {
$this->shipmentDeliveredOrderState = $orderState;
} else {
$this->shipmentDeliveredOrderState = false;
}
}
return $this->shipmentDeliveredOrderState ?: null;
}
}

View File

@@ -0,0 +1,32 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,108 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Handler\ShippingService;
use Carrier;
use InPost\Shipping\CarrierConfigurationUpdater;
use InPost\Shipping\CarrierUpdater;
use InPost\Shipping\Traits\ErrorsTrait;
use InPostCarrierModel;
use InPostShipping;
class AddServiceHandler
{
use ErrorsTrait;
const TRANSLATION_SOURCE = 'AddServiceHandler';
protected $module;
protected $carrierUpdater;
protected $configurationUpdater;
public function __construct(
InPostShipping $module,
CarrierUpdater $carrierUpdater,
CarrierConfigurationUpdater $configurationUpdater
) {
$this->module = $module;
$this->carrierUpdater = $carrierUpdater;
$this->configurationUpdater = $configurationUpdater;
}
public function handle(array $request)
{
$this->resetErrors();
$inPostCarrier = new InPostCarrierModel();
$inPostCarrier->service = $request['service'];
$inPostCarrier->cod = $request['cashOnDelivery'];
$inPostCarrier->weekend_delivery = $request['weekendDelivery'];
$inPostCarrier->use_product_dimensions = $request['useProductDimensions'];
if (isset($request['carrierReference']) && $request['carrierReference']) {
$updateSettings = $request['updateSettings'];
if (!$carrier = Carrier::getCarrierByReference($request['carrierReference'])) {
$this->errors['carrierReference'] = sprintf(
$this->module->l('Could not find carrier with reference %s', self::TRANSLATION_SOURCE),
$request['carrierReference']
);
}
} else {
$updateSettings = true;
$carrier = new Carrier();
$carrier->name = $request['carrierName'];
}
if (!$this->configurationUpdater->update($request)) {
$this->errors = array_merge(
$this->errors,
$this->configurationUpdater->getErrors()
);
}
if (empty($this->errors)) {
$carrier = $this->carrierUpdater->update(
$carrier,
$request['service'],
$request['cashOnDelivery'],
$request['weekendDelivery'],
$updateSettings
);
if ($carrier) {
$inPostCarrier->id = $carrier->id_reference;
$inPostCarrier->add();
return $inPostCarrier;
} else {
$this->setErrors($this->carrierUpdater->getErrors());
}
}
return false;
}
}

View File

@@ -0,0 +1,60 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Handler\ShippingService;
use InPost\Shipping\Traits\ErrorsTrait;
use InPostCarrierModel;
use InPostShipping;
use Validate;
class DeleteServiceHandler
{
use ErrorsTrait;
const TRANSLATION_SOURCE = 'DeleteServiceHandler';
protected $module;
public function __construct(InPostShipping $module)
{
$this->module = $module;
}
public function handle(array $request)
{
$this->resetErrors();
if (!Validate::isLoadedObject($inPostCarrier = new InPostCarrierModel($request['carrierReference']))) {
$this->addError(sprintf(
$this->module->l('No service associated with carrier with reference %s', self::TRANSLATION_SOURCE),
$request['carrierReference']
));
} else {
$inPostCarrier->delete();
}
return !$this->hasErrors();
}
}

View File

@@ -0,0 +1,98 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Handler\ShippingService;
use InPost\Shipping\CarrierConfigurationUpdater;
use InPost\Shipping\CarrierUpdater;
use InPost\Shipping\Traits\ErrorsTrait;
use InPostCarrierModel;
use InPostShipping;
use Validate;
class UpdateServiceHandler
{
use ErrorsTrait;
const TRANSLATION_SOURCE = 'UpdateServiceHandler';
protected $module;
protected $carrierUpdater;
protected $configurationUpdater;
public function __construct(
InPostShipping $module,
CarrierUpdater $carrierUpdater,
CarrierConfigurationUpdater $configurationUpdater
) {
$this->module = $module;
$this->carrierUpdater = $carrierUpdater;
$this->configurationUpdater = $configurationUpdater;
}
public function handle(array $request)
{
$this->resetErrors();
if (Validate::isLoadedObject($inPostCarrier = new InPostCarrierModel($request['carrierReference']))) {
if ($request['updateSettings']) {
$carrier = $this->carrierUpdater->update(
$inPostCarrier->getCarrier(),
$request['service'],
$request['cashOnDelivery'],
$request['weekendDelivery']
);
if (!$carrier) {
$this->setErrors($this->carrierUpdater->getErrors());
}
}
if (!$this->configurationUpdater->update($request)) {
$this->errors = array_merge(
$this->errors,
$this->configurationUpdater->getErrors()
);
}
if (!$this->hasErrors()) {
$inPostCarrier->service = $request['service'];
$inPostCarrier->cod = $request['cashOnDelivery'];
$inPostCarrier->weekend_delivery = $request['weekendDelivery'];
$inPostCarrier->use_product_dimensions = $request['useProductDimensions'];
$inPostCarrier->update();
return $inPostCarrier;
}
} else {
$this->addError(sprintf(
$this->module->l('No service associated with carrier with reference %s', self::TRANSLATION_SOURCE),
$request['carrierReference']
));
}
return false;
}
}

View File

@@ -0,0 +1,32 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,32 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,49 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Helper;
use InPost\Shipping\ChoiceProvider\ShipmentReferenceFieldChoiceProvider;
use InPost\Shipping\Configuration\SendingConfiguration;
use Order;
class DefaultShipmentReferenceExtractor
{
protected $sendingConfiguration;
public function __construct(SendingConfiguration $sendingConfiguration)
{
$this->sendingConfiguration = $sendingConfiguration;
}
public function getShipmentReference(Order $order)
{
switch ($this->sendingConfiguration->getDefaultShipmentReferenceField()) {
case ShipmentReferenceFieldChoiceProvider::ORDER_ID:
return $order->id;
default:
return $order->reference;
}
}
}

View File

@@ -0,0 +1,94 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Helper;
use InPost\Shipping\DataProvider\TemplateDimensionsDataProvider;
use InPost\Shipping\ShipX\Resource\Organization\Shipment;
class ParcelDimensionsComparator
{
protected $dataProvider;
protected $templateIndex;
public function __construct(TemplateDimensionsDataProvider $dataProvider)
{
$this->dataProvider = $dataProvider;
$this->templateIndex = array_flip(Shipment::DIMENSION_TEMPLATES);
}
public function compareTemplates($templateA, $templateB)
{
if ($templateA === $templateB) {
return 0;
}
return $this->templateIndex[$templateA] > $this->templateIndex[$templateB] ? 1 : -1;
}
public function compareDimensions(array $dimensionsA, array $dimensionsB)
{
$sumA = array_sum($dimensionsA['dimensions']);
$sumB = array_sum($dimensionsB['dimensions']);
if ($sumA > $sumB) {
return 1;
} elseif ($sumB > $sumA) {
return -1;
} else {
if ($dimensionsA['weight']['amount'] === $dimensionsB['weight']['amount']) {
return 0;
}
return $dimensionsA['weight']['amount'] > $dimensionsB['weight']['amount'] ? 1 : -1;
}
}
public function compareTemplateWithDimensions($template, array $dimensions)
{
return $this->compareDimensions(
$this->dataProvider->getDimensions($template),
$dimensions
);
}
public function getLargestTemplate(array $templates)
{
if (!empty($templates)) {
$max = array_pop($templates);
foreach ($templates as $template) {
if ($this->compareTemplates($template, $max) > 0) {
$max = $template;
}
}
return $max;
}
return null;
}
}

View File

@@ -0,0 +1,32 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,70 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Hook;
use InPost\Shipping\Views\Modal\CreateDispatchOrderModal;
use InPost\Shipping\Views\Modal\PrintShipmentLabelModal;
abstract class AbstractAdminOrdersHook extends AbstractHook
{
const HOOK_LIST_177 = [];
/**
* @return array
*/
public function getAvailableHooks()
{
return $this->shopContext->is177()
? static::HOOK_LIST_177
: static::HOOK_LIST;
}
protected function renderPrintShipmentLabelModal()
{
/** @var PrintShipmentLabelModal $modal */
$modal = $this->module->getService('inpost.shipping.views.modal.print_label');
return $modal
->setTemplate($this->getTemplatePath('modal/print-shipment-label.tpl'))
->render();
}
protected function renderDispatchOrderModal()
{
/** @var CreateDispatchOrderModal $modal */
$modal = $this->module->getService('inpost.shipping.views.modal.dispatch_order');
return $modal
->setTemplate($this->getTemplatePath('modal/create-dispatch-order.tpl'))
->render();
}
protected function getTemplatePath($template)
{
return $this->shopContext->is177()
? 'views/templates/hook/177/' . $template
: 'views/templates/hook/' . $template;
}
}

View File

@@ -0,0 +1,60 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Hook;
use Context;
use InPost\Shipping\PrestaShopContext;
use InPostShipping;
abstract class AbstractHook
{
const HOOK_LIST = [];
const HOOK_LIST_16 = [];
const HOOK_LIST_17 = [];
protected $module;
protected $context;
protected $shopContext;
public function __construct(InPostShipping $module, PrestaShopContext $shopContext)
{
$this->module = $module;
$this->context = Context::getContext();
$this->shopContext = $shopContext;
}
/**
* @return array
*/
public function getAvailableHooks()
{
return array_merge(
static::HOOK_LIST,
$this->shopContext->is17()
? static::HOOK_LIST_17
: static::HOOK_LIST_16
);
}
}

View File

@@ -0,0 +1,198 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Hook;
use Carrier;
use InPost\Shipping\Configuration\ShipXConfiguration;
use InPost\Shipping\DataProvider\CustomerChoiceDataProvider;
use InPost\Shipping\DataProvider\OrderShipmentsDataProvider;
use InPost\Shipping\DataProvider\PointDataProvider;
use InPost\Shipping\Install\Tabs;
use InPost\Shipping\Presenter\PointAddressPresenter;
use InPost\Shipping\ShipX\Resource\Service;
use InPost\Shipping\Views\Modal\CreateShipmentModal;
use InPost\Shipping\Views\Modal\ShipmentDetailsModal;
use Order;
class AdminOrderDetails extends AbstractAdminOrdersHook
{
const HOOK_LIST = [
'displayAdminOrderTabShip',
'displayAdminOrderContentShip',
];
const HOOK_LIST_177 = [
'displayAdminOrderTabLink',
'displayAdminOrderTabContent',
];
/** @var Order */
protected $order;
protected $templateVarsAssigned = false;
public function hookDisplayAdminOrderTabShip($params)
{
$this->order = $params['order'];
return $this->displayTabLink();
}
public function hookDisplayAdminOrderTabLink($params)
{
$this->order = new Order($params['id_order']);
return $this->displayTabLink();
}
protected function displayTabLink()
{
if ($this->shouldDisplayOrderContent()) {
$this->assignCommonTemplateVariables();
return $this->module->display($this->module->name, $this->getTemplatePath('admin-order-tab-ship.tpl'));
}
return '';
}
public function hookDisplayAdminOrderContentShip($params)
{
$this->order = $params['order'];
return $this->displayTabContent();
}
public function hookDisplayAdminOrderTabContent($params)
{
return $this->displayTabContent();
}
protected function displayTabContent()
{
if ($this->shouldDisplayOrderContent()) {
$this->assignCommonTemplateVariables();
return $this->module->display($this->module->name, $this->getTemplatePath('admin-order-content-ship.tpl'))
. $this->renderModals();
}
return '';
}
protected function shouldDisplayOrderContent()
{
/** @var CustomerChoiceDataProvider $customerChoiceDataProvider */
$customerChoiceDataProvider = $this->module->getService('inpost.shipping.data_provider.customer_choice');
return !empty($customerChoiceDataProvider->getDataByCartId($this->order->id_cart))
|| (new Carrier($this->order->id_carrier))->external_module_name === $this->module->name;
}
protected function assignCommonTemplateVariables()
{
if (!$this->templateVarsAssigned) {
/** @var OrderShipmentsDataProvider $shipmentsDataProvider */
$shipmentsDataProvider = $this->module->getService('inpost.shipping.data_provider.order_shipments');
$this->context->smarty->assign([
'inPostShipmentsListUrl' => $this->context->link->getAdminLink(Tabs::SHIPMENTS_CONTROLLER_NAME),
'inPostShipments' => $shipmentsDataProvider->getOrderShipments($this->order->id),
'inPostLockerAddress' => $this->getLockerAddress(),
]);
$this->templateVarsAssigned = true;
}
}
protected function renderModals()
{
return $this->renderDispatchOrderModal()
. $this->renderShipmentFormModal()
. $this->renderPrintShipmentLabelModal()
. $this->renderShipmentDetailsModal();
}
protected function renderShipmentFormModal()
{
/** @var CreateShipmentModal $modal */
$modal = $this->module->getService('inpost.shipping.views.modal.shipment');
return $modal
->setOrder($this->order)
->setTemplate($this->getTemplatePath('modal/create-shipment.tpl'))
->render();
}
protected function renderShipmentDetailsModal()
{
/** @var ShipmentDetailsModal $modal */
$modal = $this->module->getService('inpost.shipping.views.modal.shipment_details');
return $modal->render();
}
protected function getLockerAddress()
{
if (($pointName = $this->getPointNameByCartId($this->order->id_cart)) &&
$point = $this->getLivePointData($pointName)
) {
/** @var PointAddressPresenter $pointAddressPresenter */
$pointAddressPresenter = $this->module->getService('inpost.shipping.presenter.point_address');
return $pointAddressPresenter->present($point, false, $this->context->language->id);
}
return null;
}
protected function getLivePointData($pointName)
{
/** @var PointDataProvider $pointDataProvider */
$pointDataProvider = $this->module->getService('inpost.shipping.data_provider.point');
/** @var ShipXConfiguration $configuration */
$configuration = $this->module->getService('inpost.shipping.configuration.shipx');
$configuration->setSandboxMode(false);
$pointData = $pointDataProvider->getPointData($pointName);
$configuration->setSandboxMode(null);
return $pointData;
}
protected function getPointNameByCartId($id_cart)
{
/** @var CustomerChoiceDataProvider $customerChoiceDataProvider */
$customerChoiceDataProvider = $this->module->getService('inpost.shipping.data_provider.customer_choice');
if (($customerChoice = $customerChoiceDataProvider->getDataByCartId($id_cart)) &&
$customerChoice->service === Service::INPOST_LOCKER_STANDARD
) {
return $customerChoice->point;
}
return null;
}
}

View File

@@ -0,0 +1,251 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Hook;
use Doctrine\DBAL\Query\QueryBuilder;
use InPost\Shipping\Adapter\LinkAdapter;
use InPost\Shipping\Configuration\ShipXConfiguration;
use InPost\Shipping\Install\Tabs;
use PrestaShop\PrestaShop\Core\Grid\Action\Bulk\Type\ButtonBulkAction;
use PrestaShop\PrestaShop\Core\Grid\Column\Type\Common\DateTimeColumn;
use PrestaShop\PrestaShop\Core\Grid\Definition\GridDefinitionInterface;
use PrestaShop\PrestaShop\Core\Grid\Filter\Filter;
use PrestaShop\PrestaShop\Core\Search\Filters\OrderFilters;
use PrestaShop\PrestaShop\Core\Util\DateTime\DateTime;
use PrestaShopBundle\Form\Admin\Type\DateRangeType;
class AdminOrderList extends AbstractAdminOrdersHook
{
const HOOK_LIST = [
'actionAdminOrdersListingFieldsModifier',
'displayAdminOrdersListBefore',
'displayAdminOrdersListAfter',
];
const HOOK_LIST_177 = [
'displayAdminGridTableBefore',
'actionOrderGridDefinitionModifier',
'actionOrderGridQueryBuilderModifier',
];
const TRANSLATION_SOURCE = 'AdminOrderList';
public function hookActionAdminOrdersListingFieldsModifier($params)
{
if (isset($params['select'])) {
/* unless there's a comma after column name/alias AdminController::getList appends field to query */
$params['select'] = 'MAX(inpost.date_add) as inpost_shipment_date, ' . $params['select'];
$params['join'] .= ' LEFT JOIN `' . _DB_PREFIX_ . 'inpost_shipment` inpost
ON inpost.id_order = a.id_order AND inpost.sandbox = ' . $this->getSandbox();
$params['group_by'] = 'GROUP BY a.id_order';
}
$params['fields']['reference']['filter_key'] = 'a!reference';
$params['fields'] = array_merge($params['fields'], [
'inpost_shipment_date' => [
'title' => $this->module->l('InPost date', self::TRANSLATION_SOURCE),
'align' => 'text-right',
'type' => 'datetime',
'filter_key' => 'inpost!date_add',
],
]);
}
public function hookDisplayAdminOrdersListBefore()
{
return $this->renderPrintShipmentLabelModal() . $this->renderDispatchOrderModal();
}
public function hookDisplayAdminOrdersListAfter()
{
$this->context->smarty->assign([
'moduleDisplayName' => $this->module->displayName,
'bulkActions' => $this->getBulkActions(),
]);
return $this->module->display($this->module->name, 'views/templates/hook/admin-orders-list-after.tpl');
}
public function hookDisplayAdminGridTableBefore($params)
{
if ($params['legacy_controller'] === 'AdminOrders') {
return '<div id="ajaxBox" class="mt-3"></div>'
. $this->renderPrintShipmentLabelModal()
. $this->renderDispatchOrderModal();
}
return '';
}
public function hookActionOrderGridDefinitionModifier($params)
{
/** @var GridDefinitionInterface $definition */
$definition = $params['definition'];
$definition->getColumns()
->addAfter(
'date_add',
(new DateTimeColumn('inpost_shipment_date'))
->setName($this->module->l('InPost shipment creation date', self::TRANSLATION_SOURCE))
->setOptions([
'field' => 'inpost_shipment_date',
'empty_data' => '--',
])
);
$definition->getFilters()
->add(
(new Filter('inpost_shipment_date', DateRangeType::class))
->setTypeOptions([
'attr' => [
'placeholder' => $this->module->l('Search date', self::TRANSLATION_SOURCE),
],
'required' => false,
])
->setAssociatedColumn('inpost_shipment_date')
);
$bulkActions = $definition->getBulkActions();
foreach ($this->getBulkActions() as $key => $bulkAction) {
$bulkActions->add(
(new ButtonBulkAction($key))
->setName($bulkAction['label'])
->setOptions([
'class' => $bulkAction['class'],
'attributes' => [
'data-action' => $bulkAction['action'],
],
])
);
}
}
public function hookActionOrderGridQueryBuilderModifier($params)
{
/** @var QueryBuilder[] $queryBuilders */
$queryBuilders = [
'search' => $params['search_query_builder'],
'count' => $params['count_query_builder'],
];
/** @var OrderFilters $searchCriteria */
$searchCriteria = $params['search_criteria'];
$filters = $searchCriteria->getFilters();
foreach ($queryBuilders as $queryBuilder) {
if (isset($filters['inpost_shipment_date']['from'])) {
$queryBuilder
->andWhere('inpost.date_add >= :inpost_date_from')
->setParameter('inpost_date_from', $filters['inpost_shipment_date']['from']);
}
if (isset($filters['inpost_shipment_date']['to'])) {
$queryBuilder
->andWhere('inpost.date_add <= :inpost_date_to')
->setParameter('inpost_date_to', $filters['inpost_shipment_date']['to']);
}
}
if (!isset($filters['inpost_shipment_date']['from']) && !isset($filters['inpost_shipment_date']['to'])) {
unset($queryBuilders['count']);
}
foreach ($queryBuilders as $queryBuilder) {
$queryBuilder
->addSelect(sprintf(
'IFNULL(MAX(inpost.date_add), "%s") as inpost_shipment_date',
DateTime::NULL_VALUE
))
->leftJoin(
'o',
_DB_PREFIX_ . 'inpost_shipment',
'inpost',
'inpost.id_order = o.id_order AND inpost.sandbox = ' . $this->getSandbox()
)
->groupBy('o.id_order');
}
}
protected function getBulkActions()
{
/** @var LinkAdapter $link */
$link = $this->module->getService('inpost.shipping.adapter.link');
return [
'inpost_create_shipments' => [
'label' => $this->module->l('Create InPost shipments', self::TRANSLATION_SOURCE),
'action' => $link->getAdminLink(Tabs::SHIPMENTS_CONTROLLER_NAME, true, [], [
'action' => 'bulkCreateShipment',
'ajax' => true,
]),
'class' => 'js-inpost-bulk-create-shipments',
'icon' => 'truck',
],
'inpost_create_print_shipments' => [
'label' => $this->module->l('Create InPost shipments and print labels', self::TRANSLATION_SOURCE),
'action' => $link->getAdminLink(Tabs::SHIPMENTS_CONTROLLER_NAME, true, [], [
'action' => 'bulkPrintLabels',
'ajax' => true,
]),
'class' => 'js-inpost-bulk-create-print-shipments',
'icon' => 'print',
],
'inpost_create_dispatch_orders' => [
'label' => $this->module->l('Create InPost dispatch orders', self::TRANSLATION_SOURCE),
'action' => $link->getAdminLink(Tabs::SHIPMENTS_CONTROLLER_NAME, true, [], [
'action' => 'bulkCreateDispatchOrders',
'ajax' => true,
]),
'class' => 'js-inpost-bulk-create-dispatch-orders',
'icon' => 'truck',
],
'inpost_print_dispatch_orders' => [
'label' => $this->module->l('Print InPost dispatch orders', self::TRANSLATION_SOURCE),
'action' => $link->getAdminLink(Tabs::SHIPMENTS_CONTROLLER_NAME, true, [], [
'action' => 'bulkPrintDispatchOrders',
'ajax' => true,
]),
'class' => 'js-inpost-bulk-print-dispatch-orders',
'icon' => 'print',
],
'inpost_refresh_shipment_status' => [
'label' => $this->module->l('Update InPost shipments\' statuses', self::TRANSLATION_SOURCE),
'action' => $link->getAdminLink(Tabs::SHIPMENTS_CONTROLLER_NAME, true, [], [
'action' => 'bulkRefreshStatuses',
'ajax' => true,
]),
'class' => 'js-inpost-bulk-refresh-shipment-status',
'icon' => 'refresh',
],
];
}
protected function getSandbox()
{
/** @var ShipXConfiguration $configuration */
$configuration = $this->module->getService('inpost.shipping.configuration.shipx');
return $configuration->isSandboxModeEnabled() ? 1 : 0;
}
}

View File

@@ -0,0 +1,88 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Hook;
use InPost\Shipping\ChoiceProvider\ProductTemplateChoiceProvider;
use InPost\Shipping\Handler\ProductUpdateHandler;
use InPostProductTemplateModel;
use PrestaShopException;
use Product;
use Tools;
class AdminProduct extends AbstractHook
{
const HOOK_LIST = [
'actionAdminProductsControllerSaveAfter',
];
const HOOK_LIST_16 = [
'displayAdminProductsExtra',
];
const HOOK_LIST_17 = [
'displayAdminProductsShippingStepBottom',
];
public function hookActionAdminProductsControllerSaveAfter($params)
{
/** @var Product $product */
if ($product = $params['return']) {
/** @var ProductUpdateHandler $updater */
$updater = $this->module->getService('inpost.shipping.handler.product_update');
$template = Tools::getValue('inpost_dimension_template') ?: null;
if (!$updater->update($product, $template)) {
throw new PrestaShopException(current($updater->getErrors()));
}
}
}
public function hookDisplayAdminProductsExtra()
{
$this->assignTemplateVariables(Tools::getValue('id_product'));
return $this->module->display($this->module->name, 'views/templates/hook/16/admin-products-form.tpl');
}
public function hookDisplayAdminProductsShippingStepBottom($params)
{
$this->assignTemplateVariables($params['id_product']);
return $this->module->display($this->module->name, 'views/templates/hook/admin-products-form.tpl');
}
protected function assignTemplateVariables($id_product)
{
/** @var ProductTemplateChoiceProvider $templateChoiceProvider */
$templateChoiceProvider = $this->module->getService('inpost.shipping.choice_provider.product_template');
$productTemplate = new InPostProductTemplateModel($id_product);
$this->context->smarty->assign([
'templateChoices' => $templateChoiceProvider->getChoices(),
'selectedTemplate' => $productTemplate->template,
]);
}
}

View File

@@ -0,0 +1,224 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Hook;
use InPost\Shipping\Configuration\CheckoutConfiguration;
use InPost\Shipping\ShipX\Resource\Service;
use Media;
use ModuleFrontController;
use Tools;
class Assets extends AbstractHook
{
const HOOK_LIST = [
'actionAdminControllerSetMedia',
'actionFrontControllerSetMedia',
'displayAdminAfterHeader',
];
const SUPERCHECKOUT_MODULE = 'supercheckout';
protected $ordersDisplay;
public function hookActionAdminControllerSetMedia()
{
if (Tools::getValue('controller') === 'AdminOrders') {
$display = $this->getOrdersDisplay();
Media::addJsDef([
'shopIs177' => $this->shopContext->is177(),
'inPostLockerServices' => Service::LOCKER_SERVICES,
'inPostLockerStandard' => Service::INPOST_LOCKER_STANDARD,
]);
if ($display === 'view') {
$assetsManager = $this->module->getAssetsManager();
$assetsManager
->registerJavaScripts([
$assetsManager::GEO_WIDGET_JS_URL,
'map.js',
'admin/tools.js',
'admin/common.js',
'admin/order-details.js',
])
->registerStyleSheets([
$assetsManager::GEO_WIDGET_CSS_URL,
'admin/orders.css',
]);
} elseif ($display === 'index') {
$this->module->getAssetsManager()
->registerJavaScripts([
'admin/tools.js',
'admin/order-list.js',
]);
}
}
if ($this->shouldDisplayLoader()) {
$this->module
->getAssetsManager()
->registerStyleSheets(['admin/loader.css']);
}
}
public function hookDisplayAdminAfterHeader()
{
return $this->shouldDisplayLoader()
? $this->module->display($this->module->name, 'views/templates/hook/loader.tpl')
: '';
}
protected function shouldDisplayLoader()
{
return Tools::getValue('controller') === 'AdminOrders'
&& in_array($this->getOrdersDisplay(), ['index', 'view'])
|| isset($this->context->controller->module)
&& $this->context->controller->module === $this->module;
}
public function hookActionFrontControllerSetMedia()
{
if ($this->isCheckoutControllerContext()) {
$assetsManager = $this->module->getAssetsManager();
$assetsManager
->registerJavaScripts([$assetsManager::GEO_WIDGET_JS_URL], [
'position' => 'head',
'attributes' => 'async',
])
->registerJavaScripts([
'map.js',
$this->shopContext->is17() ? 'checkout17.js' : 'checkout16.js',
])
->registerStyleSheets([
$assetsManager::GEO_WIDGET_CSS_URL,
'front.css',
]);
if ($scripts = $this->getModuleSpecificScriptFiles()) {
$assetsManager->registerJavaScripts($scripts);
}
Media::addJsDef([
'inPostAjaxController' => $this->context->link->getModuleLink($this->module->name, 'ajax'),
'inPostLocale' => Tools::strtolower($this->context->language->iso_code) === 'pl' ? 'pl' : 'uk',
]);
}
}
protected function getOrdersDisplay()
{
if (!isset($this->ordersDisplay)) {
$this->ordersDisplay = $this->initOrdersDisplay();
}
return $this->ordersDisplay;
}
protected function initOrdersDisplay()
{
if ($this->shopContext->is177()) {
switch (Tools::getValue('action')) {
case 'vieworder':
return 'view';
case 'addorder':
return 'create';
default:
return 'index';
}
}
if (Tools::isSubmit('vieworder')) {
return 'view';
} elseif (Tools::isSubmit('addorder')) {
return 'create';
}
return 'index';
}
protected function isCheckoutControllerContext()
{
$controller = Tools::getValue('controller');
if (in_array($controller, ['order', 'orderopc'])) {
return true;
}
if ($this->context->controller instanceof ModuleFrontController) {
switch ($this->context->controller->module->name) {
case self::SUPERCHECKOUT_MODULE:
return 'supercheckout' === $this->getModuleControllerName($controller);
default:
return $this->isCustomCheckoutController(
$this->context->controller->module->name,
$controller
);
}
}
return false;
}
protected function getModuleControllerName($controller)
{
$parts = explode('-', $controller);
return end($parts);
}
protected function isCustomCheckoutController($moduleName, $controller)
{
/** @var CheckoutConfiguration $configuration */
$configuration = $this->module->getService('inpost.shipping.configuration.checkout');
if ($configuration->isUsingCustomCheckoutModule()) {
$controllers = $configuration->getCustomCheckoutControllers();
return isset($controllers[$moduleName])
&& in_array(
$this->getModuleControllerName($controller),
$controllers[$moduleName]
);
}
return false;
}
protected function getModuleSpecificScriptFiles()
{
if ($this->context->controller instanceof ModuleFrontController) {
switch ($this->context->controller->module->name) {
case self::SUPERCHECKOUT_MODULE:
return ['modules/supercheckout.js'];
default:
return [];
}
}
return [];
}
}

View File

@@ -0,0 +1,248 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Hook;
use Address;
use Carrier;
use Cart;
use InPost\Shipping\CartChoiceUpdater;
use InPost\Shipping\Presenter\CheckoutDataPresenter;
use InPost\Shipping\Traits\ErrorsTrait;
use InPostCarrierModel;
use InPostCartChoiceModel;
use Order;
use OrderController;
use Tools;
class Checkout extends AbstractHook
{
use ErrorsTrait;
const HOOK_LIST = [
'actionCarrierProcess',
'actionValidateOrder',
];
const HOOK_LIST_16 = [
'displayCarrierList',
];
const HOOK_LIST_17 = [
'displayCarrierExtraContent',
'actionValidateStepComplete',
];
protected $deliveryChoiceProcessed = false;
public function hookActionCarrierProcess($params)
{
if ($this->shopContext->is17()) {
if (!$this->deliveryChoiceProcessed && Tools::isSubmit('delivery_option')) {
$this->processDeliveryChoice($params['cart'], Tools::getAllValues());
}
} elseif (Tools::getValue('step') == OrderController::STEP_PAYMENT) {
$this->processDeliveryChoice($params['cart'], Tools::getAllValues());
if ($this->hasErrors()) {
$this->context->controller->errors = array_merge(
$this->context->controller->errors,
$this->getErrors()
);
$this->module->getAssetsManager()
->registerJavaScripts([
_THEME_JS_DIR_ . 'order-carrier.js',
]);
}
}
}
public function hookActionValidateStepComplete($params)
{
if ($params['step_name'] === 'delivery' &&
$this->processDeliveryChoice($this->context->cart, $params['request_params'])
) {
$this->deliveryChoiceProcessed = true;
if ($this->hasErrors()) {
$params['completed'] = false;
$this->storeSessionData($params['request_params']);
}
}
}
protected function processDeliveryChoice(Cart $cart, array $requestParams)
{
$deliveryOption = $requestParams['delivery_option'];
$carrierIds = explode(',', trim($deliveryOption[$cart->id_address_delivery], ','));
foreach ($carrierIds as $carrierId) {
if ($carrierData = InPostCarrierModel::getDataByCarrierId($carrierId)) {
$updater = $this->getCartChoiceUpdater($cart->id, $carrierData)
->setEmail(isset($requestParams['inpost_email']) ? $requestParams['inpost_email'] : null)
->setPhone(isset($requestParams['inpost_phone']) ? $requestParams['inpost_phone'] : null);
if ($carrierData['lockerService']) {
$locker = isset($requestParams['inpost_locker'][$carrierId])
? $requestParams['inpost_locker'][$carrierId]
: null;
$updater->setTargetPoint($locker);
}
$updater->saveChoice($cart->id);
if ($updater->hasErrors()) {
$this->setErrors($updater->getErrors());
}
return true;
}
}
return false;
}
protected function getCartChoiceUpdater($id_cart, array $carrierData)
{
/** @var CartChoiceUpdater $updater */
$updater = $this->module->getService('inpost.shipping.updater.cart_choice');
return $updater
->setCartChoice(new InPostCartChoiceModel($id_cart))
->setCarrierData($carrierData);
}
public function hookDisplayCarrierExtraContent($params)
{
if ((!Tools::getValue('confirmDeliveryOption') || $this->deliveryChoiceProcessed) &&
$carrierData = InPostCarrierModel::getDataByCarrierId($params['carrier']['id'])
) {
$this->assignTemplateVariables($carrierData, $this->retrieveSessionData());
return $this->module->display(
$this->module->name,
'views/templates/hook/carrier-extra-content.tpl'
);
}
return '';
}
public function hookDisplayCarrierList($params)
{
$content = '';
/** @var Address $address */
$address = $params['address'];
$deliveryOption = $this->context->cart->getDeliveryOption(null, true);
$carrierIds = explode(',', trim($deliveryOption[$address->id], ','));
foreach ($carrierIds as $carrierId) {
if ($carrierData = InPostCarrierModel::getDataByCarrierId($carrierId)) {
$this->assignTemplateVariables($carrierData);
$content .= $this->module->display(
$this->module->name,
'views/templates/hook/16/carrier-extra-content.tpl'
);
}
}
return $content;
}
protected function assignTemplateVariables(array $carrierData, array $sessionData = [])
{
/** @var CheckoutDataPresenter $presenter */
$presenter = $this->module->getService('inpost.shipping.presenter.checkout_data');
$this->context->smarty->assign($presenter->present($carrierData, $sessionData));
}
public function hookActionValidateOrder($params)
{
/** @var Order $order */
$order = $params['order'];
$carrier = new Carrier($order->id_carrier);
if ($carrier->external_module_name !== $this->module->name) {
$cartChoice = new InPostCartChoiceModel();
$cartChoice->id = $order->id_cart;
$cartChoice->delete();
}
}
// preserve errors and submitted values to retrieve after redirect
protected function storeSessionData(array $requestParams)
{
$data = json_encode([
'email' => isset($requestParams['inpost_email']) ? $requestParams['inpost_email'] : null,
'phone' => isset($requestParams['inpost_phone']) ? $requestParams['inpost_phone'] : null,
'errors' => $this->getErrors(),
]);
switch (session_status()) {
// case PHP_SESSION_NONE:
// session_start();
// // no break
// case PHP_SESSION_ACTIVE:
// $_SESSION['inpost_data'] = $data;
// break;
default:
$this->context->cookie->inpost_data = $data;
break;
}
}
protected function retrieveSessionData()
{
static $data;
if (!isset($data)) {
$data = [];
switch (session_status()) {
// case PHP_SESSION_NONE:
// session_start();
// // no break
// case PHP_SESSION_ACTIVE:
// if (isset($_SESSION['inpost_data'])) {
// $data = json_decode($_SESSION['inpost_data'], true);
// unset($_SESSION['inpost_data']);
// }
// break;
default:
if (isset($this->context->cookie->inpost_data)) {
$data = json_decode($this->context->cookie->inpost_data, true);
unset($this->context->cookie->inpost_data);
}
break;
}
}
return $data;
}
}

View File

@@ -0,0 +1,124 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Hook;
use InPost\Shipping\Configuration\OrdersConfiguration;
use InPost\Shipping\DataProvider\CustomerChoiceDataProvider;
use InPost\Shipping\DataProvider\PointDataProvider;
use InPost\Shipping\Presenter\PointAddressPresenter;
use InPost\Shipping\Presenter\PointPresenter;
use InPost\Shipping\ShipX\Resource\Service;
use Order;
class Mail extends AbstractHook
{
const HOOK_LIST = [
'actionGetExtraMailTemplateVars',
];
protected $orderIndex = [];
public function hookActionGetExtraMailTemplateVars($params)
{
switch ($params['template']) {
case 'new_order':
$this->modifyNewOrderTemplateVariables($params);
break;
case 'order_conf':
$this->modifyOrderConfirmationTemplateVariables($params);
break;
default:
break;
}
}
protected function modifyNewOrderTemplateVariables($params)
{
if (($order = $this->getOrderByReference($params['template_vars']['{order_name}'])) &&
$pointName = $this->getPointNameByCartId($order->id_cart)
) {
/** @var PointDataProvider $pointDataProvider */
$pointDataProvider = $this->module->getService('inpost.shipping.data_provider.point');
if ($point = $pointDataProvider->getPointData($pointName)) {
/** @var PointAddressPresenter $pointAddressPresenter */
$pointAddressPresenter = $this->module->getService('inpost.shipping.presenter.point_address');
$params['extra_template_vars'] = array_merge($params['extra_template_vars'], [
'{delivery_block_txt}' => $pointAddressPresenter->present($point, true, $params['id_lang']),
'{delivery_block_html}' => $pointAddressPresenter->present($point, false, $params['id_lang']),
]);
}
}
}
protected function modifyOrderConfirmationTemplateVariables($params)
{
/** @var OrdersConfiguration $configuration */
$configuration = $this->module->getService('inpost.shipping.configuration.orders');
if ($configuration->shouldDisplayOrderConfirmationLocker() &&
($order = $this->getOrderByReference($params['template_vars']['{order_name}'])) &&
$pointName = $this->getPointNameByCartId($order->id_cart)
) {
/** @var PointPresenter $pointPresenter */
$pointPresenter = $this->module->getService('inpost.shipping.presenter.point');
$carrierName = isset($params['extra_template_vars']['{carrier}'])
? $params['extra_template_vars']['{carrier}']
: $params['template_vars']['{carrier}'];
$params['extra_template_vars']['{carrier}'] = sprintf(
'%s (%s)',
$carrierName,
$pointPresenter->present($pointName, $params['id_lang'], '%s [%s]')
);
}
}
/** @return Order|null */
protected function getOrderByReference($reference)
{
if (!isset($this->orderIndex[$reference])) {
$this->orderIndex[$reference] = Order::getByReference($reference)->getFirst();
}
return $this->orderIndex[$reference] ?: null;
}
protected function getPointNameByCartId($id_cart)
{
/** @var CustomerChoiceDataProvider $customerChoiceDataProvider */
$customerChoiceDataProvider = $this->module->getService('inpost.shipping.data_provider.customer_choice');
if (($customerChoice = $customerChoiceDataProvider->getDataByCartId($id_cart)) &&
$customerChoice->service === Service::INPOST_LOCKER_STANDARD
) {
return $customerChoice->point;
}
return null;
}
}

View File

@@ -0,0 +1,50 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Hook;
use InPost\Shipping\Configuration\SzybkieZwrotyConfiguration;
class OrderHistory extends AbstractHook
{
const HOOK_LIST = [
'displayOrderDetail',
];
public function hookDisplayOrderDetail()
{
/** @var SzybkieZwrotyConfiguration $configuration */
$configuration = $this->module->getService('inpost.shipping.configuration.szybkie_zwroty');
if ($link = $configuration->getOrderReturnFormUrl()) {
$this->context->smarty->assign('returnFormUrl', $link);
return $this->shopContext->is17()
? $this->module->display($this->module->name, 'views/templates/hook/order-detail.tpl')
: $this->module->display($this->module->name, 'views/templates/hook/16/order-detail.tpl');
}
return '';
}
}

View File

@@ -0,0 +1,32 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,90 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping;
use InPost\Shipping\Hook\AbstractHook;
use InPost\Shipping\Hook\AdminOrderDetails;
use InPost\Shipping\Hook\AdminOrderList;
use InPost\Shipping\Hook\AdminProduct;
use InPost\Shipping\Hook\Assets;
use InPost\Shipping\Hook\Checkout;
use InPost\Shipping\Hook\Mail;
use InPost\Shipping\Hook\OrderHistory;
use InPostShipping;
class HookDispatcher
{
const HOOK_CLASSES = [
AdminOrderDetails::class,
AdminOrderList::class,
AdminProduct::class,
Assets::class,
Checkout::class,
Mail::class,
OrderHistory::class,
];
/**
* Hook instances.
*
* @var AbstractHook[]
*/
protected $hooks = [];
public function __construct(InPostShipping $module, PrestaShopContext $shopContext)
{
foreach (static::HOOK_CLASSES as $hookClass) {
/** @var AbstractHook $hook */
$hook = new $hookClass($module, $shopContext);
$this->hooks[] = $hook;
}
}
/**
* Get available hooks
*
* @return string[]
*/
public function getAvailableHooks()
{
$availableHooks = [];
foreach ($this->hooks as $hook) {
$availableHooks = array_merge($availableHooks, $hook->getAvailableHooks());
}
return $availableHooks;
}
public function dispatch($hookName, array $params = [])
{
foreach ($this->hooks as $hook) {
if (method_exists($hook, $hookName)) {
return $hook->{$hookName}($params);
}
}
return false;
}
}

View File

@@ -0,0 +1,69 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Install;
use Carrier;
use InPostShipping;
use PrestaShopCollection;
class Carriers implements InstallerInterface
{
/**
* @var InPostShipping
*/
protected $module;
public function __construct(InPostShipping $module)
{
$this->module = $module;
}
public function install()
{
return true;
}
public function uninstall()
{
$result = true;
$collection = (new PrestaShopCollection(Carrier::class))
->where('is_module', '=', true)
->where('deleted', '=', false)
->where('external_module_name', 'LIKE', $this->module->name);
/** @var Carrier $carrier */
foreach ($collection as $carrier) {
$carrier->deleted = true;
$carrier->is_module = false;
$carrier->external_module_name = null;
$carrier->active = false;
$result &= $carrier->update();
}
return $result;
}
}

View File

@@ -0,0 +1,67 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Install;
use InPost\Shipping\Configuration\AbstractConfiguration;
class Configuration implements InstallerInterface
{
/**
* @var AbstractConfiguration[]
*/
protected $configurations;
/**
* @param AbstractConfiguration[] $configurations
*/
public function __construct(array $configurations)
{
$this->configurations = array_filter($configurations, function ($configuration) {
return $configuration instanceof AbstractConfiguration;
});
}
public function install()
{
$result = true;
foreach ($this->configurations as $configuration) {
$result &= $configuration->setDefaults();
}
return $result;
}
public function uninstall()
{
$result = true;
foreach ($this->configurations as $configuration) {
$result &= $configuration->reset();
}
return $result;
}
}

View File

@@ -0,0 +1,277 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Install;
use Db;
use InPost\Shipping\PrestaShopContext;
use InPost\Shipping\ShipX\Resource\Organization\Shipment;
use InPost\Shipping\ShipX\Resource\SendingMethod;
use InPost\Shipping\ShipX\Resource\Service;
use InPost\Shipping\ShipX\Resource\Status;
use InPostShipmentStatusModel;
use Language;
class Database implements InstallerInterface
{
const ID_LANG_DEF_16 = 'INT(10) UNSIGNED NOT NULL';
const ID_LANG_DEF_17 = 'INT(11) NOT NULL';
protected $shopContext;
protected $db;
public function __construct(PrestaShopContext $shopContext)
{
$this->shopContext = $shopContext;
$this->db = Db::getInstance();
}
public function install()
{
return $this->createTables()
&& $this->addStatuses();
}
public function createTables()
{
$result = true;
$services = '"' . implode('","', Service::SERVICES) . '"';
$templates = '"' . implode('","', Shipment::DIMENSION_TEMPLATES) . '"';
$idLangDef = $this->shopContext->is17()
? self::ID_LANG_DEF_17
: self::ID_LANG_DEF_16;
$result &= $this->db->execute('
CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'inpost_shipment_status` (
`id_status` INT(10) UNSIGNED AUTO_INCREMENT NOT NULL,
`name` VARCHAR(64) NOT NULL,
PRIMARY KEY (`id_status`),
UNIQUE (`name`)
)
ENGINE = ' . _MYSQL_ENGINE_ . '
CHARSET = utf8
COLLATE = utf8_general_ci
');
$result &= $this->db->execute('
CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'inpost_shipment_status_lang` (
`id_status` INT(10) UNSIGNED NOT NULL,
`id_lang` ' . $idLangDef . ',
`title` VARCHAR(128) NOT NULL,
`description` VARCHAR(512) NOT NULL,
PRIMARY KEY (`id_status`, `id_lang`),
FOREIGN KEY (`id_status`)
REFERENCES `' . _DB_PREFIX_ . 'inpost_shipment_status` (`id_status`)
ON DELETE CASCADE,
FOREIGN KEY (`id_lang`)
REFERENCES `' . _DB_PREFIX_ . 'lang` (`id_lang`)
ON DELETE CASCADE
)
ENGINE = ' . _MYSQL_ENGINE_ . '
CHARSET = utf8
COLLATE = utf8_general_ci
');
$result &= $this->db->execute('
CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'inpost_carrier` (
`id_reference` INT(10) UNSIGNED NOT NULL,
`service` ENUM(' . $services . ') NOT NULL,
`cod` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
`weekend_delivery` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
`use_product_dimensions` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (`id_reference`),
FOREIGN KEY (`id_reference`)
REFERENCES `' . _DB_PREFIX_ . 'carrier` (`id_reference`)
ON DELETE CASCADE
)
ENGINE = ' . _MYSQL_ENGINE_ . '
CHARSET = utf8
COLLATE = utf8_general_ci
');
$result &= $this->db->execute('
CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'inpost_cart_choice` (
`id_cart` INT(10) UNSIGNED NOT NULL,
`service` ENUM(' . $services . ') NOT NULL,
`email` VARCHAR(255),
`phone` VARCHAR(255),
`point` VARCHAR(32),
PRIMARY KEY (`id_cart`)
)
ENGINE = ' . _MYSQL_ENGINE_ . '
CHARSET = utf8
COLLATE = utf8_general_ci
');
$result &= $this->db->execute('
CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'inpost_dispatch_point` (
`id_dispatch_point` INT(10) UNSIGNED AUTO_INCREMENT NOT NULL,
`name` VARCHAR(255) NOT NULL,
`office_hours` VARCHAR(255),
`email` VARCHAR(255),
`phone` VARCHAR(255),
`street` VARCHAR(255) NOT NULL,
`building_number` VARCHAR(255) NOT NULL,
`post_code` CHAR(6) NOT NULL,
`city` VARCHAR(255) NOT NULL,
`deleted` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (`id_dispatch_point`)
)
ENGINE = ' . _MYSQL_ENGINE_ . '
CHARSET = utf8
COLLATE = utf8_general_ci
');
$result &= $this->db->execute('
CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'inpost_dispatch_order` (
`id_dispatch_order` INT(10) UNSIGNED AUTO_INCREMENT NOT NULL,
`id_dispatch_point` INT(10) UNSIGNED,
`shipx_dispatch_order_id` INT(10) UNSIGNED NOT NULL,
`number` INT(10) UNSIGNED,
`status` VARCHAR(64),
`price` DECIMAL(20,6),
`date_add` DATETIME NOT NULL,
PRIMARY KEY (`id_dispatch_order`),
FOREIGN KEY (`id_dispatch_point`)
REFERENCES `' . _DB_PREFIX_ . 'inpost_dispatch_point` (`id_dispatch_point`)
ON DELETE SET NULL
)
ENGINE = ' . _MYSQL_ENGINE_ . '
CHARSET = utf8
COLLATE = utf8_general_ci
');
$result &= $this->db->execute('
CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'inpost_shipment` (
`id_shipment` INT(10) UNSIGNED AUTO_INCREMENT NOT NULL,
`organization_id` INT(10) UNSIGNED NOT NULL,
`id_order` INT(10) UNSIGNED NOT NULL,
`sandbox` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
`shipx_shipment_id` INT(10) UNSIGNED NOT NULL,
`reference` VARCHAR(100),
`email` varchar(255) NOT NULL,
`phone` varchar(255) NOT NULL,
`service` ENUM(' . $services . ') NOT NULL,
`sending_method` ENUM("' . implode('","', SendingMethod::SENDING_METHODS) . '"),
`sending_point` VARCHAR(32),
`weekend_delivery` TINYINT(1) UNSIGNED,
`template` ENUM(' . $templates . '),
`dimensions` VARCHAR(255),
`id_dispatch_order` INT(10) UNSIGNED,
`target_point` VARCHAR(32),
`cod_amount` DECIMAL(20,6),
`insurance_amount` DECIMAL(20,6),
`tracking_number` CHAR(24),
`status` VARCHAR(64),
`price` DECIMAL(20,6),
`label_printed` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
`date_add` DATETIME NOT NULL,
PRIMARY KEY (`id_shipment`),
FOREIGN KEY (`id_order`)
REFERENCES `' . _DB_PREFIX_ . 'orders` (`id_order`)
ON DELETE CASCADE,
FOREIGN KEY (`id_dispatch_order`)
REFERENCES `' . _DB_PREFIX_ . 'inpost_dispatch_order` (`id_dispatch_order`)
ON DELETE SET NULL
)
ENGINE = ' . _MYSQL_ENGINE_ . '
CHARSET = utf8
COLLATE = utf8_general_ci
');
$result &= $this->db->execute('
CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'inpost_product_template` (
`id_product` INT(10) UNSIGNED NOT NULL,
`template` ENUM(' . $templates . ') NOT NULL,
PRIMARY KEY (`id_product`),
FOREIGN KEY (`id_product`)
REFERENCES `' . _DB_PREFIX_ . 'product` (`id_product`)
ON DELETE CASCADE
)
ENGINE = ' . _MYSQL_ENGINE_ . '
CHARSET = utf8
COLLATE = utf8_general_ci
');
return $result;
}
protected function addStatuses()
{
$languageIds = Language::getIDs(false);
$indexPl = [];
if ($id_lang_pl = Language::getIdByIso('PL')) {
$statuses = Status::getAll([
'query' => ['lang' => 'pl_PL'],
]);
foreach ($statuses as $status) {
$indexPl[$status->name] = [
'title' => $status->title,
'description' => $status->description,
];
}
}
$statuses = Status::getAll([
'query' => ['lang' => 'en_GB'],
]);
foreach ($statuses as $status) {
if (!InPostShipmentStatusModel::getStatusByName($status->name)) {
$statusModel = new InPostShipmentStatusModel();
$statusModel->name = $status->name;
foreach ($languageIds as $id_lang) {
if ($id_lang == $id_lang_pl) {
$statusModel->title[$id_lang] = $indexPl[$status->name]['title'];
$statusModel->description[$id_lang] = $indexPl[$status->name]['description'];
} else {
$statusModel->title[$id_lang] = $status->title;
$statusModel->description[$id_lang] = $status->description;
}
}
$statusModel->add();
}
}
return true;
}
public function uninstall()
{
$result = true;
$result &= $this->db->execute('DROP TABLE IF EXISTS `' . _DB_PREFIX_ . 'inpost_carrier`');
$result &= $this->db->execute('DROP TABLE IF EXISTS `' . _DB_PREFIX_ . 'inpost_shipment_status_lang`');
$result &= $this->db->execute('DROP TABLE IF EXISTS `' . _DB_PREFIX_ . 'inpost_shipment_status`');
$result &= $this->db->execute('DROP TABLE IF EXISTS `' . _DB_PREFIX_ . 'inpost_product_template`');
return $result;
}
}

View File

@@ -0,0 +1,56 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Install;
use InPost\Shipping\HookDispatcher;
use InPostShipping;
class Hooks implements InstallerInterface
{
protected $module;
protected $hookDispatcher;
public function __construct(InPostShipping $module, HookDispatcher $hookDispatcher)
{
$this->module = $module;
$this->hookDispatcher = $hookDispatcher;
}
public function install()
{
return $this->module->registerHook(
$this->hookDispatcher->getAvailableHooks()
);
}
public function uninstall()
{
foreach ($this->hookDispatcher->getAvailableHooks() as $hookName) {
$this->module->unregisterHook($hookName);
}
return true;
}
}

View File

@@ -0,0 +1,60 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Install;
class Installer implements InstallerInterface
{
/** @var InstallerInterface[] */
protected $subInstallers;
public function __construct(array $subInstallers)
{
$this->subInstallers = array_filter($subInstallers, function ($installer) {
return $installer instanceof InstallerInterface;
});
}
public function install()
{
$result = true;
foreach ($this->subInstallers as $installer) {
$result &= $installer->install();
}
return $result;
}
public function uninstall()
{
$result = true;
foreach ($this->subInstallers as $installer) {
$result &= $installer->uninstall();
}
return $result;
}
}

View File

@@ -0,0 +1,34 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Install;
interface InstallerInterface
{
/** @return bool */
public function install();
/** @return bool */
public function uninstall();
}

View File

@@ -0,0 +1,149 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Install;
use InPost\Shipping\DataProvider\LanguageDataProvider;
use InPost\Shipping\PrestaShopContext;
use InPostShipping;
use Tab;
class Tabs implements InstallerInterface
{
const TRANSLATION_SOURCE = 'Tabs';
const AJAX_CONTROLLER_NAME = 'AdminInPostAjax';
const DISPATCH_POINT_CONTROLLER_NAME = 'AdminInPostDispatchPoints';
const SHIPMENTS_CONTROLLER_NAME = 'AdminInPostConfirmedShipments';
const DISPATCH_ORDERS_CONTROLLER_NAME = 'AdminInPostDispatchOrders';
const SENT_SHIPMENTS_CONTROLLER_NAME = 'AdminInPostSentShipments';
const PARENT_SHIPMENTS_TAB_NAME = 'AdminParentInPostShipments';
const SHIPMENTS_TAB_NAMES = [
self::SHIPMENTS_CONTROLLER_NAME,
self::DISPATCH_ORDERS_CONTROLLER_NAME,
self::SENT_SHIPMENTS_CONTROLLER_NAME,
];
protected $module;
protected $shopContext;
protected $languageDataProvider;
public function __construct(
InPostShipping $module,
PrestaShopContext $shopContext,
LanguageDataProvider $languageDataProvider
) {
$this->module = $module;
$this->shopContext = $shopContext;
$this->languageDataProvider = $languageDataProvider;
}
public function install()
{
$result = true;
$parentTab = $this->shopContext->is17()
? self::PARENT_SHIPMENTS_TAB_NAME
: self::SHIPMENTS_CONTROLLER_NAME;
if ($id_parent = $this->installTab($parentTab, Tab::getIdFromClassName('AdminParentShipping'))) {
foreach (self::SHIPMENTS_TAB_NAMES as $className) {
$result &= (bool) $this->installTab($className, $id_parent);
}
} else {
$result = false;
}
$result &= (bool) $this->installTab(self::AJAX_CONTROLLER_NAME, -1);
$result &= (bool) $this->installTab(self::DISPATCH_POINT_CONTROLLER_NAME, -1);
return $result;
}
public function uninstall()
{
$result = true;
/** @var Tab $tab */
foreach (Tab::getCollectionFromModule($this->module->name) as $tab) {
$result &= $tab->delete();
}
return $result;
}
protected function installTab($className, $id_parent)
{
if ($id_tab = Tab::getIdFromClassName($className)) {
return $id_tab;
}
$tab = new Tab();
$tab->module = $this->module->name;
$tab->class_name = $className;
$tab->id_parent = $id_parent;
$tab->name = $this->getTabName($className);
if ($tab->add()) {
return $tab->id;
}
return false;
}
protected function getTabName($className = null)
{
$name = [];
foreach ($this->languageDataProvider->getLanguages() as $id_lang => $language) {
switch ($className) {
case self::PARENT_SHIPMENTS_TAB_NAME:
$name[$id_lang] = $this->module->l('InPost shipments', self::TRANSLATION_SOURCE, $language['locale']);
break;
case self::SHIPMENTS_CONTROLLER_NAME:
$name[$id_lang] = $this->shopContext->is17()
? $this->module->l('Confirmed shipments', self::TRANSLATION_SOURCE, $language['locale'])
: $this->module->l('InPost shipments', self::TRANSLATION_SOURCE, $language['locale']);
break;
case self::DISPATCH_ORDERS_CONTROLLER_NAME:
$name[$id_lang] = $this->module->l('Dispatch orders', self::TRANSLATION_SOURCE, $language['locale']);
break;
case self::SENT_SHIPMENTS_CONTROLLER_NAME:
$name[$id_lang] = $this->module->l('Sent shipments', self::TRANSLATION_SOURCE, $language['locale']);
break;
case self::DISPATCH_POINT_CONTROLLER_NAME:
$name[$id_lang] = $this->module->l('InPost Dispatch Points', self::TRANSLATION_SOURCE, $language['locale']);
break;
default:
$name[$id_lang] = $this->module->name;
break;
}
}
return $name;
}
}

View File

@@ -0,0 +1,32 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,65 @@
<?php
/**
* Copyright 2021-2022 InPost S.A.
*
* NOTICE OF LICENSE
*
* Licensed under the EUPL-1.2 or later.
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* It is also bundled with this package in the file LICENSE.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an AS IS basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions
* and limitations under the Licence.
*
* @author InPost S.A.
* @copyright 2021-2022 InPost S.A.
* @license https://joinup.ec.europa.eu/software/page/eupl
*/
namespace InPost\Shipping\Presenter;
use InPost\Shipping\Adapter\LinkAdapter;
use InPost\Shipping\Configuration\CarriersConfiguration;
use InPost\Shipping\ShipX\Resource\Service;
use InPostCarrierModel;
class CarrierPresenter
{
protected $link;
protected $carriersConfiguration;
public function __construct(LinkAdapter $link, CarriersConfiguration $carriersConfiguration)
{
$this->link = $link;
$this->carriersConfiguration = $carriersConfiguration;
}
public function present(InPostCarrierModel $inPostCarrier)
{
$carrier = $inPostCarrier->getCarrier();
return [
'id' => $inPostCarrier->id,
'service' => $inPostCarrier->service,
'cod' => (bool) $inPostCarrier->cod,
'weekendDelivery' => (bool) $inPostCarrier->weekend_delivery,
'defaultTemplate' => in_array($inPostCarrier->service, Service::LOCKER_SERVICES)
? $this->carriersConfiguration->getDefaultDimensionTemplates($inPostCarrier->service)
: null,
'defaultDimensions' => $this->carriersConfiguration->getDefaultShipmentDimensions($inPostCarrier->service),
'defaultSendingMethod' => $this->carriersConfiguration->getDefaultSendingMethods($inPostCarrier->service),
'useProductDimensions' => (bool) $inPostCarrier->use_product_dimensions,
'carrier' => $carrier->name,
'active' => (bool) $carrier->active,
'editUrl' => $this->link->getAdminLink('AdminCarrierWizard', true, [], [
'id_carrier' => $carrier->id,
]),
];
}
}

Some files were not shown because too many files have changed in this diff Show More