diff --git a/.github/workflows/release-publish.yml b/.github/workflows/release-publish.yml index 8106cff6..d31ede76 100644 --- a/.github/workflows/release-publish.yml +++ b/.github/workflows/release-publish.yml @@ -141,14 +141,12 @@ jobs: cc <@france.berut> <@khadija.cherif> - name: Send changelog to Slack - uses: slackapi/slack-github-action@v1.27.0 + uses: slackapi/slack-github-action@v2.0.0 with: - channel-id: CR9C57YM6 - slack-message: ${{ steps.slack-markdown-release-notes.outputs.text }} + method: chat.postMessage + token: ${{ secrets.SLACK_RELEASE_CHANGELOG_BOT_TOKEN }} payload: | - { - "username": "${{ github.event.sender.login }}", - "icon_url": "${{ github.event.sender.avatar_url }}" - } - env: - SLACK_BOT_TOKEN: ${{ secrets.SLACK_RELEASE_CHANGELOG_BOT_TOKEN }} + channel: CR9C57YM6 + username: "${{ github.event.sender.login }}" + icon_url: "${{ github.event.sender.avatar_url }}" + text: ${{ toJson(steps.slack-markdown-release-notes.outputs.text) }} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1e12d7ef..0212944c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -2,7 +2,7 @@ # See https://pre-commit.com/hooks.html for more hooks repos: - repo: https://github.com/commitizen-tools/commitizen - rev: v3.30.1 + rev: v4.0.0 hooks: - id: commitizen name: Check commit message format @@ -39,7 +39,7 @@ repos: stages: [commit] - repo: https://github.com/returntocorp/semgrep - rev: v1.96.0 + rev: v1.97.0 hooks: - id: semgrep args: diff --git a/CHANGELOG.md b/CHANGELOG.md index eba1d829..721a97e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## v4.6.0 - 2024-12-10 + +### Changes + +### 馃殌 New Features + +- feat: Product analytics for plugin performance (#587) + +### 馃悰 Bug Fixes + +- fix: Custom Description for payment button credit (#614) + +#### Contributors + +@Benjamin-Freoua-Alma, @alma-renovate-bot, @alma-renovate-bot[bot], @github-actions and @remi-zuffinetti + ## v4.5.0 - 2024-11-13 ### Changes diff --git a/alma/alma.php b/alma/alma.php index 5a5ff224..fbcbec84 100644 --- a/alma/alma.php +++ b/alma/alma.php @@ -30,7 +30,7 @@ class Alma extends PaymentModule { - const VERSION = '4.5.0'; + const VERSION = '4.6.0'; const PS_ACCOUNTS_VERSION_REQUIRED = '5.3.0'; public $_path; @@ -81,7 +81,7 @@ public function __construct() { $this->name = 'alma'; $this->tab = 'payments_gateways'; - $this->version = '4.5.0'; + $this->version = '4.6.0'; $this->author = 'Alma'; $this->need_instance = false; $this->bootstrap = true; diff --git a/alma/composer.json b/alma/composer.json index 72b1b29f..c902dafb 100644 --- a/alma/composer.json +++ b/alma/composer.json @@ -11,7 +11,7 @@ }, "require": { "php": "^5.6 || ~7.0 || ~7.1 || ~7.2 || ~7.3 || ~7.4 || ~8.0 || ~8.1", - "alma/alma-php-client": "^2.2.0", + "alma/alma-php-client": "^2.3.1", "ext-json": "*", "ext-openssl": "*", "prestashop/prestashop-accounts-installer": "^v1.0.4", diff --git a/alma/controllers/front/cmsdataexport.php b/alma/controllers/front/cmsdataexport.php new file mode 100644 index 00000000..f4f773a7 --- /dev/null +++ b/alma/controllers/front/cmsdataexport.php @@ -0,0 +1,134 @@ + + * @copyright 2018-2024 Alma SAS + * @license https://opensource.org/licenses/MIT The MIT License + */ + +use Alma\API\Entities\MerchantData\CmsFeatures; +use Alma\API\Entities\MerchantData\CmsInfo; +use Alma\API\Lib\PayloadFormatter; +use Alma\PrestaShop\Builders\Helpers\SettingsHelperBuilder; +use Alma\PrestaShop\Exceptions\CmsDataException; +use Alma\PrestaShop\Exceptions\ValidateException; +use Alma\PrestaShop\Helpers\CmsDataHelper; +use Alma\PrestaShop\Helpers\SettingsHelper; +use Alma\PrestaShop\Helpers\ValidateHelper; +use Alma\PrestaShop\Traits\AjaxTrait; + +if (!defined('_PS_VERSION_')) { + exit; +} + +/** + * AlmaCmsDataExportModuleFrontController + */ +class AlmaCmsDataExportModuleFrontController extends ModuleFrontController +{ + use AjaxTrait; + + /** + * @var ValidateHelper + */ + protected $validateHelper; + /** + * @var \Alma\PrestaShop\Helpers\SettingsHelper + */ + protected $settingsHelper; + /** + * @var \Alma\API\Lib\PayloadFormatter + */ + protected $payloadFormatter; + /** + * @var CmsDataHelper + */ + protected $cmsDataHelper; + + public function __construct() + { + parent::__construct(); + $this->validateHelper = new ValidateHelper(); + $this->cmsDataHelper = new CmsDataHelper(); + $this->settingsHelper = (new SettingsHelperBuilder())->getInstance(); + $this->payloadFormatter = new PayloadFormatter(); + } + + /** + * @throws \Alma\PrestaShop\Exceptions\CmsDataException + * @throws \PrestaShopException + */ + public function postProcess() + { + parent::postProcess(); + try { + $this->validateHelper->checkSignature($this->settingsHelper->getIdMerchant(), SettingsHelper::getActiveAPIKey(), $_SERVER['HTTP_X_ALMA_SIGNATURE']); + } catch (ValidateException $e) { + throw new CmsDataException('[Alma] checkSignature - ' . $e->getMessage()); + } catch (\Exception $e) { + throw new CmsDataException('[Alma] Get Merchant Id - ' . $e->getMessage()); + } + + $cmsInfo = new CmsInfo($this->cmsDataHelper->getCmsInfoArray()); + $cmsFeature = new CmsFeatures($this->cmsDataHelper->getCmsFeatureArray()); + + $payload = $this->payloadFormatter->formatConfigurationPayload($cmsInfo, $cmsFeature); + $this->ajaxRenderAndExit(json_encode($payload)); + } + + /** + * @param $validateHelper + * + * @return void + */ + public function setValidateHelper($validateHelper) + { + $this->validateHelper = $validateHelper; + } + + /** + * @param $settingsHelper + * + * @return void + */ + public function setSettingsHelper($settingsHelper) + { + $this->settingsHelper = $settingsHelper; + } + + /** + * @param $payloadFormatter + * + * @return void + */ + public function setPayloadFormatter($payloadFormatter) + { + $this->payloadFormatter = $payloadFormatter; + } + + /** + * @param $cmsDataHelper + * + * @return void + */ + public function setCmsDataHelper($cmsDataHelper) + { + $this->cmsDataHelper = $cmsDataHelper; + } +} diff --git a/alma/controllers/hook/GetContentHookController.php b/alma/controllers/hook/GetContentHookController.php index 9c1bd9fa..783b4a3d 100644 --- a/alma/controllers/hook/GetContentHookController.php +++ b/alma/controllers/hook/GetContentHookController.php @@ -29,8 +29,10 @@ } use Alma\API\Entities\Merchant; +use Alma\API\Lib\IntegrationsConfigurationsUtils; use Alma\API\RequestError; use Alma\PrestaShop\Builders\Helpers\ApiHelperBuilder; +use Alma\PrestaShop\Builders\Helpers\ContextHelperBuilder; use Alma\PrestaShop\Builders\Helpers\CustomFieldHelperBuilder; use Alma\PrestaShop\Builders\Helpers\PriceHelperBuilder; use Alma\PrestaShop\Builders\Helpers\SettingsHelperBuilder; @@ -51,7 +53,9 @@ use Alma\PrestaShop\Helpers\ApiHelper; use Alma\PrestaShop\Helpers\ApiKeyHelper; use Alma\PrestaShop\Helpers\ClientHelper; +use Alma\PrestaShop\Helpers\CmsDataHelper; use Alma\PrestaShop\Helpers\ConstantsHelper; +use Alma\PrestaShop\Helpers\ContextHelper; use Alma\PrestaShop\Helpers\CustomFieldsHelper; use Alma\PrestaShop\Helpers\MediaHelper; use Alma\PrestaShop\Helpers\PriceHelper; @@ -69,7 +73,7 @@ final class GetContentHookController extends AdminHookController /** @var ApiKeyHelper */ private $apiKeyHelper; - /** @var Alma */ + /** @var \Module */ protected $module; /** @@ -97,6 +101,11 @@ final class GetContentHookController extends AdminHookController */ protected $hasKey; + /** + * @var ContextHelper + */ + protected $contextHelper; + /** * @var array */ @@ -178,6 +187,9 @@ public function __construct($module) $mediaHelperBuilder = new MediaHelperBuilder(); $this->mediaHelper = $mediaHelperBuilder->getInstance(); + $contextHelperBuilder = new ContextHelperBuilder(); + $this->contextHelper = $contextHelperBuilder->getInstance(); + $this->hasKey = false; parent::__construct($module); @@ -250,8 +262,8 @@ public function processConfiguration() } // Down here, we know the provided API keys are correct (at least the one for the chosen API mode) - $this->setKeyIfValueIsNotObscur($liveKey, ALMA_MODE_LIVE); - $this->setKeyIfValueIsNotObscur($testKey, ALMA_MODE_TEST); + $this->setKeyIfValueIsNotObscure($liveKey, ALMA_MODE_LIVE); + $this->setKeyIfValueIsNotObscure($testKey, ALMA_MODE_TEST); // Try to get merchant from configured API key/mode try { @@ -421,20 +433,25 @@ public function processConfiguration() return $credentialsError['message']; } + if (IntegrationsConfigurationsUtils::isUrlRefreshRequired($this->settingsHelper->getKey(CmsDataHelper::ALMA_CMSDATA_DATE))) { + $this->apiHelper->sendUrlForGatherCmsData($this->contextHelper->getModuleLink('cmsdataexport', [], true)); + $this->settingsHelper->updateKey(CmsDataHelper::ALMA_CMSDATA_DATE, time()); + } + $this->context->smarty->clearAssign('validation_error'); return $this->module->display($this->module->file, 'getContent.tpl'); } /** - * Check if Api key are obscur. + * Check if Api key are obscure. * * @param string $apiKey * @param string $mode * * @return void */ - private function setKeyIfValueIsNotObscur($apiKey, $mode) + private function setKeyIfValueIsNotObscure($apiKey, $mode) { if (ConstantsHelper::OBSCURE_VALUE === $apiKey) { return; diff --git a/alma/exceptions/CmsDataException.php b/alma/exceptions/CmsDataException.php new file mode 100644 index 00000000..a1d531c7 --- /dev/null +++ b/alma/exceptions/CmsDataException.php @@ -0,0 +1,33 @@ + + * @copyright 2018-2024 Alma SAS + * @license https://opensource.org/licenses/MIT The MIT License + */ + +namespace Alma\PrestaShop\Exceptions; + +if (!defined('_PS_VERSION_')) { + exit; +} + +class CmsDataException extends AlmaException +{ +} diff --git a/alma/exceptions/ValidateException.php b/alma/exceptions/ValidateException.php new file mode 100644 index 00000000..21c5e9f8 --- /dev/null +++ b/alma/exceptions/ValidateException.php @@ -0,0 +1,33 @@ + + * @copyright 2018-2024 Alma SAS + * @license https://opensource.org/licenses/MIT The MIT License + */ + +namespace Alma\PrestaShop\Exceptions; + +if (!defined('_PS_VERSION_')) { + exit; +} + +class ValidateException extends AlmaException +{ +} diff --git a/alma/lib/Builders/Helpers/SettingsHelperBuilder.php b/alma/lib/Builders/Helpers/SettingsHelperBuilder.php index 7bce0da2..2b17f4f7 100644 --- a/alma/lib/Builders/Helpers/SettingsHelperBuilder.php +++ b/alma/lib/Builders/Helpers/SettingsHelperBuilder.php @@ -45,7 +45,10 @@ public function getInstance() { return new SettingsHelper( $this->getShopHelper(), - $this->getConfigurationHelper() + $this->getConfigurationHelper(), + $this->getCategoryFactory(), + $this->getContextFactory(), + $this->getValidateHelper() ); } } diff --git a/alma/lib/Factories/CartFactory.php b/alma/lib/Factories/CartFactory.php index e8c44a57..41a8b391 100644 --- a/alma/lib/Factories/CartFactory.php +++ b/alma/lib/Factories/CartFactory.php @@ -33,21 +33,6 @@ */ class CartFactory { - /** - * @var \Cart - */ - protected $cart; - - /** - * @param \Cart|null $cart - */ - public function __construct($cart = null) - { - if ($cart !== null) { - $this->cart = $cart; - } - } - /** * @param int $id * diff --git a/alma/lib/Factories/CategoryFactory.php b/alma/lib/Factories/CategoryFactory.php new file mode 100644 index 00000000..59b483db --- /dev/null +++ b/alma/lib/Factories/CategoryFactory.php @@ -0,0 +1,45 @@ + + * @copyright 2018-2024 Alma SAS + * @license https://opensource.org/licenses/MIT The MIT License + */ + +namespace Alma\PrestaShop\Factories; + +if (!defined('_PS_VERSION_')) { + exit; +} + +/** + * Class CategoryFactory. + */ +class CategoryFactory +{ + /** + * @param int $id + * + * @return \Category + */ + public function create($id = null, $idLang = null) + { + return new \Category($id, $idLang); + } +} diff --git a/alma/lib/Factories/ModuleFactory.php b/alma/lib/Factories/ModuleFactory.php index 8d4e915f..35928325 100644 --- a/alma/lib/Factories/ModuleFactory.php +++ b/alma/lib/Factories/ModuleFactory.php @@ -33,7 +33,8 @@ } /** - * Class ModuleFactory. + * @deprecated + * Class ModuleFactory */ class ModuleFactory { @@ -48,6 +49,8 @@ public function __construct($toolsHelper) } /** + * @deprecated Use getModule() in ModuleProxy instead + * * @return false|\Module */ public function getModule() @@ -56,6 +59,8 @@ public function getModule() } /** + * @deprecated + * * @return string */ public function getModuleName() @@ -70,6 +75,8 @@ public function getModuleName() } /** + * @deprecated + * * @return string|null */ public function getPathUri() @@ -90,6 +97,8 @@ public function getPathUri() * Otherwise, translation key will not match for Module library * when module is loaded with eval() Module::getModulesOnDisk() * + * @deprecated + * * @param string $string String to translate * @param bool|string $specific filename to use in translation key * @param string|null $locale Locale to translate to @@ -110,6 +119,8 @@ public function l($string, $specific = false, $locale = null) /** * Check if module is installed. * + * @deprecated Use isInstalled() in ModuleProxy instead + * * @param string $moduleName * * @return bool @@ -126,6 +137,8 @@ public function isInstalled($moduleName) /** * @codeCoverageIgnore * + * @deprecated + * * @param $moduleName * * @return bool @@ -138,6 +151,8 @@ public function isInstalledBefore17($moduleName) /** * @codeCoverageIgnore * + * @deprecated + * * @param $moduleName * * @return bool diff --git a/alma/lib/Forms/PnxAdminFormBuilder.php b/alma/lib/Forms/PnxAdminFormBuilder.php index 9592faa5..74335d1f 100644 --- a/alma/lib/Forms/PnxAdminFormBuilder.php +++ b/alma/lib/Forms/PnxAdminFormBuilder.php @@ -39,6 +39,7 @@ */ class PnxAdminFormBuilder extends AbstractAlmaAdminFormBuilder { + const ALMA_FEE_PLANS = 'ALMA_FEE_PLANS'; /** * @var SettingsHelper */ @@ -196,7 +197,7 @@ protected function configForm() protected function disableFeePlan($key, $installmentsPlans) { unset($installmentsPlans->$key); - SettingsHelper::updateValue('ALMA_FEE_PLANS', json_encode($installmentsPlans)); + SettingsHelper::updateValue(self::ALMA_FEE_PLANS, json_encode($installmentsPlans)); } /** diff --git a/alma/lib/Helpers/ApiHelper.php b/alma/lib/Helpers/ApiHelper.php index af4da786..18561022 100644 --- a/alma/lib/Helpers/ApiHelper.php +++ b/alma/lib/Helpers/ApiHelper.php @@ -28,6 +28,7 @@ use Alma\API\Entities\Merchant; use Alma\PrestaShop\Exceptions\ActivationException; use Alma\PrestaShop\Exceptions\ApiMerchantsException; +use Alma\PrestaShop\Exceptions\ClientException; use Alma\PrestaShop\Exceptions\InsuranceInstallException; use Alma\PrestaShop\Exceptions\WrongCredentialsException; use Alma\PrestaShop\Factories\ModuleFactory; @@ -75,14 +76,20 @@ class ApiHelper * @param ConfigurationHelper $configurationHelper * @param AdminInsuranceHelper $insuranceHelper */ - public function __construct($moduleFactory, $clientHelper, $toolsHelper, $insuranceService, $configurationHelper, $insuranceHelper) - { + public function __construct( + $moduleFactory, + $clientHelper, + $toolsHelper, + $insuranceService, + $configurationHelper, + $insuranceHelper + ) { $this->moduleFactory = $moduleFactory; - $this->insuranceHelper = $insuranceHelper; - $this->insuranceService = $insuranceService; - $this->configurationHelper = $configurationHelper; $this->clientHelper = $clientHelper; $this->toolsHelper = $toolsHelper; + $this->insuranceService = $insuranceService; + $this->configurationHelper = $configurationHelper; + $this->insuranceHelper = $insuranceHelper; } /** @@ -204,4 +211,23 @@ public function getPaymentEligibility($paymentData) return []; } + + /** + * @param string $url + * + * @return void + */ + public function sendUrlForGatherCmsData($url) + { + try { + $this->clientHelper->sendUrlForGatherCmsData($url); + } catch (ClientException $e) { + Logger::instance()->error( + sprintf( + '[Alma] Error sending URL for gather CMS data: %s', + $e->getMessage() + ) + ); + } + } } diff --git a/alma/lib/Helpers/ClientHelper.php b/alma/lib/Helpers/ClientHelper.php index ccbce3db..771d0516 100644 --- a/alma/lib/Helpers/ClientHelper.php +++ b/alma/lib/Helpers/ClientHelper.php @@ -177,4 +177,22 @@ public function getClientPaymentsEndpoint() { return $this->getAlmaClient()->payments; } + + /** + * @param string $url + * + * @throws \Alma\PrestaShop\Exceptions\ClientException + */ + public function sendUrlForGatherCmsData($url) + { + try { + $this->getAlmaClient()->configuration->sendIntegrationsConfigurationsUrl($url); + } catch (Alma\API\Exceptions\RequestException $e) { + throw new ClientException('[Alma] Error Request: ' . $e->getMessage()); + } catch (RequestError $e) { + throw new ClientException('[Alma] Error Request: ' . $e->getMessage()); + } catch (ClientException $e) { + throw new ClientException('[Alma] Error to get Alma Client: ' . $e->getMessage()); + } + } } diff --git a/alma/lib/Helpers/CmsDataHelper.php b/alma/lib/Helpers/CmsDataHelper.php new file mode 100644 index 00000000..70d12a10 --- /dev/null +++ b/alma/lib/Helpers/CmsDataHelper.php @@ -0,0 +1,176 @@ + + * @copyright 2018-2024 Alma SAS + * @license https://opensource.org/licenses/MIT The MIT License + */ + +namespace Alma\PrestaShop\Helpers; + +use Alma\API\Client; +use Alma\PrestaShop\Builders\Helpers\SettingsHelperBuilder; +use Alma\PrestaShop\Forms\CartEligibilityAdminFormBuilder; +use Alma\PrestaShop\Forms\DebugAdminFormBuilder; +use Alma\PrestaShop\Forms\InpageAdminFormBuilder; +use Alma\PrestaShop\Forms\PnxAdminFormBuilder; +use Alma\PrestaShop\Forms\ProductEligibilityAdminFormBuilder; +use Alma\PrestaShop\Model\AlmaModuleModel; +use Alma\PrestaShop\Model\ShopModel; + +if (!defined('_PS_VERSION_')) { + exit; +} + +class CmsDataHelper +{ + const ALMA_CMSDATA_DATE = 'ALMA_CMSDATA_DATE'; + /** + * @var ModuleHelper + */ + protected $moduleHelper; + /** + * @var ThemeHelper + */ + protected $themeHelper; + /** + * @var AlmaModuleModel + */ + protected $almaModuleModel; + /** + * @var SettingsHelper + */ + protected $settingsHelper; + /** + * @var ToolsHelper + */ + protected $toolsHelper; + /** + * @var ShopModel + */ + protected $shopModel; + + /** + * @param ModuleHelper $moduleHelper + * @param ThemeHelper $themeHelper + * @param AlmaModuleModel $almaModuleModel + * @param SettingsHelper $settingsHelper + * @param ToolsHelper $toolsHelper + * @param ShopModel $shopModel + */ + public function __construct( + $moduleHelper = null, + $themeHelper = null, + $almaModuleModel = null, + $settingsHelper = null, + $toolsHelper = null, + $shopModel = null + ) { + if (!$moduleHelper) { + $moduleHelper = new ModuleHelper(); + } + $this->moduleHelper = $moduleHelper; + + if (!$themeHelper) { + $themeHelper = new ThemeHelper(); + } + $this->themeHelper = $themeHelper; + + if (!$almaModuleModel) { + $almaModuleModel = new AlmaModuleModel(); + } + $this->almaModuleModel = $almaModuleModel; + + if (!$settingsHelper) { + $settingsHelper = (new SettingsHelperBuilder())->getInstance(); + } + $this->settingsHelper = $settingsHelper; + + if (!$toolsHelper) { + $toolsHelper = new ToolsHelper(); + } + $this->toolsHelper = $toolsHelper; + + if (!$shopModel) { + $shopModel = new ShopModel(); + } + $this->shopModel = $shopModel; + } + + /** + * @return array + */ + public function getCmsInfoArray() + { + return [ + 'cms_name' => 'Prestashop', + 'cms_version' => $this->toolsHelper->getPsVersion(), + 'third_parties_plugins' => $this->moduleHelper->getModuleList(), + 'themes' => $this->themeHelper->getThemeNameWithVersion(), + 'language_name' => 'PHP', + 'language_version' => phpversion(), + 'alma_plugin_version' => $this->almaModuleModel->getVersion(), + 'alma_sdk_name' => 'ALMA-PHP-CLIENT', + 'alma_sdk_version' => Client::VERSION, + ]; + } + + /** + * @return array + */ + public function getCmsFeatureArray() + { + return [ + 'alma_enabled' => (bool) (int) $this->settingsHelper->getKey(SettingsHelper::ALMA_FULLY_CONFIGURED), // clef fully configured + 'widget_cart_activated' => (bool) (int) $this->settingsHelper->getKey(CartEligibilityAdminFormBuilder::ALMA_SHOW_ELIGIBILITY_MESSAGE), + 'widget_product_activated' => (bool) (int) $this->settingsHelper->getKey(ProductEligibilityAdminFormBuilder::ALMA_SHOW_PRODUCT_ELIGIBILITY), + 'used_fee_plans' => $this->getUsedFeePlans(), + //'payment_method_position' => null, // not applicable - position is set in the used_fee_plans + 'in_page_activated' => (bool) (int) $this->settingsHelper->getKey(InpageAdminFormBuilder::ALMA_ACTIVATE_INPAGE), + 'log_activated' => (bool) (int) $this->settingsHelper->getKey(DebugAdminFormBuilder::ALMA_ACTIVATE_LOGGING), + 'excluded_categories' => $this->settingsHelper->getCategoriesExcludedNames(), + 'specific_features' => [], // no specific features in Prestashop + 'country_restriction' => $this->getCountriesRestrictions(), + 'custom_widget_css' => (bool) $this->settingsHelper->getKey(ProductEligibilityAdminFormBuilder::ALMA_WIDGET_POSITION_SELECTOR), + 'is_multisite' => $this->shopModel->isMultisite(), + ]; + } + + /** + * @return array + */ + private function getCountriesRestrictions() + { + return []; + } + + /** + * @return array|null + */ + private function getUsedFeePlans() + { + $feePlans = json_decode($this->settingsHelper->getKey(PnxAdminFormBuilder::ALMA_FEE_PLANS), true); + + if (empty($feePlans)) { + return null; + } + + return $feePlans; + } +} diff --git a/alma/lib/Helpers/ModuleHelper.php b/alma/lib/Helpers/ModuleHelper.php new file mode 100644 index 00000000..d6bfbdb0 --- /dev/null +++ b/alma/lib/Helpers/ModuleHelper.php @@ -0,0 +1,67 @@ + + * @copyright 2018-2024 Alma SAS + * @license https://opensource.org/licenses/MIT The MIT License + */ + +namespace Alma\PrestaShop\Helpers; + +use Alma\PrestaShop\Proxy\ModuleProxy; + +if (!defined('_PS_VERSION_')) { + exit; +} + +/** + * Class ModuleHelper. + */ +class ModuleHelper +{ + /** + * @var ModuleProxy + */ + protected $moduleProxy; + + public function __construct($moduleProxy = null) + { + if (!$moduleProxy) { + $moduleProxy = new ModuleProxy(); + } + $this->moduleProxy = $moduleProxy; + } + + /** + * @return array + */ + public function getModuleList() + { + $modules = []; + $modulesInstalled = $this->moduleProxy->getModulesInstalled(); + foreach ($modulesInstalled as $module) { + $modules[] = [ + 'name' => $module['name'], + 'version' => $module['version'], + ]; + } + + return $modules; + } +} diff --git a/alma/lib/Helpers/PaymentOptionHelper.php b/alma/lib/Helpers/PaymentOptionHelper.php index f580cec4..49c78b51 100644 --- a/alma/lib/Helpers/PaymentOptionHelper.php +++ b/alma/lib/Helpers/PaymentOptionHelper.php @@ -201,7 +201,7 @@ public function getTextsByTypes($installementCount, $duration, $isCredit, $isDef return $this->getTexts( $installementCount, PaymentButtonAdminFormBuilder::ALMA_PNX_AIR_BUTTON_TITLE, - PaymentButtonAdminFormBuilder::ALMA_PNX_BUTTON_DESC + PaymentButtonAdminFormBuilder::ALMA_PNX_AIR_BUTTON_DESC ); } if ($isDeferred) { diff --git a/alma/lib/Helpers/SettingsHelper.php b/alma/lib/Helpers/SettingsHelper.php index 762b13e6..76954b72 100644 --- a/alma/lib/Helpers/SettingsHelper.php +++ b/alma/lib/Helpers/SettingsHelper.php @@ -36,6 +36,9 @@ define('ALMA_MODE_LIVE', 'live'); } +use Alma\PrestaShop\Exceptions\AlmaException; +use Alma\PrestaShop\Factories\CategoryFactory; +use Alma\PrestaShop\Factories\ContextFactory; use Alma\PrestaShop\Forms\ApiAdminFormBuilder; use Alma\PrestaShop\Forms\ExcludedCategoryAdminFormBuilder; use Alma\PrestaShop\Forms\InpageAdminFormBuilder; @@ -48,6 +51,8 @@ */ class SettingsHelper { + const ALMA_FULLY_CONFIGURED = 'ALMA_FULLY_CONFIGURED'; + const ALMA_EXCLUDED_CATEGORIES = 'ALMA_EXCLUDED_CATEGORIES'; /** * @var ShopHelper */ @@ -57,15 +62,35 @@ class SettingsHelper * @var ConfigurationHelper */ protected $configurationHelper; + /** + * @var CategoryFactory + */ + protected $categoryFactory; + /** + * @var ContextFactory + */ + protected $contextFactory; + /** + * @var ValidateHelper + */ + protected $validateHelper; /** * @param ShopHelper $shopHelper * @param ConfigurationHelper $configurationHelper */ - public function __construct($shopHelper, $configurationHelper) - { + public function __construct( + $shopHelper, + $configurationHelper, + $categoryFactory, + $contextFactory, + $validateHelper + ) { $this->shopHelper = $shopHelper; $this->configurationHelper = $configurationHelper; + $this->categoryFactory = $categoryFactory; + $this->contextFactory = $contextFactory; + $this->validateHelper = $validateHelper; } /** @@ -172,7 +197,7 @@ public static function updateValue($configKey, $value) public static function deleteAllValues() { $configKeys = [ - 'ALMA_FULLY_CONFIGURED', + self::ALMA_FULLY_CONFIGURED, 'ALMA_ACTIVATE_LOGGING', ShareOfCheckoutAdminFormBuilder::ALMA_SHARE_OF_CHECKOUT_STATE, ShareOfCheckoutAdminFormBuilder::ALMA_SHARE_OF_CHECKOUT_DATE, @@ -220,6 +245,7 @@ public static function deleteAllValues() ConstantsHelper::ALMA_SHOW_INSURANCE_WIDGET_PRODUCT, ConstantsHelper::ALMA_SHOW_INSURANCE_WIDGET_CART, ConstantsHelper::ALMA_SHOW_INSURANCE_POPUP_CART, + CmsDataHelper::ALMA_CMSDATA_DATE, ]; foreach ($configKeys as $configKey) { @@ -234,7 +260,7 @@ public static function deleteAllValues() */ public static function isFullyConfigured() { - return (bool) (int) static::get('ALMA_FULLY_CONFIGURED', false); + return (bool) (int) static::get(self::ALMA_FULLY_CONFIGURED, false); } /** @@ -932,4 +958,30 @@ public function getDataFromKey($key) return $dataFromKey; } + + /** + * @return array + */ + public function getCategoriesExcludedNames() + { + $categories = $this->configurationHelper->get(self::ALMA_EXCLUDED_CATEGORIES); + if (!$categories) { + return []; + } + + $categoriesNames = []; + + foreach (json_decode($categories) as $id) { + try { + $category = $this->categoryFactory->create($id, $this->contextFactory->getContextLanguageId()); + } catch (AlmaException $e) { + $category = $this->categoryFactory->create($id); + } + if ($this->validateHelper->isLoadedObject($category) && $category->name !== null) { + $categoriesNames[] = $category->name; + } + } + + return $categoriesNames; + } } diff --git a/alma/lib/Helpers/ThemeHelper.php b/alma/lib/Helpers/ThemeHelper.php new file mode 100644 index 00000000..971caa7e --- /dev/null +++ b/alma/lib/Helpers/ThemeHelper.php @@ -0,0 +1,72 @@ + + * @copyright 2018-2024 Alma SAS + * @license https://opensource.org/licenses/MIT The MIT License + */ + +namespace Alma\PrestaShop\Helpers; + +use Alma\PrestaShop\Factories\ContextFactory; + +if (!defined('_PS_VERSION_')) { + exit; +} + +/** + * Class ThemeHelper. + */ +class ThemeHelper +{ + const CONFIG_THEME_FILE = _PS_THEME_DIR_ . 'config/theme.yml'; + /** + * @var ContextFactory + */ + protected $contextFactory; + /** + * @var ToolsHelper + */ + protected $toolsHelper; + + public function __construct() + { + $this->contextFactory = new ContextFactory(); + $this->toolsHelper = new ToolsHelper(); + } + + /** + * @return string + */ + public function getThemeNameWithVersion() + { + $themeName = $this->contextFactory->getContext()->shop->theme_name; + $themeConfigPath = self::CONFIG_THEME_FILE; + + if ($this->toolsHelper->psVersionCompare('1.7', '>=')) { + if (file_exists($themeConfigPath)) { + $themeConfig = \Symfony\Component\Yaml\Yaml::parseFile($themeConfigPath); + $themeVersion = $themeConfig['version'] ?: 'undefined'; + $themeName = $themeName . ' ' . $themeVersion; + } + } + + return $themeName; + } +} diff --git a/alma/lib/Helpers/ToolsHelper.php b/alma/lib/Helpers/ToolsHelper.php index 26c20a88..f93332d0 100644 --- a/alma/lib/Helpers/ToolsHelper.php +++ b/alma/lib/Helpers/ToolsHelper.php @@ -142,4 +142,14 @@ public function getJsonValues($array, $key) return json_encode($return); } + + /** + * Return _PS_VERSION_ + * + * @return string + */ + public function getPsVersion() + { + return _PS_VERSION_; + } } diff --git a/alma/lib/Helpers/ValidateHelper.php b/alma/lib/Helpers/ValidateHelper.php index 981d3e4c..100fec69 100644 --- a/alma/lib/Helpers/ValidateHelper.php +++ b/alma/lib/Helpers/ValidateHelper.php @@ -24,6 +24,9 @@ namespace Alma\PrestaShop\Helpers; +use Alma\API\Lib\RequestUtils; +use Alma\PrestaShop\Exceptions\ValidateException; + if (!defined('_PS_VERSION_')) { exit; } @@ -39,4 +42,29 @@ public function isLoadedObject($object) { return \Validate::isLoadedObject($object); } + + /** + * @param $externalId + * @param $apiKey + * @param $signature + * + * @return void + * + * @throws \Alma\PrestaShop\Exceptions\ValidateException + */ + public function checkSignature($externalId, $apiKey, $signature) + { + if (!$externalId) { + throw new ValidateException('[Alma] External ID is missing'); + } + if (!$apiKey) { + throw new ValidateException('[Alma] Api key is missing'); + } + if (!$signature) { + throw new ValidateException('[Alma] Signature is missing'); + } + if (!RequestUtils::isHmacValidated($externalId, $apiKey, $signature)) { + throw new ValidateException('[Alma] Signature is invalid'); + } + } } diff --git a/alma/lib/Model/AlmaModuleModel.php b/alma/lib/Model/AlmaModuleModel.php new file mode 100644 index 00000000..73d53c87 --- /dev/null +++ b/alma/lib/Model/AlmaModuleModel.php @@ -0,0 +1,66 @@ + + * @copyright 2018-2024 Alma SAS + * @license https://opensource.org/licenses/MIT The MIT License + */ + +namespace Alma\PrestaShop\Model; + +use Alma\PrestaShop\Helpers\ConstantsHelper; +use Alma\PrestaShop\Proxy\ModuleProxy; + +if (!defined('_PS_VERSION_')) { + exit; +} + +/** + * Class ModuleFactory. + */ +class AlmaModuleModel +{ + /** + * @var ModuleProxy + */ + private $moduleProxy; + private $moduleName = ConstantsHelper::ALMA_MODULE_NAME; + + public function __construct($moduleProxy = null) + { + if (!$moduleProxy) { + $moduleProxy = new ModuleProxy(); + } + $this->moduleProxy = $moduleProxy; + } + + /** + * @return string + */ + public function getVersion() + { + $module = $this->moduleProxy->getModule($this->moduleName); + + if ($module) { + return $this->moduleProxy->getModuleVersion($module); + } + + return ''; + } +} diff --git a/alma/lib/Model/ShopModel.php b/alma/lib/Model/ShopModel.php new file mode 100644 index 00000000..1e672914 --- /dev/null +++ b/alma/lib/Model/ShopModel.php @@ -0,0 +1,39 @@ + + * @copyright 2018-2024 Alma SAS + * @license https://opensource.org/licenses/MIT The MIT License + */ + +namespace Alma\PrestaShop\Model; + +if (!defined('_PS_VERSION_')) { + exit; +} +class ShopModel +{ + /** + * @return bool|null + */ + public function isMultisite() + { + return \Shop::isFeatureActive(); + } +} diff --git a/alma/lib/Proxy/ModuleProxy.php b/alma/lib/Proxy/ModuleProxy.php new file mode 100644 index 00000000..b7dd17a4 --- /dev/null +++ b/alma/lib/Proxy/ModuleProxy.php @@ -0,0 +1,121 @@ + + * @copyright 2018-2024 Alma SAS + * @license https://opensource.org/licenses/MIT The MIT License + */ + +namespace Alma\PrestaShop\Proxy; + +use Alma\PrestaShop\Helpers\ToolsHelper; +use PrestaShop\PrestaShop\Core\Addon\Module\ModuleManagerBuilder; + +if (!defined('_PS_VERSION_')) { + exit; +} + +class ModuleProxy +{ + /** + * @var ToolsHelper + */ + private $toolsHelper; + + /** + * @param $toolsHelper + */ + public function __construct($toolsHelper = null) + { + if (!$toolsHelper) { + $toolsHelper = new ToolsHelper(); + } + $this->toolsHelper = $toolsHelper; + } + + /** + * @return false|\Module + */ + public function getModule($moduleName) + { + return \Module::getInstanceByName($moduleName); + } + + /** + * @return array + */ + public function getModulesInstalled() + { + return \Module::getModulesInstalled(); + } + + /** + * Check if module is installed. + * + * @param string $moduleName + * + * @return bool + */ + public function isInstalled($moduleName) + { + if ($this->toolsHelper->psVersionCompare('1.7', '<')) { + return $this->isInstalledBefore17($moduleName); + } + + return $this->isInstalledAfter17($moduleName); + } + + /** + * @codeCoverageIgnore + * + * @deprecated use isInstalled instead + * + * @param $moduleName + * + * @return bool + */ + public function isInstalledBefore17($moduleName) + { + return (bool) \Module::isInstalled($moduleName); + } + + /** + * @codeCoverageIgnore + * + * @deprecated use isInstalled instead + * + * @param $moduleName + * + * @return bool + */ + public function isInstalledAfter17($moduleName) + { + return ModuleManagerBuilder::getInstance()->build()->isInstalled($moduleName); + } + + /** + * @param \Module $module + * + * @return string + */ + public function getModuleVersion($module) + { + return $module->version; + } +} diff --git a/alma/lib/Traits/BuilderTrait.php b/alma/lib/Traits/BuilderTrait.php index 96c1df6c..e31ab38a 100644 --- a/alma/lib/Traits/BuilderTrait.php +++ b/alma/lib/Traits/BuilderTrait.php @@ -28,6 +28,7 @@ use Alma\PrestaShop\Factories\AddressFactory; use Alma\PrestaShop\Factories\CarrierFactory; use Alma\PrestaShop\Factories\CartFactory; +use Alma\PrestaShop\Factories\CategoryFactory; use Alma\PrestaShop\Factories\CombinationFactory; use Alma\PrestaShop\Factories\ContextFactory; use Alma\PrestaShop\Factories\CurrencyFactory; @@ -206,7 +207,10 @@ public function getSettingsHelper($settingsHelper = null) return new SettingsHelper( $this->getShopHelper(), - $this->getConfigurationHelper() + $this->getConfigurationHelper(), + $this->getCategoryFactory(), + $this->getContextFactory(), + $this->getValidateHelper() ); } @@ -966,7 +970,10 @@ public function getFeePlanHelper($feePlanHelper = null) return new FeePlanHelper( new SettingsHelper( new ShopHelper(), - new ConfigurationHelper() + new ConfigurationHelper(), + new CategoryFactory(), + new ContextFactory(), + new ValidateHelper() ), new EligibilityFactory() ); @@ -1213,4 +1220,12 @@ public function getClientPaymentValidator() { return new PaymentValidator(); } + + /** + * @return CategoryFactory + */ + public function getCategoryFactory() + { + return new CategoryFactory(); + } } diff --git a/alma/tests/Unit/Builders/Helpers/EligibilityHelperBuilderTest.php b/alma/tests/Unit/Builders/Helpers/EligibilityHelperBuilderTest.php index 05e6c4cf..60077e46 100644 --- a/alma/tests/Unit/Builders/Helpers/EligibilityHelperBuilderTest.php +++ b/alma/tests/Unit/Builders/Helpers/EligibilityHelperBuilderTest.php @@ -25,6 +25,7 @@ namespace Alma\PrestaShop\Tests\Unit\Builders\Helpers; use Alma\PrestaShop\Builders\Helpers\EligibilityHelperBuilder; +use Alma\PrestaShop\Factories\CategoryFactory; use Alma\PrestaShop\Factories\ContextFactory; use Alma\PrestaShop\Helpers\ApiHelper; use Alma\PrestaShop\Helpers\CarrierHelper; @@ -38,6 +39,7 @@ use Alma\PrestaShop\Helpers\SettingsHelper; use Alma\PrestaShop\Helpers\ShopHelper; use Alma\PrestaShop\Helpers\ToolsHelper; +use Alma\PrestaShop\Helpers\ValidateHelper; use Alma\PrestaShop\Model\CarrierData; use PHPUnit\Framework\TestCase; @@ -88,7 +90,10 @@ public function setUp() $this->settingsHelper = new SettingsHelper( new ShopHelper(), - new ConfigurationHelper() + new ConfigurationHelper(), + new CategoryFactory(), + new ContextFactory(), + new ValidateHelper() ); $this->priceHelper = \Mockery::mock(PriceHelper::class); diff --git a/alma/tests/Unit/Builders/Helpers/PaymentOptionHelperBuilderTest.php b/alma/tests/Unit/Builders/Helpers/PaymentOptionHelperBuilderTest.php index 5d41d682..cc0795cc 100644 --- a/alma/tests/Unit/Builders/Helpers/PaymentOptionHelperBuilderTest.php +++ b/alma/tests/Unit/Builders/Helpers/PaymentOptionHelperBuilderTest.php @@ -25,6 +25,7 @@ namespace Alma\PrestaShop\Tests\Unit\Builders\Helpers; use Alma\PrestaShop\Builders\Helpers\PaymentOptionHelperBuilder; +use Alma\PrestaShop\Factories\CategoryFactory; use Alma\PrestaShop\Factories\ContextFactory; use Alma\PrestaShop\Factories\MediaFactory; use Alma\PrestaShop\Helpers\ConfigurationHelper; @@ -34,6 +35,7 @@ use Alma\PrestaShop\Helpers\PaymentOptionTemplateHelper; use Alma\PrestaShop\Helpers\SettingsHelper; use Alma\PrestaShop\Helpers\ShopHelper; +use Alma\PrestaShop\Helpers\ValidateHelper; use PHPUnit\Framework\TestCase; class PaymentOptionHelperBuilderTest extends TestCase @@ -53,7 +55,10 @@ public function setUp() $this->paymentOptionHelperBuilder = new PaymentOptionHelperBuilder(); $this->settingsHelper = new SettingsHelper( new ShopHelper(), - new ConfigurationHelper() + new ConfigurationHelper(), + new CategoryFactory(), + new ContextFactory(), + new ValidateHelper() ); } diff --git a/alma/tests/Unit/Builders/Models/PaymentDataBuilderTest.php b/alma/tests/Unit/Builders/Models/PaymentDataBuilderTest.php index 8953a255..ae1f2edd 100644 --- a/alma/tests/Unit/Builders/Models/PaymentDataBuilderTest.php +++ b/alma/tests/Unit/Builders/Models/PaymentDataBuilderTest.php @@ -25,6 +25,7 @@ namespace Alma\PrestaShop\Tests\Unit\Builders\Models; use Alma\PrestaShop\Builders\Models\PaymentDataBuilder; +use Alma\PrestaShop\Factories\CategoryFactory; use Alma\PrestaShop\Factories\ContextFactory; use Alma\PrestaShop\Helpers\AddressHelper; use Alma\PrestaShop\Helpers\CarrierHelper; @@ -40,6 +41,7 @@ use Alma\PrestaShop\Helpers\ShopHelper; use Alma\PrestaShop\Helpers\StateHelper; use Alma\PrestaShop\Helpers\ToolsHelper; +use Alma\PrestaShop\Helpers\ValidateHelper; use Alma\PrestaShop\Model\CarrierData; use Alma\PrestaShop\Model\CartData; use Alma\PrestaShop\Model\PaymentData; @@ -92,7 +94,10 @@ public function setUp() $this->settingsHelper = new SettingsHelper( new ShopHelper(), - new ConfigurationHelper() + new ConfigurationHelper(), + new CategoryFactory(), + new ContextFactory(), + new ValidateHelper() ); $this->priceHelper = \Mockery::mock(PriceHelper::class); diff --git a/alma/tests/Unit/Builders/Services/PaymentServiceBuilderTest.php b/alma/tests/Unit/Builders/Services/PaymentServiceBuilderTest.php index c58a8926..0f9a0f37 100644 --- a/alma/tests/Unit/Builders/Services/PaymentServiceBuilderTest.php +++ b/alma/tests/Unit/Builders/Services/PaymentServiceBuilderTest.php @@ -27,6 +27,7 @@ use Alma\PrestaShop\Builders\Factories\ModuleFactoryBuilder; use Alma\PrestaShop\Builders\Services\PaymentServiceBuilder; use Alma\PrestaShop\Factories\AddressFactory; +use Alma\PrestaShop\Factories\CategoryFactory; use Alma\PrestaShop\Factories\ContextFactory; use Alma\PrestaShop\Factories\ModuleFactory; use Alma\PrestaShop\Helpers\CarrierHelper; @@ -49,6 +50,7 @@ use Alma\PrestaShop\Helpers\ShopHelper; use Alma\PrestaShop\Helpers\ToolsHelper; use Alma\PrestaShop\Helpers\TranslationHelper; +use Alma\PrestaShop\Helpers\ValidateHelper; use Alma\PrestaShop\Model\CarrierData; use Alma\PrestaShop\Model\CartData; use Alma\PrestaShop\Repositories\ProductRepository; @@ -139,7 +141,10 @@ public function setUp() $this->settingsHelper = new SettingsHelper( new ShopHelper(), - $this->configurationHelper + $this->configurationHelper, + new CategoryFactory(), + new ContextFactory(), + new ValidateHelper() ); $this->cartData = new CartData( diff --git a/alma/tests/Unit/Controllers/Front/CmsDataExportTest.php b/alma/tests/Unit/Controllers/Front/CmsDataExportTest.php new file mode 100644 index 00000000..5d53f947 --- /dev/null +++ b/alma/tests/Unit/Controllers/Front/CmsDataExportTest.php @@ -0,0 +1,147 @@ + + * @copyright 2018-2024 Alma SAS + * @license https://opensource.org/licenses/MIT The MIT License + */ + +namespace Alma\PrestaShop\Tests\Unit\Controllers\Front; + +use Alma\API\Lib\PayloadFormatter; +use Alma\PrestaShop\Exceptions\CartException; +use Alma\PrestaShop\Exceptions\CmsDataException; +use Alma\PrestaShop\Helpers\CmsDataHelper; +use Alma\PrestaShop\Helpers\SettingsHelper; +use Alma\PrestaShop\Helpers\ValidateHelper; +use PHPUnit\Framework\TestCase; +use PrestaShop\PrestaShop\Core\Foundation\IoC\Exception; + +include_once __DIR__ . '/../../../../controllers/front/cmsdataexport.php'; +class AlmaCmsDataExportTest extends TestCase +{ + /** + * @var ValidateHelper + */ + protected $validateHelper; + /** + * @var SettingsHelper + */ + protected $settingsHelper; + /** + * @var PayloadFormatter + */ + protected $payloadFormatter; + /** + * @var CmsDataHelper + */ + protected $cmsDataHelper; + + public function setUp() + { + $this->validateHelper = $this->createMock(ValidateHelper::class); + $this->settingsHelper = $this->createMock(SettingsHelper::class); + $this->payloadFormatter = $this->createMock(PayloadFormatter::class); + $this->cmsDataHelper = $this->createMock(CmsDataHelper::class); + + $this->cmsDataExportMock = $this->getMockBuilder(\AlmaCmsDataExportModuleFrontController::class) + ->disableOriginalConstructor() + ->setMethodsExcept(['postProcess', 'setValidateHelper', 'setSettingsHelper', 'setPayloadFormatter', 'setCmsDataHelper']) + ->getMock(); + } + + public function tearDown() + { + $this->validateHelper = null; + $this->settingsHelper = null; + unset($_SERVER['HTTP_X_ALMA_SIGNATURE']); + } + + /** + * @throws \PrestaShopException + * @throws \Alma\PrestaShop\Exceptions\CmsDataException + */ + public function testPostProcessThrowExceptionWithWrongSignature() + { + $_SERVER['HTTP_X_ALMA_SIGNATURE'] = '1234'; + $this->settingsHelper->method('getIdMerchant')->willReturn('merchant_id'); + $this->validateHelper->method('checkSignature')->willThrowException(new CartException('Exception')); + $this->cmsDataExportMock->setValidateHelper($this->validateHelper); + $this->cmsDataExportMock->setSettingsHelper($this->settingsHelper); + $this->expectException(CmsDataException::class); + $this->cmsDataExportMock->postProcess(); + } + + /** + * @throws \PrestaShopException + * @throws \Alma\PrestaShop\Exceptions\CmsDataException + */ + public function testPostProcessThrowExceptionWithWrongGetMerchantId() + { + $_SERVER['HTTP_X_ALMA_SIGNATURE'] = '1234'; + $this->settingsHelper->method('getIdMerchant')->willThrowException(new Exception('Exception')); + $this->validateHelper->method('checkSignature')->willReturn(true); + $this->cmsDataExportMock->setValidateHelper($this->validateHelper); + $this->cmsDataExportMock->setSettingsHelper($this->settingsHelper); + $this->expectException(CmsDataException::class); + $this->cmsDataExportMock->postProcess(); + } + + public function testPostProcessWithRightData() + { + $cmsInfoArray = [ + 'cms_name' => 'Prestashop', + 'cms_version' => '1.2.3', + 'third_parties_plugins' => ['moduleList'], + 'themes' => 'ThemeName', + 'language_name' => 'PHP', + 'language_version' => phpversion(), + 'alma_plugin_version' => '4.3.2', + 'alma_sdk_name' => 'ALMA-PHP-CLIENT', + 'alma_sdk_version' => '2.3.4', + ]; + $cmsFeatureArray = [ + 'alma_enabled' => false, + 'widget_cart_activated' => false, + 'widget_product_activated' => false, + 'used_fee_plans' => ['general_1_0_0' => ['enabled' => '1']], + 'in_page_activated' => true, + 'log_activated' => true, + 'excluded_categories' => null, + 'specific_features' => [], + 'country_restriction' => [], + 'custom_widget_css' => true, + 'is_multisite' => true, + ]; + + $_SERVER['HTTP_X_ALMA_SIGNATURE'] = '1234'; + $this->settingsHelper + ->method('getIdMerchant') + ->willReturn('merchant_id'); + $this->validateHelper->method('checkSignature')->willReturn(true); + $this->cmsDataHelper->method('getCmsInfoArray')->willReturn($cmsInfoArray); + $this->cmsDataHelper->method('getCmsFeatureArray')->willReturn($cmsFeatureArray); + $this->payloadFormatter->method('formatConfigurationPayload'); + $this->cmsDataExportMock->setValidateHelper($this->validateHelper); + $this->cmsDataExportMock->setSettingsHelper($this->settingsHelper); + $this->cmsDataExportMock->setPayloadFormatter($this->payloadFormatter); + $this->cmsDataExportMock->setCmsDataHelper($this->cmsDataHelper); + // We can't test the return value because the method exit after echo the response + } +} diff --git a/alma/tests/Unit/Factories/CartFactoryTest.php b/alma/tests/Unit/Factories/CartFactoryTest.php index 3b7babf3..5a698861 100644 --- a/alma/tests/Unit/Factories/CartFactoryTest.php +++ b/alma/tests/Unit/Factories/CartFactoryTest.php @@ -29,26 +29,8 @@ class CartFactoryTest extends TestCase { - /** - * @var CartFactory - */ - protected $cartFactory; - /** - * @var \Cart - */ - protected $cartMock; - - public function setUp() - { - $this->cartMock = $this->createMock(\Cart::class); - $this->cartMock->id = 10; - $this->cartFactory = new CartFactory( - $this->cartMock - ); - } - public function testCreate() { - $this->assertInstanceOf(\Cart::class, $this->cartFactory->create(10)); + $this->assertInstanceOf(\Cart::class, (new CartFactory())->create(10)); } } diff --git a/alma/tests/Unit/Helper/ApiHelperTest.php b/alma/tests/Unit/Helper/ApiHelperTest.php index ce824395..5ed93169 100644 --- a/alma/tests/Unit/Helper/ApiHelperTest.php +++ b/alma/tests/Unit/Helper/ApiHelperTest.php @@ -31,6 +31,9 @@ use Alma\PrestaShop\Exceptions\ApiMerchantsException; use Alma\PrestaShop\Exceptions\InsuranceInstallException; use Alma\PrestaShop\Exceptions\WrongCredentialsException; +use Alma\PrestaShop\Factories\ModuleFactory; +use Alma\PrestaShop\Helpers\Admin\AdminInsuranceHelper; +use Alma\PrestaShop\Helpers\ApiHelper; use Alma\PrestaShop\Helpers\ClientHelper; use Alma\PrestaShop\Helpers\ConfigurationHelper; use Alma\PrestaShop\Helpers\ConstantsHelper; @@ -42,6 +45,28 @@ class ApiHelperTest extends TestCase { + /** + * @var \Alma\PrestaShop\Helpers\ApiHelper + */ + protected $apiHelper; + /** + * @var \Alma\PrestaShop\Helpers\ClientHelper + */ + protected $clientHelperMock; + + public function setUp() + { + $this->clientHelperMock = $this->createMock(ClientHelper::class); + $this->apiHelper = new ApiHelper( + $this->createMock(ModuleFactory::class), + $this->clientHelperMock, + $this->createMock(ToolsHelper::class), + $this->createMock(InsuranceService::class), + $this->createMock(ConfigurationHelper::class), + $this->createMock(AdminInsuranceHelper::class) + ); + } + public function testGetMerchant() { $responseCode = new \stdClass(); @@ -222,4 +247,16 @@ public function testGetPaymentEligibility() $apiHelper = $apiHelperBuilder->getInstance(); $this->assertEquals([], $apiHelper->getPaymentEligibility($paymentData)); } + + /** + * @return void + */ + public function testSendUrlForGatherCmsData() + { + $url = 'url'; + $this->clientHelperMock->expects($this->once()) + ->method('sendUrlForGatherCmsData') + ->with($url); + $this->apiHelper->sendUrlForGatherCmsData($url); + } } diff --git a/alma/tests/Unit/Helper/ClientHelperTest.php b/alma/tests/Unit/Helper/ClientHelperTest.php index 3f9efe19..6b3d0d62 100644 --- a/alma/tests/Unit/Helper/ClientHelperTest.php +++ b/alma/tests/Unit/Helper/ClientHelperTest.php @@ -24,11 +24,14 @@ namespace Alma\PrestaShop\Tests\Unit\Helper; +use Alma\API\Client; use Alma\API\ClientContext; +use Alma\API\Endpoints\Configuration; use Alma\API\Endpoints\Orders; use Alma\API\Entities\Payment; use Alma\API\Exceptions\ParametersException; use Alma\API\Exceptions\RequestException; +use Alma\API\RequestError; use Alma\PrestaShop\Exceptions\ClientException; use Alma\PrestaShop\Helpers\ClientHelper; use Mockery; @@ -39,11 +42,22 @@ class ClientHelperTest extends TestCase /** * @var Mockery\Mock|(Mockery\MockInterface&ClientHelper) */ + protected $clientHelperMock; + /** + * @var \Alma\PrestaShop\Helpers\ClientHelper + */ protected $clientHelper; public function setUp() { - $this->clientHelper = Mockery::mock(ClientHelper::class)->makePartial(); + $this->clientHelperMock = Mockery::mock(ClientHelper::class)->makePartial(); + $this->clientHelper = new ClientHelper(); + } + + public function tearDown() + { + $this->clientHelperMock = null; + $this->clientHelper = null; } /** @@ -53,10 +67,10 @@ public function setUp() */ public function testSendOrderEndpointNoAlmaClient() { - $this->clientHelper->shouldReceive('getAlmaClient')->andThrow(ClientException::class); + $this->clientHelperMock->shouldReceive('getAlmaClient')->andThrow(ClientException::class); $this->expectException(ClientException::class); - $this->clientHelper->getClientOrdersEndpoint(); + $this->clientHelperMock->getClientOrdersEndpoint(); } /** @@ -68,9 +82,9 @@ public function testSendOrderEndpoint() $almaClient = new \stdClass(); $almaClient->orders = new Orders(Mockery::mock(ClientContext::class)); - $this->clientHelper->shouldReceive('getAlmaClient')->andReturn($almaClient); + $this->clientHelperMock->shouldReceive('getAlmaClient')->andReturn($almaClient); - $this->assertInstanceOf(Orders::class, $this->clientHelper->getClientOrdersEndpoint()); + $this->assertInstanceOf(Orders::class, $this->clientHelperMock->getClientOrdersEndpoint()); } /** @@ -107,32 +121,34 @@ public function testSendOrderStatusBadRequest() /** * When i call an api - * Then I expect a endpoint paymentqs + * Then I expect a endpoint payments */ public function testSendPaymentEndpoint() { $almaClient = new \stdClass(); $almaClient->payments = Mockery::mock(Payment::class); - $this->clientHelper->shouldReceive('getAlmaClient')->andReturn($almaClient); + $this->clientHelperMock->shouldReceive('getAlmaClient')->andReturn($almaClient); - $this->assertInstanceOf(Payment::class, $this->clientHelper->getClientPaymentsEndpoint()); + $this->assertInstanceOf(Payment::class, $this->clientHelperMock->getClientPaymentsEndpoint()); } /** + * TODO : Need to be removed, useless test * When i call an api * And there is no alma client * Then I expect a client exception */ public function testSendPaymentEndpointNoAlmaClient() { - $this->clientHelper->shouldReceive('getAlmaClient')->andThrow(ClientException::class); + $this->clientHelperMock->shouldReceive('getAlmaClient')->andThrow(ClientException::class); $this->expectException(ClientException::class); - $this->clientHelper->getClientPaymentsEndpoint(); + $this->clientHelperMock->getClientPaymentsEndpoint(); } /** + * TODO : Need to be removed, useless test * When i call the function and the request fails * Then I expect a Request exception */ @@ -148,8 +164,43 @@ public function testGetPaymentByTransactionIdBadRequest() $clientHelper->getPaymentByTransactionId('transactionId'); } - public function tearDown() + /** + * @dataProvider sendUrlForGatherCmsDataExceptionsDataProvider + * + * @throws \Alma\PrestaShop\Exceptions\ClientException + */ + public function testSendUrlForGatherCmsDataWithThrowRequestException($exceptions) { - $this->clientHelper = null; + $url = 'url'; + $clientContextMock = $this->createMock(ClientContext::class); + $almaClientMock = $this->createMock(Client::class); + + $almaClientMock->configuration = $this->getMockBuilder(Configuration::class) + ->setConstructorArgs([$clientContextMock]) + ->setMethods(['sendIntegrationsConfigurationsUrl']) + ->getMock(); + $almaClientMock->configuration->expects($this->once()) + ->method('sendIntegrationsConfigurationsUrl') + ->with($url) + ->willThrowException($exceptions); + + $clientHelperPartialMock = $this->getMockBuilder(ClientHelper::class) + ->setMethods(['getAlmaClient']) + ->getMock(); + $clientHelperPartialMock->expects($this->once()) + ->method('getAlmaClient') + ->willReturn($almaClientMock); + + $this->expectException(ClientException::class); + $clientHelperPartialMock->sendUrlForGatherCmsData($url); + } + + public function sendUrlForGatherCmsDataExceptionsDataProvider() + { + return [ + [new RequestException('error')], + [new RequestError('error')], + [new ClientException('error')], + ]; } } diff --git a/alma/tests/Unit/Helper/CmsDataHelperTest.php b/alma/tests/Unit/Helper/CmsDataHelperTest.php new file mode 100644 index 00000000..d9540f0d --- /dev/null +++ b/alma/tests/Unit/Helper/CmsDataHelperTest.php @@ -0,0 +1,153 @@ +moduleHelper = $this->createMock(ModuleHelper::class); + $this->themeHelper = $this->createMock(ThemeHelper::class); + $this->almaModuleModel = $this->createMock(AlmaModuleModel::class); + $this->settingsHelper = $this->createMock(SettingsHelper::class); + $this->toolsHelper = $this->createMock(ToolsHelper::class); + $this->shopModel = $this->createMock(ShopModel::class); + $this->cmsDataHelper = new CmsDataHelper( + $this->moduleHelper, + $this->themeHelper, + $this->almaModuleModel, + $this->settingsHelper, + $this->toolsHelper, + $this->shopModel + ); + } + + public function tearDown() + { + $this->moduleHelper = null; + $this->themeHelper = null; + $this->almaModuleModel = null; + $this->settingsHelper = null; + $this->cmsDataHelper = null; + $this->toolsHelper = null; + $this->shopModel = null; + } + + /** + * @return void + */ + public function testGetCmsInfoArray() + { + $this->toolsHelper->method('getPsVersion')->willReturn('1.2.3'); + $this->moduleHelper->method('getModuleList')->willReturn(['moduleList']); + $this->themeHelper->method('getThemeNameWithVersion')->willReturn('ThemeName'); + $this->almaModuleModel->method('getVersion')->willReturn('4.3.2'); + $expected = [ + 'cms_name' => 'Prestashop', + 'cms_version' => '1.2.3', + 'third_parties_plugins' => ['moduleList'], + 'themes' => 'ThemeName', + 'language_name' => 'PHP', + 'language_version' => phpversion(), + 'alma_plugin_version' => '4.3.2', + 'alma_sdk_name' => 'ALMA-PHP-CLIENT', + 'alma_sdk_version' => Client::VERSION, + ]; + + $this->assertEquals($expected, $this->cmsDataHelper->getCmsInfoArray()); + } + + /** + * @return void + */ + public function testGetCmsFeatureArray() + { + $this->settingsHelper->method('getKey')->willReturnMap( + [ + [SettingsHelper::ALMA_FULLY_CONFIGURED, null, false], + [CartEligibilityAdminFormBuilder::ALMA_SHOW_ELIGIBILITY_MESSAGE, null, false], + [ProductEligibilityAdminFormBuilder::ALMA_SHOW_PRODUCT_ELIGIBILITY, null, false], + [PnxAdminFormBuilder::ALMA_FEE_PLANS, null, '{"general_1_0_0":{"enabled":"1"}}'], + [InpageAdminFormBuilder::ALMA_ACTIVATE_INPAGE, null, true], + [DebugAdminFormBuilder::ALMA_ACTIVATE_LOGGING, null, true], + [ProductEligibilityAdminFormBuilder::ALMA_WIDGET_POSITION_SELECTOR, null, '#selectorCss'], + ] + ); + $this->shopModel->method('isMultisite')->willReturn(false); + $expected = [ + 'alma_enabled' => false, + 'widget_cart_activated' => false, + 'widget_product_activated' => false, + 'used_fee_plans' => ['general_1_0_0' => ['enabled' => '1']], + 'in_page_activated' => true, + 'log_activated' => true, + 'excluded_categories' => null, + 'specific_features' => [], + 'country_restriction' => [], + 'custom_widget_css' => (bool) '#selectorCss', + 'is_multisite' => false, + ]; + + $this->assertEquals($expected, $this->cmsDataHelper->getCmsFeatureArray()); + } + + /** + * @return void + */ + public function testGetCmsFeatureArrayWithFeePlansEmptyReturnNull() + { + $this->settingsHelper->method('getKey')->willReturnMap( + [ + [SettingsHelper::ALMA_FULLY_CONFIGURED, null, false], + [CartEligibilityAdminFormBuilder::ALMA_SHOW_ELIGIBILITY_MESSAGE, null, false], + [ProductEligibilityAdminFormBuilder::ALMA_SHOW_PRODUCT_ELIGIBILITY, null, false], + [PnxAdminFormBuilder::ALMA_FEE_PLANS, null, '{}'], + [InpageAdminFormBuilder::ALMA_ACTIVATE_INPAGE, null, true], + [DebugAdminFormBuilder::ALMA_ACTIVATE_LOGGING, null, true], + [ProductEligibilityAdminFormBuilder::ALMA_WIDGET_POSITION_SELECTOR, null, '#selectorCss'], + ] + ); + $this->shopModel->method('isMultisite')->willReturn(false); + $expected = [ + 'alma_enabled' => false, + 'widget_cart_activated' => false, + 'widget_product_activated' => false, + 'used_fee_plans' => null, + 'in_page_activated' => true, + 'log_activated' => true, + 'excluded_categories' => null, + 'specific_features' => [], + 'country_restriction' => [], + 'custom_widget_css' => (bool) '#selectorCss', + 'is_multisite' => false, + ]; + + $this->assertEquals($expected, $this->cmsDataHelper->getCmsFeatureArray()); + } +} diff --git a/alma/tests/Unit/Helper/ModuleHelperTest.php b/alma/tests/Unit/Helper/ModuleHelperTest.php new file mode 100644 index 00000000..7e04436d --- /dev/null +++ b/alma/tests/Unit/Helper/ModuleHelperTest.php @@ -0,0 +1,108 @@ + + * @copyright 2018-2024 Alma SAS + * @license https://opensource.org/licenses/MIT The MIT License + */ + +namespace Alma\PrestaShop\Tests\Unit\Helper; + +use Alma\PrestaShop\Helpers\ModuleHelper; +use Alma\PrestaShop\Proxy\ModuleProxy; +use PHPUnit\Framework\TestCase; + +class ModuleHelperTest extends TestCase +{ + /** + * @var ModuleHelper + */ + protected $moduleHelper; + /** + * @var ModuleProxy + */ + protected $moduleProxyMock; + + public function setUp() + { + $this->moduleProxyMock = $this->createMock(ModuleProxy::class); + $this->moduleHelper = new ModuleHelper( + $this->moduleProxyMock + ); + } + + /** + * @dataProvider modulesInstalledDataProvider + * + * @return void + */ + public function testGetModuleListWithListOfModules($moduleInstalled, $expectedModulesList) + { + $this->moduleProxyMock->expects($this->once()) + ->method('getModulesInstalled') + ->willReturn($moduleInstalled); + $this->assertEquals($expectedModulesList, $this->moduleHelper->getModuleList()); + } + + public function modulesInstalledDataProvider() + { + return [ + 'With Modules installed' => [ + 'Modules installed' => [ + [ + 'id_module' => '1', + 'name' => 'blockwishlist', + 'active' => '1', + 'version' => '2.1.0', + ], + [ + 'id_module' => '2', + 'name' => 'contactform', + 'active' => '1', + 'version' => '4.3.0', + ], + [ + 'id_module' => '3', + 'name' => 'dashactivity', + 'active' => '1', + 'version' => '2.0.2', + ], + ], + 'Modules list' => [ + [ + 'name' => 'blockwishlist', + 'version' => '2.1.0', + ], + [ + 'name' => 'contactform', + 'version' => '4.3.0', + ], + [ + 'name' => 'dashactivity', + 'version' => '2.0.2', + ], + ], + ], + 'With no module installed' => [ + 'Modules installed' => [], + 'Modules list' => [], + ], + ]; + } +} diff --git a/alma/tests/Unit/Helper/SettingsHelperTest.php b/alma/tests/Unit/Helper/SettingsHelperTest.php index 1b2506d7..f20e6937 100644 --- a/alma/tests/Unit/Helper/SettingsHelperTest.php +++ b/alma/tests/Unit/Helper/SettingsHelperTest.php @@ -26,10 +26,14 @@ use Alma\API\Entities\FeePlan; use Alma\PrestaShop\Builders\Helpers\SettingsHelperBuilder; +use Alma\PrestaShop\Exceptions\AlmaException; +use Alma\PrestaShop\Factories\CategoryFactory; +use Alma\PrestaShop\Factories\ContextFactory; use Alma\PrestaShop\Forms\InpageAdminFormBuilder; use Alma\PrestaShop\Helpers\ConfigurationHelper; use Alma\PrestaShop\Helpers\SettingsHelper; use Alma\PrestaShop\Helpers\ShopHelper; +use Alma\PrestaShop\Helpers\ValidateHelper; use PHPUnit\Framework\TestCase; class SettingsHelperTest extends TestCase @@ -41,27 +45,51 @@ class SettingsHelperTest extends TestCase /** * @var ShopHelper */ - protected $shopHelper; + protected $shopHelperMock; /** * @var ConfigurationHelper */ - protected $configurationHelper; + protected $configurationHelperMock; /** * @var (SettingsHelper&\PHPUnit\Framework\MockObject\MockObject)|\PHPUnit_Framework_MockObject_MockObject */ protected $settingsHelperMock; + /** + * @var \Alma\PrestaShop\Factories\CategoryFactory|(\Alma\PrestaShop\Factories\CategoryFactory&\PHPUnit_Framework_MockObject_MockObject)|\PHPUnit_Framework_MockObject_MockObject + */ + protected $categoryFactoryMock; + /** + * @var \Alma\PrestaShop\Factories\ContextFactory|(\Alma\PrestaShop\Factories\ContextFactory&\PHPUnit_Framework_MockObject_MockObject)|\PHPUnit_Framework_MockObject_MockObject + */ + protected $contextFactoryMock; + /** + * @var \Alma\PrestaShop\Helpers\ValidateHelper|(\Alma\PrestaShop\Helpers\ValidateHelper&\PHPUnit_Framework_MockObject_MockObject)|\PHPUnit_Framework_MockObject_MockObject + */ + protected $validateHelperMock; public function setUp() { - $this->shopHelper = $this->createMock(ShopHelper::class); - $this->configurationHelper = $this->createMock(ConfigurationHelper::class); + $this->shopHelperMock = $this->createMock(ShopHelper::class); + $this->configurationHelperMock = $this->createMock(ConfigurationHelper::class); + $this->categoryFactoryMock = $this->createMock(CategoryFactory::class); + $this->contextFactoryMock = $this->createMock(ContextFactory::class); + $this->validateHelperMock = $this->createMock(ValidateHelper::class); $this->settingsHelper = new SettingsHelper( - $this->shopHelper, - $this->configurationHelper + $this->shopHelperMock, + $this->configurationHelperMock, + $this->categoryFactoryMock, + $this->contextFactoryMock, + $this->validateHelperMock ); $this->settingsHelperMock = $this->getMockBuilder(SettingsHelper::class) - ->setConstructorArgs([$this->shopHelper, $this->configurationHelper]) + ->setConstructorArgs([ + $this->shopHelperMock, + $this->configurationHelperMock, + $this->categoryFactoryMock, + $this->contextFactoryMock, + $this->validateHelperMock, + ]) ->setMethods(['isInPageEnabled', 'getKey']) ->getMock(); } @@ -372,7 +400,17 @@ protected function getSettingsHelperMockForIsPaymentTriggerEnabledByState($keyNa $configurationHelperMock->shouldReceive('get')->with($keyName, null, 1, 1, '')->andReturn($keyValue); $configurationHelperMock->shouldReceive('hasKey')->with($keyName, null, 1, 1)->andReturn(false); - return \Mockery::mock(SettingsHelper::class, [$shopHelperMock, $configurationHelperMock])->shouldAllowMockingProtectedMethods()->makePartial(); + $categoryFactoryMock = \Mockery::mock(CategoryFactory::class); + $contextFactoryMock = \Mockery::mock(ContextFactory::class); + $validateHelperMock = \Mockery::mock(ValidateHelper::class); + + return \Mockery::mock(SettingsHelper::class, [ + $shopHelperMock, + $configurationHelperMock, + $categoryFactoryMock, + $contextFactoryMock, + $validateHelperMock, + ])->shouldAllowMockingProtectedMethods()->makePartial(); } public function testKey() @@ -492,4 +530,100 @@ public function inPageSettingsDataProvider() ], ]; } + + public function testGetCategoriesExcludedNamesWithNoCategories() + { + $this->configurationHelperMock->expects($this->once()) + ->method('get') + ->with(SettingsHelper::ALMA_EXCLUDED_CATEGORIES) + ->willReturn(false); + $this->assertEquals([], $this->settingsHelper->getCategoriesExcludedNames()); + } + + /** + * @return void + */ + public function testGetCategoriesExcludedNamesWithCategoriesDontExist() + { + $categories = [ + 10 => $this->createMock(\Category::class), + 11 => $this->createMock(\Category::class), + ]; + + $this->configurationHelperMock->expects($this->once()) + ->method('get') + ->with(SettingsHelper::ALMA_EXCLUDED_CATEGORIES) + ->willReturn('[10, 11]'); + $this->categoryFactoryMock->expects($this->exactly(2)) + ->method('create') + ->withConsecutive([10, 1], [11, 1]) + ->willReturnOnConsecutiveCalls($categories[10], $categories[11]); + $this->contextFactoryMock->expects($this->exactly(2)) + ->method('getContextLanguageId') + ->willReturn(1); + $this->validateHelperMock->expects($this->exactly(2)) + ->method('isLoadedObject') + ->withConsecutive([$categories[10]], [$categories[11]]) + ->willReturnOnConsecutiveCalls(false, false); + $this->assertEquals([], $this->settingsHelper->getCategoriesExcludedNames()); + } + + public function testGetCategoriesExcludedNamesWithReturnOnlyCategoryExisting() + { + /** @var \Category[] $categories */ + $categories = [ + 12 => $this->createMock(\Category::class), + 13 => $this->createMock(\Category::class), + ]; + + $categories[12]->id = 12; + $categories[12]->name = 'category 12'; + + $this->configurationHelperMock->expects($this->once()) + ->method('get') + ->with(SettingsHelper::ALMA_EXCLUDED_CATEGORIES) + ->willReturn('[12, 13]'); + $this->categoryFactoryMock->expects($this->exactly(2)) + ->method('create') + ->withConsecutive([12, 1], [13, 1]) + ->willReturnOnConsecutiveCalls($categories[12], $categories[13]); + $this->contextFactoryMock->expects($this->exactly(2)) + ->method('getContextLanguageId') + ->willReturn(1); + $this->validateHelperMock->expects($this->exactly(2)) + ->method('isLoadedObject') + ->withConsecutive([$categories[12]], [$categories[13]]) + ->willReturnOnConsecutiveCalls(true, false); + $this->assertEquals(['category 12'], $this->settingsHelper->getCategoriesExcludedNames()); + } + + public function testGetCategoriesExcludedNamesWithGetContextLanguageIdThrowException() + { + /** @var \Category[] $categories */ + $categories = [ + 14 => $this->createMock(\Category::class), + 15 => $this->createMock(\Category::class), + ]; + + $categories[14]->id = 14; + $categories[14]->name = 'category 14'; + + $this->configurationHelperMock->expects($this->once()) + ->method('get') + ->with(SettingsHelper::ALMA_EXCLUDED_CATEGORIES) + ->willReturn('[14, 15]'); + + $this->contextFactoryMock->expects($this->exactly(2)) + ->method('getContextLanguageId') + ->willThrowException(new AlmaException('Context language is null')); + $this->categoryFactoryMock->expects($this->exactly(2)) + ->method('create') + ->withConsecutive([14], [15]) + ->willReturnOnConsecutiveCalls($categories[14], $categories[15]); + $this->validateHelperMock->expects($this->exactly(2)) + ->method('isLoadedObject') + ->withConsecutive([$categories[14]], [$categories[15]]) + ->willReturnOnConsecutiveCalls(true, false); + $this->assertEquals(['category 14'], $this->settingsHelper->getCategoriesExcludedNames()); + } } diff --git a/alma/tests/Unit/Helper/ValidateHelperTest.php b/alma/tests/Unit/Helper/ValidateHelperTest.php new file mode 100644 index 00000000..b4003081 --- /dev/null +++ b/alma/tests/Unit/Helper/ValidateHelperTest.php @@ -0,0 +1,94 @@ + + * @copyright 2018-2024 Alma SAS + * @license https://opensource.org/licenses/MIT The MIT License + */ + +namespace Alma\PrestaShop\Tests\Unit\Helper; + +use Alma\PrestaShop\Exceptions\ValidateException; +use Alma\PrestaShop\Helpers\ValidateHelper; +use PHPUnit\Framework\TestCase; + +class ValidateHelperTest extends TestCase +{ + const API_KEY = 'api_key_test'; + const EXTERNAL_ID = 'merchant_id_test'; + const WRONG_SIGNATURE = 'wrong_signature'; + const GOOD_SIGNATURE = '0dd3cb4632c074ead0d0f346c75015c76ad4e1e115f01c7e0850dd5accb7b4b0'; + /** + * @var ValidateHelper + */ + protected $validateHelper; + + public function setUp() + { + $this->validateHelper = new ValidateHelper(); + } + + public function tearDown() + { + $this->validateHelper = null; + } + + /** + * @dataProvider checkSignatureWrongParamsDataProvider + * + * @throws ValidateException + */ + public function testCheckSignatureWithoutParamsReturnError($externalId, $apiKey, $signature) + { + $this->expectException(ValidateException::class); + $this->validateHelper->checkSignature($externalId, $apiKey, $signature); + } + + /** + * @throws ValidateException + */ + public function testCheckSignatureWithBadSignatureReturnError() + { + $this->expectException(ValidateException::class); + $this->validateHelper->checkSignature(self::EXTERNAL_ID, self::API_KEY, self::WRONG_SIGNATURE); + } + + /** + * @throws ValidateException + */ + public function testCheckSignatureWithGoodSignature() + { + $this->validateHelper->checkSignature(self::EXTERNAL_ID, self::API_KEY, self::GOOD_SIGNATURE); + } + + /** + * @return array[] + */ + public function checkSignatureWrongParamsDataProvider() + { + return [ + 'Without api key' => [self::EXTERNAL_ID, '', self::GOOD_SIGNATURE], + 'Without payement id' => ['', self::API_KEY, self::GOOD_SIGNATURE], + 'Without signature' => [self::EXTERNAL_ID, self::API_KEY, ''], + 'With api key null' => [self::EXTERNAL_ID, null, self::GOOD_SIGNATURE], + 'With payement id null' => [null, self::API_KEY, self::GOOD_SIGNATURE], + 'With signature null' => [self::EXTERNAL_ID, self::API_KEY, null], + ]; + } +} diff --git a/alma/tests/Unit/Model/AlmaModuleModelTest.php b/alma/tests/Unit/Model/AlmaModuleModelTest.php new file mode 100644 index 00000000..97637c86 --- /dev/null +++ b/alma/tests/Unit/Model/AlmaModuleModelTest.php @@ -0,0 +1,94 @@ + + * @copyright 2018-2024 Alma SAS + * @license https://opensource.org/licenses/MIT The MIT License + */ + +namespace Alma\PrestaShop\Tests\Unit\Model; + +use Alma\PrestaShop\Helpers\ConstantsHelper; +use Alma\PrestaShop\Model\AlmaModuleModel; +use Alma\PrestaShop\Proxy\ModuleProxy; +use PHPUnit\Framework\TestCase; + +class AlmaModuleModelTest extends TestCase +{ + /** + * @var AlmaModuleModel + */ + protected $almaModuleModel; + + /** + * @var ModuleProxy + */ + protected $moduleProxyMock; + + public function setUp() + { + $this->moduleProxyMock = $this->createMock(ModuleProxy::class); + $this->almaModuleModel = new AlmaModuleModel( + $this->moduleProxyMock + ); + } + + public function tearDown() + { + $this->moduleProxyMock = null; + $this->almaModuleModel = null; + } + + /** + * @dataProvider moduleDataProvider + * + * @return void + */ + public function testGetAlmaModuleVersion($module, $expectedVersion) + { + if ($module) { + $module->version = $expectedVersion; + $this->moduleProxyMock->expects($this->once()) + ->method('getModuleVersion') + ->with($module) + ->willReturn($expectedVersion); + } + + $this->moduleProxyMock->expects($this->once()) + ->method('getModule') + ->with(ConstantsHelper::ALMA_MODULE_NAME) + ->willReturn($module); + + $this->assertEquals($expectedVersion, $this->almaModuleModel->getVersion()); + } + + public function moduleDataProvider() + { + return [ + 'With module' => [ + 'module' => $this->createMock(\Module::class), + 'expectedVersion' => '4.4.0', + ], + 'Without module' => [ + 'module' => false, + 'expectedVersion' => '', + ], + ]; + } +} diff --git a/alma/tests/Unit/Model/CartDataTest.php b/alma/tests/Unit/Model/CartDataTest.php index 092fc04b..f0863c60 100644 --- a/alma/tests/Unit/Model/CartDataTest.php +++ b/alma/tests/Unit/Model/CartDataTest.php @@ -25,6 +25,8 @@ namespace Alma\PrestaShop\Tests\Unit\Model; use Alma\PrestaShop\Builders\Models\CartDataBuilder; +use Alma\PrestaShop\Factories\CategoryFactory; +use Alma\PrestaShop\Factories\ContextFactory; use Alma\PrestaShop\Factories\CurrencyFactory; use Alma\PrestaShop\Helpers\ConfigurationHelper; use Alma\PrestaShop\Helpers\CurrencyHelper; @@ -33,6 +35,7 @@ use Alma\PrestaShop\Helpers\SettingsHelper; use Alma\PrestaShop\Helpers\ShopHelper; use Alma\PrestaShop\Helpers\ToolsHelper; +use Alma\PrestaShop\Helpers\ValidateHelper; use Alma\PrestaShop\Repositories\ProductRepository; use Cart; use PHPUnit\Framework\TestCase; @@ -235,7 +238,13 @@ public function testGetCartExclusion() $cart = \Mockery::mock(\Cart::class); $cart->allows()->getProducts(true)->andReturns([['id_product' => 1]]); - $settingsHelperMock = \Mockery::mock(SettingsHelper::class, [new ShopHelper(), new ConfigurationHelper()]); + $settingsHelperMock = \Mockery::mock(SettingsHelper::class, [ + new ShopHelper(), + new ConfigurationHelper(), + new CategoryFactory(), + new ContextFactory(), + new ValidateHelper(), + ]); $settingsHelperMock->shouldReceive('getExcludedCategories')->andReturn(['cateexclue']); $productHelperMock = \Mockery::mock(ProductHelper::class); diff --git a/alma/tests/Unit/Proxy/ModuleProxyTest.php b/alma/tests/Unit/Proxy/ModuleProxyTest.php new file mode 100644 index 00000000..1e9dfcbe --- /dev/null +++ b/alma/tests/Unit/Proxy/ModuleProxyTest.php @@ -0,0 +1,108 @@ + + * @copyright 2018-2024 Alma SAS + * @license https://opensource.org/licenses/MIT The MIT License + */ + +namespace Alma\PrestaShop\Tests\Unit\Proxy; + +use Alma\PrestaShop\Helpers\ConstantsHelper; +use Alma\PrestaShop\Helpers\ToolsHelper; +use Alma\PrestaShop\Proxy\ModuleProxy; +use PHPUnit\Framework\TestCase; + +class ModuleProxyTest extends TestCase +{ + /** + * @var ModuleProxy + */ + protected $moduleProxy; + + /** + * @var ToolsHelper + */ + protected $toolsHelperMock; + + public function setUp() + { + $this->toolsHelperMock = $this->createMock(ToolsHelper::class); + $this->moduleProxy = new ModuleProxy( + $this->toolsHelperMock + ); + } + + public function tearDown() + { + $this->moduleProxy = null; + $this->toolsHelperMock = null; + } + + public function testGetModule() + { + $this->assertInstanceOf(\Module::class, $this->moduleProxy->getModule(ConstantsHelper::ALMA_MODULE_NAME)); + } + + public function testIsInstalledPsAfter17() + { + $this->toolsHelperMock->expects($this->once()) + ->method('psVersionCompare') + ->willReturn(false); + + $moduleProxyPartialMock = $this->getMockBuilder(ModuleProxy::class) + ->setConstructorArgs([$this->toolsHelperMock]) + ->setMethods(['isInstalledAfter17', 'isInstalledBefore17']) + ->getMock(); + $moduleProxyPartialMock->expects($this->never()) + ->method('isInstalledBefore17'); + $moduleProxyPartialMock->expects($this->once()) + ->method('isInstalledAfter17') + ->willReturn(true); + + $this->assertTrue($moduleProxyPartialMock->isInstalled('mymodulename')); + } + + public function testIsInstalledPsBefore17() + { + $this->toolsHelperMock->expects($this->once()) + ->method('psVersionCompare') + ->willReturn(true); + + $moduleProxyPartialMock = $this->getMockBuilder(ModuleProxy::class) + ->setConstructorArgs([$this->toolsHelperMock]) + ->setMethods(['isInstalledBefore17', 'isInstalledAfter17']) + ->getMock(); + $moduleProxyPartialMock->expects($this->never()) + ->method('isInstalledAfter17'); + $moduleProxyPartialMock->expects($this->once()) + ->method('isInstalledBefore17') + ->willReturn(false); + + $this->assertFalse($moduleProxyPartialMock->isInstalled('mymodulename')); + } + + public function testGetModuleVersion() + { + $module = $this->createMock(\Module::class); + $module->version = '4.4.0'; + + $this->assertEquals('4.4.0', $this->moduleProxy->getModuleVersion($module)); + } +} diff --git a/alma/translations/es.php b/alma/translations/es.php index ccd31d3a..b3005635 100644 --- a/alma/translations/es.php +++ b/alma/translations/es.php @@ -80,12 +80,12 @@ $_MODULE['<{alma}prestashop>excludedcategoryadminformbuilder_c4cea4750fb3ef077cbf2e1283c312ac'] = 'Mensaje a mostrar en la p谩gina de un producto excluido o en la p谩gina del carrito si contiene un producto excluido.'; $_MODULE['<{alma}prestashop>excludedcategoryadminformbuilder_36359547b09bdb31f46c419a0bd5807e'] = 'Categor铆as excluidas'; $_MODULE['<{alma}prestashop>inpageadminformbuilder_2420ebe02d61c738479f399a97e1cf18'] = 'Activar el pago integrado'; -$_MODULE['<{alma}prestashop>inpageadminformbuilder_3dd32a0e923aeb930c7c0ced60f7b2e0'] = 'Activar en la p谩gina de pago para todos los m茅todos de pago Alma'; +$_MODULE['<{alma}prestashop>inpageadminformbuilder_3dd32a0e923aeb930c7c0ced60f7b2e0'] = 'Activar in-page checkout para todos los m茅todos de pago Alma'; $_MODULE['<{alma}prestashop>inpageadminformbuilder_220a4f39147308a2160f7abc4d00ae43'] = 'La p谩gina de pago en tu propio sitio web'; $_MODULE['<{alma}prestashop>inpageadminformbuilder_6f7991629de2e9ee19a0bf2a0469138c'] = 'Bot贸n de pago de entrada Selector de Alma'; $_MODULE['<{alma}prestashop>inpageadminformbuilder_6644897911f79aa5889998a5ab18c5cd'] = '%1$sAvanzado%2$s [Opcional] Selector CSS utilizado por nuestros scripts para identificar el bot贸n de pago Alma'; $_MODULE['<{alma}prestashop>inpageadminformbuilder_cc12a5229a16dced1984745e05872a94'] = 'Por ejemplo, #id, .class, ...'; -$_MODULE['<{alma}prestashop>inpageadminformbuilder_8ee0042ba2657c2af782fcc8893fa45a'] = 'Selector de botones para realizar pedidos'; +$_MODULE['<{alma}prestashop>inpageadminformbuilder_8ee0042ba2657c2af782fcc8893fa45a'] = 'Ubica los botones para realizar pedidos'; $_MODULE['<{alma}prestashop>inpageadminformbuilder_afa1a431a4735641af813166d75b1c06'] = '%1$sAvanzado%2$s [Opcional] Selector CSS utilizado por nuestros scripts para identificar el bot贸n de confirmaci贸n de pago.'; $_MODULE['<{alma}prestashop>inpageadminformbuilder_6de24747c86085e597f6b38d4d1d01a4'] = 'Pago integrado'; $_MODULE['<{alma}prestashop>carteligibilityadminformbuilder_a2a52a9dd1864e2b995793bd67b8c6e5'] = 'Este widget te permite informar a tus Clientes de la disponibilidad del pago aplazado con Alma directamente desde la p谩gina del producto. Esto te ayudar谩 a aumentar tu tasa de conversi贸n. Para m谩s detalles sobre su configuraci贸n o en caso de problemas, consulta %1$sesta documentaci贸n%2$s.'; @@ -158,7 +158,7 @@ $_MODULE['<{alma}prestashop>admininsurancehelper_7442e29d7d53e549b78d93c46b8cdcfc'] = 'Pedidos'; $_MODULE['<{alma}prestashop>insuranceservice_d87aee5118a62a7ff6c21e4ac31006c5'] = 'Por la presente acepto suscribir el seguro ofrecido por Alma. Al hacerlo, confirmo que he revisado previamente el [aviso informativo, que constituye las condiciones generales], el [documento de informaci贸n sobre el producto de seguro] y la [hoja de informaci贸n y asesoramiento precontractual]. Y sin reservas, acepto firmar electr贸nicamente los distintos documentos que forman mi contrato, si procede. Consiento expresamente la recolecci贸n y utilizaci贸n de mis datos personales a efectos de la suscripci贸n y gesti贸n de mi(s) contrato(s) de seguro.'; $_MODULE['<{alma}prestashop>adminalmainsuranceconfiguration_b824200e9b8aca1fbb762d6566ff0cd7'] = 'Tu configuraci贸n se ha guardado'; -$_MODULE['<{alma}prestashop>adminalmainsuranceconfiguration_a6bf06f186e2fccecad054fd831c2144'] = '[Alma] Error al asegurar el producto durante la configuraci贸n del cambio: %1$s'; +$_MODULE['<{alma}prestashop>adminalmainsuranceconfiguration_a6bf06f186e2fccecad054fd831c2144'] = '[Alma] Error al asegurar el producto durante el cambio de configuraci贸n: %1$s'; $_MODULE['<{alma}prestashop>adminalmainsuranceconfiguration_b42688965893bdb7a37cf1197e506e25'] = '[Alma] Error al crear la configuraci贸n Alma seguro: %1$s'; $_MODULE['<{alma}prestashop>adminalmainsuranceorders_a66f446516cd125af12bd25073f88b78'] = 'Pedidos con seguro'; $_MODULE['<{alma}prestashop>adminalmainsuranceorders_49414cda71621b3ee718ae5ff40804c5'] = 'Id Orden'; diff --git a/alma/upgrade/upgrade-4.6.0.php b/alma/upgrade/upgrade-4.6.0.php new file mode 100644 index 00000000..85a8b377 --- /dev/null +++ b/alma/upgrade/upgrade-4.6.0.php @@ -0,0 +1,58 @@ + + * @copyright 2018-2024 Alma SAS + * @license https://opensource.org/licenses/MIT The MIT License + */ + +use Alma\API\Lib\IntegrationsConfigurationsUtils; +use Alma\PrestaShop\Builders\Helpers\ApiHelperBuilder; +use Alma\PrestaShop\Builders\Helpers\ContextHelperBuilder; +use Alma\PrestaShop\Builders\Helpers\SettingsHelperBuilder; +use Alma\PrestaShop\Helpers\CmsDataHelper; +use Alma\PrestaShop\Helpers\ConstantsHelper; +use Alma\PrestaShop\Logger; + +if (!defined('_PS_VERSION_')) { + exit; +} + +function upgrade_module_4_6_0() +{ + $settingsHelper = (new SettingsHelperBuilder())->getInstance(); + $contextHelper = (new ContextHelperBuilder())->getInstance(); + $apiHelper = (new ApiHelperBuilder())->getInstance(); + + try { + if (IntegrationsConfigurationsUtils::isUrlRefreshRequired($settingsHelper->getKey(CmsDataHelper::ALMA_CMSDATA_DATE))) { + $apiHelper->sendUrlForGatherCmsData($contextHelper->getModuleLink('cmsdataexport', [], true)); + $settingsHelper->updateKey(CmsDataHelper::ALMA_CMSDATA_DATE, time()); + } + } catch (\Alma\PrestaShop\Exceptions\AlmaException $e) { + Logger::instance()->error('Failed to send URL for CMS data gathering', ['exception' => $e]); + } + + if (version_compare(_PS_VERSION_, ConstantsHelper::PRESTASHOP_VERSION_1_7_0_2, '>')) { + Tools::clearAllCache(); + Tools::clearXMLCache(); + } + + return true; +}