Add InPost Pay integration to admin templates

- Created a new template for the cart rule form with custom label, switch, and choice widgets.
- Implemented the InPost Pay block in the order details template for displaying delivery method, APM, and VAT invoice request.
- Added legacy support for the order details template to maintain compatibility with older PrestaShop versions.
This commit is contained in:
2025-09-14 14:38:09 +02:00
parent d895f86a03
commit 4066f6fa31
1086 changed files with 76598 additions and 6 deletions

View File

@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace InPost\Izi\Upgrade;
require_once __DIR__ . '/FileRemoverTrait.php';
trait AssetsRemoverTrait
{
use FileRemoverTrait;
private function removeStaleAssets(array $paths): bool
{
return $this->removeFiles(array_map(static function (string $path): string {
return 'views/' . $path;
}, $paths));
}
}

View File

@@ -0,0 +1,87 @@
<?php
declare(strict_types=1);
namespace InPost\Izi\Upgrade;
use Symfony\Component\Filesystem\Filesystem;
final class CacheClearer
{
/**
* @var Filesystem
*/
private $filesystem;
private $registered = false;
private static $instance;
private function __construct()
{
$this->filesystem = new Filesystem();
}
public static function getInstance(): self
{
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
public function clear(): void
{
if ($this->registered) {
return;
}
$this->registered = true;
$this->doClear();
}
private function doClear(): void
{
if (\Tools::version_compare(_PS_VERSION_, '1.7.1')) {
register_shutdown_function(function () {
$this->removeCacheDirectory('prod');
$this->removeCacheDirectory('dev');
});
return;
}
if (\Tools::version_compare(_PS_VERSION_, '8.0.0')) {
\Tools::clearSf2Cache('prod');
\Tools::clearSf2Cache('dev');
return;
}
if ('prod' !== _PS_ENV_) {
register_shutdown_function(function () {
$this->removeCacheDirectory('prod');
});
}
/* @see \Module::$_INSTANCE if not empty when dumping container metadata on PHP versions before 8.1, might cause the script to exceed memory limit
* in {@see \Symfony\Component\Config\Resource\ReflectionClassResource::generateSignature()} due to https://bugs.php.net/bug.php?id=80821 */
if (80100 > PHP_VERSION_ID) {
register_shutdown_function([\Module::class, 'resetStaticCache']);
}
\Tools::clearSf2Cache();
}
private function removeCacheDirectory(string $env): void
{
$dir = sprintf('%s/%s', dirname(_PS_CACHE_DIR_), $env);
$this->filesystem->remove($dir);
}
private function __clone()
{
}
}

View File

@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace InPost\Izi\Upgrade;
trait ConfigUpdaterTrait
{
/**
* @var \Db
*/
private $db;
private function getConfigDataByKeys(array $keys): array
{
$sql = (new \DbQuery())
->select('c.*')
->from('configuration', 'c')
->where(sprintf('c.name IN ("%s")', implode('","', $keys)));
return $this->db->executeS($sql) ?: [];
}
private function groupConfigValuesByShop(array $data): array
{
$dataByShopGroup = [];
foreach ($data as $row) {
$dataByShopGroup[(int) $row['id_shop_group']][(int) $row['id_shop']][$row['name']] = $row['value'];
}
return $dataByShopGroup;
}
private function setJsonConfigValues(string $key, array $dataByShopGroup): bool
{
foreach ($dataByShopGroup as $shopGroupId => $dataByShop) {
foreach ($dataByShop as $shopId => $data) {
$value = json_encode($data);
if (!\Configuration::updateValue($key, $value, false, $shopGroupId, $shopId)) {
return false;
}
}
}
return true;
}
private function deleteConfigurationByKeys(array $keys): bool
{
return $this->db->delete('configuration', 'name IN ("' . implode('","', $keys) . '")');
}
}

View File

@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
namespace InPost\Izi\Upgrade;
use Symfony\Component\Filesystem\Filesystem;
/**
* @internal
*/
trait FileRemoverTrait
{
private static $namespacePrefix = 'izi\\prestashop\\';
/**
* @var \Module
*/
private $module;
/**
* @var Filesystem
*/
private $filesystem;
private function removeFiles(array $paths): bool
{
$basePath = rtrim($this->module->getLocalPath(), '/');
$files = array_map(static function (string $path) use ($basePath): string {
return sprintf('%s/%s', $basePath, $path);
}, $paths);
$this->getFileSystem()->remove($files);
return true;
}
private function removeClasses(array $classes): bool
{
$paths = array_map(static function (string $class): string {
$class = str_replace(self::$namespacePrefix, '', $class);
return 'src/' . str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
}, $classes);
return $this->removeFiles($paths);
}
private function getFileSystem(): Filesystem
{
return $this->filesystem ?? $this->filesystem = new Filesystem();
}
}

View File

@@ -0,0 +1,75 @@
<?php
use InPost\Izi\Upgrade\AssetsRemoverTrait;
use InPost\Izi\Upgrade\CacheClearer;
use izi\prestashop\Hook\Common\ActionObjectOrderUpdateAfter;
use izi\prestashop\Hook\Common\ActionObjectOrderUpdateBefore;
if (!defined('_PS_VERSION_')) {
exit;
}
require_once __DIR__ . '/CacheClearer.php';
require_once __DIR__ . '/AssetsRemoverTrait.php';
class InPostIziUpdater_1_10_0
{
use AssetsRemoverTrait;
private const STALE_ASSETS = [
'js/prestashopizi.58c5a80572557c0d225d.js',
'js/prestashopizi.58c5a80572557c0d225d.js.map',
];
public function __construct(Module $module)
{
$this->module = $module;
}
public function upgrade(): bool
{
CacheClearer::getInstance()->clear();
return $this->registerHooks()
&& $this->initCodPaymentOrderStateConfig()
&& $this->removeStaleAssets(self::STALE_ASSETS);
}
private function registerHooks(): bool
{
$hooks = [
ActionObjectOrderUpdateBefore::HOOK_NAME,
ActionObjectOrderUpdateAfter::HOOK_NAME,
];
return $this->module->registerHook($hooks);
}
private function initCodPaymentOrderStateConfig(): bool
{
if (0 >= $orderStateId = $this->getCodPaymentOrderStateId()) {
return true;
}
return \Configuration::updateGlobalValue('INPOST_PAY_COD_OS_ID', $orderStateId);
}
private function getCodPaymentOrderStateId(): int
{
$orderStateId = (int) Configuration::get('PS_OS_COD_VALIDATION');
if (Validate::isLoadedObject(new OrderState($orderStateId))) {
return $orderStateId;
}
return (int) Configuration::get('INPOST_PAY_INITIAL_OS_ID');
}
}
/**
* @param InPostIzi $module
*/
function upgrade_module_1_10_0(Module $module): bool
{
return (new InPostIziUpdater_1_10_0($module))->upgrade();
}

View File

@@ -0,0 +1,65 @@
<?php
use InPost\Izi\Upgrade\CacheClearer;
use izi\prestashop\Configuration\Adapter\Configuration;
use izi\prestashop\Database\Connection;
use izi\prestashop\Hook\Admin\ActionAdminCartRuleSaveAfter;
use izi\prestashop\Hook\Admin\ActionAdminControllerSetMedia;
use izi\prestashop\Hook\Admin\DisplayBackOfficeHeader;
use izi\prestashop\Installer\Database\Version_1_11_0;
use izi\prestashop\Installer\DatabaseInstaller;
if (!defined('_PS_VERSION_')) {
exit;
}
require_once __DIR__ . '/CacheClearer.php';
class InPostIziUpdater_1_11_0
{
/**
* @var Module
*/
private $module;
/**
* @var DatabaseInstaller
*/
private $installer;
public function __construct(Module $module, DatabaseInstaller $installer)
{
$this->module = $module;
$this->installer = $installer;
}
public function upgrade(): bool
{
CacheClearer::getInstance()->clear();
$this->installer->install($this->module);
return $this->registerHooks();
}
private function registerHooks(): bool
{
return $this->module->registerHook([
ActionAdminCartRuleSaveAfter::HOOK_NAME,
ActionAdminControllerSetMedia::HOOK_NAME,
DisplayBackOfficeHeader::HOOK_NAME,
]);
}
}
/**
* @param InPostIzi $module
*/
function upgrade_module_1_11_0(Module $module): bool
{
$db = Db::getInstance();
$dbInstaller = new DatabaseInstaller(new Configuration($db), [
new Version_1_11_0(new Connection($db)),
]);
return (new InPostIziUpdater_1_11_0($module, $dbInstaller))->upgrade();
}

View File

@@ -0,0 +1,30 @@
<?php
if (!defined('_PS_VERSION_')) {
exit;
}
/**
* @param InPostIzi $module
*
* @return bool
*/
function upgrade_module_1_3_15(Module $module)
{
foreach (['INPOST_PAY_payment_courier', 'INPOST_PAY_payment_courier_cod'] as $key) {
if (!$carrierId = Configuration::get($key)) {
continue;
}
$carrier = new Carrier($carrierId);
if (!Configuration::updateValue($key, $carrier->id_reference)) {
return false;
}
}
return $module->registerHook('displayPaymentReturn')
&& $module->registerHook('actionAjaxDieCartControllerDisplayAjaxUpdateBefore')
&& $module->unregisterHook('actionPresentCart')
&& $module->unregisterHook('actionCartUpdateQuantityBefore');
}

View File

@@ -0,0 +1,41 @@
<?php
use izi\prestashop\Configuration\Adapter\Configuration;
use izi\prestashop\Database\Connection;
use izi\prestashop\Installer\Database\Version_1_4_0;
use izi\prestashop\Installer\DatabaseInstaller;
use izi\prestashop\View\Widget\Variant;
if (!defined('_PS_VERSION_')) {
exit;
}
/**
* @param InPostIzi $module
*
* @return bool
*/
function upgrade_module_1_4_0(Module $module)
{
$db = Db::getInstance();
$migration = new Version_1_4_0(new Connection($db));
$dbInstaller = new DatabaseInstaller(new Configuration(), [$migration]);
$db->delete('configuration', 'name LIKE "INPOST_PAY_status_translation_%"');
$db->execute(sprintf('
UPDATE `%sconfiguration`
SET `value` = (`value` = "dark")
WHERE `name` IN ("INPOST_PAY_background_cart", "INPOST_PAY_background_details")
', _DB_PREFIX_));
$db->execute(sprintf('
UPDATE `%sconfiguration`
SET `value` = IF(`value` = "yellow", "%s", "%s")
WHERE `name` IN ("INPOST_PAY_variant_cart", "INPOST_PAY_variant_details")
', _DB_PREFIX_, Variant::Primary()->value, Variant::Secondary()->value));
$dbInstaller->install($module);
return $module->registerHook('actionObjectCartDeleteBefore')
&& $module->registerHook('actionObjectInPostShipmentModelUpdateBefore')
&& \Configuration::updateGlobalValue('INPOST_PAY_INITIAL_OS_ID', \Configuration::get('PS_OS_BANKWIRE'));
}

View File

@@ -0,0 +1,59 @@
<?php
use izi\prestashop\Hook\Front\DisplayPaymentReturn;
use izi\prestashop\Hook\Front\DisplayShoppingCart;
use izi\prestashop\Hook\Front\DisplayShoppingCartFooter;
use izi\prestashop\Hook\HookExecutor;
if (!defined('_PS_VERSION_')) {
exit;
}
/**
* @param InPostIzi $module
*
* @return bool
*/
function upgrade_module_1_4_1(Module $module)
{
$db = Db::getInstance();
$sql = (new DbQuery())
->select('c.*, cl.*')
->from('configuration', 'c')
->innerJoin('configuration_lang', 'cl', 'cl.id_configuration = c.id_configuration')
->where('c.name LIKE "INPOST_PAY_OS_DESCRIPTION_%"');
if ($data = $db->executeS($sql)) {
$configIds = [];
$mappings = [];
foreach ($data as $row) {
$configId = (int) $row['id_configuration'];
$configIds[$configId] = $configId;
if ('' === trim($row['value'])) {
continue;
}
$osId = (int) filter_var($row['name'], FILTER_SANITIZE_NUMBER_INT);
$mappings[(int) $row['id_shop_group']][(int) $row['id_shop']][(int) $row['id_lang']][$osId] = $row['value'];
}
foreach ($mappings as $shopGroupId => $mappingsByShop) {
foreach ($mappingsByShop as $shopId => $mappingsByLang) {
Configuration::updateValue('INPOST_PAY_OS_DESCRIPTION_MAP', array_map('json_encode', $mappingsByLang), false, $shopGroupId, $shopId);
}
}
$db->delete('configuration', 'id_configuration IN (' . implode(',', $configIds) . ')');
$db->delete('configuration_lang', 'id_configuration IN (' . implode(',', $configIds) . ')');
}
Configuration::updateGlobalValue('INPOST_PAY_THANK_YOU_DISPLAY', DisplayPaymentReturn::getHookName());
return $module->unregisterHook('displayFooterProduct')
&& $module->unregisterHook(DisplayShoppingCart::HOOK_NAME)
&& $module->unregisterHook(DisplayShoppingCartFooter::HOOK_NAME)
&& $module->registerHook(HookExecutor::getHooksToInstall(_PS_VERSION_));
}

View File

@@ -0,0 +1,274 @@
<?php
use InPost\Izi\Upgrade\CacheClearer;
use InPost\Izi\Upgrade\ConfigUpdaterTrait;
use izi\prestashop\Common\Basket\ConsentRequirementType;
use izi\prestashop\Common\BindingPlace;
use izi\prestashop\Configuration\DTO\Consent;
use izi\prestashop\Configuration\DTO\ConsentLink;
use izi\prestashop\Configuration\DTO\HtmlStyles;
use izi\prestashop\View\Widget\FrameStyle;
use izi\prestashop\View\Widget\Variant;
use izi\prestashop\View\Widget\WidgetConfiguration;
if (!defined('_PS_VERSION_')) {
exit;
}
require_once __DIR__ . '/ConfigUpdaterTrait.php';
require_once __DIR__ . '/CacheClearer.php';
class InPostIziUpdater_1_5_0
{
use ConfigUpdaterTrait;
private const CART_WIDGET_CONFIG_MAP = [
'INPOST_PAY_background_cart' => 'darkMode',
'INPOST_PAY_variant_cart' => 'variant',
'INPOST_PAY_frame_style_cart' => 'frameStyle',
'INPOST_PAY_min_width_cart' => 'minWidthPx',
'INPOST_PAY_max_width_cart' => 'maxWidthPx',
];
private const PRODUCT_WIDGET_CONFIG_MAP = [
'INPOST_PAY_alignment_details' => 'alignment',
'INPOST_PAY_background_details' => 'darkMode',
'INPOST_PAY_variant_details' => 'variant',
'INPOST_PAY_frame_style_details' => 'frameStyle',
'INPOST_PAY_min_width_details' => 'minWidthPx',
'INPOST_PAY_max_width_details' => 'maxWidthPx',
];
private const CART_STYLES_CONFIG_MAP = [
'INPOST_PAY_margin_cart_up' => 'marginTop',
'INPOST_PAY_margin_cart_left' => 'marginLeft',
'INPOST_PAY_margin_cart_right' => 'marginRight',
'INPOST_PAY_margin_cart_down' => 'marginBottom',
'INPOST_PAY_alignment_cart' => 'alignment',
];
private const PRODUCT_STYLES_CONFIG_MAP = [
'INPOST_PAY_alignment_details' => 'alignment',
];
/**
* @var Db
*/
private $db;
public function __construct(Db $db)
{
$this->db = $db;
}
public function upgrade(): bool
{
CacheClearer::getInstance()->clear();
return $this->updateEnabledConfigValue()
&& $this->updateConsentStructure()
&& $this->updateWidgetConfigStructure();
}
private function updateEnabledConfigValue(): bool
{
return $this->db->execute(sprintf('
UPDATE `%sconfiguration`
SET `value` = (`value` = 2)
WHERE `name` = "INPOST_PAY_show_izi"
', _DB_PREFIX_));
}
private function updateConsentStructure(): bool
{
$consentsByShopGroup = [];
$configIds = [];
$languageIds = Language::getLanguages(false, false, true);
$requirementTypes = [
'additional' => ConsentRequirementType::Optional(),
'required' => ConsentRequirementType::RequiredAlways(),
'required_once' => ConsentRequirementType::RequiredOnce(),
];
foreach ($requirementTypes as $key => $requirementType) {
$cmsIdsKey = sprintf('INPOST_PAY_terms_options_%s', $key);
$textKey = sprintf('%s_text', $cmsIdsKey);
$sql = (new DbQuery())
->select('c.*')
->from('configuration', 'c')
->where(sprintf('c.name IN ("%s", "%s")', $cmsIdsKey, $textKey));
$data = $this->db->executeS($sql);
if ([] === $data) {
continue;
}
$dataByShopGroup = $this->groupConfigValuesByShop($data, $configIds);
foreach ($dataByShopGroup as $shopGroupId => $dataByShop) {
foreach ($dataByShop as $shopId => $data) {
$cmsPageIds = explode(',', $data[$cmsIdsKey]);
$text = trim($data[$textKey]);
if ('' === $text) {
continue;
}
$descriptions = [];
foreach ($languageIds as $languageId) {
$descriptions[$languageId] = $text;
}
$dateUpdated = DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $data['date_upd']);
foreach ($cmsPageIds as $index => $cmsPageId) {
if (0 >= $cmsPageId = (int) $cmsPageId) {
continue;
}
$consentsByShopGroup[$shopGroupId][$shopId][] = new Consent(
new ConsentLink((string) $index, $cmsPageId),
$descriptions,
$requirementType,
[],
$dateUpdated
);
}
}
}
}
if (!$this->setJsonConfigValues('INPOST_PAY_CONSENTS', $consentsByShopGroup)) {
return false;
}
if ([] === $configIds) {
return true;
}
return $this->db->delete('configuration', 'id_configuration IN (' . implode(',', $configIds) . ')');
}
private function updateWidgetConfigStructure(): bool
{
return $this->updateCartWidgetConfigStructure()
&& $this->updateProductWidgetConfigStructure();
}
private function updateCartWidgetConfigStructure(): bool
{
$configs = $this->getWidgetConfigs(self::CART_WIDGET_CONFIG_MAP, BindingPlace::BasketSummary());
$styles = $this->getWidgetStyles(self::CART_STYLES_CONFIG_MAP);
return $this->setJsonConfigValues('INPOST_PAY_CART_WIDGET_CONFIG', $configs)
&& $this->setJsonConfigValues('INPOST_PAY_CART_HTML_STYLES', $styles)
&& $this->deleteConfigurationByKeys(array_keys(array_merge(self::CART_WIDGET_CONFIG_MAP, self::CART_STYLES_CONFIG_MAP)));
}
private function updateProductWidgetConfigStructure(): bool
{
$configs = $this->getWidgetConfigs(self::PRODUCT_WIDGET_CONFIG_MAP, BindingPlace::ProductCard());
$styles = $this->getWidgetStyles(self::PRODUCT_STYLES_CONFIG_MAP);
return $this->setJsonConfigValues('INPOST_PAY_PRODUCT_CARD_WIDGET_CONFIG', $configs)
&& $this->setJsonConfigValues('INPOST_PAY_PRODUCT_HTML_STYLES', $styles)
&& $this->deleteConfigurationByKeys(array_keys(self::PRODUCT_WIDGET_CONFIG_MAP));
}
private function getWidgetConfigs(array $map, BindingPlace $bindingPlace): array
{
if ([] === $data = $this->getConfigDataByKeys(array_keys($map))) {
return [];
}
$dataByShopGroup = $this->groupConfigValuesByShop($data);
$configs = [];
foreach ($dataByShopGroup as $shopGroupId => $dataByShop) {
foreach ($dataByShop as $shopId => $data) {
$config = [];
foreach ($map as $key => $value) {
$config[$value] = $data[$key] ?? null;
}
$maxWidth = $this->getWidgetWidth((int) $config['maxWidthPx']);
$configs[$shopGroupId][$shopId] = (new WidgetConfiguration($bindingPlace))
->setVariant(Variant::tryFrom($config['variant']) ?? Variant::Secondary())
->setDarkMode((bool) $config['darkMode'])
->setFrameStyle(FrameStyle::tryFrom($config['frameStyle']))
->setMaxWidthPx($maxWidth);
}
}
return $configs;
}
private function getWidgetStyles(array $map): array
{
if ([] === $data = $this->getConfigDataByKeys(array_keys($map))) {
return [];
}
$dataByShopGroup = $this->groupConfigValuesByShop($data);
$styles = [];
foreach ($dataByShopGroup as $shopGroupId => $dataByShop) {
foreach ($dataByShop as $shopId => $data) {
$config = [];
foreach ($map as $key => $value) {
$config[$value] = $data[$key] ?? null;
}
$justifyContent = HtmlStyles::getJustifyContentStyleByAlignment($config['alignment'] ?? null);
$styles[$shopGroupId][$shopId] = (new HtmlStyles())
->setMarginTop($config['marginTop'] ?? null)
->setMarginLeft($config['marginLeft'] ?? null)
->setMarginRight($config['marginRight'] ?? null)
->setMarginBottom($config['marginBottom'] ?? null)
->setJustifyContent($justifyContent);
}
}
return $styles;
}
private function groupConfigValuesByShop(array $data, array &$configIds = []): array
{
$dataByShopGroup = [];
foreach ($data as $row) {
$dateUpdated = $dataByShopGroup[(int) $row['id_shop_group']][(int) $row['id_shop']]['date_upd'] ?? null;
$dataByShopGroup[(int) $row['id_shop_group']][(int) $row['id_shop']][$row['name']] = $row['value'];
if (null === $dateUpdated || $row['date_upd'] < $dateUpdated) {
$dataByShopGroup[(int) $row['id_shop_group']][(int) $row['id_shop']]['date_upd'] = $row['date_upd'];
}
$configIds[] = $row['id_configuration'];
}
return $dataByShopGroup;
}
private function getWidgetWidth(int $width): ?int
{
return WidgetConfiguration::WIDTH_MIN_PX <= $width && WidgetConfiguration::WIDTH_MAX_PX >= $width ? $width : null;
}
}
/**
* @param InPostIzi $module
*
* @return bool
*/
function upgrade_module_1_5_0(Module $module)
{
return (new InPostIziUpdater_1_5_0(Db::getInstance()))->upgrade();
}

View File

@@ -0,0 +1,212 @@
<?php
use InPost\Izi\Upgrade\CacheClearer;
use InPost\Izi\Upgrade\ConfigUpdaterTrait;
use izi\prestashop\Common\Delivery\DeliveryType;
use izi\prestashop\Common\Delivery\ServiceCode;
use izi\prestashop\Configuration\DTO\Shipping\CarrierMapping;
use izi\prestashop\Configuration\DTO\Shipping\ServiceOptions;
use izi\prestashop\Configuration\DTO\Shipping\ShippingOptions;
use izi\prestashop\Configuration\DTO\Shipping\TimeOfWeek;
use izi\prestashop\Configuration\DTO\Shipping\TimeOfWeekRange;
use izi\prestashop\Configuration\DTO\Shipping\WeekDay;
use izi\prestashop\Hook\Front\ActionGetPaymentOptions;
if (!defined('_PS_VERSION_')) {
exit;
}
require_once __DIR__ . '/ConfigUpdaterTrait.php';
require_once __DIR__ . '/CacheClearer.php';
class InPostIziUpdater_1_5_5
{
use ConfigUpdaterTrait;
private const APM_CONFIG_MAP = [
'INPOST_PAY_payment_apm' => 'mappingId',
'INPOST_PAY_payment_apm_cod' => 'services.COD.cost',
'INPOST_PAY_payment_apm_pww' => 'services.PWW.cost',
'INPOST_PAY_payment_apm_pww_from_day' => 'services.PWW.availability.start.day',
'INPOST_PAY_payment_apm_pww_from_time' => 'services.PWW.availability.start.time',
'INPOST_PAY_payment_apm_pww_to_day' => 'services.PWW.availability.end.day',
'INPOST_PAY_payment_apm_pww_to_time' => 'services.PWW.availability.end.time',
];
private const COURIER_CONFIG_MAP = [
'INPOST_PAY_payment_courier' => 'mappingId',
'INPOST_PAY_payment_courier_cod' => 'services.COD.cost',
];
private const UNMAPPED_CONFIG_KEYS = [
'INPOST_PAY_payment_apm_cod_from_day',
'INPOST_PAY_payment_apm_cod_from_time',
'INPOST_PAY_payment_apm_cod_to_day',
'INPOST_PAY_payment_apm_cod_to_time',
'INPOST_PAY_payment_courier_cod_from_day',
'INPOST_PAY_payment_courier_cod_to_day',
'INPOST_PAY_payment_courier_cod_from_time',
'INPOST_PAY_payment_courier_cod_to_time',
'INPOST_PAY_payment_courier_pww',
'INPOST_PAY_payment_courier_pww_from_day',
'INPOST_PAY_payment_courier_pww_to_day',
'INPOST_PAY_payment_courier_pww_from_time',
'INPOST_PAY_payment_courier_pww_to_time',
];
/**
* @var Db
*/
private $db;
/**
* @var Module
*/
private $module;
public function __construct(Db $db, Module $module)
{
$this->db = $db;
$this->module = $module;
}
public function upgrade(): bool
{
CacheClearer::getInstance()->clear();
if (!$this->updateShippingConfigStructure()) {
return false;
}
$this->module->unregisterHook(ActionGetPaymentOptions::HOOK_NAME);
return true;
}
private function updateShippingConfigStructure(): bool
{
return $this->updateApmShippingConfigStructure()
&& $this->updateCourierShippingConfigStructure()
&& $this->deleteConfigurationByKeys(self::UNMAPPED_CONFIG_KEYS);
}
private function updateApmShippingConfigStructure(): bool
{
$configs = $this->getShippingOptionsConfigs(self::APM_CONFIG_MAP, DeliveryType::Apm());
return $this->setJsonConfigValues('INPOST_PAY_APM_SHIPPING_OPTIONS', $configs)
&& $this->deleteConfigurationByKeys(array_keys(self::APM_CONFIG_MAP));
}
private function updateCourierShippingConfigStructure(): bool
{
$configs = $this->getShippingOptionsConfigs(self::COURIER_CONFIG_MAP, DeliveryType::Courier());
return $this->setJsonConfigValues('INPOST_PAY_COURIER_SHIPPING_OPTIONS', $configs)
&& $this->deleteConfigurationByKeys(array_keys(self::COURIER_CONFIG_MAP));
}
private function getShippingOptionsConfigs(array $map, DeliveryType $deliveryType): array
{
if ([] === $data = $this->getConfigDataByKeys(array_keys($map))) {
return [];
}
$shippingOptions = [];
$dataByShopGroup = $this->groupConfigValuesByShop($data);
foreach ($dataByShopGroup as $shopGroupId => $dataByShop) {
foreach ($dataByShop as $shopId => $data) {
$config = $this->reorganizeData($data, $map);
$shippingOptions[$shopGroupId][$shopId] = new ShippingOptions(
$this->getCarrierMappings($config['mappingId'], $deliveryType),
$this->getOptionalServices($config['services'], $deliveryType)
);
}
}
return $shippingOptions;
}
private function getCarrierMappings(?int $referenceId, DeliveryType $deliveryType): array
{
$mappings = [];
foreach (ServiceCode::getAvailableCombinations($deliveryType) as $serviceCodes) {
$mappings[] = new CarrierMapping($referenceId, $serviceCodes);
}
return $mappings;
}
private function getOptionalServices(array $config, DeliveryType $deliveryType): array
{
$services = [];
foreach ($deliveryType->getAvailableServiceCodes() as $serviceCode) {
$key = $serviceCode->value;
$services[] = $this->getServiceOptions($config[$key], $serviceCode);
}
return $services;
}
private function getServiceOptions(array $config, ServiceCode $serviceCode): ServiceOptions
{
return new ServiceOptions(
$serviceCode,
isset($config['cost']) ? (float) $config['cost'] : null,
$serviceCode->isAvailabilityTimeDependent() ? $this->getTimeRange($config['availability']) : null
);
}
private function getTimeRange(array $config): TimeOfWeekRange
{
return new TimeOfWeekRange(
$this->getTimeOfWeek($config['start']),
$this->getTimeOfWeek($config['end'])
);
}
private function getTimeOfWeek(array $config): TimeOfWeek
{
$weekDay = isset($config['day']) ? WeekDay::tryFrom($config['day'] + 1) : null;
$time = isset($config['time'])
? DateTimeImmutable::createFromFormat('G', (int) $config['time'])
: null;
return new TimeOfWeek($weekDay, $time);
}
private function reorganizeData(array $data, array $map): array
{
$config = [];
foreach ($map as $key => $path) {
$value = $data[$key] ?? null;
if (false === strpos($path, '.')) {
$config[$path] = $value;
} else {
$path = explode('.', $path);
while ($part = array_pop($path)) {
$value = [$part => $value];
}
$config = array_merge_recursive($config, $value);
}
}
return $config;
}
}
/**
* @param InPostIzi $module
*
* @return bool
*/
function upgrade_module_1_5_5(Module $module)
{
return (new InPostIziUpdater_1_5_5(Db::getInstance(), $module))->upgrade();
}

View File

@@ -0,0 +1,19 @@
<?php
if (!defined('_PS_VERSION_')) {
exit;
}
/**
* @param InPostIzi $module
*
* @return bool
*/
function upgrade_module_1_5_7(Module $module)
{
if (Tools::version_compare(_PS_VERSION_, '1.7.5')) {
Media::clearCache();
}
return true;
}

View File

@@ -0,0 +1,148 @@
<?php
use InPost\Izi\Upgrade\AssetsRemoverTrait;
use InPost\Izi\Upgrade\CacheClearer;
use InPost\Izi\Upgrade\ConfigUpdaterTrait;
use izi\prestashop\Common\PaymentType;
use izi\prestashop\Hook\Admin\DisplayAdminOrderLeft;
use izi\prestashop\Hook\Common\ActionCartUpdateAfter;
use izi\prestashop\Hook\Common\ActionOrderStatusPostUpdate;
use izi\prestashop\Hook\Front\DisplayCheckoutSummaryTop;
use izi\prestashop\Hook\Front\DisplayCustomerAccountFormTop;
use izi\prestashop\Hook\Front\DisplayCustomerLoginFormAfter;
use izi\prestashop\Hook\Front\DisplayIziCartPreviewButton;
use izi\prestashop\Hook\Front\DisplayIziCheckoutButton;
use izi\prestashop\Hook\Front\DisplayProductActions;
use izi\prestashop\Hook\Front\DisplayProductAdditionalInfo;
if (!defined('_PS_VERSION_')) {
exit;
}
require_once __DIR__ . '/ConfigUpdaterTrait.php';
require_once __DIR__ . '/CacheClearer.php';
require_once __DIR__ . '/AssetsRemoverTrait.php';
class InPostIziUpdater_1_6_0
{
use ConfigUpdaterTrait;
use AssetsRemoverTrait;
public function __construct(Db $db, Module $module)
{
$this->db = $db;
$this->module = $module;
}
public function upgrade(): bool
{
CacheClearer::getInstance()->clear();
return $this->registerHooks()
&& $this->updateAvailablePaymentOptionsConfig()
&& $this->removeStaleAssets([
'js/prestashopizi.js',
]);
}
private function registerHooks(): bool
{
$productCardHook = $this->getDefaultProductCardHook();
if (!Configuration::updateGlobalValue('INPOST_PAY_PRODUCT_CARD_DISPLAY_HOOK', $productCardHook)) {
return false;
}
return $this->module->unregisterHook('actionCartSave')
&& $this->module->registerHook($this->getHooksToInstall());
}
private function getDefaultProductCardHook(): string
{
if (
DisplayProductActions::getVersionRange()->contains(_PS_VERSION_)
&& !$this->module->isRegisteredInHook(DisplayProductAdditionalInfo::HOOK_NAME)
) {
return DisplayProductActions::HOOK_NAME;
}
return DisplayProductAdditionalInfo::HOOK_NAME;
}
private function updateAvailablePaymentOptionsConfig(): bool
{
$map = [
'INPOST_PAY_payment_inpost' => [PaymentType::CashOnDelivery()],
'INPOST_PAY_payment_aion' => [
PaymentType::Card(),
PaymentType::CardToken(),
PaymentType::GooglePay(),
PaymentType::ApplePay(),
PaymentType::BlikCode(),
PaymentType::BlikToken(),
PaymentType::PayByLink(),
PaymentType::ShoppingLimit(),
],
];
$configs = $this->getAvailablePaymentOptionsConfigs($map);
return $this->setJsonConfigValues('INPOST_PAY_AVAILABLE_PAYMENT_OPTIONS', $configs)
&& $this->deleteConfigurationByKeys(array_keys($map));
}
private function getAvailablePaymentOptionsConfigs(array $map): array
{
if ([] === $data = $this->getConfigDataByKeys(array_keys($map))) {
return [];
}
$paymentOptions = [];
$dataByShopGroup = $this->groupConfigValuesByShop($data);
foreach ($dataByShopGroup as $shopGroupId => $dataByShop) {
foreach ($dataByShop as $shopId => $data) {
if ([] === $data = array_filter($data)) {
continue;
}
$types = [];
foreach ($data as $key => $ignored) {
$types[] = $map[$key];
}
$paymentOptions[$shopGroupId][$shopId] = array_merge(...$types);
}
}
return $paymentOptions;
}
private function getHooksToInstall(): array
{
$hooks = [
DisplayCustomerLoginFormAfter::HOOK_NAME,
DisplayCustomerAccountFormTop::HOOK_NAME,
DisplayCheckoutSummaryTop::HOOK_NAME,
DisplayIziCartPreviewButton::HOOK_NAME,
DisplayIziCheckoutButton::HOOK_NAME,
ActionCartUpdateAfter::HOOK_NAME,
ActionOrderStatusPostUpdate::HOOK_NAME,
];
if (DisplayAdminOrderLeft::getVersionRange()->contains(_PS_VERSION_)) {
$hooks[] = DisplayAdminOrderLeft::HOOK_NAME;
}
return $hooks;
}
}
/**
* @param InPostIzi $module
*/
function upgrade_module_1_6_0(Module $module): bool
{
return (new InPostIziUpdater_1_6_0(Db::getInstance(), $module))->upgrade();
}

View File

@@ -0,0 +1,83 @@
<?php
use InPost\Izi\Upgrade\AssetsRemoverTrait;
use InPost\Izi\Upgrade\CacheClearer;
use InPost\Izi\Upgrade\ConfigUpdaterTrait;
if (!defined('_PS_VERSION_')) {
exit;
}
require_once __DIR__ . '/CacheClearer.php';
require_once __DIR__ . '/ConfigUpdaterTrait.php';
require_once __DIR__ . '/AssetsRemoverTrait.php';
class InPostIziUpdater_1_7_0
{
use ConfigUpdaterTrait;
use AssetsRemoverTrait;
private const STALE_ASSETS = [
'js/prestashopizi.f8bd8f9189c554596cce.js',
'js/prestashopizi.f8bd8f9189c554596cce.js.map',
];
public function __construct(Db $db, Module $module)
{
$this->db = $db;
$this->module = $module;
}
public function upgrade(): bool
{
CacheClearer::getInstance()->clear();
return $this->fixAvailablePaymentOptionsConfig()
&& $this->removeStaleAssets(self::STALE_ASSETS);
}
private function fixAvailablePaymentOptionsConfig(): bool
{
$configs = $this->getAvailablePaymentOptionsConfigs();
return $this->setJsonConfigValues('INPOST_PAY_AVAILABLE_PAYMENT_OPTIONS', $configs);
}
private function getAvailablePaymentOptionsConfigs(): array
{
if ([] === $data = $this->getConfigDataByKeys(['INPOST_PAY_AVAILABLE_PAYMENT_OPTIONS'])) {
return [];
}
$configs = [];
$dataByShopGroup = $this->groupConfigValuesByShop($data);
foreach ($dataByShopGroup as $shopGroupId => $dataByShop) {
foreach ($dataByShop as $shopId => $data) {
if (null === $value = $data['INPOST_PAY_AVAILABLE_PAYMENT_OPTIONS']) {
continue;
}
$data = json_decode($value, true);
if (!is_array($data) || $data === $config = array_values($data)) {
continue;
}
$configs[$shopGroupId][$shopId] = $config;
}
}
return $configs;
}
}
/**
* @param InPostIzi $module
*/
function upgrade_module_1_7_0(Module $module): bool
{
$db = Db::getInstance();
return (new InPostIziUpdater_1_7_0($db, $module))->upgrade();
}

View File

@@ -0,0 +1,19 @@
<?php
use InPost\Izi\Upgrade\CacheClearer;
if (!defined('_PS_VERSION_')) {
exit;
}
require_once __DIR__ . '/CacheClearer.php';
/**
* @param InPostIzi $module
*/
function upgrade_module_1_7_1(Module $module): bool
{
CacheClearer::getInstance()->clear();
return true;
}

View File

@@ -0,0 +1,19 @@
<?php
use InPost\Izi\Upgrade\CacheClearer;
if (!defined('_PS_VERSION_')) {
exit;
}
require_once __DIR__ . '/CacheClearer.php';
/**
* @param InPostIzi $module
*/
function upgrade_module_1_8_0(Module $module): bool
{
CacheClearer::getInstance()->clear();
return true;
}

View File

@@ -0,0 +1,60 @@
<?php
use InPost\Izi\Upgrade\AssetsRemoverTrait;
use InPost\Izi\Upgrade\CacheClearer;
use InPost\Izi\Upgrade\ConfigUpdaterTrait;
use izi\prestashop\Configuration\Adapter\Configuration;
use izi\prestashop\Database\Connection;
use izi\prestashop\Installer\Database\Version_1_9_0;
use izi\prestashop\Installer\DatabaseInstaller;
if (!defined('_PS_VERSION_')) {
exit;
}
require_once __DIR__ . '/CacheClearer.php';
require_once __DIR__ . '/ConfigUpdaterTrait.php';
require_once __DIR__ . '/AssetsRemoverTrait.php';
class InPostIziUpdater_1_9_0
{
use ConfigUpdaterTrait;
use AssetsRemoverTrait;
private const STALE_ASSETS = [
'js/prestashopizi.972421cbefe1f8bf3243.js',
'js/prestashopizi.972421cbefe1f8bf3243.js.map',
];
/**
* @var DatabaseInstaller
*/
private $installer;
public function __construct(Module $module, DatabaseInstaller $installer)
{
$this->module = $module;
$this->installer = $installer;
}
public function upgrade(): bool
{
CacheClearer::getInstance()->clear();
$this->installer->install($this->module);
return $this->removeStaleAssets(self::STALE_ASSETS);
}
}
/**
* @param InPostIzi $module
*/
function upgrade_module_1_9_0(Module $module): bool
{
$db = Db::getInstance();
$dbInstaller = new DatabaseInstaller(new Configuration($db), [
new Version_1_9_0(new Connection($db)),
]);
return (new InPostIziUpdater_1_9_0($module, $dbInstaller))->upgrade();
}

View File

@@ -0,0 +1,230 @@
<?php
use InPost\Izi\Upgrade\AssetsRemoverTrait;
use InPost\Izi\Upgrade\CacheClearer;
use InPost\Izi\Upgrade\ConfigUpdaterTrait;
use izi\prestashop\Common\BindingPlace;
use izi\prestashop\Configuration\Adapter\Configuration;
use izi\prestashop\Configuration\DTO\HtmlStyles;
use izi\prestashop\Configuration\GuiConfiguration;
use izi\prestashop\Database\Connection;
use izi\prestashop\Installer\Database\Version_2_0_0;
use izi\prestashop\Installer\DatabaseInstaller;
if (!defined('_PS_VERSION_')) {
exit;
}
require_once __DIR__ . '/AssetsRemoverTrait.php';
require_once __DIR__ . '/ConfigUpdaterTrait.php';
require_once __DIR__ . '/CacheClearer.php';
class InPostIziUpdater_2_0_0
{
use AssetsRemoverTrait;
use ConfigUpdaterTrait;
private const STALE_ASSETS = [
'js/prestashopizi.109989890fd3720148dc.js',
'css/product.6f69cd7d93f20866f321.css',
];
private const CLASSES_TO_REMOVE = [
izi\prestashop\Command\BindBasketCommand::class,
izi\prestashop\Handler\BindBasketHandlerInterface::class,
izi\prestashop\Handler\BindBasketHandler::class,
izi\prestashop\Handler\Result\BasketBindingResult::class,
izi\prestashop\Command\GenerateDeepLinkCommand::class,
izi\prestashop\Handler\GenerateDeepLinkHandlerInterface::class,
izi\prestashop\Handler\GenerateDeepLinkHandler::class,
izi\prestashop\Handler\Result\DeepLink::class,
izi\prestashop\Command\GetBindingConfirmationCommand::class,
izi\prestashop\Handler\GetBindingConfirmationHandlerInterface::class,
izi\prestashop\Handler\GetBindingConfirmationHandler::class,
izi\prestashop\Handler\Result\BindingConfirmationStream::class,
izi\prestashop\Command\GetClientDetailsCommand::class,
izi\prestashop\Handler\GetClientDetailsHandlerInterface::class,
izi\prestashop\Handler\GetClientDetailsHandler::class,
izi\prestashop\Command\GetOrderEventsCommand::class,
izi\prestashop\Handler\GetOrderEventsHandlerInterface::class,
izi\prestashop\Handler\GetOrderEventsHandler::class,
izi\prestashop\Handler\Result\OrderEvent::class,
izi\prestashop\Handler\Result\OrderEventStream::class,
izi\prestashop\Command\GetProductWidgetCommand::class,
izi\prestashop\Handler\GetProductWidgetHandlerInterface::class,
izi\prestashop\Handler\GetProductWidgetHandler::class,
izi\prestashop\Handler\Result\ProductWidgetResult::class,
izi\prestashop\Hook\Common\ActionCartSave::class,
izi\prestashop\BasketApp\Basket\Request\BindingMethod::class,
izi\prestashop\BasketApp\Basket\Request\BindingRequest::class,
izi\prestashop\BasketApp\Basket\Request\Browser::class,
izi\prestashop\BasketApp\Basket\Response\QrCode::class,
izi\prestashop\BasketApp\Basket\Response\UpsertBasketResponse::class,
izi\prestashop\BasketApp\Browser\BrowserApiClientInterface::class,
izi\prestashop\BasketApp\Exception\BrowserNotFoundException::class,
izi\prestashop\Hook\WidgetRenderer::class,
izi\prestashop\Hook\WidgetConfigurationResolver::class,
izi\prestashop\View\Widget\Alignment::class,
izi\prestashop\View\Widget\Language::class,
izi\prestashop\View\Widget\Configuration::class,
izi\prestashop\Form\Type\Widget\WidgetAlignmentChoiceType::class,
izi\prestashop\CartSession::class,
izi\prestashop\Environment\UatEnvironment::class,
izi\prestashop\Twig\Loader\TemplateNameMappingLoaderDecoratorTrait::class,
];
private const FILES_TO_REMOVE = [
'lib/',
'classes/',
'controllers/front/cart.php',
'views/templates/hook/buttonWidget.tpl',
'views/templates/hook/productButtonWidget.tpl',
'views/templates/hook/widget.tpl',
'views/templates/hook/backend.tpl',
'views/templates/hook/admin_order_left.tpl',
];
/**
* @var DatabaseInstaller
*/
private $installer;
public function __construct(Module $module, DatabaseInstaller $installer, Db $db)
{
$this->module = $module;
$this->installer = $installer;
$this->db = $db;
}
public function upgrade(): bool
{
CacheClearer::getInstance()->clear();
$this->installer->install($this->module);
return $this->updateGuiConfiguration()
&& $this->removeStaleAssets(self::STALE_ASSETS)
&& $this->removeClasses(self::CLASSES_TO_REMOVE)
&& $this->removeFiles(self::FILES_TO_REMOVE);
}
private function updateGuiConfiguration(): bool
{
$result = true;
foreach ($this->getConfigurableBindingPlaces() as $bindingPlace) {
$result &= $this->updateStylesConfig($bindingPlace);
}
return (bool) $result;
}
/**
* Method may not exist if the previous version of the file was already included (e.g., during recompilation of the container)
* before unpacking a new version of the module.
*/
private function getConfigurableBindingPlaces(): array
{
if (method_exists(GuiConfiguration::class, 'getConfigurableBindingPlaces')) {
return GuiConfiguration::getConfigurableBindingPlaces();
}
return [
BindingPlace::BasketSummary(),
BindingPlace::ProductCard(),
BindingPlace::LoginPage(),
BindingPlace::RegisterFormPage(),
BindingPlace::CheckoutPage(),
BindingPlace::MiniCartPage(),
BindingPlace::OrderCreate(),
];
}
private function updateStylesConfig(BindingPlace $bindingPlace): bool
{
$data = $this->getConfigDataByKeys([
$widgetConfigKey = self::getWidgetConfigKey($bindingPlace),
$stylesConfigKey = self::getHtmlStylesConfigKey($bindingPlace),
]);
if ([] === $data) {
return true;
}
$dataByShopGroup = $this->groupConfigValuesByShop($data);
$newWidgetConfigs = [];
$newStyles = [];
foreach ($dataByShopGroup as $shopGroupId => $dataByShop) {
foreach ($dataByShop as $shopId => $data) {
if (null === $widgetConfig = $data[$widgetConfigKey] ?? null) {
continue;
}
$widgetConfig = json_decode($widgetConfig, true);
if (!is_array($widgetConfig) || !isset($widgetConfig['alignment'])) {
continue;
}
if (isset($data[$stylesConfigKey])) {
$stylesConfig = json_decode($data[$stylesConfigKey], true) ?? [];
} else {
$stylesConfig = [];
}
$stylesConfig['justifyContent'] = HtmlStyles::getJustifyContentStyleByAlignment($widgetConfig['alignment']);
unset($widgetConfig['alignment'], $widgetConfig['basket'], $widgetConfig['minWidthPx']);
$newStyles[$shopGroupId][$shopId] = $stylesConfig;
$newWidgetConfigs[$shopGroupId][$shopId] = $widgetConfig;
}
}
return $this->setJsonConfigValues($widgetConfigKey, $newWidgetConfigs)
&& $this->setJsonConfigValues($stylesConfigKey, $newStyles);
}
private static function getWidgetConfigKey(BindingPlace $bindingPlace): string
{
if (BindingPlace::BasketSummary() === $bindingPlace) {
return 'INPOST_PAY_CART_WIDGET_CONFIG';
}
return 'INPOST_PAY_' . $bindingPlace->value . '_WIDGET_CONFIG';
}
private static function getHtmlStylesConfigKey(BindingPlace $bindingPlace): string
{
if (BindingPlace::BasketSummary() === $bindingPlace) {
return 'INPOST_PAY_CART_HTML_STYLES';
}
if (BindingPlace::ProductCard() === $bindingPlace) {
return 'INPOST_PAY_PRODUCT_HTML_STYLES';
}
return 'INPOST_PAY_' . $bindingPlace->value . '_HTML_STYLES';
}
}
/**
* @param InPostIzi $module
*/
function upgrade_module_2_0_0(Module $module): bool
{
if (Tools::version_compare(_PS_VERSION_, '1.7.1')) {
try {
$module->uninstall();
} finally {
return false;
}
}
$db = Db::getInstance();
$dbInstaller = new DatabaseInstaller(new Configuration($db), [
new Version_2_0_0(new Connection($db)),
]);
return (new InPostIziUpdater_2_0_0($module, $dbInstaller, $db))->upgrade();
}

View File

@@ -0,0 +1,36 @@
<?php
use InPost\Izi\Upgrade\AssetsRemoverTrait;
if (!defined('_PS_VERSION_')) {
exit;
}
require_once __DIR__ . '/AssetsRemoverTrait.php';
class InPostIziUpdater_2_0_2
{
use AssetsRemoverTrait;
private const STALE_ASSETS = [
'js/front/v2.bcd9fca64e00b4978766.js',
];
public function __construct(Module $module)
{
$this->module = $module;
}
public function upgrade(): bool
{
return $this->removeStaleAssets(self::STALE_ASSETS);
}
}
/**
* @param InPostIzi $module
*/
function upgrade_module_2_0_2(Module $module): bool
{
return (new InPostIziUpdater_2_0_2($module))->upgrade();
}

View File

@@ -0,0 +1,91 @@
<?php
use InPost\Izi\Upgrade\CacheClearer;
use izi\prestashop\Configuration\Adapter\Configuration;
use izi\prestashop\Database\Connection;
use izi\prestashop\Hook\Common\Product as ProductHooks;
use izi\prestashop\Installer\Database\Version_2_1_0;
use izi\prestashop\Installer\DatabaseInstaller;
if (!defined('_PS_VERSION_')) {
exit;
}
require_once __DIR__ . '/CacheClearer.php';
class InPostIziUpdater_2_1_0
{
/**
* @var Module
*/
private $module;
/**
* @var DatabaseInstaller
*/
private $installer;
/**
* @var Db
*/
private $db;
public function __construct(Module $module, DatabaseInstaller $installer, Db $db)
{
$this->module = $module;
$this->installer = $installer;
$this->db = $db;
}
public static function create(Module $module): self
{
$db = Db::getInstance();
$dbInstaller = new DatabaseInstaller(new Configuration($db), [
new Version_2_1_0(new Connection($db)),
]);
return new self($module, $dbInstaller, $db);
}
public function upgrade(): bool
{
CacheClearer::getInstance()->clear();
$this->installer->install($this->module);
return $this->registerHooks()
&& $this->renameCartRulesConfigKey();
}
private function registerHooks(): bool
{
return $this->module->registerHook([
ProductHooks\ActionProductDeleteBefore::HOOK_NAME,
ProductHooks\ActionProductDeleteAfter::HOOK_NAME,
ProductHooks\ActionProductUpdateAfter::HOOK_NAME,
ProductHooks\ActionCombinationDeleteBefore::HOOK_NAME,
ProductHooks\ActionCombinationDeleteAfter::HOOK_NAME,
ProductHooks\ActionCombinationUpdateAfter::HOOK_NAME,
ProductHooks\ActionImageAddAfter::HOOK_NAME,
ProductHooks\ActionImageDeleteAfter::HOOK_NAME,
ProductHooks\ActionSpecificPriceAddAfter::HOOK_NAME,
ProductHooks\ActionSpecificPriceUpdateAfter::HOOK_NAME,
ProductHooks\ActionSpecificPriceDeleteAfter::HOOK_NAME,
ProductHooks\ActionUpdateQuantity::HOOK_NAME,
]);
}
private function renameCartRulesConfigKey(): bool
{
return $this->db->update('configuration', [
'name' => 'INPOST_PAY_HAS_OMNIBUS_CART_RULES',
], 'name = "INPOST_PAY_OMNIBUS_CART_RULE_ID"');
}
}
/**
* @param InPostIzi $module
*/
function upgrade_module_2_1_0(Module $module): bool
{
return InPostIziUpdater_2_1_0::create($module)->upgrade();
}

View File

@@ -0,0 +1,73 @@
<?php
use InPost\Izi\Upgrade\CacheClearer;
use izi\prestashop\Configuration\Adapter\Configuration;
use izi\prestashop\Database\Connection;
use izi\prestashop\Hook\Admin\ActionAdminInPostConfirmedShipmentsControllerAfter;
use izi\prestashop\Hook\Admin\ActionAdminInPostConfirmedShipmentsControllerBefore;
use izi\prestashop\Hook\Common\ActionEmailSendBefore;
use izi\prestashop\Hook\Front\DisplayHeader;
use izi\prestashop\Installer\Database\Version_2_2_0;
use izi\prestashop\Installer\DatabaseInstaller;
if (!defined('_PS_VERSION_')) {
exit;
}
require_once __DIR__ . '/CacheClearer.php';
class InPostIziUpdater_2_2_0
{
/**
* @var Module
*/
private $module;
/**
* @var DatabaseInstaller
*/
private $installer;
public function __construct(Module $module, DatabaseInstaller $installer)
{
$this->module = $module;
$this->installer = $installer;
}
public static function create(Module $module): self
{
$db = Db::getInstance();
$dbInstaller = new DatabaseInstaller(new Configuration($db), [
new Version_2_2_0(new Connection($db)),
]);
return new self($module, $dbInstaller);
}
public function upgrade(): bool
{
CacheClearer::getInstance()->clear();
$this->installer->install($this->module);
return $this->registerHooks();
}
private function registerHooks(): bool
{
return $this->module->registerHook([
ActionEmailSendBefore::HOOK_NAME,
ActionAdminInPostConfirmedShipmentsControllerAfter::HOOK_NAME,
ActionAdminInPostConfirmedShipmentsControllerBefore::HOOK_NAME,
DisplayHeader::HOOK_NAME,
]);
}
}
/**
* @param InPostIzi $module
*/
function upgrade_module_2_2_0(Module $module): bool
{
return InPostIziUpdater_2_2_0::create($module)->upgrade();
}

View File

@@ -0,0 +1,119 @@
<?php
use InPost\Izi\Upgrade\CacheClearer;
use InPost\Izi\Upgrade\ConfigUpdaterTrait;
use izi\prestashop\BasketApp\BasketAppClientInterface;
use izi\prestashop\BasketApp\Payment\PaymentsApiClientInterface;
use izi\prestashop\Common\PaymentType;
use izi\prestashop\Enum\Enum;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
if (!defined('_PS_VERSION_')) {
exit;
}
require_once __DIR__ . '/CacheClearer.php';
require_once __DIR__ . '/ConfigUpdaterTrait.php';
class InPostIziUpdater_2_2_2
{
use ConfigUpdaterTrait;
/**
* @var PaymentsApiClientInterface|null
*/
private $client;
public function __construct(Db $db, ?PaymentsApiClientInterface $client)
{
CacheClearer::getInstance()->clear();
$this->db = $db;
$this->client = $client;
}
public static function create(Module $module): self
{
$db = Db::getInstance();
try {
$client = $module->get(BasketAppClientInterface::class);
} catch (ServiceNotFoundException $e) {
$client = null;
}
return new self($db, $client);
}
public function upgrade(): bool
{
return $this->updatePaymentOptionsConfig();
}
private function updatePaymentOptionsConfig(): bool
{
if (null === $this->client || !$clientId = \Configuration::get('INPOST_PAY_client_id')) {
return true;
}
try {
$availableTypes = $this->client->getAvailablePaymentOptions()->getPaymentTypes();
} catch (\Exception $e) {
return true;
}
$data = $this->getConfigDataByKeys([
'INPOST_PAY_client_id',
'INPOST_PAY_AVAILABLE_PAYMENT_OPTIONS',
]);
$dataByShopGroup = $this->groupConfigValuesByShop($data);
foreach ($dataByShopGroup as $shopGroupId => $dataByShop) {
foreach ($dataByShop as $shopId => $data) {
if (!isset($data['INPOST_PAY_AVAILABLE_PAYMENT_OPTIONS'])) {
continue;
}
if ($clientId !== $this->resolveClientId($dataByShopGroup, $shopGroupId, $shopId)) {
continue;
}
$enabledTypes = $this->decodePaymentTypesList($data['INPOST_PAY_AVAILABLE_PAYMENT_OPTIONS']);
$value = [] === array_udiff($availableTypes, $enabledTypes, [Enum::class, 'compareValues']);
if (!\Configuration::updateValue('INPOST_PAY_ENABLE_ALL_PAYMENT_OPTIONS', (int) $value, false, $shopGroupId, $shopId)) {
return false;
}
}
}
return true;
}
private function resolveClientId(array $config, int $shopGroupId, int $shopId): ?string
{
return $config[$shopGroupId][$shopId]['INPOST_PAY_client_id']
?? $config[$shopGroupId][0]['INPOST_PAY_client_id']
?? $config[0][0]['INPOST_PAY_client_id']
?? null;
}
private function decodePaymentTypesList(string $value): array
{
$data = json_decode($value, true);
if (!is_array($data)) {
return [];
}
return array_filter(array_map([PaymentType::class, 'tryFrom'], $data));
}
}
/**
* @param InPostIzi $module
*/
function upgrade_module_2_2_2(Module $module): bool
{
return InPostIziUpdater_2_2_2::create($module)->upgrade();
}