From 55689707cac4e64f527c21eb7f4d1e0945b1b648 Mon Sep 17 00:00:00 2001 From: Ievgen Sentiabov Date: Tue, 25 Oct 2016 16:44:49 +0300 Subject: [PATCH 01/19] MAGETWO-59832: Move Braintree and Vault module changes - Moved Braintree, Vault and Payment modules changes - Updated unit and integration tests --- .../Customer/PayPal/VaultTokenRenderer.php | 76 ++++ .../Command/CaptureStrategyCommand.php | 25 +- .../Braintree/Gateway/Config/Config.php | 24 ++ .../Gateway/Config/PayPal/Config.php | 51 +++ .../Gateway/Helper/SubjectReader.php | 2 +- .../Gateway/Request/DescriptorDataBuilder.php | 44 +++ .../Request/PayPal/DeviceDataBuilder.php | 52 +++ .../Request/PayPal/VaultDataBuilder.php | 60 +++ .../Gateway/Request/VaultDataBuilder.php | 5 +- .../Response/PayPal/VaultDetailsHandler.php | 130 +++++++ .../Gateway/Response/RiskDataHandler.php | 10 + .../Gateway/Validator/ResponseValidator.php | 3 +- app/code/Magento/Braintree/Helper/Country.php | 15 +- .../Model/Paypal/Helper/QuoteUpdater.php | 11 +- .../Model/Report/Row/TransactionMap.php | 4 + .../Model/Report/TransactionsCollection.php | 3 +- .../PayPal/TokenUiComponentProvider.php | 84 ++++ .../Ui/Adminhtml/TokenUiComponentProvider.php | 1 + .../Braintree/Model/Ui/ConfigProvider.php | 34 +- .../Model/Ui/PayPal/ConfigProvider.php | 56 +++ .../Ui/PayPal/TokenUiComponentProvider.php | 73 ++++ .../Braintree/Observer/AddPaypalShortcuts.php | 5 +- .../Braintree/Test/Unit/Block/FormTest.php | 1 - .../Command/CaptureStrategyCommandTest.php | 2 +- .../Test/Unit/Gateway/Config/ConfigTest.php | 62 +++ .../Request/DescriptorDataBuilderTest.php | 105 +++++ .../Request/KountPaymentDataBuilderTest.php | 2 +- .../Request/PayPal/DeviceDataBuilderTest.php | 115 ++++++ .../Request/PayPal/VaultDataBuilderTest.php | 112 ++++++ .../Request/VaultCaptureDataBuilderTest.php | 8 +- .../PayPal/VaultDetailsHandlerTest.php | 252 ++++++++++++ .../Gateway/Response/RiskDataHandlerTest.php | 118 +++--- .../Response/VaultDetailsHandlerTest.php | 12 +- .../GeneralResponseValidatorTest.php | 2 +- .../Validator/ResponseValidatorTest.php | 60 +-- .../Model/Paypal/Helper/QuoteUpdaterTest.php | 2 +- .../Unit/Model/Report/TransactionMapTest.php | 62 ++- .../Report/TransactionsCollectionTest.php | 38 ++ .../PayPal/TokenUiComponentProviderTest.php | 114 ++++++ .../TokenUiComponentProviderTest.php | 7 +- .../Test/Unit/Model/Ui/ConfigProviderTest.php | 56 +-- .../Model/Ui/PayPal/ConfigProviderTest.php | 118 ++++++ .../PayPal/TokenUiComponentProviderTest.php | 92 +++++ .../Report/Filters/Type/DateRangeTest.php | 251 ++++++++++++ .../Report/Filters/Type/DateRange.php | 19 + .../Report/Listing/Column/PaymentType.php | 12 +- .../Report/Listing/Column/Status.php | 28 +- .../Report/Listing/Column/TransactionType.php | 4 +- .../Magento/Braintree/etc/adminhtml/di.xml | 3 + .../Braintree/etc/adminhtml/system.xml | 45 ++- app/code/Magento/Braintree/etc/config.xml | 12 +- app/code/Magento/Braintree/etc/di.xml | 296 +++++++++----- .../Magento/Braintree/etc/frontend/di.xml | 2 + app/code/Magento/Braintree/i18n/en_US.csv | 29 +- .../layout/sales_order_create_index.xml | 8 +- ...order_create_load_block_billing_method.xml | 4 + .../templates/form/paypal/vault.phtml | 30 ++ .../view/adminhtml/templates/form/vault.phtml | 3 +- .../ui_component/braintree_report.xml | 19 +- .../Braintree/view/adminhtml/web/js/vault.js | 34 +- .../Braintree/view/adminhtml/web/styles.css | 5 +- .../view/base/web/images/paypal-small.png | Bin 0 -> 1398 bytes .../Braintree/view/base/web/images/paypal.png | Bin 0 -> 2432 bytes .../layout/vault_cards_listaction.xml | 3 + .../view/frontend/requirejs-config.js | 2 +- .../templates/paypal/vault_token.phtml | 49 +++ .../payment/method-renderer/paypal-vault.js | 87 +++++ .../js/view/payment/method-renderer/paypal.js | 134 ++++++- .../js/view/payment/method-renderer/vault.js | 5 +- .../frontend/web/template/payment/form.html | 12 +- .../frontend/web/template/payment/paypal.html | 45 ++- .../web/template/payment/paypal/vault.html | 47 +++ .../Api/Data/PaymentMethodInterface.php | 43 ++ .../Api/PaymentMethodListInterface.php | 30 ++ .../Magento/Payment/Block/Form/Container.php | 73 +++- .../Payment/Block/Info/Substitution.php | 2 +- .../Gateway/Data/PaymentDataObjectFactory.php | 2 +- app/code/Magento/Payment/Helper/Data.php | 1 + .../Payment/Model/Cart/SalesModel/Factory.php | 4 +- .../CanUseForCountry/CountryProvider.php | 4 +- .../Payment/Model/Method/AbstractMethod.php | 4 +- .../Magento/Payment/Model/Method/Adapter.php | 19 +- app/code/Magento/Payment/Model/Method/Cc.php | 33 +- .../Payment/Model/Method/InstanceFactory.php | 42 ++ .../Payment/Model/Method/Substitution.php | 2 +- app/code/Magento/Payment/Model/MethodList.php | 59 ++- .../Magento/Payment/Model/PaymentMethod.php | 78 ++++ .../Payment/Model/PaymentMethodList.php | 92 +++++ .../Block/Adminhtml/Transparent/FormTest.php | 16 +- .../Test/Unit/Block/Form/ContainerTest.php | 6 +- .../Payment/Test/Unit/Block/FormTest.php | 26 +- .../Payment/Test/Unit/Block/Info/CcTest.php | 40 +- .../Unit/Block/Info/ContainerAbstractTest.php | 8 +- .../Test/Unit/Block/Info/InstructionsTest.php | 6 +- .../Test/Unit/Block/Info/SubstitutionTest.php | 21 +- .../Payment/Test/Unit/Block/InfoTest.php | 20 +- .../Test/Unit/Block/Transparent/FormTest.php | 27 +- .../Unit/Gateway/Command/CommandPoolTest.php | 16 +- .../Gateway/Command/GatewayCommandTest.php | 13 +- .../Test/Unit/Gateway/Config/ConfigTest.php | 2 +- .../Gateway/Config/ConfigValueHandlerTest.php | 2 +- .../Gateway/Config/ValueHandlerPoolTest.php | 19 +- .../Gateway/Data/Order/AddressAdapterTest.php | 2 +- .../Gateway/Data/Order/OrderAdapterTest.php | 12 +- .../Data/PaymentDataObjectFactoryTest.php | 24 +- .../Gateway/Data/PaymentDataObjectTest.php | 4 +- .../Gateway/Data/Quote/AddressAdapterTest.php | 2 +- .../Gateway/Data/Quote/QuoteAdapterTest.php | 20 +- .../Unit/Gateway/Http/Client/SoapTest.php | 11 +- .../Unit/Gateway/Http/Client/ZendTest.php | 18 +- .../Gateway/Request/BuilderCompositeTest.php | 26 +- .../Gateway/Response/HandlerChainTest.php | 16 +- .../Validator/CountryValidatorTest.php | 10 +- .../Unit/Gateway/Validator/ResultTest.php | 2 +- .../Validator/ValidatorCompositeTest.php | 25 +- .../Gateway/Validator/ValidatorPoolTest.php | 16 +- .../Payment/Test/Unit/Helper/DataTest.php | 31 +- .../Model/Cart/SalesModel/FactoryTest.php | 6 +- .../Unit/Model/Cart/SalesModel/OrderTest.php | 2 +- .../Unit/Model/Cart/SalesModel/QuoteTest.php | 8 +- .../Payment/Test/Unit/Model/CartTest.php | 6 +- .../Test/Unit/Model/CcConfigProviderTest.php | 6 +- .../Payment/Test/Unit/Model/CcConfigTest.php | 10 +- .../Model/CcGenericConfigProviderTest.php | 4 +- .../Unit/Model/Checks/CanUseCheckoutTest.php | 4 +- .../CanUseForCountry/CountryProviderTest.php | 130 +++++-- .../Model/Checks/CanUseForCountryTest.php | 6 +- .../Model/Checks/CanUseForCurrencyTest.php | 6 +- .../Unit/Model/Checks/CanUseInternalTest.php | 4 +- .../Test/Unit/Model/Checks/CompositeTest.php | 6 +- .../Model/Checks/SpecificationFactoryTest.php | 6 +- .../Unit/Model/Checks/TotalMinMaxTest.php | 4 +- .../Test/Unit/Model/Checks/ZeroTotalTest.php | 4 +- .../Unit/Model/Config/SchemaLocatorTest.php | 2 +- .../Model/Config/Source/AllmethodsTest.php | 2 +- .../Unit/Model/Config/Source/CctypeTest.php | 2 +- .../Payment/Test/Unit/Model/ConfigTest.php | 18 +- .../Payment/Test/Unit/Model/InfoTest.php | 20 +- .../Unit/Model/Method/AbstractMethodTest.php | 13 +- .../Test/Unit/Model/Method/AdapterTest.php | 117 +++--- .../Test/Unit/Model/Method/FactoryTest.php | 8 +- .../Test/Unit/Model/Method/FreeTest.php | 38 +- .../Test/Unit/Model/Method/LoggerTest.php | 2 +- .../Method/Specification/CompositeTest.php | 8 +- .../Method/Specification/FactoryTest.php | 6 +- .../Unit/Model/Method/SubstitutionTest.php | 4 +- .../Test/Unit/Model/MethodListTest.php | 77 ++-- .../Test/Unit/Model/PaymentMethodListTest.php | 215 ++++++++++ .../ResourceModel/Grid/GroupListTest.php | 2 +- .../Model/ResourceModel/Grid/TypeListTest.php | 2 +- .../Test/Unit/Model/Source/CctypeTest.php | 2 +- .../SalesOrderBeforeSaveObserverTest.php | 12 +- ...derStatusForPaymentMethodsObserverTest.php | 22 +- app/code/Magento/Payment/etc/di.xml | 2 + .../Payment/view/adminhtml/web/transparent.js | 78 ++-- .../credit-card-data.js | 19 + .../credit-card-number-validator.js | 72 ++++ .../credit-card-type.js | 140 +++++++ .../luhn10-validator.js | 22 ++ .../credit-card-validation/cvv-validator.js | 41 ++ .../expiration-date-validator.js | 51 +++ .../expiration-month-validator.js | 41 ++ .../expiration-year-validator.js | 42 ++ .../expiration-date-validator/parse-date.js | 32 ++ .../model/credit-card-validation/validator.js | 96 +++++ .../Unit/Model/Payflow/TransparentTest.php | 6 +- app/code/Magento/Paypal/etc/adminhtml/di.xml | 1 + app/code/Magento/Paypal/etc/di.xml | 5 + app/code/Magento/Sales/Model/Order.php | 2 +- .../Order/Payment/State/AuthorizeCommand.php | 24 +- .../Order/Payment/State/CaptureCommand.php | 22 +- .../Payment/State/AuthorizeCommandTest.php | 213 ++++++++++ .../Payment/State/CaptureCommandTest.php | 211 ++++++++++ .../Sales/Test/Unit/Model/OrderTest.php | 136 ++++++- app/code/Magento/Sales/i18n/en_US.csv | 8 +- .../Ui/Component/Filters/Type/Date.php | 9 +- .../Api/Data/PaymentTokenInterfaceFactory.php | 25 ++ .../Vault/Api/PaymentMethodListInterface.php | 30 ++ .../Vault/Block/AbstractCardRenderer.php | 46 +-- .../Vault/Block/AbstractTokenRenderer.php | 56 +++ .../Vault/Block/CardRendererInterface.php | 24 +- .../Vault/Block/Customer/AccountTokens.php | 22 ++ .../Vault/Block/Customer/CreditCards.php | 22 ++ .../Vault/Block/Customer/IconInterface.php | 30 ++ .../Vault/Block/Customer/PaymentTokens.php | 100 +++++ .../Vault/Block/TokenRendererInterface.php | 6 + .../Vault/Controller/Cards/DeleteAction.php | 2 +- .../Vault/Controller/Cards/ListAction.php | 2 +- .../Model/AbstractPaymentTokenFactory.php | 43 ++ .../Model/AccountPaymentTokenFactory.php | 26 ++ .../Vault/Model/CreditCardTokenFactory.php | 26 ++ app/code/Magento/Vault/Model/Method/Vault.php | 26 +- .../Magento/Vault/Model/PaymentMethodList.php | 78 ++++ .../Vault/Model/PaymentTokenManagement.php | 51 ++- .../ResourceModel/PaymentToken/Collection.php | 8 +- .../Ui/Adminhtml/TokensConfigProvider.php | 149 +++++-- .../Vault/Model/Ui/TokensConfigProvider.php | 37 +- .../Vault/Model/Ui/VaultConfigProvider.php | 44 +-- .../Vault/Observer/PaymentTokenAssigner.php | 5 +- .../Plugin/PaymentVaultAttributesLoad.php | 19 +- app/code/Magento/Vault/Setup/UpgradeData.php | 89 +++++ .../Unit/Block/Customer/AccountTokensTest.php | 73 ++++ .../Model/AccountPaymentTokenFactoryTest.php | 59 +++ .../Unit/Model/CreditCardTokenFactoryTest.php | 59 +++ .../Test/Unit/Model/Method/VaultTest.php | 157 +++++++- .../Test/Unit/Model/PaymentMethodListTest.php | 74 ++++ .../Unit/Model/PaymentTokenManagementTest.php | 6 +- .../Ui/Adminhtml/TokensConfigProviderTest.php | 368 ++++++++++++++---- .../Model/Ui/TokensConfigProviderTest.php | 33 +- .../Unit/Model/Ui/VaultConfigProviderTest.php | 32 +- .../Observer/PaymentTokenAssignerTest.php | 38 -- app/code/Magento/Vault/etc/di.xml | 1 + app/code/Magento/Vault/etc/module.xml | 2 +- .../layout/vault_cards_listaction.xml | 3 +- .../view/frontend/templates/cards_list.phtml | 8 +- .../view/frontend/templates/token_list.phtml | 27 ++ .../frontend/web/js/view/payment/vault.js | 3 +- .../web/css/source/_module.less | 98 +++++ .../web/css/source/_module.less | 24 -- .../web/css/source/_module.less | 28 -- .../Braintree/Block/Form/ContainerTest.php | 64 +++ .../Block/VaultTokenRendererTest.php | 67 ++++ .../Adminhtml/Order/PaymentReviewTest.php | 112 ++++++ .../Controller/Cards/DeleteActionTest.php | 53 +++ .../Braintree/Model/PaymentMethodListTest.php | 71 ++++ .../PayPal/TokenUiComponentProviderTest.php | 62 +++ .../Model/Ui/TokensConfigProviderTest.php | 87 +++++ .../Magento/Braintree/_files/fraud_order.php | 38 ++ .../Magento/Braintree/_files/payments.php | 16 + .../Magento/Braintree/_files/paypal_quote.php | 25 ++ .../Braintree/_files/paypal_vault_token.php | 41 ++ .../Payment/Block/Transparent/IframeTest.php | 12 +- .../Model/PaymentTokenRepositoryTest.php | 80 ++++ .../Model/ResourceModel/PaymentTokenTest.php | 114 ++++++ .../Magento/Vault/_files/customer.php | 34 ++ .../Magento/Vault/_files/payment_tokens.php | 54 +++ .../Test/Js/_files/blacklist/magento.txt | 9 - 237 files changed, 7940 insertions(+), 1340 deletions(-) create mode 100644 app/code/Magento/Braintree/Block/Customer/PayPal/VaultTokenRenderer.php create mode 100644 app/code/Magento/Braintree/Gateway/Request/DescriptorDataBuilder.php create mode 100644 app/code/Magento/Braintree/Gateway/Request/PayPal/DeviceDataBuilder.php create mode 100644 app/code/Magento/Braintree/Gateway/Request/PayPal/VaultDataBuilder.php create mode 100644 app/code/Magento/Braintree/Gateway/Response/PayPal/VaultDetailsHandler.php create mode 100644 app/code/Magento/Braintree/Model/Ui/Adminhtml/PayPal/TokenUiComponentProvider.php create mode 100644 app/code/Magento/Braintree/Model/Ui/PayPal/ConfigProvider.php create mode 100644 app/code/Magento/Braintree/Model/Ui/PayPal/TokenUiComponentProvider.php create mode 100644 app/code/Magento/Braintree/Test/Unit/Gateway/Request/DescriptorDataBuilderTest.php create mode 100644 app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/DeviceDataBuilderTest.php create mode 100644 app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/VaultDataBuilderTest.php create mode 100644 app/code/Magento/Braintree/Test/Unit/Gateway/Response/PayPal/VaultDetailsHandlerTest.php create mode 100644 app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php create mode 100644 app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/ConfigProviderTest.php create mode 100644 app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/TokenUiComponentProviderTest.php create mode 100644 app/code/Magento/Braintree/Test/Unit/Ui/Component/Report/Filters/Type/DateRangeTest.php create mode 100644 app/code/Magento/Braintree/Ui/Component/Report/Filters/Type/DateRange.php create mode 100644 app/code/Magento/Braintree/view/adminhtml/templates/form/paypal/vault.phtml create mode 100644 app/code/Magento/Braintree/view/base/web/images/paypal-small.png create mode 100644 app/code/Magento/Braintree/view/base/web/images/paypal.png create mode 100644 app/code/Magento/Braintree/view/frontend/templates/paypal/vault_token.phtml create mode 100644 app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/paypal-vault.js create mode 100644 app/code/Magento/Braintree/view/frontend/web/template/payment/paypal/vault.html create mode 100644 app/code/Magento/Payment/Api/Data/PaymentMethodInterface.php create mode 100644 app/code/Magento/Payment/Api/PaymentMethodListInterface.php create mode 100644 app/code/Magento/Payment/Model/Method/InstanceFactory.php create mode 100644 app/code/Magento/Payment/Model/PaymentMethod.php create mode 100644 app/code/Magento/Payment/Model/PaymentMethodList.php create mode 100644 app/code/Magento/Payment/Test/Unit/Model/PaymentMethodListTest.php create mode 100644 app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-data.js create mode 100644 app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator.js create mode 100644 app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator/credit-card-type.js create mode 100644 app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator/luhn10-validator.js create mode 100644 app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/cvv-validator.js create mode 100644 app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator.js create mode 100644 app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator.js create mode 100644 app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/expiration-year-validator.js create mode 100644 app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/parse-date.js create mode 100644 app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/validator.js create mode 100644 app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/AuthorizeCommandTest.php create mode 100644 app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/CaptureCommandTest.php create mode 100644 app/code/Magento/Vault/Api/Data/PaymentTokenInterfaceFactory.php create mode 100644 app/code/Magento/Vault/Api/PaymentMethodListInterface.php create mode 100644 app/code/Magento/Vault/Block/AbstractTokenRenderer.php create mode 100644 app/code/Magento/Vault/Block/Customer/AccountTokens.php create mode 100644 app/code/Magento/Vault/Block/Customer/CreditCards.php create mode 100644 app/code/Magento/Vault/Block/Customer/IconInterface.php create mode 100644 app/code/Magento/Vault/Block/Customer/PaymentTokens.php create mode 100644 app/code/Magento/Vault/Model/AbstractPaymentTokenFactory.php create mode 100644 app/code/Magento/Vault/Model/AccountPaymentTokenFactory.php create mode 100644 app/code/Magento/Vault/Model/CreditCardTokenFactory.php create mode 100644 app/code/Magento/Vault/Model/PaymentMethodList.php create mode 100644 app/code/Magento/Vault/Setup/UpgradeData.php create mode 100644 app/code/Magento/Vault/Test/Unit/Block/Customer/AccountTokensTest.php create mode 100644 app/code/Magento/Vault/Test/Unit/Model/AccountPaymentTokenFactoryTest.php create mode 100644 app/code/Magento/Vault/Test/Unit/Model/CreditCardTokenFactoryTest.php create mode 100644 app/code/Magento/Vault/Test/Unit/Model/PaymentMethodListTest.php create mode 100644 app/code/Magento/Vault/view/frontend/templates/token_list.phtml delete mode 100644 app/design/frontend/Magento/blank/Magento_BraintreeTwo/web/css/source/_module.less delete mode 100644 app/design/frontend/Magento/luma/Magento_BraintreeTwo/web/css/source/_module.less create mode 100644 dev/tests/integration/testsuite/Magento/Braintree/Block/Form/ContainerTest.php create mode 100644 dev/tests/integration/testsuite/Magento/Braintree/Block/VaultTokenRendererTest.php create mode 100644 dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Order/PaymentReviewTest.php create mode 100644 dev/tests/integration/testsuite/Magento/Braintree/Controller/Cards/DeleteActionTest.php create mode 100644 dev/tests/integration/testsuite/Magento/Braintree/Model/PaymentMethodListTest.php create mode 100644 dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php create mode 100644 dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/TokensConfigProviderTest.php create mode 100644 dev/tests/integration/testsuite/Magento/Braintree/_files/fraud_order.php create mode 100644 dev/tests/integration/testsuite/Magento/Braintree/_files/payments.php create mode 100644 dev/tests/integration/testsuite/Magento/Braintree/_files/paypal_quote.php create mode 100644 dev/tests/integration/testsuite/Magento/Braintree/_files/paypal_vault_token.php create mode 100644 dev/tests/integration/testsuite/Magento/Vault/Model/PaymentTokenRepositoryTest.php create mode 100644 dev/tests/integration/testsuite/Magento/Vault/Model/ResourceModel/PaymentTokenTest.php create mode 100644 dev/tests/integration/testsuite/Magento/Vault/_files/customer.php create mode 100644 dev/tests/integration/testsuite/Magento/Vault/_files/payment_tokens.php diff --git a/app/code/Magento/Braintree/Block/Customer/PayPal/VaultTokenRenderer.php b/app/code/Magento/Braintree/Block/Customer/PayPal/VaultTokenRenderer.php new file mode 100644 index 0000000000000..0af012352a2b8 --- /dev/null +++ b/app/code/Magento/Braintree/Block/Customer/PayPal/VaultTokenRenderer.php @@ -0,0 +1,76 @@ +config = $config; + } + + /** + * @inheritdoc + */ + public function getIconUrl() + { + return $this->config->getPayPalIcon()['url']; + } + + /** + * @inheritdoc + */ + public function getIconHeight() + { + return $this->config->getPayPalIcon()['height']; + } + + /** + * @inheritdoc + */ + public function getIconWidth() + { + return $this->config->getPayPalIcon()['width']; + } + + /** + * Can render specified token + * + * @param PaymentTokenInterface $token + * @return boolean + */ + public function canRender(PaymentTokenInterface $token) + { + return $token->getPaymentMethodCode() === ConfigProvider::PAYPAL_CODE; + } + + /** + * Get email of PayPal payer + * @return string + */ + public function getPayerEmail() + { + return $this->getTokenDetails()['payerEmail']; + } +} diff --git a/app/code/Magento/Braintree/Gateway/Command/CaptureStrategyCommand.php b/app/code/Magento/Braintree/Gateway/Command/CaptureStrategyCommand.php index 3119042b776e2..a03546b366045 100644 --- a/app/code/Magento/Braintree/Gateway/Command/CaptureStrategyCommand.php +++ b/app/code/Magento/Braintree/Gateway/Command/CaptureStrategyCommand.php @@ -166,16 +166,25 @@ private function isExpiredAuthorization(OrderPaymentInterface $payment) */ private function isExistsCaptureTransaction(OrderPaymentInterface $payment) { - $filters[] = $this->filterBuilder->setField('payment_id') - ->setValue($payment->getId()) - ->create(); + $this->searchCriteriaBuilder->addFilters( + [ + $this->filterBuilder + ->setField('payment_id') + ->setValue($payment->getId()) + ->create(), + ] + ); - $filters[] = $this->filterBuilder->setField('txn_type') - ->setValue(TransactionInterface::TYPE_CAPTURE) - ->create(); + $this->searchCriteriaBuilder->addFilters( + [ + $this->filterBuilder + ->setField('txn_type') + ->setValue(TransactionInterface::TYPE_CAPTURE) + ->create(), + ] + ); - $searchCriteria = $this->searchCriteriaBuilder->addFilters($filters) - ->create(); + $searchCriteria = $this->searchCriteriaBuilder->create(); $count = $this->transactionRepository->getList($searchCriteria)->getTotalCount(); return (boolean) $count; diff --git a/app/code/Magento/Braintree/Gateway/Config/Config.php b/app/code/Magento/Braintree/Gateway/Config/Config.php index 4d612bf5e64f3..774b8e365368f 100644 --- a/app/code/Magento/Braintree/Gateway/Config/Config.php +++ b/app/code/Magento/Braintree/Gateway/Config/Config.php @@ -30,6 +30,14 @@ class Config extends \Magento\Payment\Gateway\Config\Config const KEY_KOUNT_MERCHANT_ID = 'kount_id'; const FRAUD_PROTECTION = 'fraudprotection'; + /** + * Get list of available dynamic descriptors keys + * @var array + */ + private static $dynamicDescriptorKeys = [ + 'name', 'phone', 'url' + ]; + /** * Return the country specific card type config * @@ -170,6 +178,22 @@ public function isActive() return (bool) $this->getValue(self::KEY_ACTIVE); } + /** + * Get list of configured dynamic descriptors + * @return array + */ + public function getDynamicDescriptors() + { + $values = []; + foreach (self::$dynamicDescriptorKeys as $key) { + $value = $this->getValue('descriptor_' . $key); + if (!empty($value)) { + $values[$key] = $value; + } + } + return $values; + } + /** * Get Merchant account ID * diff --git a/app/code/Magento/Braintree/Gateway/Config/PayPal/Config.php b/app/code/Magento/Braintree/Gateway/Config/PayPal/Config.php index 06ff216acd49c..f94c6abfd773b 100644 --- a/app/code/Magento/Braintree/Gateway/Config/PayPal/Config.php +++ b/app/code/Magento/Braintree/Gateway/Config/PayPal/Config.php @@ -5,6 +5,9 @@ */ namespace Magento\Braintree\Gateway\Config\PayPal; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Payment\Model\CcConfig; + /** * Class Config */ @@ -22,6 +25,26 @@ class Config extends \Magento\Payment\Gateway\Config\Config const KEY_REQUIRE_BILLING_ADDRESS = 'require_billing_address'; + /** + * @var CcConfig + */ + private $ccConfig; + + /** + * @var array + */ + private $icon = []; + + public function __construct( + ScopeConfigInterface $scopeConfig, + CcConfig $ccConfig, + $methodCode = null, + $pathPattern = self::DEFAULT_PATH_PATTERN + ) { + parent::__construct($scopeConfig, $methodCode, $pathPattern); + $this->ccConfig = $ccConfig; + } + /** * Get Payment configuration status * @@ -79,4 +102,32 @@ public function getTitle() { return $this->getValue(self::KEY_TITLE); } + + /** + * Is need to skip order review + * @return bool + */ + public function isSkipOrderReview() + { + return (bool) $this->getValue('skip_order_review'); + } + + /** + * Get PayPal icon + * @return array + */ + public function getPayPalIcon() + { + if (empty($this->icon)) { + $asset = $this->ccConfig->createAsset('Magento_Braintree::images/paypal.png'); + list($width, $height) = getimagesize($asset->getSourceFile()); + $this->icon = [ + 'url' => $asset->getUrl(), + 'width' => $width, + 'height' => $height + ]; + } + + return $this->icon; + } } diff --git a/app/code/Magento/Braintree/Gateway/Helper/SubjectReader.php b/app/code/Magento/Braintree/Gateway/Helper/SubjectReader.php index c91abc49b2dd2..e5082a5df6fdd 100644 --- a/app/code/Magento/Braintree/Gateway/Helper/SubjectReader.php +++ b/app/code/Magento/Braintree/Gateway/Helper/SubjectReader.php @@ -83,7 +83,7 @@ public function readAmount(array $subject) */ public function readCustomerId(array $subject) { - if (empty($subject['customer_id'])) { + if (!isset($subject['customer_id'])) { throw new \InvalidArgumentException('The "customerId" field does not exists'); } diff --git a/app/code/Magento/Braintree/Gateway/Request/DescriptorDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/DescriptorDataBuilder.php new file mode 100644 index 0000000000000..f2c5515eac712 --- /dev/null +++ b/app/code/Magento/Braintree/Gateway/Request/DescriptorDataBuilder.php @@ -0,0 +1,44 @@ +config = $config; + } + + /** + * @inheritdoc + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function build(array $buildSubject) + { + $values = $this->config->getDynamicDescriptors(); + return !empty($values) ? [self::$descriptorKey => $values] : []; + } +} diff --git a/app/code/Magento/Braintree/Gateway/Request/PayPal/DeviceDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/PayPal/DeviceDataBuilder.php new file mode 100644 index 0000000000000..bac5dc5fa0e0a --- /dev/null +++ b/app/code/Magento/Braintree/Gateway/Request/PayPal/DeviceDataBuilder.php @@ -0,0 +1,52 @@ +subjectReader = $subjectReader; + } + + /** + * @inheritdoc + */ + public function build(array $buildSubject) + { + $result = []; + $paymentDO = $this->subjectReader->readPayment($buildSubject); + + $payment = $paymentDO->getPayment(); + $data = $payment->getAdditionalInformation(); + if (!empty($data[DataAssignObserver::DEVICE_DATA])) { + $result[self::$deviceDataKey] = $data[DataAssignObserver::DEVICE_DATA]; + } + + return $result; + } +} diff --git a/app/code/Magento/Braintree/Gateway/Request/PayPal/VaultDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/PayPal/VaultDataBuilder.php new file mode 100644 index 0000000000000..efffdbf5fef27 --- /dev/null +++ b/app/code/Magento/Braintree/Gateway/Request/PayPal/VaultDataBuilder.php @@ -0,0 +1,60 @@ +subjectReader = $subjectReader; + } + + /** + * @inheritdoc + */ + public function build(array $buildSubject) + { + $result = []; + $paymentDO = $this->subjectReader->readPayment($buildSubject); + + $payment = $paymentDO->getPayment(); + $data = $payment->getAdditionalInformation(); + if (!empty($data[VaultConfigProvider::IS_ACTIVE_CODE])) { + $result[self::$optionsKey] = [ + self::$storeInVaultOnSuccess => true + ]; + } + + return $result; + } +} diff --git a/app/code/Magento/Braintree/Gateway/Request/VaultDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/VaultDataBuilder.php index 728089d0cab73..3165b67cc5c49 100644 --- a/app/code/Magento/Braintree/Gateway/Request/VaultDataBuilder.php +++ b/app/code/Magento/Braintree/Gateway/Request/VaultDataBuilder.php @@ -18,9 +18,8 @@ class VaultDataBuilder implements BuilderInterface const OPTIONS = 'options'; /** - * The option that determines whether the shipping address information - * provided with the transaction should be associated with the customer ID specified. - * When passed, the payment method will always be stored in the Vault. + * The option that determines whether the payment method associated with + * the successful transaction should be stored in the Vault. */ const STORE_IN_VAULT_ON_SUCCESS = 'storeInVaultOnSuccess'; diff --git a/app/code/Magento/Braintree/Gateway/Response/PayPal/VaultDetailsHandler.php b/app/code/Magento/Braintree/Gateway/Response/PayPal/VaultDetailsHandler.php new file mode 100644 index 0000000000000..c43f68fc608f4 --- /dev/null +++ b/app/code/Magento/Braintree/Gateway/Response/PayPal/VaultDetailsHandler.php @@ -0,0 +1,130 @@ +paymentTokenFactory = $paymentTokenFactory; + $this->paymentExtensionFactory = $paymentExtensionFactory; + $this->subjectReader = $subjectReader; + $this->dateTimeFactory = $dateTimeFactory; + } + + /** + * @inheritdoc + */ + public function handle(array $handlingSubject, array $response) + { + $paymentDO = $this->subjectReader->readPayment($handlingSubject); + $transaction = $this->subjectReader->readTransaction($response); + $payment = $paymentDO->getPayment(); + + // add vault payment token entity to extension attributes + $paymentToken = $this->getVaultPaymentToken($transaction); + if ($paymentToken !== null) { + $extensionAttributes = $this->getExtensionAttributes($payment); + $extensionAttributes->setVaultPaymentToken($paymentToken); + } + } + + /** + * Get vault payment token entity + * + * @param \Braintree\Transaction $transaction + * @return PaymentTokenInterface|null + */ + private function getVaultPaymentToken(Transaction $transaction) + { + // Check token existing in gateway response + $token = $transaction->paypalDetails->token; + if (empty($token)) { + return null; + } + + /** @var PaymentTokenInterface $paymentToken */ + $paymentToken = $this->paymentTokenFactory->create(); + $paymentToken->setGatewayToken($token); + $paymentToken->setExpiresAt($this->getExpirationDate()); + $details = json_encode([ + 'payerEmail' => $transaction->paypalDetails->payerEmail + ]); + $paymentToken->setTokenDetails($details); + + return $paymentToken; + } + + /** + * @return string + */ + private function getExpirationDate() + { + $expDate = $this->dateTimeFactory->create('now', new \DateTimeZone('UTC')); + $expDate->add(new \DateInterval('P1Y')); + return $expDate->format('Y-m-d 00:00:00'); + } + + /** + * Get payment extension attributes + * @param InfoInterface $payment + * @return OrderPaymentExtensionInterface + */ + private function getExtensionAttributes(InfoInterface $payment) + { + $extensionAttributes = $payment->getExtensionAttributes(); + if ($extensionAttributes === null) { + $extensionAttributes = $this->paymentExtensionFactory->create(); + $payment->setExtensionAttributes($extensionAttributes); + } + return $extensionAttributes; + } +} diff --git a/app/code/Magento/Braintree/Gateway/Response/RiskDataHandler.php b/app/code/Magento/Braintree/Gateway/Response/RiskDataHandler.php index 46d415c97b7c6..6cadf252e7a3b 100644 --- a/app/code/Magento/Braintree/Gateway/Response/RiskDataHandler.php +++ b/app/code/Magento/Braintree/Gateway/Response/RiskDataHandler.php @@ -24,6 +24,11 @@ class RiskDataHandler implements HandlerInterface */ const RISK_DATA_DECISION = 'riskDataDecision'; + /** + * Risk data Review status + */ + private static $statusReview = 'Review'; + /** * @var SubjectReader */ @@ -62,5 +67,10 @@ public function handle(array $handlingSubject, array $response) $payment->setAdditionalInformation(self::RISK_DATA_ID, $transaction->riskData->id); $payment->setAdditionalInformation(self::RISK_DATA_DECISION, $transaction->riskData->decision); + + // mark payment as fraud + if ($transaction->riskData->decision === self::$statusReview) { + $payment->setIsFraudDetected(true); + } } } diff --git a/app/code/Magento/Braintree/Gateway/Validator/ResponseValidator.php b/app/code/Magento/Braintree/Gateway/Validator/ResponseValidator.php index d2add721c4bcf..346d43f3312e1 100644 --- a/app/code/Magento/Braintree/Gateway/Validator/ResponseValidator.php +++ b/app/code/Magento/Braintree/Gateway/Validator/ResponseValidator.php @@ -25,7 +25,8 @@ protected function getResponseValidators() [ function ($response) { return [ - isset($response->transaction) + $response instanceof Successful + && isset($response->transaction) && in_array( $response->transaction->status, [Transaction::AUTHORIZED, Transaction::SUBMITTED_FOR_SETTLEMENT, Transaction::SETTLING] diff --git a/app/code/Magento/Braintree/Helper/Country.php b/app/code/Magento/Braintree/Helper/Country.php index 3a3116b0d9ac0..e8660b8523b30 100644 --- a/app/code/Magento/Braintree/Helper/Country.php +++ b/app/code/Magento/Braintree/Helper/Country.php @@ -6,6 +6,7 @@ namespace Magento\Braintree\Helper; use Magento\Directory\Model\ResourceModel\Country\CollectionFactory; +use Magento\Braintree\Model\Adminhtml\System\Config\Country as CountryConfig; /** * Class Country @@ -13,12 +14,12 @@ class Country { /** - * @var \Magento\Directory\Model\ResourceModel\Country\CollectionFactory + * @var CollectionFactory */ private $collectionFactory; /** - * @var \Magento\Braintree\Model\Adminhtml\System\Config\Country + * @var CountryConfig */ private $countryConfig; @@ -28,13 +29,11 @@ class Country private $countries; /** - * @param \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $factory - * @param \Magento\Braintree\Model\Adminhtml\System\Config\Country $countryConfig + * @param CollectionFactory $factory + * @param CountryConfig $countryConfig */ - public function __construct( - \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $factory, - \Magento\Braintree\Model\Adminhtml\System\Config\Country $countryConfig - ) { + public function __construct(CollectionFactory $factory, CountryConfig $countryConfig) + { $this->collectionFactory = $factory; $this->countryConfig = $countryConfig; } diff --git a/app/code/Magento/Braintree/Model/Paypal/Helper/QuoteUpdater.php b/app/code/Magento/Braintree/Model/Paypal/Helper/QuoteUpdater.php index ef6bfaccecdb6..4cfbf0f3a833f 100644 --- a/app/code/Magento/Braintree/Model/Paypal/Helper/QuoteUpdater.php +++ b/app/code/Magento/Braintree/Model/Paypal/Helper/QuoteUpdater.php @@ -5,14 +5,13 @@ */ namespace Magento\Braintree\Model\Paypal\Helper; +use Magento\Braintree\Gateway\Config\PayPal\Config; +use Magento\Braintree\Model\Ui\PayPal\ConfigProvider; +use Magento\Braintree\Observer\DataAssignObserver; +use Magento\Framework\Exception\LocalizedException; +use Magento\Quote\Api\CartRepositoryInterface; use Magento\Quote\Model\Quote; use Magento\Quote\Model\Quote\Address; -use Magento\Quote\Model\Quote\Payment; -use Magento\Quote\Api\CartRepositoryInterface; -use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Framework\Exception\LocalizedException; -use Magento\Braintree\Observer\DataAssignObserver; -use Magento\Braintree\Gateway\Config\PayPal\Config; /** * Class QuoteUpdater diff --git a/app/code/Magento/Braintree/Model/Report/Row/TransactionMap.php b/app/code/Magento/Braintree/Model/Report/Row/TransactionMap.php index 0abae8af89fbc..c914b21893e25 100644 --- a/app/code/Magento/Braintree/Model/Report/Row/TransactionMap.php +++ b/app/code/Magento/Braintree/Model/Report/Row/TransactionMap.php @@ -115,9 +115,13 @@ public function setCustomAttribute($attributeCode, $attributeValue) */ public function getCustomAttributes() { + $shouldBeLocalized = ['paymentInstrumentType', 'type', 'status']; $output = []; foreach ($this->getMappedValues() as $key => $value) { $attribute = $this->attributeValueFactory->create(); + if(in_array($key, $shouldBeLocalized)) { + $value = __($value); + } $output[] = $attribute->setAttributeCode($key)->setValue($value); } return $output; diff --git a/app/code/Magento/Braintree/Model/Report/TransactionsCollection.php b/app/code/Magento/Braintree/Model/Report/TransactionsCollection.php index f52f19c0ab6f0..7b177cff3af1d 100644 --- a/app/code/Magento/Braintree/Model/Report/TransactionsCollection.php +++ b/app/code/Magento/Braintree/Model/Report/TransactionsCollection.php @@ -6,6 +6,7 @@ namespace Magento\Braintree\Model\Report; use Magento\Braintree\Model\Adapter\BraintreeAdapter; +use Magento\Braintree\Model\Report\Row\TransactionMap; use Magento\Framework\Api\Search\SearchResultInterface; use Magento\Framework\Api\SearchCriteriaInterface; use Magento\Framework\Data\Collection; @@ -26,7 +27,7 @@ class TransactionsCollection extends Collection implements SearchResultInterface * * @var string */ - protected $_itemObjectClass = 'Magento\Braintree\Model\Report\Row\TransactionMap'; + protected $_itemObjectClass = TransactionMap::class; /** * @var array diff --git a/app/code/Magento/Braintree/Model/Ui/Adminhtml/PayPal/TokenUiComponentProvider.php b/app/code/Magento/Braintree/Model/Ui/Adminhtml/PayPal/TokenUiComponentProvider.php new file mode 100644 index 0000000000000..fd94e18e2cd94 --- /dev/null +++ b/app/code/Magento/Braintree/Model/Ui/Adminhtml/PayPal/TokenUiComponentProvider.php @@ -0,0 +1,84 @@ +componentFactory = $componentFactory; + $this->urlBuilder = $urlBuilder; + $this->config = $config; + } + + /** + * @inheritdoc + */ + public function getComponentForToken(PaymentTokenInterface $paymentToken) + { + $data = json_decode($paymentToken->getTokenDetails() ?: '{}', true); + $data['icon'] = $this->config->getPayPalIcon(); + $component = $this->componentFactory->create( + [ + 'config' => [ + 'code' => PayPalConfigProvider::PAYPAL_VAULT_CODE, + 'nonceUrl' => $this->getNonceRetrieveUrl(), + TokenUiComponentProviderInterface::COMPONENT_DETAILS => $data, + TokenUiComponentProviderInterface::COMPONENT_PUBLIC_HASH => $paymentToken->getPublicHash(), + 'template' => 'Magento_Braintree::form/paypal/vault.phtml' + ], + 'name' => Template::class + ] + ); + + return $component; + } + + /** + * Get url to retrieve payment method nonce + * @return string + */ + private function getNonceRetrieveUrl() + { + return $this->urlBuilder->getUrl(ConfigProvider::CODE . '/payment/getnonce', ['_secure' => true]); + } +} diff --git a/app/code/Magento/Braintree/Model/Ui/Adminhtml/TokenUiComponentProvider.php b/app/code/Magento/Braintree/Model/Ui/Adminhtml/TokenUiComponentProvider.php index 6cfc96ea23d0d..420b8365b3ea4 100644 --- a/app/code/Magento/Braintree/Model/Ui/Adminhtml/TokenUiComponentProvider.php +++ b/app/code/Magento/Braintree/Model/Ui/Adminhtml/TokenUiComponentProvider.php @@ -49,6 +49,7 @@ public function getComponentForToken(PaymentTokenInterface $paymentToken) $component = $this->componentFactory->create( [ 'config' => [ + 'code' => ConfigProvider::CC_VAULT_CODE, 'nonceUrl' => $this->getNonceRetrieveUrl(), TokenUiComponentProviderInterface::COMPONENT_DETAILS => $data, TokenUiComponentProviderInterface::COMPONENT_PUBLIC_HASH => $paymentToken->getPublicHash(), diff --git a/app/code/Magento/Braintree/Model/Ui/ConfigProvider.php b/app/code/Magento/Braintree/Model/Ui/ConfigProvider.php index 3a7a773c33c46..76788c3c14510 100644 --- a/app/code/Magento/Braintree/Model/Ui/ConfigProvider.php +++ b/app/code/Magento/Braintree/Model/Ui/ConfigProvider.php @@ -8,9 +8,7 @@ use Magento\Braintree\Gateway\Request\PaymentDataBuilder; use Magento\Checkout\Model\ConfigProviderInterface; use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Gateway\Config\PayPal\Config as PayPalConfig; use Magento\Braintree\Model\Adapter\BraintreeAdapter; -use Magento\Framework\Locale\ResolverInterface; /** * Class ConfigProvider @@ -19,25 +17,13 @@ final class ConfigProvider implements ConfigProviderInterface { const CODE = 'braintree'; - const PAYPAL_CODE = 'braintree_paypal'; - const CC_VAULT_CODE = 'braintree_cc_vault'; - /** - * @var ResolverInterface - */ - private $localeResolver; - /** * @var Config */ private $config; - /** - * @var PayPalConfig - */ - private $payPalConfig; - /** * @var BraintreeAdapter */ @@ -52,20 +38,14 @@ final class ConfigProvider implements ConfigProviderInterface * Constructor * * @param Config $config - * @param PayPalConfig $payPalConfig; * @param BraintreeAdapter $adapter - * @param ResolverInterface $localeResolver */ public function __construct( Config $config, - PayPalConfig $payPalConfig, - BraintreeAdapter $adapter, - ResolverInterface $localeResolver + BraintreeAdapter $adapter ) { $this->config = $config; - $this->payPalConfig = $payPalConfig; $this->adapter = $adapter; - $this->localeResolver = $localeResolver; } /** @@ -75,7 +55,6 @@ public function __construct( */ public function getConfig() { - $isPayPalActive = $this->payPalConfig->isActive(); return [ 'payment' => [ self::CODE => [ @@ -90,22 +69,13 @@ public function getConfig() 'kountMerchantId' => $this->config->getKountMerchantId(), 'hasFraudProtection' => $this->config->hasFraudProtection(), 'merchantId' => $this->config->getMerchantId(), - 'ccVaultCode' => static::CC_VAULT_CODE + 'ccVaultCode' => self::CC_VAULT_CODE ], Config::CODE_3DSECURE => [ 'enabled' => $this->config->isVerify3DSecure(), 'thresholdAmount' => $this->config->getThresholdAmount(), 'specificCountries' => $this->config->get3DSecureSpecificCountries() ], - self::PAYPAL_CODE => [ - 'isActive' => $isPayPalActive, - 'title' => $this->payPalConfig->getTitle(), - 'isAllowShippingAddressOverride' => $this->payPalConfig->isAllowToEditShippingAddress(), - 'merchantName' => $this->payPalConfig->getMerchantName(), - 'locale' => strtolower($this->localeResolver->getLocale()), - 'paymentAcceptanceMarkSrc' => - 'https://www.paypalobjects.com/webstatic/en_US/i/buttons/pp-acceptance-medium.png', - ] ] ]; } diff --git a/app/code/Magento/Braintree/Model/Ui/PayPal/ConfigProvider.php b/app/code/Magento/Braintree/Model/Ui/PayPal/ConfigProvider.php new file mode 100644 index 0000000000000..65fb5370181db --- /dev/null +++ b/app/code/Magento/Braintree/Model/Ui/PayPal/ConfigProvider.php @@ -0,0 +1,56 @@ +config = $config; + $this->resolver = $resolver; + } + + public function getConfig() + { + return [ + 'payment' => [ + self::PAYPAL_CODE => [ + 'isActive' => $this->config->isActive(), + 'title' => $this->config->getTitle(), + 'isAllowShippingAddressOverride' => $this->config->isAllowToEditShippingAddress(), + 'merchantName' => $this->config->getMerchantName(), + 'locale' => strtolower($this->resolver->getLocale()), + 'paymentAcceptanceMarkSrc' => + 'https://www.paypalobjects.com/webstatic/en_US/i/buttons/pp-acceptance-medium.png', + 'vaultCode' => self::PAYPAL_VAULT_CODE, + 'skipOrderReview' => $this->config->isSkipOrderReview(), + 'paymentIcon' => $this->config->getPayPalIcon(), + ] + ] + ]; + } +} diff --git a/app/code/Magento/Braintree/Model/Ui/PayPal/TokenUiComponentProvider.php b/app/code/Magento/Braintree/Model/Ui/PayPal/TokenUiComponentProvider.php new file mode 100644 index 0000000000000..2f3e3db75cc34 --- /dev/null +++ b/app/code/Magento/Braintree/Model/Ui/PayPal/TokenUiComponentProvider.php @@ -0,0 +1,73 @@ +componentFactory = $componentFactory; + $this->urlBuilder = $urlBuilder; + } + + /** + * Get UI component for token + * @param PaymentTokenInterface $paymentToken + * @return TokenUiComponentInterface + */ + public function getComponentForToken(PaymentTokenInterface $paymentToken) + { + $jsonDetails = json_decode($paymentToken->getTokenDetails() ?: '{}', true); + $component = $this->componentFactory->create( + [ + 'config' => [ + 'code' => ConfigProvider::PAYPAL_VAULT_CODE, + 'nonceUrl' => $this->getNonceRetrieveUrl(), + TokenUiComponentProviderInterface::COMPONENT_DETAILS => $jsonDetails, + TokenUiComponentProviderInterface::COMPONENT_PUBLIC_HASH => $paymentToken->getPublicHash() + ], + 'name' => 'Magento_Braintree/js/view/payment/method-renderer/paypal-vault' + ] + ); + + return $component; + } + + /** + * Get url to retrieve payment method nonce + * @return string + */ + private function getNonceRetrieveUrl() + { + return $this->urlBuilder->getUrl(CommonConfigProvider::CODE . '/payment/getnonce', ['_secure' => true]); + } +} diff --git a/app/code/Magento/Braintree/Observer/AddPaypalShortcuts.php b/app/code/Magento/Braintree/Observer/AddPaypalShortcuts.php index bbf4b91ef474f..e5be5c2bab43c 100644 --- a/app/code/Magento/Braintree/Observer/AddPaypalShortcuts.php +++ b/app/code/Magento/Braintree/Observer/AddPaypalShortcuts.php @@ -5,8 +5,9 @@ */ namespace Magento\Braintree\Observer; -use Magento\Framework\Event\Observer; +use Magento\Braintree\Block\Paypal\Button; use Magento\Catalog\Block\ShortcutButtons; +use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; /** @@ -17,7 +18,7 @@ class AddPaypalShortcuts implements ObserverInterface /** * Block class */ - const PAYPAL_SHORTCUT_BLOCK = 'Magento\Braintree\Block\Paypal\Button'; + const PAYPAL_SHORTCUT_BLOCK = Button::class; /** * Add Braintree PayPal shortcut buttons diff --git a/app/code/Magento/Braintree/Test/Unit/Block/FormTest.php b/app/code/Magento/Braintree/Test/Unit/Block/FormTest.php index f056ba0cefd36..e6c7ce59d0e29 100644 --- a/app/code/Magento/Braintree/Test/Unit/Block/FormTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Block/FormTest.php @@ -16,7 +16,6 @@ use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\StoreManagerInterface; use Magento\Vault\Model\VaultPaymentInterface; -use OAuthTest\Mocks\Common\Service\Mock; use PHPUnit_Framework_MockObject_MockObject as MockObject; /** diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Command/CaptureStrategyCommandTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Command/CaptureStrategyCommandTest.php index fda3e85d167c2..9665afa1f3655 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Command/CaptureStrategyCommandTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Command/CaptureStrategyCommandTest.php @@ -374,7 +374,7 @@ private function buildSearchCriteria() ->willReturnSelf(); $searchCriteria = new SearchCriteria(); - $this->searchCriteriaBuilder->expects(static::once()) + $this->searchCriteriaBuilder->expects(static::exactly(2)) ->method('addFilters') ->willReturnSelf(); $this->searchCriteriaBuilder->expects(static::once()) diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Config/ConfigTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Config/ConfigTest.php index 66f6c7dd78e79..e4dd13985fa9a 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Config/ConfigTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Config/ConfigTest.php @@ -271,6 +271,68 @@ public function threeDSecureSpecificCountriesDataProvider() ]; } + /** + * @covers \Magento\Braintree\Gateway\Config\Config::getDynamicDescriptors + * @param $name + * @param $phone + * @param $url + * @param array $expected + * @dataProvider descriptorsDataProvider + */ + public function testGetDynamicDescriptors($name, $phone, $url, array $expected) + { + $this->scopeConfigMock->expects(static::at(0)) + ->method('getValue') + ->with($this->getPath('descriptor_name'), ScopeInterface::SCOPE_STORE, null) + ->willReturn($name); + $this->scopeConfigMock->expects(static::at(1)) + ->method('getValue') + ->with($this->getPath('descriptor_phone'), ScopeInterface::SCOPE_STORE, null) + ->willReturn($phone); + $this->scopeConfigMock->expects(static::at(2)) + ->method('getValue') + ->with($this->getPath('descriptor_url'), ScopeInterface::SCOPE_STORE, null) + ->willReturn($url); + + $actual = $this->model->getDynamicDescriptors(); + static::assertEquals($expected, $actual); + } + + /** + * Get variations to test dynamic descriptors + * @return array + */ + public function descriptorsDataProvider() + { + $name = 'company * product'; + $phone = '333-22-22-333'; + $url = 'https://test.url.mage.com'; + return [ + [ + $name, $phone, $url, + 'expected' => [ + 'name' => $name, 'phone' => $phone, 'url' => $url + ] + ], + [ + $name, null, null, + 'expected' => [ + 'name' => $name + ] + ], + [ + null, null, $url, + 'expected' => [ + 'url' => $url + ] + ], + [ + null, null, null, + 'expected' => [] + ] + ]; + } + /** * Return config path * diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/DescriptorDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/DescriptorDataBuilderTest.php new file mode 100644 index 0000000000000..ffee329491795 --- /dev/null +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/DescriptorDataBuilderTest.php @@ -0,0 +1,105 @@ +config = $this->getMockBuilder(Config::class) + ->disableOriginalConstructor() + ->setMethods(['getDynamicDescriptors']) + ->getMock(); + + $this->builder = new DescriptorDataBuilder($this->config); + } + + /** + * @covers \Magento\Braintree\Gateway\Request\DescriptorDataBuilder::build + * @param array $descriptors + * @param array $expected + * @dataProvider buildDataProvider + */ + public function testBuild(array $descriptors, array $expected) + { + $this->config->expects(static::once()) + ->method('getDynamicDescriptors') + ->willReturn($descriptors); + + $actual = $this->builder->build([]); + static::assertEquals($expected, $actual); + } + + /** + * Get variations for build method testing + * @return array + */ + public function buildDataProvider() + { + $name = 'company * product'; + $phone = '333-22-22-333'; + $url = 'https://test.url.mage.com'; + return [ + [ + 'descriptors' => [ + 'name' => $name, + 'phone' => $phone, + 'url' => $url + ], + 'expected' => [ + 'descriptor' => [ + 'name' => $name, + 'phone' => $phone, + 'url' => $url + ] + ] + ], + [ + 'descriptors' => [ + 'name' => $name, + 'phone' => $phone + ], + 'expected' => [ + 'descriptor' => [ + 'name' => $name, + 'phone' => $phone + ] + ] + ], + [ + 'descriptors' => [ + 'name' => $name + ], + 'expected' => [ + 'descriptor' => [ + 'name' => $name + ] + ] + ], + [ + 'descriptors' => [], + 'expected' => [] + ] + ]; + } +} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/KountPaymentDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/KountPaymentDataBuilderTest.php index c695ad24376b3..f1485fe192f23 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/KountPaymentDataBuilderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/KountPaymentDataBuilderTest.php @@ -84,7 +84,7 @@ public function testBuildReadPaymentException() public function testBuild() { $additionalData = [ - DataAssignObserver::DEVICE_DATA => self::DEVICE_DATA + DataAssignObserver::DEVICE_DATA => self::DEVICE_DATA ]; $expectedResult = [ diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/DeviceDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/DeviceDataBuilderTest.php new file mode 100644 index 0000000000000..268f1d6251109 --- /dev/null +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/DeviceDataBuilderTest.php @@ -0,0 +1,115 @@ +subjectReader = $this->getMockBuilder(SubjectReader::class) + ->disableOriginalConstructor() + ->setMethods(['readPayment']) + ->getMock(); + + $this->paymentDataObject = $this->getMock(PaymentDataObjectInterface::class); + + $this->paymentInfo = $this->getMock(InfoInterface::class); + + $this->builder = new DeviceDataBuilder($this->subjectReader); + } + + /** + * @covers \Magento\Braintree\Gateway\Request\PayPal\DeviceDataBuilder::build + * @param array $paymentData + * @param array $expected + * @dataProvider buildDataProvider + */ + public function testBuild(array $paymentData, array $expected) + { + $subject = [ + 'payment' => $this->paymentDataObject + ]; + + $this->subjectReader->expects(static::once()) + ->method('readPayment') + ->with($subject) + ->willReturn($this->paymentDataObject); + + $this->paymentDataObject->expects(static::once()) + ->method('getPayment') + ->willReturn($this->paymentInfo); + + $this->paymentInfo->expects(static::once()) + ->method('getAdditionalInformation') + ->willReturn($paymentData); + + $actual = $this->builder->build($subject); + static::assertEquals($expected, $actual); + } + + /** + * Get variations for build method testing + * @return array + */ + public function buildDataProvider() + { + return [ + [ + 'paymentData' => [ + 'device_data' => '{correlation_id: 12s3jf9as}' + ], + 'expected' => [ + 'deviceData' => '{correlation_id: 12s3jf9as}' + ] + ], + [ + 'paymentData' => [ + 'device_data' => null, + ], + 'expected' => [] + ], + [ + 'paymentData' => [ + 'deviceData' => '{correlation_id: 12s3jf9as}', + ], + 'expected' => [] + ], + [ + 'paymentData' => [], + 'expected' => [] + ] + ]; + } +} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/VaultDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/VaultDataBuilderTest.php new file mode 100644 index 0000000000000..bee9ae2e06de1 --- /dev/null +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/VaultDataBuilderTest.php @@ -0,0 +1,112 @@ +paymentDataObject = $this->getMock(PaymentDataObjectInterface::class); + + $this->paymentInfo = $this->getMock(InfoInterface::class); + + $this->subjectReader = $this->getMockBuilder(SubjectReader::class) + ->disableOriginalConstructor() + ->setMethods(['readPayment']) + ->getMock(); + + $this->builder = new VaultDataBuilder($this->subjectReader); + } + + /** + * @covers \Magento\Braintree\Gateway\Request\PayPal\VaultDataBuilder::build + * @param array $additionalInfo + * @param array $expected + * @dataProvider buildDataProvider + */ + public function testBuild(array $additionalInfo, array $expected) + { + $subject = [ + 'payment' => $this->paymentDataObject + ]; + + $this->subjectReader->expects(static::once()) + ->method('readPayment') + ->with($subject) + ->willReturn($this->paymentDataObject); + + $this->paymentDataObject->expects(static::once()) + ->method('getPayment') + ->willReturn($this->paymentInfo); + + $this->paymentInfo->expects(static::once()) + ->method('getAdditionalInformation') + ->willReturn($additionalInfo); + + $actual = $this->builder->build($subject); + static::assertEquals($expected, $actual); + } + + /** + * Get variations to test build method + * @return array + */ + public function buildDataProvider() + { + return [ + [ + 'additionalInfo' => [ + VaultConfigProvider::IS_ACTIVE_CODE => true + ], + 'expected' => [ + 'options' => [ + 'storeInVaultOnSuccess' => true + ] + ] + ], + [ + 'additionalInfo' => [ + VaultConfigProvider::IS_ACTIVE_CODE => false + ], + 'expected' => [] + ], + [ + 'additionalInfo' => [], + 'expected' => [] + ], + ]; + } +} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VaultCaptureDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VaultCaptureDataBuilderTest.php index b5df7f312ec61..165bc94aa6842 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VaultCaptureDataBuilderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VaultCaptureDataBuilderTest.php @@ -5,14 +5,12 @@ */ namespace Magento\Braintree\Test\Unit\Gateway\Request; -use Magento\Braintree\Gateway\Config\Config; +use Magento\Braintree\Gateway\Helper\SubjectReader; use Magento\Braintree\Gateway\Request\VaultCaptureDataBuilder; -use Magento\Braintree\Observer\DataAssignObserver; use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; +use Magento\Sales\Api\Data\OrderPaymentExtension; use Magento\Sales\Model\Order\Payment; -use Magento\Braintree\Gateway\Helper\SubjectReader; use Magento\Vault\Model\PaymentToken; -use Magento\Sales\Api\Data\OrderPaymentExtension; class VaultCaptureDataBuilderTest extends \PHPUnit_Framework_TestCase { @@ -82,7 +80,7 @@ public function testBuild() $paymentExtension = $this->getMockBuilder(OrderPaymentExtension::class) ->setMethods(['getVaultPaymentToken']) ->disableOriginalConstructor() - ->getMock(); + ->getMockForAbstractClass(); $paymentToken = $this->getMockBuilder(PaymentToken::class) ->disableOriginalConstructor() diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PayPal/VaultDetailsHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PayPal/VaultDetailsHandlerTest.php new file mode 100644 index 0000000000000..be2239151a2db --- /dev/null +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PayPal/VaultDetailsHandlerTest.php @@ -0,0 +1,252 @@ +paymentDataObject = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); + + $this->paymentInfo = $this->getMockBuilder(Payment::class) + ->disableOriginalConstructor() + ->setMethods(['__wakeup']) + ->getMock(); + + $this->paymentToken = $objectManager->getObject(PaymentToken::class); + + $this->paymentTokenFactory = $this->getMockBuilder(AccountPaymentTokenFactory::class) + ->setMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + + $this->paymentExtension = $this->getMockBuilder(OrderPaymentExtensionInterface::class) + ->setMethods(['setVaultPaymentToken', 'getVaultPaymentToken']) + ->disableOriginalConstructor() + ->getMock(); + $this->paymentExtensionFactory = $this->getMockBuilder(OrderPaymentExtensionInterfaceFactory::class) + ->disableOriginalConstructor() + ->setMethods(['create']) + ->getMock(); + + $this->subject = [ + 'payment' => $this->paymentDataObject, + ]; + $this->subjectReader = $this->getMockBuilder(SubjectReader::class) + ->disableOriginalConstructor() + ->setMethods(['readPayment', 'readTransaction']) + ->getMock(); + $this->subjectReader->expects(static::once()) + ->method('readPayment') + ->with($this->subject) + ->willReturn($this->paymentDataObject); + + $this->dateTimeFactory = $this->getMockBuilder(DateTimeFactory::class) + ->disableOriginalConstructor() + ->setMethods(['create']) + ->getMock(); + + $this->handler = new VaultDetailsHandler( + $this->paymentTokenFactory, + $this->paymentExtensionFactory, + $this->subjectReader, + $this->dateTimeFactory + ); + } + + /** + * @covers \Magento\Braintree\Gateway\Response\PayPal\VaultDetailsHandler::handle + */ + public function testHandle() + { + /** @var Transaction $transaction */ + $transaction = $this->getTransaction(); + $response = [ + 'object' => $transaction + ]; + + $this->paymentExtension->expects(static::once()) + ->method('setVaultPaymentToken') + ->with($this->paymentToken); + $this->paymentExtension->expects(static::once()) + ->method('getVaultPaymentToken') + ->willReturn($this->paymentToken); + + $this->subjectReader->expects(static::once()) + ->method('readTransaction') + ->with($response) + ->willReturn($transaction); + + $this->paymentDataObject->expects(static::once()) + ->method('getPayment') + ->willReturn($this->paymentInfo); + + $this->paymentTokenFactory->expects(static::once()) + ->method('create') + ->willReturn($this->paymentToken); + + $this->paymentExtensionFactory->expects(static::once()) + ->method('create') + ->willReturn($this->paymentExtension); + + $dateTime = new \DateTime('2016-07-05 00:00:00', new \DateTimeZone('UTC')); + $expirationDate = '2017-07-05 00:00:00'; + $this->dateTimeFactory->expects(static::once()) + ->method('create') + ->willReturn($dateTime); + + $this->handler->handle($this->subject, $response); + + $extensionAttributes = $this->paymentInfo->getExtensionAttributes(); + /** @var PaymentTokenInterface $paymentToken */ + $paymentToken = $extensionAttributes->getVaultPaymentToken(); + static::assertNotNull($paymentToken); + + $tokenDetails = json_decode($paymentToken->getTokenDetails(), true); + + static::assertSame($this->paymentToken, $paymentToken); + static::assertEquals($transaction->paypalDetails->token, $paymentToken->getGatewayToken()); + static::assertEquals($transaction->paypalDetails->payerEmail, $tokenDetails['payerEmail']); + static::assertEquals($expirationDate, $paymentToken->getExpiresAt()); + } + + /** + * @covers \Magento\Braintree\Gateway\Response\PayPal\VaultDetailsHandler::handle + */ + public function testHandleWithoutToken() + { + $transaction = $this->getTransaction(); + $transaction->paypalDetails->token = null; + + $response = [ + 'object' => $transaction + ]; + + $this->subjectReader->expects(static::once()) + ->method('readTransaction') + ->with($response) + ->willReturn($transaction); + + $this->paymentDataObject->expects(static::once()) + ->method('getPayment') + ->willReturn($this->paymentInfo); + + $this->paymentTokenFactory->expects(static::never()) + ->method('create'); + + $this->dateTimeFactory->expects(static::never()) + ->method('create'); + + $this->handler->handle($this->subject, $response); + static::assertNull($this->paymentInfo->getExtensionAttributes()); + } + + /** + * Create Braintree transaction + * @return Transaction + */ + private function getTransaction() + { + $attributes = [ + 'id' => self::$transactionId, + 'paypalDetails' => $this->getPayPalDetails() + ]; + + $transaction = Transaction::factory($attributes); + + return $transaction; + } + + /** + * Get PayPal transaction details + * @return PayPalDetails + */ + private function getPayPalDetails() + { + $attributes = [ + 'token' => 'rc39al', + 'payerEmail' => 'john.doe@example.com' + ]; + + $details = new PayPalDetails($attributes); + + return $details; + } +} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/RiskDataHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/RiskDataHandlerTest.php index 239524e04c0e0..2baf3356a0008 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/RiskDataHandlerTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/RiskDataHandlerTest.php @@ -5,12 +5,12 @@ */ namespace Magento\Braintree\Test\Unit\Gateway\Response; -use Braintree\RiskData; use Braintree\Transaction; -use Magento\Sales\Model\Order\Payment; use Magento\Braintree\Gateway\Helper\SubjectReader; use Magento\Braintree\Gateway\Response\RiskDataHandler; use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; +use Magento\Sales\Model\Order\Payment; +use PHPUnit_Framework_MockObject_MockObject as MockObject; /** * Class RiskDataHandlerTest @@ -25,99 +25,95 @@ class RiskDataHandlerTest extends \PHPUnit_Framework_TestCase private $riskDataHandler; /** - * @var SubjectReader|\PHPUnit_Framework_MockObject_MockObject + * @var SubjectReader|MockObject */ - private $subjectReaderMock; + private $subjectReader; /** * Set up */ protected function setUp() { - $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) + $this->subjectReader = $this->getMockBuilder(SubjectReader::class) ->disableOriginalConstructor() + ->setMethods(['readPayment', 'readTransaction']) ->getMock(); - $this->riskDataHandler = new RiskDataHandler($this->subjectReaderMock); + $this->riskDataHandler = new RiskDataHandler($this->subjectReader); } /** - * Run test for handle method + * Test for handle method + * @covers \Magento\Braintree\Gateway\Response\RiskDataHandler::handle + * @param string $riskDecision + * @param boolean $isFraud + * @dataProvider riskDataProvider */ - public function testHandle() + public function testHandle($riskDecision, $isFraud) { - $paymentData = $this->getPaymentDataObjectMock(); - $transaction = $this->getBraintreeTransactionMock(); + /** @var Payment|MockObject $payment */ + $payment = $this->getMockBuilder(Payment::class) + ->disableOriginalConstructor() + ->setMethods(['setAdditionalInformation', 'setIsFraudDetected']) + ->getMock(); + /** @var PaymentDataObjectInterface|MockObject $paymentDO */ + $paymentDO = $this->getMock(PaymentDataObjectInterface::class); + $paymentDO->expects(self::once()) + ->method('getPayment') + ->willReturn($payment); + + $transaction = Transaction::factory([ + 'riskData' => [ + 'id' => 'test-id', + 'decision' => $riskDecision + ] + ]); $response = [ 'object' => $transaction ]; $handlingSubject = [ - 'payment' =>$paymentData, + 'payment' => $paymentDO, ]; - $this->subjectReaderMock->expects(self::once()) + $this->subjectReader->expects(static::once()) ->method('readPayment') ->with($handlingSubject) - ->willReturn($paymentData); - $this->subjectReaderMock->expects(self::once()) + ->willReturn($paymentDO); + $this->subjectReader->expects(static::once()) ->method('readTransaction') ->with($response) ->willReturn($transaction); - $this->riskDataHandler->handle($handlingSubject, $response); - } - - /** - * @return \PHPUnit_Framework_MockObject_MockObject - */ - private function getBraintreeTransactionMock() - { - $transaction = \Braintree\Transaction::factory([]); - $transaction->_set( - 'riskData', - RiskData::factory( - [ - 'id' => 'test-id', - 'decision' => 'test-decision', - ] - ) - ); - - return $transaction; - } - - /** - * @return \PHPUnit_Framework_MockObject_MockObject - */ - private function getPaymentDataObjectMock() - { - $mock = $this->getMockBuilder(PaymentDataObjectInterface::class) - ->getMockForAbstractClass(); + $payment->expects(static::at(0)) + ->method('setAdditionalInformation') + ->with(RiskDataHandler::RISK_DATA_ID, 'test-id'); + $payment->expects(static::at(1)) + ->method('setAdditionalInformation') + ->with(RiskDataHandler::RISK_DATA_DECISION, $riskDecision); - $mock->expects(static::once()) - ->method('getPayment') - ->willReturn($this->getPaymentMock()); + if (!$isFraud) { + $payment->expects(static::never()) + ->method('setIsFraudDetected'); + } else { + $payment->expects(static::once()) + ->method('setIsFraudDetected') + ->with(true); + } - return $mock; + $this->riskDataHandler->handle($handlingSubject, $response); } /** - * @return \PHPUnit_Framework_MockObject_MockObject + * Get list of variations to test fraud + * @return array */ - private function getPaymentMock() + public function riskDataProvider() { - $paymentMock = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->getMock(); - - $paymentMock->expects(self::at(0)) - ->method('setAdditionalInformation') - ->with(RiskDataHandler::RISK_DATA_ID, 'test-id'); - $paymentMock->expects(self::at(1)) - ->method('setAdditionalInformation') - ->with(RiskDataHandler::RISK_DATA_DECISION, 'test-decision'); - - return $paymentMock; + return [ + ['decision' => 'Not Evaluated', 'isFraud' => false], + ['decision' => 'Approve', 'isFraud' => false], + ['decision' => 'Review', 'isFraud' => true], + ]; } } diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/VaultDetailsHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/VaultDetailsHandlerTest.php index 57b625a4488ce..4f641bbb56765 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/VaultDetailsHandlerTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/VaultDetailsHandlerTest.php @@ -7,18 +7,18 @@ use Braintree\Transaction; use Braintree\Transaction\CreditCardDetails; +use Magento\Braintree\Gateway\Config\Config; +use Magento\Braintree\Gateway\Helper\SubjectReader; use Magento\Braintree\Gateway\Response\VaultDetailsHandler; use Magento\Framework\DataObject; use Magento\Payment\Gateway\Data\PaymentDataObject; -use Magento\Sales\Api\Data\OrderPaymentExtensionInterfaceFactory; use Magento\Sales\Api\Data\OrderPaymentExtensionInterface; +use Magento\Sales\Api\Data\OrderPaymentExtensionInterfaceFactory; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Payment; use Magento\Vault\Api\Data\PaymentTokenInterface; -use Magento\Vault\Api\Data\PaymentTokenInterfaceFactory; -use Magento\Braintree\Gateway\Helper\SubjectReader; +use Magento\Vault\Model\CreditCardTokenFactory; use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Braintree\Gateway\Config\Config; /** * VaultDetailsHandler Test @@ -40,7 +40,7 @@ class VaultDetailsHandlerTest extends \PHPUnit_Framework_TestCase private $payment; /** - * @var \Magento\Vault\Api\Data\PaymentTokenInterfaceFactory|MockObject + * @var CreditCardTokenFactory|MockObject */ private $paymentTokenFactory; @@ -72,7 +72,7 @@ class VaultDetailsHandlerTest extends \PHPUnit_Framework_TestCase protected function setUp() { $this->paymentToken = $this->getMock(PaymentTokenInterface::class); - $this->paymentTokenFactory = $this->getMockBuilder(PaymentTokenInterfaceFactory::class) + $this->paymentTokenFactory = $this->getMockBuilder(CreditCardTokenFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/GeneralResponseValidatorTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/GeneralResponseValidatorTest.php index 469cfea9c5fbb..8f57cd0e6f575 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/GeneralResponseValidatorTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/GeneralResponseValidatorTest.php @@ -37,7 +37,7 @@ class GeneralResponseValidatorTest extends \PHPUnit_Framework_TestCase protected function setUp() { $this->resultInterfaceFactoryMock = $this->getMockBuilder( - 'Magento\Payment\Gateway\Validator\ResultInterfaceFactory' + \Magento\Payment\Gateway\Validator\ResultInterfaceFactory::class )->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/ResponseValidatorTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/ResponseValidatorTest.php index 68fddf24bfd7d..c486783be6bca 100644 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/ResponseValidatorTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/ResponseValidatorTest.php @@ -11,6 +11,9 @@ use Magento\Payment\Gateway\Validator\ResultInterfaceFactory; use Magento\Braintree\Gateway\Validator\ResponseValidator; use Magento\Braintree\Gateway\Helper\SubjectReader; +use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Braintree\Result\Error; +use Braintree\Result\Successful; /** * Class ResponseValidatorTest @@ -23,14 +26,14 @@ class ResponseValidatorTest extends \PHPUnit_Framework_TestCase private $responseValidator; /** - * @var ResultInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var ResultInterfaceFactory|MockObject */ - private $resultInterfaceFactoryMock; + private $resultInterfaceFactory; /** - * @var SubjectReader|\PHPUnit_Framework_MockObject_MockObject + * @var SubjectReader|MockObject */ - private $subjectReaderMock; + private $subjectReader; /** * Set up @@ -39,18 +42,17 @@ class ResponseValidatorTest extends \PHPUnit_Framework_TestCase */ protected function setUp() { - $this->resultInterfaceFactoryMock = $this->getMockBuilder( - 'Magento\Payment\Gateway\Validator\ResultInterfaceFactory' - )->disableOriginalConstructor() + $this->resultInterfaceFactory = $this->getMockBuilder(ResultInterfaceFactory::class) + ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) + $this->subjectReader = $this->getMockBuilder(SubjectReader::class) ->disableOriginalConstructor() ->getMock(); $this->responseValidator = new ResponseValidator( - $this->resultInterfaceFactoryMock, - $this->subjectReaderMock + $this->resultInterfaceFactory, + $this->subjectReader ); } @@ -63,7 +65,7 @@ public function testValidateReadResponseException() 'response' => null ]; - $this->subjectReaderMock->expects(self::once()) + $this->subjectReader->expects(self::once()) ->method('readResponseObject') ->with($validationSubject) ->willThrowException(new \InvalidArgumentException()); @@ -80,7 +82,7 @@ public function testValidateReadResponseObjectException() 'response' => ['object' => null] ]; - $this->subjectReaderMock->expects(self::once()) + $this->subjectReader->expects(self::once()) ->method('readResponseObject') ->with($validationSubject) ->willThrowException(new \InvalidArgumentException()); @@ -100,25 +102,25 @@ public function testValidateReadResponseObjectException() */ public function testValidate(array $validationSubject, $isValid, $messages) { - /** @var ResultInterface|\PHPUnit_Framework_MockObject_MockObject $resultMock */ - $resultMock = $this->getMock(ResultInterface::class); + /** @var ResultInterface|MockObject $result */ + $result = $this->getMock(ResultInterface::class); - $this->subjectReaderMock->expects(self::once()) + $this->subjectReader->expects(self::once()) ->method('readResponseObject') ->with($validationSubject) ->willReturn($validationSubject['response']['object']); - $this->resultInterfaceFactoryMock->expects(self::once()) + $this->resultInterfaceFactory->expects(self::once()) ->method('create') ->with([ 'isValid' => $isValid, 'failsDescription' => $messages ]) - ->willReturn($resultMock); + ->willReturn($result); - $actualMock = $this->responseValidator->validate($validationSubject); + $actual = $this->responseValidator->validate($validationSubject); - self::assertEquals($resultMock, $actualMock); + self::assertEquals($result, $actual); } /** @@ -126,19 +128,21 @@ public function testValidate(array $validationSubject, $isValid, $messages) */ public function dataProviderTestValidate() { - $successTrue = new \stdClass(); + $successTrue = new Successful(); $successTrue->success = true; $successTrue->transaction = new \stdClass(); $successTrue->transaction->status = Transaction::AUTHORIZED; - $successFalse = new \stdClass(); + $successFalse = new Successful(); $successFalse->success = false; - $transactionDeclined = new \stdClass(); + $transactionDeclined = new Successful(); $transactionDeclined->success = true; $transactionDeclined->transaction = new \stdClass(); $transactionDeclined->transaction->status = Transaction::SETTLEMENT_DECLINED; + $errorResult = new Error(['errors' => []]); + return [ [ 'validationSubject' => [ @@ -171,6 +175,18 @@ public function dataProviderTestValidate() [ __('Wrong transaction status') ] + ], + [ + 'validationSubject' => [ + 'response' => [ + 'object' => $errorResult, + ] + ], + 'isValid' => false, + [ + __('Braintree error response.'), + __('Wrong transaction status') + ] ] ]; } diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/QuoteUpdaterTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/QuoteUpdaterTest.php index 32767d469f199..c2413517fe06f 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/QuoteUpdaterTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/QuoteUpdaterTest.php @@ -9,7 +9,7 @@ use Magento\Quote\Model\Quote\Address; use Magento\Quote\Model\Quote\Payment; use Magento\Quote\Api\CartRepositoryInterface; -use Magento\Braintree\Model\Ui\ConfigProvider; +use Magento\Braintree\Model\Ui\PayPal\ConfigProvider; use Magento\Braintree\Observer\DataAssignObserver; use Magento\Braintree\Gateway\Config\PayPal\Config; use Magento\Braintree\Model\Paypal\Helper\QuoteUpdater; diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionMapTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionMapTest.php index c44a67b2c61d9..34c607c88784d 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionMapTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionMapTest.php @@ -11,6 +11,8 @@ use Magento\Braintree\Model\Report\Row\TransactionMap; use Magento\Framework\Api\AttributeValue; use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Phrase; +use Magento\Framework\Phrase\RendererInterface; use Magento\Store\Model\StoreManagerInterface; /** @@ -30,6 +32,16 @@ class TransactionMapTest extends \PHPUnit_Framework_TestCase */ private $attributeValueFactoryMock; + /** + * @var RendererInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $defaultRenderer; + + /** + * @var RendererInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $rendererMock; + /** * Setup */ @@ -39,6 +51,9 @@ protected function setUp() ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); + $this->defaultRenderer = Phrase::getRenderer(); + $this->rendererMock = $this->getMockBuilder(RendererInterface::class) + ->getMock(); } /** @@ -65,6 +80,8 @@ public function testGetCustomAttributes($transaction) $this->transactionStub ); + Phrase::setRenderer($this->rendererMock); + /** @var AttributeValue[] $result */ $result = $map->getCustomAttributes(); @@ -77,6 +94,31 @@ public function testGetCustomAttributes($transaction) $result[6]->getValue() ); $this->assertEquals(implode(', ', $transaction['refundIds']), $result[11]->getValue()); + $this->assertEquals($transaction['merchantAccountId'], $result[1]->getValue()); + $this->assertEquals($transaction['orderId'], $result[2]->getValue()); + $this->assertEquals($transaction['amount'], $result[7]->getValue()); + $this->assertEquals($transaction['processorSettlementResponseCode'], $result[8]->getValue()); + $this->assertEquals($transaction['processorSettlementResponseText'], $result[10]->getValue()); + $this->assertEquals($transaction['settlementBatchId'], $result[12]->getValue()); + $this->assertEquals($transaction['currencyIsoCode'], $result[13]->getValue()); + + $this->rendererMock->expects($this->at(0)) + ->method('render') + ->with([$transaction['paymentInstrumentType']]) + ->willReturn('Credit card'); + $this->assertEquals('Credit card', $result[3]->getValue()->render()); + + $this->rendererMock->expects($this->at(0)) + ->method('render') + ->with([$transaction['type']]) + ->willReturn('Sale'); + $this->assertEquals('Sale', $result[5]->getValue()->render()); + + $this->rendererMock->expects($this->at(0)) + ->method('render') + ->with([$transaction['status']]) + ->willReturn('Pending for settlement'); + $this->assertEquals('Pending for settlement', $result[9]->getValue()->render()); } /** @@ -90,9 +132,27 @@ public function getConfigDataProvider() 'id' => 1, 'createdAt' => new \DateTime(), 'paypalDetails' => new PayPalDetails(['paymentId' => 10]), - 'refundIds' => [1, 2, 3, 4, 5] + 'refundIds' => [1, 2, 3, 4, 5], + 'merchantAccountId' => 'MerchantId', + 'orderId' => 1, + 'paymentInstrumentType' => 'credit_card', + 'type' => 'sale', + 'amount' => '$19.99', + 'processorSettlementResponseCode' => 1, + 'status' => 'pending_for_settlement', + 'processorSettlementResponseText' => 'sample text', + 'settlementBatchId' => 2, + 'currencyIsoCode' => 'USD' ] ] ]; } + + /** + * @return void + */ + protected function tearDown() + { + Phrase::setRenderer($this->defaultRenderer); + } } diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionsCollectionTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionsCollectionTest.php index 50488df2600c6..6024141280a02 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionsCollectionTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionsCollectionTest.php @@ -184,4 +184,42 @@ public function testGetItemsWithNullLimit() $this->assertEquals(TransactionsCollection::TRANSACTION_MAXIMUM_COUNT, count($items)); $this->assertInstanceOf(DocumentInterface::class, $items[1]); } + + /** + * Add fields to filter + * + * @dataProvider addToFilterDataProvider + */ + public function testAddToFilter($field, $condition, $filterMapperCall, $expectedCondition) + { + $this->filterMapperMock->expects(static::exactly($filterMapperCall)) + ->method('getFilter') + ->with($field, $expectedCondition) + ->willReturn(new BraintreeSearchNodeStub()); + + $collection = new TransactionsCollection( + $this->entityFactoryMock, + $this->braintreeAdapterMock, + $this->filterMapperMock + ); + + static::assertInstanceOf( + TransactionsCollection::class, + $collection->addFieldToFilter($field, $condition) + ); + } + + /** + * addToFilter DataProvider + * + * @return array + */ + public function addToFilterDataProvider() + { + return [ + ['orderId', ['like' => 1], 1, ['like' => 1]], + ['type', 'sale', 1, ['eq' => 'sale']], + [['type', 'orderId'], [], 0, []], + ]; + } } diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php new file mode 100644 index 0000000000000..bdc39cbc5b868 --- /dev/null +++ b/app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php @@ -0,0 +1,114 @@ +componentFactory = $this->getMockBuilder(TokenUiComponentInterfaceFactory::class) + ->disableOriginalConstructor() + ->setMethods(['create']) + ->getMock(); + + $this->urlBuilder = $this->getMock(UrlInterface::class); + + $this->config = $this->getMockBuilder(Config::class) + ->disableOriginalConstructor() + ->setMethods(['getPayPalIcon']) + ->getMock(); + + $this->tokenUiComponentProvider = new TokenUiComponentProvider( + $this->componentFactory, + $this->urlBuilder, + $this->config + ); + } + + /** + * @covers \Magento\Braintree\Model\Ui\Adminhtml\PayPal\TokenUiComponentProvider::getComponentForToken + */ + public function testGetComponentForToken() + { + $nonceUrl = 'https://payment/adminhtml/nonce/url'; + $payerEmail = 'john.doe@test.com'; + $icon = [ + 'url' => 'https://payment/adminhtml/icon.png', + 'width' => 48, + 'height' => 32 + ]; + + $expected = [ + 'code' => 'vault', + 'nonceUrl' => $nonceUrl, + 'details' => [ + 'payerEmail' => $payerEmail, + 'icon' => $icon + ], + 'template' => 'vault.phtml' + ]; + + $this->config->expects(static::once()) + ->method('getPayPalIcon') + ->willReturn($icon); + + $paymentToken = $this->getMock(PaymentTokenInterface::class); + $paymentToken->expects(static::once()) + ->method('getTokenDetails') + ->willReturn('{"payerEmail":" ' . $payerEmail . '"}'); + $paymentToken->expects(static::once()) + ->method('getPublicHash') + ->willReturn('cmk32dl21l'); + + $this->urlBuilder->expects(static::once()) + ->method('getUrl') + ->willReturn($nonceUrl); + + $tokenComponent = $this->getMock(TokenUiComponentInterface::class); + $tokenComponent->expects(static::once()) + ->method('getConfig') + ->willReturn($expected); + + $this->componentFactory->expects(static::once()) + ->method('create') + ->willReturn($tokenComponent); + + $component = $this->tokenUiComponentProvider->getComponentForToken($paymentToken); + static::assertEquals($tokenComponent, $component); + static::assertEquals($expected, $component->getConfig()); + } +} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/TokenUiComponentProviderTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/TokenUiComponentProviderTest.php index d1665c71804cf..f159136cf4c46 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/TokenUiComponentProviderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/TokenUiComponentProviderTest.php @@ -7,10 +7,10 @@ use Magento\Braintree\Model\Ui\Adminhtml\TokenUiComponentProvider; use Magento\Framework\UrlInterface; -use Magento\Framework\View\Element\Template; use Magento\Vault\Api\Data\PaymentTokenInterface; use Magento\Vault\Model\Ui\TokenUiComponentInterface; use Magento\Vault\Model\Ui\TokenUiComponentInterfaceFactory; +use PHPUnit_Framework_MockObject_MockObject as MockObject; /** * Class TokenUiComponentProviderTest @@ -19,12 +19,12 @@ class TokenUiComponentProviderTest extends \PHPUnit_Framework_TestCase { /** - * @var TokenUiComponentInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var TokenUiComponentInterfaceFactory|MockObject */ private $componentFactory; /** - * @var UrlInterface|\PHPUnit_Framework_MockObject_MockObject + * @var UrlInterface|MockObject */ private $urlBuilder; @@ -59,6 +59,7 @@ public function testGetComponentForToken() $expirationDate = '12/2015'; $expected = [ + 'code' => 'vault', 'nonceUrl' => $nonceUrl, 'details' => [ 'type' => $type, diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Ui/ConfigProviderTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Ui/ConfigProviderTest.php index 0195c8bd7a883..04846f369eba9 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/Ui/ConfigProviderTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/Ui/ConfigProviderTest.php @@ -8,8 +8,7 @@ use Magento\Braintree\Gateway\Config\Config; use Magento\Braintree\Model\Adapter\BraintreeAdapter; use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Braintree\Gateway\Config\PayPal\Config as PayPalConfig; -use Magento\Framework\Locale\ResolverInterface; +use PHPUnit_Framework_MockObject_MockObject as MockObject; /** * Class ConfigProviderTest @@ -23,25 +22,15 @@ class ConfigProviderTest extends \PHPUnit_Framework_TestCase const MERCHANT_ACCOUNT_ID = '245345'; /** - * @var Config|\PHPUnit_Framework_MockObject_MockObject + * @var Config|MockObject */ private $config; /** - * @var PayPalConfig|\PHPUnit_Framework_MockObject_MockObject - */ - private $payPalConfig; - - /** - * @var BraintreeAdapter|\PHPUnit_Framework_MockObject_MockObject + * @var BraintreeAdapter|MockObject */ private $braintreeAdapter; - /** - * @var ResolverInterface|\PHPUnit_Framework_MockObject_MockObject - */ - private $localeResolver; - /** * @var ConfigProvider */ @@ -53,21 +42,13 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->payPalConfig = $this->getMockBuilder(PayPalConfig::class) - ->disableOriginalConstructor() - ->getMock(); - $this->braintreeAdapter = $this->getMockBuilder(BraintreeAdapter::class) ->disableOriginalConstructor() ->getMock(); - $this->localeResolver = $this->getMockForAbstractClass(ResolverInterface::class); - $this->configProvider = new ConfigProvider( $this->config, - $this->payPalConfig, - $this->braintreeAdapter, - $this->localeResolver + $this->braintreeAdapter ); } @@ -90,26 +71,6 @@ public function testGetConfig($config, $expected) ->willReturn($value); } - $this->payPalConfig->expects(static::once()) - ->method('isActive') - ->willReturn(true); - - $this->payPalConfig->expects(static::once()) - ->method('isAllowToEditShippingAddress') - ->willReturn(true); - - $this->payPalConfig->expects(static::once()) - ->method('getMerchantName') - ->willReturn('Test'); - - $this->payPalConfig->expects(static::once()) - ->method('getTitle') - ->willReturn('Payment Title'); - - $this->localeResolver->expects(static::once()) - ->method('getLocale') - ->willReturn('en_US'); - static::assertEquals($expected, $this->configProvider->getConfig()); } @@ -179,15 +140,6 @@ public function getConfigDataProvider() 'enabled' => true, 'thresholdAmount' => 20, 'specificCountries' => ['GB', 'US', 'CA'] - ], - ConfigProvider::PAYPAL_CODE => [ - 'isActive' => true, - 'title' => 'Payment Title', - 'isAllowShippingAddressOverride' => true, - 'merchantName' => 'Test', - 'locale' => 'en_us', - 'paymentAcceptanceMarkSrc' => - 'https://www.paypalobjects.com/webstatic/en_US/i/buttons/pp-acceptance-medium.png' ] ] ] diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/ConfigProviderTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/ConfigProviderTest.php new file mode 100644 index 0000000000000..8859425eb0def --- /dev/null +++ b/app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/ConfigProviderTest.php @@ -0,0 +1,118 @@ +config = $this->getMockBuilder(Config::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->localeResolver = $this->getMockForAbstractClass(ResolverInterface::class); + + $this->configProvider = new ConfigProvider( + $this->config, + $this->localeResolver + ); + } + + /** + * Run test getConfig method + * + * @param array $config + * @dataProvider getConfigDataProvider + */ + public function testGetConfig($expected) + { + $this->config->expects(static::once()) + ->method('isActive') + ->willReturn(true); + + $this->config->expects(static::once()) + ->method('isAllowToEditShippingAddress') + ->willReturn(true); + + $this->config->expects(static::once()) + ->method('getMerchantName') + ->willReturn('Test'); + + $this->config->expects(static::once()) + ->method('getTitle') + ->willReturn('Payment Title'); + + $this->localeResolver->expects(static::once()) + ->method('getLocale') + ->willReturn('en_US'); + + $this->config->expects(static::once()) + ->method('isSkipOrderReview') + ->willReturn(false); + + $this->config->expects(static::once()) + ->method('getPayPalIcon') + ->willReturn([ + 'width' => 30, 'height' => 26, 'url' => 'https://icon.test.url' + ]); + + static::assertEquals($expected, $this->configProvider->getConfig()); + } + + /** + * @return array + */ + public function getConfigDataProvider() + { + return [ + [ + 'expected' => [ + 'payment' => [ + ConfigProvider::PAYPAL_CODE => [ + 'isActive' => true, + 'title' => 'Payment Title', + 'isAllowShippingAddressOverride' => true, + 'merchantName' => 'Test', + 'locale' => 'en_us', + 'paymentAcceptanceMarkSrc' => + 'https://www.paypalobjects.com/webstatic/en_US/i/buttons/pp-acceptance-medium.png', + 'vaultCode' => ConfigProvider::PAYPAL_VAULT_CODE, + 'skipOrderReview' => false, + 'paymentIcon' => [ + 'width' => 30, 'height' => 26, 'url' => 'https://icon.test.url' + ] + ] + ] + ] + ] + ]; + } +} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/TokenUiComponentProviderTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/TokenUiComponentProviderTest.php new file mode 100644 index 0000000000000..d0368a22ef960 --- /dev/null +++ b/app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/TokenUiComponentProviderTest.php @@ -0,0 +1,92 @@ +componentFactory = $this->getMockBuilder(TokenUiComponentInterfaceFactory::class) + ->disableOriginalConstructor() + ->setMethods(['create']) + ->getMock(); + + $this->tokenComponent = $this->getMockForAbstractClass(TokenUiComponentInterface::class); + + $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); + + $this->paymentToken = $this->getMockForAbstractClass(PaymentTokenInterface::class); + + $this->componentProvider = new TokenUiComponentProvider( + $this->componentFactory, + $this->urlBuilder + ); + } + + /** + * @covers \Magento\Braintree\Model\Ui\PayPal\TokenUiComponentProvider::getComponentForToken + */ + public function testGetComponentForToken() + { + $tokenDetails = [ + 'payerEmail' => 'john.doe@example.com' + ]; + $hash = '4g1mn4ew0vj23n2jf'; + + $this->paymentToken->expects(static::once()) + ->method('getTokenDetails') + ->willReturn(json_encode($tokenDetails)); + + $this->componentFactory->expects(static::once()) + ->method('create') + ->willReturn($this->tokenComponent); + + $this->paymentToken->expects(static::once()) + ->method('getPublicHash') + ->willReturn($hash); + + $this->urlBuilder->expects(static::once()) + ->method('getUrl'); + + $actual = $this->componentProvider->getComponentForToken($this->paymentToken); + static::assertEquals($this->tokenComponent, $actual); + } +} diff --git a/app/code/Magento/Braintree/Test/Unit/Ui/Component/Report/Filters/Type/DateRangeTest.php b/app/code/Magento/Braintree/Test/Unit/Ui/Component/Report/Filters/Type/DateRangeTest.php new file mode 100644 index 0000000000000..b81dbe2fb036f --- /dev/null +++ b/app/code/Magento/Braintree/Test/Unit/Ui/Component/Report/Filters/Type/DateRangeTest.php @@ -0,0 +1,251 @@ +contextMock = $this->getMockForAbstractClass(ContextInterface::class); + $processor = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\Processor::class) + ->disableOriginalConstructor() + ->getMock(); + $this->contextMock->expects(static::any()) + ->method('getProcessor') + ->willReturn($processor); + $this->uiComponentFactory = $this->getMockBuilder(UiComponentFactory::class) + ->setMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->filterBuilderMock = $this->getMockBuilder(FilterBuilder::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->filterModifierMock = $this->getMockBuilder(FilterModifier::class) + ->setMethods(['applyFilterModifier']) + ->disableOriginalConstructor() + ->getMock(); + + $this->dataProviderMock = $this->getMockForAbstractClass(DataProviderInterface::class); + } + + /** + * Run test prepare method + * + * @param string $name + * @param array $filterData + * @param array|null $expectedCondition + * @dataProvider getPrepareDataProvider + * @return void + */ + public function testPrepare($name, $filterData, $expectedCondition) + { + /** @var FormDate PHPUnit_Framework_MockObject_MockObject|$uiComponent */ + $uiComponent = $this->getMockBuilder(FormDate::class) + ->disableOriginalConstructor() + ->getMock(); + + $uiComponent->expects($this->any()) + ->method('getContext') + ->willReturn($this->contextMock); + + $this->contextMock->expects($this->any()) + ->method('getNamespace') + ->willReturn(DateRange::NAME); + $this->contextMock->expects($this->any()) + ->method('addComponentDefinition') + ->with(DateRange::NAME, ['extends' => DateRange::NAME]); + + $this->contextMock->expects($this->any()) + ->method('getFiltersParams') + ->willReturn($filterData); + + $this->contextMock->expects($this->any()) + ->method('getDataProvider') + ->willReturn($this->dataProviderMock); + + if ($expectedCondition !== null) { + if (is_string($filterData[$name])) { + $uiComponent->expects(static::once()) + ->method('convertDate') + ->with($filterData[$name]) + ->willReturn(new \DateTime($filterData[$name], new \DateTimeZone('UTC'))); + } else { + $uiComponent->method('convertDate') + ->willReturnMap([ + [ + $filterData[$name]['from'], 0, 0, 0, + new \DateTime($filterData[$name]['from'], new \DateTimeZone('UTC')) + ], + [ + $filterData[$name]['to'], 23, 59, 59, + new \DateTime($filterData[$name]['to'] . ' 23:59:00', new \DateTimeZone('UTC')) + ], + ]); + } + + $i=0; + switch (true) { + case is_string($filterData[$name]): + case isset($filterData[$name]['from']) && !isset($filterData[$name]['to']): + case !isset($filterData[$name]['from']) && isset($filterData[$name]['to']): + $filterMock = $this->getFilterMock( + $name, + $expectedCondition['type'], + $expectedCondition['date'], + $i + ); + $this->dataProviderMock->expects(static::once()) + ->method('addFilter') + ->with($filterMock); + break; + case isset($filterData[$name]['from']) && isset($filterData[$name]['to']): + $this->getFilterMock( + $name, + $expectedCondition['type_from'], + $expectedCondition['date_from'], + $i + ); + $filterMock = $this->getFilterMock( + $name, + $expectedCondition['type_to'], + $expectedCondition['date_to'], + $i + ); + $this->dataProviderMock->expects(static::exactly(2)) + ->method('addFilter') + ->with($filterMock); + break; + } + } + + $this->uiComponentFactory->expects($this->any()) + ->method('create') + ->with($name, DateRange::COMPONENT, ['context' => $this->contextMock]) + ->willReturn($uiComponent); + + $date = new DateRange( + $this->contextMock, + $this->uiComponentFactory, + $this->filterBuilderMock, + $this->filterModifierMock, + [], + ['name' => $name] + ); + $date->prepare(); + } + + /** + * Gets Filter mock + * + * @param string $name + * @param string $expectedType + * @param string $expectedDate + * @param int $i + * + * @return Filter|\PHPUnit_Framework_MockObject_MockObject + */ + private function getFilterMock($name, $expectedType, $expectedDate, &$i) + { + $this->filterBuilderMock->expects(static::at($i++)) + ->method('setConditionType') + ->with($expectedType) + ->willReturnSelf(); + $this->filterBuilderMock->expects(static::at($i++)) + ->method('setField') + ->with($name) + ->willReturnSelf(); + $this->filterBuilderMock->expects(static::at($i++)) + ->method('setValue') + ->with($expectedDate) + ->willReturnSelf(); + + $filterMock = $this->getMock(Filter::class); + $this->filterBuilderMock->expects(static::at($i++)) + ->method('create') + ->willReturn($filterMock); + + return $filterMock; + } + + /** + * @return array + */ + public function getPrepareDataProvider() + { + return [ + [ + 'test_date', + ['test_date' => ['from' => '11-05-2015', 'to' => null]], + ['date' => '2015-05-11T00:00:00+0000', 'type' => 'gteq'], + ], + [ + 'test_date', + ['test_date' => ['from' => null, 'to' => '11-05-2015']], + ['date' => '2015-05-11T23:59:00+0000', 'type' => 'lteq'], + ], + [ + 'test_date', + ['test_date' => ['from' => '11-05-2015', 'to' => '11-05-2015']], + [ + 'date_from' => '2015-05-11T00:00:00+0000', 'type_from' => 'gteq', + 'date_to' => '2015-05-11T23:59:00+0000', 'type_to' => 'lteq' + ], + ], + [ + 'test_date', + ['test_date' => '11-05-2015'], + ['date' => '2015-05-11T00:00:00+0000', 'type' => 'eq'], + ], + [ + 'test_date', + ['test_date' => ['from' => '', 'to' => '']], + null, + ] + ]; + } +} diff --git a/app/code/Magento/Braintree/Ui/Component/Report/Filters/Type/DateRange.php b/app/code/Magento/Braintree/Ui/Component/Report/Filters/Type/DateRange.php new file mode 100644 index 0000000000000..adbb3b78cb663 --- /dev/null +++ b/app/code/Magento/Braintree/Ui/Component/Report/Filters/Type/DateRange.php @@ -0,0 +1,19 @@ + __('Paypal account'), - PaymentInstrumentType::COINBASE_ACCOUNT => __('Coinbase account'), - PaymentInstrumentType::EUROPE_BANK_ACCOUNT => __('Europe bank account'), - PaymentInstrumentType::CREDIT_CARD => __('Credit card'), - PaymentInstrumentType::APPLE_PAY_CARD => __('Apple pay card'), - PaymentInstrumentType::ANDROID_PAY_CARD => __('Android pay card') + PaymentInstrumentType::PAYPAL_ACCOUNT => __(PaymentInstrumentType::PAYPAL_ACCOUNT), + PaymentInstrumentType::COINBASE_ACCOUNT => __(PaymentInstrumentType::COINBASE_ACCOUNT), + PaymentInstrumentType::EUROPE_BANK_ACCOUNT => __(PaymentInstrumentType::EUROPE_BANK_ACCOUNT), + PaymentInstrumentType::CREDIT_CARD => __(PaymentInstrumentType::CREDIT_CARD), + PaymentInstrumentType::APPLE_PAY_CARD => __(PaymentInstrumentType::APPLE_PAY_CARD), + PaymentInstrumentType::ANDROID_PAY_CARD => __(PaymentInstrumentType::ANDROID_PAY_CARD) ]; } } diff --git a/app/code/Magento/Braintree/Ui/Component/Report/Listing/Column/Status.php b/app/code/Magento/Braintree/Ui/Component/Report/Listing/Column/Status.php index f5424c6dd9b7f..ca6d6522990b4 100644 --- a/app/code/Magento/Braintree/Ui/Component/Report/Listing/Column/Status.php +++ b/app/code/Magento/Braintree/Ui/Component/Report/Listing/Column/Status.php @@ -44,20 +44,20 @@ public function toOptionArray() private function getAvailableStatuses() { return [ - Transaction::AUTHORIZATION_EXPIRED => __('Authorization expired'), - Transaction::AUTHORIZING => __('Authorizing'), - Transaction::AUTHORIZED => __('Authorized'), - Transaction::GATEWAY_REJECTED => __('Gateway rejected'), - Transaction::FAILED => __('Failed'), - Transaction::PROCESSOR_DECLINED => __('Processor declined'), - Transaction::SETTLED => __('Settled'), - Transaction::SETTLING => __('Settling'), - Transaction::SUBMITTED_FOR_SETTLEMENT => __('Submitted for settlement'), - Transaction::VOIDED => __('Voided'), - Transaction::UNRECOGNIZED => __('Unrecognized'), - Transaction::SETTLEMENT_DECLINED => __('Settlement declined'), - Transaction::SETTLEMENT_PENDING => __('Settlement pending'), - Transaction::SETTLEMENT_CONFIRMED => __('Settlement confirmed') + Transaction::AUTHORIZATION_EXPIRED => __(Transaction::AUTHORIZATION_EXPIRED), + Transaction::AUTHORIZING => __(Transaction::AUTHORIZING), + Transaction::AUTHORIZED => __(Transaction::AUTHORIZED), + Transaction::GATEWAY_REJECTED => __(Transaction::GATEWAY_REJECTED), + Transaction::FAILED => __(Transaction::FAILED), + Transaction::PROCESSOR_DECLINED => __(Transaction::PROCESSOR_DECLINED), + Transaction::SETTLED => __(Transaction::SETTLED), + Transaction::SETTLING => __(Transaction::SETTLING), + Transaction::SUBMITTED_FOR_SETTLEMENT => __(Transaction::SUBMITTED_FOR_SETTLEMENT), + Transaction::VOIDED => __(Transaction::VOIDED), + Transaction::UNRECOGNIZED => __(Transaction::UNRECOGNIZED), + Transaction::SETTLEMENT_DECLINED => __(Transaction::SETTLEMENT_DECLINED), + Transaction::SETTLEMENT_PENDING => __(Transaction::SETTLEMENT_PENDING), + Transaction::SETTLEMENT_CONFIRMED => __(Transaction::SETTLEMENT_CONFIRMED) ]; } } diff --git a/app/code/Magento/Braintree/Ui/Component/Report/Listing/Column/TransactionType.php b/app/code/Magento/Braintree/Ui/Component/Report/Listing/Column/TransactionType.php index 312b2f518b464..0fe752d423277 100644 --- a/app/code/Magento/Braintree/Ui/Component/Report/Listing/Column/TransactionType.php +++ b/app/code/Magento/Braintree/Ui/Component/Report/Listing/Column/TransactionType.php @@ -44,8 +44,8 @@ public function toOptionArray() private function getAvailableTransactionTypes() { return [ - Transaction::SALE => __('Sale'), - Transaction::CREDIT => __('Credit') + Transaction::SALE => __(Transaction::SALE), + Transaction::CREDIT => __(Transaction::CREDIT) ]; } } diff --git a/app/code/Magento/Braintree/etc/adminhtml/di.xml b/app/code/Magento/Braintree/etc/adminhtml/di.xml index ed52db8cf7234..d154aabbb01b5 100644 --- a/app/code/Magento/Braintree/etc/adminhtml/di.xml +++ b/app/code/Magento/Braintree/etc/adminhtml/di.xml @@ -27,6 +27,7 @@ Magento\Braintree\Gateway\Request\ChannelDataBuilder Magento\Braintree\Gateway\Request\AddressDataBuilder Magento\Braintree\Gateway\Request\VaultDataBuilder + Magento\Braintree\Gateway\Request\DescriptorDataBuilder @@ -37,6 +38,7 @@ Magento\Braintree\Gateway\Request\PaymentDataBuilder Magento\Braintree\Gateway\Request\ChannelDataBuilder Magento\Braintree\Gateway\Request\AddressDataBuilder + Magento\Braintree\Gateway\Request\DescriptorDataBuilder @@ -45,6 +47,7 @@ Magento\Braintree\Model\Ui\Adminhtml\TokenUiComponentProvider + Magento\Braintree\Model\Ui\Adminhtml\PayPal\TokenUiComponentProvider diff --git a/app/code/Magento/Braintree/etc/adminhtml/system.xml b/app/code/Magento/Braintree/etc/adminhtml/system.xml index 3668cd7779fda..f36f6b819e273 100644 --- a/app/code/Magento/Braintree/etc/adminhtml/system.xml +++ b/app/code/Magento/Braintree/etc/adminhtml/system.xml @@ -35,7 +35,7 @@ - + Magento\Config\Model\Config\Source\Yesno payment/braintree_cc_vault/active @@ -153,6 +153,14 @@ payment/braintree_paypal/title It is recommended to set this value to "PayPal" per store views. + + + Magento\Config\Model\Config\Source\Yesno + payment/braintree_paypal_vault/active + + + + validate-number @@ -200,6 +208,11 @@ payment/braintree_paypal/display_on_shopping_cart Also affects mini-shopping cart. + + + Magento\Config\Model\Config\Source\Yesno + payment/braintree_paypal/skip_order_review + @@ -225,6 +238,36 @@ payment/braintree/verify_specific_countries + + + Braintree Support.]]> + Magento\Config\Block\System\Config\Form\Fieldset + + + payment/braintree/descriptor_name + + The value in the business name field of a customer's statement. Company name/DBA section must be either 3, 7 or 12 characters + and the product descriptor can be up to 18, 14, or 9 characters respectively (with an * in between for a total descriptor name of 22 characters). + + + + + payment/braintree/descriptor_phone + + The value in the phone number field of a customer's statement. Phone must be 10-14 characters and can only contain numbers, dashes, parentheses and periods. + + + + + payment/braintree/descriptor_url + + The value in the URL/web address field of a customer's statement. The URL must be 13 characters or shorter. + + + diff --git a/app/code/Magento/Braintree/etc/config.xml b/app/code/Magento/Braintree/etc/config.xml index 7511ec2ca1563..bf19324ae7a02 100644 --- a/app/code/Magento/Braintree/etc/config.xml +++ b/app/code/Magento/Braintree/etc/config.xml @@ -25,13 +25,16 @@ 1 1 1 + 1 + 1 + 1 AE,VI,MC,DI,JCB,CUP,DN,MI 1 processing sandbox 0 - + cvv,number @@ -57,6 +60,8 @@ 1 1 1 + 1 + 1 processorResponseCode,processorResponseText,paymentId processorResponseCode,processorResponseText,paymentId,payerEmail @@ -64,6 +69,11 @@ BraintreeCreditCardVaultFacade Stored Cards (Braintree) + + BraintreePayPalVaultFacade + Stored Accounts (Braintree PayPal) + 1 + diff --git a/app/code/Magento/Braintree/etc/di.xml b/app/code/Magento/Braintree/etc/di.xml index def12ff4c8a7e..d051ef78cfcd2 100644 --- a/app/code/Magento/Braintree/etc/di.xml +++ b/app/code/Magento/Braintree/etc/di.xml @@ -19,13 +19,15 @@ - Magento\Braintree\Model\Ui\ConfigProvider::PAYPAL_CODE + Magento\Braintree\Model\Ui\PayPal\ConfigProvider::PAYPAL_CODE BraintreePayPalInfo BraintreePayPalValueHandlerPool + BraintreePayPalValidatorPool BraintreePayPalCommandPool - + + Magento\Braintree\Model\Ui\ConfigProvider::CC_VAULT_CODE @@ -51,6 +53,32 @@ Magento\Braintree\Model\Ui\ConfigProvider::CC_VAULT_CODE + + + Magento\Braintree\Model\Ui\PayPal\ConfigProvider::PAYPAL_VAULT_CODE + + + + + BraintreePayPalVaultPaymentConfig + + + + + + BraintreePayPalVaultPaymentValueHandler + + + + + + BraintreePayPalVaultPaymentConfig + BraintreePayPalVaultPaymentValueHandlerPool + BraintreePayPalFacade + Magento\Braintree\Model\Ui\PayPal\ConfigProvider::PAYPAL_VAULT_CODE + + + @@ -60,7 +88,7 @@ - Magento\Braintree\Model\Ui\ConfigProvider::PAYPAL_CODE + Magento\Braintree\Model\Ui\PayPal\ConfigProvider::PAYPAL_CODE @@ -70,6 +98,27 @@ Magento\Braintree\Gateway\Config\Config + + + BraintreeLoggerForTransactionSale + + + + + BraintreeLoggerForTransactionSale + + + + + BraintreeLoggerForTransactionSale + + + + + BraintreeLoggerForTransactionSale + + + @@ -85,6 +134,7 @@ BraintreeVoidCommand BraintreeRefundCommand BraintreeVoidCommand + BraintreeVoidCommand @@ -95,39 +145,49 @@ BraintreePayPalSaleCommand BraintreePayPalCaptureStrategyCommand BraintreeCaptureCommand + BraintreePayPalVaultAuthorizeCommand + BraintreePayPalVaultSaleCommand + BraintreeVaultCaptureCommand BraintreeVoidCommand BraintreeRefundCommand BraintreeVoidCommand - - + BraintreeCommandPool - - + - - BraintreeCommandManager - + BraintreePayPalCommandPool - + + - + + BraintreeCommandPool - + BraintreePayPalCommandPool + + + + BraintreeCommandManager + BraintreePayPalCommandManager + + + + - + BraintreeAuthorizeRequest @@ -146,11 +206,42 @@ Magento\Braintree\Gateway\Request\AddressDataBuilder Magento\Braintree\Gateway\Request\VaultDataBuilder Magento\Braintree\Gateway\Request\ThreeDSecureDataBuilder - Magento\Braintree\Gateway\Request\KountPaymentDataBuilder + Magento\Braintree\Gateway\Request\KountPaymentDataBuilder + Magento\Braintree\Gateway\Request\DescriptorDataBuilder + + + + + + + BraintreeSaleRequest + + + + + + BraintreeAuthorizeRequest + Magento\Braintree\Gateway\Request\SettlementDataBuilder + + + + + + + BraintreeCaptureRequest + Magento\Braintree\Gateway\Http\TransferFactory + Magento\Braintree\Gateway\Http\Client\TransactionSubmitForSettlement + Magento\Braintree\Gateway\Response\TransactionIdHandler + Magento\Braintree\Gateway\Validator\ResponseValidator + + + + + + Magento\Braintree\Gateway\Request\CaptureDataBuilder - @@ -169,74 +260,61 @@ Magento\Braintree\Gateway\Request\ChannelDataBuilder Magento\Braintree\Gateway\Request\AddressDataBuilder Magento\Braintree\Gateway\Request\ThreeDSecureDataBuilder - Magento\Braintree\Gateway\Request\KountPaymentDataBuilder + Magento\Braintree\Gateway\Request\KountPaymentDataBuilder + Magento\Braintree\Gateway\Request\DescriptorDataBuilder - - - + + - BraintreePayPalAuthorizeRequest - BraintreePayPalResponseHandler + BraintreeVaultSaleRequest - + - Magento\Braintree\Gateway\Request\CustomerDataBuilder - Magento\Braintree\Gateway\Request\PaymentDataBuilder - Magento\Braintree\Gateway\Request\ChannelDataBuilder + BraintreeVaultAuthorizeRequest + Magento\Braintree\Gateway\Request\SettlementDataBuilder - - - - BraintreeLoggerForTransactionSale - - - - - BraintreeLoggerForTransactionSale - - - - - BraintreeLoggerForTransactionSale - - - - - BraintreeLoggerForTransactionSale - - - - - + + - BraintreeSaleRequest + BraintreeVaultCaptureRequest + Magento\Braintree\Gateway\Http\TransferFactory + Magento\Braintree\Gateway\Http\Client\TransactionSale + Magento\Braintree\Gateway\Response\TransactionIdHandler + Magento\Braintree\Gateway\Validator\ResponseValidator - + - BraintreeAuthorizeRequest + Magento\Braintree\Gateway\Request\VaultCaptureDataBuilder Magento\Braintree\Gateway\Request\SettlementDataBuilder - - + + + + - BraintreeVaultSaleRequest + BraintreePayPalAuthorizeRequest + BraintreePayPalResponseHandler - + - BraintreeVaultAuthorizeRequest - Magento\Braintree\Gateway\Request\SettlementDataBuilder + Magento\Braintree\Gateway\Request\CustomerDataBuilder + Magento\Braintree\Gateway\Request\PaymentDataBuilder + Magento\Braintree\Gateway\Request\ChannelDataBuilder + Magento\Braintree\Gateway\Request\PayPal\VaultDataBuilder + Magento\Braintree\Gateway\Request\PayPal\DeviceDataBuilder + Magento\Braintree\Gateway\Request\DescriptorDataBuilder @@ -254,45 +332,46 @@ - - - + + - BraintreeCaptureRequest - Magento\Braintree\Gateway\Http\TransferFactory - Magento\Braintree\Gateway\Http\Client\TransactionSubmitForSettlement - Magento\Braintree\Gateway\Response\TransactionIdHandler - Magento\Braintree\Gateway\Validator\ResponseValidator + BraintreePayPalVaultAuthorizeRequest + BraintreePayPalVaultResponseHandler - + - Magento\Braintree\Gateway\Request\CaptureDataBuilder + Magento\Braintree\Gateway\Request\CustomerDataBuilder + Magento\Braintree\Gateway\Request\PaymentDataBuilder + Magento\Braintree\Gateway\Request\ChannelDataBuilder + Magento\Braintree\Gateway\Request\AddressDataBuilder + Magento\Braintree\Gateway\Request\DescriptorDataBuilder - - - + + - BraintreeVaultCaptureRequest - Magento\Braintree\Gateway\Http\TransferFactory - Magento\Braintree\Gateway\Http\Client\TransactionSale - Magento\Braintree\Gateway\Response\TransactionIdHandler - Magento\Braintree\Gateway\Validator\ResponseValidator + BraintreePayPalVaultSaleRequest - + - Magento\Braintree\Gateway\Request\VaultCaptureDataBuilder + BraintreePayPalVaultAuthorizeRequest Magento\Braintree\Gateway\Request\SettlementDataBuilder + + + + Magento\Vault\Model\CreditCardTokenFactory + + @@ -330,17 +409,14 @@ - - - - Magento\Braintree\Gateway\Response\PaymentDetailsHandler - Magento\Braintree\Gateway\Response\TransactionIdHandler - Magento\Braintree\Gateway\Response\PayPalDetailsHandler - - - + + + + Magento\Vault\Model\AccountPaymentTokenFactory + + @@ -356,6 +432,26 @@ Magento\Braintree\Gateway\Config\PayPal\Config + + + + Magento\Braintree\Gateway\Response\PaymentDetailsHandler + Magento\Braintree\Gateway\Response\TransactionIdHandler + Magento\Braintree\Gateway\Response\PayPalDetailsHandler + Magento\Braintree\Gateway\Response\PayPal\VaultDetailsHandler + + + + + + + Magento\Braintree\Gateway\Response\PaymentDetailsHandler + Magento\Braintree\Gateway\Response\TransactionIdHandler + Magento\Braintree\Gateway\Response\PayPalDetailsHandler + + + + @@ -379,7 +475,7 @@ - + Magento\Braintree\Gateway\Config\Config @@ -392,6 +488,22 @@ + + + + + + Magento\Braintree\Gateway\Config\PayPal\Config + + + + + + BraintreePayPalCountryValidator + + + + @@ -404,6 +516,7 @@ + @@ -411,19 +524,16 @@ - BraintreeTransactionsCollectionFactoryForReporting - BraintreeTransactionsReporting - @@ -433,5 +543,5 @@ - + diff --git a/app/code/Magento/Braintree/etc/frontend/di.xml b/app/code/Magento/Braintree/etc/frontend/di.xml index 98ae47dea794a..cdd56e236a72b 100644 --- a/app/code/Magento/Braintree/etc/frontend/di.xml +++ b/app/code/Magento/Braintree/etc/frontend/di.xml @@ -10,6 +10,7 @@ Magento\Braintree\Model\Ui\ConfigProvider + Magento\Braintree\Model\Ui\PayPal\ConfigProvider @@ -32,6 +33,7 @@ Magento\Braintree\Model\Ui\TokenUiComponentProvider + Magento\Braintree\Model\Ui\PayPal\TokenUiComponentProvider diff --git a/app/code/Magento/Braintree/i18n/en_US.csv b/app/code/Magento/Braintree/i18n/en_US.csv index f912e59c2edac..f5e2d36e1e9bb 100644 --- a/app/code/Magento/Braintree/i18n/en_US.csv +++ b/app/code/Magento/Braintree/i18n/en_US.csv @@ -140,6 +140,29 @@ Debug,Debug "liabilityShifted", "Liability Shifted" "liabilityShiftPossible", "Liability Shift Possible" "riskDataId", "Risk ID" -"riskDataDecision", "Risk Decision", -"paymentId", "Payment Id", -"payerEmail", "Payer Email", +"riskDataDecision", "Risk Decision" +"paymentId", "Payment Id" +"payerEmail", "Payer Email" +"sale","Sale" +"credit","Credit" +"authorization_expired","Authorization expired" +"authorizing","Authorizing" +"authorized","Authorized" +"gateway_rejected","Gateway rejected" +"failed","Failed" +"processor_declined","Processor declined" +"settled","Settled" +"settling","Settling" +"submitted_for_settlement","Submitted for settlement" +"voided","Voided" +"unrecognized","Unrecognized" +"settlement_declined","Settlement declined" +"settlement_pending","Settlement pending" +"settlement_confirmed","Settlement confirmed" +"paypal_account","Paypal account" +"coinbase_account","Coinbase account" +"europe_bank_accout","Europe bank account" +"credit_card","Credit card" +"apple_pay_card","Apple pay card" +"android_pay_card","Android pay card" +"Accept credit/debit cards and PayPal in your Magento store.
No setup or monthly fees and your customers never leave your store to complete the purchase.","Accept credit/debit cards and PayPal in your Magento store.
No setup or monthly fees and your customers never leave your store to complete the purchase." \ No newline at end of file diff --git a/app/code/Magento/Braintree/view/adminhtml/layout/sales_order_create_index.xml b/app/code/Magento/Braintree/view/adminhtml/layout/sales_order_create_index.xml index 76f6b5a4d616c..5e4f36e1c1fb4 100644 --- a/app/code/Magento/Braintree/view/adminhtml/layout/sales_order_create_index.xml +++ b/app/code/Magento/Braintree/view/adminhtml/layout/sales_order_create_index.xml @@ -18,13 +18,17 @@ braintree_cc_vault Magento_Vault::form/vault.phtml + + braintree_paypal_vault + Magento_Vault::form/vault.phtml + + class="Magento\Braintree\Block\Payment" + after="billing_method"/> diff --git a/app/code/Magento/Braintree/view/adminhtml/layout/sales_order_create_load_block_billing_method.xml b/app/code/Magento/Braintree/view/adminhtml/layout/sales_order_create_load_block_billing_method.xml index 68e0abc0cd009..579b82c61f690 100644 --- a/app/code/Magento/Braintree/view/adminhtml/layout/sales_order_create_load_block_billing_method.xml +++ b/app/code/Magento/Braintree/view/adminhtml/layout/sales_order_create_load_block_billing_method.xml @@ -18,6 +18,10 @@ braintree_cc_vault Magento_Vault::form/vault.phtml + + braintree_paypal_vault + Magento_Vault::form/vault.phtml + \ No newline at end of file diff --git a/app/code/Magento/Braintree/view/adminhtml/templates/form/paypal/vault.phtml b/app/code/Magento/Braintree/view/adminhtml/templates/form/paypal/vault.phtml new file mode 100644 index 0000000000000..22930bbc65666 --- /dev/null +++ b/app/code/Magento/Braintree/view/adminhtml/templates/form/paypal/vault.phtml @@ -0,0 +1,30 @@ +getData(TokenUiComponentProviderInterface::COMPONENT_DETAILS); +$icon = $details['icon']; +$id = $block->escapeHtml($block->getData('id')); +?> +
", + "nonceUrl": "escapeUrl($block->getData('nonceUrl')); ?>" + } + }' id="payment_" class="admin__field"> +
+ + + escapeHtml($details['payerEmail']); ?> +
+
diff --git a/app/code/Magento/Braintree/view/adminhtml/templates/form/vault.phtml b/app/code/Magento/Braintree/view/adminhtml/templates/form/vault.phtml index 3811461884725..001422d4bf911 100644 --- a/app/code/Magento/Braintree/view/adminhtml/templates/form/vault.phtml +++ b/app/code/Magento/Braintree/view/adminhtml/templates/form/vault.phtml @@ -7,7 +7,7 @@ use Magento\Vault\Model\Ui\TokenUiComponentProviderInterface; // @codingStandardsIgnoreFile /** @var \Magento\Framework\View\Element\Template $block */ -$details = $block->getData('details'); +$details = $block->getData(TokenUiComponentProviderInterface::COMPONENT_DETAILS); $icon = $block->getData('icons')[$details['type']]; $id = $block->escapeHtml($block->getData('id')); ?> @@ -15,6 +15,7 @@ $id = $block->escapeHtml($block->getData('id')); "Magento_Braintree/js/vault": { "container": "payment_", "publicHash": "escapeHtml($block->getData(TokenUiComponentProviderInterface::COMPONENT_PUBLIC_HASH)); ?>", + "code": "escapeHtml($block->getData('code')); ?>", "nonceUrl": "escapeUrl($block->getData('nonceUrl')); ?>" } }' id="payment_" class="admin__field"> diff --git a/app/code/Magento/Braintree/view/adminhtml/ui_component/braintree_report.xml b/app/code/Magento/Braintree/view/adminhtml/ui_component/braintree_report.xml index d1b661b2c3ecd..031ddca7a8707 100644 --- a/app/code/Magento/Braintree/view/adminhtml/ui_component/braintree_report.xml +++ b/app/code/Magento/Braintree/view/adminhtml/ui_component/braintree_report.xml @@ -109,7 +109,6 @@ - @@ -135,6 +133,22 @@ + + + + ${ $.parentName } + + componentType = column, index = ${ $.index }:visible + + braintree_report.braintree_report.listing_top.listing_filters + ui/grid/filters/elements/group + Magento_Ui/js/grid/filters/range + date + createdAt + Created At + + + @@ -216,7 +230,6 @@ desc - dateRange date Magento_Ui/js/grid/columns/date Created At diff --git a/app/code/Magento/Braintree/view/adminhtml/web/js/vault.js b/app/code/Magento/Braintree/view/adminhtml/web/js/vault.js index fcff173e7fcd4..ea832acb537e0 100644 --- a/app/code/Magento/Braintree/view/adminhtml/web/js/vault.js +++ b/app/code/Magento/Braintree/view/adminhtml/web/js/vault.js @@ -14,7 +14,8 @@ define([ return Class.extend({ defaults: { $selector: null, - selector: 'edit_form' + selector: 'edit_form', + $container: null }, /** @@ -25,17 +26,18 @@ define([ var self = this; self.$selector = $('#' + self.selector); + self.$container = $('#' + self.container); self.$selector.on( 'setVaultNotActive', function () { - self.$selector.off('submitOrder.braintree_vault'); + self.$selector.off('submitOrder.' + self.getCode()); } ); - this._super(); + self._super(); - this.initEventHandlers(); + self.initEventHandlers(); - return this; + return self; }, /** @@ -43,14 +45,14 @@ define([ * @returns {String} */ getCode: function () { - return 'braintree'; + return this.code; }, /** * Init event handlers */ initEventHandlers: function () { - $('#' + this.container).find('[name="payment[token_switcher]"]') + $(this.$container).find('[name="payment[token_switcher]"]') .on('click', this.selectPaymentMethod.bind(this)); }, @@ -66,7 +68,7 @@ define([ * Enable form event listeners */ enableEventListeners: function () { - this.$selector.on('submitOrder.braintree_vault', this.submitOrder.bind(this)); + this.$selector.on('submitOrder.' + this.getCode(), this.submitOrder.bind(this)); }, /** @@ -129,7 +131,7 @@ define([ this.createPublicHashSelector(); this.$selector.find('[name="payment[public_hash]"]').val(this.publicHash); - this.$selector.find('#braintree_nonce').val(nonce); + this.$container.find('#' + this.getNonceSelectorName()).val(nonce); }, /** @@ -138,16 +140,16 @@ define([ createPublicHashSelector: function () { var $input; - if (this.$selector.find('#braintree_nonce').size() === 0) { + if (this.$container.find('#' + this.getNonceSelectorName()).size() === 0) { $input = $('').attr( { type: 'hidden', - id: 'braintree_nonce', + id: this.getNonceSelectorName(), name: 'payment[payment_method_nonce]' } ); - $input.appendTo(this.$selector); + $input.appendTo(this.$container); $input.prop('disabled', false); } }, @@ -160,6 +162,14 @@ define([ alert({ content: message }); + }, + + /** + * Get selector name for nonce input + * @returns {String} + */ + getNonceSelectorName: function () { + return 'nonce_' + this.getCode(); } }); }); diff --git a/app/code/Magento/Braintree/view/adminhtml/web/styles.css b/app/code/Magento/Braintree/view/adminhtml/web/styles.css index c0d8822e779d4..81378f636eb61 100644 --- a/app/code/Magento/Braintree/view/adminhtml/web/styles.css +++ b/app/code/Magento/Braintree/view/adminhtml/web/styles.css @@ -3,5 +3,6 @@ * See COPYING.txt for license details. */ -.braintree-section .entry-edit-head > .config-heading .heading strong {padding-left:150px;background:url(images/braintree_logo.png) no-repeat 0 0 / 145px auto;line-height:36px;} -.braintree-section .entry-edit-head > .config-heading:before {background: url("images/braintree_allinone.png") no-repeat 0 0 / 100% auto;content: "";display: inline;float: right;height: 35px;width: 280px;} +.braintree-section .heading {background: url("images/braintree_logo.png") no-repeat 0 50% / 18rem auto; padding-left: 20rem;} +.braintree-section .button-container {float: right;} +.braintree-section .config-alt {background: url("images/braintree_allinone.png") no-repeat scroll 0 0 / 100% auto; height: 28px; margin: 0.5rem 0 0; width: 230px;} \ No newline at end of file diff --git a/app/code/Magento/Braintree/view/base/web/images/paypal-small.png b/app/code/Magento/Braintree/view/base/web/images/paypal-small.png new file mode 100644 index 0000000000000000000000000000000000000000..92d5c63bca4426abfc46ab0cff20bb968ffeaeed GIT binary patch literal 1398 zcmeAS@N?(olHy`uVBq!ia0vp^d_XL~!2~2%e!H0qq$EpRBT9nv(@M${i&7aJQ}UBi z6+Ckj(^G>|6H_V+Po~;1Ffc1+hD4M^`1)8S=jZArg4F0$^BXQ!4Z zB&DWj=GiK}-@RW+Av48RDcsc8z_-9TH6zobswg$M$}c3jDm&RSMakYy!KT6rXh3di zNuokUZcbjYRfVk**jy_h8zii+qySb@l5ML5aa4qFfP!;=QL2Kep0RGSfuW&-nVFuU ziK&^Hp^k!)fuWJU0T7w#8k$&{npqi{D?ot~(6*wKG^-#NH>h1eo~=?wNlAf~zJ7Um zxn8-kUVc%!zM-Y1CCCgTBVC{h-Qvo;lEez#ykcdT2`;I{$wiq3C7Jno3Lp~`lk!VT zY?Xj6g?J&i0B&qvF*KNf0j6J(SfFpHX8`gNOrftYexnUy@&(kzb(T9Bihb5uTZsl3!k| z30CjxYvq|&T#}fVoa*Ufs{}MbFEca6%D~9U+`!1x(Zt-$(a_M<%+b=oz{1qX$=T7- z#n{E!6sFfDKe;qFHLnDwHwB^B38!9AQpha;+U$~Alv$RV;#QQOs{r=0RVHq?Sl~1d zsy79*nctuBb#gG=+jF<-`#hGLvA2wK{+-Gnwdv&7HjR5dRwlxYR9)(Z!HoP7z0f{ zEOz{D@HcS()mQBL_HX4M;P!@m(b1YXRUx2rCA%JSTf)v3{~4>w%r4(68X zR*js^tZ6VidCr=1&UXA7;ohHOG?$m{S@!<>SvSF_S50>soR^t!X@$Sglv9l_4*r@H zIqmt|{z)P8r#!G?b5~h(;-t@9p5@C3+IVR#*24FX9) z=p-MW50QYTuox!fRg8&%!4|VYAZx6EO{RnbJa7;YLT6$iV~-v~z;r4GvJXi#C9>@S z8r?aH19(Nbktk826e}tOYXi0xpv3|VfJX)k7-38DzY|r8VV5Et;F~t-P2cu9Xa0C*CfdV_LyrWgjvN*P{Iz5>{l~eO|4{E6 zm-^#e5I^L?#L2)`8~b04UfUA8XLb7Bw&KNi;{!~w+c{!ePhD2a1c79xUGO-Pprg!p zH>-=J_9g87gtgg)vuPQ}P;~99@w_9X5}ACtD-fd_iGxNP??Qc!{j^cr_8nyJlEl;4 z<4-rrOUKG=4Dyh6mGE|MhPZDu`;E|%7VlzkTDbV6^o{w=+L`iML~22R@Zf>YfvJTi zep4w>TwJV|T&S`s;pu5PMPiHUK$n~1n+Qr)DC*KVXv4)t*=X4A*Np&wW2huLC+~W#w!Z>{dKvp@QEE%32QHTYq)sZFW34 zh7!c9a4oJK(`<)-nu~NV?hJ|lwaaMT$74s*HDUe(x(`L$E+7_+zW5~|m9><#Q65e* zrpdWDmBkA!MGa(J?=nv@+Jlrlaf)Ez!9=+Gvtl%(YLT_!WCKNNG~xW+lvKxZ+1it{ zcvZrd@!2SiNHc;Z^{!$?=Fx}q!`AzSy$ZLQOL#@S>UY96WB!(opQDCTr*UObUo2Bn zmD1<5BoT)*pvFMtKxx^)$~xl0B6wLpZ#@ z=5x+c@(UZA)H<);fc$IE>ZOeZqH2mqU{9h;tY(iOByO6<*LZ%d)dQO$HM#PkU*W)q zzQPUD*k--Tngnxo=ZPmrGnJC=zg-|s>C9PZD&+b%NJlA11gq_dZ?{7F72npK&5|`a zVCdXyHAFf7x8&)Yr(ET|>wWwR{;J3FMdQ;*~6bhU+zNj_7D)Ga8=VRVc@(lf8d6t%*QXsB4cf{Y-FI_@rHv1 z5#FwKvPniEOG2Zj^W`38yS65$gzD?xXGsNj{9N06-Eq35?ncOqO5rjxcl6@;WL~eY z1av5m(8)ZmW1%HdKo5nkbb<@?|m96?VN|yGFunxI<;kcIS_be zl&pAt?i#9I^k?KcLY>#-UJHf`xiI4qmt}`c6O$O1K7+*Ltb745+{BESmmcxd($LGf4{6%S9Z_4J4JlsM% zbU-?X)U~VaU4H%C1(v^Quvo&cbFNgKDQm{MIXnEh3@}vr90A zwDb)mY3<)lNW<>f>I)wfyRC~9q)5l_PY>3%rCB2*b|%?exhOiH!eC4XnW+~25hJS6yQSgP7MAOK zHGk<`fr8p@X<8iZ0Ri%=Q?J!65FDTaC{mA!-u7*?*vm}J&GQ_s*1*r$eF?qCNO+%9 z@mcb0qB_-6(NJ;`N7-DlORYRTG3L_?E$8j{9h#bY;V2eW8$Bl=$m-_<_n|P~Y>d_G z!qF-VeS>}Hb~c?zDbRSPJFMPzf=D{409}8%k^7U*qnxI;0}`!5W{*l6@)Y&G4)L-n z;)MRo+c=#|R|9I!yzuPHxiND8!G21<2%*T%d_dy>S6|VF*sPF|fsPw(BhlG<6o*!W zn~lZVLTKZeCm8AWv*&sq<@rURehF+)RFPB?QAV-}A2r)5x+BMWokpa0RSsJ}dzGIV zq5J60&lNQzbAAnH5e0h-S~6yK5L&v@S2Erjrq-#Yk8!+>&d`-V1zd5T- + + + diff --git a/app/code/Magento/Braintree/view/frontend/requirejs-config.js b/app/code/Magento/Braintree/view/frontend/requirejs-config.js index c08a45bdbecd7..76391a81fe663 100644 --- a/app/code/Magento/Braintree/view/frontend/requirejs-config.js +++ b/app/code/Magento/Braintree/view/frontend/requirejs-config.js @@ -6,7 +6,7 @@ var config = { map: { '*': { - braintree: 'https://js.braintreegateway.com/js/braintree-2.17.6.min.js' + braintree: 'https://js.braintreegateway.com/js/braintree-2.25.0.min.js' } } }; diff --git a/app/code/Magento/Braintree/view/frontend/templates/paypal/vault_token.phtml b/app/code/Magento/Braintree/view/frontend/templates/paypal/vault_token.phtml new file mode 100644 index 0000000000000..32c2d98e7e76b --- /dev/null +++ b/app/code/Magento/Braintree/view/frontend/templates/paypal/vault_token.phtml @@ -0,0 +1,49 @@ +escapeHtml($block->getPayerEmail()); +?> + + + <?php echo $block->escapeHtml(__('PayPal Logo')); ?> + + + +
+ getBlockHtml('formkey'); ?> + + +
+ + diff --git a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/paypal-vault.js b/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/paypal-vault.js new file mode 100644 index 0000000000000..a609175fe25bf --- /dev/null +++ b/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/paypal-vault.js @@ -0,0 +1,87 @@ +/** + * Copyright © 2016 Magento. All rights reserved. + * See COPYING.txt for license details. + */ +/*browser:true*/ +/*global define*/ +define([ + 'jquery', + 'underscore', + 'Magento_Vault/js/view/payment/method-renderer/vault', + 'Magento_Ui/js/model/messageList', + 'Magento_Checkout/js/model/full-screen-loader' +], function ($, _, VaultComponent, globalMessageList, fullScreenLoader) { + 'use strict'; + + return VaultComponent.extend({ + defaults: { + template: 'Magento_Braintree/payment/paypal/vault', + additionalData: {} + }, + + /** + * Get PayPal payer email + * @returns {String} + */ + getPayerEmail: function () { + return this.details.payerEmail; + }, + + /** + * Get type of payment + * @returns {String} + */ + getPaymentIcon: function () { + return window.checkoutConfig.payment['braintree_paypal'].paymentIcon; + }, + + /** + * Place order + */ + beforePlaceOrder: function () { + this.getPaymentMethodNonce(); + }, + + /** + * Send request to get payment method nonce + */ + getPaymentMethodNonce: function () { + var self = this; + + fullScreenLoader.startLoader(); + $.get(self.nonceUrl, { + 'public_hash': self.publicHash + }) + .done(function (response) { + fullScreenLoader.stopLoader(); + self.additionalData['payment_method_nonce'] = response.paymentMethodNonce; + self.placeOrder(); + }) + .fail(function (response) { + var error = JSON.parse(response.responseText); + + fullScreenLoader.stopLoader(); + globalMessageList.addErrorMessage({ + message: error.message + }); + }); + }, + + /** + * Get payment method data + * @returns {Object} + */ + getData: function () { + var data = { + 'method': this.code, + 'additional_data': { + 'public_hash': this.publicHash + } + }; + + data['additional_data'] = _.extend(data['additional_data'], this.additionalData); + + return data; + } + }); +}); diff --git a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/paypal.js b/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/paypal.js index 2b7aea3db5c4f..075a1fdaf1fc1 100644 --- a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/paypal.js +++ b/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/paypal.js @@ -11,8 +11,20 @@ define([ 'Magento_Braintree/js/view/payment/adapter', 'Magento_Checkout/js/model/quote', 'Magento_Checkout/js/model/full-screen-loader', - 'Magento_Checkout/js/model/payment/additional-validators' -], function ($, _, Component, Braintree, quote, fullScreenLoader, additionalValidators) { + 'Magento_Checkout/js/model/payment/additional-validators', + 'Magento_Vault/js/view/payment/vault-enabler', + 'Magento_Checkout/js/action/create-billing-address' +], function ( + $, + _, + Component, + Braintree, + quote, + fullScreenLoader, + additionalValidators, + VaultEnabler, + createBillingAddress +) { 'use strict'; return Component.extend({ @@ -22,12 +34,24 @@ define([ active: false, paymentMethodNonce: null, grandTotalAmount: null, + isReviewRequired: false, + customerEmail: null, + + /** + * Additional payment data + * + * {Object} + */ + additionalData: {}, /** * PayPal client configuration * {Object} */ clientConfig: { + dataCollector: { + paypal: true + }, /** * Triggers when widget is loaded @@ -35,6 +59,7 @@ define([ */ onReady: function (checkout) { Braintree.checkout = checkout; + this.additionalData['device_data'] = checkout.deviceData; this.enableButton(); Braintree.onReady(); }, @@ -60,17 +85,24 @@ define([ var self = this; this._super() - .observe(['active']); + .observe(['active', 'isReviewRequired', 'customerEmail']); + + this.vaultEnabler = new VaultEnabler(); + this.vaultEnabler.setPaymentCode(this.getVaultCode()); + this.vaultEnabler.isActivePaymentTokenEnabler.subscribe(function () { + self.onVaultPaymentTokenEnablerChange(); + }); this.grandTotalAmount = quote.totals()['base_grand_total']; quote.totals.subscribe(function () { if (self.grandTotalAmount !== quote.totals()['base_grand_total']) { self.grandTotalAmount = quote.totals()['base_grand_total']; - self.reInitPayPal(); } }); + // for each component initialization need update property + this.isReviewRequired(false); this.initClientConfig(); return this; @@ -131,8 +163,6 @@ define([ this.clientConfig[name] = fn.bind(this); } }, this); - - Braintree.config = _.extend(Braintree.config, this.clientConfig); }, /** @@ -152,14 +182,16 @@ define([ var billingAddress = { street: [address.streetAddress], city: address.locality, - regionCode: address.region, postcode: address.postalCode, countryId: address.countryCodeAlpha2, + email: customer.email, firstname: customer.firstName, lastname: customer.lastName, telephone: customer.phone }; + billingAddress['region_code'] = address.region; + billingAddress = createBillingAddress(billingAddress); quote.billingAddress(billingAddress); }, @@ -173,7 +205,13 @@ define([ if (quote.billingAddress() === null && typeof data.details.billingAddress !== 'undefined') { this.setBillingAddress(data.details, data.details.billingAddress); } - this.placeOrder(); + + if (this.isSkipOrderReview()) { + this.placeOrder(); + } else { + this.customerEmail(data.details.email); + this.isReviewRequired(true); + } }, /** @@ -193,15 +231,6 @@ define([ Braintree.setup(); }, - /** - * Triggers when customer click "Continue to PayPal" button - */ - payWithPayPal: function () { - if (additionalValidators.validate()) { - Braintree.checkout.paypal.initAuthFlow(); - } - }, - /** * Get locale * @returns {String} @@ -224,11 +253,12 @@ define([ */ getPayPalConfig: function () { var totals = quote.totals(), - config = {}; + config = {}, + isActiveVaultEnabler = this.isActiveVault(); config.paypal = { container: 'paypal-container', - singleUse: true, + singleUse: !isActiveVaultEnabler, headless: true, amount: this.grandTotalAmount, currency: totals['base_currency_code'], @@ -296,12 +326,18 @@ define([ * @returns {Object} */ getData: function () { - return { + var data = { 'method': this.getCode(), 'additional_data': { 'payment_method_nonce': this.paymentMethodNonce } }; + + data['additional_data'] = _.extend(data['additional_data'], this.additionalData); + + this.vaultEnabler.visitAdditionalData(data); + + return data; }, /** @@ -313,12 +349,43 @@ define([ return window.checkoutConfig.payment[this.getCode()].paymentAcceptanceMarkSrc; }, + /** + * @returns {String} + */ + getVaultCode: function () { + return window.checkoutConfig.payment[this.getCode()].vaultCode; + }, + + /** + * Check if need to skip order review + * @returns {Boolean} + */ + isSkipOrderReview: function () { + return window.checkoutConfig.payment[this.getCode()].skipOrderReview; + }, + + /** + * Checks if vault is active + * @returns {Boolean} + */ + isActiveVault: function () { + return this.vaultEnabler.isVaultEnabled() && this.vaultEnabler.isActivePaymentTokenEnabler(); + }, + + /** + * Re-init PayPal Auth flow to use Vault + */ + onVaultPaymentTokenEnablerChange: function () { + this.clientConfig.paypal.singleUse = !this.isActiveVault(); + this.reInitPayPal(); + }, + /** * Disable submit button */ disableButton: function () { // stop any previous shown loaders - fullScreenLoader.stopLoader(); + fullScreenLoader.stopLoader(true); fullScreenLoader.startLoader(); $('[data-button="place"]').attr('disabled', 'disabled'); }, @@ -329,6 +396,31 @@ define([ enableButton: function () { $('[data-button="place"]').removeAttr('disabled'); fullScreenLoader.stopLoader(); + }, + + /** + * Triggers when customer click "Continue to PayPal" button + */ + payWithPayPal: function () { + if (additionalValidators.validate()) { + Braintree.checkout.paypal.initAuthFlow(); + } + }, + + /** + * Get button title + * @returns {String} + */ + getButtonTitle: function () { + return this.isSkipOrderReview() ? 'Pay with PayPal' : 'Continue to PayPal'; + }, + + /** + * Get button id + * @returns {String} + */ + getButtonId: function () { + return this.getCode() + (this.isSkipOrderReview() ? '_pay_with' : '_continue_to'); } }); }); diff --git a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/vault.js b/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/vault.js index 3c349afca754d..dc2b0bdf34128 100644 --- a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/vault.js +++ b/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/vault.js @@ -6,12 +6,11 @@ /*global define*/ define([ 'jquery', - 'Magento_Braintree/js/view/payment/method-renderer/cc-form', 'Magento_Vault/js/view/payment/method-renderer/vault', 'Magento_Braintree/js/view/payment/adapter', 'Magento_Ui/js/model/messageList', 'Magento_Checkout/js/model/full-screen-loader' -], function ($, Component, VaultComponent, Braintree, globalMessageList, fullScreenLoader) { +], function ($, VaultComponent, Braintree, globalMessageList, fullScreenLoader) { 'use strict'; return VaultComponent.extend({ @@ -53,7 +52,7 @@ define([ var self = this; /** - * Define on ready callback + * Define already callback */ Braintree.onReady = function () { self.getPaymentMethodNonce(); diff --git a/app/code/Magento/Braintree/view/frontend/web/template/payment/form.html b/app/code/Magento/Braintree/view/frontend/web/template/payment/form.html index 9d1dda23c2d84..cd080c83ecfea 100644 --- a/app/code/Magento/Braintree/view/frontend/web/template/payment/form.html +++ b/app/code/Magento/Braintree/view/frontend/web/template/payment/form.html @@ -7,9 +7,9 @@
+ name="payment[method]" + class="radio" + data-bind="attr: {'id': getCode()}, value: getCode(), checked: isChecked, click: selectPaymentMethod, visible: isRadioButtonVisible()"/> @@ -109,8 +109,8 @@ -
- \ No newline at end of file + diff --git a/app/code/Magento/Braintree/view/frontend/web/template/payment/paypal.html b/app/code/Magento/Braintree/view/frontend/web/template/payment/paypal.html index f392d21b04091..a674299994c06 100644 --- a/app/code/Magento/Braintree/view/frontend/web/template/payment/paypal.html +++ b/app/code/Magento/Braintree/view/frontend/web/template/payment/paypal.html @@ -21,20 +21,57 @@
-
+
-
+ +
+ + +
+ + + +
+
+
+ +
+ +
+ +
+
+
diff --git a/app/code/Magento/Braintree/view/frontend/web/template/payment/paypal/vault.html b/app/code/Magento/Braintree/view/frontend/web/template/payment/paypal/vault.html new file mode 100644 index 0000000000000..eef06f048cdc1 --- /dev/null +++ b/app/code/Magento/Braintree/view/frontend/web/template/payment/paypal/vault.html @@ -0,0 +1,47 @@ + +
+
+ + +
+ +
+ +
+ + + +
+
+
+ +
+
+
+
\ No newline at end of file diff --git a/app/code/Magento/Payment/Api/Data/PaymentMethodInterface.php b/app/code/Magento/Payment/Api/Data/PaymentMethodInterface.php new file mode 100644 index 0000000000000..881595f60e541 --- /dev/null +++ b/app/code/Magento/Payment/Api/Data/PaymentMethodInterface.php @@ -0,0 +1,43 @@ +_paymentHelper = $paymentHelper; $this->methodSpecificationFactory = $methodSpecificationFactory; + $this->additionalChecks = $additionalChecks; parent::__construct($context, $data); } @@ -69,13 +88,17 @@ protected function _prepareLayout() */ protected function _canUseMethod($method) { - return $this->methodSpecificationFactory->create( + $checks = array_merge( [ AbstractMethod::CHECK_USE_FOR_COUNTRY, AbstractMethod::CHECK_USE_FOR_CURRENCY, AbstractMethod::CHECK_ORDER_TOTAL_MIN_MAX, - ] - )->isApplicable( + AbstractMethod::CHECK_ZERO_TOTAL + ], + $this->additionalChecks + ); + + return $this->methodSpecificationFactory->create($checks)->isApplicable( $method, $this->getQuote() ); @@ -124,11 +147,11 @@ public function getMethods() $quote = $this->getQuote(); $store = $quote ? $quote->getStoreId() : null; $methods = []; - $specification = $this->methodSpecificationFactory->create([AbstractMethod::CHECK_ZERO_TOTAL]); - foreach ($this->_paymentHelper->getStoreMethods($store, $quote) as $method) { - if ($this->_canUseMethod($method) && $specification->isApplicable($method, $this->getQuote())) { - $this->_assignMethod($method); - $methods[] = $method; + foreach ($this->getPaymentMethodList()->getActiveList($store) as $method) { + $methodInstance = $this->getPaymentMethodInstanceFactory()->create($method); + if ($methodInstance->isAvailable($quote) && $this->_canUseMethod($methodInstance)) { + $this->_assignMethod($methodInstance); + $methods[] = $methodInstance; } } $this->setData('methods', $methods); @@ -150,4 +173,36 @@ public function getSelectedMethodCode() } return false; } + + /** + * Get payment method list. + * + * @return \Magento\Payment\Api\PaymentMethodListInterface + * @deprecated + */ + private function getPaymentMethodList() + { + if ($this->paymentMethodList === null) { + $this->paymentMethodList = ObjectManager::getInstance()->get( + \Magento\Payment\Api\PaymentMethodListInterface::class + ); + } + return $this->paymentMethodList; + } + + /** + * Get payment method instance factory. + * + * @return \Magento\Payment\Model\Method\InstanceFactory + * @deprecated + */ + private function getPaymentMethodInstanceFactory() + { + if ($this->paymentMethodInstanceFactory === null) { + $this->paymentMethodInstanceFactory = ObjectManager::getInstance()->get( + \Magento\Payment\Model\Method\InstanceFactory::class + ); + } + return $this->paymentMethodInstanceFactory; + } } diff --git a/app/code/Magento/Payment/Block/Info/Substitution.php b/app/code/Magento/Payment/Block/Info/Substitution.php index 5cbc7ba325dea..c06212ebe7315 100644 --- a/app/code/Magento/Payment/Block/Info/Substitution.php +++ b/app/code/Magento/Payment/Block/Info/Substitution.php @@ -25,7 +25,7 @@ protected function _beforeToHtml() $container = $parentBlock->getParentBlock(); if ($container) { $block = $this->_layout->createBlock( - 'Magento\Framework\View\Element\Template', + \Magento\Framework\View\Element\Template::class, '', ['data' => ['method' => $this->getMethod(), 'template' => 'Magento_Payment::info/substitution.phtml']] ); diff --git a/app/code/Magento/Payment/Gateway/Data/PaymentDataObjectFactory.php b/app/code/Magento/Payment/Gateway/Data/PaymentDataObjectFactory.php index 92dd860a28311..0ab98673d9afa 100644 --- a/app/code/Magento/Payment/Gateway/Data/PaymentDataObjectFactory.php +++ b/app/code/Magento/Payment/Gateway/Data/PaymentDataObjectFactory.php @@ -65,7 +65,7 @@ public function create(InfoInterface $paymentInfo) $data['payment'] = $paymentInfo; return $this->objectManager->create( - 'Magento\Payment\Gateway\Data\PaymentDataObject', + \Magento\Payment\Gateway\Data\PaymentDataObject::class, $data ); } diff --git a/app/code/Magento/Payment/Helper/Data.php b/app/code/Magento/Payment/Helper/Data.php index 78cde93ba6717..0c5518a5c4c9f 100644 --- a/app/code/Magento/Payment/Helper/Data.php +++ b/app/code/Magento/Payment/Helper/Data.php @@ -118,6 +118,7 @@ public function getMethodInstance($code) * @param null|string|bool|int $store * @param Quote|null $quote * @return AbstractMethod[] + * @deprecated */ public function getStoreMethods($store = null, $quote = null) { diff --git a/app/code/Magento/Payment/Model/Cart/SalesModel/Factory.php b/app/code/Magento/Payment/Model/Cart/SalesModel/Factory.php index e43026ce3718e..2cb288dba0773 100644 --- a/app/code/Magento/Payment/Model/Cart/SalesModel/Factory.php +++ b/app/code/Magento/Payment/Model/Cart/SalesModel/Factory.php @@ -34,9 +34,9 @@ public function create($salesModel) { $arguments = ['salesModel' => $salesModel]; if ($salesModel instanceof \Magento\Quote\Model\Quote) { - return $this->_objectManager->create('Magento\Payment\Model\Cart\SalesModel\Quote', $arguments); + return $this->_objectManager->create(\Magento\Payment\Model\Cart\SalesModel\Quote::class, $arguments); } elseif ($salesModel instanceof \Magento\Sales\Model\Order) { - return $this->_objectManager->create('Magento\Payment\Model\Cart\SalesModel\Order', $arguments); + return $this->_objectManager->create(\Magento\Payment\Model\Cart\SalesModel\Order::class, $arguments); } throw new \InvalidArgumentException('Sales model has bad type!'); } diff --git a/app/code/Magento/Payment/Model/Checks/CanUseForCountry/CountryProvider.php b/app/code/Magento/Payment/Model/Checks/CanUseForCountry/CountryProvider.php index 8342b181d5e6f..cb7791cbc6d2d 100644 --- a/app/code/Magento/Payment/Model/Checks/CanUseForCountry/CountryProvider.php +++ b/app/code/Magento/Payment/Model/Checks/CanUseForCountry/CountryProvider.php @@ -31,8 +31,8 @@ public function __construct(DirectoryHelper $directoryHelper) */ public function getCountry(Quote $quote) { - $address = $quote->isVirtual() ? $quote->getBillingAddress() : $quote->getShippingAddress(); - return $address + $address = $quote->getBillingAddress() ? : $quote->getShippingAddress(); + return (!empty($address) && !empty($address->getCountry())) ? $address->getCountry() : $this->directoryHelper->getDefaultCountry(); } diff --git a/app/code/Magento/Payment/Model/Method/AbstractMethod.php b/app/code/Magento/Payment/Model/Method/AbstractMethod.php index 24b543ca02d62..50c0f52e3f45b 100644 --- a/app/code/Magento/Payment/Model/Method/AbstractMethod.php +++ b/app/code/Magento/Payment/Model/Method/AbstractMethod.php @@ -70,12 +70,12 @@ abstract class AbstractMethod extends \Magento\Framework\Model\AbstractExtensibl /** * @var string */ - protected $_formBlockType = 'Magento\Payment\Block\Form'; + protected $_formBlockType = \Magento\Payment\Block\Form::class; /** * @var string */ - protected $_infoBlockType = 'Magento\Payment\Block\Info'; + protected $_infoBlockType = \Magento\Payment\Block\Info::class; /** * Payment Method feature diff --git a/app/code/Magento/Payment/Model/Method/Adapter.php b/app/code/Magento/Payment/Model/Method/Adapter.php index 1d693e11fe51f..07a4dcdef5f3c 100644 --- a/app/code/Magento/Payment/Model/Method/Adapter.php +++ b/app/code/Magento/Payment/Model/Method/Adapter.php @@ -268,14 +268,17 @@ public function isAvailable(CartInterface $quote = null) $checkResult = new DataObject(); $checkResult->setData('is_available', true); try { - $validator = $this->getValidatorPool()->get('availability'); - $result = $validator->validate( - [ - 'payment' => $this->paymentDataObjectFactory->create($this->getInfoInstance()) - ] - ); - - $checkResult->setData('is_available', $result->isValid()); + $infoInstance = $this->getInfoInstance(); + if ($infoInstance !== null) { + $validator = $this->getValidatorPool()->get('availability'); + $result = $validator->validate( + [ + 'payment' => $this->paymentDataObjectFactory->create($infoInstance) + ] + ); + + $checkResult->setData('is_available', $result->isValid()); + } } catch (\Exception $e) { // pass } diff --git a/app/code/Magento/Payment/Model/Method/Cc.php b/app/code/Magento/Payment/Model/Method/Cc.php index c5dcfb727e37c..f5dd670b2ede4 100644 --- a/app/code/Magento/Payment/Model/Method/Cc.php +++ b/app/code/Magento/Payment/Model/Method/Cc.php @@ -19,12 +19,12 @@ class Cc extends \Magento\Payment\Model\Method\AbstractMethod /** * @var string */ - protected $_formBlockType = 'Magento\Payment\Block\Form\Cc'; + protected $_formBlockType = \Magento\Payment\Block\Form\Cc::class; /** * @var string */ - protected $_infoBlockType = 'Magento\Payment\Block\Info\Cc'; + protected $_infoBlockType = \Magento\Payment\Block\Info\Cc::class; /** * @var bool @@ -127,28 +127,25 @@ public function validate() //Solo, Switch or Maestro. International safe 'SO' => '/(^(6334)[5-9](\d{11}$|\d{13,14}$))|(^(6767)(\d{12}$|\d{14,15}$))/', 'SM' => '/(^(5[0678])\d{11,18}$)|(^(6[^05])\d{11,18}$)|(^(601)[^1]\d{9,16}$)|(^(6011)\d{9,11}$)' . - '|(^(6011)\d{13,16}$)|(^(65)\d{11,13}$)|(^(65)\d{15,18}$)' . - '|(^(49030)[2-9](\d{10}$|\d{12,13}$))|(^(49033)[5-9](\d{10}$|\d{12,13}$))' . - '|(^(49110)[1-2](\d{10}$|\d{12,13}$))|(^(49117)[4-9](\d{10}$|\d{12,13}$))' . - '|(^(49118)[0-2](\d{10}$|\d{12,13}$))|(^(4936)(\d{12}$|\d{14,15}$))/', + '|(^(6011)\d{13,16}$)|(^(65)\d{11,13}$)|(^(65)\d{15,18}$)' . + '|(^(49030)[2-9](\d{10}$|\d{12,13}$))|(^(49033)[5-9](\d{10}$|\d{12,13}$))' . + '|(^(49110)[1-2](\d{10}$|\d{12,13}$))|(^(49117)[4-9](\d{10}$|\d{12,13}$))' . + '|(^(49118)[0-2](\d{10}$|\d{12,13}$))|(^(4936)(\d{12}$|\d{14,15}$))/', // Visa 'VI' => '/^4[0-9]{12}([0-9]{3})?$/', // Master Card - 'MC' => '/^5[1-5][0-9]{14}$/', + 'MC' => '/^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$/', // American Express 'AE' => '/^3[47][0-9]{13}$/', // Discover - 'DI' => '/^(30[0-5][0-9]{13}|3095[0-9]{12}|35(2[8-9][0-9]{12}|[3-8][0-9]{13})' . - '|36[0-9]{12}|3[8-9][0-9]{14}|6011(0[0-9]{11}|[2-4][0-9]{11}|74[0-9]{10}|7[7-9][0-9]{10}' . - '|8[6-9][0-9]{10}|9[0-9]{11})|62(2(12[6-9][0-9]{10}|1[3-9][0-9]{11}|[2-8][0-9]{12}' . - '|9[0-1][0-9]{11}|92[0-5][0-9]{10})|[4-6][0-9]{13}|8[2-8][0-9]{12})|6(4[4-9][0-9]{13}' . - '|5[0-9]{14}))$/', + 'DI' => '/^(6011((0|9|[2-4])[0-9]{11,14}|(74|7[7-9]|8[6-9])[0-9]{10,13})|6(4[4-9][0-9]{13,16}|' . + '5[0-9]{14,17}))/', + 'DN' => '/^3(0[0-5][0-9]{13,16}|095[0-9]{12,15}|(6|[8-9])[0-9]{14,17})/', + // UnionPay + 'UN' => '/^622(1(2[6-9][0-9]{10,13}|[3-9][0-9]{11,14})|[3-8][0-9]{12,15}|9([[0-1][0-9]{11,14}|' . + '2[0-5][0-9]{10,13}))|62[4-6][0-9]{13,16}|628[2-8][0-9]{12,15}/', // JCB - 'JCB' => '/^(30[0-5][0-9]{13}|3095[0-9]{12}|35(2[8-9][0-9]{12}|[3-8][0-9]{13})|36[0-9]{12}' . - '|3[8-9][0-9]{14}|6011(0[0-9]{11}|[2-4][0-9]{11}|74[0-9]{10}|7[7-9][0-9]{10}' . - '|8[6-9][0-9]{10}|9[0-9]{11})|62(2(12[6-9][0-9]{10}|1[3-9][0-9]{11}|[2-8][0-9]{12}' . - '|9[0-1][0-9]{11}|92[0-5][0-9]{10})|[4-6][0-9]{13}|8[2-8][0-9]{12})|6(4[4-9][0-9]{13}' . - '|5[0-9]{14}))$/', + 'JCB' => '/^35(2[8-9][0-9]{12,15}|[3-8][0-9]{13,16})/', 'MI' => '/^(5(0|[6-9])|63|67(?!59|6770|6774))\d*$/', 'MD' => '/^(6759(?!24|38|40|6[3-9]|70|76)|676770|676774)\d*$/', ]; @@ -215,6 +212,8 @@ public function getVerificationRegEx() 'MC' => '/^[0-9]{3}$/', 'AE' => '/^[0-9]{4}$/', 'DI' => '/^[0-9]{3}$/', + 'DN' => '/^[0-9]{3}$/', + 'UN' => '/^[0-9]{3}$/', 'SS' => '/^[0-9]{3,4}$/', 'SM' => '/^[0-9]{3,4}$/', 'SO' => '/^[0-9]{3,4}$/', diff --git a/app/code/Magento/Payment/Model/Method/InstanceFactory.php b/app/code/Magento/Payment/Model/Method/InstanceFactory.php new file mode 100644 index 0000000000000..c273c71e78330 --- /dev/null +++ b/app/code/Magento/Payment/Model/Method/InstanceFactory.php @@ -0,0 +1,42 @@ +helper = $helper; + } + + /** + * Create payment method instance. + * + * @param PaymentMethodInterface $paymentMethod + * @return \Magento\Payment\Model\MethodInterface + */ + public function create(PaymentMethodInterface $paymentMethod) + { + $methodInstance = $this->helper->getMethodInstance($paymentMethod->getCode()); + $methodInstance->setStore($paymentMethod->getStoreId()); + + return $methodInstance; + } +} diff --git a/app/code/Magento/Payment/Model/Method/Substitution.php b/app/code/Magento/Payment/Model/Method/Substitution.php index 375f4452494d3..3d2ca06609783 100644 --- a/app/code/Magento/Payment/Model/Method/Substitution.php +++ b/app/code/Magento/Payment/Model/Method/Substitution.php @@ -31,7 +31,7 @@ class Substitution extends AbstractMethod /** * @var string */ - protected $_infoBlockType = 'Magento\Payment\Block\Info\Substitution'; + protected $_infoBlockType = \Magento\Payment\Block\Info\Substitution::class; /** * Retrieve payment method title diff --git a/app/code/Magento/Payment/Model/MethodList.php b/app/code/Magento/Payment/Model/MethodList.php index df0ddb9ed4b0c..ff1f786c77f61 100644 --- a/app/code/Magento/Payment/Model/MethodList.php +++ b/app/code/Magento/Payment/Model/MethodList.php @@ -6,12 +6,14 @@ namespace Magento\Payment\Model; +use Magento\Framework\App\ObjectManager; use Magento\Payment\Model\Method\AbstractMethod; class MethodList { /** * @var \Magento\Payment\Helper\Data + * @deprecated */ protected $paymentHelper; @@ -20,6 +22,16 @@ class MethodList */ protected $methodSpecificationFactory; + /** + * @var \Magento\Payment\Api\PaymentMethodListInterface + */ + private $paymentMethodList; + + /** + * @var \Magento\Payment\Model\Method\InstanceFactory + */ + private $paymentMethodInstanceFactory; + /** * @param \Magento\Payment\Helper\Data $paymentHelper * @param Checks\SpecificationFactory $specificationFactory @@ -40,14 +52,16 @@ public function __construct( public function getAvailableMethods(\Magento\Quote\Api\Data\CartInterface $quote = null) { $store = $quote ? $quote->getStoreId() : null; - $methods = []; - foreach ($this->paymentHelper->getStoreMethods($store, $quote) as $method) { - if ($this->_canUseMethod($method, $quote)) { - $method->setInfoInstance($quote->getPayment()); - $methods[] = $method; + $availableMethods = []; + + foreach ($this->getPaymentMethodList()->getActiveList($store) as $method) { + $methodInstance = $this->getPaymentMethodInstanceFactory()->create($method); + if ($methodInstance->isAvailable($quote) && $this->_canUseMethod($methodInstance, $quote)) { + $methodInstance->setInfoInstance($quote->getPayment()); + $availableMethods[] = $methodInstance; } } - return $methods; + return $availableMethods; } /** @@ -61,6 +75,7 @@ protected function _canUseMethod($method, \Magento\Quote\Api\Data\CartInterface { return $this->methodSpecificationFactory->create( [ + AbstractMethod::CHECK_USE_CHECKOUT, AbstractMethod::CHECK_USE_FOR_COUNTRY, AbstractMethod::CHECK_USE_FOR_CURRENCY, AbstractMethod::CHECK_ORDER_TOTAL_MIN_MAX, @@ -70,4 +85,36 @@ protected function _canUseMethod($method, \Magento\Quote\Api\Data\CartInterface $quote ); } + + /** + * Get payment method list. + * + * @return \Magento\Payment\Api\PaymentMethodListInterface + * @deprecated + */ + private function getPaymentMethodList() + { + if ($this->paymentMethodList === null) { + $this->paymentMethodList = ObjectManager::getInstance()->get( + \Magento\Payment\Api\PaymentMethodListInterface::class + ); + } + return $this->paymentMethodList; + } + + /** + * Get payment method instance factory. + * + * @return \Magento\Payment\Model\Method\InstanceFactory + * @deprecated + */ + private function getPaymentMethodInstanceFactory() + { + if ($this->paymentMethodInstanceFactory === null) { + $this->paymentMethodInstanceFactory = ObjectManager::getInstance()->get( + \Magento\Payment\Model\Method\InstanceFactory::class + ); + } + return $this->paymentMethodInstanceFactory; + } } diff --git a/app/code/Magento/Payment/Model/PaymentMethod.php b/app/code/Magento/Payment/Model/PaymentMethod.php new file mode 100644 index 0000000000000..581c4703f777e --- /dev/null +++ b/app/code/Magento/Payment/Model/PaymentMethod.php @@ -0,0 +1,78 @@ +code = $code; + $this->title = $title; + $this->storeId = $storeId; + $this->isActive = $isActive; + } + + /** + * {@inheritdoc} + */ + public function getCode() + { + return $this->code; + } + + /** + * {@inheritdoc} + */ + public function getTitle() + { + return $this->title; + } + + /** + * {@inheritdoc} + */ + public function getStoreId() + { + return $this->storeId; + } + + /** + * {@inheritdoc} + */ + public function getIsActive() + { + return $this->isActive; + } +} diff --git a/app/code/Magento/Payment/Model/PaymentMethodList.php b/app/code/Magento/Payment/Model/PaymentMethodList.php new file mode 100644 index 0000000000000..5968d201ca686 --- /dev/null +++ b/app/code/Magento/Payment/Model/PaymentMethodList.php @@ -0,0 +1,92 @@ +methodFactory = $methodFactory; + $this->helper = $helper; + } + + /** + * {@inheritdoc} + */ + public function getList($storeId) + { + $methodsCodes = array_keys($this->helper->getPaymentMethods()); + + $methodsInstances = array_map( + function ($code) { + return $this->helper->getMethodInstance($code); + }, + $methodsCodes + ); + + $methodsInstances = array_filter($methodsInstances, function (MethodInterface $method) { + return !($method instanceof \Magento\Payment\Model\Method\Substitution); + }); + + @uasort( + $methodsInstances, + function (MethodInterface $a, MethodInterface $b) use ($storeId) { + return (int)$a->getConfigData('sort_order', $storeId) - (int)$b->getConfigData('sort_order', $storeId); + } + ); + + $methodList = array_map( + function (MethodInterface $methodInstance) use ($storeId) { + + return $this->methodFactory->create([ + 'code' => (string)$methodInstance->getCode(), + 'title' => (string)$methodInstance->getTitle(), + 'storeId' => (int)$storeId, + 'isActive' => (bool)$methodInstance->isActive($storeId) + ]); + }, + $methodsInstances + ); + + return array_values($methodList); + } + + /** + * {@inheritdoc} + */ + public function getActiveList($storeId) + { + $methodList = array_filter( + $this->getList($storeId), + function (PaymentMethodInterface $method) { + return $method->getIsActive(); + } + ); + + return array_values($methodList); + } +} diff --git a/app/code/Magento/Payment/Test/Unit/Block/Adminhtml/Transparent/FormTest.php b/app/code/Magento/Payment/Test/Unit/Block/Adminhtml/Transparent/FormTest.php index c87b597825d1c..7b156f244165c 100644 --- a/app/code/Magento/Payment/Test/Unit/Block/Adminhtml/Transparent/FormTest.php +++ b/app/code/Magento/Payment/Test/Unit/Block/Adminhtml/Transparent/FormTest.php @@ -32,25 +32,25 @@ protected function setUp() { $objectManagerHelper = new ObjectManager($this); - $this->requestMock = $this->getMockBuilder('\Magento\Framework\App\RequestInterface') + $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) ->setMethods(['getParam']) ->getMockForAbstractClass(); - $this->urlBuilderMock = $this->getMockBuilder('\Magento\Framework\UrlInterface') + $this->urlBuilderMock = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) ->setMethods(['getUrl']) ->getMockForAbstractClass(); - $context = $objectManagerHelper->getObject('Magento\Framework\View\Element\Template\Context'); + $context = $objectManagerHelper->getObject(\Magento\Framework\View\Element\Template\Context::class); - $this->methodMock = $this->getMockBuilder('Magento\Payment\Model\Method\TransparentInterface') + $this->methodMock = $this->getMockBuilder(\Magento\Payment\Model\Method\TransparentInterface::class) ->getMock(); - $this->checkoutSessionMock = $this->getMockBuilder('Magento\Checkout\Model\Session') + $this->checkoutSessionMock = $this->getMockBuilder(\Magento\Checkout\Model\Session::class) ->setMethods([]) ->disableOriginalConstructor() ->getMock(); - $paymentConfigMock = $this->getMockBuilder('Magento\Payment\Model\Config') + $paymentConfigMock = $this->getMockBuilder(\Magento\Payment\Model\Config::class) ->setMethods([]) ->disableOriginalConstructor() ->getMock(); @@ -64,10 +64,10 @@ protected function setUp() public function testToHtmlShouldRender() { - $quoteMock = $this->getMockBuilder('Magento\Quote\Model\Quote') + $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) ->disableOriginalConstructor() ->getMock(); - $paymentMock = $this->getMockBuilder('Magento\Quote\Model\Quote\Payment') + $paymentMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Payment::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Payment/Test/Unit/Block/Form/ContainerTest.php b/app/code/Magento/Payment/Test/Unit/Block/Form/ContainerTest.php index 4cb09ba321c3c..e6de90409de1d 100644 --- a/app/code/Magento/Payment/Test/Unit/Block/Form/ContainerTest.php +++ b/app/code/Magento/Payment/Test/Unit/Block/Form/ContainerTest.php @@ -17,8 +17,8 @@ class ContainerTest extends \PHPUnit_Framework_TestCase public function testSetMethodFormTemplate() { $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $childBlockA = $objectManagerHelper->getObject('Magento\Framework\View\Element\Template'); - $childBlockB = $objectManagerHelper->getObject('Magento\Framework\View\Element\Template'); + $childBlockA = $objectManagerHelper->getObject(\Magento\Framework\View\Element\Template::class); + $childBlockB = $objectManagerHelper->getObject(\Magento\Framework\View\Element\Template::class); $func = function ($blockName) use ($childBlockA, $childBlockB) { switch ($blockName) { @@ -29,7 +29,7 @@ public function testSetMethodFormTemplate() } return null; }; - $block = $this->getMock('Magento\Payment\Block\Form\Container', ['getChildBlock'], [], '', false); + $block = $this->getMock(\Magento\Payment\Block\Form\Container::class, ['getChildBlock'], [], '', false); $block->expects($this->atLeastOnce())->method('getChildBlock')->will($this->returnCallback($func)); $template = 'any_template.phtml'; diff --git a/app/code/Magento/Payment/Test/Unit/Block/FormTest.php b/app/code/Magento/Payment/Test/Unit/Block/FormTest.php index 0524358d6562f..ac207c02b0691 100644 --- a/app/code/Magento/Payment/Test/Unit/Block/FormTest.php +++ b/app/code/Magento/Payment/Test/Unit/Block/FormTest.php @@ -35,26 +35,26 @@ class FormTest extends \PHPUnit_Framework_TestCase protected function setUp() { $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_storeManager = $this->getMockBuilder( - '\Magento\Store\Model\StoreManager' + $this->_storeManager = $this->getMockBuilder( + \Magento\Store\Model\StoreManager::class )->setMethods( ['getStore'] )->disableOriginalConstructor()->getMock(); - $this->_eventManager = $this->getMockBuilder( - '\Magento\Framework\Event\ManagerInterface' + $this->_eventManager = $this->getMockBuilder( + \Magento\Framework\Event\ManagerInterface::class )->setMethods( ['dispatch'] )->disableOriginalConstructor()->getMock(); - $this->_escaper = $this->getMock('\Magento\Framework\Escaper', null, [], '', true); - $context = $helper->getObject( - 'Magento\Framework\View\Element\Template\Context', + $this->_escaper = $this->getMock(\Magento\Framework\Escaper::class, null, [], '', true); + $context = $helper->getObject( + \Magento\Framework\View\Element\Template\Context::class, [ 'storeManager' => $this->_storeManager, 'eventManager' => $this->_eventManager, 'escaper' => $this->_escaper ] ); - $this->_object = $helper->getObject('Magento\Payment\Block\Form', ['context' => $context]); + $this->_object = $helper->getObject(\Magento\Payment\Block\Form::class, ['context' => $context]); } /** @@ -69,7 +69,7 @@ public function testGetMethodException() public function testGetMethodCode() { - $method = $this->getMock('Magento\Payment\Model\MethodInterface', [], [], '', false); + $method = $this->getMock(\Magento\Payment\Model\MethodInterface::class, [], [], '', false); $method->expects($this->once()) ->method('getCode') ->will($this->returnValue('method_code')); @@ -82,7 +82,7 @@ public function testGetMethodCode() */ public function testGetInfoData($field, $value, $expected) { - $methodInstance = $this->getMockBuilder('\Magento\Payment\Model\Method\AbstractMethod') + $methodInstance = $this->getMockBuilder(\Magento\Payment\Model\Method\AbstractMethod::class) ->setMethods(['getData']) ->disableOriginalConstructor() ->getMock(); @@ -90,8 +90,8 @@ public function testGetInfoData($field, $value, $expected) ->method('getData') ->with($field) ->will($this->returnValue($value)); - $method = $this->getMockBuilder( - 'Magento\Payment\Model\MethodInterface' + $method = $this->getMockBuilder( + \Magento\Payment\Model\MethodInterface::class )->getMockForAbstractClass(); $method->expects($this->any()) ->method('getInfoInstance') @@ -118,7 +118,7 @@ public function getInfoDataProvider() public function testSetMethod() { - $methodInterfaceMock = $this->getMockBuilder('\Magento\Payment\Model\MethodInterface') + $methodInterfaceMock = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) ->getMockForAbstractClass(); $this->assertSame($this->_object, $this->_object->setMethod($methodInterfaceMock)); diff --git a/app/code/Magento/Payment/Test/Unit/Block/Info/CcTest.php b/app/code/Magento/Payment/Test/Unit/Block/Info/CcTest.php index 744beb6634a85..3d75aaa39be34 100644 --- a/app/code/Magento/Payment/Test/Unit/Block/Info/CcTest.php +++ b/app/code/Magento/Payment/Test/Unit/Block/Info/CcTest.php @@ -31,14 +31,26 @@ class CcTest extends \PHPUnit_Framework_TestCase protected function setUp() { $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->paymentConfig = $this->getMock('Magento\Payment\Model\Config', [], [], '', false); - $this->localeDate = $this->getMock('Magento\Framework\Stdlib\DateTime\TimezoneInterface', [], [], '', false); - $context = $this->getMock('Magento\Framework\View\Element\Template\Context', ['getLocaleDate'], [], '', false); + $this->paymentConfig = $this->getMock(\Magento\Payment\Model\Config::class, [], [], '', false); + $this->localeDate = $this->getMock( + \Magento\Framework\Stdlib\DateTime\TimezoneInterface::class, + [], + [], + '', + false + ); + $context = $this->getMock( + \Magento\Framework\View\Element\Template\Context::class, + ['getLocaleDate'], + [], + '', + false + ); $context->expects($this->any()) ->method('getLocaleDate') ->will($this->returnValue($this->localeDate)); $this->model = $this->objectManager->getObject( - 'Magento\Payment\Block\Info\Cc', + \Magento\Payment\Block\Info\Cc::class, [ 'paymentConfig' => $this->paymentConfig, 'context' => $context @@ -54,7 +66,7 @@ public function testGetCcTypeName($configCcTypes, $ccType, $expected) $this->paymentConfig->expects($this->any()) ->method('getCcTypes') ->will($this->returnValue($configCcTypes)); - $paymentInfo = $this->getMock('Magento\Payment\Model\Info', ['getCcType'], [], '', false); + $paymentInfo = $this->getMock(\Magento\Payment\Model\Info::class, ['getCcType'], [], '', false); $paymentInfo->expects($this->any()) ->method('getCcType') ->will($this->returnValue($ccType)); @@ -79,7 +91,13 @@ public function getCcTypeNameDataProvider() */ public function testHasCcExpDate($ccExpMonth, $ccExpYear, $expected) { - $paymentInfo = $this->getMock('Magento\Payment\Model\Info', ['getCcExpMonth', 'getCcExpYear'], [], '', false); + $paymentInfo = $this->getMock( + \Magento\Payment\Model\Info::class, + ['getCcExpMonth', 'getCcExpYear'], + [], + '', + false + ); $paymentInfo->expects($this->any()) ->method('getCcExpMonth') ->will($this->returnValue($ccExpMonth)); @@ -107,7 +125,7 @@ public function hasCcExpDateDataProvider() */ public function testGetCcExpMonth($ccExpMonth, $expected) { - $paymentInfo = $this->getMock('Magento\Payment\Model\Info', ['getCcExpMonth'], [], '', false); + $paymentInfo = $this->getMock(\Magento\Payment\Model\Info::class, ['getCcExpMonth'], [], '', false); $paymentInfo->expects($this->any()) ->method('getCcExpMonth') ->will($this->returnValue($ccExpMonth)); @@ -131,7 +149,13 @@ public function ccExpMonthDataProvider() */ public function testGetCcExpDate($ccExpMonth, $ccExpYear) { - $paymentInfo = $this->getMock('Magento\Payment\Model\Info', ['getCcExpMonth', 'getCcExpYear'], [], '', false); + $paymentInfo = $this->getMock( + \Magento\Payment\Model\Info::class, + ['getCcExpMonth', 'getCcExpYear'], + [], + '', + false + ); $paymentInfo ->expects($this->any()) ->method('getCcExpMonth') diff --git a/app/code/Magento/Payment/Test/Unit/Block/Info/ContainerAbstractTest.php b/app/code/Magento/Payment/Test/Unit/Block/Info/ContainerAbstractTest.php index 7555a39917c43..5c87fb4ca28eb 100644 --- a/app/code/Magento/Payment/Test/Unit/Block/Info/ContainerAbstractTest.php +++ b/app/code/Magento/Payment/Test/Unit/Block/Info/ContainerAbstractTest.php @@ -14,19 +14,19 @@ class ContainerAbstractTest extends \PHPUnit_Framework_TestCase public function testSetInfoTemplate() { $block = $this->getMock( - 'Magento\Payment\Block\Info\AbstractContainer', + \Magento\Payment\Block\Info\AbstractContainer::class, ['getChildBlock', 'getPaymentInfo'], [], '', false ); $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $paymentInfo = $objectManagerHelper->getObject('Magento\Payment\Model\Info'); - $methodInstance = $objectManagerHelper->getObject('Magento\OfflinePayments\Model\Checkmo'); + $paymentInfo = $objectManagerHelper->getObject(\Magento\Payment\Model\Info::class); + $methodInstance = $objectManagerHelper->getObject(\Magento\OfflinePayments\Model\Checkmo::class); $paymentInfo->setMethodInstance($methodInstance); $block->expects($this->atLeastOnce())->method('getPaymentInfo')->will($this->returnValue($paymentInfo)); - $childBlock = $objectManagerHelper->getObject('Magento\Framework\View\Element\Template'); + $childBlock = $objectManagerHelper->getObject(\Magento\Framework\View\Element\Template::class); $block->expects( $this->atLeastOnce() )->method( diff --git a/app/code/Magento/Payment/Test/Unit/Block/Info/InstructionsTest.php b/app/code/Magento/Payment/Test/Unit/Block/Info/InstructionsTest.php index ab8171e262d5e..40efa750c596e 100644 --- a/app/code/Magento/Payment/Test/Unit/Block/Info/InstructionsTest.php +++ b/app/code/Magento/Payment/Test/Unit/Block/Info/InstructionsTest.php @@ -23,9 +23,9 @@ class InstructionsTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $context = $this->getMock('Magento\Framework\View\Element\Template\Context', [], [], '', false); + $context = $this->getMock(\Magento\Framework\View\Element\Template\Context::class, [], [], '', false); $this->_instructions = new \Magento\Payment\Block\Info\Instructions($context); - $this->_info = $this->getMock('Magento\Payment\Model\Info', [], [], '', false); + $this->_info = $this->getMock(\Magento\Payment\Model\Info::class, [], [], '', false); $this->_instructions->setData('info', $this->_info); } @@ -44,7 +44,7 @@ public function testGetInstructionAdditionalInformation() public function testGetInstruction() { $methodInstance = $this->getMockBuilder( - 'Magento\Payment\Model\MethodInterface' + \Magento\Payment\Model\MethodInterface::class )->getMockForAbstractClass(); $methodInstance->expects($this->once()) ->method('getConfigData') diff --git a/app/code/Magento/Payment/Test/Unit/Block/Info/SubstitutionTest.php b/app/code/Magento/Payment/Test/Unit/Block/Info/SubstitutionTest.php index 97286561fad41..fb8f720b4735d 100644 --- a/app/code/Magento/Payment/Test/Unit/Block/Info/SubstitutionTest.php +++ b/app/code/Magento/Payment/Test/Unit/Block/Info/SubstitutionTest.php @@ -8,6 +8,9 @@ namespace Magento\Payment\Test\Unit\Block\Info; +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ class SubstitutionTest extends \PHPUnit_Framework_TestCase { /** @@ -30,19 +33,19 @@ protected function setUp() $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->layout = $this->getMockBuilder( - 'Magento\Framework\View\LayoutInterface' + \Magento\Framework\View\LayoutInterface::class )->disableOriginalConstructor()->setMethods( [] )->getMock(); $eventManager = $this->getMockBuilder( - 'Magento\Framework\Event\ManagerInterface' + \Magento\Framework\Event\ManagerInterface::class )->disableOriginalConstructor()->setMethods( [] )->getMock(); $scopeConfig = $this->getMockBuilder( - 'Magento\Framework\App\Config\ScopeConfigInterface' + \Magento\Framework\App\Config\ScopeConfigInterface::class )->disableOriginalConstructor()->setMethods( [] )->getMock(); @@ -62,7 +65,7 @@ protected function setUp() ); $context = $this->getMockBuilder( - 'Magento\Framework\View\Element\Template\Context' + \Magento\Framework\View\Element\Template\Context::class )->disableOriginalConstructor()->setMethods( ['getLayout', 'getEventManager', 'getScopeConfig'] )->getMock(); @@ -95,7 +98,7 @@ protected function setUp() ); $this->block = $this->objectManager->getObject( - 'Magento\Payment\Block\Info\Substitution', + \Magento\Payment\Block\Info\Substitution::class, [ 'context' => $context, 'data' => [ @@ -108,7 +111,7 @@ protected function setUp() public function testBeforeToHtml() { $abstractBlock = $this->getMockBuilder( - 'Magento\Framework\View\Element\AbstractBlock' + \Magento\Framework\View\Element\AbstractBlock::class )->disableOriginalConstructor()->setMethods( [] )->getMock(); @@ -120,12 +123,12 @@ public function testBeforeToHtml() $this->layout->expects($this->any())->method('getBlock')->will($this->returnValue($abstractBlock)); $infoMock = $this->getMockBuilder( - 'Magento\Payment\Model\Info' + \Magento\Payment\Model\Info::class )->disableOriginalConstructor()->setMethods( [] )->getMock(); $methodMock = $this->getMockBuilder( - 'Magento\Payment\Model\MethodInterface' + \Magento\Payment\Model\MethodInterface::class )->getMockForAbstractClass(); $infoMock->expects($this->once())->method('getMethodInstance')->will($this->returnValue($methodMock)); $this->block->setInfo($infoMock); @@ -136,7 +139,7 @@ public function testBeforeToHtml() )->method( 'createBlock' )->with( - 'Magento\Framework\View\Element\Template', + \Magento\Framework\View\Element\Template::class, '', ['data' => ['method' => $methodMock, 'template' => 'Magento_Payment::info/substitution.phtml']] )->will( diff --git a/app/code/Magento/Payment/Test/Unit/Block/InfoTest.php b/app/code/Magento/Payment/Test/Unit/Block/InfoTest.php index 913f570410a0a..6799e2156200f 100644 --- a/app/code/Magento/Payment/Test/Unit/Block/InfoTest.php +++ b/app/code/Magento/Payment/Test/Unit/Block/InfoTest.php @@ -33,25 +33,25 @@ protected function setUp() { $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->_storeManager = $this->getMockBuilder( - '\Magento\Store\Model\StoreManager' + \Magento\Store\Model\StoreManager::class )->setMethods( ['getStore'] )->disableOriginalConstructor()->getMock(); $this->_eventManager = $this->getMockBuilder( - '\Magento\Framework\Event\ManagerInterface' + \Magento\Framework\Event\ManagerInterface::class )->setMethods( ['dispatch'] )->disableOriginalConstructor()->getMock(); - $this->_escaper = $this->getMock('\Magento\Framework\Escaper', null, [], '', true); + $this->_escaper = $this->getMock(\Magento\Framework\Escaper::class, null, [], '', true); $context = $helper->getObject( - 'Magento\Framework\View\Element\Template\Context', + \Magento\Framework\View\Element\Template\Context::class, [ 'storeManager' => $this->_storeManager, 'eventManager' => $this->_eventManager, 'escaper' => $this->_escaper ] ); - $this->_object = $helper->getObject('Magento\Payment\Block\Info', ['context' => $context]); + $this->_object = $helper->getObject(\Magento\Payment\Block\Info::class, ['context' => $context]); } /** @@ -73,7 +73,8 @@ public function testGetIsSecureMode($isSecureMode, $methodInstance, $store, $sto $this->_storeManager->expects($this->any())->method('getStore')->will($this->returnValue($storeMock)); } - $paymentInfo = $this->getMockBuilder('\Magento\Payment\Model\Info')->disableOriginalConstructor()->getMock(); + $paymentInfo = $this->getMockBuilder(\Magento\Payment\Model\Info::class) + ->disableOriginalConstructor()->getMock(); $paymentInfo->expects($this->any())->method('getMethodInstance')->will($this->returnValue($methodInstance)); $this->_object->setData('info', $paymentInfo); @@ -101,7 +102,7 @@ public function getIsSecureModeDataProvider() protected function _getMethodInstanceMock($store) { $methodInstance = $this->getMockBuilder( - '\Magento\Payment\Model\Method\AbstractMethod' + \Magento\Payment\Model\Method\AbstractMethod::class )->setMethods( ['getStore'] )->disableOriginalConstructor()->getMock(); @@ -115,7 +116,7 @@ protected function _getMethodInstanceMock($store) */ protected function _getStoreMock($storeCode) { - $storeMock = $this->getMockBuilder('\Magento\Store\Model\Store')->disableOriginalConstructor()->getMock(); + $storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class)->disableOriginalConstructor()->getMock(); $storeMock->expects($this->any())->method('getCode')->will($this->returnValue($storeCode)); return $storeMock; } @@ -131,7 +132,8 @@ public function testGetInfoThrowException() public function testGetSpecificInformation() { - $paymentInfo = $this->getMockBuilder('\Magento\Payment\Model\Info')->disableOriginalConstructor()->getMock(); + $paymentInfo = $this->getMockBuilder(\Magento\Payment\Model\Info::class) + ->disableOriginalConstructor()->getMock(); $this->_object->setData('info', $paymentInfo); $this->_object->getSpecificInformation(); diff --git a/app/code/Magento/Payment/Test/Unit/Block/Transparent/FormTest.php b/app/code/Magento/Payment/Test/Unit/Block/Transparent/FormTest.php index ad33b4cd37407..2366508c2d348 100644 --- a/app/code/Magento/Payment/Test/Unit/Block/Transparent/FormTest.php +++ b/app/code/Magento/Payment/Test/Unit/Block/Transparent/FormTest.php @@ -12,6 +12,9 @@ use Magento\Framework\UrlInterface; use Magento\Payment\Model\Method\TransparentInterface; +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ class FormTest extends \PHPUnit_Framework_TestCase { /** @@ -43,31 +46,31 @@ protected function setUp() { $objectManagerHelper = new ObjectManager($this); - $this->requestMock = $this->getMockBuilder('\Magento\Framework\App\RequestInterface') + $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) ->setMethods(['getParam']) ->getMockForAbstractClass(); - $this->urlBuilderMock = $this->getMockBuilder('\Magento\Framework\UrlInterface') + $this->urlBuilderMock = $this->getMockBuilder(\Magento\Framework\UrlInterface::class) ->setMethods(['getUrl']) ->getMockForAbstractClass(); $context = $objectManagerHelper->getObject( - 'Magento\Framework\View\Element\Template\Context', + \Magento\Framework\View\Element\Template\Context::class, [ 'request' => $this->requestMock, 'urlBuilder' => $this->urlBuilderMock ] ); - $this->methodMock = $this->getMockBuilder('Magento\Payment\Model\Method\TransparentInterface') + $this->methodMock = $this->getMockBuilder(\Magento\Payment\Model\Method\TransparentInterface::class) ->getMock(); - $this->checkoutSessionMock = $this->getMockBuilder('Magento\Checkout\Model\Session') + $this->checkoutSessionMock = $this->getMockBuilder(\Magento\Checkout\Model\Session::class) ->setMethods([]) ->disableOriginalConstructor() ->getMock(); - $paymentConfigMock = $this->getMockBuilder('Magento\Payment\Model\Config') + $paymentConfigMock = $this->getMockBuilder(\Magento\Payment\Model\Config::class) ->setMethods([]) ->disableOriginalConstructor() ->getMock(); @@ -113,7 +116,7 @@ public function testGetMethodConfigData($fieldName, $fieldValue, $expected) */ private function initializeMethodWithConfigMock(array $configMap = []) { - $configInterface = $this->getMockBuilder('Magento\Payment\Model\Method\ConfigInterface') + $configInterface = $this->getMockBuilder(\Magento\Payment\Model\Method\ConfigInterface::class) ->getMock(); $configInterface->expects($this->any()) @@ -234,10 +237,10 @@ public function testGetCardFieldsMap() public function testToHtmlShouldRender() { - $quoteMock = $this->getMockBuilder('Magento\Quote\Model\Quote') + $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) ->disableOriginalConstructor() ->getMock(); - $paymentMock = $this->getMockBuilder('Magento\Quote\Model\Quote\Payment') + $paymentMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Payment::class) ->disableOriginalConstructor() ->getMock(); @@ -265,7 +268,7 @@ public function testToHtmlShouldNotRenderEmptyQuote() public function testToHtmlShouldNotRenderEmptyPayment() { - $quoteMock = $this->getMockBuilder('Magento\Quote\Model\Quote') + $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) ->disableOriginalConstructor() ->getMock(); @@ -288,11 +291,11 @@ public function testGetMethodSuccess() public function testGetMethodNotTransparentInterface() { $this->setExpectedException( - 'Magento\Framework\Exception\LocalizedException', + \Magento\Framework\Exception\LocalizedException::class, __('We cannot retrieve the transparent payment method model object.') ); - $methodMock = $this->getMockBuilder('Magento\Payment\Model\MethodInterface') + $methodMock = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) ->getMockForAbstractClass(); $this->form->setMethod($methodMock); diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Command/CommandPoolTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Command/CommandPoolTest.php index 4327cda62bdb3..6cecb6f7ac43a 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Command/CommandPoolTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Command/CommandPoolTest.php @@ -12,13 +12,13 @@ class CommandPoolTest extends \PHPUnit_Framework_TestCase { public function testGet() { - $commandI = $this->getMockBuilder('Magento\Payment\Gateway\CommandInterface') + $commandI = $this->getMockBuilder(\Magento\Payment\Gateway\CommandInterface::class) ->getMockForAbstractClass(); - $tMapFactory = $this->getMockBuilder('Magento\Framework\ObjectManager\TMapFactory') + $tMapFactory = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMapFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $tMap = $this->getMockBuilder('Magento\Framework\ObjectManager\TMap') + $tMap = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMap::class) ->disableOriginalConstructor() ->getMock(); @@ -26,7 +26,7 @@ public function testGet() ->method('create') ->with( [ - 'array' => ['Magento\Payment\Gateway\CommandInterface'], + 'array' => [\Magento\Payment\Gateway\CommandInterface::class], 'type' => CommandInterface::class ] ) @@ -40,20 +40,20 @@ public function testGet() ->with('command') ->willReturn($commandI); - $pool = new CommandPool($tMapFactory, ['Magento\Payment\Gateway\CommandInterface']); + $pool = new CommandPool($tMapFactory, [\Magento\Payment\Gateway\CommandInterface::class]); static::assertSame($commandI, $pool->get('command')); } public function testGetException() { - $this->setExpectedException('Magento\Framework\Exception\NotFoundException'); + $this->setExpectedException(\Magento\Framework\Exception\NotFoundException::class); - $tMapFactory = $this->getMockBuilder('Magento\Framework\ObjectManager\TMapFactory') + $tMapFactory = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMapFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $tMap = $this->getMockBuilder('Magento\Framework\ObjectManager\TMap') + $tMap = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMap::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Command/GatewayCommandTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Command/GatewayCommandTest.php index 8c42a625f1b55..ae939c881e4be 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Command/GatewayCommandTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Command/GatewayCommandTest.php @@ -13,6 +13,9 @@ use Magento\Payment\Gateway\Validator\ValidatorInterface; use Psr\Log\LoggerInterface; +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ class GatewayCommandTest extends \PHPUnit_Framework_TestCase { /** @var GatewayCommand */ @@ -86,12 +89,12 @@ public function testExecute() ]; $response = ['response_field1' => 'response_value1']; $validationResult = $this->getMockBuilder( - 'Magento\Payment\Gateway\Validator\ResultInterface' + \Magento\Payment\Gateway\Validator\ResultInterface::class ) ->getMockForAbstractClass(); $transferO = $this->getMockBuilder( - 'Magento\Payment\Gateway\Http\TransferInterface' + \Magento\Payment\Gateway\Http\TransferInterface::class ) ->getMockForAbstractClass(); @@ -127,7 +130,7 @@ public function testExecute() public function testExecuteValidationFail() { $this->setExpectedException( - 'Magento\Payment\Gateway\Command\CommandException' + \Magento\Payment\Gateway\Command\CommandException::class ); $commandSubject = ['authorize']; @@ -141,12 +144,12 @@ public function testExecuteValidationFail() __('Failure #2'), ]; $validationResult = $this->getMockBuilder( - 'Magento\Payment\Gateway\Validator\ResultInterface' + \Magento\Payment\Gateway\Validator\ResultInterface::class ) ->getMockForAbstractClass(); $transferO = $this->getMockBuilder( - 'Magento\Payment\Gateway\Http\TransferInterface' + \Magento\Payment\Gateway\Http\TransferInterface::class ) ->getMockForAbstractClass(); diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Config/ConfigTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Config/ConfigTest.php index d7f5f87fa83b4..d11b4ad562655 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Config/ConfigTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Config/ConfigTest.php @@ -24,7 +24,7 @@ class ConfigTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->scopeConfigMock = $this->getMockBuilder('Magento\Framework\App\Config\ScopeConfigInterface') + $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) ->getMockForAbstractClass(); } diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Config/ConfigValueHandlerTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Config/ConfigValueHandlerTest.php index f6f494076ec62..9b7f2d8d22605 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Config/ConfigValueHandlerTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Config/ConfigValueHandlerTest.php @@ -23,7 +23,7 @@ class ConfigValueHandlerTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->configMock = $this->getMockBuilder('Magento\Payment\Gateway\ConfigInterface') + $this->configMock = $this->getMockBuilder(\Magento\Payment\Gateway\ConfigInterface::class) ->getMockForAbstractClass(); $this->model = new ConfigValueHandler($this->configMock); } diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Config/ValueHandlerPoolTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Config/ValueHandlerPoolTest.php index 9491df3b76d2e..ae49880c53d80 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Config/ValueHandlerPoolTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Config/ValueHandlerPoolTest.php @@ -13,7 +13,7 @@ class ValueHandlerPoolTest extends \PHPUnit_Framework_TestCase public function testConstructorException() { $this->setExpectedException('LogicException'); - $tMapFactory = $this->getMockBuilder('Magento\Framework\ObjectManager\TMapFactory') + $tMapFactory = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMapFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -25,17 +25,17 @@ public function testConstructorException() public function testGet() { - $defaultHandler = $this->getMockBuilder('Magento\Payment\Gateway\Config\ValueHandlerInterface') + $defaultHandler = $this->getMockBuilder(\Magento\Payment\Gateway\Config\ValueHandlerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $someValueHandler = $this->getMockBuilder('Magento\Payment\Gateway\Config\ValueHandlerInterface') + $someValueHandler = $this->getMockBuilder(\Magento\Payment\Gateway\Config\ValueHandlerInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $tMapFactory = $this->getMockBuilder('Magento\Framework\ObjectManager\TMapFactory') + $tMapFactory = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMapFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $tMap = $this->getMockBuilder('Magento\Framework\ObjectManager\TMap') + $tMap = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMap::class) ->disableOriginalConstructor() ->getMock(); @@ -44,8 +44,9 @@ public function testGet() ->with( [ 'array' => [ - ValueHandlerPool::DEFAULT_HANDLER => 'Magento\Payment\Gateway\Config\ValueHandlerInterface', - 'some_value' => 'Magento\Payment\Gateway\Config\ValueHandlerInterface' + ValueHandlerPool::DEFAULT_HANDLER => + \Magento\Payment\Gateway\Config\ValueHandlerInterface::class, + 'some_value' => \Magento\Payment\Gateway\Config\ValueHandlerInterface::class ], 'type' => ValueHandlerInterface::class ] @@ -71,8 +72,8 @@ public function testGet() $pool = new ValueHandlerPool( $tMapFactory, [ - ValueHandlerPool::DEFAULT_HANDLER => 'Magento\Payment\Gateway\Config\ValueHandlerInterface', - 'some_value' => 'Magento\Payment\Gateway\Config\ValueHandlerInterface' + ValueHandlerPool::DEFAULT_HANDLER => \Magento\Payment\Gateway\Config\ValueHandlerInterface::class, + 'some_value' => \Magento\Payment\Gateway\Config\ValueHandlerInterface::class ] ); static::assertSame($someValueHandler, $pool->get('some_value')); diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Data/Order/AddressAdapterTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Data/Order/AddressAdapterTest.php index fd8538b0994e8..7dd939fed7b46 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Data/Order/AddressAdapterTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Data/Order/AddressAdapterTest.php @@ -23,7 +23,7 @@ class AddressAdapterTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->orderAddressMock = $this->getMockBuilder('Magento\Sales\Api\Data\OrderAddressInterface') + $this->orderAddressMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderAddressInterface::class) ->getMockForAbstractClass(); $this->model = new AddressAdapter($this->orderAddressMock); diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Data/Order/OrderAdapterTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Data/Order/OrderAdapterTest.php index ee83f7a2b0553..f128de111c2b1 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Data/Order/OrderAdapterTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Data/Order/OrderAdapterTest.php @@ -29,12 +29,12 @@ class OrderAdapterTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->orderMock = $this->getMockBuilder('Magento\Sales\Model\Order') + $this->orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) ->disableOriginalConstructor() ->getMock(); $this->addressAdapterFactoryMock = - $this->getMockBuilder('Magento\Payment\Gateway\Data\Order\AddressAdapterFactory') + $this->getMockBuilder(\Magento\Payment\Gateway\Data\Order\AddressAdapterFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); @@ -73,10 +73,10 @@ public function testGetBillingAddressIsNull() public function testGetBillingAddress() { /** @var AddressAdapterInterface $addressAdapterMock */ - $addressAdapterMock = $this->getMockBuilder('Magento\Payment\Gateway\Data\AddressAdapterInterface') + $addressAdapterMock = $this->getMockBuilder(\Magento\Payment\Gateway\Data\AddressAdapterInterface::class) ->getMockForAbstractClass(); /** @var \Magento\Sales\Api\Data\OrderAddressInterface $orderAddressMock */ - $orderAddressMock = $this->getMockBuilder('Magento\Sales\Api\Data\OrderAddressInterface') + $orderAddressMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderAddressInterface::class) ->getMockForAbstractClass(); $this->addressAdapterFactoryMock->expects($this->once()) ->method('create') @@ -97,10 +97,10 @@ public function testGetShippingAddressIsNull() public function testGetShippingAddress() { /** @var AddressAdapterInterface $addressAdapterMock */ - $addressAdapterMock = $this->getMockBuilder('Magento\Payment\Gateway\Data\AddressAdapterInterface') + $addressAdapterMock = $this->getMockBuilder(\Magento\Payment\Gateway\Data\AddressAdapterInterface::class) ->getMockForAbstractClass(); /** @var \Magento\Sales\Api\Data\OrderAddressInterface $orderAddressMock */ - $orderAddressMock = $this->getMockBuilder('Magento\Sales\Api\Data\OrderAddressInterface') + $orderAddressMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderAddressInterface::class) ->getMockForAbstractClass(); $this->addressAdapterFactoryMock->expects($this->once()) ->method('create') diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Data/PaymentDataObjectFactoryTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Data/PaymentDataObjectFactoryTest.php index 1c192251da5d3..cf9e9f165007a 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Data/PaymentDataObjectFactoryTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Data/PaymentDataObjectFactoryTest.php @@ -41,23 +41,23 @@ class PaymentDataObjectFactoryTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->objectManagerMock = $this->getMockBuilder('Magento\Framework\ObjectManagerInterface') + $this->objectManagerMock = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) ->getMockForAbstractClass(); $this->orderAdapterFactoryMock = - $this->getMockBuilder('Magento\Payment\Gateway\Data\Order\OrderAdapterFactory') + $this->getMockBuilder(\Magento\Payment\Gateway\Data\Order\OrderAdapterFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->quoteAdapterFactoryMock = - $this->getMockBuilder('Magento\Payment\Gateway\Data\Quote\QuoteAdapterFactory') + $this->getMockBuilder(\Magento\Payment\Gateway\Data\Quote\QuoteAdapterFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); $this->paymentDataObjectMock = - $this->getMock('Magento\Payment\Gateway\Data\PaymentDataObjectInterface'); + $this->getMock(\Magento\Payment\Gateway\Data\PaymentDataObjectInterface::class); $this->model = new PaymentDataObjectFactory( $this->objectManagerMock, @@ -69,17 +69,17 @@ protected function setUp() public function testCreatePaymentDataObjectFromOrder() { /** @var Order $orderMock */ - $orderMock = $this->getMockBuilder('Magento\Sales\Model\Order') + $orderMock = $this->getMockBuilder(\Magento\Sales\Model\Order::class) ->disableOriginalConstructor() ->getMock(); /** @var OrderAdapter $orderAdapterMock */ - $orderAdapterMock = $this->getMockBuilder('Magento\Payment\Gateway\Data\Order\OrderAdapter') + $orderAdapterMock = $this->getMockBuilder(\Magento\Payment\Gateway\Data\Order\OrderAdapter::class) ->disableOriginalConstructor() ->getMock(); /** @var \Magento\Sales\Model\Order\Payment $paymentInfoMock */ - $paymentInfoMock = $this->getMockBuilder('Magento\Sales\Model\Order\Payment') + $paymentInfoMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Payment::class) ->disableOriginalConstructor() ->getMock(); @@ -95,7 +95,7 @@ public function testCreatePaymentDataObjectFromOrder() $this->objectManagerMock->expects($this->once()) ->method('create') ->with( - 'Magento\Payment\Gateway\Data\PaymentDataObject', + \Magento\Payment\Gateway\Data\PaymentDataObject::class, [ 'order' => $orderAdapterMock, 'payment' => $paymentInfoMock @@ -108,17 +108,17 @@ public function testCreatePaymentDataObjectFromOrder() public function testCreatePaymentDataObjectFromQuote() { /** @var \Magento\Quote\Model\Quote $quoteMock */ - $quoteMock = $this->getMockBuilder('Magento\Quote\Model\Quote') + $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) ->disableOriginalConstructor() ->getMock(); /** @var OrderAdapter $orderAdapterMock */ - $quoteAdapterMock = $this->getMockBuilder('Magento\Payment\Gateway\Data\Quote\QuoteAdapter') + $quoteAdapterMock = $this->getMockBuilder(\Magento\Payment\Gateway\Data\Quote\QuoteAdapter::class) ->disableOriginalConstructor() ->getMock(); /** @var \Magento\Quote\Model\Quote\Payment $paymentInfoMock */ - $paymentInfoMock = $this->getMockBuilder('Magento\Quote\Model\Quote\Payment') + $paymentInfoMock = $this->getMockBuilder(\Magento\Quote\Model\Quote\Payment::class) ->disableOriginalConstructor() ->getMock(); @@ -134,7 +134,7 @@ public function testCreatePaymentDataObjectFromQuote() $this->objectManagerMock->expects($this->once()) ->method('create') ->with( - 'Magento\Payment\Gateway\Data\PaymentDataObject', + \Magento\Payment\Gateway\Data\PaymentDataObject::class, [ 'order' => $quoteAdapterMock, 'payment' => $paymentInfoMock diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Data/PaymentDataObjectTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Data/PaymentDataObjectTest.php index 1ff0bbe6b5d64..d28ad246367bc 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Data/PaymentDataObjectTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Data/PaymentDataObjectTest.php @@ -29,10 +29,10 @@ class PaymentDataObjectTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->orderMock = $this->getMockBuilder('Magento\Payment\Gateway\Data\OrderAdapterInterface') + $this->orderMock = $this->getMockBuilder(\Magento\Payment\Gateway\Data\OrderAdapterInterface::class) ->getMockForAbstractClass(); - $this->paymentMock = $this->getMockBuilder('Magento\Payment\Model\InfoInterface') + $this->paymentMock = $this->getMockBuilder(\Magento\Payment\Model\InfoInterface::class) ->getMockForAbstractClass(); $this->model = new PaymentDataObject($this->orderMock, $this->paymentMock); diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Data/Quote/AddressAdapterTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Data/Quote/AddressAdapterTest.php index 7af4957c0af11..4583732a82910 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Data/Quote/AddressAdapterTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Data/Quote/AddressAdapterTest.php @@ -23,7 +23,7 @@ class AddressAdapterTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->quoteAddressMock = $this->getMockBuilder('Magento\Quote\Api\Data\AddressInterface') + $this->quoteAddressMock = $this->getMockBuilder(\Magento\Quote\Api\Data\AddressInterface::class) ->getMockForAbstractClass(); $this->model = new AddressAdapter($this->quoteAddressMock); diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Data/Quote/QuoteAdapterTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Data/Quote/QuoteAdapterTest.php index c5d111662a036..4864e3c25ad7c 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Data/Quote/QuoteAdapterTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Data/Quote/QuoteAdapterTest.php @@ -29,10 +29,10 @@ class QuoteAdapterTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->quoteMock = $this->getMock('Magento\Quote\Model\Quote', [], [], '', false); + $this->quoteMock = $this->getMock(\Magento\Quote\Model\Quote::class, [], [], '', false); $this->addressAdapterFactoryMock = - $this->getMockBuilder('Magento\Payment\Gateway\Data\Quote\AddressAdapterFactory') + $this->getMockBuilder(\Magento\Payment\Gateway\Data\Quote\AddressAdapterFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); @@ -44,7 +44,9 @@ public function testGetCurrencyCode() { $expected = 'USD'; /** @var \Magento\Quote\Api\Data\CurrencyInterface $currencyrMock */ - $currencyMock = $this->getMockBuilder('Magento\Quote\Api\Data\CurrencyInterface')->getMockForAbstractClass(); + $currencyMock = $this->getMockBuilder( + \Magento\Quote\Api\Data\CurrencyInterface::class + )->getMockForAbstractClass(); $currencyMock->expects($this->once())->method('getBaseCurrencyCode')->willReturn($expected); $this->quoteMock->expects($this->once())->method('getCurrency')->willReturn($currencyMock); $this->assertEquals($expected, $this->model->getCurrencyCode()); @@ -61,7 +63,9 @@ public function testGetCustomerId() { $expected = 1; /** @var \Magento\Customer\Api\Data\CustomerInterface $customerMock */ - $customerMock = $this->getMockBuilder('Magento\Customer\Api\Data\CustomerInterface')->getMockForAbstractClass(); + $customerMock = $this->getMockBuilder( + \Magento\Customer\Api\Data\CustomerInterface::class + )->getMockForAbstractClass(); $customerMock->expects($this->once())->method('getId')->willReturn($expected); $this->quoteMock->expects($this->once())->method('getCustomer')->willReturn($customerMock); $this->assertEquals($expected, $this->model->getCustomerId()); @@ -77,10 +81,10 @@ public function testGetBillingAddressIsNull() public function testGetBillingAddress() { /** @var AddressAdapterInterface $addressAdapterMock */ - $addressAdapterMock = $this->getMockBuilder('Magento\Payment\Gateway\Data\AddressAdapterInterface') + $addressAdapterMock = $this->getMockBuilder(\Magento\Payment\Gateway\Data\AddressAdapterInterface::class) ->getMockForAbstractClass(); /** @var \Magento\Quote\Api\Data\AddressInterface $quoteAddressMock */ - $quoteAddressMock = $this->getMockBuilder('Magento\Quote\Api\Data\AddressInterface') + $quoteAddressMock = $this->getMockBuilder(\Magento\Quote\Api\Data\AddressInterface::class) ->getMockForAbstractClass(); $this->addressAdapterFactoryMock->expects($this->once()) ->method('create') @@ -101,10 +105,10 @@ public function testGetShippingAddressIsNull() public function testGetShippingAddress() { /** @var AddressAdapterInterface $addressAdapterMock */ - $addressAdapterMock = $this->getMockBuilder('Magento\Payment\Gateway\Data\AddressAdapterInterface') + $addressAdapterMock = $this->getMockBuilder(\Magento\Payment\Gateway\Data\AddressAdapterInterface::class) ->getMockForAbstractClass(); /** @var \Magento\Quote\Api\Data\AddressInterface $quoteAddressMock */ - $quoteAddressMock = $this->getMockBuilder('Magento\Quote\Api\Data\AddressInterface') + $quoteAddressMock = $this->getMockBuilder(\Magento\Quote\Api\Data\AddressInterface::class) ->getMockForAbstractClass(); $this->addressAdapterFactoryMock->expects($this->once()) ->method('create') diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Http/Client/SoapTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Http/Client/SoapTest.php index b8282228d7334..2a3ae9c306373 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Http/Client/SoapTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Http/Client/SoapTest.php @@ -37,17 +37,18 @@ class SoapTest extends \PHPUnit_Framework_TestCase protected function setUp() { $this->logger = $this->getMockBuilder( - 'Magento\Payment\Model\Method\Logger' + \Magento\Payment\Model\Method\Logger::class ) ->disableOriginalConstructor() ->getMock(); $this->clientFactory = $this->getMockBuilder( - 'Magento\Framework\Webapi\Soap\ClientFactory' + \Magento\Framework\Webapi\Soap\ClientFactory::class )->getMock(); $this->converter = $this->getMockBuilder( - 'Magento\Payment\Gateway\Http\ConverterInterface' + \Magento\Payment\Gateway\Http\ConverterInterface::class )->getMockForAbstractClass(); - $this->client = $this->getMockBuilder('\SoapClient') + $this->client = $this->getMockBuilder(\SoapClient::class) + ->setMethods(['__setSoapHeaders', '__soapCall', '__getLastRequest']) ->disableOriginalConstructor() ->getMock(); @@ -137,7 +138,7 @@ public function testPlaceRequestSoapException() private function getTransferObject() { $transferObject = $this->getMockBuilder( - 'Magento\Payment\Gateway\Http\TransferInterface' + \Magento\Payment\Gateway\Http\TransferInterface::class )->getMock(); $transferObject->expects(static::any()) diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Http/Client/ZendTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Http/Client/ZendTest.php index d94b6f1d31d8e..17c2e9401c3d3 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Http/Client/ZendTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Http/Client/ZendTest.php @@ -46,23 +46,23 @@ class ZendTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->converterMock = $this->getMockBuilder('Magento\Payment\Gateway\Http\ConverterInterface') + $this->converterMock = $this->getMockBuilder(\Magento\Payment\Gateway\Http\ConverterInterface::class) ->getMockForAbstractClass(); - $this->zendClientFactoryMock = $this->getMockBuilder('Magento\Framework\HTTP\ZendClientFactory') + $this->zendClientFactoryMock = $this->getMockBuilder(\Magento\Framework\HTTP\ZendClientFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->clientMock = $this->getMockBuilder('Magento\Framework\HTTP\ZendClient') + $this->clientMock = $this->getMockBuilder(\Magento\Framework\HTTP\ZendClient::class) ->disableOriginalConstructor() ->getMock(); - $this->loggerMock = $this->getMockBuilder('Magento\Payment\Model\Method\Logger') + $this->loggerMock = $this->getMockBuilder(\Magento\Payment\Model\Method\Logger::class) ->disableOriginalConstructor() ->getMock(); - $this->transferObjectMock = $this->getMockBuilder('Magento\Payment\Gateway\Http\TransferInterface') + $this->transferObjectMock = $this->getMockBuilder(\Magento\Payment\Gateway\Http\TransferInterface::class) ->getMockForAbstractClass(); $this->model = new Zend( @@ -77,7 +77,9 @@ public function testPlaceRequest() $this->setClientTransferObjects(); $responseBody = 'Response body content'; - $zendHttpResponseMock = $this->getMockBuilder('Zend_Http_Response')->disableOriginalConstructor()->getMock(); + $zendHttpResponseMock = $this->getMockBuilder( + \Zend_Http_Response::class + )->disableOriginalConstructor()->getMock(); $zendHttpResponseMock->expects($this->once())->method('getBody')->willReturn($responseBody); $this->clientMock->expects($this->once())->method('request')->willReturn($zendHttpResponseMock); @@ -121,7 +123,9 @@ public function testPlaceRequestConvertResponseFail() $this->setClientTransferObjects(); $responseBody = 'Response body content'; - $zendHttpResponseMock = $this->getMockBuilder('Zend_Http_Response')->disableOriginalConstructor()->getMock(); + $zendHttpResponseMock = $this->getMockBuilder( + \Zend_Http_Response::class + )->disableOriginalConstructor()->getMock(); $zendHttpResponseMock->expects($this->once())->method('getBody')->willReturn($responseBody); $this->clientMock->expects($this->once())->method('request')->willReturn($zendHttpResponseMock); diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Request/BuilderCompositeTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Request/BuilderCompositeTest.php index fdc062210f81e..87049bddd0494 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Request/BuilderCompositeTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Request/BuilderCompositeTest.php @@ -12,11 +12,11 @@ class BuilderCompositeTest extends \PHPUnit_Framework_TestCase { public function testBuildEmpty() { - $tMapFactory = $this->getMockBuilder('Magento\Framework\ObjectManager\TMapFactory') + $tMapFactory = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMapFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $tMap = $this->getMockBuilder('Magento\Framework\ObjectManager\TMap') + $tMap = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMap::class) ->disableOriginalConstructor() ->getMock(); @@ -44,18 +44,18 @@ public function testBuildEmpty() */ public function testBuild(array $expected) { - $tMapFactory = $this->getMockBuilder('Magento\Framework\ObjectManager\TMapFactory') + $tMapFactory = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMapFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $tMap = $this->getMockBuilder('Magento\Framework\ObjectManager\TMap') + $tMap = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMap::class) ->disableOriginalConstructor() ->getMock(); - $customerBuilder = $this->getMockBuilder('Magento\Payment\Gateway\Request\BuilderInterface') + $customerBuilder = $this->getMockBuilder(\Magento\Payment\Gateway\Request\BuilderInterface::class) ->getMockForAbstractClass(); - $productBuilder = $this->getMockBuilder('Magento\Payment\Gateway\Request\BuilderInterface') + $productBuilder = $this->getMockBuilder(\Magento\Payment\Gateway\Request\BuilderInterface::class) ->getMockForAbstractClass(); - $magentoBuilder = $this->getMockBuilder('Magento\Payment\Gateway\Request\BuilderInterface') + $magentoBuilder = $this->getMockBuilder(\Magento\Payment\Gateway\Request\BuilderInterface::class) ->getMockForAbstractClass(); $customerBuilder->expects(static::once()) @@ -91,9 +91,9 @@ public function testBuild(array $expected) ->with( [ 'array' => [ - 'customer' => 'Magento\Payment\Gateway\Request\BuilderInterface', - 'product' => 'Magento\Payment\Gateway\Request\BuilderInterface', - 'magento' => 'Magento\Payment\Gateway\Request\BuilderInterface' + 'customer' => \Magento\Payment\Gateway\Request\BuilderInterface::class, + 'product' => \Magento\Payment\Gateway\Request\BuilderInterface::class, + 'magento' => \Magento\Payment\Gateway\Request\BuilderInterface::class ], 'type' => BuilderInterface::class ] @@ -106,9 +106,9 @@ public function testBuild(array $expected) $builder = new BuilderComposite( $tMapFactory, [ - 'customer' => 'Magento\Payment\Gateway\Request\BuilderInterface', - 'product' => 'Magento\Payment\Gateway\Request\BuilderInterface', - 'magento' => 'Magento\Payment\Gateway\Request\BuilderInterface' + 'customer' => \Magento\Payment\Gateway\Request\BuilderInterface::class, + 'product' => \Magento\Payment\Gateway\Request\BuilderInterface::class, + 'magento' => \Magento\Payment\Gateway\Request\BuilderInterface::class ] ); diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Response/HandlerChainTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Response/HandlerChainTest.php index 2e556fb4f216f..b52e96af8bbae 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Response/HandlerChainTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Response/HandlerChainTest.php @@ -12,15 +12,15 @@ class HandlerChainTest extends \PHPUnit_Framework_TestCase { public function testHandle() { - $handler1 = $this->getMockBuilder('Magento\Payment\Gateway\Response\HandlerInterface') + $handler1 = $this->getMockBuilder(\Magento\Payment\Gateway\Response\HandlerInterface::class) ->getMockForAbstractClass(); - $handler2 = $this->getMockBuilder('Magento\Payment\Gateway\Response\HandlerInterface') + $handler2 = $this->getMockBuilder(\Magento\Payment\Gateway\Response\HandlerInterface::class) ->getMockForAbstractClass(); - $tMapFactory = $this->getMockBuilder('Magento\Framework\ObjectManager\TMapFactory') + $tMapFactory = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMapFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $tMap = $this->getMockBuilder('Magento\Framework\ObjectManager\TMap') + $tMap = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMap::class) ->disableOriginalConstructor() ->getMock(); @@ -29,8 +29,8 @@ public function testHandle() ->with( [ 'array' => [ - 'handler1' => 'Magento\Payment\Gateway\Response\HandlerInterface', - 'handler2' => 'Magento\Payment\Gateway\Response\HandlerInterface' + 'handler1' => \Magento\Payment\Gateway\Response\HandlerInterface::class, + 'handler2' => \Magento\Payment\Gateway\Response\HandlerInterface::class ], 'type' => HandlerInterface::class ] @@ -52,8 +52,8 @@ public function testHandle() $chain = new HandlerChain( $tMapFactory, [ - 'handler1' => 'Magento\Payment\Gateway\Response\HandlerInterface', - 'handler2' => 'Magento\Payment\Gateway\Response\HandlerInterface' + 'handler1' => \Magento\Payment\Gateway\Response\HandlerInterface::class, + 'handler2' => \Magento\Payment\Gateway\Response\HandlerInterface::class ] ); $chain->handle($handlingSubject, $response); diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Validator/CountryValidatorTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Validator/CountryValidatorTest.php index 8a429dbc88798..d36fda3fd6be5 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Validator/CountryValidatorTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Validator/CountryValidatorTest.php @@ -27,13 +27,14 @@ class CountryValidatorTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->configMock = $this->getMockBuilder('Magento\Payment\Gateway\ConfigInterface') + $this->configMock = $this->getMockBuilder(\Magento\Payment\Gateway\ConfigInterface::class) ->getMockForAbstractClass(); - $this->resultFactoryMock = $this->getMockBuilder('Magento\Payment\Gateway\Validator\ResultInterfaceFactory') - ->setMethods(['create']) + $this->resultFactoryMock = $this->getMockBuilder( + \Magento\Payment\Gateway\Validator\ResultInterfaceFactory::class + )->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->resultMock = $this->getMockBuilder('Magento\Payment\Gateway\Validator\Result') + $this->resultMock = $this->getMockBuilder(\Magento\Payment\Gateway\Validator\Result::class) ->disableOriginalConstructor() ->getMock(); @@ -43,7 +44,6 @@ protected function setUp() ); } - /** * @dataProvider validateAllowspecificTrueDataProvider */ diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ResultTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ResultTest.php index 50310adb42e8a..49e7ace9a0a5f 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ResultTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ResultTest.php @@ -31,7 +31,7 @@ public function testResult($isValid, $failsDescription, $expectedIsValid, $expec public function resultDataProvider() { - $phraseMock = $this->getMockBuilder('Magento\Framework\Phrase')->disableOriginalConstructor()->getMock(); + $phraseMock = $this->getMockBuilder(\Magento\Framework\Phrase::class)->disableOriginalConstructor()->getMock(); return [ [true, [$phraseMock, $phraseMock], true, [$phraseMock, $phraseMock]], ['', [], false, []], diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ValidatorCompositeTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ValidatorCompositeTest.php index 027117eca5471..baf11d67773bc 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ValidatorCompositeTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ValidatorCompositeTest.php @@ -13,15 +13,15 @@ class ValidatorCompositeTest extends \PHPUnit_Framework_TestCase public function testValidate() { $validationSubject = []; - $validator1 = $this->getMockBuilder('Magento\Payment\Gateway\Validator\ValidatorInterface') + $validator1 = $this->getMockBuilder(\Magento\Payment\Gateway\Validator\ValidatorInterface::class) ->getMockForAbstractClass(); - $validator2 = $this->getMockBuilder('Magento\Payment\Gateway\Validator\ValidatorInterface') + $validator2 = $this->getMockBuilder(\Magento\Payment\Gateway\Validator\ValidatorInterface::class) ->getMockForAbstractClass(); - $tMapFactory = $this->getMockBuilder('Magento\Framework\ObjectManager\TMapFactory') + $tMapFactory = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMapFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $tMap = $this->getMockBuilder('Magento\Framework\ObjectManager\TMap') + $tMap = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMap::class) ->disableOriginalConstructor() ->getMock(); @@ -30,8 +30,8 @@ public function testValidate() ->with( [ 'array' => [ - 'validator1' => 'Magento\Payment\Gateway\Validator\ValidatorInterface', - 'validator2' => 'Magento\Payment\Gateway\Validator\ValidatorInterface' + 'validator1' => \Magento\Payment\Gateway\Validator\ValidatorInterface::class, + 'validator2' => \Magento\Payment\Gateway\Validator\ValidatorInterface::class ], 'type' => ValidatorInterface::class ] @@ -41,12 +41,12 @@ public function testValidate() ->method('getIterator') ->willReturn(new \ArrayIterator([$validator1, $validator2])); - $resultSuccess = $this->getMockBuilder('Magento\Payment\Gateway\Validator\ResultInterface') + $resultSuccess = $this->getMockBuilder(\Magento\Payment\Gateway\Validator\ResultInterface::class) ->getMockForAbstractClass(); $resultSuccess->expects(static::once()) ->method('isValid') ->willReturn(true); - $resultFail = $this->getMockBuilder('Magento\Payment\Gateway\Validator\ResultInterface') + $resultFail = $this->getMockBuilder(\Magento\Payment\Gateway\Validator\ResultInterface::class) ->getMockForAbstractClass(); $resultFail->expects(static::once()) ->method('isValid') @@ -64,9 +64,9 @@ public function testValidate() ->with($validationSubject) ->willReturn($resultFail); - $compositeResult = $this->getMockBuilder('Magento\Payment\Gateway\Validator\ResultInterface') + $compositeResult = $this->getMockBuilder(\Magento\Payment\Gateway\Validator\ResultInterface::class) ->getMockForAbstractClass(); - $resultFactory = $this->getMockBuilder('Magento\Payment\Gateway\Validator\ResultInterfaceFactory') + $resultFactory = $this->getMockBuilder(\Magento\Payment\Gateway\Validator\ResultInterfaceFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -80,13 +80,12 @@ public function testValidate() ) ->willReturn($compositeResult); - $validatorComposite = new ValidatorComposite( $resultFactory, $tMapFactory, [ - 'validator1' => 'Magento\Payment\Gateway\Validator\ValidatorInterface', - 'validator2' => 'Magento\Payment\Gateway\Validator\ValidatorInterface' + 'validator1' => \Magento\Payment\Gateway\Validator\ValidatorInterface::class, + 'validator2' => \Magento\Payment\Gateway\Validator\ValidatorInterface::class ] ); static::assertSame($compositeResult, $validatorComposite->validate($validationSubject)); diff --git a/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ValidatorPoolTest.php b/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ValidatorPoolTest.php index a568d0de60720..8d408abf147c4 100644 --- a/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ValidatorPoolTest.php +++ b/app/code/Magento/Payment/Test/Unit/Gateway/Validator/ValidatorPoolTest.php @@ -12,12 +12,12 @@ class ValidatorPoolTest extends \PHPUnit_Framework_TestCase { public function testGet() { - $commandI = $this->getMockBuilder('Magento\Payment\Gateway\Validator\ValidatorInterface') + $commandI = $this->getMockBuilder(\Magento\Payment\Gateway\Validator\ValidatorInterface::class) ->getMockForAbstractClass(); - $tMap = $this->getMockBuilder('Magento\Framework\ObjectManager\TMap') + $tMap = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMap::class) ->disableOriginalConstructor() ->getMock(); - $tMapFactory = $this->getMockBuilder('Magento\Framework\ObjectManager\TMapFactory') + $tMapFactory = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMapFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -26,7 +26,7 @@ public function testGet() ->method('create') ->with( [ - 'array' => ['validator' => 'Magento\Payment\Gateway\Validator\ValidatorInterface'], + 'array' => ['validator' => \Magento\Payment\Gateway\Validator\ValidatorInterface::class], 'type' => ValidatorInterface::class ] ) @@ -42,7 +42,7 @@ public function testGet() $pool = new ValidatorPool( $tMapFactory, - ['validator' => 'Magento\Payment\Gateway\Validator\ValidatorInterface'] + ['validator' => \Magento\Payment\Gateway\Validator\ValidatorInterface::class] ); static::assertSame($commandI, $pool->get('validator')); @@ -50,13 +50,13 @@ public function testGet() public function testGetException() { - $this->setExpectedException('Magento\Framework\Exception\NotFoundException'); + $this->setExpectedException(\Magento\Framework\Exception\NotFoundException::class); - $tMapFactory = $this->getMockBuilder('Magento\Framework\ObjectManager\TMapFactory') + $tMapFactory = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMapFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $tMap = $this->getMockBuilder('Magento\Framework\ObjectManager\TMap') + $tMap = $this->getMockBuilder(\Magento\Framework\ObjectManager\TMap::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Payment/Test/Unit/Helper/DataTest.php b/app/code/Magento/Payment/Test/Unit/Helper/DataTest.php index 756810416c2ae..81329a9bb98cc 100644 --- a/app/code/Magento/Payment/Test/Unit/Helper/DataTest.php +++ b/app/code/Magento/Payment/Test/Unit/Helper/DataTest.php @@ -37,12 +37,12 @@ class DataTest extends \PHPUnit_Framework_TestCase protected function setUp() { $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $className = 'Magento\Payment\Helper\Data'; + $className = \Magento\Payment\Helper\Data::class; $arguments = $objectManagerHelper->getConstructArguments($className); /** @var \Magento\Framework\App\Helper\Context $context */ $context = $arguments['context']; $this->scopeConfig = $context->getScopeConfig(); - $this->layoutMock = $this->getMock('Magento\Framework\View\LayoutInterface', [], [], '', false); + $this->layoutMock = $this->getMock(\Magento\Framework\View\LayoutInterface::class, [], [], '', false); $layoutFactoryMock = $arguments['layoutFactory']; $layoutFactoryMock->expects($this->once())->method('create')->willReturn($this->layoutMock); @@ -53,7 +53,6 @@ protected function setUp() $this->helper = $objectManagerHelper->getObject($className, $arguments); } - public function testGetMethodInstance() { list($code, $class, $methodInstance) = ['method_code', 'method_class', 'method_instance']; @@ -120,19 +119,19 @@ public function testSortMethods(array $methodA, array $methodB) $this->scopeConfig->expects(new MethodInvokedAtIndex(0)) ->method('getValue') ->with(sprintf('%s/%s/model', Data::XML_PATH_PAYMENT_METHODS, $methodA['code'])) - ->will($this->returnValue('Magento\Payment\Model\Method\AbstractMethod')); + ->will($this->returnValue(\Magento\Payment\Model\Method\AbstractMethod::class)); $this->scopeConfig->expects(new MethodInvokedAtIndex(1)) ->method('getValue') ->with( sprintf('%s/%s/model', Data::XML_PATH_PAYMENT_METHODS, $methodB['code']) ) - ->will($this->returnValue('Magento\Payment\Model\Method\AbstractMethod')); + ->will($this->returnValue(\Magento\Payment\Model\Method\AbstractMethod::class)); $this->scopeConfig->expects(new MethodInvokedAtIndex(2)) ->method('getValue') ->with(sprintf('%s/%s/model', Data::XML_PATH_PAYMENT_METHODS, 'empty')) ->will($this->returnValue(null)); - $methodInstanceMockA = $this->getMockBuilder('Magento\Payment\Model\MethodInterface') + $methodInstanceMockA = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) ->getMockForAbstractClass(); $methodInstanceMockA->expects($this->any()) ->method('isAvailable') @@ -142,7 +141,7 @@ public function testSortMethods(array $methodA, array $methodB) ->with('sort_order', null) ->will($this->returnValue($methodA['data']['sort_order'])); - $methodInstanceMockB = $this->getMockBuilder('Magento\Payment\Model\MethodInterface') + $methodInstanceMockB = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) ->getMockForAbstractClass(); $methodInstanceMockB->expects($this->any()) ->method('isAvailable') @@ -171,13 +170,13 @@ public function testGetMethodFormBlock() { list($blockType, $methodCode) = ['method_block_type', 'method_code']; - $methodMock = $this->getMockBuilder('Magento\Payment\Model\MethodInterface') + $methodMock = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) ->getMockForAbstractClass(); - $layoutMock = $this->getMockBuilder('Magento\Framework\View\LayoutInterface') + $layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $blockMock = $this->getMockBuilder('Magento\Framework\View\Element\BlockInterface') + $blockMock = $this->getMockBuilder(\Magento\Framework\View\Element\BlockInterface::class) ->disableOriginalConstructor() ->setMethods(['setMethod', 'toHtml']) ->getMock(); @@ -196,13 +195,13 @@ public function testGetInfoBlock() { $blockType = 'method_block_type'; - $methodMock = $this->getMockBuilder('Magento\Payment\Model\MethodInterface') + $methodMock = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) ->getMockForAbstractClass(); - $infoMock = $this->getMockBuilder('Magento\Payment\Model\Info') + $infoMock = $this->getMockBuilder(\Magento\Payment\Model\Info::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $blockMock = $this->getMockBuilder('Magento\Framework\View\Element\BlockInterface') + $blockMock = $this->getMockBuilder(\Magento\Framework\View\Element\BlockInterface::class) ->disableOriginalConstructor() ->setMethods(['setInfo', 'toHtml']) ->getMock(); @@ -221,13 +220,13 @@ public function testGetInfoBlockHtml() { list($storeId, $blockHtml, $secureMode, $blockType) = [1, 'HTML MARKUP', true, 'method_block_type']; - $methodMock = $this->getMockBuilder('Magento\Payment\Model\MethodInterface') + $methodMock = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) ->getMockForAbstractClass(); - $infoMock = $this->getMockBuilder('Magento\Payment\Model\Info') + $infoMock = $this->getMockBuilder(\Magento\Payment\Model\Info::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); - $paymentBlockMock = $this->getMockBuilder('Magento\Framework\View\Element\BlockInterface') + $paymentBlockMock = $this->getMockBuilder(\Magento\Framework\View\Element\BlockInterface::class) ->disableOriginalConstructor() ->setMethods(['setArea', 'setIsSecureMode', 'getMethod', 'setStore', 'toHtml', 'setInfo']) ->getMock(); diff --git a/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/FactoryTest.php b/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/FactoryTest.php index d7bd9dfdc1483..c0b49635fea9e 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/FactoryTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/FactoryTest.php @@ -15,7 +15,7 @@ class FactoryTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->_objectManagerMock = $this->getMock('Magento\Framework\ObjectManagerInterface'); + $this->_objectManagerMock = $this->getMock(\Magento\Framework\ObjectManagerInterface::class); $this->_model = new \Magento\Payment\Model\Cart\SalesModel\Factory($this->_objectManagerMock); } @@ -43,8 +43,8 @@ public function testCreate($salesModelClass, $expectedType) public function createDataProvider() { return [ - ['Magento\Quote\Model\Quote', 'Magento\Payment\Model\Cart\SalesModel\Quote'], - ['Magento\Sales\Model\Order', 'Magento\Payment\Model\Cart\SalesModel\Order'] + [\Magento\Quote\Model\Quote::class, \Magento\Payment\Model\Cart\SalesModel\Quote::class], + [\Magento\Sales\Model\Order::class, \Magento\Payment\Model\Cart\SalesModel\Order::class] ]; } diff --git a/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/OrderTest.php b/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/OrderTest.php index b3c76b3407fe7..b3096c35258a5 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/OrderTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/OrderTest.php @@ -15,7 +15,7 @@ class OrderTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->_orderMock = $this->getMock('Magento\Sales\Model\Order', [], [], '', false); + $this->_orderMock = $this->getMock(\Magento\Sales\Model\Order::class, [], [], '', false); $this->_model = new \Magento\Payment\Model\Cart\SalesModel\Order($this->_orderMock); } diff --git a/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/QuoteTest.php b/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/QuoteTest.php index 7516ff49f9daf..aded897dcd21b 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/QuoteTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Cart/SalesModel/QuoteTest.php @@ -15,7 +15,7 @@ class QuoteTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->_quoteMock = $this->getMock('Magento\Quote\Model\Quote', [], [], '', false); + $this->_quoteMock = $this->getMock(\Magento\Quote\Model\Quote::class, [], [], '', false); $this->_model = new \Magento\Payment\Model\Cart\SalesModel\Quote($this->_quoteMock); } @@ -64,7 +64,7 @@ public function testGetTaxContainer() */ public function testGetAllItems($pItem, $name, $qty, $price) { - $itemMock = $this->getMock('Magento\Quote\Model\Quote\Item\AbstractItem', [], [], '', false); + $itemMock = $this->getMock(\Magento\Quote\Model\Quote\Item\AbstractItem::class, [], [], '', false); $itemMock->expects($this->any())->method('getParentItem')->will($this->returnValue($pItem)); $itemMock->expects($this->once())->method('__call')->with('getName')->will($this->returnValue($name)); $itemMock->expects($this->any())->method('getTotalQty')->will($this->returnValue($qty)); @@ -114,7 +114,7 @@ public function testGetBaseSubtotal() */ public function testGetter($isVirtual, $getterMethod) { - $address = $this->getMock('Magento\Quote\Model\Quote\Address', [], [], '', false); + $address = $this->getMock(\Magento\Quote\Model\Quote\Address::class, [], [], '', false); $address->expects( $this->any() )->method( @@ -124,7 +124,7 @@ public function testGetter($isVirtual, $getterMethod) )->will( $this->returnValue($getterMethod) ); - $quoteMock = $this->getMock('Magento\Quote\Model\Quote', [], [], '', false); + $quoteMock = $this->getMock(\Magento\Quote\Model\Quote::class, [], [], '', false); $quoteMock->expects($this->any())->method('getIsVirtual')->will($this->returnValue($isVirtual)); $method = 'getShippingAddress'; if ($isVirtual) { diff --git a/app/code/Magento/Payment/Test/Unit/Model/CartTest.php b/app/code/Magento/Payment/Test/Unit/Model/CartTest.php index 67b04b8344d77..9a4041183f3e6 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/CartTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/CartTest.php @@ -20,9 +20,9 @@ class CartTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->_eventManagerMock = $this->getMock('Magento\Framework\Event\ManagerInterface'); - $this->_salesModelMock = $this->getMock('Magento\Payment\Model\Cart\SalesModel\SalesModelInterface'); - $factoryMock = $this->getMock('Magento\Payment\Model\Cart\SalesModel\Factory', [], [], '', false); + $this->_eventManagerMock = $this->getMock(\Magento\Framework\Event\ManagerInterface::class); + $this->_salesModelMock = $this->getMock(\Magento\Payment\Model\Cart\SalesModel\SalesModelInterface::class); + $factoryMock = $this->getMock(\Magento\Payment\Model\Cart\SalesModel\Factory::class, [], [], '', false); $factoryMock->expects($this->once())->method('create')->will($this->returnValue($this->_salesModelMock)); $this->_model = new \Magento\Payment\Model\Cart($factoryMock, $this->_eventManagerMock, null); diff --git a/app/code/Magento/Payment/Test/Unit/Model/CcConfigProviderTest.php b/app/code/Magento/Payment/Test/Unit/Model/CcConfigProviderTest.php index 056cefeafdaa1..9897628514387 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/CcConfigProviderTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/CcConfigProviderTest.php @@ -24,8 +24,8 @@ class CcConfigProviderTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->ccConfigMock = $this->getMock('\Magento\Payment\Model\CcConfig', [], [], '', false); - $this->assetSourceMock = $this->getMock('\Magento\Framework\View\Asset\Source', [], [], '', false); + $this->ccConfigMock = $this->getMock(\Magento\Payment\Model\CcConfig::class, [], [], '', false); + $this->assetSourceMock = $this->getMock(\Magento\Framework\View\Asset\Source::class, [], [], '', false); $this->model = new \Magento\Payment\Model\CcConfigProvider( $this->ccConfigMock, $this->assetSourceMock @@ -66,7 +66,7 @@ public function testGetConfig() 'url' => 'http://cc.card/ae.png' ] ]; - $assetMock = $this->getMock('\Magento\Framework\View\Asset\File', [], [], '', false); + $assetMock = $this->getMock(\Magento\Framework\View\Asset\File::class, [], [], '', false); $this->ccConfigMock->expects($this->once())->method('getCcAvailableTypes')->willReturn($ccAvailableTypesMock); diff --git a/app/code/Magento/Payment/Test/Unit/Model/CcConfigTest.php b/app/code/Magento/Payment/Test/Unit/Model/CcConfigTest.php index 46663d30d8a0d..468d71f0ba9ea 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/CcConfigTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/CcConfigTest.php @@ -29,11 +29,11 @@ class CcConfigTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->configMock = $this->getMock('Magento\Payment\Model\Config', [], [], '', false); - $this->repositoryMock = $this->getMock('Magento\Framework\View\Asset\Repository', [], [], '', false); - $this->requestMock = $this->getMock('Magento\Framework\App\RequestInterface'); - $this->urlMock = $this->getMock('Magento\Framework\UrlInterface'); - $this->loggerMock = $this->getMock('Psr\Log\LoggerInterface'); + $this->configMock = $this->getMock(\Magento\Payment\Model\Config::class, [], [], '', false); + $this->repositoryMock = $this->getMock(\Magento\Framework\View\Asset\Repository::class, [], [], '', false); + $this->requestMock = $this->getMock(\Magento\Framework\App\RequestInterface::class); + $this->urlMock = $this->getMock(\Magento\Framework\UrlInterface::class); + $this->loggerMock = $this->getMock(\Psr\Log\LoggerInterface::class); $this->model = new \Magento\Payment\Model\CcConfig( $this->configMock, diff --git a/app/code/Magento/Payment/Test/Unit/Model/CcGenericConfigProviderTest.php b/app/code/Magento/Payment/Test/Unit/Model/CcGenericConfigProviderTest.php index 4628eb9446bed..60827173f72d7 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/CcGenericConfigProviderTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/CcGenericConfigProviderTest.php @@ -22,8 +22,8 @@ class CcGenericConfigProviderTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->ccConfigMock = $this->getMock('Magento\Payment\Model\CcConfig', [], [], '', false); - $this->paymentHelperMock = $this->getMock('Magento\Payment\Helper\Data', [], [], '', false); + $this->ccConfigMock = $this->getMock(\Magento\Payment\Model\CcConfig::class, [], [], '', false); + $this->paymentHelperMock = $this->getMock(\Magento\Payment\Helper\Data::class, [], [], '', false); $this->model = new CcGenericConfigProvider( $this->ccConfigMock, diff --git a/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseCheckoutTest.php b/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseCheckoutTest.php index d64efadbeb2f5..f397445418eb0 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseCheckoutTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseCheckoutTest.php @@ -26,11 +26,11 @@ protected function setUp() */ public function testIsApplicable($expectation) { - $quote = $this->getMockBuilder('Magento\Quote\Model\Quote')->disableOriginalConstructor()->setMethods( + $quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class)->disableOriginalConstructor()->setMethods( [] )->getMock(); $paymentMethod = $this->getMockBuilder( - '\Magento\Payment\Model\MethodInterface' + \Magento\Payment\Model\MethodInterface::class )->disableOriginalConstructor()->setMethods([])->getMock(); $paymentMethod->expects($this->once())->method('canUseCheckout')->will( $this->returnValue($expectation) diff --git a/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCountry/CountryProviderTest.php b/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCountry/CountryProviderTest.php index dd33a4c0b877d..02cfd0387c3e5 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCountry/CountryProviderTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCountry/CountryProviderTest.php @@ -5,55 +5,123 @@ */ namespace Magento\Payment\Test\Unit\Model\Checks\CanUseForCountry; +use Magento\Directory\Helper\Data; +use Magento\Payment\Model\Checks\CanUseForCountry\CountryProvider; +use Magento\Quote\Model\Quote; +use Magento\Quote\Model\Quote\Address; +use PHPUnit_Framework_MockObject_MockObject as MockObject; + +/** + * CountryProviderTest contains tests for CountryProvider class + */ class CountryProviderTest extends \PHPUnit_Framework_TestCase { /** - * @var \Magento\Payment\Model\Checks\CanUseForCountry\CountryProvider + * @var CountryProvider */ - protected $model; + private $countryProvider; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var Data|MockObject */ - protected $directoryMock; + private $directory; + + /** + * @var Quote|MockObject + */ + private $quote; protected function setUp() { - $this->directoryMock = $this->getMock('Magento\Directory\Helper\Data', [], [], '', false, false); - $this->model = new \Magento\Payment\Model\Checks\CanUseForCountry\CountryProvider($this->directoryMock); + $this->directory = $this->getMockBuilder(Data::class) + ->disableOriginalConstructor() + ->setMethods(['getDefaultCountry']) + ->getMock(); + + $this->quote = $this->getMockBuilder(Quote::class) + ->disableOriginalConstructor() + ->setMethods(['getBillingAddress', 'getShippingAddress']) + ->getMock(); + + $this->countryProvider = new CountryProvider($this->directory); } - public function testGetCountryForNonVirtualQuote() + /** + * @covers \Magento\Payment\Model\Checks\CanUseForCountry\CountryProvider::getCountry + */ + public function testGetCountry() { - $quoteMock = $this->getMock('Magento\Quote\Model\Quote', [], [], '', false, false); - $quoteMock->expects($this->once())->method('isVirtual')->willReturn(false); - $addressMock = $this->getMock('Magento\Quote\Model\Quote\Address', [], [], '', false, false); - $addressMock->expects($this->once())->method('getCountry')->will($this->returnValue(1)); - $quoteMock->expects($this->once())->method('getShippingAddress')->will($this->returnValue($addressMock)); - $this->assertEquals(1, $this->model->getCountry($quoteMock)); + $address = $this->getMockBuilder(Address::class) + ->disableOriginalConstructor() + ->setMethods(['getCountry']) + ->getMock(); + + $this->quote->expects(static::once()) + ->method('getBillingAddress') + ->willReturn($address); + + $this->quote->expects(static::never()) + ->method('getShippingAddress'); + + $address->expects(static::exactly(2)) + ->method('getCountry') + ->willReturn('UK'); + $this->directory->expects(static::never()) + ->method('getDefaultCountry'); + + static::assertEquals('UK', $this->countryProvider->getCountry($this->quote)); } - public function testGetCountryForVirtualQuoteWhenBillingAddressNotExist() + /** + * @covers \Magento\Payment\Model\Checks\CanUseForCountry\CountryProvider::getCountry + */ + public function testGetCountryForBillingAddressWithoutCountry() { - $quoteMock = $this->getMock('Magento\Quote\Model\Quote', [], [], '', false, false); - $quoteMock->expects($this->once())->method('isVirtual')->willReturn(true); - $addressMock = $this->getMock('Magento\Quote\Model\Quote\Address', [], [], '', false, false); - $addressMock->expects($this->never())->method('getCountry'); - $quoteMock->expects($this->never())->method('getShippingAddress'); - $quoteMock->expects($this->once())->method('getBillingAddress')->willReturn(null); - $this->directoryMock->expects($this->once())->method('getDefaultCountry')->willReturn(10); - $this->assertEquals(10, $this->model->getCountry($quoteMock)); + $address = $this->getMockBuilder(Address::class) + ->disableOriginalConstructor() + ->setMethods(['getCountry']) + ->getMock(); + + $this->quote->expects(static::never()) + ->method('getShippingAddress'); + $this->quote->expects(static::once()) + ->method('getBillingAddress') + ->willReturn($address); + + $address->expects(static::once()) + ->method('getCountry') + ->willReturn(null); + $this->directory->expects(static::once()) + ->method('getDefaultCountry') + ->willReturn('US'); + static::assertEquals('US', $this->countryProvider->getCountry($this->quote)); } - public function testGetCountryForVirtualQuoteWhenBillingAddressExist() + /** + * @covers \Magento\Payment\Model\Checks\CanUseForCountry\CountryProvider::getCountry + */ + public function testGetCountryShippingAddress() { - $quoteMock = $this->getMock('Magento\Quote\Model\Quote', [], [], '', false, false); - $quoteMock->expects($this->once())->method('isVirtual')->willReturn(true); - $addressMock = $this->getMock('Magento\Quote\Model\Quote\Address', [], [], '', false, false); - $addressMock->expects($this->once())->method('getCountry')->willReturn(10); - $quoteMock->expects($this->never())->method('getShippingAddress'); - $quoteMock->expects($this->once())->method('getBillingAddress')->willReturn($addressMock); - $this->directoryMock->expects($this->never())->method('getDefaultCountry'); - $this->assertEquals(10, $this->model->getCountry($quoteMock)); + $address = $this->getMockBuilder(Address::class) + ->disableOriginalConstructor() + ->setMethods(['getCountry']) + ->getMock(); + + $this->quote->expects(static::once()) + ->method('getBillingAddress') + ->willReturn(null); + + $this->quote->expects(static::once()) + ->method('getShippingAddress') + ->willReturn($address); + + $address->expects(static::exactly(2)) + ->method('getCountry') + ->willReturn('CA'); + + $this->directory->expects(static::never()) + ->method('getDefaultCountry'); + + static::assertEquals('CA', $this->countryProvider->getCountry($this->quote)); } } diff --git a/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCountryTest.php b/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCountryTest.php index 2742f152b4f74..0842bc6a6f887 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCountryTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCountryTest.php @@ -28,7 +28,7 @@ class CanUseForCountryTest extends \PHPUnit_Framework_TestCase protected function setUp() { $this->countryProvider = $this->getMock( - 'Magento\Payment\Model\Checks\CanUseForCountry\CountryProvider', + \Magento\Payment\Model\Checks\CanUseForCountry\CountryProvider::class, [], [], '', @@ -44,12 +44,12 @@ protected function setUp() */ public function testIsApplicable($expectation) { - $quoteMock = $this->getMockBuilder('Magento\Quote\Model\Quote')->disableOriginalConstructor()->setMethods( + $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class)->disableOriginalConstructor()->setMethods( [] )->getMock(); $paymentMethod = $this->getMockBuilder( - '\Magento\Payment\Model\MethodInterface' + \Magento\Payment\Model\MethodInterface::class )->disableOriginalConstructor()->setMethods([])->getMock(); $paymentMethod->expects($this->once())->method('canUseForCountry')->with( self::EXPECTED_COUNTRY_ID diff --git a/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCurrencyTest.php b/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCurrencyTest.php index a3b6c6db899a6..7b8d2587520dc 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCurrencyTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseForCurrencyTest.php @@ -32,17 +32,17 @@ protected function setUp() public function testIsApplicable($expectation) { $paymentMethod = $this->getMockBuilder( - '\Magento\Payment\Model\MethodInterface' + \Magento\Payment\Model\MethodInterface::class )->disableOriginalConstructor()->setMethods([])->getMock(); $paymentMethod->expects($this->once())->method('canUseForCurrency')->with( self::EXPECTED_CURRENCY_CODE )->will($this->returnValue($expectation)); - $quoteMock = $this->getMockBuilder('Magento\Quote\Model\Quote')->disableOriginalConstructor()->setMethods( + $quoteMock = $this->getMockBuilder(\Magento\Quote\Model\Quote::class)->disableOriginalConstructor()->setMethods( [] )->getMock(); $store = $this->getMockBuilder( - 'Magento\Store\Model\Store' + \Magento\Store\Model\Store::class )->disableOriginalConstructor()->setMethods([])->getMock(); $store->expects($this->once())->method('getBaseCurrencyCode')->will( $this->returnValue(self::EXPECTED_CURRENCY_CODE) diff --git a/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseInternalTest.php b/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseInternalTest.php index 54f69431ff4a5..5d30493e485db 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseInternalTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Checks/CanUseInternalTest.php @@ -26,11 +26,11 @@ protected function setUp() */ public function testIsApplicable($expectation) { - $quote = $this->getMockBuilder('Magento\Quote\Model\Quote')->disableOriginalConstructor()->setMethods( + $quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class)->disableOriginalConstructor()->setMethods( [] )->getMock(); $paymentMethod = $this->getMockBuilder( - '\Magento\Payment\Model\MethodInterface' + \Magento\Payment\Model\MethodInterface::class )->disableOriginalConstructor()->setMethods([])->getMock(); $paymentMethod->expects($this->once())->method('canUseInternal')->will( $this->returnValue($expectation) diff --git a/app/code/Magento/Payment/Test/Unit/Model/Checks/CompositeTest.php b/app/code/Magento/Payment/Test/Unit/Model/Checks/CompositeTest.php index e369d6e9550a7..8ce5abe8c180a 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Checks/CompositeTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Checks/CompositeTest.php @@ -16,15 +16,15 @@ class CompositeTest extends \PHPUnit_Framework_TestCase */ public function testIsApplicable($expectation) { - $quote = $this->getMockBuilder('Magento\Quote\Model\Quote')->disableOriginalConstructor()->setMethods( + $quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class)->disableOriginalConstructor()->setMethods( [] )->getMock(); $paymentMethod = $this->getMockBuilder( - '\Magento\Payment\Model\MethodInterface' + \Magento\Payment\Model\MethodInterface::class )->disableOriginalConstructor()->setMethods([])->getMock(); $specification = $this->getMockBuilder( - 'Magento\Payment\Model\Checks\SpecificationInterface' + \Magento\Payment\Model\Checks\SpecificationInterface::class )->disableOriginalConstructor()->setMethods([])->getMock(); $specification->expects($this->once())->method('isApplicable')->with($paymentMethod, $quote)->will( $this->returnValue($expectation) diff --git a/app/code/Magento/Payment/Test/Unit/Model/Checks/SpecificationFactoryTest.php b/app/code/Magento/Payment/Test/Unit/Model/Checks/SpecificationFactoryTest.php index 898076d54f180..63aa63d96ed31 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Checks/SpecificationFactoryTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Checks/SpecificationFactoryTest.php @@ -23,19 +23,19 @@ class SpecificationFactoryTest extends \PHPUnit_Framework_TestCase protected function setUp() { $this->_compositeFactory = $this->getMockBuilder( - 'Magento\Payment\Model\Checks\CompositeFactory' + \Magento\Payment\Model\Checks\CompositeFactory::class )->disableOriginalConstructor()->setMethods(['create'])->getMock(); } public function testCreate() { $specification = $this->getMockBuilder( - 'Magento\Payment\Model\Checks\SpecificationInterface' + \Magento\Payment\Model\Checks\SpecificationInterface::class )->disableOriginalConstructor()->setMethods([])->getMock(); $specificationMapping = [self::SPECIFICATION_KEY => $specification]; $expectedComposite = $this->getMockBuilder( - 'Magento\Payment\Model\Checks\Composite' + \Magento\Payment\Model\Checks\Composite::class )->disableOriginalConstructor()->setMethods([])->getMock(); $modelFactory = new SpecificationFactory($this->_compositeFactory, $specificationMapping); $this->_compositeFactory->expects($this->once())->method('create')->with( diff --git a/app/code/Magento/Payment/Test/Unit/Model/Checks/TotalMinMaxTest.php b/app/code/Magento/Payment/Test/Unit/Model/Checks/TotalMinMaxTest.php index acb786d0b796a..0adf1cb386455 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Checks/TotalMinMaxTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Checks/TotalMinMaxTest.php @@ -28,7 +28,7 @@ class TotalMinMaxTest extends \PHPUnit_Framework_TestCase public function testIsApplicable($baseGrandTotal, $expectation) { $paymentMethod = $this->getMockBuilder( - '\Magento\Payment\Model\MethodInterface' + \Magento\Payment\Model\MethodInterface::class )->disableOriginalConstructor()->setMethods([])->getMock(); $paymentMethod->expects($this->at(0))->method('getConfigData')->with( TotalMinMax::MIN_ORDER_TOTAL @@ -37,7 +37,7 @@ public function testIsApplicable($baseGrandTotal, $expectation) TotalMinMax::MAX_ORDER_TOTAL )->will($this->returnValue(self::PAYMENT_MAX_TOTAL)); - $quote = $this->getMockBuilder('Magento\Quote\Model\Quote')->disableOriginalConstructor()->setMethods( + $quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class)->disableOriginalConstructor()->setMethods( ['getBaseGrandTotal', '__wakeup'] )->getMock(); $quote->expects($this->once())->method('getBaseGrandTotal')->will($this->returnValue($baseGrandTotal)); diff --git a/app/code/Magento/Payment/Test/Unit/Model/Checks/ZeroTotalTest.php b/app/code/Magento/Payment/Test/Unit/Model/Checks/ZeroTotalTest.php index 2b816a6151211..af6d7e78c2555 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Checks/ZeroTotalTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Checks/ZeroTotalTest.php @@ -18,7 +18,7 @@ class ZeroTotalTest extends \PHPUnit_Framework_TestCase */ public function testIsApplicable($code, $total, $expectation) { - $paymentMethod = $this->getMockBuilder('\Magento\Payment\Model\MethodInterface') + $paymentMethod = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) ->disableOriginalConstructor() ->setMethods([]) ->getMock(); @@ -29,7 +29,7 @@ public function testIsApplicable($code, $total, $expectation) ->will($this->returnValue($code)); } - $quote = $this->getMockBuilder('Magento\Quote\Model\Quote') + $quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) ->disableOriginalConstructor() ->setMethods(['getBaseGrandTotal', '__wakeup']) ->getMock(); diff --git a/app/code/Magento/Payment/Test/Unit/Model/Config/SchemaLocatorTest.php b/app/code/Magento/Payment/Test/Unit/Model/Config/SchemaLocatorTest.php index 665d5c6e882c7..9a744a94a2aa5 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Config/SchemaLocatorTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Config/SchemaLocatorTest.php @@ -19,7 +19,7 @@ class SchemaLocatorTest extends \PHPUnit_Framework_TestCase protected function setUp() { $moduleReader = $this->getMockBuilder( - 'Magento\Framework\Module\Dir\Reader' + \Magento\Framework\Module\Dir\Reader::class )->disableOriginalConstructor()->setMethods([])->getMock(); $moduleReader->expects($this->once())->method('getModuleDir')->with('etc', 'Magento_Payment')->will( $this->returnValue(self::MODULE_DIR_PATH) diff --git a/app/code/Magento/Payment/Test/Unit/Model/Config/Source/AllmethodsTest.php b/app/code/Magento/Payment/Test/Unit/Model/Config/Source/AllmethodsTest.php index 67de175ca0147..7d0224a46be7c 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Config/Source/AllmethodsTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Config/Source/AllmethodsTest.php @@ -27,7 +27,7 @@ class AllmethodsTest extends \PHPUnit_Framework_TestCase protected function setUp() { $this->_paymentData = $this->getMockBuilder( - 'Magento\Payment\Helper\Data' + \Magento\Payment\Helper\Data::class )->disableOriginalConstructor()->setMethods([])->getMock(); $this->_model = new Allmethods($this->_paymentData); diff --git a/app/code/Magento/Payment/Test/Unit/Model/Config/Source/CctypeTest.php b/app/code/Magento/Payment/Test/Unit/Model/Config/Source/CctypeTest.php index 87d32873be24e..58a9826c1ee89 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Config/Source/CctypeTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Config/Source/CctypeTest.php @@ -25,7 +25,7 @@ class CctypeTest extends \PHPUnit_Framework_TestCase protected function setUp() { $this->_paymentConfig = $this->getMockBuilder( - 'Magento\Payment\Model\Config' + \Magento\Payment\Model\Config::class )->disableOriginalConstructor()->setMethods([])->getMock(); $this->_model = new Cctype($this->_paymentConfig); diff --git a/app/code/Magento/Payment/Test/Unit/Model/ConfigTest.php b/app/code/Magento/Payment/Test/Unit/Model/ConfigTest.php index 2a07b2ae14db0..dd3cd3e3b52f2 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/ConfigTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/ConfigTest.php @@ -13,6 +13,9 @@ use Magento\Payment\Model\MethodInterface; use Magento\Store\Model\ScopeInterface; +/** + * Class ConfigTest + */ class ConfigTest extends \PHPUnit_Framework_TestCase { /** @var \Magento\Payment\Model\Config */ @@ -43,7 +46,7 @@ class ConfigTest extends \PHPUnit_Framework_TestCase * * @var array */ - protected $paymentMethodsList = [ + private $paymentMethodsList = [ 'not_active_method' => ['active' => 0], 'active_method_no_model' => ['active' => 1], 'active_method' => ['active' => 1, 'model' => 'model_name'], @@ -97,20 +100,20 @@ class ConfigTest extends \PHPUnit_Framework_TestCase protected function setUp() { $this->scopeConfig = $this->getMock( - 'Magento\Framework\App\Config\ScopeConfigInterface', + \Magento\Framework\App\Config\ScopeConfigInterface::class, [], [], '', false ); - $this->paymentMethodFactory = $this->getMock('Magento\Payment\Model\Method\Factory', [], [], '', false); - $this->localeResolver = $this->getMock('Magento\Framework\Locale\ResolverInterface', [], [], '', false); - $this->dataStorage = $this->getMock('Magento\Framework\Config\DataInterface', [], [], '', false); - $this->date = $this->getMock('Magento\Framework\Stdlib\DateTime\DateTime', [], [], '', false); + $this->paymentMethodFactory = $this->getMock(\Magento\Payment\Model\Method\Factory::class, [], [], '', false); + $this->localeResolver = $this->getMock(\Magento\Framework\Locale\ResolverInterface::class, [], [], '', false); + $this->dataStorage = $this->getMock(\Magento\Framework\Config\DataInterface::class, [], [], '', false); + $this->date = $this->getMock(\Magento\Framework\Stdlib\DateTime\DateTime::class, [], [], '', false); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->config = $this->objectManagerHelper->getObject( - 'Magento\Payment\Model\Config', + \Magento\Payment\Model\Config::class, [ 'scopeConfig' => $this->scopeConfig, 'paymentMethodFactory' => $this->paymentMethodFactory, @@ -122,6 +125,7 @@ protected function setUp() } /** + * @covers \Magento\Payment\Model\Config::getActiveMethods * @param bool $isActive * @dataProvider getActiveMethodsDataProvider */ diff --git a/app/code/Magento/Payment/Test/Unit/Model/InfoTest.php b/app/code/Magento/Payment/Test/Unit/Model/InfoTest.php index 72a6e3eda5507..84412a32b9212 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/InfoTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/InfoTest.php @@ -34,22 +34,28 @@ class InfoTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->contextMock = $this->getMock('Magento\Framework\Model\Context', [], [], '', false); - $this->registryMock = $this->getMock('Magento\Framework\Registry'); - $this->paymentHelperMock = $this->getMock('Magento\Payment\Helper\Data', ['getMethodInstance'], [], '', false); + $this->contextMock = $this->getMock(\Magento\Framework\Model\Context::class, [], [], '', false); + $this->registryMock = $this->getMock(\Magento\Framework\Registry::class); + $this->paymentHelperMock = $this->getMock( + \Magento\Payment\Helper\Data::class, + ['getMethodInstance'], + [], + '', + false + ); $this->encryptorInterfaceMock = $this->getMock( - 'Magento\Framework\Encryption\EncryptorInterface', + \Magento\Framework\Encryption\EncryptorInterface::class, [], [], '', false ); - $this->methodInstanceMock = $this->getMockBuilder('Magento\Payment\Model\MethodInterface') + $this->methodInstanceMock = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) ->getMockForAbstractClass(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->info = $this->objectManagerHelper->getObject( - 'Magento\Payment\Model\Info', + \Magento\Payment\Model\Info::class, [ 'context' => $this->contextMock, 'registry' => $this->registryMock, @@ -138,7 +144,7 @@ public function testGetMethodInstanceWithNoMethod() $this->info->setData('method', false); $this->info->getMethodInstance(); } - + public function testGetMethodInstanceRequestedMethod() { $code = 'real_method'; diff --git a/app/code/Magento/Payment/Test/Unit/Model/Method/AbstractMethodTest.php b/app/code/Magento/Payment/Test/Unit/Model/Method/AbstractMethodTest.php index 22c35df17e897..511d2821828dc 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Method/AbstractMethodTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Method/AbstractMethodTest.php @@ -15,6 +15,7 @@ * Class AbstractMethodTest * * Test for class \Magento\Payment\Model\Method\AbstractMethod + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class AbstractMethodTest extends \PHPUnit_Framework_TestCase { @@ -45,24 +46,24 @@ class AbstractMethodTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->scopeConfigMock = $this->getMockBuilder('Magento\Framework\App\Config\ScopeConfigInterface') + $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) ->setMethods(['getValue']) ->getMockForAbstractClass(); - $this->eventManagerMock = $this->getMockBuilder('Magento\Framework\Event\ManagerInterface') + $this->eventManagerMock = $this->getMockBuilder(\Magento\Framework\Event\ManagerInterface::class) ->setMethods(['dispatch']) ->getMockForAbstractClass(); - $this->quoteMock = $this->getMockBuilder('Magento\Quote\Api\Data\CartInterface') + $this->quoteMock = $this->getMockBuilder(\Magento\Quote\Api\Data\CartInterface::class) ->setMethods(['getStoreId']) ->getMockForAbstractClass(); - $contextMock = $this->getMockBuilder('Magento\Framework\Model\Context') + $contextMock = $this->getMockBuilder(\Magento\Framework\Model\Context::class) ->disableOriginalConstructor() ->setMethods(['getEventDispatcher']) ->getMock(); $contextMock->expects($this->once()) ->method('getEventDispatcher') ->willReturn($this->eventManagerMock); - $this->loggerMock = $this->getMockBuilder('\Magento\Payment\Model\Method\Logger') - ->setConstructorArgs([$this->getMockForAbstractClass('Psr\Log\LoggerInterface')]) + $this->loggerMock = $this->getMockBuilder(\Magento\Payment\Model\Method\Logger::class) + ->setConstructorArgs([$this->getMockForAbstractClass(\Psr\Log\LoggerInterface::class)]) ->setMethods(['debug']) ->getMock(); diff --git a/app/code/Magento/Payment/Test/Unit/Model/Method/AdapterTest.php b/app/code/Magento/Payment/Test/Unit/Model/Method/AdapterTest.php index 9489219ed7aa2..d8fefb7345e0f 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Method/AdapterTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Method/AdapterTest.php @@ -13,34 +13,40 @@ use Magento\Payment\Gateway\Config\ValueHandlerPoolInterface; use Magento\Payment\Gateway\Data\PaymentDataObjectFactory; use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; +use Magento\Payment\Gateway\Validator\ResultInterface; +use Magento\Payment\Gateway\Validator\ValidatorInterface; use Magento\Payment\Gateway\Validator\ValidatorPoolInterface; use Magento\Payment\Model\InfoInterface; use Magento\Payment\Model\Method\Adapter; +use PHPUnit_Framework_MockObject_MockObject as MockObject; +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ class AdapterTest extends \PHPUnit_Framework_TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject | ManagerInterface + * @var MockObject|ManagerInterface */ private $eventManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject | ValueHandlerPoolInterface + * @var MockObject|ValueHandlerPoolInterface */ private $valueHandlerPool; /** - * @var \PHPUnit_Framework_MockObject_MockObject | ValidatorPoolInterface + * @var MockObject|ValidatorPoolInterface */ private $validatorPool; /** - * @var \PHPUnit_Framework_MockObject_MockObject | CommandPoolInterface + * @var MockObject|CommandPoolInterface */ private $commandPool; /** - * @var \PHPUnit_Framework_MockObject_MockObject | PaymentDataObjectFactory + * @var MockObject|PaymentDataObjectFactory */ private $paymentDataObjectFactory; @@ -66,21 +72,11 @@ class AdapterTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->eventManager = $this->getMock( - 'Magento\Framework\Event\ManagerInterface' - ); - $this->valueHandlerPool = $this->getMock( - 'Magento\Payment\Gateway\Config\ValueHandlerPoolInterface' - ); - $this->validatorPool = $this->getMock( - 'Magento\Payment\Gateway\Validator\ValidatorPoolInterface' - ); - $this->commandPool = $this->getMock( - 'Magento\Payment\Gateway\Command\CommandPoolInterface' - ); - $this->paymentDataObjectFactory = $this->getMockBuilder( - 'Magento\Payment\Gateway\Data\PaymentDataObjectFactory' - ) + $this->eventManager = $this->getMock(ManagerInterface::class); + $this->valueHandlerPool = $this->getMock(ValueHandlerPoolInterface::class); + $this->validatorPool = $this->getMock(ValidatorPoolInterface::class); + $this->commandPool = $this->getMock(CommandPoolInterface::class); + $this->paymentDataObjectFactory = $this->getMockBuilder(PaymentDataObjectFactory::class) ->disableOriginalConstructor() ->getMock(); @@ -100,11 +96,12 @@ protected function setUp() ); } + /** + * @covers \Magento\Payment\Model\Method\Adapter::isAvailable + */ public function testIsAvailableNotActive() { - $activeValueHandler = $this->getMock( - 'Magento\Payment\Gateway\Config\ValueHandlerInterface' - ); + $activeValueHandler = $this->getMock(ValueHandlerInterface::class); $this->valueHandlerPool->expects(static::once()) ->method('get') @@ -121,17 +118,16 @@ public function testIsAvailableNotActive() static::assertFalse($this->adapter->isAvailable(null)); } + /** + * @covers \Magento\Payment\Model\Method\Adapter::isAvailable + */ public function testIsAvailableEmptyQuote() { - $activeValueHandler = $this->getMock( - 'Magento\Payment\Gateway\Config\ValueHandlerInterface' - ); - $availabilityValidator = $this->getMock( - 'Magento\Payment\Gateway\Validator\ValidatorInterface' - ); - $paymentDO = $this->getMock('Magento\Payment\Gateway\Data\PaymentDataObjectInterface'); - $validationResult = $this->getMock('Magento\Payment\Gateway\Validator\ResultInterface'); - $paymentInfo = $this->getMock('Magento\Payment\Model\InfoInterface'); + $activeValueHandler = $this->getMock(ValueHandlerInterface::class); + $availabilityValidator = $this->getMock(ValidatorInterface::class); + $paymentDO = $this->getMock(PaymentDataObjectInterface::class); + $validationResult = $this->getMock(ResultInterface::class); + $paymentInfo = $this->getMock(InfoInterface::class); $this->valueHandlerPool->expects(static::once()) ->method('get') @@ -164,24 +160,49 @@ public function testIsAvailableEmptyQuote() static::assertTrue($this->adapter->isAvailable(null)); } + /** + * @covers \Magento\Payment\Model\Method\Adapter::isAvailable + */ + public function testIsAvailableWithEmptyInfoInstance() + { + $activeValueHandler = $this->getMock(ValueHandlerInterface::class); + $this->valueHandlerPool->expects(static::once()) + ->method('get') + ->with('active') + ->willReturn($activeValueHandler); + $activeValueHandler->expects(static::once()) + ->method('handle') + ->with(['field' => 'active']) + ->willReturn(true); + + $this->validatorPool->expects(static::never()) + ->method('get') + ->with('availability'); + + $this->eventManager->expects(static::once()) + ->method('dispatch'); + + static::assertTrue($this->adapter->isAvailable(null)); + } + public function testExecuteCommandWithCommandExecutor() { - /** @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject $eventManager */ + /** @var ManagerInterface|MockObject $eventManager */ $eventManager = $this->getMock( ManagerInterface::class ); - /** @var ValueHandlerPoolInterface|\PHPUnit_Framework_MockObject_MockObject $valueHandlerPool */ + /** @var ValueHandlerPoolInterface|MockObject $valueHandlerPool */ $valueHandlerPool = $this->getMock( ValueHandlerPoolInterface::class ); - /** @var CommandManagerInterface|\PHPUnit_Framework_MockObject_MockObject $commandManager */ + /** @var CommandManagerInterface|MockObject $commandManager */ $commandManager = $this->getMock( CommandManagerInterface::class ); - /** @var PaymentDataObjectFactory|\PHPUnit_Framework_MockObject_MockObject $paymentDataObjectFactory */ + /** @var PaymentDataObjectFactory|MockObject $paymentDataObjectFactory */ $paymentDataObjectFactory = $this->getMockBuilder( PaymentDataObjectFactory::class ) @@ -229,25 +250,17 @@ public function testExecuteCommandWithCommandExecutor() public function testExecuteCommandWithCommandPool() { - /** @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject $eventManager */ - $eventManager = $this->getMock( - ManagerInterface::class - ); + /** @var ManagerInterface|MockObject $eventManager */ + $eventManager = $this->getMock(ManagerInterface::class); - /** @var ValueHandlerPoolInterface|\PHPUnit_Framework_MockObject_MockObject $valueHandlerPool */ - $valueHandlerPool = $this->getMock( - ValueHandlerPoolInterface::class - ); + /** @var ValueHandlerPoolInterface|MockObject $valueHandlerPool */ + $valueHandlerPool = $this->getMock(ValueHandlerPoolInterface::class); - /** @var CommandPoolInterface|\PHPUnit_Framework_MockObject_MockObject $commandPool */ - $commandPool = $this->getMock( - CommandPoolInterface::class - ); + /** @var CommandPoolInterface|MockObject $commandPool */ + $commandPool = $this->getMock(CommandPoolInterface::class); - /** @var PaymentDataObjectFactory|\PHPUnit_Framework_MockObject_MockObject $paymentDataObjectFactory */ - $paymentDataObjectFactory = $this->getMockBuilder( - PaymentDataObjectFactory::class - ) + /** @var PaymentDataObjectFactory|MockObject $paymentDataObjectFactory */ + $paymentDataObjectFactory = $this->getMockBuilder(PaymentDataObjectFactory::class) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/Payment/Test/Unit/Model/Method/FactoryTest.php b/app/code/Magento/Payment/Test/Unit/Model/Method/FactoryTest.php index b46d237fd8d11..712994f933f11 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Method/FactoryTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Method/FactoryTest.php @@ -21,16 +21,16 @@ protected function setUp() { $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_objectManagerMock = $this->getMock('Magento\Framework\ObjectManagerInterface'); + $this->_objectManagerMock = $this->getMock(\Magento\Framework\ObjectManagerInterface::class); $this->_factory = $objectManagerHelper->getObject( - 'Magento\Payment\Model\Method\Factory', + \Magento\Payment\Model\Method\Factory::class, ['objectManager' => $this->_objectManagerMock] ); } public function testCreateMethod() { - $className = 'Magento\Payment\Model\Method\AbstractMethod'; + $className = \Magento\Payment\Model\Method\AbstractMethod::class; $methodMock = $this->getMock($className, [], [], '', false); $this->_objectManagerMock->expects( $this->once() @@ -48,7 +48,7 @@ public function testCreateMethod() public function testCreateMethodWithArguments() { - $className = 'Magento\Payment\Model\Method\AbstractMethod'; + $className = \Magento\Payment\Model\Method\AbstractMethod::class; $data = ['param1', 'param2']; $methodMock = $this->getMock($className, [], [], '', false); $this->_objectManagerMock->expects( diff --git a/app/code/Magento/Payment/Test/Unit/Model/Method/FreeTest.php b/app/code/Magento/Payment/Test/Unit/Model/Method/FreeTest.php index 59dafd905db20..2dc274aa089f9 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Method/FreeTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Method/FreeTest.php @@ -8,6 +8,9 @@ namespace Magento\Payment\Test\Unit\Model\Method; +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ class FreeTest extends \PHPUnit_Framework_TestCase { /** @var \Magento\Payment\Model\Method\Free */ @@ -21,26 +24,39 @@ class FreeTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $paymentData = $this->getMock('Magento\Payment\Helper\Data', [], [], '', false); - $this->scopeConfig = $this->getMock('Magento\Framework\App\Config\ScopeConfigInterface', [], [], '', false); - $this->currencyPrice = $this->getMockBuilder('Magento\Framework\Pricing\PriceCurrencyInterface')->getMock(); + $paymentData = $this->getMock(\Magento\Payment\Helper\Data::class, [], [], '', false); + $this->scopeConfig = $this->getMock( + \Magento\Framework\App\Config\ScopeConfigInterface::class, + [], + [], + '', + false + ); + $this->currencyPrice = $this->getMockBuilder(\Magento\Framework\Pricing\PriceCurrencyInterface::class) + ->getMock(); - $context = $this->getMock('\Magento\Framework\Model\Context', ['getEventDispatcher'], [], '', false); - $eventManagerMock = $this->getMock('\Magento\Framework\Event\ManagerInterface'); + $context = $this->getMock(\Magento\Framework\Model\Context::class, ['getEventDispatcher'], [], '', false); + $eventManagerMock = $this->getMock(\Magento\Framework\Event\ManagerInterface::class); $context->expects($this->any())->method('getEventDispatcher')->willReturn($eventManagerMock); - $registry = $this->getMock('\Magento\Framework\Registry', [], [], '', false); + $registry = $this->getMock(\Magento\Framework\Registry::class, [], [], '', false); $extensionAttributesFactory = $this->getMock( - 'Magento\Framework\Api\ExtensionAttributesFactory', + \Magento\Framework\Api\ExtensionAttributesFactory::class, + [], + [], + '', + false + ); + $customAttributeFactory = $this->getMock( + \Magento\Framework\Api\AttributeValueFactory::class, [], [], '', false ); - $customAttributeFactory = $this->getMock('\Magento\Framework\Api\AttributeValueFactory', [], [], '', false); - $loggerMock = $this->getMockBuilder('\Magento\Payment\Model\Method\Logger') - ->setConstructorArgs([$this->getMockForAbstractClass('Psr\Log\LoggerInterface')]) + $loggerMock = $this->getMockBuilder(\Magento\Payment\Model\Method\Logger::class) + ->setConstructorArgs([$this->getMockForAbstractClass(\Psr\Log\LoggerInterface::class)]) ->getMock(); $this->methodFree = new \Magento\Payment\Model\Method\Free( @@ -86,7 +102,7 @@ public function testIsAvailable($grandTotal, $isActive, $notEmptyQuote, $result) { $quote = null; if ($notEmptyQuote) { - $quote = $this->getMock('Magento\Quote\Model\Quote', [], [], '', false); + $quote = $this->getMock(\Magento\Quote\Model\Quote::class, [], [], '', false); $quote->expects($this->any()) ->method('__call') ->with($this->equalTo('getGrandTotal')) diff --git a/app/code/Magento/Payment/Test/Unit/Model/Method/LoggerTest.php b/app/code/Magento/Payment/Test/Unit/Model/Method/LoggerTest.php index 3a8107d0ba678..5d9720c7896e4 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Method/LoggerTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Method/LoggerTest.php @@ -19,7 +19,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->loggerMock = $this->getMockForAbstractClass('Psr\Log\LoggerInterface'); + $this->loggerMock = $this->getMockForAbstractClass(\Psr\Log\LoggerInterface::class); $this->logger = new Logger($this->loggerMock); } diff --git a/app/code/Magento/Payment/Test/Unit/Model/Method/Specification/CompositeTest.php b/app/code/Magento/Payment/Test/Unit/Model/Method/Specification/CompositeTest.php index fd905ab7612a4..d7c8928622535 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Method/Specification/CompositeTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Method/Specification/CompositeTest.php @@ -18,7 +18,7 @@ class CompositeTest extends \PHPUnit_Framework_TestCase protected function setUp() { $this->factoryMock = $this->getMock( - 'Magento\Payment\Model\Method\Specification\Factory', + \Magento\Payment\Model\Method\Specification\Factory::class, [], [], '', @@ -35,7 +35,7 @@ protected function createComposite($specifications = []) $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); return $objectManager->getObject( - 'Magento\Payment\Model\Method\Specification\Composite', + \Magento\Payment\Model\Method\Specification\Composite::class, ['factory' => $this->factoryMock, 'specifications' => $specifications] ); } @@ -50,7 +50,7 @@ public function testComposite($firstSpecificationResult, $secondSpecificationRes { $method = 'method-name'; - $specificationFirst = $this->getMock('Magento\Payment\Model\Method\SpecificationInterface'); + $specificationFirst = $this->getMock(\Magento\Payment\Model\Method\SpecificationInterface::class); $specificationFirst->expects( $this->once() )->method( @@ -61,7 +61,7 @@ public function testComposite($firstSpecificationResult, $secondSpecificationRes $this->returnValue($firstSpecificationResult) ); - $specificationSecond = $this->getMock('Magento\Payment\Model\Method\SpecificationInterface'); + $specificationSecond = $this->getMock(\Magento\Payment\Model\Method\SpecificationInterface::class); $specificationSecond->expects( $this->any() )->method( diff --git a/app/code/Magento/Payment/Test/Unit/Model/Method/Specification/FactoryTest.php b/app/code/Magento/Payment/Test/Unit/Model/Method/Specification/FactoryTest.php index a5e878bd22f73..fbf0a79961448 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Method/Specification/FactoryTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Method/Specification/FactoryTest.php @@ -22,18 +22,18 @@ class FactoryTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->objectManagerMock = $this->getMock('Magento\Framework\ObjectManagerInterface'); + $this->objectManagerMock = $this->getMock(\Magento\Framework\ObjectManagerInterface::class); $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->factory = $objectManagerHelper->getObject( - 'Magento\Payment\Model\Method\Specification\Factory', + \Magento\Payment\Model\Method\Specification\Factory::class, ['objectManager' => $this->objectManagerMock] ); } public function testCreateMethod() { - $className = 'Magento\Payment\Model\Method\SpecificationInterface'; + $className = \Magento\Payment\Model\Method\SpecificationInterface::class; $methodMock = $this->getMock($className); $this->objectManagerMock->expects( $this->once() diff --git a/app/code/Magento/Payment/Test/Unit/Model/Method/SubstitutionTest.php b/app/code/Magento/Payment/Test/Unit/Model/Method/SubstitutionTest.php index 1edfea43da258..0f60dce0d8e3a 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Method/SubstitutionTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Method/SubstitutionTest.php @@ -21,13 +21,13 @@ class SubstitutionTest extends \PHPUnit_Framework_TestCase protected function setUp() { $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->model = $this->objectManager->getObject('Magento\Payment\Model\Method\Substitution'); + $this->model = $this->objectManager->getObject(\Magento\Payment\Model\Method\Substitution::class); } public function testGetTitle() { $infoMock = $this->getMockBuilder( - 'Magento\Payment\Model\Info' + \Magento\Payment\Model\Info::class )->disableOriginalConstructor()->setMethods( [] )->getMock(); diff --git a/app/code/Magento/Payment/Test/Unit/Model/MethodListTest.php b/app/code/Magento/Payment/Test/Unit/Model/MethodListTest.php index b1e5bedb5a250..872782407c129 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/MethodListTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/MethodListTest.php @@ -8,8 +8,8 @@ namespace Magento\Payment\Test\Unit\Model; -use Magento\Payment\Model\Method\Free; -use \Magento\Payment\Model\MethodList; +use Magento\Payment\Model\MethodList; +use Magento\Payment\Model\Method\AbstractMethod; class MethodListTest extends \PHPUnit_Framework_TestCase { @@ -24,9 +24,14 @@ class MethodListTest extends \PHPUnit_Framework_TestCase protected $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Payment\Api\PaymentMethodListInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $paymentMethodList; + + /** + * @var \Magento\Payment\Model\Method\InstanceFactory|\PHPUnit_Framework_MockObject_MockObject */ - protected $paymentHelperMock; + private $paymentMethodInstanceFactory; /** * @var \PHPUnit_Framework_MockObject_MockObject @@ -36,52 +41,80 @@ class MethodListTest extends \PHPUnit_Framework_TestCase protected function setUp() { $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->paymentHelperMock = $this->getMock('\Magento\Payment\Helper\Data', [], [], '', false); + + $this->paymentMethodList = $this->getMockBuilder(\Magento\Payment\Api\PaymentMethodListInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + + $this->paymentMethodInstanceFactory = $this->getMockBuilder( + \Magento\Payment\Model\Method\InstanceFactory::class + )->disableOriginalConstructor()->getMock(); + $this->specificationFactoryMock = $this->getMock( - '\Magento\Payment\Model\Checks\SpecificationFactory', [], [], '', false + \Magento\Payment\Model\Checks\SpecificationFactory::class, [], [], '', false ); $this->methodList = $this->objectManager->getObject( - 'Magento\Payment\Model\MethodList', + \Magento\Payment\Model\MethodList::class, [ - 'paymentHelper' => $this->paymentHelperMock, 'specificationFactory' => $this->specificationFactoryMock ] ); + + $this->objectManager->setBackwardCompatibleProperty( + $this->methodList, + 'paymentMethodList', + $this->paymentMethodList + ); + $this->objectManager->setBackwardCompatibleProperty( + $this->methodList, + 'paymentMethodInstanceFactory', + $this->paymentMethodInstanceFactory + ); } public function testGetAvailableMethods() { $storeId = 1; - $quoteMock = $this->getMock('\Magento\Quote\Model\Quote', [], [], '', false); + $quoteMock = $this->getMock(\Magento\Quote\Model\Quote::class, [], [], '', false); $quoteMock->expects($this->once())->method('getStoreId')->will($this->returnValue($storeId)); $quoteMock->expects($this->atLeastOnce()) ->method('getPayment') - ->will($this->returnValue($this->getMock('\Magento\Quote\Model\Quote\Payment', [], [], '', false))); + ->will($this->returnValue($this->getMock(\Magento\Quote\Model\Quote\Payment::class, [], [], '', false))); - $methodMock = $this->getMock('Magento\Payment\Model\Method\AbstractMethod', [], [], '', false); + $methodInstanceMock = $this->getMock(\Magento\Payment\Model\Method\AbstractMethod::class, [], [], '', false); + $methodInstanceMock->expects($this->once()) + ->method('isAvailable') + ->willReturn(true); - $compositeMock = $this->getMock('\Magento\Payment\Model\Checks\Composite', [], [], '', false); + $compositeMock = $this->getMock(\Magento\Payment\Model\Checks\Composite::class, [], [], '', false); $compositeMock->expects($this->atLeastOnce()) ->method('isApplicable') - ->with($methodMock, $quoteMock) + ->with($methodInstanceMock, $quoteMock) ->will($this->returnValue(true)); $this->specificationFactoryMock->expects($this->atLeastOnce()) ->method('create') + ->with([ + AbstractMethod::CHECK_USE_CHECKOUT, + AbstractMethod::CHECK_USE_FOR_COUNTRY, + AbstractMethod::CHECK_USE_FOR_CURRENCY, + AbstractMethod::CHECK_ORDER_TOTAL_MIN_MAX + ]) ->will($this->returnValue($compositeMock)); - $storeMethods = [$methodMock]; - - $this->paymentHelperMock->expects($this->once()) - ->method('getStoreMethods') - ->with($storeId, $quoteMock) - ->will($this->returnValue($storeMethods)); + $methodMock = $this->getMockForAbstractClass(\Magento\Payment\Api\Data\PaymentMethodInterface::class); + $this->paymentMethodList->expects($this->once()) + ->method('getActiveList') + ->willReturn([$methodMock]); + $this->paymentMethodInstanceFactory->expects($this->once()) + ->method('create') + ->willReturn($methodInstanceMock); - $methodMock->expects($this->atLeastOnce()) + $methodInstanceMock->expects($this->atLeastOnce()) ->method('setInfoInstance') - ->with($this->getMock('\Magento\Quote\Model\Quote\Payment', [], [], '', false)) + ->with($this->getMock(\Magento\Quote\Model\Quote\Payment::class, [], [], '', false)) ->will($this->returnSelf()); - $this->assertEquals([$methodMock], $this->methodList->getAvailableMethods($quoteMock)); + $this->assertEquals([$methodInstanceMock], $this->methodList->getAvailableMethods($quoteMock)); } } diff --git a/app/code/Magento/Payment/Test/Unit/Model/PaymentMethodListTest.php b/app/code/Magento/Payment/Test/Unit/Model/PaymentMethodListTest.php new file mode 100644 index 0000000000000..c41e5ac2a1aac --- /dev/null +++ b/app/code/Magento/Payment/Test/Unit/Model/PaymentMethodListTest.php @@ -0,0 +1,215 @@ +methodFactoryMock = $this->getMockBuilder(\Magento\Payment\Api\Data\PaymentMethodInterfaceFactory::class) + ->setMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->helperMock = $this->getMockBuilder(\Magento\Payment\Helper\Data::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + $this->paymentMethodList = $this->objectManagerHelper->getObject( + \Magento\Payment\Model\PaymentMethodList::class, + [ + 'methodFactory' => $this->methodFactoryMock, + 'helper' => $this->helperMock + ] + ); + } + + /** + * Setup getList method. + * + * @param array $paymentMethodConfig + * @param array $methodInstancesMap + * @return void + */ + private function setUpGetList($paymentMethodConfig, $methodInstancesMap) + { + $this->helperMock->expects($this->once()) + ->method('getPaymentMethods') + ->willReturn($paymentMethodConfig); + $this->helperMock->expects($this->any()) + ->method('getMethodInstance') + ->willReturnMap($methodInstancesMap); + + $this->methodFactoryMock->expects($this->any()) + ->method('create') + ->willReturnCallback(function ($data) { + $paymentMethod = $this->getMockBuilder(\Magento\Payment\Api\Data\PaymentMethodInterface::class) + ->getMockForAbstractClass(); + $paymentMethod->expects($this->any()) + ->method('getCode') + ->willReturn($data['code']); + $paymentMethod->expects($this->any()) + ->method('getIsActive') + ->willReturn($data['isActive']); + + return $paymentMethod; + }); + } + + /** + * Test getList. + * + * @param int $storeId + * @param array $paymentMethodConfig + * @param array $methodInstancesMap + * @param array $expected + * @return void + * + * @dataProvider getListDataProvider + */ + public function testGetList($storeId, $paymentMethodConfig, $methodInstancesMap, $expected) + { + $this->setUpGetList($paymentMethodConfig, $methodInstancesMap); + + $codes = array_map( + function ($method) { + return $method->getCode(); + }, + $this->paymentMethodList->getList($storeId) + ); + + $this->assertEquals($expected, $codes); + } + + /** + * Data provider for getList. + * + * @return array + */ + public function getListDataProvider() + { + return [ + [ + 1, + ['method_code_1' => [], 'method_code_2' => []], + [ + ['method_code_1', $this->mockPaymentMethodInstance(1, 10, 'method_code_1', 'title', true)], + ['method_code_2', $this->mockPaymentMethodInstance(1, 5, 'method_code_2', 'title', true)] + ], + ['method_code_2', 'method_code_1'] + ] + ]; + } + + /** + * Test getActiveList. + * + * @param int $storeId + * @param array $paymentMethodConfig + * @param array $methodInstancesMap + * @param array $expected + * @return void + * + * @dataProvider getActiveListDataProvider + */ + public function testGetActiveList($storeId, $paymentMethodConfig, $methodInstancesMap, $expected) + { + $this->setUpGetList($paymentMethodConfig, $methodInstancesMap); + + $codes = array_map( + function ($method) { + return $method->getCode(); + }, + $this->paymentMethodList->getActiveList($storeId) + ); + + $this->assertEquals($expected, $codes); + } + + /** + * Data provider for getActiveList. + * + * @return array + */ + public function getActiveListDataProvider() + { + return [ + [ + 1, + ['method_code_1' => [], 'method_code_2' => []], + [ + ['method_code_1', $this->mockPaymentMethodInstance(1, 10, 'method_code_1', 'title', false)], + ['method_code_2', $this->mockPaymentMethodInstance(1, 5, 'method_code_2', 'title', true)] + ], + ['method_code_2'] + ] + ]; + } + + /** + * Mock payment method instance. + * + * @param int $storeId + * @param int $sortOrder + * @param string $code + * @param string $title + * @param bool $isActive + * @return \PHPUnit_Framework_MockObject_MockObject + */ + private function mockPaymentMethodInstance($storeId, $sortOrder, $code, $title, $isActive) + { + $paymentMethodInstance = $this->getMockBuilder(\Magento\Payment\Model\Method\AbstractMethod::class) + ->setMethods(['getCode', 'getTitle', 'isActive', 'getConfigData']) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $paymentMethodInstance->expects($this->any()) + ->method('getConfigData') + ->willReturnMap([ + ['sort_order', $storeId, $sortOrder] + ]); + $paymentMethodInstance->expects($this->any()) + ->method('getCode') + ->willReturn($code); + $paymentMethodInstance->expects($this->any()) + ->method('getTitle') + ->willReturn($title); + $paymentMethodInstance->expects($this->any()) + ->method('isActive') + ->willReturn($isActive); + + return $paymentMethodInstance; + } +} diff --git a/app/code/Magento/Payment/Test/Unit/Model/ResourceModel/Grid/GroupListTest.php b/app/code/Magento/Payment/Test/Unit/Model/ResourceModel/Grid/GroupListTest.php index 63b3bf4d94cc4..4049cdb3d2151 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/ResourceModel/Grid/GroupListTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/ResourceModel/Grid/GroupListTest.php @@ -20,7 +20,7 @@ class GroupListTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->helperMock = $this->getMock('Magento\Payment\Helper\Data', [], [], '', false); + $this->helperMock = $this->getMock(\Magento\Payment\Helper\Data::class, [], [], '', false); $this->groupArrayModel = new \Magento\Payment\Model\ResourceModel\Grid\GroupList($this->helperMock); } diff --git a/app/code/Magento/Payment/Test/Unit/Model/ResourceModel/Grid/TypeListTest.php b/app/code/Magento/Payment/Test/Unit/Model/ResourceModel/Grid/TypeListTest.php index e509c30741959..c42c2e0c26c83 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/ResourceModel/Grid/TypeListTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/ResourceModel/Grid/TypeListTest.php @@ -20,7 +20,7 @@ class TypeListTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->helperMock = $this->getMock('Magento\Payment\Helper\Data', [], [], '', false); + $this->helperMock = $this->getMock(\Magento\Payment\Helper\Data::class, [], [], '', false); $this->typesArrayModel = new \Magento\Payment\Model\ResourceModel\Grid\TypeList($this->helperMock); } diff --git a/app/code/Magento/Payment/Test/Unit/Model/Source/CctypeTest.php b/app/code/Magento/Payment/Test/Unit/Model/Source/CctypeTest.php index 6380e7013d5fd..13e8775fa6b24 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Source/CctypeTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Source/CctypeTest.php @@ -46,7 +46,7 @@ class CctypeTest extends \PHPUnit_Framework_TestCase protected function setUp() { $this->_paymentConfig = $this->getMockBuilder( - 'Magento\Payment\Model\Config' + \Magento\Payment\Model\Config::class )->disableOriginalConstructor()->setMethods([])->getMock(); $this->_model = new Cctype($this->_paymentConfig); diff --git a/app/code/Magento/Payment/Test/Unit/Observer/SalesOrderBeforeSaveObserverTest.php b/app/code/Magento/Payment/Test/Unit/Observer/SalesOrderBeforeSaveObserverTest.php index d6336d6cd04df..be6cc1957a31d 100644 --- a/app/code/Magento/Payment/Test/Unit/Observer/SalesOrderBeforeSaveObserverTest.php +++ b/app/code/Magento/Payment/Test/Unit/Observer/SalesOrderBeforeSaveObserverTest.php @@ -26,12 +26,12 @@ protected function setUp() { $this->objectManagerHelper = new ObjectManagerHelper($this); $this->salesOrderBeforeSaveObserver = $this->objectManagerHelper->getObject( - 'Magento\Payment\Observer\SalesOrderBeforeSaveObserver', + \Magento\Payment\Observer\SalesOrderBeforeSaveObserver::class, [] ); $this->observerMock = $this->getMockBuilder( - 'Magento\Framework\Event\Observer' + \Magento\Framework\Event\Observer::class )->disableOriginalConstructor()->setMethods([])->getMock(); } @@ -131,7 +131,7 @@ public function testSalesOrderBeforeSaveSetForced() private function _prepareEventMockWithMethods($methodsList) { $this->eventMock = $this->getMockBuilder( - 'Magento\Framework\Event' + \Magento\Framework\Event::class )->disableOriginalConstructor()->setMethods($methodsList)->getMock(); $this->observerMock->expects($this->any())->method('getEvent')->will($this->returnValue($this->eventMock)); } @@ -145,15 +145,15 @@ private function _prepareEventMockWithMethods($methodsList) */ private function _getPreparedOrderMethod($methodCode, $orderMethods = []) { - $order = $this->getMockBuilder('Magento\Sales\Model\Order')->disableOriginalConstructor()->setMethods( + $order = $this->getMockBuilder(\Magento\Sales\Model\Order::class)->disableOriginalConstructor()->setMethods( array_merge(['__wakeup', 'getPayment'], $orderMethods) )->getMock(); $paymentMock = $this->getMockBuilder( - 'Magento\Sales\Model\Order\Payment' + \Magento\Sales\Model\Order\Payment::class )->disableOriginalConstructor()->setMethods([])->getMock(); $order->expects($this->once())->method('getPayment')->will($this->returnValue($paymentMock)); $methodInstance = $this->getMockBuilder( - 'Magento\Payment\Model\MethodInterface' + \Magento\Payment\Model\MethodInterface::class )->getMockForAbstractClass(); $paymentMock->expects($this->once())->method('getMethodInstance')->will($this->returnValue($methodInstance)); $methodInstance->expects($this->once())->method('getCode')->will($this->returnValue($methodCode)); diff --git a/app/code/Magento/Payment/Test/Unit/Observer/UpdateOrderStatusForPaymentMethodsObserverTest.php b/app/code/Magento/Payment/Test/Unit/Observer/UpdateOrderStatusForPaymentMethodsObserverTest.php index 781a7f9a43429..bf666dd76f55c 100644 --- a/app/code/Magento/Payment/Test/Unit/Observer/UpdateOrderStatusForPaymentMethodsObserverTest.php +++ b/app/code/Magento/Payment/Test/Unit/Observer/UpdateOrderStatusForPaymentMethodsObserverTest.php @@ -37,13 +37,19 @@ class UpdateOrderStatusForPaymentMethodsObserverTest extends \PHPUnit_Framework_ protected function setUp() { - $this->orderConfigMock = $this->getMock('Magento\Sales\Model\Order\Config', [], [], '', false); - $this->paymentConfigMock = $this->getMock('Magento\Payment\Model\Config', [], [], '', false); - $this->coreResourceConfigMock = $this->getMock('Magento\Config\Model\ResourceModel\Config', [], [], '', false); + $this->orderConfigMock = $this->getMock(\Magento\Sales\Model\Order\Config::class, [], [], '', false); + $this->paymentConfigMock = $this->getMock(\Magento\Payment\Model\Config::class, [], [], '', false); + $this->coreResourceConfigMock = $this->getMock( + \Magento\Config\Model\ResourceModel\Config::class, + [], + [], + '', + false + ); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->updateOrderStatusForPaymentMethodsObserver = $this->objectManagerHelper->getObject( - 'Magento\Payment\Observer\UpdateOrderStatusForPaymentMethodsObserver', + \Magento\Payment\Observer\UpdateOrderStatusForPaymentMethodsObserver::class, [ 'salesOrderConfig' => $this->orderConfigMock, 'paymentConfig' => $this->paymentConfigMock, @@ -52,7 +58,7 @@ protected function setUp() ); $this->observerMock = $this->getMockBuilder( - 'Magento\Framework\Event\Observer' + \Magento\Framework\Event\Observer::class )->disableOriginalConstructor()->setMethods([])->getMock(); } @@ -99,7 +105,7 @@ public function testUpdateOrderStatusForPaymentMethodsNewState() private function _prepareEventMockWithMethods($methodsList) { $this->eventMock = $this->getMockBuilder( - 'Magento\Framework\Event' + \Magento\Framework\Event::class )->disableOriginalConstructor()->setMethods($methodsList)->getMock(); $this->observerMock->expects($this->any())->method('getEvent')->will($this->returnValue($this->eventMock)); } @@ -112,7 +118,7 @@ private function _prepareEventMockWithMethods($methodsList) private function _getPreparedActiveMethods() { $method1 = $this->getMockBuilder( - 'Magento\Payment\Model\MethodInterface' + \Magento\Payment\Model\MethodInterface::class )->getMockForAbstractClass(); $method1->expects($this->once())->method('getConfigData')->with('order_status')->will( $this->returnValue(self::ORDER_STATUS) @@ -122,7 +128,7 @@ private function _getPreparedActiveMethods() ); $method2 = $this->getMockBuilder( - 'Magento\Payment\Model\MethodInterface' + \Magento\Payment\Model\MethodInterface::class )->getMockForAbstractClass(); $method2->expects($this->once())->method('getConfigData')->with('order_status')->will( $this->returnValue('not_a_status') diff --git a/app/code/Magento/Payment/etc/di.xml b/app/code/Magento/Payment/etc/di.xml index 73f8e2a76334b..c12c2d2cfd51c 100644 --- a/app/code/Magento/Payment/etc/di.xml +++ b/app/code/Magento/Payment/etc/di.xml @@ -6,6 +6,8 @@ */ --> + + diff --git a/app/code/Magento/Payment/view/adminhtml/web/transparent.js b/app/code/Magento/Payment/view/adminhtml/web/transparent.js index cf60a0dcee97c..b94e9bd4b2673 100644 --- a/app/code/Magento/Payment/view/adminhtml/web/transparent.js +++ b/app/code/Magento/Payment/view/adminhtml/web/transparent.js @@ -6,12 +6,14 @@ define([ 'jquery', 'mage/template', - 'Magento_Ui/js/modal/alert' + 'Magento_Ui/js/modal/alert', + 'Magento_Payment/js/model/credit-card-validation/validator' ], function ($, mageTemplate, alert) { 'use strict'; $.widget('mage.transparent', { options: { + editFormSelector: '#edit_form', hiddenFormTmpl: '
4) : c; + } + return !(d%10) + }; + } +); diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/cvv-validator.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/cvv-validator.js new file mode 100644 index 0000000000000..5688f50aa865b --- /dev/null +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/cvv-validator.js @@ -0,0 +1,41 @@ +/** + * Copyright © 2016 Magento. All rights reserved. + * See COPYING.txt for license details. + */ +/*jshint browser:true jquery:true*/ +/*global alert*/ +define( + [], + function() { + 'use strict'; + + function resultWrapper(isValid, isPotentiallyValid) { + return { + isValid: isValid, + isPotentiallyValid: isPotentiallyValid + }; + } + + /** + * CVV number validation + * validate digit count fot CVV code + */ + return function(value, maxLength) { + var DEFAULT_LENGTH = 3; + maxLength = maxLength || DEFAULT_LENGTH; + + if (!/^\d*$/.test(value)) { + return resultWrapper(false, false); + } + if (value.length === maxLength) { + return resultWrapper(true, true); + } + if (value.length < maxLength) { + return resultWrapper(false, true); + } + if (value.length > maxLength) { + return resultWrapper(false, false); + } + }; + } +); diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator.js new file mode 100644 index 0000000000000..6661a595b8bc2 --- /dev/null +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator.js @@ -0,0 +1,51 @@ +/** + * Copyright © 2016 Magento. All rights reserved. + * See COPYING.txt for license details. + */ +/*jshint browser:true jquery:true*/ +/*global alert*/ +define( + [ + 'mageUtils', + 'Magento_Payment/js/model/credit-card-validation/expiration-date-validator/parse-date', + 'Magento_Payment/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator', + 'Magento_Payment/js/model/credit-card-validation/expiration-date-validator/expiration-year-validator' + ], + function(utils, parseDate, expirationMonth, expirationYear) { + 'use strict'; + + function resultWrapper(isValid, isPotentiallyValid, month, year) { + return { + isValid: isValid, + isPotentiallyValid: isPotentiallyValid, + month: month, + year: year + }; + } + + return function(value) { + var date, + monthValid, + yearValid; + + if (utils.isEmpty(value)) { + return resultWrapper(false, false, null, null); + } + + value = value.replace(/^(\d\d) (\d\d(\d\d)?)$/, '$1/$2'); + date = parseDate(value); + monthValid = expirationMonth(date.month); + yearValid = expirationYear(date.year); + + if (monthValid.isValid && yearValid.isValid) { + return resultWrapper(true, true, date.month, date.year); + } + + if (monthValid.isPotentiallyValid && yearValid.isPotentiallyValid) { + return resultWrapper(false, true, null, null); + } + + return resultWrapper(false, false, null, null); + } + } +); diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator.js new file mode 100644 index 0000000000000..03b4ebcdec683 --- /dev/null +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator.js @@ -0,0 +1,41 @@ +/** + * Copyright © 2016 Magento. All rights reserved. + * See COPYING.txt for license details. + */ +/*jshint browser:true jquery:true*/ +/*global alert*/ +define( + [], + function () { + 'use strict'; + + function resultWrapper(isValid, isPotentiallyValid) { + return { + isValid: isValid, + isPotentiallyValid: isPotentiallyValid + }; + } + + return function (value) { + var month, + monthValid; + + if ((value.replace(/\s/g, '') === '') || (value === '0')) { + return resultWrapper(false, true); + } + + if (!/^\d*$/.test(value)) { + return resultWrapper(false, false); + } + + if (isNaN(value)) { + return resultWrapper(false, false); + } + + month = parseInt(value, 10); + monthValid = month > 0 && month < 13; + + return resultWrapper(monthValid, monthValid); + }; + } +); diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/expiration-year-validator.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/expiration-year-validator.js new file mode 100644 index 0000000000000..38494ccbe9c06 --- /dev/null +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/expiration-year-validator.js @@ -0,0 +1,42 @@ +/** + * Copyright © 2016 Magento. All rights reserved. + * See COPYING.txt for license details. + */ +/*jshint browser:true jquery:true*/ +/*global alert*/ +define( + [], + function() { + 'use strict'; + + function resultWrapper(isValid, isPotentiallyValid) { + return { + isValid: isValid, + isPotentiallyValid: isPotentiallyValid + }; + } + + return function(value) { + var currentYear = new Date().getFullYear(), + len = value.length, + valid, + expMaxLifetime = 19; + + if (value.replace(/\s/g, '') === '') { + return resultWrapper(false, true); + } + + if (!/^\d*$/.test(value)) { + return resultWrapper(false, false); + } + + if (len !== 4) { + return resultWrapper(false, true); + } + + value = parseInt(value, 10); + valid = value >= currentYear && value <= currentYear + expMaxLifetime; + return resultWrapper(valid, valid); + }; + } +); diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/parse-date.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/parse-date.js new file mode 100644 index 0000000000000..057eb1491f27c --- /dev/null +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/parse-date.js @@ -0,0 +1,32 @@ +/** + * Copyright © 2016 Magento. All rights reserved. + * See COPYING.txt for license details. + */ +/*jshint browser:true jquery:true*/ +/*global alert*/ +define( + [], + function() { + 'use strict'; + return function(value) { + var month, len; + + if (value.match('/')) { + value = value.split(/\s*\/\s*/g); + + return { + month: value[0], + year: value.slice(1).join() + }; + } + + len = (value[0] === '0' || value.length > 5 || value.length === 4 || value.length === 3) ? 2 : 1; + month = value.substr(0, len); + + return { + month: month, + year: value.substr(month.length, 4) + }; + } + } +); diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/validator.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/validator.js new file mode 100644 index 0000000000000..4a733dd155a22 --- /dev/null +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/validator.js @@ -0,0 +1,96 @@ +/** + * Copyright © 2016 Magento. All rights reserved. + * See COPYING.txt for license details. + */ +/*jshint browser:true jquery:true*/ +/*global alert*/ +(function (factory) { + if (typeof define === 'function' && define.amd) { + define([ + 'jquery', + 'Magento_Payment/js/model/credit-card-validation/cvv-validator', + 'Magento_Payment/js/model/credit-card-validation/credit-card-number-validator', + 'Magento_Payment/js/model/credit-card-validation/expiration-date-validator/expiration-year-validator', + 'Magento_Payment/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator', + 'Magento_Payment/js/model/credit-card-validation/credit-card-data', + 'mage/translate' + ], factory); + } else { + factory(jQuery); + } +}(function ($, cvvValidator, creditCardNumberValidator, expirationDateValidator, monthValidator, creditCardData) { + "use strict"; + + $.each({ + 'validate-card-type': [ + function (number, item, allowedTypes) { + var cardInfo, + i, + l; + + if (!creditCardNumberValidator(number).isValid) { + return false; + } else { + cardInfo = creditCardNumberValidator(number).card; + + for (i = 0, l = allowedTypes.length; i < l; i++) { + if (cardInfo.title == allowedTypes[i].type) { + return true; + } + } + return false; + } + }, + $.mage.__('Please enter a valid credit card type number.') + ], + 'validate-card-number': [ + /** + * Validate credit card number based on mod 10 + * @param number - credit card number + * @return {boolean} + */ + function (number) { + return creditCardNumberValidator(number).isValid; + }, + $.mage.__('Please enter a valid credit card number.') + ], + 'validate-card-date': [ + /** + * Validate credit card number based on mod 10 + * @param date - month + * @return {boolean} + */ + function (date) { + return monthValidator(date).isValid; + }, + $.mage.__('Incorrect credit card expiration month.') + ], + 'validate-card-cvv': [ + /** + * Validate credit card number based on mod 10 + * @param cvv - month + * @return {boolean} + */ + function (cvv) { + var maxLength = creditCardData.creditCard ? creditCardData.creditCard.code.size : 3; + return cvvValidator(cvv, maxLength).isValid; + }, + $.mage.__('Please enter a valid credit card verification number.') + ], + 'validate-card-year': [ + /** + * Validate credit card number based on mod 10 + * @param date - month + * @return {boolean} + */ + function (date) { + return monthValidator(date).isValid; + }, + $.mage.__('Incorrect credit card expiration year.') + ] + + }, function (i, rule) { + rule.unshift(i); + $.validator.addMethod.apply($.validator, rule); + }); +})); \ No newline at end of file diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/TransparentTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/TransparentTest.php index bbbb3ea187d18..259ec22b4b10f 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Payflow/TransparentTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Payflow/TransparentTest.php @@ -8,7 +8,7 @@ use Magento\Paypal\Model\Payflowpro; use Magento\Paypal\Model\Payflow\Transparent; use Magento\Vault\Api\Data\PaymentTokenInterface; -use Magento\Vault\Api\Data\PaymentTokenInterfaceFactory; +use Magento\Vault\Model\CreditCardTokenFactory; /** * Class TransparentTest @@ -49,7 +49,7 @@ class TransparentTest extends \PHPUnit_Framework_TestCase protected $addressShippingMock; /** - * @var PaymentTokenInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject + * @var CreditCardTokenFactory|\PHPUnit_Framework_MockObject_MockObject */ protected $paymentTokenFactory; @@ -66,7 +66,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->paymentTokenFactory = $this->getMockBuilder('\Magento\Vault\Api\Data\PaymentTokenInterfaceFactory') + $this->paymentTokenFactory = $this->getMockBuilder(CreditCardTokenFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); diff --git a/app/code/Magento/Paypal/etc/adminhtml/di.xml b/app/code/Magento/Paypal/etc/adminhtml/di.xml index 0ae9d9569969d..186649b01a22f 100644 --- a/app/code/Magento/Paypal/etc/adminhtml/di.xml +++ b/app/code/Magento/Paypal/etc/adminhtml/di.xml @@ -42,6 +42,7 @@ + Magento\Vault\Model\CreditCardTokenFactory Magento\Paypal\Block\Adminhtml\Payflowpro\CcForm diff --git a/app/code/Magento/Paypal/etc/di.xml b/app/code/Magento/Paypal/etc/di.xml index 8b287d08e77a4..ed390b5c6c7cd 100644 --- a/app/code/Magento/Paypal/etc/di.xml +++ b/app/code/Magento/Paypal/etc/di.xml @@ -176,4 +176,9 @@ + + + Magento\Vault\Model\CreditCardTokenFactory + + diff --git a/app/code/Magento/Sales/Model/Order.php b/app/code/Magento/Sales/Model/Order.php index bee30355e69e5..fde151914b92a 100644 --- a/app/code/Magento/Sales/Model/Order.php +++ b/app/code/Magento/Sales/Model/Order.php @@ -769,7 +769,7 @@ public function canReorderIgnoreSalable() */ protected function _canReorder($ignoreSalable = false) { - if ($this->canUnhold() || $this->isPaymentReview() || !$this->getCustomerId()) { + if ($this->canUnhold() || $this->isPaymentReview()) { return false; } diff --git a/app/code/Magento/Sales/Model/Order/Payment/State/AuthorizeCommand.php b/app/code/Magento/Sales/Model/Order/Payment/State/AuthorizeCommand.php index 67291b9372421..5bef05e6f28e0 100644 --- a/app/code/Magento/Sales/Model/Order/Payment/State/AuthorizeCommand.php +++ b/app/code/Magento/Sales/Model/Order/Payment/State/AuthorizeCommand.php @@ -10,6 +10,9 @@ use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Payment; +/** + * Class AuthorizeCommand + */ class AuthorizeCommand implements CommandInterface { /** @@ -23,29 +26,22 @@ public function execute(OrderPaymentInterface $payment, $amount, OrderInterface $state = Order::STATE_PROCESSING; $status = false; $formattedAmount = $order->getBaseCurrency()->formatTxt($amount); + if ($payment->getIsTransactionPending()) { $state = Order::STATE_PAYMENT_REVIEW; - $message = __( - 'We will authorize %1 after the payment is approved at the payment gateway.', - $formattedAmount - ); + $message = 'We will authorize %1 after the payment is approved at the payment gateway.'; } else { - if ($payment->getIsFraudDetected()) { - $state = Order::STATE_PROCESSING; - $message = __( - 'Order is suspended as its authorizing amount %1 is suspected to be fraudulent.', - $formattedAmount - ); - } else { - $message = __('Authorized amount of %1', $formattedAmount); - } + $message = 'Authorized amount of %1.'; } + if ($payment->getIsFraudDetected()) { + $state = Order::STATE_PAYMENT_REVIEW; $status = Order::STATUS_FRAUD; + $message .= ' Order is suspended as its authorizing amount %1 is suspected to be fraudulent.'; } $this->setOrderStateAndStatus($order, $status, $state); - return $message; + return __($message, $formattedAmount); } /** diff --git a/app/code/Magento/Sales/Model/Order/Payment/State/CaptureCommand.php b/app/code/Magento/Sales/Model/Order/Payment/State/CaptureCommand.php index 5639de4433f93..d2c7e2a7e71b3 100644 --- a/app/code/Magento/Sales/Model/Order/Payment/State/CaptureCommand.php +++ b/app/code/Magento/Sales/Model/Order/Payment/State/CaptureCommand.php @@ -9,6 +9,9 @@ use Magento\Sales\Api\Data\OrderPaymentInterface; use Magento\Sales\Model\Order as SalesOrder; +/** + * Class CaptureCommand + */ class CaptureCommand implements CommandInterface { /** @@ -24,22 +27,23 @@ public function execute(OrderPaymentInterface $payment, $amount, OrderInterface $state = SalesOrder::STATE_PROCESSING; $status = false; $formattedAmount = $order->getBaseCurrency()->formatTxt($amount); + if ($payment->getIsTransactionPending()) { - $message = __( - 'An amount of %1 will be captured after being approved at the payment gateway.', - $formattedAmount - ); $state = SalesOrder::STATE_PAYMENT_REVIEW; - if ($payment->getIsFraudDetected()) { - $status = SalesOrder::STATUS_FRAUD; - } + $message = 'An amount of %1 will be captured after being approved at the payment gateway.'; } else { // normal online capture: invoice is marked as "paid" - $message = __('Captured amount of %1 online', $formattedAmount); + $message = 'Captured amount of %1 online.'; + } + + if ($payment->getIsFraudDetected()) { + $state = SalesOrder::STATE_PAYMENT_REVIEW; + $status = SalesOrder::STATUS_FRAUD; + $message .= ' Order is suspended as its capturing amount %1 is suspected to be fraudulent.'; } $this->setOrderStateAndStatus($order, $status, $state); - return $message; + return __($message, $formattedAmount); } /** diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/AuthorizeCommandTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/AuthorizeCommandTest.php new file mode 100644 index 0000000000000..ae75fcb8ee2b0 --- /dev/null +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/AuthorizeCommandTest.php @@ -0,0 +1,213 @@ +currency = $this->getMockBuilder(Currency::class) + ->disableOriginalConstructor() + ->setMethods(['formatTxt']) + ->getMock(); + + $this->config = $this->getMockBuilder(Config::class) + ->disableOriginalConstructor() + ->setMethods(['getStateDefaultStatus']) + ->getMock(); + + $this->payment = $this->getMockBuilder(Payment::class) + ->disableOriginalConstructor() + ->setMethods(['getIsTransactionPending', 'getIsFraudDetected']) + ->getMock(); + $this->order = $this->getMockBuilder(Order::class) + ->disableOriginalConstructor() + ->setMethods(['getBaseCurrency', 'getConfig', 'setState', 'setStatus']) + ->getMock(); + + $this->order->expects(static::once()) + ->method('getBaseCurrency') + ->willReturn($this->currency); + $this->currency->expects(static::once()) + ->method('formatTxt') + ->with($this->amount) + ->willReturn($this->amount); + + $this->command = new AuthorizeCommand(); + } + + /** + * @covers \Magento\Sales\Model\Order\Payment\State\AuthorizeCommand::execute + */ + public function testExecute() + { + $message = __('Authorized amount of %1.', $this->amount); + + $this->payment->expects(static::once()) + ->method('getIsTransactionPending') + ->willReturn(false); + $this->payment->expects(static::once()) + ->method('getIsFraudDetected') + ->willReturn(false); + + $this->order->expects(static::once()) + ->method('getConfig') + ->willReturn($this->config); + $this->config->expects(static::once()) + ->method('getStateDefaultStatus') + ->with(Order::STATE_PROCESSING) + ->willReturn(Order::STATE_PROCESSING); + + $this->order->expects(static::once()) + ->method('setState') + ->with(Order::STATE_PROCESSING) + ->willReturnSelf(); + $this->order->expects(static::once()) + ->method('setStatus') + ->with(Order::STATE_PROCESSING); + + $actual = $this->command->execute($this->payment, $this->amount, $this->order); + static::assertEquals($message, $actual); + } + + /** + * @covers \Magento\Sales\Model\Order\Payment\State\AuthorizeCommand::execute + */ + public function testExecutePendingTransaction() + { + $message = __('We will authorize %1 after the payment is approved at the payment gateway.', $this->amount); + + $this->payment->expects(static::once()) + ->method('getIsTransactionPending') + ->willReturn(true); + $this->payment->expects(static::once()) + ->method('getIsFraudDetected') + ->willReturn(false); + + $this->order->expects(static::once()) + ->method('getConfig') + ->willReturn($this->config); + $this->config->expects(static::once()) + ->method('getStateDefaultStatus') + ->with(Order::STATE_PAYMENT_REVIEW) + ->willReturn(Order::STATE_PAYMENT_REVIEW); + + $this->order->expects(static::once()) + ->method('setState') + ->with(Order::STATE_PAYMENT_REVIEW) + ->willReturnSelf(); + $this->order->expects(static::once()) + ->method('setStatus') + ->with(Order::STATE_PAYMENT_REVIEW); + + $actual = $this->command->execute($this->payment, $this->amount, $this->order); + static::assertEquals($message, $actual); + } + + /** + * @covers \Magento\Sales\Model\Order\Payment\State\AuthorizeCommand::execute + */ + public function testExecutePendingTransactionFraud() + { + $expectedMessage = 'We will authorize %1 after the payment is approved at the payment gateway. '; + $expectedMessage .= 'Order is suspended as its authorizing amount %1 is suspected to be fraudulent.'; + $message = __($expectedMessage, $this->amount); + + $this->payment->expects(static::once()) + ->method('getIsTransactionPending') + ->willReturn(true); + $this->payment->expects(static::once()) + ->method('getIsFraudDetected') + ->willReturn(true); + + $this->order->expects(static::never()) + ->method('getConfig'); + + $this->order->expects(static::once()) + ->method('setState') + ->with(Order::STATE_PAYMENT_REVIEW) + ->willReturnSelf(); + $this->order->expects(static::once()) + ->method('setStatus') + ->with(Order::STATUS_FRAUD); + + $actual = $this->command->execute($this->payment, $this->amount, $this->order); + static::assertEquals($message, $actual); + } + + /** + * @covers \Magento\Sales\Model\Order\Payment\State\AuthorizeCommand::execute + */ + public function testExecuteFraud() + { + $message = __( + 'Authorized amount of %1. Order is suspended as its authorizing amount %1 is suspected to be fraudulent.', + $this->amount + ); + + $this->payment->expects(static::once()) + ->method('getIsTransactionPending') + ->willReturn(false); + $this->payment->expects(static::once()) + ->method('getIsFraudDetected') + ->willReturn(true); + + $this->order->expects(static::never()) + ->method('getConfig'); + + $this->order->expects(static::once()) + ->method('setState') + ->with(Order::STATE_PAYMENT_REVIEW) + ->willReturnSelf(); + $this->order->expects(static::once()) + ->method('setStatus') + ->with(Order::STATUS_FRAUD); + + $actual = $this->command->execute($this->payment, $this->amount, $this->order); + static::assertEquals($message, $actual); + } +} diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/CaptureCommandTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/CaptureCommandTest.php new file mode 100644 index 0000000000000..50ddfe7132564 --- /dev/null +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/State/CaptureCommandTest.php @@ -0,0 +1,211 @@ +currency = $this->getMockBuilder(Currency::class) + ->disableOriginalConstructor() + ->setMethods(['formatTxt']) + ->getMock(); + + $this->config = $this->getMockBuilder(Config::class) + ->disableOriginalConstructor() + ->setMethods(['getStateDefaultStatus']) + ->getMock(); + + $this->payment = $this->getMockBuilder(Payment::class) + ->disableOriginalConstructor() + ->setMethods(['getIsTransactionPending', 'getIsFraudDetected']) + ->getMock(); + $this->order = $this->getMockBuilder(Order::class) + ->disableOriginalConstructor() + ->setMethods(['getBaseCurrency', 'getConfig', 'setState', 'setStatus']) + ->getMock(); + + $this->order->expects(static::once()) + ->method('getBaseCurrency') + ->willReturn($this->currency); + $this->currency->expects(static::once()) + ->method('formatTxt') + ->with($this->amount) + ->willReturn($this->amount); + + $this->command = new CaptureCommand(); + } + + /** + * @covers \Magento\Sales\Model\Order\Payment\State\CaptureCommand::execute + */ + public function testExecute() + { + $message = __('Captured amount of %1 online.', $this->amount); + + $this->payment->expects(static::once()) + ->method('getIsTransactionPending') + ->willReturn(false); + $this->payment->expects(static::once()) + ->method('getIsFraudDetected') + ->willReturn(false); + + $this->order->expects(static::once()) + ->method('getConfig') + ->willReturn($this->config); + $this->config->expects(static::once()) + ->method('getStateDefaultStatus') + ->with(Order::STATE_PROCESSING) + ->willReturn(Order::STATE_PROCESSING); + + $this->order->expects(static::once()) + ->method('setState') + ->with(Order::STATE_PROCESSING) + ->willReturnSelf(); + $this->order->expects(static::once()) + ->method('setStatus') + ->with(Order::STATE_PROCESSING); + + $actual = $this->command->execute($this->payment, $this->amount, $this->order); + static::assertEquals($message, $actual); + } + + /** + * @covers \Magento\Sales\Model\Order\Payment\State\CaptureCommand::execute + */ + public function testExecutePendingTransaction() + { + $message = __('An amount of %1 will be captured after being approved at the payment gateway.', $this->amount); + + $this->payment->expects(static::once()) + ->method('getIsTransactionPending') + ->willReturn(true); + $this->payment->expects(static::once()) + ->method('getIsFraudDetected') + ->willReturn(false); + + $this->order->expects(static::once()) + ->method('getConfig') + ->willReturn($this->config); + $this->config->expects(static::once()) + ->method('getStateDefaultStatus') + ->with(Order::STATE_PAYMENT_REVIEW) + ->willReturn(Order::STATE_PAYMENT_REVIEW); + + $this->order->expects(static::once()) + ->method('setState') + ->with(Order::STATE_PAYMENT_REVIEW) + ->willReturnSelf(); + $this->order->expects(static::once()) + ->method('setStatus') + ->with(Order::STATE_PAYMENT_REVIEW); + + $actual = $this->command->execute($this->payment, $this->amount, $this->order); + static::assertEquals($message, $actual); + } + + /** + * @covers \Magento\Sales\Model\Order\Payment\State\CaptureCommand::execute + */ + public function testExecutePendingTransactionFraud() + { + $expectedMessage = 'An amount of %1 will be captured after being approved at the payment gateway. '; + $expectedMessage .= 'Order is suspended as its capturing amount %1 is suspected to be fraudulent.'; + $message = __($expectedMessage, $this->amount); + + $this->payment->expects(static::once()) + ->method('getIsTransactionPending') + ->willReturn(true); + $this->payment->expects(static::once()) + ->method('getIsFraudDetected') + ->willReturn(true); + + $this->order->expects(static::never()) + ->method('getConfig'); + + $this->order->expects(static::once()) + ->method('setState') + ->with(Order::STATE_PAYMENT_REVIEW) + ->willReturnSelf(); + $this->order->expects(static::once()) + ->method('setStatus') + ->with(Order::STATUS_FRAUD); + + $actual = $this->command->execute($this->payment, $this->amount, $this->order); + static::assertEquals($message, $actual); + } + + /** + * @covers \Magento\Sales\Model\Order\Payment\State\CaptureCommand::execute + */ + public function testExecuteFraud() + { + $expectedMessage = 'Captured amount of %1 online. '; + $expectedMessage .= 'Order is suspended as its capturing amount %1 is suspected to be fraudulent.'; + $message = __($expectedMessage, $this->amount); + + $this->payment->expects(static::once()) + ->method('getIsTransactionPending') + ->willReturn(false); + $this->payment->expects(static::once()) + ->method('getIsFraudDetected') + ->willReturn(true); + + $this->order->expects(static::never()) + ->method('getConfig'); + + $this->order->expects(static::once()) + ->method('setState') + ->with(Order::STATE_PAYMENT_REVIEW) + ->willReturnSelf(); + $this->order->expects(static::once()) + ->method('setStatus') + ->with(Order::STATUS_FRAUD); + + $actual = $this->command->execute($this->payment, $this->amount, $this->order); + static::assertEquals($message, $actual); + } +} diff --git a/app/code/Magento/Sales/Test/Unit/Model/OrderTest.php b/app/code/Magento/Sales/Test/Unit/Model/OrderTest.php index 399092745977a..dbce9d875e3da 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/OrderTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/OrderTest.php @@ -5,8 +5,12 @@ */ namespace Magento\Sales\Test\Unit\Model; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Catalog\Api\ProductRepositoryInterface; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Sales\Model\Order; use Magento\Sales\Model\ResourceModel\Order\Status\History\CollectionFactory as HistoryCollectionFactory; +use Magento\Sales\Model\ResourceModel\Order\Item; /** * Test class for \Magento\Sales\Model\Order @@ -63,6 +67,11 @@ class OrderTest extends \PHPUnit_Framework_TestCase */ protected $salesOrderCollectionMock; + /** + * @var ProductRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $productRepository; + protected function setUp() { $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); @@ -101,6 +110,17 @@ protected function setUp() '', false ); + $this->item = $this->getMockBuilder(Item::class) + ->disableOriginalConstructor() + ->setMethods([ + 'isDeleted', + 'getQtyToInvoice', + 'getParentItemId', + 'getQuoteItemId', + 'getLockedDoInvoice', + 'getProductId' + ]) + ->getMock(); $this->salesOrderCollectionMock = $this->getMockBuilder('Magento\Sales\Model\ResourceModel\Order\Collection') ->disableOriginalConstructor() ->setMethods(['addFieldToFilter', 'load', 'getFirstItem']) @@ -112,6 +132,9 @@ protected function setUp() $collection->expects($this->any()) ->method('getItems') ->willReturn([$this->item]); + $collection->expects(self::any()) + ->method('getIterator') + ->willReturn(new \ArrayIterator([$this->item])); $this->orderItemCollectionFactoryMock->expects($this->any()) ->method('create') ->willReturn($collection); @@ -126,6 +149,9 @@ protected function setUp() ['round'] ); + $this->productRepository = $this->getMockBuilder(ProductRepositoryInterface::class) + ->getMockForAbstractClass(); + $this->incrementId = '#00000001'; $this->eventManager = $this->getMock('Magento\Framework\Event\Manager', [], [], '', false); $context = $this->getMock('Magento\Framework\Model\Context', ['getEventDispatcher'], [], '', false); @@ -142,7 +168,8 @@ protected function setUp() 'context' => $context, 'historyCollectionFactory' => $this->historyCollectionFactoryMock, 'salesOrderCollectionFactory' => $this->salesOrderCollectionFactoryMock, - 'priceCurrency' => $this->priceCurrency + 'priceCurrency' => $this->priceCurrency, + 'productRepository' => $this->productRepository ] ); } @@ -368,6 +395,113 @@ public function testCanEditIfHasInvoices() $this->assertFalse($this->order->canEdit()); } + /** + * @covers \Magento\Sales\Model\Order::canReorder + */ + public function testCanReorder() + { + $productId = 1; + + $this->order->setState(Order::STATE_PROCESSING); + $this->order->setActionFlag(Order::ACTION_FLAG_REORDER, true); + + $this->item->expects(static::once()) + ->method('getProductId') + ->willReturn($productId); + + $product = $this->getMockBuilder(ProductInterface::class) + ->setMethods(['isSalable']) + ->getMockForAbstractClass(); + $product->expects(static::once()) + ->method('isSalable') + ->willReturn(true); + + $this->productRepository->expects(static::once()) + ->method('getById') + ->with($productId, false) + ->willReturn($product); + + $this->assertTrue($this->order->canReorder()); + } + + /** + * @covers \Magento\Sales\Model\Order::canReorder + */ + public function testCanReorderIsPaymentReview() + { + $this->order->setState(Order::STATE_PAYMENT_REVIEW); + + $this->assertFalse($this->order->canReorder()); + } + + /** + * @covers \Magento\Sales\Model\Order::canReorder + */ + public function testCanReorderFlagReorderFalse() + { + $this->order->setState(Order::STATE_PROCESSING); + $this->order->setActionFlag(Order::ACTION_FLAG_REORDER, false); + + $this->assertFalse($this->order->canReorder()); + } + + /** + * @covers \Magento\Sales\Model\Order::canReorder + */ + public function testCanReorderProductNotExists() + { + $productId = 1; + + $this->order->setState(Order::STATE_PROCESSING); + $this->order->setActionFlag(Order::ACTION_FLAG_REORDER, true); + + $this->item->expects(static::once()) + ->method('getProductId') + ->willReturn($productId); + + $product = $this->getMockBuilder(ProductInterface::class) + ->setMethods(['isSalable']) + ->getMockForAbstractClass(); + $product->expects(static::never()) + ->method('isSalable'); + + $this->productRepository->expects(static::once()) + ->method('getById') + ->with($productId, false) + ->willThrowException(new NoSuchEntityException(__('Requested product doesn\'t exist'))); + + $this->assertFalse($this->order->canReorder()); + } + + /** + * @covers \Magento\Sales\Model\Order::canReorder + */ + public function testCanReorderProductNotSalable() + { + $productId = 1; + + $this->order->setState(Order::STATE_PROCESSING); + $this->order->setActionFlag(Order::ACTION_FLAG_REORDER, true); + + $this->item->expects(static::once()) + ->method('getProductId') + ->willReturn($productId); + + $product = $this->getMockBuilder(ProductInterface::class) + ->setMethods(['isSalable']) + ->getMockForAbstractClass(); + $product->expects(static::once()) + ->method('isSalable') + ->willReturn(false); + + $this->productRepository->expects(static::once()) + ->method('getById') + ->with($productId, false) + ->willReturn($product); + + $this->assertFalse($this->order->canReorder()); + } + public function testCanCancelCanReviewPayment() { $paymentMock = $this->getMockBuilder('Magento\Sales\Model\ResourceModel\Order\Payment') diff --git a/app/code/Magento/Sales/i18n/en_US.csv b/app/code/Magento/Sales/i18n/en_US.csv index 9eb38b8488025..b285a2fa33202 100644 --- a/app/code/Magento/Sales/i18n/en_US.csv +++ b/app/code/Magento/Sales/i18n/en_US.csv @@ -352,10 +352,14 @@ Mixed,Mixed "The payment disallows storing objects.","The payment disallows storing objects." "The transaction ""%1"" cannot be captured yet.","The transaction ""%1"" cannot be captured yet." "We will authorize %1 after the payment is approved at the payment gateway.","We will authorize %1 after the payment is approved at the payment gateway." +"We will authorize %1 after the payment is approved at the payment gateway. Order is suspended as its authorizing amount %1 is suspected to be fraudulent.","We will authorize %1 after the payment is approved at the payment gateway. Order is suspended as its authorizing amount %1 is suspected to be fraudulent." "Order is suspended as its authorizing amount %1 is suspected to be fraudulent.","Order is suspended as its authorizing amount %1 is suspected to be fraudulent." -"Authorized amount of %1","Authorized amount of %1" +"Authorized amount of %1.","Authorized amount of %1." +"Authorized amount of %1. Order is suspended as its authorizing amount %1 is suspected to be fraudulent.","Authorized amount of %1. Order is suspended as its authorizing amount %1 is suspected to be fraudulent." "An amount of %1 will be captured after being approved at the payment gateway.","An amount of %1 will be captured after being approved at the payment gateway." -"Captured amount of %1 online","Captured amount of %1 online" +"An amount of %1 will be captured after being approved at the payment gateway. Order is suspended as its authorizing amount %1 is suspected to be fraudulent.","An amount of %1 will be captured after being approved at the payment gateway. Order is suspended as its authorizing amount %1 is suspected to be fraudulent." +"Captured amount of %1 online.","Captured amount of %1 online." +"Captured amount of %1 online. Order is suspended as its authorizing amount %1 is suspected to be fraudulent.","Captured amount of %1 online. Order is suspended as its authorizing amount %1 is suspected to be fraudulent." "The order amount of %1 is pending approval on the payment gateway.","The order amount of %1 is pending approval on the payment gateway." "Ordered amount of %1","Ordered amount of %1" "Registered notification about captured amount of %1.","Registered notification about captured amount of %1." diff --git a/app/code/Magento/Ui/Component/Filters/Type/Date.php b/app/code/Magento/Ui/Component/Filters/Type/Date.php index f670f826e4e20..f5d392ea51365 100644 --- a/app/code/Magento/Ui/Component/Filters/Type/Date.php +++ b/app/code/Magento/Ui/Component/Filters/Type/Date.php @@ -23,6 +23,13 @@ class Date extends AbstractFilter */ protected $wrappedComponent; + /** + * Date format + * + * @var string + */ + protected static $dateFormat = 'Y-m-d H:i:s'; + /** * Prepare component configuration * @@ -96,7 +103,7 @@ protected function applyFilterByType($type, $value) if (!empty($value)) { $filter = $this->filterBuilder->setConditionType($type) ->setField($this->getName()) - ->setValue($value->format('Y-m-d H:i:s')) + ->setValue($value->format(static::$dateFormat)) ->create(); $this->getContext()->getDataProvider()->addFilter($filter); diff --git a/app/code/Magento/Vault/Api/Data/PaymentTokenInterfaceFactory.php b/app/code/Magento/Vault/Api/Data/PaymentTokenInterfaceFactory.php new file mode 100644 index 0000000000000..2969eca4f5eba --- /dev/null +++ b/app/code/Magento/Vault/Api/Data/PaymentTokenInterfaceFactory.php @@ -0,0 +1,25 @@ +iconsProvider = $iconsProvider; } - /** - * Renders specified token - * - * @param PaymentTokenInterface $token - * @return string - */ - public function render(PaymentTokenInterface $token) - { - $this->token = $token; - $this->tokenDetails = json_decode($this->getToken()->getTokenDetails() ?: '{}', true); - $result = $this->toHtml(); - $this->token = null; - $this->tokenDetails = null; - - return $result; - } - - /** - * @return PaymentTokenInterface - */ - public function getToken() - { - return $this->token; - } - - /** - * @return array - */ - protected function getTokenDetails() - { - return $this->tokenDetails; - } - /** * @param string $type * @return array diff --git a/app/code/Magento/Vault/Block/AbstractTokenRenderer.php b/app/code/Magento/Vault/Block/AbstractTokenRenderer.php new file mode 100644 index 0000000000000..15df2e772a342 --- /dev/null +++ b/app/code/Magento/Vault/Block/AbstractTokenRenderer.php @@ -0,0 +1,56 @@ +token = $token; + $this->tokenDetails = json_decode($this->getToken()->getTokenDetails() ?: '{}', true); + return $this->toHtml(); + } + + /** + * @return PaymentTokenInterface|null + */ + public function getToken() + { + return $this->token; + } + + /** + * @return array|null + */ + protected function getTokenDetails() + { + return $this->tokenDetails; + } +} diff --git a/app/code/Magento/Vault/Block/CardRendererInterface.php b/app/code/Magento/Vault/Block/CardRendererInterface.php index e94354ba72c4e..65e6ad6424b86 100644 --- a/app/code/Magento/Vault/Block/CardRendererInterface.php +++ b/app/code/Magento/Vault/Block/CardRendererInterface.php @@ -5,13 +5,13 @@ */ namespace Magento\Vault\Block; -use Magento\Vault\Api\Data\PaymentTokenInterface; +use Magento\Vault\Block\Customer\IconInterface; /** * Interface CardRendererInterface * @api */ -interface CardRendererInterface extends TokenRendererInterface +interface CardRendererInterface extends TokenRendererInterface, IconInterface { /** * @return string @@ -22,24 +22,4 @@ public function getNumberLast4Digits(); * @return string */ public function getExpDate(); - - /** - * @return string - */ - public function getIconUrl(); - - /** - * @return int - */ - public function getIconHeight(); - - /** - * @return int - */ - public function getIconWidth(); - - /** - * @return PaymentTokenInterface - */ - public function getToken(); } diff --git a/app/code/Magento/Vault/Block/Customer/AccountTokens.php b/app/code/Magento/Vault/Block/Customer/AccountTokens.php new file mode 100644 index 0000000000000..37fd5f33bd54d --- /dev/null +++ b/app/code/Magento/Vault/Block/Customer/AccountTokens.php @@ -0,0 +1,22 @@ +customerTokenManagement = $customerTokenManagement; + } + + /** + * Get type of token + * @return string + */ + abstract function getType(); + + /** + * @return PaymentTokenInterface[] + */ + public function getPaymentTokens() + { + $tokens = []; + /** @var PaymentTokenInterface $token */ + foreach ($this->getCustomerTokens() as $token) { + if ($token->getType() === $this->getType()) { + $tokens[] = $token; + } + }; + return $tokens; + } + + /** + * @param PaymentTokenInterface $token + * @return string + */ + public function renderTokenHtml(PaymentTokenInterface $token) + { + foreach ($this->getChildNames() as $childName) { + $childBlock = $this->getChildBlock($childName); + if ($childBlock instanceof TokenRendererInterface && $childBlock->canRender($token)) { + return $childBlock->render($token); + } + } + + return ''; + } + + /** + * Checks if customer tokens exists + * @return bool + */ + public function isExistsCustomerTokens() + { + return !empty($this->getCustomerTokens()); + } + + /** + * Get customer session tokens + * @return PaymentTokenInterface[] + */ + private function getCustomerTokens() + { + if (empty($this->customerTokens)) { + $this->customerTokens = $this->customerTokenManagement->getCustomerSessionTokens(); + } + return $this->customerTokens; + } +} diff --git a/app/code/Magento/Vault/Block/TokenRendererInterface.php b/app/code/Magento/Vault/Block/TokenRendererInterface.php index 62d3effc801a3..040790202c3f6 100644 --- a/app/code/Magento/Vault/Block/TokenRendererInterface.php +++ b/app/code/Magento/Vault/Block/TokenRendererInterface.php @@ -28,4 +28,10 @@ public function canRender(PaymentTokenInterface $token); * @return string */ public function render(PaymentTokenInterface $token); + + /** + * Get payment token + * @return PaymentTokenInterface|null + */ + public function getToken(); } diff --git a/app/code/Magento/Vault/Controller/Cards/DeleteAction.php b/app/code/Magento/Vault/Controller/Cards/DeleteAction.php index d1d12e541a09d..041fba82a6508 100644 --- a/app/code/Magento/Vault/Controller/Cards/DeleteAction.php +++ b/app/code/Magento/Vault/Controller/Cards/DeleteAction.php @@ -133,7 +133,7 @@ private function createErrorResponse($errorCode) private function createSuccessMessage() { $this->messageManager->addSuccessMessage( - __('Credit Card was successfully removed') + __('Stored Payment Method was successfully removed') ); return $this->_redirect('vault/cards/listaction'); } diff --git a/app/code/Magento/Vault/Controller/Cards/ListAction.php b/app/code/Magento/Vault/Controller/Cards/ListAction.php index 22d5666d21020..f4ad8f8487eba 100644 --- a/app/code/Magento/Vault/Controller/Cards/ListAction.php +++ b/app/code/Magento/Vault/Controller/Cards/ListAction.php @@ -41,7 +41,7 @@ public function __construct( public function execute() { $resultPage = $this->pageFactory->create(); - $resultPage->getConfig()->getTitle()->set(__('My Credit Cards')); + $resultPage->getConfig()->getTitle()->set(__('Stored Payment Methods')); return $resultPage; } diff --git a/app/code/Magento/Vault/Model/AbstractPaymentTokenFactory.php b/app/code/Magento/Vault/Model/AbstractPaymentTokenFactory.php new file mode 100644 index 0000000000000..24bd03d42bb20 --- /dev/null +++ b/app/code/Magento/Vault/Model/AbstractPaymentTokenFactory.php @@ -0,0 +1,43 @@ +objectManager = $objectManager; + } + + /** + * Create payment token entity + * @return PaymentTokenInterface + */ + public function create() + { + /** @var PaymentTokenInterface $paymentToken */ + $paymentToken = $this->objectManager->create(PaymentTokenInterface::class); + $paymentToken->setType($this->getType()); + return $paymentToken; + } +} diff --git a/app/code/Magento/Vault/Model/AccountPaymentTokenFactory.php b/app/code/Magento/Vault/Model/AccountPaymentTokenFactory.php new file mode 100644 index 0000000000000..553b922bf7387 --- /dev/null +++ b/app/code/Magento/Vault/Model/AccountPaymentTokenFactory.php @@ -0,0 +1,26 @@ +getVaultProvider()->canUseInternal(); + $isInternalAllowed = $this->getConfiguredValue('can_use_internal'); + // if config has't been specified for Vault, need to check payment provider option + if ($isInternalAllowed === null) { + return $this->getVaultProvider()->canUseInternal(); + } + return (bool) $isInternalAllowed; } /** @@ -452,19 +457,17 @@ public function capture(\Magento\Payment\Model\InfoInterface $payment, $amount) /** * @param OrderPaymentInterface $orderPayment * @return void - * @throws \LogicException */ private function attachTokenExtensionAttribute(OrderPaymentInterface $orderPayment) { $additionalInformation = $orderPayment->getAdditionalInformation(); - - if (empty($additionalInformation[PaymentTokenInterface::CUSTOMER_ID]) || - empty($additionalInformation[PaymentTokenInterface::PUBLIC_HASH]) - ) { - throw new \LogicException('Customer and public hash should be defined'); + if (empty($additionalInformation[PaymentTokenInterface::PUBLIC_HASH])) { + throw new \LogicException('Public hash should be defined'); } - $customerId = $additionalInformation[PaymentTokenInterface::CUSTOMER_ID]; + $customerId = isset($additionalInformation[PaymentTokenInterface::CUSTOMER_ID]) ? + $additionalInformation[PaymentTokenInterface::CUSTOMER_ID] : null; + $publicHash = $additionalInformation[PaymentTokenInterface::PUBLIC_HASH]; $paymentToken = $this->tokenManagement->getByPublicHash($publicHash, $customerId); @@ -579,7 +582,8 @@ public function assignData(\Magento\Framework\DataObject $data) */ public function isAvailable(\Magento\Quote\Api\Data\CartInterface $quote = null) { - return $this->getVaultProvider()->isAvailable($quote); + return $this->getVaultProvider()->isAvailable($quote) + && $this->config->getValue(self::$activeKey, $this->getStore() ?: ($quote ? $quote->getStoreId() : null)); } /** diff --git a/app/code/Magento/Vault/Model/PaymentMethodList.php b/app/code/Magento/Vault/Model/PaymentMethodList.php new file mode 100644 index 0000000000000..bec073df79711 --- /dev/null +++ b/app/code/Magento/Vault/Model/PaymentMethodList.php @@ -0,0 +1,78 @@ +instanceFactory = $instanceFactory; + $this->paymentMethodList = $paymentMethodList; + } + + /** + * @inheritdoc + */ + public function getList($storeId) + { + return $this->filterList($this->paymentMethodList->getList($storeId)); + } + + /** + * @inheritdoc + */ + public function getActiveList($storeId) + { + return $this->filterList($this->paymentMethodList->getActiveList($storeId)); + } + + /** + * Filter vault methods from payments + * @param PaymentMethodInterface[] $list + * @return VaultPaymentInterface[] + */ + private function filterList(array $list) + { + $paymentMethods = array_map( + function (PaymentMethodInterface $paymentMethod) { + return $this->instanceFactory->create($paymentMethod); + }, + $list + ); + + $availableMethods = array_filter( + $paymentMethods, + function (MethodInterface $methodInstance) { + return $methodInstance instanceof VaultPaymentInterface; + } + ); + return array_values($availableMethods); + } +} diff --git a/app/code/Magento/Vault/Model/PaymentTokenManagement.php b/app/code/Magento/Vault/Model/PaymentTokenManagement.php index 510dc4cea3162..f4a445b35fb34 100644 --- a/app/code/Magento/Vault/Model/PaymentTokenManagement.php +++ b/app/code/Magento/Vault/Model/PaymentTokenManagement.php @@ -128,26 +128,37 @@ public function getListByCustomerId($customerId) */ public function getVisibleAvailableTokens($customerId) { - $filters[] = $this->filterBuilder->setField(PaymentTokenInterface::CUSTOMER_ID) - ->setValue($customerId) - ->create(); - $filters[] = $this->filterBuilder->setField(PaymentTokenInterface::IS_VISIBLE) - ->setValue(1) - ->create(); - $filters[] = $this->filterBuilder->setField(PaymentTokenInterface::IS_ACTIVE) - ->setValue(1) - ->create(); - $filters[] = $this->filterBuilder->setField(PaymentTokenInterface::EXPIRES_AT) - ->setConditionType('gt') - ->setValue( - $this->dateTimeFactory->create( - 'now', - new \DateTimeZone('UTC') - )->format('Y-m-d 00:00:00') - ) - ->create(); - $searchCriteria = $this->searchCriteriaBuilder->addFilters($filters) - ->create(); + $customerFilter = [ + $this->filterBuilder->setField(PaymentTokenInterface::CUSTOMER_ID) + ->setValue($customerId) + ->create() + ]; + $visibleFilter = [ + $this->filterBuilder->setField(PaymentTokenInterface::IS_VISIBLE) + ->setValue(1) + ->create() + ]; + $isActiveFilter = [ + $this->filterBuilder->setField(PaymentTokenInterface::IS_ACTIVE) + ->setValue(1) + ->create() + ]; + $expiresAtFilter = [ + $this->filterBuilder->setField(PaymentTokenInterface::EXPIRES_AT) + ->setConditionType('gt') + ->setValue( + $this->dateTimeFactory->create( + 'now', + new \DateTimeZone('UTC') + )->format('Y-m-d 00:00:00') + ) + ->create() + ]; + $this->searchCriteriaBuilder->addFilters($customerFilter); + $this->searchCriteriaBuilder->addFilters($visibleFilter); + $this->searchCriteriaBuilder->addFilters($isActiveFilter); + // add filters to different filter groups in order to filter by AND expression + $searchCriteria = $this->searchCriteriaBuilder->addFilters($expiresAtFilter)->create(); return $this->paymentTokenRepository->getList($searchCriteria)->getItems(); } diff --git a/app/code/Magento/Vault/Model/ResourceModel/PaymentToken/Collection.php b/app/code/Magento/Vault/Model/ResourceModel/PaymentToken/Collection.php index 0e6264ca90e5b..6ac1c8ae342d4 100644 --- a/app/code/Magento/Vault/Model/ResourceModel/PaymentToken/Collection.php +++ b/app/code/Magento/Vault/Model/ResourceModel/PaymentToken/Collection.php @@ -5,10 +5,14 @@ */ namespace Magento\Vault\Model\ResourceModel\PaymentToken; +use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection; +use Magento\Vault\Model\PaymentToken; +use Magento\Vault\Model\ResourceModel\PaymentToken as ResourcePaymentToken; + /** * Vault Payment Tokens collection */ -class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection +class Collection extends AbstractCollection { /** * Resource initialization @@ -17,6 +21,6 @@ class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\Ab */ public function _construct() { - $this->_init('Magento\Vault\Model\PaymentToken', 'Magento\Vault\Model\ResourceModel\PaymentToken'); + $this->_init(PaymentToken::class, ResourcePaymentToken::class); } } diff --git a/app/code/Magento/Vault/Model/Ui/Adminhtml/TokensConfigProvider.php b/app/code/Magento/Vault/Model/Ui/Adminhtml/TokensConfigProvider.php index 81fb24d14bcbd..f3a2cbfa78739 100644 --- a/app/code/Magento/Vault/Model/Ui/Adminhtml/TokensConfigProvider.php +++ b/app/code/Magento/Vault/Model/Ui/Adminhtml/TokensConfigProvider.php @@ -8,11 +8,15 @@ use Magento\Framework\Api\FilterBuilder; use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\App\ObjectManager; +use Magento\Framework\Exception\InputException; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\Intl\DateTimeFactory; use Magento\Framework\Session\SessionManagerInterface; use Magento\Payment\Helper\Data; +use Magento\Sales\Api\OrderRepositoryInterface; use Magento\Store\Model\StoreManagerInterface; use Magento\Vault\Api\Data\PaymentTokenInterface; +use Magento\Vault\Api\PaymentTokenManagementInterface; use Magento\Vault\Api\PaymentTokenRepositoryInterface; use Magento\Vault\Model\Ui\TokenUiComponentInterface; use Magento\Vault\Model\Ui\TokenUiComponentProviderInterface; @@ -65,6 +69,16 @@ final class TokensConfigProvider */ private $paymentDataHelper; + /** + * @var OrderRepositoryInterface + */ + private $orderRepository; + + /** + * @var PaymentTokenManagementInterface + */ + private $paymentTokenManagement; + /** * Constructor * @@ -103,9 +117,6 @@ public function getTokensComponents($vaultPaymentCode) $result = []; $customerId = $this->session->getCustomerId(); - if (!$customerId) { - return $result; - } $vaultPayment = $this->getVaultPayment($vaultPaymentCode); if ($vaultPayment === null) { @@ -118,26 +129,58 @@ public function getTokensComponents($vaultPaymentCode) return $result; } - $filters[] = $this->filterBuilder->setField(PaymentTokenInterface::CUSTOMER_ID) - ->setValue($customerId) - ->create(); - $filters[] = $this->filterBuilder->setField(PaymentTokenInterface::PAYMENT_METHOD_CODE) - ->setValue($vaultProviderCode) - ->create(); - $filters[] = $this->filterBuilder->setField(PaymentTokenInterface::IS_ACTIVE) - ->setValue(1) - ->create(); - $filters[] = $this->filterBuilder->setField(PaymentTokenInterface::EXPIRES_AT) - ->setConditionType('gt') - ->setValue( - $this->dateTimeFactory->create( - 'now', - new \DateTimeZone('UTC') - )->format('Y-m-d 00:00:00') - ) - ->create(); - $searchCriteria = $this->searchCriteriaBuilder->addFilters($filters) - ->create(); + if ($customerId) { + $this->searchCriteriaBuilder->addFilters( + [ + $this->filterBuilder->setField(PaymentTokenInterface::CUSTOMER_ID) + ->setValue($customerId) + ->create(), + ] + ); + } else { + try { + $this->searchCriteriaBuilder->addFilters( + [ + $this->filterBuilder->setField(PaymentTokenInterface::ENTITY_ID) + ->setValue($this->getPaymentTokenEntityId()) + ->create(), + ] + ); + } catch (InputException $e) { + return $result; + } catch (NoSuchEntityException $e) { + return $result; + } + } + $this->searchCriteriaBuilder->addFilters( + [ + $this->filterBuilder->setField(PaymentTokenInterface::PAYMENT_METHOD_CODE) + ->setValue($vaultProviderCode) + ->create(), + ] + ); + $this->searchCriteriaBuilder->addFilters( + [ + $this->filterBuilder->setField(PaymentTokenInterface::IS_ACTIVE) + ->setValue(1) + ->create(), + ] + ); + $this->searchCriteriaBuilder->addFilters( + [ + $this->filterBuilder->setField(PaymentTokenInterface::EXPIRES_AT) + ->setConditionType('gt') + ->setValue( + $this->dateTimeFactory->create( + 'now', + new \DateTimeZone('UTC') + )->format('Y-m-d 00:00:00') + ) + ->create(), + ] + ); + + $searchCriteria = $this->searchCriteriaBuilder->create(); foreach ($this->paymentTokenRepository->getList($searchCriteria)->getItems() as $token) { $result[] = $componentProvider->getComponentForToken($token); @@ -162,7 +205,7 @@ private function getComponentProvider($vaultProviderCode) /** * Get active vault payment by code - * @param $vaultPaymentCode + * @param string $vaultPaymentCode * @return VaultPaymentInterface|null */ private function getVaultPayment($vaultPaymentCode) @@ -172,6 +215,34 @@ private function getVaultPayment($vaultPaymentCode) return $vaultPayment->isActive($storeId) ? $vaultPayment : null; } + /** + * Returns payment token entity id by order payment id + * @return int|null + */ + private function getPaymentTokenEntityId() + { + $paymentToken = $this->getPaymentTokenManagement()->getByPaymentId($this->getOrderPaymentEntityId()); + if ($paymentToken === null) { + throw new NoSuchEntityException(__('No available payment tokens for specified order payment.')); + } + return $paymentToken->getEntityId(); + } + + /** + * Returns order payment entity id + * Using 'getReordered' for Reorder action + * Using 'getOrder' for Edit action + * @return int + */ + private function getOrderPaymentEntityId() + { + $orderId = $this->session->getReordered() + ?: $this->session->getOrder()->getEntityId(); + $order = $this->getOrderRepository()->get($orderId); + + return (int) $order->getPayment()->getEntityId(); + } + /** * Get payment data helper instance * @return Data @@ -184,4 +255,34 @@ private function getPaymentDataHelper() } return $this->paymentDataHelper; } + + /** + * Returns order repository instance + * @return OrderRepositoryInterface + * @deprecated + */ + private function getOrderRepository() + { + if ($this->orderRepository === null) { + $this->orderRepository = ObjectManager::getInstance() + ->get(OrderRepositoryInterface::class); + } + + return $this->orderRepository; + } + + /** + * Returns payment token management instance + * @return PaymentTokenManagementInterface + * @deprecated + */ + private function getPaymentTokenManagement() + { + if ($this->paymentTokenManagement === null) { + $this->paymentTokenManagement = ObjectManager::getInstance() + ->get(PaymentTokenManagementInterface::class); + } + + return $this->paymentTokenManagement; + } } diff --git a/app/code/Magento/Vault/Model/Ui/TokensConfigProvider.php b/app/code/Magento/Vault/Model/Ui/TokensConfigProvider.php index 434a5875b5bb1..40343c29620e1 100644 --- a/app/code/Magento/Vault/Model/Ui/TokensConfigProvider.php +++ b/app/code/Magento/Vault/Model/Ui/TokensConfigProvider.php @@ -7,10 +7,9 @@ use Magento\Checkout\Model\ConfigProviderInterface; use Magento\Framework\App\ObjectManager; -use Magento\Payment\Helper\Data; use Magento\Store\Model\StoreManagerInterface; +use Magento\Vault\Api\PaymentMethodListInterface; use Magento\Vault\Model\CustomerTokenManagement; -use Magento\Vault\Model\VaultPaymentInterface; /** * Class ConfigProvider @@ -39,9 +38,9 @@ final class TokensConfigProvider implements ConfigProviderInterface private $customerTokenManagement; /** - * @var Data + * @var PaymentMethodListInterface */ - private $paymentDataHelper; + private $vaultPaymentList; /** * Constructor @@ -84,8 +83,10 @@ public function getConfig() $componentProvider = $providers[$paymentCode]; $component = $componentProvider->getComponentForToken($token); - $vaultPayments[$paymentCode . '_item_' . $i] = [ - 'config' => $component->getConfig(), + $config = $component->getConfig(); + $vaultPaymentCode = !empty($config['code']) ? $config['code'] : $paymentCode; + $vaultPayments[$vaultPaymentCode . '_' . $i] = [ + 'config' => $config, 'component' => $component->getName() ]; } @@ -98,21 +99,17 @@ public function getConfig() } /** - * Get list of available vault ui token providers + * Get list of available vault ui token providers. + * * @return TokenUiComponentProviderInterface[] */ private function getComponentProviders() { $providers = []; $storeId = $this->storeManager->getStore()->getId(); - $paymentMethods = $this->getPaymentDataHelper()->getStoreMethods($storeId); + $vaultPaymentMethods = $this->getVaultPaymentList()->getActiveList($storeId); - foreach ($paymentMethods as $method) { - /** VaultPaymentInterface $method */ - if (!$method instanceof VaultPaymentInterface || !$method->isActive($storeId)) { - continue; - } - + foreach ($vaultPaymentMethods as $method) { $providerCode = $method->getProviderCode(); $componentProvider = $this->getComponentProvider($providerCode); if ($componentProvider === null) { @@ -139,15 +136,15 @@ private function getComponentProvider($vaultProviderCode) } /** - * Get payment data helper instance - * @return Data + * Get instance of vault payment list instance + * @return PaymentMethodListInterface * @deprecated */ - private function getPaymentDataHelper() + private function getVaultPaymentList() { - if ($this->paymentDataHelper === null) { - $this->paymentDataHelper = ObjectManager::getInstance()->get(Data::class); + if ($this->vaultPaymentList === null) { + $this->vaultPaymentList = ObjectManager::getInstance()->get(PaymentMethodListInterface::class); } - return $this->paymentDataHelper; + return $this->vaultPaymentList; } } diff --git a/app/code/Magento/Vault/Model/Ui/VaultConfigProvider.php b/app/code/Magento/Vault/Model/Ui/VaultConfigProvider.php index 8bf88e7a94f50..bc3110a101452 100644 --- a/app/code/Magento/Vault/Model/Ui/VaultConfigProvider.php +++ b/app/code/Magento/Vault/Model/Ui/VaultConfigProvider.php @@ -8,9 +8,8 @@ use Magento\Checkout\Model\ConfigProviderInterface; use Magento\Framework\App\ObjectManager; use Magento\Framework\Session\SessionManagerInterface; -use Magento\Payment\Helper\Data; use Magento\Store\Model\StoreManagerInterface; -use Magento\Vault\Model\VaultPaymentInterface; +use Magento\Vault\Api\PaymentMethodListInterface; class VaultConfigProvider implements ConfigProviderInterface { @@ -32,9 +31,9 @@ class VaultConfigProvider implements ConfigProviderInterface private $session; /** - * @var Data + * @var PaymentMethodListInterface */ - private $paymentDataHelper; + private $vaultPaymentList; /** * VaultConfigProvider constructor. @@ -57,9 +56,9 @@ public function __construct( public function getConfig() { $availableMethods = []; - $vaultPayments = $this->getVaultPaymentMethodList(); - $customerId = $this->session->getCustomerId(); $storeId = $this->storeManager->getStore()->getId(); + $vaultPayments = $this->getVaultPaymentList()->getActiveList($storeId); + $customerId = $this->session->getCustomerId(); foreach ($vaultPayments as $method) { $availableMethods[$method->getCode()] = [ @@ -73,36 +72,15 @@ public function getConfig() } /** - * Get list of active Vault payment methods - * @return array - */ - private function getVaultPaymentMethodList() - { - $availableMethods = []; - $storeId = $this->storeManager->getStore()->getId(); - - $paymentMethods = $this->getPaymentDataHelper()->getStoreMethods($storeId); - foreach ($paymentMethods as $method) { - /** VaultPaymentInterface $method */ - if (!$method instanceof VaultPaymentInterface) { - continue; - } - $availableMethods[] = $method; - } - - return $availableMethods; - } - - /** - * Get payment data helper instance - * @return Data + * Get vault payment list instance + * @return PaymentMethodListInterface * @deprecated */ - private function getPaymentDataHelper() + private function getVaultPaymentList() { - if ($this->paymentDataHelper === null) { - $this->paymentDataHelper = ObjectManager::getInstance()->get(Data::class); + if ($this->vaultPaymentList === null) { + $this->vaultPaymentList = ObjectManager::getInstance()->get(PaymentMethodListInterface::class); } - return $this->paymentDataHelper; + return $this->vaultPaymentList; } } diff --git a/app/code/Magento/Vault/Observer/PaymentTokenAssigner.php b/app/code/Magento/Vault/Observer/PaymentTokenAssigner.php index 13ae2e8110f9f..7601d49b9fe84 100644 --- a/app/code/Magento/Vault/Observer/PaymentTokenAssigner.php +++ b/app/code/Magento/Vault/Observer/PaymentTokenAssigner.php @@ -57,10 +57,7 @@ public function execute(Observer $observer) } $quote = $paymentModel->getQuote(); - $customerId = $quote->getCustomer()->getId(); - if ($customerId === null) { - return; - } + $customerId = (int) $quote->getCustomer()->getId(); $paymentToken = $this->paymentTokenManagement->getByPublicHash($tokenPublicHash, $customerId); if ($paymentToken === null) { diff --git a/app/code/Magento/Vault/Plugin/PaymentVaultAttributesLoad.php b/app/code/Magento/Vault/Plugin/PaymentVaultAttributesLoad.php index 810a8c5242da8..710b765d11eff 100644 --- a/app/code/Magento/Vault/Plugin/PaymentVaultAttributesLoad.php +++ b/app/code/Magento/Vault/Plugin/PaymentVaultAttributesLoad.php @@ -10,6 +10,8 @@ use Magento\Sales\Api\Data\OrderPaymentExtensionInterface; use Magento\Sales\Api\Data\OrderPaymentInterface; use Magento\Vault\Api\PaymentTokenManagementInterface; +use Magento\Sales\Api\Data\OrderPaymentExtensionFactory; +use Magento\Vault\Api\Data\PaymentTokenInterface; /** * Plugin for loading vault payment extension attribute to order/payment entity @@ -17,7 +19,7 @@ class PaymentVaultAttributesLoad { /** - * @var \Magento\Sales\Api\Data\OrderPaymentExtensionFactory + * @var OrderPaymentExtensionFactory */ protected $paymentExtensionFactory; @@ -27,11 +29,11 @@ class PaymentVaultAttributesLoad protected $paymentTokenManagement; /** - * @param \Magento\Sales\Api\Data\OrderPaymentExtensionFactory $paymentExtensionFactory + * @param OrderPaymentExtensionFactory $paymentExtensionFactory * @param PaymentTokenManagement|PaymentTokenManagementInterface $paymentTokenManagement */ public function __construct( - \Magento\Sales\Api\Data\OrderPaymentExtensionFactory $paymentExtensionFactory, + OrderPaymentExtensionFactory $paymentExtensionFactory, PaymentTokenManagementInterface $paymentTokenManagement ) { $this->paymentExtensionFactory = $paymentExtensionFactory; @@ -42,16 +44,13 @@ public function __construct( * Load vault payment extension attribute to order/payment entity * * @param OrderPaymentInterface $payment - * @param \Closure $proceed + * @param OrderPaymentExtensionInterface|null $paymentExtension * @return OrderPaymentExtensionInterface */ - public function aroundGetExtensionAttributes( + public function afterGetExtensionAttributes( OrderPaymentInterface $payment, - \Closure $proceed + OrderPaymentExtensionInterface $paymentExtension = null ) { - /** @var OrderPaymentExtensionInterface $paymentExtension */ - $paymentExtension = $proceed(); - if ($paymentExtension === null) { $paymentExtension = $this->paymentExtensionFactory->create(); } @@ -59,7 +58,7 @@ public function aroundGetExtensionAttributes( $paymentToken = $paymentExtension->getVaultPaymentToken(); if ($paymentToken === null) { $paymentToken = $this->paymentTokenManagement->getByPaymentId($payment->getEntityId()); - if ($paymentToken instanceof \Magento\Vault\Api\Data\PaymentTokenInterface) { + if ($paymentToken instanceof PaymentTokenInterface) { $paymentExtension->setVaultPaymentToken($paymentToken); } $payment->setExtensionAttributes($paymentExtension); diff --git a/app/code/Magento/Vault/Setup/UpgradeData.php b/app/code/Magento/Vault/Setup/UpgradeData.php new file mode 100644 index 0000000000000..757b5f4d3167c --- /dev/null +++ b/app/code/Magento/Vault/Setup/UpgradeData.php @@ -0,0 +1,89 @@ +startSetup(); + $connection = $this->getConnection(); + + // data update for Vault module < 2.0.1 + if (version_compare($context->getVersion(), '2.0.1', '<')) { + // update sets credit card as default token type + $connection->update($setup->getTable(InstallSchema::PAYMENT_TOKEN_TABLE), [ + PaymentTokenInterface::TYPE => CreditCardTokenFactory::TOKEN_TYPE_CREDIT_CARD + ], PaymentTokenInterface::TYPE . ' = ""'); + } + + // data update for Vault module < 2.0.2 + if (version_compare($context->getVersion(), '2.0.2', '<')) { + // update converts additional info with token metadata to single dimensional array + $select = $connection->select() + ->from($setup->getTable('sales_order_payment'), 'entity_id') + ->columns(['additional_information']) + ->where('additional_information LIKE ?', '%token_metadata%'); + + $items = $connection->fetchAll($select); + foreach ($items as $item) { + $additionalInfo = unserialize($item['additional_information']); + $additionalInfo[PaymentTokenInterface::CUSTOMER_ID] = + $additionalInfo['token_metadata'][PaymentTokenInterface::CUSTOMER_ID]; + $additionalInfo[PaymentTokenInterface::PUBLIC_HASH] = + $additionalInfo['token_metadata'][PaymentTokenInterface::PUBLIC_HASH]; + unset($additionalInfo['token_metadata']); + + $connection->update( + $setup->getTable('sales_order_payment'), + ['additional_information' => serialize($additionalInfo)], + ['entity_id = ?' => $item['entity_id']] + ); + } + } + + $setup->endSetup(); + } + + /** + * Tries to get connection for scalable sales DB, otherwise returns default connection + * @return AdapterInterface + */ + private function getConnection() + { + if ($this->connection === null) { + /** @var ResourceConnection $conn */ + $conn = ObjectManager::getInstance()->get(ResourceConnection::class); + try { + $this->connection = $conn->getConnectionByName('sales'); + } catch (\DomainException $e) { + $this->connection = $conn->getConnection(); + } + } + + return $this->connection; + } +} diff --git a/app/code/Magento/Vault/Test/Unit/Block/Customer/AccountTokensTest.php b/app/code/Magento/Vault/Test/Unit/Block/Customer/AccountTokensTest.php new file mode 100644 index 0000000000000..d2de86c58c0b7 --- /dev/null +++ b/app/code/Magento/Vault/Test/Unit/Block/Customer/AccountTokensTest.php @@ -0,0 +1,73 @@ +objectManager = new ObjectManager($this); + + $this->tokenManagement = $this->getMockBuilder(CustomerTokenManagement::class) + ->disableOriginalConstructor() + ->setMethods(['getCustomerSessionTokens']) + ->getMock(); + + $this->block = $this->objectManager->getObject(AccountTokens::class, [ + 'customerTokenManagement' => $this->tokenManagement + ]); + } + + /** + * @covers \Magento\Vault\Block\Customer\AccountTokens::getPaymentTokens + */ + public function testGetPaymentTokens() + { + $cardToken = $this->objectManager->getObject(PaymentToken::class, [ + 'data' => [PaymentTokenInterface::TYPE => CreditCardTokenFactory::TOKEN_TYPE_CREDIT_CARD] + ]); + $token = $this->objectManager->getObject(PaymentToken::class, [ + 'data' => [PaymentTokenInterface::TYPE => AccountPaymentTokenFactory::TOKEN_TYPE_ACCOUNT] + ]); + $this->tokenManagement->expects(static::once()) + ->method('getCustomerSessionTokens') + ->willReturn([$cardToken, $token]); + + $actual = $this->block->getPaymentTokens(); + static::assertCount(1, $actual); + + /** @var PaymentTokenInterface $actualToken */ + $actualToken = array_pop($actual); + static::assertEquals(AccountPaymentTokenFactory::TOKEN_TYPE_ACCOUNT, $actualToken->getType()); + } +} diff --git a/app/code/Magento/Vault/Test/Unit/Model/AccountPaymentTokenFactoryTest.php b/app/code/Magento/Vault/Test/Unit/Model/AccountPaymentTokenFactoryTest.php new file mode 100644 index 0000000000000..ed764d2be1194 --- /dev/null +++ b/app/code/Magento/Vault/Test/Unit/Model/AccountPaymentTokenFactoryTest.php @@ -0,0 +1,59 @@ +paymentToken = $objectManager->getObject(PaymentToken::class); + + $this->objectManager = $this->getMock(ObjectManagerInterface::class); + $this->factory = new AccountPaymentTokenFactory($this->objectManager); + } + + /** + * @covers \Magento\Vault\Model\AccountPaymentTokenFactory::create + */ + public function testCreate() + { + $this->objectManager->expects(static::once()) + ->method('create') + ->willReturn($this->paymentToken); + + /** @var PaymentTokenInterface $paymentToken */ + $paymentToken = $this->factory->create(); + static::assertInstanceOf(PaymentTokenInterface::class, $paymentToken); + static::assertEquals(AccountPaymentTokenFactory::TOKEN_TYPE_ACCOUNT, $paymentToken->getType()); + } +} diff --git a/app/code/Magento/Vault/Test/Unit/Model/CreditCardTokenFactoryTest.php b/app/code/Magento/Vault/Test/Unit/Model/CreditCardTokenFactoryTest.php new file mode 100644 index 0000000000000..ed613283c9f14 --- /dev/null +++ b/app/code/Magento/Vault/Test/Unit/Model/CreditCardTokenFactoryTest.php @@ -0,0 +1,59 @@ +paymentToken = $objectManager->getObject(PaymentToken::class); + + $this->objectManager = $this->getMock(ObjectManagerInterface::class); + $this->factory = new CreditCardTokenFactory($this->objectManager); + } + + /** + * @covers \Magento\Vault\Model\CreditCardTokenFactory::create + */ + public function testCreate() + { + $this->objectManager->expects(static::once()) + ->method('create') + ->willReturn($this->paymentToken); + + /** @var PaymentTokenInterface $paymentToken */ + $paymentToken = $this->factory->create(); + static::assertInstanceOf(PaymentTokenInterface::class, $paymentToken); + static::assertEquals(CreditCardTokenFactory::TOKEN_TYPE_CREDIT_CARD, $paymentToken->getType()); + } +} diff --git a/app/code/Magento/Vault/Test/Unit/Model/Method/VaultTest.php b/app/code/Magento/Vault/Test/Unit/Model/Method/VaultTest.php index bc64636b8ff39..ade93c9367858 100644 --- a/app/code/Magento/Vault/Test/Unit/Model/Method/VaultTest.php +++ b/app/code/Magento/Vault/Test/Unit/Model/Method/VaultTest.php @@ -8,8 +8,12 @@ use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Payment\Gateway\Command\CommandManagerInterface; use Magento\Payment\Gateway\Command\CommandManagerPoolInterface; +use Magento\Payment\Gateway\Config\ValueHandlerInterface; +use Magento\Payment\Gateway\Config\ValueHandlerPoolInterface; +use Magento\Payment\Gateway\ConfigInterface; use Magento\Payment\Model\InfoInterface; use Magento\Payment\Model\MethodInterface; +use Magento\Quote\Api\Data\CartInterface; use Magento\Sales\Api\Data\OrderPaymentExtensionInterface; use Magento\Sales\Api\Data\TransactionInterface; use Magento\Sales\Model\Order\Payment; @@ -17,6 +21,7 @@ use Magento\Vault\Api\PaymentTokenManagementInterface; use Magento\Vault\Model\Method\Vault; use Magento\Vault\Model\VaultPaymentInterface; +use PHPUnit_Framework_MockObject_MockObject as MockObject; /** * Class VaultTest @@ -29,9 +34,15 @@ class VaultTest extends \PHPUnit_Framework_TestCase */ private $objectManager; + /** + * @var MethodInterface|MockObject + */ + private $vaultProvider; + public function setUp() { $this->objectManager = new ObjectManager($this); + $this->vaultProvider = $this->getMock(MethodInterface::class); } /** @@ -48,11 +59,12 @@ public function testAuthorizeNotOrderPayment() } /** + * @param array $additionalInfo * @expectedException \LogicException - * @expectedExceptionMessage Customer and public hash should be defined - * @dataProvider tokenMetadataProvider + * @expectedExceptionMessage Public hash should be defined + * @dataProvider additionalInfoDataProvider */ - public function testAuthorizeNoTokenMetadata($additionalInfo) + public function testAuthorizeNoTokenMetadata(array $additionalInfo) { $paymentModel = $this->getMockBuilder(Payment::class) ->disableOriginalConstructor() @@ -68,17 +80,15 @@ public function testAuthorizeNoTokenMetadata($additionalInfo) } /** - * Get list of variations + * Get list of additional information variations * @return array */ - public function tokenMetadataProvider() + public function additionalInfoDataProvider() { return [ ['additionalInfo' => []], + ['additionalInfo' => ['customer_id' => 1]], ['additionalInfo' => ['public_hash' => null]], - ['additionalInfo' => ['customer_id' => null]], - ['additionalInfo' => ['public_hash' => '1ds23', 'customer_id' => null]], - ['additionalInfo' => ['public_hash' => null, 'customer_id' => 1]], ]; } @@ -136,8 +146,6 @@ public function testAuthorize() $commandManagerPool = $this->getMock(CommandManagerPoolInterface::class); $commandManager = $this->getMock(CommandManagerInterface::class); - $vaultProvider = $this->getMock(MethodInterface::class); - $tokenManagement = $this->getMock(PaymentTokenManagementInterface::class); $token = $this->getMock(PaymentTokenInterface::class); @@ -160,7 +168,7 @@ public function testAuthorize() ->method('setVaultPaymentToken') ->with($token); - $vaultProvider->expects(static::atLeastOnce()) + $this->vaultProvider->expects(static::atLeastOnce()) ->method('getCode') ->willReturn($vaultProviderCode); $commandManagerPool->expects(static::once()) @@ -187,7 +195,7 @@ public function testAuthorize() [ 'tokenManagement' => $tokenManagement, 'commandManagerPool' => $commandManagerPool, - 'vaultProvider' => $vaultProvider + 'vaultProvider' => $this->vaultProvider ] ); $model->authorize($paymentModel, $amount); @@ -225,4 +233,129 @@ public function testCapture() $model = $this->objectManager->getObject(Vault::class); $model->capture($paymentModel, 0); } + + /** + * @covers \Magento\Vault\Model\Method\Vault::isAvailable + * @dataProvider isAvailableDataProvider + */ + public function testIsAvailable($isAvailableProvider, $isActive, $expected) + { + $storeId = 1; + $quote = $this->getMockForAbstractClass(CartInterface::class); + $config = $this->getMockForAbstractClass(ConfigInterface::class); + + $this->vaultProvider->expects(static::once()) + ->method('isAvailable') + ->with($quote) + ->willReturn($isAvailableProvider); + + $config->expects(static::any()) + ->method('getValue') + ->with('active', $storeId) + ->willReturn($isActive); + + $quote->expects(static::any()) + ->method('getStoreId') + ->willReturn($storeId); + + /** @var Vault $model */ + $model = $this->objectManager->getObject(Vault::class, [ + 'config' => $config, + 'vaultProvider' => $this->vaultProvider + ]); + $actual = $model->isAvailable($quote); + static::assertEquals($expected, $actual); + } + + /** + * List of variations for testing isAvailable method + * @return array + */ + public function isAvailableDataProvider() + { + return [ + ['isAvailableProvider' => true, 'isActiveVault' => false, 'expected' => false], + ['isAvailableProvider' => false, 'isActiveVault' => false, 'expected' => false], + ['isAvailableProvider' => false, 'isActiveVault' => true, 'expected' => false], + ['isAvailableProvider' => true, 'isActiveVault' => true, 'expected' => true], + ]; + } + + /** + * @covers \Magento\Vault\Model\Method\Vault::isAvailable + */ + public function testIsAvailableWithoutQuote() + { + $quote = null; + $config = $this->getMockForAbstractClass(ConfigInterface::class); + + $this->vaultProvider->expects(static::once()) + ->method('isAvailable') + ->with($quote) + ->willReturn(true); + + $config->expects(static::once()) + ->method('getValue') + ->with('active', $quote) + ->willReturn(false); + + /** @var Vault $model */ + $model = $this->objectManager->getObject(Vault::class, [ + 'config' => $config, + 'vaultProvider' => $this->vaultProvider + ]); + static::assertFalse($model->isAvailable($quote)); + } + + /** + * @covers \Magento\Vault\Model\Method\Vault::canUseInternal + * @param bool|null $configValue + * @param bool|null $paymentValue + * @param bool $expected + * @dataProvider internalUsageDataProvider + */ + public function testCanUseInternal($configValue, $paymentValue, $expected) + { + $handlerPool = $this->getMock(ValueHandlerPoolInterface::class); + $handler = $this->getMock(ValueHandlerInterface::class); + + $handlerPool->expects(static::once()) + ->method('get') + ->with('can_use_internal') + ->willReturn($handler); + + $handler->expects(static::once()) + ->method('handle') + ->with(['field' => 'can_use_internal'], null) + ->willReturn($configValue); + + $this->vaultProvider->expects(static::any()) + ->method('canUseInternal') + ->willReturn($paymentValue); + + /** @var Vault $model */ + $model = $this->objectManager->getObject(Vault::class, [ + 'vaultProvider' => $this->vaultProvider, + 'valueHandlerPool' => $handlerPool, + ]); + static::assertEquals($expected, $model->canUseInternal()); + } + + /** + * Get list of variations for testing canUseInternal method + * @return array + */ + public function internalUsageDataProvider() + { + return [ + ['configValue' => true, 'paymentValue' => true, 'expected' => true], + ['configValue' => true, 'paymentValue' => null, 'expected' => true], + ['configValue' => true, 'paymentValue' => false, 'expected' => true], + ['configValue' => false, 'paymentValue' => true, 'expected' => false], + ['configValue' => false, 'paymentValue' => false, 'expected' => false], + ['configValue' => null, 'paymentValue' => true, 'expected' => true], + ['configValue' => null, 'paymentValue' => false, 'expected' => false], + ['configValue' => null, 'paymentValue' => null, 'expected' => false], + ]; + } } diff --git a/app/code/Magento/Vault/Test/Unit/Model/PaymentMethodListTest.php b/app/code/Magento/Vault/Test/Unit/Model/PaymentMethodListTest.php new file mode 100644 index 0000000000000..9e9d426fa8f3a --- /dev/null +++ b/app/code/Magento/Vault/Test/Unit/Model/PaymentMethodListTest.php @@ -0,0 +1,74 @@ +paymentMethodList = $this->getMock(PaymentMethodListInterface::class); + $this->instanceFactory = $this->getMockBuilder(InstanceFactory::class) + ->disableOriginalConstructor() + ->setMethods(['create']) + ->getMock(); + + $this->vaultPaymentList = new PaymentMethodList($this->paymentMethodList, $this->instanceFactory); + } + + /** + * @covers \Magento\Vault\Model\PaymentMethodList::getActiveList + */ + public function testGetActivePaymentList() + { + $storeId = 1; + $vaultPayment = $this->getMock(VaultPaymentInterface::class); + $paymentMethodInterface1 = $this->getMock(PaymentMethodInterface::class); + $paymentMethodInterface2 = $this->getMock(PaymentMethodInterface::class); + $activePayments = [ + $paymentMethodInterface1, + $paymentMethodInterface2 + ]; + + $this->paymentMethodList->expects(static::once()) + ->method('getActiveList') + ->with($storeId) + ->willReturn($activePayments); + + $this->instanceFactory->expects(static::exactly(2)) + ->method('create') + ->willReturnMap([ + [$paymentMethodInterface1, $this->getMock(MethodInterface::class)], + [$paymentMethodInterface2, $vaultPayment] + ]); + + $vaultPayments = $this->vaultPaymentList->getActiveList($storeId); + static::assertCount(1, $vaultPayments); + static::assertInstanceOf(VaultPaymentInterface::class, $vaultPayment); + } +} diff --git a/app/code/Magento/Vault/Test/Unit/Model/PaymentTokenManagementTest.php b/app/code/Magento/Vault/Test/Unit/Model/PaymentTokenManagementTest.php index 8c8486407b04d..8784522a80f7a 100644 --- a/app/code/Magento/Vault/Test/Unit/Model/PaymentTokenManagementTest.php +++ b/app/code/Magento/Vault/Test/Unit/Model/PaymentTokenManagementTest.php @@ -474,7 +474,7 @@ public function testGetVisibleAvailableTokens() ->with('gt') ->willReturnSelf(); - $date = $this->getMockBuilder('DateTime') + $date = $this->getMockBuilder(\DateTime::class) ->disableOriginalConstructor() ->getMock(); $this->dateTimeFactory->expects(static::once()) @@ -486,9 +486,9 @@ public function testGetVisibleAvailableTokens() ->with('Y-m-d 00:00:00') ->willReturn('2015-01-01 00:00:00'); - $this->searchCriteriaBuilder->expects(self::once()) + $this->searchCriteriaBuilder->expects(self::exactly(4)) ->method('addFilters') - ->with([$customerFilter, $visibilityFilter, $isActiveFilter, $expiresAtFilter]) + ->withConsecutive($customerFilter, $visibilityFilter, $isActiveFilter, $expiresAtFilter) ->willReturnSelf(); $this->searchCriteriaBuilder->expects(self::once()) diff --git a/app/code/Magento/Vault/Test/Unit/Model/Ui/Adminhtml/TokensConfigProviderTest.php b/app/code/Magento/Vault/Test/Unit/Model/Ui/Adminhtml/TokensConfigProviderTest.php index e54f9cc9c979b..bbac491386c44 100644 --- a/app/code/Magento/Vault/Test/Unit/Model/Ui/Adminhtml/TokensConfigProviderTest.php +++ b/app/code/Magento/Vault/Test/Unit/Model/Ui/Adminhtml/TokensConfigProviderTest.php @@ -10,20 +10,26 @@ use Magento\Framework\Api\FilterBuilder; use Magento\Framework\Api\SearchCriteria; use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\Exception\InputException; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\Intl\DateTimeFactory; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\TestFramework\Unit\Matcher\MethodInvokedAtIndex; use Magento\Payment\Helper\Data; +use Magento\Sales\Api\Data\OrderInterface; +use Magento\Sales\Api\Data\OrderPaymentInterface; +use Magento\Sales\Api\OrderRepositoryInterface; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\StoreManagerInterface; use Magento\Vault\Api\Data\PaymentTokenInterface; use Magento\Vault\Api\Data\PaymentTokenSearchResultsInterface; +use Magento\Vault\Api\PaymentTokenManagementInterface; use Magento\Vault\Api\PaymentTokenRepositoryInterface; use Magento\Vault\Model\Ui\Adminhtml\TokensConfigProvider; use Magento\Vault\Model\Ui\TokenUiComponentInterface; use Magento\Vault\Model\Ui\TokenUiComponentProviderInterface; use Magento\Vault\Model\VaultPaymentInterface; use PHPUnit_Framework_MockObject_MockObject as MockObject; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; /** * Class TokensConfigProviderTest @@ -32,6 +38,17 @@ */ class TokensConfigProviderTest extends \PHPUnit_Framework_TestCase { + /**#@+ + * Global values + */ + const STORE_ID = 1; + const ORDER_ID = 2; + const ORDER_PAYMENT_ENTITY_ID = 3; + const ENTITY_ID = 4; + const VAULT_PAYMENT_CODE = 'vault_payment'; + const VAULT_PROVIDER_CODE = 'payment'; + /**#@-*/ + /** * @var PaymentTokenRepositoryInterface|MockObject */ @@ -77,11 +94,31 @@ class TokensConfigProviderTest extends \PHPUnit_Framework_TestCase */ private $vaultPayment; + /** + * @var PaymentTokenManagementInterface|MockObject + */ + private $paymentTokenManagement; + + /** + * @var OrderRepositoryInterface|MockObject + */ + private $orderRepository; + + /** + * @var TokenUiComponentProviderInterface|MockObject + */ + private $tokenComponentProvider; + /** * @var ObjectManager */ private $objectManager; + /** + * @var TokensConfigProvider + */ + private $configProvider; + protected function setUp() { $this->paymentTokenRepository = $this->getMockBuilder(PaymentTokenRepositoryInterface::class) @@ -94,7 +131,7 @@ protected function setUp() ->getMock(); $this->session = $this->getMockBuilder(Quote::class) ->disableOriginalConstructor() - ->setMethods(['getCustomerId']) + ->setMethods(['getCustomerId', 'getReordered']) ->getMock(); $this->dateTimeFactory = $this->getMockBuilder(DateTimeFactory::class) ->disableOriginalConstructor() @@ -103,23 +140,54 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods(['getMethodInstance']) ->getMock(); + $this->paymentTokenManagement = $this->getMockBuilder(PaymentTokenManagementInterface::class) + ->getMockForAbstractClass(); + $this->orderRepository = $this->getMockBuilder(OrderRepositoryInterface::class) + ->getMockForAbstractClass(); $this->vaultPayment = $this->getMockForAbstractClass(VaultPaymentInterface::class); $this->objectManager = new ObjectManager($this); + + $this->initStoreMock(); + + $this->tokenComponentProvider = $this->getMock(TokenUiComponentProviderInterface::class); + + $this->configProvider = new TokensConfigProvider( + $this->session, + $this->paymentTokenRepository, + $this->filterBuilder, + $this->searchCriteriaBuilder, + $this->storeManager, + $this->dateTimeFactory, + [ + self::VAULT_PROVIDER_CODE => $this->tokenComponentProvider + ] + ); + + $this->objectManager->setBackwardCompatibleProperty( + $this->configProvider, + 'paymentDataHelper', + $this->paymentDataHelper + ); + $this->objectManager->setBackwardCompatibleProperty( + $this->configProvider, + 'paymentTokenManagement', + $this->paymentTokenManagement + ); + $this->objectManager->setBackwardCompatibleProperty( + $this->configProvider, + 'orderRepository', + $this->orderRepository + ); } /** * @covers \Magento\Vault\Model\Ui\Adminhtml\TokensConfigProvider::getTokensComponents */ - public function testGetTokensComponents() + public function testGetTokensComponentsRegisteredCustomer() { - $storeId = 1; - $customerId = 2; - $vaultPaymentCode = 'vault_payment'; - $vaultProviderCode = 'payment'; - - $this->initStoreMock(); + $customerId = 1; $this->session->expects(static::once()) ->method('getCustomerId') @@ -127,26 +195,26 @@ public function testGetTokensComponents() $this->paymentDataHelper->expects(static::once()) ->method('getMethodInstance') - ->with($vaultPaymentCode) + ->with(self::VAULT_PAYMENT_CODE) ->willReturn($this->vaultPayment); $this->vaultPayment->expects(static::once()) ->method('isActive') - ->with($storeId) + ->with(self::STORE_ID) ->willReturn(true); $this->vaultPayment->expects(static::once()) ->method('getProviderCode') - ->willReturn($vaultProviderCode); + ->willReturn(self::VAULT_PROVIDER_CODE); /** @var PaymentTokenInterface|MockObject $token */ $token = $this->getMockBuilder(PaymentTokenInterface::class) ->getMockForAbstractClass(); - list($tokenUiComponent, $tokenUiComponentProvider) = $this->getTokenUiComponentProvider($token); + $tokenUiComponent = $this->getTokenUiComponentProvider($token); - $searchCriteria = $this->getSearchCriteria($customerId, $vaultProviderCode); + $searchCriteria = $this->getSearchCriteria($customerId, self::ENTITY_ID, self::VAULT_PROVIDER_CODE); - $date = $this->getMockBuilder('DateTime') + $date = $this->getMockBuilder(\DateTime::class) ->disableOriginalConstructor() ->getMock(); $this->dateTimeFactory->expects(static::once()) @@ -169,53 +237,140 @@ public function testGetTokensComponents() ->method('getItems') ->willReturn([$token]); - $configProvider = new TokensConfigProvider( - $this->session, - $this->paymentTokenRepository, - $this->filterBuilder, - $this->searchCriteriaBuilder, - $this->storeManager, - $this->dateTimeFactory, - [ - $vaultProviderCode => $tokenUiComponentProvider - ] - ); - - $this->objectManager->setBackwardCompatibleProperty( - $configProvider, - 'paymentDataHelper', - $this->paymentDataHelper - ); + static::assertEquals([$tokenUiComponent], $this->configProvider->getTokensComponents(self::VAULT_PAYMENT_CODE)); + } + + /** + * @covers \Magento\Vault\Model\Ui\Adminhtml\TokensConfigProvider::getTokensComponents + */ + public function testGetTokensComponentsGuestCustomer() + { + $customerId = null; + + $this->initStoreMock(); + + $this->session->expects(static::once()) + ->method('getCustomerId') + ->willReturn($customerId); + + $this->paymentDataHelper->expects(static::once()) + ->method('getMethodInstance') + ->with(self::VAULT_PAYMENT_CODE) + ->willReturn($this->vaultPayment); + + $this->vaultPayment->expects(static::once()) + ->method('isActive') + ->with(self::STORE_ID) + ->willReturn(true); + $this->vaultPayment->expects(static::once()) + ->method('getProviderCode') + ->willReturn(self::VAULT_PROVIDER_CODE); + + /** @var PaymentTokenInterface|MockObject $token */ + $token = $this->getMockBuilder(PaymentTokenInterface::class) + ->getMockForAbstractClass(); + + $this->session->expects(static::once()) + ->method('getReordered') + ->willReturn(self::ORDER_ID); + $this->orderRepository->expects(static::once()) + ->method('get') + ->with(self::ORDER_ID) + ->willReturn($this->getOrderMock()); + $this->paymentTokenManagement->expects(static::once()) + ->method('getByPaymentId') + ->with(self::ORDER_PAYMENT_ENTITY_ID) + ->willReturn($token); + $token->expects(static::once()) + ->method('getEntityId') + ->willReturn(self::ENTITY_ID); + + $tokenUiComponent = $this->getTokenUiComponentProvider($token); + + $searchCriteria = $this->getSearchCriteria($customerId, self::ENTITY_ID, self::VAULT_PROVIDER_CODE); + + $date = $this->getMockBuilder('DateTime') + ->disableOriginalConstructor() + ->getMock(); + $this->dateTimeFactory->expects(static::once()) + ->method('create') + ->with("now", new \DateTimeZone('UTC')) + ->willReturn($date); + $date->expects(static::once()) + ->method('format') + ->with('Y-m-d 00:00:00') + ->willReturn('2015-01-01 00:00:00'); - static::assertEquals([$tokenUiComponent], $configProvider->getTokensComponents($vaultPaymentCode)); + $searchResult = $this->getMockBuilder(PaymentTokenSearchResultsInterface::class) + ->getMockForAbstractClass(); + $this->paymentTokenRepository->expects(self::once()) + ->method('getList') + ->with($searchCriteria) + ->willReturn($searchResult); + + $searchResult->expects(self::once()) + ->method('getItems') + ->willReturn([$token]); + + static::assertEquals([$tokenUiComponent], $this->configProvider->getTokensComponents(self::VAULT_PAYMENT_CODE)); } /** + * @param \Exception $exception * @covers \Magento\Vault\Model\Ui\Adminhtml\TokensConfigProvider::getTokensComponents + * @dataProvider getTokensComponentsGuestCustomerExceptionsProvider */ - public function testGetTokensComponentsNotExistsCustomer() + public function testGetTokensComponentsGuestCustomerOrderNotFound($exception) { - $vaultPaymentCode = 'vault_payment'; - $this->store = $this->getMock(StoreInterface::class); - $this->storeManager = $this->getMock(StoreManagerInterface::class); + $customerId = null; $this->session->expects(static::once()) ->method('getCustomerId') - ->willReturn(null); + ->willReturn($customerId); + + $this->paymentDataHelper->expects(static::once()) + ->method('getMethodInstance') + ->with(self::VAULT_PAYMENT_CODE) + ->willReturn($this->vaultPayment); - $this->storeManager->expects(static::never()) - ->method('getStore'); + $this->vaultPayment->expects(static::once()) + ->method('isActive') + ->with(self::STORE_ID) + ->willReturn(true); + $this->vaultPayment->expects(static::once()) + ->method('getProviderCode') + ->willReturn(self::VAULT_PROVIDER_CODE); - $configProvider = new TokensConfigProvider( - $this->session, - $this->paymentTokenRepository, - $this->filterBuilder, - $this->searchCriteriaBuilder, - $this->storeManager, - $this->dateTimeFactory - ); + $this->session->expects(static::once()) + ->method('getReordered') + ->willReturn(self::ORDER_ID); + $this->orderRepository->expects(static::once()) + ->method('get') + ->with(self::ORDER_ID) + ->willThrowException($exception); + + $this->filterBuilder->expects(static::once()) + ->method('setField') + ->with(PaymentTokenInterface::ENTITY_ID) + ->willReturnSelf(); + $this->filterBuilder->expects(static::never()) + ->method('setValue'); + $this->searchCriteriaBuilder->expects(self::never()) + ->method('addFilters'); + + static::assertEmpty($this->configProvider->getTokensComponents(self::VAULT_PAYMENT_CODE)); + } - static::assertEmpty($configProvider->getTokensComponents($vaultPaymentCode)); + /** + * Set of catching exception types + * @return array + */ + public function getTokensComponentsGuestCustomerExceptionsProvider() + { + return [ + [new InputException()], + [new NoSuchEntityException()], + ]; } /** @@ -223,9 +378,7 @@ public function testGetTokensComponentsNotExistsCustomer() */ public function testGetTokensComponentsEmptyComponentProvider() { - $storeId = 1; - $customerId = 2; - $vaultPaymentCode = 'vault_payment'; + $customerId = 1; $this->session->expects(static::once()) ->method('getCustomerId') @@ -235,12 +388,12 @@ public function testGetTokensComponentsEmptyComponentProvider() $this->paymentDataHelper->expects(static::once()) ->method('getMethodInstance') - ->with($vaultPaymentCode) + ->with(self::VAULT_PAYMENT_CODE) ->willReturn($this->vaultPayment); $this->vaultPayment->expects(static::once()) ->method('isActive') - ->with($storeId) + ->with(self::STORE_ID) ->willReturn(false); $this->paymentTokenRepository->expects(static::never()) @@ -261,7 +414,55 @@ public function testGetTokensComponentsEmptyComponentProvider() $this->paymentDataHelper ); - static::assertEmpty($configProvider->getTokensComponents($vaultPaymentCode)); + static::assertEmpty($configProvider->getTokensComponents(self::VAULT_PAYMENT_CODE)); + } + + /** + * @covers \Magento\Vault\Model\Ui\Adminhtml\TokensConfigProvider::getTokensComponents + */ + public function testGetTokensComponentsForGuestCustomerWithoutStoredTokens() + { + $this->session->expects(static::once()) + ->method('getCustomerId') + ->willReturn(null); + + $this->paymentDataHelper->expects(static::once()) + ->method('getMethodInstance') + ->with(self::VAULT_PAYMENT_CODE) + ->willReturn($this->vaultPayment); + + $this->vaultPayment->expects(static::once()) + ->method('isActive') + ->with(self::STORE_ID) + ->willReturn(true); + $this->vaultPayment->expects(static::once()) + ->method('getProviderCode') + ->willReturn(self::VAULT_PROVIDER_CODE); + + $this->session->expects(static::once()) + ->method('getReordered') + ->willReturn(self::ORDER_ID); + $this->orderRepository->expects(static::once()) + ->method('get') + ->with(self::ORDER_ID) + ->willReturn($this->getOrderMock()); + + $this->paymentTokenManagement->expects(static::once()) + ->method('getByPaymentId') + ->with(self::ORDER_PAYMENT_ENTITY_ID) + ->willReturn(null); + + $this->filterBuilder->expects(static::once()) + ->method('setField') + ->with(PaymentTokenInterface::ENTITY_ID) + ->willReturnSelf(); + $this->filterBuilder->expects(static::never()) + ->method('setValue'); + + $this->searchCriteriaBuilder->expects(static::never()) + ->method('addFilters'); + + static::assertEmpty($this->configProvider->getTokensComponents(self::VAULT_PAYMENT_CODE)); } /** @@ -269,36 +470,55 @@ public function testGetTokensComponentsEmptyComponentProvider() */ private function initStoreMock() { - $storeId = 1; - $this->store = $this->getMock(StoreInterface::class); - $this->store->expects(static::once()) + $this->store->expects(static::any()) ->method('getId') - ->willReturn($storeId); + ->willReturn(self::STORE_ID); $this->storeManager = $this->getMock(StoreManagerInterface::class); - $this->storeManager->expects(static::once()) + $this->storeManager->expects(static::any()) ->method('getStore') ->with(null) ->willReturn($this->store); } + /** + * Returns order mock with order payment mock + * @return OrderInterface + */ + private function getOrderMock() + { + /** @var OrderInterface|MockObject $order */ + $order = $this->getMockBuilder(OrderInterface::class) + ->getMockForAbstractClass(); + /** @var OrderPaymentInterface|MockObject $orderPayment */ + $orderPayment = $this->getMockBuilder(OrderPaymentInterface::class) + ->getMockForAbstractClass(); + + $order->expects(static::once()) + ->method('getPayment') + ->willReturn($orderPayment); + $orderPayment->expects(static::once()) + ->method('getEntityId') + ->willReturn(self::ORDER_PAYMENT_ENTITY_ID); + + return $order; + } + /** * Get mock for token ui component provider * @param PaymentTokenInterface $token - * @return array + * @return TokenUiComponentInterface|MockObject */ private function getTokenUiComponentProvider($token) { $tokenUiComponent = $this->getMock(TokenUiComponentInterface::class); - - $tokenUiComponentProvider = $this->getMock(TokenUiComponentProviderInterface::class); - $tokenUiComponentProvider->expects(static::once()) + $this->tokenComponentProvider->expects(static::once()) ->method('getComponentForToken') ->with($token) ->willReturn($tokenUiComponent); - return [$tokenUiComponent, $tokenUiComponentProvider]; + return $tokenUiComponent; } /** @@ -331,16 +551,18 @@ private function createExpectedFilter($field, $value, $atIndex) /** * Build search criteria * @param int $customerId + * @param int $entityId * @param string $vaultProviderCode * @return \PHPUnit_Framework_MockObject_MockObject */ - private function getSearchCriteria($customerId, $vaultProviderCode) + private function getSearchCriteria($customerId, $entityId, $vaultProviderCode) { $searchCriteria = $this->getMockBuilder(SearchCriteria::class) ->disableOriginalConstructor() ->getMock(); - $customerFilter = $this->createExpectedFilter(PaymentTokenInterface::CUSTOMER_ID, $customerId, 0); + $customerFilter = $customerId ? $this->createExpectedFilter(PaymentTokenInterface::CUSTOMER_ID, $customerId, 0) + : $this->createExpectedFilter(PaymentTokenInterface::ENTITY_ID, $entityId, 0); $codeFilter = $this->createExpectedFilter( PaymentTokenInterface::PAYMENT_METHOD_CODE, $vaultProviderCode, @@ -360,10 +582,16 @@ private function getSearchCriteria($customerId, $vaultProviderCode) ->with('gt') ->willReturnSelf(); - $this->searchCriteriaBuilder->expects(self::once()) + $this->searchCriteriaBuilder->expects(self::exactly(4)) ->method('addFilters') - ->with([$customerFilter, $codeFilter, $expiresAtFilter, $isActiveFilter]) - ->willReturnSelf(); + ->willReturnMap( + [ + [$customerFilter, $this->searchCriteriaBuilder], + [$codeFilter, $this->searchCriteriaBuilder], + [$expiresAtFilter, $this->searchCriteriaBuilder], + [$isActiveFilter, $this->searchCriteriaBuilder], + ] + ); $this->searchCriteriaBuilder->expects(self::once()) ->method('create') diff --git a/app/code/Magento/Vault/Test/Unit/Model/Ui/TokensConfigProviderTest.php b/app/code/Magento/Vault/Test/Unit/Model/Ui/TokensConfigProviderTest.php index e64fff27ff14c..34b7c52404971 100644 --- a/app/code/Magento/Vault/Test/Unit/Model/Ui/TokensConfigProviderTest.php +++ b/app/code/Magento/Vault/Test/Unit/Model/Ui/TokensConfigProviderTest.php @@ -5,12 +5,11 @@ */ namespace Magento\Vault\Test\Unit\Model\Ui; -use Magento\Customer\Model\Session; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Payment\Helper\Data; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\StoreManagerInterface; use Magento\Vault\Api\Data\PaymentTokenInterface; +use Magento\Vault\Api\PaymentMethodListInterface; use Magento\Vault\Model\CustomerTokenManagement; use Magento\Vault\Model\Ui\TokensConfigProvider; use Magento\Vault\Model\Ui\TokenUiComponentInterface; @@ -48,9 +47,9 @@ class TokensConfigProviderTest extends \PHPUnit_Framework_TestCase private $customerTokenManagement; /** - * @var Data|MockObject + * @var PaymentMethodListInterface|MockObject */ - private $paymentDataHelper; + private $vaultPaymentList; /** * @var ObjectManager @@ -59,15 +58,12 @@ class TokensConfigProviderTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->vaultPayment = $this->getMock(VaultPaymentInterface::class); + $this->objectManager = new ObjectManager($this); + $this->vaultPaymentList = $this->getMock(PaymentMethodListInterface::class); + $this->vaultPayment = $this->getMockForAbstractClass(VaultPaymentInterface::class); $this->storeManager = $this->getMock(StoreManagerInterface::class); $this->store = $this->getMock(StoreInterface::class); - $this->paymentDataHelper = $this->getMockBuilder(Data::class) - ->disableOriginalConstructor() - ->setMethods(['getStoreMethods']) - ->getMock(); - $this->objectManager = new ObjectManager($this); $this->customerTokenManagement = $this->getMockBuilder(CustomerTokenManagement::class) ->disableOriginalConstructor() ->getMock(); @@ -81,7 +77,7 @@ public function testGetConfig() $expectedConfig = [ 'payment' => [ 'vault' => [ - $vaultProviderCode . '_item_' . '0' => [ + $vaultProviderCode . '_' . '0' => [ 'config' => ['token_code' => 'code'], 'component' => 'Vendor_Module/js/vault_component' ] @@ -99,16 +95,12 @@ public function testGetConfig() $this->store->expects(static::once()) ->method('getId') ->willReturn($storeId); - - $this->paymentDataHelper->expects(static::once()) - ->method('getStoreMethods') + + $this->vaultPaymentList->expects(static::once()) + ->method('getActiveList') ->with($storeId) ->willReturn([$this->vaultPayment]); - $this->vaultPayment->expects(static::once()) - ->method('isActive') - ->with($storeId) - ->willReturn(true); $this->vaultPayment->expects(static::once()) ->method('getProviderCode') ->willReturn($vaultProviderCode); @@ -139,11 +131,10 @@ public function testGetConfig() $vaultProviderCode => $tokenUiComponentProvider ] ); - $this->objectManager->setBackwardCompatibleProperty( $configProvider, - 'paymentDataHelper', - $this->paymentDataHelper + 'vaultPaymentList', + $this->vaultPaymentList ); static::assertEquals($expectedConfig, $configProvider->getConfig()); diff --git a/app/code/Magento/Vault/Test/Unit/Model/Ui/VaultConfigProviderTest.php b/app/code/Magento/Vault/Test/Unit/Model/Ui/VaultConfigProviderTest.php index 7d0d8339ab2b1..e9d6af3bec356 100644 --- a/app/code/Magento/Vault/Test/Unit/Model/Ui/VaultConfigProviderTest.php +++ b/app/code/Magento/Vault/Test/Unit/Model/Ui/VaultConfigProviderTest.php @@ -7,24 +7,18 @@ use Magento\Customer\Model\Session; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Payment\Helper\Data; use Magento\Store\Api\Data\StoreInterface; use Magento\Store\Model\StoreManagerInterface; +use Magento\Vault\Api\PaymentMethodListInterface; use Magento\Vault\Model\Ui\VaultConfigProvider; use Magento\Vault\Model\VaultPaymentInterface; use PHPUnit_Framework_MockObject_MockObject as MockObject; /** * Class VaultConfigProviderTest - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class VaultConfigProviderTest extends \PHPUnit_Framework_TestCase { - /** - * @var Data|MockObject - */ - private $paymentDataHelper; - /** * @var VaultPaymentInterface|MockObject */ @@ -45,6 +39,11 @@ class VaultConfigProviderTest extends \PHPUnit_Framework_TestCase */ private $storeManager; + /** + * @var PaymentMethodListInterface|MockObject + */ + private $vaultPaymentList; + /** * @var VaultConfigProvider */ @@ -52,24 +51,20 @@ class VaultConfigProviderTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->paymentDataHelper = $this->getMockBuilder(Data::class) - ->disableOriginalConstructor() - ->setMethods(['getStoreMethods']) - ->getMock(); - $this->vaultPayment = $this->getMockForAbstractClass(VaultPaymentInterface::class); $this->storeManager = $this->getMockForAbstractClass(StoreManagerInterface::class); $this->store = $this->getMockForAbstractClass(StoreInterface::class); $this->session = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); + $this->vaultPaymentList = $this->getMock(PaymentMethodListInterface::class); $objectManager = new ObjectManager($this); $this->vaultConfigProvider = new VaultConfigProvider($this->storeManager, $this->session); $objectManager->setBackwardCompatibleProperty( $this->vaultConfigProvider, - 'paymentDataHelper', - $this->paymentDataHelper + 'vaultPaymentList', + $this->vaultPaymentList ); } @@ -94,16 +89,15 @@ public function testGetConfig($customerId, $vaultEnabled) $this->session->expects(static::once()) ->method('getCustomerId') ->willReturn($customerId); - $this->storeManager->expects(static::exactly(2)) + $this->storeManager->expects(static::once()) ->method('getStore') ->willReturn($this->store); - $this->store->expects(static::exactly(2)) + $this->store->expects(static::once()) ->method('getId') ->willReturn($storeId); - $this->paymentDataHelper->expects(static::once()) - ->method('getStoreMethods') - ->with($storeId) + $this->vaultPaymentList->expects(static::once()) + ->method('getActiveList') ->willReturn([$this->vaultPayment]); $this->vaultPayment->expects(static::once()) diff --git a/app/code/Magento/Vault/Test/Unit/Observer/PaymentTokenAssignerTest.php b/app/code/Magento/Vault/Test/Unit/Observer/PaymentTokenAssignerTest.php index 6281dc83da7fd..d973e1cce5782 100644 --- a/app/code/Magento/Vault/Test/Unit/Observer/PaymentTokenAssignerTest.php +++ b/app/code/Magento/Vault/Test/Unit/Observer/PaymentTokenAssignerTest.php @@ -78,44 +78,6 @@ public function testExecuteNotOrderPaymentModel() $this->observer->execute($observer); } - public function testExecuteNoCustomerId() - { - $dataObject = new DataObject( - [ - PaymentInterface::KEY_ADDITIONAL_DATA => [ - PaymentTokenInterface::PUBLIC_HASH => 'public_hash_value' - ] - ] - ); - - $paymentModel = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->getMock(); - $quote = $this->getMock(CartInterface::class); - $customer = $this->getMock(CustomerInterface::class); - - $paymentModel->expects(static::once()) - ->method('getQuote') - ->willReturn($quote); - $quote->expects(static::once()) - ->method('getCustomer') - ->willReturn($customer); - $customer->expects(static::once()) - ->method('getId') - ->willReturn(null); - - $observer = $this->getPreparedObserverWithMap( - [ - [AbstractDataAssignObserver::DATA_CODE, $dataObject], - [AbstractDataAssignObserver::MODEL_CODE, $paymentModel] - ] - ); - - $this->paymentTokenManagement->expects(static::never()) - ->method('getByPublicHash'); - $this->observer->execute($observer); - } - public function testExecuteNoPaymentToken() { $customerId = 1; diff --git a/app/code/Magento/Vault/etc/di.xml b/app/code/Magento/Vault/etc/di.xml index e44e1da3e3d61..14354da7e2c52 100644 --- a/app/code/Magento/Vault/etc/di.xml +++ b/app/code/Magento/Vault/etc/di.xml @@ -11,6 +11,7 @@ + diff --git a/app/code/Magento/Vault/etc/module.xml b/app/code/Magento/Vault/etc/module.xml index cc654548a1bba..7ab8db1d86fce 100644 --- a/app/code/Magento/Vault/etc/module.xml +++ b/app/code/Magento/Vault/etc/module.xml @@ -6,7 +6,7 @@ */ --> - + diff --git a/app/code/Magento/Vault/view/frontend/layout/vault_cards_listaction.xml b/app/code/Magento/Vault/view/frontend/layout/vault_cards_listaction.xml index bac49fe7869f5..5731fbd79154b 100644 --- a/app/code/Magento/Vault/view/frontend/layout/vault_cards_listaction.xml +++ b/app/code/Magento/Vault/view/frontend/layout/vault_cards_listaction.xml @@ -9,7 +9,8 @@ - + + diff --git a/app/code/Magento/Vault/view/frontend/templates/cards_list.phtml b/app/code/Magento/Vault/view/frontend/templates/cards_list.phtml index dac022f28826d..2dd08ca4c5c09 100644 --- a/app/code/Magento/Vault/view/frontend/templates/cards_list.phtml +++ b/app/code/Magento/Vault/view/frontend/templates/cards_list.phtml @@ -5,13 +5,13 @@ */ // @codingStandardsIgnoreFile -/** @var \Magento\Vault\Block\CreditCards $block */ +/** @var \Magento\Vault\Block\Customer\CreditCards $block */ $tokens = $block->getPaymentTokens(); ?>
- + @@ -30,6 +30,6 @@ $tokens = $block->getPaymentTokens();
- -
+isExistsCustomerTokens()): ?> +
diff --git a/app/code/Magento/Vault/view/frontend/templates/token_list.phtml b/app/code/Magento/Vault/view/frontend/templates/token_list.phtml new file mode 100644 index 0000000000000..d5086cf5ec54c --- /dev/null +++ b/app/code/Magento/Vault/view/frontend/templates/token_list.phtml @@ -0,0 +1,27 @@ +getPaymentTokens(); +?> + +
+ + + + + + + + + + renderTokenHtml($token); ?> + + +
escapeHtml(__('PayPal Account')); ?> 
+
+ diff --git a/app/code/Magento/Vault/view/frontend/web/js/view/payment/vault.js b/app/code/Magento/Vault/view/frontend/web/js/view/payment/vault.js index cba9256f2a563..05d56e305f23e 100644 --- a/app/code/Magento/Vault/view/frontend/web/js/view/payment/vault.js +++ b/app/code/Magento/Vault/view/frontend/web/js/view/payment/vault.js @@ -31,7 +31,8 @@ define( * @return {Boolean} */ typeComparatorCallback: function (typeA, typeB) { - return typeA.indexOf(typeB) === 0; + // vault token items have the same name as vault payment without index + return typeA.substring(0, typeA.lastIndexOf('_')) === typeB; } } ); diff --git a/app/design/frontend/Magento/blank/Magento_Braintree/web/css/source/_module.less b/app/design/frontend/Magento/blank/Magento_Braintree/web/css/source/_module.less index 9573d4b8a1e65..00716c776990d 100644 --- a/app/design/frontend/Magento/blank/Magento_Braintree/web/css/source/_module.less +++ b/app/design/frontend/Magento/blank/Magento_Braintree/web/css/source/_module.less @@ -13,6 +13,11 @@ @braintree-focus__color: @color-blue2; @braintree-success__color: @color-dark-green1; +@braintree-paypal-icon__height: 16px; +@braintree-paypal-icon__width: 16px; +@braintree-paypal-account__padding-right: 50px; +@braintree-paypal-account__padding-vertical: 15px; + // // Common // _____________________________________________ @@ -86,6 +91,80 @@ opacity: 0; } } + + .braintree-paypal-logo { + margin-top: @indent__s; + text-align: center; + } + + .braintree-paypal-account { + padding: @braintree-paypal-account__padding-vertical 0 @braintree-paypal-account__padding-vertical @braintree-paypal-account__padding-right; + position: relative; + + .lib-icon-image( + @_icon-image: '@{baseDir}Magento_Braintree/images/paypal-small.png', + @_icon-image-position: before, + @_icon-image-width: @braintree-paypal-icon__width, + @_icon-image-height: @braintree-paypal-icon__height + ); + + &:before { + left: @braintree-paypal-account__padding-right/2 - @braintree-paypal-icon__width/2; + margin-top: -@braintree-paypal-icon__height/2; + position: absolute; + top: 50%; + } + + .payment-method-type { + font-weight: @font-weight__bold; + } + + .payment-method-description { + color: @color-gray34; + } + } + + .braintree-paypal-fieldset { + border: 0; + margin: 0; + padding: 0; + } + + .action-braintree-paypal-logo { + .lib-button-reset(); + + img { + margin: 0; + width: 114px; + } + } + + .payment-method { + .payment-method-content { + .actions-toolbar { + &.braintree-paypal-actions { + margin-left: 0; + } + } + } + } + + // My Account > Stored Payment Methods + .account { + .table { + .col { + &.paypal-account { + img { + vertical-align: middle; + } + + + .actions { + vertical-align: middle; + } + } + } + } + } } // @@ -100,4 +179,23 @@ } } } + + .braintree-paypal-account { + border-color: @color-gray80; + border-style: solid; + border-width: 1px 0; + display: inline-block; + width: 50%; + } + + // My Account > Stored Payment Methods + .account { + .table-credit-cards { + .col { + &.actions { + width: 100px; + } + } + } + } } diff --git a/app/design/frontend/Magento/blank/Magento_BraintreeTwo/web/css/source/_module.less b/app/design/frontend/Magento/blank/Magento_BraintreeTwo/web/css/source/_module.less deleted file mode 100644 index 45f41cff13e4b..0000000000000 --- a/app/design/frontend/Magento/blank/Magento_BraintreeTwo/web/css/source/_module.less +++ /dev/null @@ -1,24 +0,0 @@ -// /** -// * Copyright © 2016 Magento. All rights reserved. -// * See COPYING.txt for license details. -// */ - -// -// Common -// _____________________________________________ - -& when (@media-common = true) { - .braintree-paypal-logo { - margin-top: @indent__s; - text-align: center; - } - - .action-braintree-paypal-logo { - .lib-button-reset(); - - img { - margin: 0; - width: 114px; - } - } -} diff --git a/app/design/frontend/Magento/luma/Magento_BraintreeTwo/web/css/source/_module.less b/app/design/frontend/Magento/luma/Magento_BraintreeTwo/web/css/source/_module.less deleted file mode 100644 index 07edd849b3d7b..0000000000000 --- a/app/design/frontend/Magento/luma/Magento_BraintreeTwo/web/css/source/_module.less +++ /dev/null @@ -1,28 +0,0 @@ -// /** -// * Copyright © 2016 Magento. All rights reserved. -// * See COPYING.txt for license details. -// */ - -// -// Common -// _____________________________________________ - -& when (@media-common = true) { - .braintree-paypal-logo { - margin-top: @indent__s; - text-align: center; - } - - .action-braintree-paypal-logo { - .lib-button-reset(); - - &:not(.primary) { - box-shadow: none; - } - - img { - margin: 0; - width: 114px; - } - } -} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Block/Form/ContainerTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Block/Form/ContainerTest.php new file mode 100644 index 0000000000000..a805e9ab1f3a0 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Braintree/Block/Form/ContainerTest.php @@ -0,0 +1,64 @@ +bootstrap = Bootstrap::getInstance(); + $this->bootstrap->loadArea(Area::AREA_ADMINHTML); + $this->objectManager = Bootstrap::getObjectManager(); + + $this->container = $this->objectManager->create(Container::class); + } + + /** + * @covers \Magento\Payment\Block\Form\Container::getMethods + * @magentoDataFixture Magento/Braintree/_files/paypal_quote.php + */ + public function testGetMethods() + { + $customerId = 1; + /** @var CartRepositoryInterface $quoteRepository */ + $quoteRepository = $this->objectManager->get(CartRepositoryInterface::class); + $quote = $quoteRepository->getForCustomer($customerId); + $this->container->setData('quote', $quote); + $actual = $this->container->getMethods(); + /** @var MethodInterface $paymentMethod */ + foreach ($actual as $paymentMethod) { + static::assertNotContains($paymentMethod->getCode(), [ + PayPalConfigProvider::PAYPAL_VAULT_CODE, PayPalConfigProvider::PAYPAL_CODE + ]); + } + } +} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Block/VaultTokenRendererTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Block/VaultTokenRendererTest.php new file mode 100644 index 0000000000000..74b99e7e3850c --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Braintree/Block/VaultTokenRendererTest.php @@ -0,0 +1,67 @@ +loadArea(Area::AREA_FRONTEND); + $this->objectManager = Bootstrap::getObjectManager(); + + $this->tokenBlock = $this->objectManager->get(AccountTokens::class); + } + + /** + * @covers \Magento\Vault\Block\Customer\AccountTokens::getPaymentTokens + * @magentoDataFixture Magento/Braintree/_files/paypal_vault_token.php + */ + public function testGetPaymentTokens() + { + $customerId = 1; + $token = 'mx29vk'; + + /** @var Session $session */ + $session = $this->objectManager->get(Session::class); + $session->setCustomerId($customerId); + + $tokens = $this->tokenBlock->getPaymentTokens(); + + static::assertCount(1, $tokens); + + /** @var PaymentTokenInterface $vaultToken */ + $vaultToken = array_pop($tokens); + + static::assertTrue($vaultToken->getIsActive()); + static::assertTrue($vaultToken->getIsVisible()); + static::assertEquals($token, $vaultToken->getGatewayToken()); + static::assertEquals(ConfigProvider::PAYPAL_CODE, $vaultToken->getPaymentMethodCode()); + static::assertEquals(AccountPaymentTokenFactory::TOKEN_TYPE_ACCOUNT, $vaultToken->getType()); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Order/PaymentReviewTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Order/PaymentReviewTest.php new file mode 100644 index 0000000000000..f319a52e42743 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Order/PaymentReviewTest.php @@ -0,0 +1,112 @@ +_objectManager->get(FilterBuilder::class); + $filters = [ + $filterBuilder->setField(OrderInterface::INCREMENT_ID) + ->setValue('100000002') + ->create() + ]; + + /** @var SearchCriteriaBuilder $searchCriteriaBuilder */ + $searchCriteriaBuilder = $this->_objectManager->get(SearchCriteriaBuilder::class); + $searchCriteria = $searchCriteriaBuilder->addFilters($filters) + ->create(); + + $this->orderRepository = $this->_objectManager->get(OrderRepositoryInterface::class); + $orders = $this->orderRepository->getList($searchCriteria) + ->getItems(); + /** @var OrderInterface $order */ + $this->order = array_pop($orders); + } + + /** + * @covers \Magento\Sales\Controller\Adminhtml\Order\ReviewPayment::execute + * @magentoDataFixture Magento/Braintree/_files/fraud_order.php + * @magentoAppArea adminhtml + */ + public function testExecuteAccept() + { + $orderId = $this->order->getEntityId(); + $this->dispatch('backend/sales/order/reviewPayment/action/accept/order_id/' . $orderId); + + static::assertRedirect(static::stringContains('sales/order/view/order_id/' . $orderId)); + static::assertSessionMessages( + static::equalTo(['The payment has been accepted.']), + MessageInterface::TYPE_SUCCESS + ); + + $order = $this->orderRepository->get($orderId); + static::assertEquals(Order::STATE_PROCESSING, $order->getState()); + static::assertEquals(Order::STATE_PROCESSING, $order->getStatus()); + } + + /** + * @covers \Magento\Sales\Controller\Adminhtml\Order\ReviewPayment::execute + * @magentoDataFixture Magento/Braintree/_files/fraud_order.php + * @magentoAppArea adminhtml + */ + public function testExecuteDeny() + { + $orderId = $this->order->getEntityId(); + $payment = $this->order->getPayment(); + + $adapter = $this->getMockBuilder(Adapter::class) + ->disableOriginalConstructor() + ->setMethods(['denyPayment']) + ->getMock(); + // uses the mock instead a real adapter to avoid api calls to Braintree gateway + $payment->setMethodInstance($adapter); + $this->orderRepository->save($this->order); + + $adapter->expects(static::once()) + ->method('denyPayment') + ->with($payment) + ->willReturn(true); + + $this->dispatch('backend/sales/order/reviewPayment/action/deny/order_id/' . $orderId); + + static::assertRedirect(static::stringContains('sales/order/view/order_id/' . $orderId)); + static::assertSessionMessages( + static::equalTo(['The payment has been denied.']), + MessageInterface::TYPE_SUCCESS + ); + + $order = $this->orderRepository->get($orderId); + static::assertEquals(Order::STATE_CANCELED, $order->getState()); + static::assertEquals(Order::STATE_CANCELED, $order->getStatus()); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Cards/DeleteActionTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Cards/DeleteActionTest.php new file mode 100644 index 0000000000000..9e79c0e3f326f --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Cards/DeleteActionTest.php @@ -0,0 +1,53 @@ +_objectManager->get(Session::class); + $session->setCustomerId($customerId); + + /** @var CustomerTokenManagement $tokenManagement */ + $tokenManagement = $this->_objectManager->get(CustomerTokenManagement::class); + $tokens = $tokenManagement->getCustomerSessionTokens(); + + static::assertCount(1, $tokens); + + $vaultToken = array_pop($tokens); + + /** @var FormKey $formKey */ + $formKey = $this->_objectManager->get(FormKey::class); + $this->getRequest() + ->setPostValue([ + 'public_hash' => $vaultToken->getPublicHash(), + 'form_key' => $formKey->getFormKey() + ]) + ->setMethod(Request::METHOD_POST); + $this->dispatch('vault/cards/deleteaction'); + + static::assertTrue($this->getResponse()->isRedirect()); + static::assertRedirect(static::stringContains('vault/cards/listaction')); + static::assertSessionMessages(static::equalTo(['Stored Payment Method was successfully removed'])); + static::assertEmpty($tokenManagement->getCustomerSessionTokens()); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Model/PaymentMethodListTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Model/PaymentMethodListTest.php new file mode 100644 index 0000000000000..0e38adda5498f --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Braintree/Model/PaymentMethodListTest.php @@ -0,0 +1,71 @@ +storeId = $objectManager->get(StoreManagerInterface::class) + ->getStore() + ->getId(); + $this->paymentMethodList = $objectManager->get(PaymentMethodListInterface::class); + } + + /** + * @magentoDataFixture Magento/Braintree/_files/payments.php + */ + public function testGetList() + { + $vaultPayments = $this->paymentMethodList->getList($this->storeId); + + static::assertNotEmpty($vaultPayments); + + $paymentCodes = array_map(function (VaultPaymentInterface $payment) { + return $payment->getCode(); + }, $vaultPayments); + + $expectedCodes = [ + PayPalConfigProvider::PAYPAL_VAULT_CODE, + ConfigProvider::CC_VAULT_CODE + ]; + static::assertNotEmpty(array_intersect($expectedCodes, $paymentCodes)); + } + + /** + * @magentoDataFixture Magento/Braintree/_files/payments.php + */ + public function testGetActiveList() + { + $vaultPayments = $this->paymentMethodList->getActiveList($this->storeId); + + static::assertNotEmpty($vaultPayments); + static::assertCount(1, $vaultPayments); + $payment = array_pop($vaultPayments); + static::assertEquals(PayPalConfigProvider::PAYPAL_VAULT_CODE, $payment->getCode()); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php new file mode 100644 index 0000000000000..e79f4ad361e36 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php @@ -0,0 +1,62 @@ +objectManager = Bootstrap::getObjectManager(); + $this->tokenComponentProvider = $this->objectManager->get(TokenUiComponentProvider::class); + } + + /** + * @covers \Magento\Braintree\Model\Ui\Adminhtml\PayPal\TokenUiComponentProvider::getComponentForToken + * @magentoDataFixture Magento/Braintree/_files/paypal_vault_token.php + * @magentoAppArea adminhtml + */ + public function testGetComponentForToken() + { + $customerId = 1; + $token = 'mx29vk'; + $payerEmail = 'john.doe@example.com'; + + /** @var PaymentTokenManagement $tokenManagement */ + $tokenManagement = $this->objectManager->get(PaymentTokenManagement::class); + $paymentToken = $tokenManagement->getByGatewayToken($token, ConfigProvider::PAYPAL_CODE, $customerId); + + $component = $this->tokenComponentProvider->getComponentForToken($paymentToken); + $config = $component->getConfig(); + + static::assertNotEmpty($config[TokenUiComponentProviderInterface::COMPONENT_DETAILS]); + static::assertNotEmpty($config[TokenUiComponentProviderInterface::COMPONENT_PUBLIC_HASH]); + static::assertEquals(ConfigProvider::PAYPAL_VAULT_CODE, $config['code']); + + $details = $config[TokenUiComponentProviderInterface::COMPONENT_DETAILS]; + static::assertEquals($payerEmail, $details['payerEmail']); + static::assertNotEmpty($details['icon']); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/TokensConfigProviderTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/TokensConfigProviderTest.php new file mode 100644 index 0000000000000..440f7674f1227 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/TokensConfigProviderTest.php @@ -0,0 +1,87 @@ +bootstrap = Bootstrap::getInstance(); + $this->bootstrap->loadArea(Area::AREA_FRONTEND); + $this->objectManager = Bootstrap::getObjectManager(); + + $this->tokenComponentProvider = $this->objectManager->get(TokenUiComponentProvider::class); + + $this->configProvider = $this->objectManager->create( + TokensConfigProvider::class, + [ + 'tokenUiComponentProviders' => [ + PayPalConfigProvider::PAYPAL_CODE => $this->tokenComponentProvider + ] + ] + ); + } + + /** + * @covers \Magento\Vault\Model\Ui\TokensConfigProvider::getConfig + * @magentoDataFixture Magento/Braintree/_files/paypal_vault_token.php + */ + public function testGetConfig() + { + $customerId = 1; + $token = 'mx29vk'; + $payerEmail = 'john.doe@example.com'; + + /** @var PaymentTokenManagement $tokenManagement */ + $tokenManagement = $this->objectManager->get(PaymentTokenManagement::class); + $paymentToken = $tokenManagement->getByGatewayToken($token, PayPalConfigProvider::PAYPAL_CODE, $customerId); + $item = PayPalConfigProvider::PAYPAL_VAULT_CODE . '_' . $paymentToken->getEntityId(); + + /** @var Session $session */ + $session = $this->objectManager->get(Session::class); + $session->setCustomerId($customerId); + + $actual = $this->configProvider->getConfig()['payment']['vault']; + static::assertCount(1, $actual); + static::assertNotEmpty($actual[$item]); + static::assertEquals(PayPalConfigProvider::PAYPAL_VAULT_CODE, $actual[$item]['config']['code']); + static::assertEquals($payerEmail, $actual[$item]['config']['details']['payerEmail']); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/_files/fraud_order.php b/dev/tests/integration/testsuite/Magento/Braintree/_files/fraud_order.php new file mode 100644 index 0000000000000..ebbce2682ce45 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Braintree/_files/fraud_order.php @@ -0,0 +1,38 @@ +get(Config::class); +$config->setDataByPath('payment/' . ConfigProvider::CODE . '/active', 1); +$config->save(); + +/** @var Payment $payment */ +$payment = $objectManager->create(Payment::class); +$payment->setMethod(ConfigProvider::CODE) + ->setLastTransId('000001'); + +$amount = 100; + +/** @var Order $order */ +$order = $objectManager->create(Order::class); +$order->setIncrementId('100000002') + ->setState(Order::STATE_PAYMENT_REVIEW) + ->setStatus(Order::STATUS_FRAUD) + ->setBaseGrandTotal($amount) + ->setPayment($payment); + +/** @var OrderRepositoryInterface $orderRepository */ +$orderRepository = $objectManager->get(OrderRepositoryInterface::class); +$orderRepository->save($order); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/_files/payments.php b/dev/tests/integration/testsuite/Magento/Braintree/_files/payments.php new file mode 100644 index 0000000000000..99ff4481f2982 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Braintree/_files/payments.php @@ -0,0 +1,16 @@ +get(Config::class); +$config->setDataByPath('payment/' . ConfigProvider::PAYPAL_CODE . '/active', 1); +$config->save(); +$config->setDataByPath('payment/' . ConfigProvider::PAYPAL_VAULT_CODE . '/active', 1); +$config->save(); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/_files/paypal_quote.php b/dev/tests/integration/testsuite/Magento/Braintree/_files/paypal_quote.php new file mode 100644 index 0000000000000..b1a6d56d299e1 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Braintree/_files/paypal_quote.php @@ -0,0 +1,25 @@ +get(StoreManagerInterface::class); + +/** @var CartInterface $quote */ +$quote = $objectManager->get(CartInterface::class); +$quote->setStoreId($storeManager->getStore()->getId()) + ->setCustomerIsGuest(false) + ->setCustomerId($customer->getId()); + +/** @var CartRepositoryInterface $quoteRepository */ +$quoteRepository = $objectManager->get(CartRepositoryInterface::class); +$quoteRepository->save($quote); + diff --git a/dev/tests/integration/testsuite/Magento/Braintree/_files/paypal_vault_token.php b/dev/tests/integration/testsuite/Magento/Braintree/_files/paypal_vault_token.php new file mode 100644 index 0000000000000..572e7ec64ac92 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Braintree/_files/paypal_vault_token.php @@ -0,0 +1,41 @@ +get(Config::class); +$config->setDataByPath('payment/' . ConfigProvider::PAYPAL_CODE . '/active', 1); +$config->save(); +$config->setDataByPath('payment/' . ConfigProvider::PAYPAL_VAULT_CODE . '/active', 1); +$config->save(); + +/** @var EncryptorInterface $encryptor */ +$encryptor = $objectManager->get(EncryptorInterface::class); + +/** @var PaymentToken $paymentToken */ +$paymentToken = $objectManager->create(PaymentToken::class); +$paymentToken + ->setCustomerId($customer->getId()) + ->setPaymentMethodCode(ConfigProvider::PAYPAL_CODE) + ->setType(AccountPaymentTokenFactory::TOKEN_TYPE_ACCOUNT) + ->setGatewayToken('mx29vk') + ->setPublicHash($encryptor->hash($customer->getId())) + ->setTokenDetails(json_encode(['payerEmail' => 'john.doe@example.com'])) + ->setIsActive(true) + ->setIsVisible(true) + ->setExpiresAt(date('Y-m-d H:i:s', strtotime('+1 year'))); + +/** @var PaymentTokenRepository $tokenRepository */ +$tokenRepository = $objectManager->create(PaymentTokenRepository::class); +$tokenRepository->save($paymentToken); \ No newline at end of file diff --git a/dev/tests/integration/testsuite/Magento/Payment/Block/Transparent/IframeTest.php b/dev/tests/integration/testsuite/Magento/Payment/Block/Transparent/IframeTest.php index aadbe9081da47..a3331bd20fe34 100644 --- a/dev/tests/integration/testsuite/Magento/Payment/Block/Transparent/IframeTest.php +++ b/dev/tests/integration/testsuite/Magento/Payment/Block/Transparent/IframeTest.php @@ -5,6 +5,10 @@ */ namespace Magento\Payment\Block\Transparent; +use Magento\Payment\Block\Transparent\Iframe; +use Magento\Framework\View\LayoutInterface; +use Magento\TestFramework\Helper\Bootstrap; + /** * Class IframeTest * @package Magento\Payment\Block\Transparent @@ -19,11 +23,9 @@ class IframeTest extends \PHPUnit_Framework_TestCase public function testToHtml($xssString) { /** @var $block Iframe */ - $block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( - 'Magento\Framework\View\LayoutInterface' - )->createBlock( - 'Magento\Payment\Block\Transparent\Iframe' - ); + $block = Bootstrap::getObjectManager() + ->get(LayoutInterface::class) + ->createBlock(Iframe::class); $block->setTemplate('transparent/iframe.phtml'); $block->setData( diff --git a/dev/tests/integration/testsuite/Magento/Vault/Model/PaymentTokenRepositoryTest.php b/dev/tests/integration/testsuite/Magento/Vault/Model/PaymentTokenRepositoryTest.php new file mode 100644 index 0000000000000..257bd36d26c09 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Vault/Model/PaymentTokenRepositoryTest.php @@ -0,0 +1,80 @@ +repository = $objectManager->create(PaymentTokenRepository::class); + $this->searchCriteriaBuilder = $objectManager->create( + \Magento\Framework\Api\SearchCriteriaBuilder::class + ); + $this->filterBuilder = $objectManager->get( + \Magento\Framework\Api\FilterBuilder::class + ); + $this->sortOrderBuilder = $objectManager->get( + \Magento\Framework\Api\SortOrderBuilder::class + ); + } + + /** + * @magentoDataFixture Magento/Vault/_files/payment_tokens.php + */ + public function testGetListWithMultipleFiltersAndSorting() + { + $filter1 = $this->filterBuilder + ->setField('type') + ->setValue('simple') + ->create(); + $filter2 = $this->filterBuilder + ->setField('is_active') + ->setValue(1) + ->create(); + $filter3 = $this->filterBuilder + ->setField('expires_at') + ->setConditionType('lt') + ->setValue('2016-11-04 10:18:15') + ->create(); + $sortOrder = $this->sortOrderBuilder + ->setField('public_hash') + ->setDirection('DESC') + ->create(); + + $this->searchCriteriaBuilder->addFilters([$filter1, $filter2]); + $this->searchCriteriaBuilder->addFilters([$filter3]); + $this->searchCriteriaBuilder->addSortOrder($sortOrder); + $searchCriteria = $this->searchCriteriaBuilder->create(); + /** @var \Magento\Vault\Api\Data\PaymentTokenSearchResultsInterface $result */ + $result = $this->repository->getList($searchCriteria); + $items = $result->getItems(); + $this->assertCount(2, $items); + $this->assertEquals('first', array_shift($items)->getPaymentMethodCode()); + $this->assertEquals('second', array_shift($items)->getPaymentMethodCode()); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Vault/Model/ResourceModel/PaymentTokenTest.php b/dev/tests/integration/testsuite/Magento/Vault/Model/ResourceModel/PaymentTokenTest.php new file mode 100644 index 0000000000000..88974f0d9cc5e --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Vault/Model/ResourceModel/PaymentTokenTest.php @@ -0,0 +1,114 @@ +objectManager = Bootstrap::getObjectManager(); + $this->order = $this->objectManager->create(Order::class); + $this->paymentToken = $this->objectManager->create(PaymentToken::class); + $this->paymentTokenManagement = $this->objectManager->get(PaymentTokenManagement::class); + + $this->resource = $this->objectManager->get(ResourceConnection::class); + $this->connection = $this->resource->getConnection(); + } + + /** + * @magentoDataFixture Magento/Sales/_files/order.php + * @magentoDataFixture Magento/Braintree/_files/paypal_vault_token.php + */ + public function testAddLinkToOrderPaymentExists() + { + $this->order->loadByIncrementId(self::ORDER_INCREMENT_ID); + $paymentToken = $this->paymentTokenManagement + ->getByGatewayToken(self::TOKEN, PayPalConfigProvider::PAYPAL_CODE, self::CUSTOMER_ID); + + $this->connection->insert( + $this->resource->getTableName(InstallSchema::ORDER_PAYMENT_TO_PAYMENT_TOKEN_TABLE), + [ + 'order_payment_id' => $this->order->getPayment()->getEntityId(), + 'payment_token_id' => $paymentToken->getEntityId() + ] + ); + + static::assertTrue( + $this->paymentToken->addLinkToOrderPayment( + $paymentToken->getEntityId(), + $this->order->getPayment()->getEntityId() + ) + ); + } + + /** + * @magentoDataFixture Magento/Sales/_files/order.php + * @magentoDataFixture Magento/Braintree/_files/paypal_vault_token.php + */ + public function testAddLinkToOrderPaymentCreate() + { + $this->order->loadByIncrementId(self::ORDER_INCREMENT_ID); + $paymentToken = $this->paymentTokenManagement + ->getByGatewayToken(self::TOKEN, PayPalConfigProvider::PAYPAL_CODE, self::CUSTOMER_ID); + + $select = $this->connection->select() + ->from($this->resource->getTableName(InstallSchema::ORDER_PAYMENT_TO_PAYMENT_TOKEN_TABLE)) + ->where('order_payment_id = ?', (int) $this->order->getPayment()->getEntityId()) + ->where('payment_token_id =?', (int) $paymentToken->getEntityId()); + + static::assertEmpty($this->connection->fetchRow($select)); + static::assertTrue( + $this->paymentToken->addLinkToOrderPayment( + $paymentToken->getEntityId(), + $this->order->getPayment()->getEntityId() + ) + ); + static::assertNotEmpty($this->connection->fetchRow($select)); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Vault/_files/customer.php b/dev/tests/integration/testsuite/Magento/Vault/_files/customer.php new file mode 100644 index 0000000000000..4a799bb4575e8 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Vault/_files/customer.php @@ -0,0 +1,34 @@ +create(\Magento\Customer\Api\CustomerRepositoryInterface::class); +$customer = $objectManager->create(\Magento\Customer\Model\Customer::class); +/** @var CustomerRegistry $customerRegistry */ +$customerRegistry = $objectManager->get(CustomerRegistry::class); +/** @var Magento\Customer\Model\Customer $customer */ +$customer->setWebsiteId(1) + ->setId(1) + ->setEmail('customer@example.com') + ->setPassword('password') + ->setGroupId(1) + ->setStoreId(1) + ->setIsActive(1) + ->setPrefix('Mr.') + ->setFirstname('John') + ->setMiddlename('A') + ->setLastname('Smith') + ->setSuffix('Esq.') + ->setDefaultBilling(1) + ->setDefaultShipping(1) + ->setTaxvat('12') + ->setGender(0); + +$customer->isObjectNew(true); +$customer->save(); +$customerRegistry->remove($customer->getId()); diff --git a/dev/tests/integration/testsuite/Magento/Vault/_files/payment_tokens.php b/dev/tests/integration/testsuite/Magento/Vault/_files/payment_tokens.php new file mode 100644 index 0000000000000..e021dc7d4372c --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Vault/_files/payment_tokens.php @@ -0,0 +1,54 @@ + 1, + 'public_hash' => '1234', + 'payment_method_code' => 'first', + 'type' => 'simple', + 'expires_at' => '2016-09-04 10:18:15', + 'is_active' => 1 + ], + [ + 'customer_id' => 1, + 'public_hash' => '12345', + 'payment_method_code' => 'second', + 'type' => 'simple', + 'expires_at' => '2016-10-04 10:18:15', + 'is_active' => 1 + ], + [ + 'customer_id' => 1, + 'public_hash' => '23456', + 'payment_method_code' => 'third', + 'type' => 'notsimple', + 'expires_at' => '2016-11-04 10:18:15', + 'is_active' => 1 + ], + [ + 'customer_id' => 1, + 'public_hash' => '234567', + 'payment_method_code' => 'fourth', + 'type' => 'simple', + 'expires_at' => '2016-12-04 10:18:15', + 'is_active' => 0 + ], +]; +/** @var array $tokenData */ +foreach ($paymentTokens as $tokenData) { + /** @var PaymentToken $bookmark */ + $paymentToken = $objectManager->create(PaymentToken::class); + $paymentToken + ->setData($tokenData) + ->save(); +} diff --git a/dev/tests/static/testsuite/Magento/Test/Js/_files/blacklist/magento.txt b/dev/tests/static/testsuite/Magento/Test/Js/_files/blacklist/magento.txt index 25096baf46912..1d1cb4ba2767a 100644 --- a/dev/tests/static/testsuite/Magento/Test/Js/_files/blacklist/magento.txt +++ b/dev/tests/static/testsuite/Magento/Test/Js/_files/blacklist/magento.txt @@ -7,16 +7,7 @@ app/code/Magento/Authorizenet/view/frontend/web/js/view/payment/authorizenet.js app/code/Magento/Authorizenet/view/frontend/web/js/view/payment/method-renderer/authorizenet-directpost.js app/code/Magento/Backend/view/adminhtml/web/js/bootstrap/editor.js app/code/Magento/Braintree/view/adminhtml/requirejs-config.js -app/code/Magento/Braintree/view/adminhtml/web/js/cc-data.js -app/code/Magento/Braintree/view/adminhtml/web/js/cc-form.js app/code/Magento/Braintree/view/frontend/requirejs-config.js -app/code/Magento/Braintree/view/frontend/web/js/braintree-paypal-shortcut.js -app/code/Magento/Braintree/view/frontend/web/js/cc-data.js -app/code/Magento/Braintree/view/frontend/web/js/cc-edit-form.js -app/code/Magento/Braintree/view/frontend/web/js/cc-form.js -app/code/Magento/Braintree/view/frontend/web/js/view/payment/braintree-methods.js -app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/braintree-paypal.js -app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/cc-form.js app/code/Magento/Bundle/view/adminhtml/web/js/bundle-product.js app/code/Magento/Bundle/view/base/web/js/price-bundle.js app/code/Magento/Bundle/view/frontend/requirejs-config.js From 82a4d67e3b3f199a1b73c28992472a70b791ecff Mon Sep 17 00:00:00 2001 From: Elena Marchenko Date: Tue, 25 Oct 2016 18:51:46 +0300 Subject: [PATCH 02/19] MAGETWO-59831: Port functional tests for payments --- .../Test/TestCase/OnePageCheckoutTest.xml | 13 +- .../Adminhtml/BraintreeSettlementReport.xml | 12 ++ .../Test/Page/Adminhtml/SalesOrderView.xml | 12 ++ .../Braintree/Test/Repository/ConfigData.xml | 121 ++++++--------- .../BraintreeSettlementReportTest.php | 6 +- .../BraintreeSettlementReportTest.xml | 4 +- .../CheckoutWithBraintreePaypalCartTest.php | 4 +- .../CheckoutWithBraintreePaypalCartTest.xml | 12 +- ...heckoutWithBraintreePaypalMinicartTest.php | 4 +- ...heckoutWithBraintreePaypalMinicartTest.xml | 12 +- ...ateOnlineCreditMemoBraintreePaypalTest.php | 4 +- ...ateOnlineCreditMemoBraintreePaypalTest.xml | 15 +- .../CreateOnlineInvoiceEntityTest.xml | 9 +- .../Test/TestCase/CreateOrderBackendTest.xml | 20 +-- ...derWithPayPalBraintreeVaultBackendTest.php | 56 +++++++ ...derWithPayPalBraintreeVaultBackendTest.xml | 32 ++++ .../TestCase/CreateVaultOrderBackendTest.xml | 7 +- .../TestCase/InvoicePayPalBraintreeTest.php | 4 +- .../TestCase/InvoicePaypalBraintreeTest.xml | 17 +- .../OnePageCheckoutAcceptPaymentTest.php | 40 +++++ .../OnePageCheckoutAcceptPaymentTest.xml | 30 ++++ .../OnePageCheckoutDenyPaymentTest.php | 40 +++++ .../OnePageCheckoutDenyPaymentTest.xml | 30 ++++ .../Test/TestCase/OnePageCheckoutTest.xml | 28 ++-- .../OnePageCheckoutWith3dSecureTest.php | 6 +- .../OnePageCheckoutWith3dSecureTest.xml | 6 +- ...OnePageCheckoutWithBraintreePaypalTest.php | 6 +- ...OnePageCheckoutWithBraintreePaypalTest.xml | 12 +- .../OnePageCheckoutWithDiscountTest.xml | 34 ++++ .../Test/TestCase/ReorderUsingVaultTest.xml | 33 ++++ ...veUseDeleteVaultForPaypalBraintreeTest.php | 58 +++++++ ...veUseDeleteVaultForPaypalBraintreeTest.xml | 30 ++++ .../Test/TestCase/UseVaultOnCheckoutTest.xml | 7 +- .../UseVaultWith3dSecureOnCheckoutTest.php | 58 +++++++ .../UseVaultWith3dSecureOnCheckoutTest.xml | 38 +++++ .../Test/TestStep/AcceptPaymentStep.php | 49 ++++++ .../ChangeOrderStatusToPaymentReviewStep.php | 84 ++++++++++ .../TestStep/CheckBraintreeConfigStep.php | 145 ++++++++++++++++++ .../Test/TestStep/ContinueToPaypalStep.php | 40 +++++ .../CreateBraintreeCreditMemoStep.php | 4 +- .../Test/TestStep/DenyPaymentStep.php | 49 ++++++ .../TestStep/PlaceOrderWithPaypalStep.php | 2 +- .../app/Magento/Braintree/Test/etc/di.xml | 4 +- .../Magento/Braintree/Test/etc/testcase.xml | 87 +++++++++++ .../Block/Onepage/Payment/DiscountCodes.php | 58 +++++++ .../Test/Block/Onepage/Payment/Method.php | 33 +++- .../Checkout/Test/Page/CheckoutOnepage.xml | 1 + .../Paypal/Test/Block/Express/Review.php | 3 +- .../CreatePayFlowOrderBackendNegativeTest.php | 50 ++++++ .../CreatePayFlowOrderBackendNegativeTest.xml | 29 ++++ .../TestCase/CreateVaultOrderBackendTest.xml | 7 +- .../ExpressCheckoutFromProductPageTest.php | 4 +- .../ExpressCheckoutFromProductPageTest.xml | 2 +- .../ExpressCheckoutFromShoppingCartTest.php | 4 +- .../ExpressCheckoutFromShoppingCartTest.xml | 6 +- .../TestCase/ExpressCheckoutOnePageTest.php | 4 +- .../TestCase/ExpressCheckoutOnePageTest.xml | 16 +- ...extExpressCheckoutFromShoppingCartTest.php | 4 +- ...extExpressCheckoutFromShoppingCartTest.xml | 4 +- .../InContextExpressOnePageCheckoutTest.php | 4 +- .../InContextExpressOnePageCheckoutTest.xml | 4 +- .../Test/TestCase/ReorderUsingVaultTest.xml | 33 ++++ .../Test/TestCase/UseVaultOnCheckoutTest.xml | 7 +- .../tests/app/Magento/Paypal/Test/etc/di.xml | 19 +++ .../app/Magento/Paypal/Test/etc/testcase.xml | 18 ++- .../Test/Block/Adminhtml/Order/Actions.php | 29 ++++ .../Test/Block/Adminhtml/Order/History.php | 54 +++++++ ...tAcceptPaymentMessageInCommentsHistory.php | 46 ++++++ ...sertAcceptPaymentSuccessMessagePresent.php | 45 ++++++ .../AssertAuthorizationInCommentsHistory.php | 2 +- ...ertDenyPaymentMessageInCommentsHistory.php | 45 ++++++ ...AssertDenyPaymentSuccessMessagePresent.php | 45 ++++++ ...sertRefundOrderStatusInCommentsHistory.php | 48 ++++++ .../Test/TestStep/SubmitOrderNegativeStep.php | 43 ++++++ .../{CreditCards.php => StoredPayments.php} | 20 ++- .../AssertStoredPaymentDeletedMessage.php | 44 ++++++ ...editCards.xml => StoredPaymentMethods.xml} | 4 +- .../TestCase/CreateVaultOrderBackendTest.php | 4 +- .../TestCase/DeleteSavedCreditCardTest.php | 44 ++++-- .../TestCase/DeleteSavedCreditCardTest.xml | 10 +- .../Test/TestCase/ReorderUsingVaultTest.php | 52 +++++++ .../Test/TestCase/UseVaultOnCheckoutTest.php | 4 +- .../DeleteCreditCardFromMyAccountStep.php | 37 +++-- .../Test/TestStep/DeleteStoredPaymentStep.php | 50 ++++++ .../TestStep/UseSavedPaymentMethodStep.php | 51 ++++++ .../TestStep/UseVaultPaymentTokenStep.php | 15 +- .../tests/app/Magento/Vault/Test/etc/di.xml | 19 +++ .../app/Magento/Vault/Test/etc/testcase.xml | 25 ++- 88 files changed, 2079 insertions(+), 251 deletions(-) create mode 100644 dev/tests/functional/tests/app/Magento/Braintree/Test/Page/Adminhtml/BraintreeSettlementReport.xml create mode 100644 dev/tests/functional/tests/app/Magento/Braintree/Test/Page/Adminhtml/SalesOrderView.xml create mode 100644 dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOrderWithPayPalBraintreeVaultBackendTest.php create mode 100644 dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOrderWithPayPalBraintreeVaultBackendTest.xml create mode 100644 dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutAcceptPaymentTest.php create mode 100644 dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutAcceptPaymentTest.xml create mode 100644 dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutDenyPaymentTest.php create mode 100644 dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutDenyPaymentTest.xml create mode 100644 dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWithDiscountTest.xml create mode 100644 dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/ReorderUsingVaultTest.xml create mode 100644 dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/SaveUseDeleteVaultForPaypalBraintreeTest.php create mode 100644 dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/SaveUseDeleteVaultForPaypalBraintreeTest.xml create mode 100644 dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/UseVaultWith3dSecureOnCheckoutTest.php create mode 100644 dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/UseVaultWith3dSecureOnCheckoutTest.xml create mode 100644 dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/AcceptPaymentStep.php create mode 100644 dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/ChangeOrderStatusToPaymentReviewStep.php create mode 100644 dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/CheckBraintreeConfigStep.php create mode 100644 dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/ContinueToPaypalStep.php create mode 100644 dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/DenyPaymentStep.php create mode 100644 dev/tests/functional/tests/app/Magento/Checkout/Test/Block/Onepage/Payment/DiscountCodes.php create mode 100644 dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/CreatePayFlowOrderBackendNegativeTest.php create mode 100644 dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/CreatePayFlowOrderBackendNegativeTest.xml create mode 100644 dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ReorderUsingVaultTest.xml create mode 100644 dev/tests/functional/tests/app/Magento/Paypal/Test/etc/di.xml create mode 100644 dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertAcceptPaymentMessageInCommentsHistory.php create mode 100644 dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertAcceptPaymentSuccessMessagePresent.php create mode 100644 dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertDenyPaymentMessageInCommentsHistory.php create mode 100644 dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertDenyPaymentSuccessMessagePresent.php create mode 100644 dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertRefundOrderStatusInCommentsHistory.php create mode 100644 dev/tests/functional/tests/app/Magento/Sales/Test/TestStep/SubmitOrderNegativeStep.php rename dev/tests/functional/tests/app/Magento/Vault/Test/Block/{CreditCards.php => StoredPayments.php} (75%) create mode 100644 dev/tests/functional/tests/app/Magento/Vault/Test/Constraint/AssertStoredPaymentDeletedMessage.php rename dev/tests/functional/tests/app/Magento/Vault/Test/Page/{MyCreditCards.xml => StoredPaymentMethods.xml} (65%) create mode 100644 dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/ReorderUsingVaultTest.php create mode 100644 dev/tests/functional/tests/app/Magento/Vault/Test/TestStep/DeleteStoredPaymentStep.php create mode 100644 dev/tests/functional/tests/app/Magento/Vault/Test/TestStep/UseSavedPaymentMethodStep.php create mode 100644 dev/tests/functional/tests/app/Magento/Vault/Test/etc/di.xml diff --git a/dev/tests/functional/tests/app/Magento/Authorizenet/Test/TestCase/OnePageCheckoutTest.xml b/dev/tests/functional/tests/app/Magento/Authorizenet/Test/TestCase/OnePageCheckoutTest.xml index 2ea4873f454a3..8a362628edaea 100644 --- a/dev/tests/functional/tests/app/Magento/Authorizenet/Test/TestCase/OnePageCheckoutTest.xml +++ b/dev/tests/functional/tests/app/Magento/Authorizenet/Test/TestCase/OnePageCheckoutTest.xml @@ -6,12 +6,12 @@ */ --> - - - catalogProductSimple::product_10_dollar + + + catalogProductSimple::product_10_dollar default - US_address_1 - guest + login + US_address_1_without_email Flat Rate Fixed @@ -26,8 +26,7 @@ No Authorization - test_type:3rd_party_test_deprecated - + test_type:3rd_party_test severity:S0 diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Page/Adminhtml/BraintreeSettlementReport.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/Page/Adminhtml/BraintreeSettlementReport.xml new file mode 100644 index 0000000000000..bd2a0e60b20ab --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/Page/Adminhtml/BraintreeSettlementReport.xml @@ -0,0 +1,12 @@ + + + + + + + diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Page/Adminhtml/SalesOrderView.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/Page/Adminhtml/SalesOrderView.xml new file mode 100644 index 0000000000000..be96e88c35f81 --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/Page/Adminhtml/SalesOrderView.xml @@ -0,0 +1,12 @@ + + + + + + + diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Repository/ConfigData.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/Repository/ConfigData.xml index 916943e03af97..7f01e4f46106c 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Repository/ConfigData.xml +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/Repository/ConfigData.xml @@ -11,25 +11,25 @@ payment 1 - + PAYMENT_BRAINTREE_MERCHANT_ID PAYMENT_BRAINTREE_MERCHANT_ID payment 1 - + PAYMENT_PAYMENT_BRAINTREE_PUBLIC_KEY PAYMENT_PAYMENT_BRAINTREE_PUBLIC_KEY payment 1 - + PAYMENT_BRAINTREE_PRIVATE_KEY PAYMENT_BRAINTREE_PRIVATE_KEY payment 1 - Yes + PAYMENT_BRAINTREE_MERCHANT_ACCOUNT_ID PAYMENT_BRAINTREE_MERCHANT_ACCOUNT_ID @@ -55,61 +55,17 @@ payment 1 - Yes + No 0 - - payment - 1 - - PAYMENT_BRAINTREE_MERCHANT_ID - - - payment - 1 - - PAYMENT_PAYMENT_BRAINTREE_PUBLIC_KEY - - - payment - 1 - - PAYMENT_BRAINTREE_PRIVATE_KEY - - - payment - 1 - Yes - PAYMENT_BRAINTREE_MERCHANT_ACCOUNT_ID - payment 1 Authorize and Capture authorize_capture - - payment - 1 - Yes - 1 - - - payment - 1 - Yes - 1 - - - - - payment - 1 - Yes - 0 - @@ -123,7 +79,7 @@ payment 1 - Yes + No 0 @@ -143,6 +99,9 @@ payment 1 + + GB + GB @@ -152,13 +111,13 @@ payment 1 - Yes + No 0 payment 1 - Yes + No 0 @@ -172,7 +131,7 @@ payment 1 - Yes + 300 300 @@ -180,13 +139,7 @@ payment 1 - Yes - 0 - - - payment - 1 - Yes + No 0 @@ -224,36 +177,64 @@ payment 1 - Yes + No 0 - + + payment + 1 + Authorize and Capture + authorize_capture + + + + payment 1 Yes 1 - + + + payment 1 - Authorize and Capture - authorize_capture + No + 0 - - + + payment 1 Yes + 1 + + + + + payment + 1 + No 0 - + + + payment 1 - Authorize - authorize + Yes + 1 + + + + + payment + 1 + No + 0 diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/BraintreeSettlementReportTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/BraintreeSettlementReportTest.php index 95b2234607d37..dda155f7fd66b 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/BraintreeSettlementReportTest.php +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/BraintreeSettlementReportTest.php @@ -19,7 +19,7 @@ * 1. Log in Storefront. * 2. Add products to the Shopping Cart. * 3. In 'Estimate Shipping and Tax' section specify destination using values from Test Data. - * 4. Click the 'Go to Checkout' button. + * 4. Click the 'Proceed to Checkout' button. * 5. Fill shipping information. * 6. Select shipping method. * 7. Select payment method (use reward points and store credit if available). @@ -30,15 +30,15 @@ * 12. Find transaction for latest order. * 13. Perform assertions. * - * @group Braintree_(CS) + * @group Braintree * @ZephyrId MAGETWO-48162 */ class BraintreeSettlementReportTest extends Scenario { /* tags */ const MVP = 'yes'; - const DOMAIN = 'CS'; const TEST_TYPE = '3rd_party_test'; + const SEVERITY = 'S1'; /* end tags */ /** diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/BraintreeSettlementReportTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/BraintreeSettlementReportTest.xml index dbdbca2378661..e80f6071ae5d1 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/BraintreeSettlementReportTest.xml +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/BraintreeSettlementReportTest.xml @@ -8,7 +8,7 @@ - catalogProductSimple::product_10_dollar + catalogProductSimple::product_10_dollar default US_address_1_without_email login @@ -22,7 +22,7 @@ visa_braintree braintree Processing - test_type:extended_acceptance_test, test_type:3rd_party_test + test_type:extended_acceptance_test, test_type:3rd_party_test, severity:S1 diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalCartTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalCartTest.php index 8bad13557c888..c9d0904c85d67 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalCartTest.php +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalCartTest.php @@ -25,15 +25,15 @@ * 8. Select payment method * 12. Perform assertions. * - * @group Braintree_(CS) + * @group Braintree * @ZephyrId MAGETWO-39363 */ class CheckoutWithBraintreePaypalCartTest extends Scenario { /* tags */ const MVP = 'yes'; - const DOMAIN = 'CS'; const TEST_TYPE = '3rd_party_test'; + const SEVERITY = 'S0'; /* end tags */ /** diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalCartTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalCartTest.xml index 8bb0cc1d84e04..9e1090d6a22f9 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalCartTest.xml +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalCartTest.xml @@ -8,7 +8,7 @@ - catalogProductSimple::product_10_dollar + catalogProductSimple::product_10_dollar default US_address_1_without_email login @@ -18,16 +18,16 @@ 15.00 braintree_paypal - braintree, braintree_paypal + braintree, braintree_paypal, braintree_paypal_skip_order_review Processing - test_type:3rd_party_test + test_type:3rd_party_test, severity:S0 - catalogProductSimple::product_10_dollar + catalogProductSimple::product_10_dollar default US_address_1_without_email login @@ -40,9 +40,9 @@ 15.00 braintree_paypal - braintree, braintree_paypal_sale + braintree, braintree_paypal, braintree_paypal_sale, braintree_paypal_skip_order_review Processing - test_type:3rd_party_test + test_type:3rd_party_test, severity:S0 diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalMinicartTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalMinicartTest.php index d6723c71816f9..9ee6bfb7c4e29 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalMinicartTest.php +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalMinicartTest.php @@ -25,15 +25,15 @@ * 8. Select payment method * 12. Perform assertions. * - * @group Braintree_(CS) + * @group Braintree * @ZephyrId MAGETWO-39359 */ class CheckoutWithBraintreePaypalMinicartTest extends Scenario { /* tags */ const MVP = 'yes'; - const DOMAIN = 'CS'; const TEST_TYPE = '3rd_party_test'; + const SEVERITY = 'S0'; /* end tags */ /** diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalMinicartTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalMinicartTest.xml index 03707a79d96d9..b41ea91e45982 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalMinicartTest.xml +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalMinicartTest.xml @@ -8,7 +8,7 @@ - catalogProductSimple::product_10_dollar + catalogProductSimple::product_10_dollar default US_address_1_without_email login @@ -18,16 +18,16 @@ 15.00 braintree_paypal - braintree, braintree_paypal + braintree, braintree_paypal, braintree_paypal_skip_order_review Processing - test_type:3rd_party_test + test_type:3rd_party_test, severity:S0 - catalogProductSimple::product_10_dollar + catalogProductSimple::product_10_dollar default US_address_1_without_email login @@ -40,9 +40,9 @@ 15.00 braintree_paypal - braintree, braintree_paypal_sale + braintree, braintree_paypal, braintree_paypal_sale, braintree_paypal_skip_order_review Processing - test_type:3rd_party_test + test_type:3rd_party_test, severity:S0 diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineCreditMemoBraintreePaypalTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineCreditMemoBraintreePaypalTest.php index f45270012dd39..9e6cf0991db4e 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineCreditMemoBraintreePaypalTest.php +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineCreditMemoBraintreePaypalTest.php @@ -17,15 +17,15 @@ * 3. Create credit memo. * 4. Perform assertions. * - * @group Braintree_(CS) + * @group Braintree * @ZephyrId MAGETWO-48689, MAGETWO-48698 */ class CreateOnlineCreditMemoBraintreePaypalTest extends Scenario { /* tags */ const MVP = 'yes'; - const DOMAIN = 'CS'; const TEST_TYPE = '3rd_party_test'; + const SEVERITY = 'S1'; /* end tags */ /** diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineCreditMemoBraintreePaypalTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineCreditMemoBraintreePaypalTest.xml index d0071ddd75db0..53847e55fd9f9 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineCreditMemoBraintreePaypalTest.xml +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineCreditMemoBraintreePaypalTest.xml @@ -8,7 +8,8 @@ - catalogProductSimple::product_10_dollar, bundleProduct::bundle_fixed_100_dollar_product + catalogProductSimple::product_10_dollar + bundleProduct::bundle_fixed_100_dollar_product default login us_ca_ny_rule @@ -19,17 +20,16 @@ Flat Rate Fixed braintree_paypal - braintree, braintree_paypal_sale + braintree, braintree_paypal, braintree_paypal_sale, braintree_paypal_skip_order_review sale - Back, Send Email, Credit Memo, Hold, Ship, Reorder - - test_type:3rd_party_test + test_type:3rd_party_test, severity:S1 - catalogProductSimple::simple_for_sales + catalogProductSimple::simple_for_sales default login us_ca_ny_rule @@ -40,13 +40,12 @@ Flat Rate Fixed braintree_paypal - braintree, braintree_paypal - Back, Send Email, Credit Memo, Hold, Ship, Reorder + braintree, braintree_paypal, braintree_paypal_skip_order_review 2 1 default Yes - test_type:3rd_party_test + test_type:3rd_party_test, severity:S1 diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineInvoiceEntityTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineInvoiceEntityTest.xml index 395cc0257e9e8..d9f382e4b650e 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineInvoiceEntityTest.xml +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineInvoiceEntityTest.xml @@ -9,7 +9,8 @@ Full capture of order placed within Braintree Credit Card - catalogProductSimple::product_10_dollar, bundleProduct::bundle_fixed_100_dollar_product + catalogProductSimple::product_10_dollar + bundleProduct::bundle_fixed_100_dollar_product default us_ca_ny_rule US_address_1_without_email @@ -28,7 +29,7 @@ - No comments - test_type:3rd_party_test + test_type:3rd_party_test, severity:S1 @@ -36,7 +37,7 @@ Partial capture for order placed within Braintree Credit Card - catalogProductSimple::product_100_dollar + catalogProductSimple::product_100_dollar default us_ca_ny_rule US_address_1_without_email @@ -57,7 +58,7 @@ 1 No comments - test_type:3rd_party_test + test_type:3rd_party_test, severity:S1 diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOrderBackendTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOrderBackendTest.xml index 9b581ddaa61a7..9614923691c6c 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOrderBackendTest.xml +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOrderBackendTest.xml @@ -8,8 +8,10 @@ - test_type:3rd_party_test - catalogProductSimple::product_10_dollar, configurableProduct::with_one_option, bundleProduct::bundle_fixed_100_dollar_product + test_type:3rd_party_test, severity:S0 + catalogProductSimple::product_10_dollar + configurableProduct::with_one_option + bundleProduct::bundle_fixed_100_dollar_product default us_ca_ny_rule US_address_1_without_email @@ -24,18 +26,19 @@ visa_braintree braintree Processing - Back, Cancel, Send Email, Hold, Invoice, Ship + Back, Cancel, Send Email, Hold, Invoice, Ship, Reorder, Edit - - test_type:extended_acceptance_test, test_type:3rd_party_test - catalogProductSimple::product_10_dollar, configurableProduct::with_one_option, bundleProduct::bundle_fixed_100_dollar_product + test_type:extended_acceptance_test, test_type:3rd_party_test, severity:S0 + catalogProductSimple::product_10_dollar + configurableProduct::with_one_option + bundleProduct::bundle_fixed_100_dollar_product default us_ca_ny_rule US_address_1_without_email @@ -51,15 +54,14 @@ braintree credit_card_braintree visa_braintree - braintree_sale + braintree, braintree_sale Processing - Back, Send Email, Hold, Ship + Back, Send Email, Hold, Ship, Reorder - diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOrderWithPayPalBraintreeVaultBackendTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOrderWithPayPalBraintreeVaultBackendTest.php new file mode 100644 index 0000000000000..6fde39412d1fe --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOrderWithPayPalBraintreeVaultBackendTest.php @@ -0,0 +1,56 @@ +executeScenario(); + } +} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOrderWithPayPalBraintreeVaultBackendTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOrderWithPayPalBraintreeVaultBackendTest.xml new file mode 100644 index 0000000000000..03e0ba330fa3b --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOrderWithPayPalBraintreeVaultBackendTest.xml @@ -0,0 +1,32 @@ + + + + + + est_type:3rd_party_test, severity:S0 + catalogProductSimple::product_10_dollar + default + US_address_1_without_email + login + Flat Rate + Fixed + braintree_paypal + braintree_paypal_vault + Processing + braintree, braintree_paypal, braintree_paypal_use_vault, braintree_paypal_skip_order_review + + 15.00 + + + + + + + + + diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateVaultOrderBackendTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateVaultOrderBackendTest.xml index 0ae7da744c2f4..c9b26df050cfc 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateVaultOrderBackendTest.xml +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateVaultOrderBackendTest.xml @@ -8,8 +8,8 @@ - test_type:3rd_party_test - catalogProductSimple::product_10_dollar + test_type:3rd_party_test, severity:S0 + catalogProductSimple::product_10_dollar default US_address_1_without_email No @@ -19,12 +19,13 @@ 15.00 braintree + braintree_cc_vault credit_card_braintree visa_braintree Yes braintree, braintree_use_vault Processing - Back, Cancel, Send Email, Hold, Invoice, Ship + Back, Cancel, Send Email, Hold, Invoice, Ship, Reorder, Edit diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/InvoicePayPalBraintreeTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/InvoicePayPalBraintreeTest.php index 625c24866e31f..062de338d8921 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/InvoicePayPalBraintreeTest.php +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/InvoicePayPalBraintreeTest.php @@ -21,15 +21,15 @@ * 6. Open Invoices tab. * 7. Perform assertions. * - * @group Braintree_(CS) + * @group Braintree * @ZephyrId MAGETWO-48614, MAGETWO-48615 */ class InvoicePayPalBraintreeTest extends Scenario { /* tags */ const MVP = 'yes'; - const DOMAIN = 'CS'; const TEST_TYPE = '3rd_party_test'; + const SEVERITY = 'S1'; /* end tags */ /** diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/InvoicePaypalBraintreeTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/InvoicePaypalBraintreeTest.xml index 418eaab55aea1..352e0ed684919 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/InvoicePaypalBraintreeTest.xml +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/InvoicePaypalBraintreeTest.xml @@ -9,7 +9,8 @@ Full capture of order placed within Braintree PayPal - catalogProductSimple::product_10_dollar, bundleProduct::bundle_fixed_100_dollar_product + catalogProductSimple::product_10_dollar + bundleProduct::bundle_fixed_100_dollar_product us_illinois_tax_rule Flat Rate Fixed @@ -20,19 +21,19 @@ 139.9 braintree_paypal - braintree, braintree_paypal - Back, Send Email, Credit Memo, Hold, Ship + braintree, braintree_paypal, braintree_paypal_skip_order_review + Back, Send Email, Credit Memo, Hold, Ship, Reorder - No comments - test_type:3rd_party_test + test_type:3rd_party_test, severity:S1 Partial capture for order placed within Braintree PayPal - catalogProductSimple::product_100_dollar + catalogProductSimple::product_100_dollar us_illinois_tax_rule Flat Rate Fixed @@ -45,12 +46,12 @@ 108.25 braintree_paypal - braintree, braintree_paypal - Back, Send Email, Credit Memo, Hold, Ship + braintree, braintree_paypal, braintree_paypal_skip_order_review + Back, Send Email, Credit Memo, Hold, Ship, Reorder 1 No comments - test_type:3rd_party_test + test_type:3rd_party_test, severity:S1 diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutAcceptPaymentTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutAcceptPaymentTest.php new file mode 100644 index 0000000000000..68d36f3c754cf --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutAcceptPaymentTest.php @@ -0,0 +1,40 @@ + Orders page. + * 3. Open the placed order. + * 4. Click Accept button. + * 5. Perform assertions. + * + * @group Braintree + * @ZephyrId MAGETWO-56023 + */ +class OnePageCheckoutAcceptPaymentTest extends Scenario +{ + /* tags */ + const MVP = 'yes'; + const TEST_TYPE = 'acceptance_test, 3rd_party_test'; + const SEVERITY = 'S2'; + /* end tags */ + + /** + * Runs one page checkout test. + * @return void + */ + public function test() + { + $this->executeScenario(); + } +} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutAcceptPaymentTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutAcceptPaymentTest.xml new file mode 100644 index 0000000000000..841145d7a5fdf --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutAcceptPaymentTest.xml @@ -0,0 +1,30 @@ + + + + + + + catalogProductSimple::product_10_dollar + + default + US_address_1 + guest + Flat Rate + Fixed + braintree + credit_card_braintree + visa_braintree + braintree,braintree_fraudprotection + Processing + test_type:3rd_party_test, severity:S2 + + + + + + diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutDenyPaymentTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutDenyPaymentTest.php new file mode 100644 index 0000000000000..143ecb5a65d7d --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutDenyPaymentTest.php @@ -0,0 +1,40 @@ + Orders page. + * 3. Open the placed order. + * 4. Click Deny button. + * 5. Perform assertions. + * + * @group Braintree + * @ZephyrId MAGETWO-56024 + */ +class OnePageCheckoutDenyPaymentTest extends Scenario +{ + /* tags */ + const MVP = 'yes'; + const TEST_TYPE = 'acceptance_test, 3rd_party_test'; + const SEVERITY = 'S2'; + /* end tags */ + + /** + * Runs one page checkout test. + * @return void + */ + public function test() + { + $this->executeScenario(); + } +} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutDenyPaymentTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutDenyPaymentTest.xml new file mode 100644 index 0000000000000..95d07079ef36c --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutDenyPaymentTest.xml @@ -0,0 +1,30 @@ + + + + + + + catalogProductSimple::product_10_dollar + + default + US_address_1 + guest + Flat Rate + Fixed + braintree + credit_card_braintree + visa_braintree + braintree,braintree_fraudprotection + Canceled + test_type:3rd_party_test, severity:S2 + + + + + + diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutTest.xml index 1e6df43a7a8e4..1e9c539c8c0d3 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutTest.xml +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutTest.xml @@ -8,7 +8,9 @@ - catalogProductSimple::product_10_dollar, configurableProduct::with_one_option, bundleProduct::bundle_fixed_100_dollar_product + catalogProductSimple::product_10_dollar + configurableProduct::with_one_option + bundleProduct::bundle_fixed_100_dollar_product default us_ca_ny_rule US_address_1_without_email @@ -23,13 +25,15 @@ visa_braintree_3dsecure braintree, braintree_3d_secure_not_triggered_due_threshold Processing - test_type:3rd_party_test + test_type:3rd_party_test, severity:S1 - catalogProductSimple::product_10_dollar, configurableProduct::with_one_option, bundleProduct::bundle_fixed_100_dollar_product + catalogProductSimple::product_10_dollar + configurableProduct::with_one_option + bundleProduct::bundle_fixed_100_dollar_product default us_ca_ny_rule US_address_1 @@ -44,13 +48,15 @@ visa_braintree_3dsecure braintree, braintree_3d_secure_uk Processing - test_type:3rd_party_test + test_type:3rd_party_test, severity:S1 - catalogProductSimple::product_10_dollar, configurableProduct::with_one_option, bundleProduct::bundle_fixed_100_dollar_product + catalogProductSimple::product_10_dollar + configurableProduct::with_one_option + bundleProduct::bundle_fixed_100_dollar_product default us_ca_ny_rule US_address_1 @@ -65,14 +71,16 @@ visa_braintree braintree Processing - test_type:extended_acceptance_test, test_type:3rd_party_test + test_type:extended_acceptance_test, test_type:3rd_party_test, severity:S0 - - catalogProductSimple::product_10_dollar, configurableProduct::with_one_option, bundleProduct::bundle_fixed_100_dollar_product + + catalogProductSimple::product_10_dollar + configurableProduct::with_one_option + bundleProduct::bundle_fixed_100_dollar_product default us_ca_ny_rule US_address_1 @@ -88,9 +96,9 @@ braintree credit_card_braintree visa_braintree - braintree_sale + braintree, braintree_sale Processing - test_type:3rd_party_test + test_type:3rd_party_test, severity:S0 diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWith3dSecureTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWith3dSecureTest.php index 5b6e254cee011..e4b7d82094db5 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWith3dSecureTest.php +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWith3dSecureTest.php @@ -21,7 +21,7 @@ * 2. Add products to the Shopping Cart. * 3. Apply discounts in Shopping Cart according to dataset. * 4. In 'Estimate Shipping and Tax' section specify destination using values from Test Data. - * 5. Click the 'Go to Checkout' button. + * 5. Click the 'Proceed to Checkout' button. * 6. Fill shipping information. * 7. Select shipping method. * 8. Select payment method (use reward points and store credit if available). @@ -31,15 +31,15 @@ * 12. Click 'Submit' to place order. * 13. Perform assertions. * - * @group Braintree_(CS) + * @group Braintree * @ZephyrId MAGETWO-46479 */ class OnePageCheckoutWith3dSecureTest extends Scenario { /* tags */ const MVP = 'yes'; - const DOMAIN = 'CS'; const TEST_TYPE = '3rd_party_test'; + const SEVERITY = 'S1'; /* end tags */ /** diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWith3dSecureTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWith3dSecureTest.xml index fa4d750e16e90..295a9dcd5c533 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWith3dSecureTest.xml +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWith3dSecureTest.xml @@ -9,7 +9,9 @@ Registered Checkout with Braintree Credit Card from Storefront with success 3D Secure verification - catalogProductSimple::product_10_dollar, configurableProduct::with_one_option, bundleProduct::bundle_fixed_100_dollar_product + catalogProductSimple::product_10_dollar + configurableProduct::with_one_option + bundleProduct::bundle_fixed_100_dollar_product default us_ca_ny_rule US_address_1_without_email @@ -29,7 +31,7 @@ secure3d_braintree braintree, braintree_3d_secure Processing - test_type:3rd_party_test + test_type:3rd_party_test, severity:S1 diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWithBraintreePaypalTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWithBraintreePaypalTest.php index 092a03b78ed8f..a984f666c4356 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWithBraintreePaypalTest.php +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWithBraintreePaypalTest.php @@ -19,7 +19,7 @@ * 1. Log in Storefront. * 2. Add products to the Shopping Cart. * 3. In 'Estimate Shipping and Tax' section specify destination using values from Test Data. - * 4. Click the 'Go to Checkout' button. + * 4. Click the 'Proceed to Checkout' button. * 5. Fill shipping information. * 6. Select shipping method. * 8. Select payment method @@ -28,7 +28,7 @@ * 11. Click 'Proceed purchase' in popup. * 12. Perform assertions. * - * @group Braintree_(CS) + * @group Braintree * @ZephyrId MAGETWO-47805 * @ZephyrId MAGETWO-47810 */ @@ -36,8 +36,8 @@ class OnePageCheckoutWithBraintreePaypalTest extends Scenario { /* tags */ const MVP = 'yes'; - const DOMAIN = 'CS'; const TEST_TYPE = '3rd_party_test'; + const SEVERITY = 'S0'; /* end tags */ /** diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWithBraintreePaypalTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWithBraintreePaypalTest.xml index fbd2569a18462..7e38e6f0303b6 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWithBraintreePaypalTest.xml +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWithBraintreePaypalTest.xml @@ -9,7 +9,7 @@ Registered Checkout with Braintree PayPal from Storefront - catalogProductSimple::product_10_dollar + catalogProductSimple::product_10_dollar default US_address_1_without_email login @@ -19,9 +19,9 @@ 15.00 braintree_paypal - braintree, braintree_paypal + braintree, braintree_paypal, braintree_paypal_skip_order_review Processing - test_type:3rd_party_test + test_type:3rd_party_test, severity:S0 @@ -29,7 +29,7 @@ Registered Checkout with Braintree PayPal from Storefront with payment action Authorize and Capture - catalogProductSimple::product_10_dollar + catalogProductSimple::product_10_dollar default US_address_1_without_email login @@ -42,9 +42,9 @@ 15.00 braintree_paypal - braintree, braintree_paypal_sale + braintree, braintree_paypal, braintree_paypal_sale, braintree_paypal_skip_order_review Processing - test_type:3rd_party_test + test_type:3rd_party_test, severity:S0 diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWithDiscountTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWithDiscountTest.xml new file mode 100644 index 0000000000000..23fc729edb99f --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWithDiscountTest.xml @@ -0,0 +1,34 @@ + + + + + + Use saved for Braintree credit card on checkout + catalogProductSimple::product_10_dollar + default + active_sales_rule_for_all_groups + US_address_1_without_email + login + Flat Rate + Fixed + braintree + credit_card_braintree + visa_braintree + + 10.00 + + Yes + braintree, braintree_use_vault + Processing + test_type:3rd_party_test, severity:S1 + + + + + + diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/ReorderUsingVaultTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/ReorderUsingVaultTest.xml new file mode 100644 index 0000000000000..ad4d5cc06e92e --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/ReorderUsingVaultTest.xml @@ -0,0 +1,33 @@ + + + + + + Reorder from Admin with saved within Braintree credit card for Guest Customer + catalogProductSimple::product_10_dollar + default + US_address_1 + guest + Flat Rate + Fixed + + 15.00 + + braintree + braintree_cc_vault + credit_card_braintree + visa_braintree + braintree, braintree_use_vault + Processing + test_type:3rd_party_test, severity:S1 + + + + + + diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/SaveUseDeleteVaultForPaypalBraintreeTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/SaveUseDeleteVaultForPaypalBraintreeTest.php new file mode 100644 index 0000000000000..8845f2a78629d --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/SaveUseDeleteVaultForPaypalBraintreeTest.php @@ -0,0 +1,58 @@ + Stored Payment Methods* section. + * 14. Click *Delete* link next to stored PayPal payer account. + * 15. Click *Delete* button on appeared pop up. + * 16. Perform assertions. * + * + * @group Braintree + * @ZephyrId MAGETWO-54838, MAGETWO-54843, MAGETWO-54844" + */ +class SaveUseDeleteVaultForPaypalBraintreeTest extends Scenario +{ + /* tags */ + const MVP = 'yes'; + const TEST_TYPE = '3rd_party_test'; + const SEVERITY = 'S0'; + /* end tags */ + + /** + * Saves vault for PayPal Braintree on checkout, uses it during checkout, deletes it from My Account. + * + * @return void + */ + public function test() + { + $this->executeScenario(); + } +} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/SaveUseDeleteVaultForPaypalBraintreeTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/SaveUseDeleteVaultForPaypalBraintreeTest.xml new file mode 100644 index 0000000000000..c7a5182a1dfb3 --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/SaveUseDeleteVaultForPaypalBraintreeTest.xml @@ -0,0 +1,30 @@ + + + + + + Use saved for Braintree credit card on checkout + catalogProductSimple::product_10_dollar + default + US_address_1_without_email + login + Flat Rate + Fixed + + 15.00 + + braintree_paypal + braintree_paypal_vault + Yes + braintree, braintree_paypal, braintree_paypal_use_vault + Processing + test_type:3rd_party_test, severity:S0 + + + + diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/UseVaultOnCheckoutTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/UseVaultOnCheckoutTest.xml index cfe2e5f51b18e..35d55784b6762 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/UseVaultOnCheckoutTest.xml +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/UseVaultOnCheckoutTest.xml @@ -9,20 +9,21 @@ Use saved for Braintree credit card on checkout - catalogProductSimple::product_10_dollar + catalogProductSimple::product_10_dollar default US_address_1_without_email login Flat Rate Fixed braintree + braintree_cc_vault credit_card_braintree visa_braintree Yes braintree, braintree_use_vault Processing - test_type:3rd_party_test - Back, Cancel, Send Email, Hold, Invoice, Ship + test_type:3rd_party_test, severity:S0 + Back, Cancel, Send Email, Hold, Invoice, Ship, Reorder, Edit diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/UseVaultWith3dSecureOnCheckoutTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/UseVaultWith3dSecureOnCheckoutTest.php new file mode 100644 index 0000000000000..d2723a300285d --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/UseVaultWith3dSecureOnCheckoutTest.php @@ -0,0 +1,58 @@ +executeScenario(); + } +} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/UseVaultWith3dSecureOnCheckoutTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/UseVaultWith3dSecureOnCheckoutTest.xml new file mode 100644 index 0000000000000..a5aa7645148e1 --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/UseVaultWith3dSecureOnCheckoutTest.xml @@ -0,0 +1,38 @@ + + + + + + Use saved for Braintree credit card on checkout + catalogProductSimple::product_10_dollar + default + US_address_1_without_email + login + Flat Rate + Fixed + braintree + braintree_cc_vault + credit_card_braintree + visa_braintree_3dsecure + + 1 + 1 + + secure3d_braintree + Yes + braintree, braintree_use_vault, braintree_3d_secure + Processing + test_type:3rd_party_test, severity:S1 + Back, Cancel, Send Email, Hold, Invoice, Ship + + + + + + + diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/AcceptPaymentStep.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/AcceptPaymentStep.php new file mode 100644 index 0000000000000..6565652f604cb --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/AcceptPaymentStep.php @@ -0,0 +1,49 @@ +orderIndex = $orderIndex; + $this->salesOrderView = $salesOrderView; + $this->order = $order; + } + + /** + * @inheritdoc + */ + public function run() + { + $this->orderIndex->open(); + $this->orderIndex->getSalesOrderGrid()->searchAndOpen(['id' => $this->order->getId()]); + $this->salesOrderView->getPageActions()->accept(); + } +} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/ChangeOrderStatusToPaymentReviewStep.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/ChangeOrderStatusToPaymentReviewStep.php new file mode 100644 index 0000000000000..346a7e8e7e4f4 --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/ChangeOrderStatusToPaymentReviewStep.php @@ -0,0 +1,84 @@ +orderId = $orderId; + $this->webApi = $webApi; + } + + /** + * @inheritdoc + */ + public function run() + { + $order = $this->getOrder($this->orderId); + $order['state'] = 'payment_review'; + $order['status'] = 'fraud'; + $this->saveOrder($order); + } + + /** + * Get order by increment id + * @param string $incrementId + * @return array + */ + private function getOrder($incrementId) + { + $url = $_ENV['app_frontend_url'] . 'rest/V1/orders/'; + $url .= '?searchCriteria[filterGroups][0][filters][0][field]=increment_id'; + $url .= '&searchCriteria[filterGroups][0][filters][0][value]=' . $incrementId; + $this->webApi->write($url, [], WebapiDecorator::GET); + $response = json_decode($this->webApi->read(), true); + $this->webApi->close(); + return $response['items'][0]; + } + + /** + * Update order entity + * @param array $order + * @throws \Exception + */ + private function saveOrder(array $order) + { + $url = $_ENV['app_frontend_url'] . 'rest/V1/orders'; + // web api doesn't allow to save payment additional information + unset($order['payment']['additional_information']); + $this->webApi->write($url, ['entity' => $order], WebapiDecorator::POST); + $response = json_decode($this->webApi->read(), true); + $this->webApi->close(); + if (empty($response['entity_id'])) { + throw new \Exception('Couldn\'t update order details'); + } + } +} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/CheckBraintreeConfigStep.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/CheckBraintreeConfigStep.php new file mode 100644 index 0000000000000..21d11bbfdf739 --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/CheckBraintreeConfigStep.php @@ -0,0 +1,145 @@ +systemConfigEditSectionPayment = $systemConfigEditSectionPayment; + $this->assertFieldsAreDisabled = $assertFieldsAreDisabled; + $this->assertFieldsArePresent = $assertFieldsArePresent; + $this->assertFieldsAreActive = $assertFieldsAreActive; + $this->assertFieldsAreEnabled = $assertFieldsAreEnabled; + $this->countryCode = $countryCode; + $this->sections = $sections; + $this->braintreeConfigBlock = $this->systemConfigEditSectionPayment->getBraintreeConfigBlock(); + } + + /** + * Run step for checking Braintree configuration. + * + * @return void + */ + public function run() + { + $this->systemConfigEditSectionPayment->getPaymentsConfigBlock()->expandPaymentSections($this->sections); + $this->enableBraintree(); + $this->disableBraintree(); + } + + /** + * Enables Braintree and makes assertions for fields. + * + * @return void + */ + private function enableBraintree() + { + $this->braintreeConfigBlock->clickConfigureButton(); + $this->braintreeConfigBlock->clearCredentials(); + $enablers = $this->braintreeConfigBlock->getEnablerFields(); + $this->assertFieldsAreDisabled->processAssert($this->systemConfigEditSectionPayment, $enablers); + $this->braintreeConfigBlock->specifyCredentials(); + $this->assertFieldsAreActive->processAssert($this->systemConfigEditSectionPayment, $enablers); + $this->braintreeConfigBlock->enableBraintree(); + $this->assertFieldsAreActive->processAssert($this->systemConfigEditSectionPayment, $enablers); + $this->systemConfigEditSectionPayment->getPageActions()->save(); + $this->systemConfigEditSectionPayment->getMessagesBlock()->waitSuccessMessage(); + } + + /** + * Disables Express Checkout and makes assertions for fields. + * + * @return void + */ + private function disableBraintree() + { + $enablers = $this->braintreeConfigBlock->getEnablerFields(); + $this->braintreeConfigBlock->clickConfigureButton(); + $this->assertFieldsAreActive->processAssert($this->systemConfigEditSectionPayment, $enablers); + $this->assertFieldsAreEnabled->processAssert( + $this->systemConfigEditSectionPayment, + [$enablers['Enable this Solution']] + ); + $this->braintreeConfigBlock->disableBraintree(); + $this->assertFieldsAreActive->processAssert($this->systemConfigEditSectionPayment, $enablers); + $this->systemConfigEditSectionPayment->getPageActions()->save(); + $this->systemConfigEditSectionPayment->getMessagesBlock()->waitSuccessMessage(); + } +} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/ContinueToPaypalStep.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/ContinueToPaypalStep.php new file mode 100644 index 0000000000000..44bb95f5d62ed --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/ContinueToPaypalStep.php @@ -0,0 +1,40 @@ +checkoutOnepage = $checkoutOnepage; + } + + /** + * Clicks Continue to PayPal button, proceeds with checkout on PayPal side. + */ + public function run() + { + $parentWindow = $this->checkoutOnepage->getPaymentBlock() + ->getSelectedPaymentMethodBlock() + ->clickContinueToPaypal(); + $this->checkoutOnepage->getBraintreePaypalBlock()->process($parentWindow); + } +} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/CreateBraintreeCreditMemoStep.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/CreateBraintreeCreditMemoStep.php index 61455ceaac4fd..085fc142a3373 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/CreateBraintreeCreditMemoStep.php +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/CreateBraintreeCreditMemoStep.php @@ -6,15 +6,13 @@ namespace Magento\Braintree\Test\TestStep; -use Magento\Config\Test\Fixture\ConfigData; use Magento\Mtf\ObjectManager; +use Magento\Mtf\TestStep\TestStepInterface; use Magento\Sales\Test\Fixture\OrderInjectable; use Magento\Sales\Test\Page\Adminhtml\OrderCreditMemoNew; use Magento\Sales\Test\Page\Adminhtml\OrderIndex; use Magento\Sales\Test\Page\Adminhtml\OrderInvoiceView; use Magento\Sales\Test\Page\Adminhtml\SalesOrderView; -use Magento\Mtf\TestStep\TestStepInterface; -use Braintree\Gateway; /** * Create credit memo for order placed via Braintree credit card payment method. diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/DenyPaymentStep.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/DenyPaymentStep.php new file mode 100644 index 0000000000000..13dc942be95d3 --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/DenyPaymentStep.php @@ -0,0 +1,49 @@ +orderIndex = $orderIndex; + $this->salesOrderView = $salesOrderView; + $this->order = $order; + } + + /** + * @inheritdoc + */ + public function run() + { + $this->orderIndex->open(); + $this->orderIndex->getSalesOrderGrid()->searchAndOpen(['id' => $this->order->getId()]); + $this->salesOrderView->getPageActions()->deny(); + } +} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/PlaceOrderWithPaypalStep.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/PlaceOrderWithPaypalStep.php index 930105fc2dc2d..0ff7f164b0996 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/PlaceOrderWithPaypalStep.php +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/PlaceOrderWithPaypalStep.php @@ -80,7 +80,7 @@ public function run() } $parentWindow = $this->checkoutOnepage->getPaymentBlock() ->getSelectedPaymentMethodBlock() - ->clickContinueToPaypal(); + ->clickPayWithPaypal(); $this->checkoutOnepage->getBraintreePaypalBlock()->process($parentWindow); $order = $this->fixtureFactory->createByCode( diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/etc/di.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/etc/di.xml index be2d771e47f5b..7bdfca2f713f2 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/etc/di.xml +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/etc/di.xml @@ -8,12 +8,12 @@ - high + S1 - high + S1 diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/etc/testcase.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/etc/testcase.xml index cf1ae3bf474ae..495f455c43a72 100644 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/etc/testcase.xml +++ b/dev/tests/functional/tests/app/Magento/Braintree/Test/etc/testcase.xml @@ -21,6 +21,27 @@ + + + + + + + + + + + + + + + + + + + + + @@ -88,4 +109,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dev/tests/functional/tests/app/Magento/Checkout/Test/Block/Onepage/Payment/DiscountCodes.php b/dev/tests/functional/tests/app/Magento/Checkout/Test/Block/Onepage/Payment/DiscountCodes.php new file mode 100644 index 0000000000000..88a6f45125a7b --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Checkout/Test/Block/Onepage/Payment/DiscountCodes.php @@ -0,0 +1,58 @@ +_rootElement->find($this->openForm, Locator::SELECTOR_CSS)->click(); + $this->_rootElement->find($this->couponCode, Locator::SELECTOR_CSS)->setValue($code); + $this->_rootElement->find($this->applyButton, Locator::SELECTOR_CSS)->click(); + } +} diff --git a/dev/tests/functional/tests/app/Magento/Checkout/Test/Block/Onepage/Payment/Method.php b/dev/tests/functional/tests/app/Magento/Checkout/Test/Block/Onepage/Payment/Method.php index 6e59dc048b9bc..50f6a3d8aa5db 100644 --- a/dev/tests/functional/tests/app/Magento/Checkout/Test/Block/Onepage/Payment/Method.php +++ b/dev/tests/functional/tests/app/Magento/Checkout/Test/Block/Onepage/Payment/Method.php @@ -40,7 +40,7 @@ class Method extends Block * * @var string */ - protected $vaultCheckbox = '#%s_vault_enabler'; + protected $vaultCheckbox = '#%s_enable_vault'; /** * PayPal load spinner. @@ -49,6 +49,20 @@ class Method extends Block */ protected $preloaderSpinner = '#preloaderSpinner'; + /** + * Continue to PayPal button for Braintree. + * + * @var string + */ + protected $continueToBraintreePaypalButton = '#braintree_paypal_continue_to'; + + /** + * Pay with Paypal button for Braintree. + * + * @var string + */ + protected $payWithBraintreePaypalButton = '#braintree_paypal_pay_with'; + /** * Wait for PayPal page is loaded. * @@ -78,7 +92,22 @@ public function clickPlaceOrder() public function clickContinueToPaypal() { $currentWindow = $this->browser->getCurrentWindow(); - $this->_rootElement->find($this->placeOrderButton)->click(); + $this->waitForElementNotVisible($this->waitElement); + $this->_rootElement->find($this->continueToBraintreePaypalButton)->click(); + $this->waitForElementNotVisible($this->waitElement); + return $currentWindow; + } + + /** + * Click Pay with Paypal button. + * + * @return string + */ + public function clickPayWithPaypal() + { + $currentWindow = $this->browser->getCurrentWindow(); + $this->waitForElementNotVisible($this->waitElement); + $this->_rootElement->find($this->payWithBraintreePaypalButton)->click(); $this->waitForElementNotVisible($this->waitElement); return $currentWindow; } diff --git a/dev/tests/functional/tests/app/Magento/Checkout/Test/Page/CheckoutOnepage.xml b/dev/tests/functional/tests/app/Magento/Checkout/Test/Page/CheckoutOnepage.xml index 60235d508b387..0bf31562dfb1e 100644 --- a/dev/tests/functional/tests/app/Magento/Checkout/Test/Page/CheckoutOnepage.xml +++ b/dev/tests/functional/tests/app/Magento/Checkout/Test/Page/CheckoutOnepage.xml @@ -11,6 +11,7 @@ + diff --git a/dev/tests/functional/tests/app/Magento/Paypal/Test/Block/Express/Review.php b/dev/tests/functional/tests/app/Magento/Paypal/Test/Block/Express/Review.php index cf3ef9a53d751..d51d5c4e39f3a 100644 --- a/dev/tests/functional/tests/app/Magento/Paypal/Test/Block/Express/Review.php +++ b/dev/tests/functional/tests/app/Magento/Paypal/Test/Block/Express/Review.php @@ -32,10 +32,9 @@ public function selectShippingMethod(array $shippingMethod) $shippingElement = $this->_rootElement->find( $this->shippingMethod, Locator::SELECTOR_CSS, - 'Magento\Paypal\Test\Block\Express\Review\ShippingoptgroupElement' + \Magento\Paypal\Test\Block\Express\Review\ShippingoptgroupElement::class ); $shippingElement->setValue($shippingMethod['shipping_service'] . '/' . $shippingMethod['shipping_method']); - $this->waitForElementVisible('#review-please-wait'); $this->waitForElementNotVisible('#review-please-wait'); } diff --git a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/CreatePayFlowOrderBackendNegativeTest.php b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/CreatePayFlowOrderBackendNegativeTest.php new file mode 100644 index 0000000000000..3e510ab12ec32 --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/CreatePayFlowOrderBackendNegativeTest.php @@ -0,0 +1,50 @@ + Orders. + * 3. Click Create New Order. + * 4. Select Customer created in preconditions. + * 5. Add Product. + * 6. Fill data according dataset. + * 7. Click Update Product qty. + * 8. Fill data according dataset. + * 9. Click Get Shipping Method and rates. + * 10. Fill data according dataset. + * 11. Select payment method Credit Card (PayFlow Pro) + * 12. Leave empty required fields for credit card + * 13. Click Submit order button + * + * @group PayPal + * @ZephyrId MAGETWO-58934 + */ +class CreatePayFlowOrderBackendNegativeTest extends Scenario +{ + /* tags */ + const MVP = 'yes'; + const TEST_TYPE = '3rd_party_test'; + const SEVERITY = 'S2'; + /* end tags */ + + /** + * Runs sales order on backend. + * + * @return void + */ + public function test() + { + $this->executeScenario(); + } +} diff --git a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/CreatePayFlowOrderBackendNegativeTest.xml b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/CreatePayFlowOrderBackendNegativeTest.xml new file mode 100644 index 0000000000000..4ad751de68a71 --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/CreatePayFlowOrderBackendNegativeTest.xml @@ -0,0 +1,29 @@ + + + + + + test_type:3rd_party_test, severity:S2 + catalogProductSimple::product_10_dollar + default + US_address_1_without_email + No + Flat Rate + Fixed + + 15.00 + + payflowpro + credit_card_admin + visa_empty + Yes + payflowpro, payflowpro_use_vault + + + + diff --git a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/CreateVaultOrderBackendTest.xml b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/CreateVaultOrderBackendTest.xml index b7f571b87270a..ca26ad42a020c 100644 --- a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/CreateVaultOrderBackendTest.xml +++ b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/CreateVaultOrderBackendTest.xml @@ -8,8 +8,8 @@ - test_type:3rd_party_test - catalogProductSimple::product_10_dollar + test_type:3rd_party_test, severity:S0 + catalogProductSimple::product_10_dollar default US_address_1_without_email No @@ -19,12 +19,13 @@ 15.00 payflowpro + payflowpro_cc_vault credit_card_admin visa_default Yes payflowpro, payflowpro_use_vault Processing - Back, Cancel, Send Email, Hold, Invoice, Ship + Back, Cancel, Send Email, Hold, Invoice, Ship, Reorder, Edit diff --git a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutFromProductPageTest.php b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutFromProductPageTest.php index be6c223a2503c..8a10d08e0f6c3 100644 --- a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutFromProductPageTest.php +++ b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutFromProductPageTest.php @@ -22,16 +22,16 @@ * 5. Process checkout via PayPal. * 6. Perform asserts. * - * @group PayPal_(CS) + * @group PayPal * @ZephyrId MAGETWO-12415 */ class ExpressCheckoutFromProductPageTest extends Scenario { /* tags */ const MVP = 'yes'; - const DOMAIN = 'CS'; const TEST_TYPE = '3rd_party_test'; const TO_MAINTAIN = 'yes'; + const SEVERITY = 'S0'; /* end tags */ /** diff --git a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutFromProductPageTest.xml b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutFromProductPageTest.xml index 4373523471cff..1d92fa149efbc 100644 --- a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutFromProductPageTest.xml +++ b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutFromProductPageTest.xml @@ -27,7 +27,7 @@ paypal_express paypal_express, freeshipping - test_type:3rd_party_test + test_type:3rd_party_test, severity:S0 diff --git a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutFromShoppingCartTest.php b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutFromShoppingCartTest.php index fc85feb524baf..6ecf356e27ff8 100644 --- a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutFromShoppingCartTest.php +++ b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutFromShoppingCartTest.php @@ -22,16 +22,16 @@ * 5. Process checkout via PayPal. * 6. Perform asserts. * - * @group PayPal_(CS) + * @group PayPal * @ZephyrId MAGETWO-12414 */ class ExpressCheckoutFromShoppingCartTest extends Scenario { /* tags */ const MVP = 'yes'; - const DOMAIN = 'CS'; const TEST_TYPE = '3rd_party_test'; const TO_MAINTAIN = 'yes'; + const SEVERITY = 'S0'; /* end tags */ /** diff --git a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutFromShoppingCartTest.xml b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutFromShoppingCartTest.xml index b2e9ce9b56327..38c876719bc3d 100644 --- a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutFromShoppingCartTest.xml +++ b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutFromShoppingCartTest.xml @@ -8,7 +8,9 @@ - catalogProductSimple::simple_10_dollar, configurableProduct::with_one_option, bundleProduct::bundle_fixed_100_dollar_product + catalogProductSimple::simple_10_dollar + configurableProduct::with_one_option + bundleProduct::bundle_fixed_100_dollar_product us_ca_ny_rule sandbox_us_default guest @@ -26,7 +28,7 @@ 145.98 payflowpro - test_type:3rd_party_test + test_type:3rd_party_test, severity:S0 diff --git a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutOnePageTest.php b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutOnePageTest.php index f57544ae5a663..5d7056d32703d 100644 --- a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutOnePageTest.php +++ b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutOnePageTest.php @@ -26,16 +26,16 @@ * 5. Process checkout via PayPal. * 6. Perform asserts. * - * @group PayPal_(CS) + * @group PayPal * @ZephyrId MAGETWO-12413, MAGETWO-14359, MAGETWO-12996 */ class ExpressCheckoutOnePageTest extends Scenario { /* tags */ const MVP = 'yes'; - const DOMAIN = 'CS'; const TEST_TYPE = '3rd_party_test'; const TO_MAINTAIN = 'yes'; + const SEVERITY = 'S0'; /* end tags */ /** diff --git a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutOnePageTest.xml b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutOnePageTest.xml index b13bab96ae0ad..e52ed631ae46f 100644 --- a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutOnePageTest.xml +++ b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ExpressCheckoutOnePageTest.xml @@ -8,7 +8,9 @@ - catalogProductSimple::simple_10_dollar, configurableProduct::with_one_option, bundleProduct::bundle_fixed_100_dollar_product + catalogProductSimple::simple_10_dollar + configurableProduct::with_one_option + bundleProduct::bundle_fixed_100_dollar_product us_ca_ny_rule sandbox_us_default default @@ -24,14 +26,16 @@ paypal_express paypal_express - test_type:3rd_party_test + test_type:3rd_party_test, severity:S0 - catalogProductSimple::simple_10_dollar, configurableProduct::with_one_option, bundleProduct::bundle_fixed_100_dollar_product + catalogProductSimple::simple_10_dollar + configurableProduct::with_one_option + bundleProduct::bundle_fixed_100_dollar_product us_ca_ny_rule sandbox_us_default default @@ -47,14 +51,16 @@ paypal_express payflowlink - test_type:3rd_party_test + test_type:3rd_party_test, severity:S0 - catalogProductSimple::simple_10_dollar, configurableProduct::with_one_option, bundleProduct::bundle_fixed_100_dollar_product + catalogProductSimple::simple_10_dollar + configurableProduct::with_one_option + bundleProduct::bundle_fixed_100_dollar_product us_ca_ny_rule sandbox_us_default default diff --git a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/InContextExpressCheckoutFromShoppingCartTest.php b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/InContextExpressCheckoutFromShoppingCartTest.php index 9637d95a7216b..66ca21d8d0f3e 100644 --- a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/InContextExpressCheckoutFromShoppingCartTest.php +++ b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/InContextExpressCheckoutFromShoppingCartTest.php @@ -23,16 +23,16 @@ * 5. Click "Cancel". * 6. Perform asserts. * - * @group PayPal_(CS) + * @group PayPal * @ZephyrId MAGETWO-47213 */ class InContextExpressCheckoutFromShoppingCartTest extends Scenario { /* tags */ const MVP = 'yes'; - const DOMAIN = 'CS'; const TEST_TYPE = '3rd_party_test'; const TO_MAINTAIN = 'yes'; + const SEVERITY = 'S0'; /* end tags */ /** diff --git a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/InContextExpressCheckoutFromShoppingCartTest.xml b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/InContextExpressCheckoutFromShoppingCartTest.xml index 01a42e252d4a4..bbc566d1e31ec 100644 --- a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/InContextExpressCheckoutFromShoppingCartTest.xml +++ b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/InContextExpressCheckoutFromShoppingCartTest.xml @@ -8,9 +8,9 @@ - catalogProductSimple::product_10_dollar + catalogProductSimple::product_10_dollar paypal_express, paypal_express_in_context - test_type:3rd_party_test + test_type:3rd_party_test, severity:S0 diff --git a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/InContextExpressOnePageCheckoutTest.php b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/InContextExpressOnePageCheckoutTest.php index 1cc9e00df7ec9..b96f6a3e4a70a 100644 --- a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/InContextExpressOnePageCheckoutTest.php +++ b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/InContextExpressOnePageCheckoutTest.php @@ -23,16 +23,16 @@ * 5. Click "Cancel". * 6. Perform asserts. * - * @group PayPal_(CS) + * @group PayPal * @ZephyrId MAGETWO-47261 */ class InContextExpressOnePageCheckoutTest extends Scenario { /* tags */ const MVP = 'yes'; - const DOMAIN = 'CS'; const TEST_TYPE = '3rd_party_test'; const TO_MAINTAIN = 'yes'; + const SEVERITY = 'S0'; /* end tags */ /** diff --git a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/InContextExpressOnePageCheckoutTest.xml b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/InContextExpressOnePageCheckoutTest.xml index 605a154cbc569..5fa8e6e8b775d 100644 --- a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/InContextExpressOnePageCheckoutTest.xml +++ b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/InContextExpressOnePageCheckoutTest.xml @@ -8,7 +8,7 @@ - catalogProductSimple::simple_10_dollar + catalogProductSimple::simple_10_dollar default US_address_1 guest @@ -18,7 +18,7 @@ paypal_express paypal_express_in_context, paypal_express, freeshipping - test_type:3rd_party_test + test_type:3rd_party_test, severity:S0 diff --git a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ReorderUsingVaultTest.xml b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ReorderUsingVaultTest.xml new file mode 100644 index 0000000000000..b1da43e473bc5 --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/ReorderUsingVaultTest.xml @@ -0,0 +1,33 @@ + + + + + + Reorder from Admin with saved within PayPal Payflow Pro credit card for Guest Customer + catalogProductSimple::product_10_dollar + default + US_address_1 + guest + Flat Rate + Fixed + + 15.00 + + payflowpro + payflowpro_cc_vault + credit_card + visa_default + payflowpro, payflowpro_use_vault + Processing + test_type:3rd_party_test, severity:S1 + + + + + + diff --git a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/UseVaultOnCheckoutTest.xml b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/UseVaultOnCheckoutTest.xml index ff5f151580b11..92b4be03b5937 100644 --- a/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/UseVaultOnCheckoutTest.xml +++ b/dev/tests/functional/tests/app/Magento/Paypal/Test/TestCase/UseVaultOnCheckoutTest.xml @@ -8,21 +8,22 @@ - catalogProductSimple::product_10_dollar + catalogProductSimple::product_10_dollar default US_address_1_without_email login Flat Rate Fixed payflowpro + payflowpro_cc_vault credit_card visa_default Yes payflowpro, payflowpro_use_vault Processing - test_type:3rd_party_test + test_type:3rd_party_test, severity:S0 Processing - Back, Cancel, Send Email, Hold, Invoice, Ship + Back, Cancel, Send Email, Hold, Invoice, Ship, Reorder, Edit diff --git a/dev/tests/functional/tests/app/Magento/Paypal/Test/etc/di.xml b/dev/tests/functional/tests/app/Magento/Paypal/Test/etc/di.xml new file mode 100644 index 0000000000000..e56386d5e0eac --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Paypal/Test/etc/di.xml @@ -0,0 +1,19 @@ + + + + + + S1 + + + + + S1 + + + diff --git a/dev/tests/functional/tests/app/Magento/Paypal/Test/etc/testcase.xml b/dev/tests/functional/tests/app/Magento/Paypal/Test/etc/testcase.xml index 288824c7e595d..7a03c6d49596c 100644 --- a/dev/tests/functional/tests/app/Magento/Paypal/Test/etc/testcase.xml +++ b/dev/tests/functional/tests/app/Magento/Paypal/Test/etc/testcase.xml @@ -53,7 +53,7 @@ - + @@ -61,4 +61,20 @@ + + + + + + + + + + + + + + + + diff --git a/dev/tests/functional/tests/app/Magento/Sales/Test/Block/Adminhtml/Order/Actions.php b/dev/tests/functional/tests/app/Magento/Sales/Test/Block/Adminhtml/Order/Actions.php index e8a912080d5a5..b1f4fb2220066 100644 --- a/dev/tests/functional/tests/app/Magento/Sales/Test/Block/Adminhtml/Order/Actions.php +++ b/dev/tests/functional/tests/app/Magento/Sales/Test/Block/Adminhtml/Order/Actions.php @@ -8,6 +8,7 @@ use Magento\Mtf\Block\Block; use Magento\Mtf\Client\Locator; +use Magento\Ui\Test\Block\Adminhtml\Modal; /** * Order actions block. @@ -263,4 +264,32 @@ public function isActionButtonVisible($buttonName) { return $this->_rootElement->find(sprintf($this->button, $buttonName), Locator::SELECTOR_XPATH)->isVisible(); } + + /** + * Accept order + * @return void + */ + public function accept() + { + $acceptPayment = '#accept_payment'; + $this->_rootElement->find($acceptPayment)->click(); + $element = $this->browser->find($this->confirmModal); + /** @var Modal $modal */ + $modal = $this->blockFactory->create(Modal::class, ['element' => $element]); + $modal->acceptAlert(); + } + + /** + * Deny order + * @return void + */ + public function deny() + { + $denyPayment = '#deny_payment'; + $this->_rootElement->find($denyPayment)->click(); + $element = $this->browser->find($this->confirmModal); + /** @var Modal $modal */ + $modal = $this->blockFactory->create(Modal::class, ['element' => $element]); + $modal->acceptAlert(); + } } diff --git a/dev/tests/functional/tests/app/Magento/Sales/Test/Block/Adminhtml/Order/History.php b/dev/tests/functional/tests/app/Magento/Sales/Test/Block/Adminhtml/Order/History.php index b3b0f4eafa74c..740f8f03fe639 100644 --- a/dev/tests/functional/tests/app/Magento/Sales/Test/Block/Adminhtml/Order/History.php +++ b/dev/tests/functional/tests/app/Magento/Sales/Test/Block/Adminhtml/Order/History.php @@ -21,6 +21,27 @@ class History extends Block */ protected $commentHistory = '.note-list-comment'; + /** + * Comment history status. + * + * @var string + */ + protected $commentHistoryStatus = '.note-list-status'; + + /** + * Comment history notified status. + * + * @var string + */ + protected $commentHistoryNotifiedStatus = '.note-list-customer'; + + /** + * Authorized Amount. + * + * @var string + */ + protected $authorizedAmount = '//div[@class="note-list-comment"][contains(text(), "Authorized amount of")]'; + /** * Captured Amount from IPN. * @@ -53,6 +74,17 @@ public function getCommentsHistory() return $this->_rootElement->find($this->commentHistory, Locator::SELECTOR_CSS)->getText(); } + /** + * Get the authorized amount from the comments history. + * + * @return string + */ + public function getAuthorizedAmount() + { + $this->waitCommentsHistory(); + return $this->_rootElement->find($this->authorizedAmount, Locator::SELECTOR_XPATH)->getText(); + } + /** * Get the captured amount from the comments history. * @@ -85,6 +117,28 @@ public function getRefundedAmount() return $result; } + /** + * Gets the status which presented in comment + * + * @return string + */ + public function getStatus() + { + $this->waitCommentsHistory(); + return $this->_rootElement->find($this->commentHistoryStatus, Locator::SELECTOR_CSS)->getText(); + } + + /** + * Gets the is customer notified status which presented in comment + * + * @return string + */ + public function getNotifiedStatus() + { + $this->waitCommentsHistory(); + return $this->_rootElement->find($this->commentHistoryNotifiedStatus, Locator::SELECTOR_CSS)->getText(); + } + /** * Wait for comments history is visible. * diff --git a/dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertAcceptPaymentMessageInCommentsHistory.php b/dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertAcceptPaymentMessageInCommentsHistory.php new file mode 100644 index 0000000000000..1871a12ee2ce4 --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertAcceptPaymentMessageInCommentsHistory.php @@ -0,0 +1,46 @@ +open(); + $orderIndex->getSalesOrderGrid()->searchAndOpen(['id' => $orderId]); + $history = $orderView->getOrderHistoryBlock()->getCommentsHistory(); + + \PHPUnit_Framework_Assert::assertContains(self::$message, $history); + } + + /** + * @inheritdoc + */ + public function toString() + { + return 'Message about approved payment is available in Comments History section.'; + } +} diff --git a/dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertAcceptPaymentSuccessMessagePresent.php b/dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertAcceptPaymentSuccessMessagePresent.php new file mode 100644 index 0000000000000..fefc148b8bd03 --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertAcceptPaymentSuccessMessagePresent.php @@ -0,0 +1,45 @@ +getMessagesBlock()->getSuccessMessage() + ); + } + + /** + * @inheritdoc + */ + public function toString() + { + return 'Success accept payment message is present.'; + } +} diff --git a/dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertAuthorizationInCommentsHistory.php b/dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertAuthorizationInCommentsHistory.php index 7495855d5351f..a6b8e8983d2b6 100644 --- a/dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertAuthorizationInCommentsHistory.php +++ b/dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertAuthorizationInCommentsHistory.php @@ -38,7 +38,7 @@ public function processAssert( $salesOrder->open(); $salesOrder->getSalesOrderGrid()->searchAndOpen(['id' => $orderId]); - $actualAuthorizedAmount = $salesOrderView->getOrderHistoryBlock()->getCommentsHistory(); + $actualAuthorizedAmount = $salesOrderView->getOrderHistoryBlock()->getAuthorizedAmount(); \PHPUnit_Framework_Assert::assertContains( self::AUTHORIZED_AMOUNT . $prices['grandTotal'], diff --git a/dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertDenyPaymentMessageInCommentsHistory.php b/dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertDenyPaymentMessageInCommentsHistory.php new file mode 100644 index 0000000000000..87cac1c38232b --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertDenyPaymentMessageInCommentsHistory.php @@ -0,0 +1,45 @@ +open(); + $orderIndex->getSalesOrderGrid()->searchAndOpen(['id' => $orderId]); + $history = $orderView->getOrderHistoryBlock()->getCommentsHistory(); + + \PHPUnit_Framework_Assert::assertContains(self::$message, $history); + } + + /** + * @inheritdoc + */ + public function toString() + { + return 'Message about denied payment is available in Comments History section.'; + } +} diff --git a/dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertDenyPaymentSuccessMessagePresent.php b/dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertDenyPaymentSuccessMessagePresent.php new file mode 100644 index 0000000000000..b6dbfdf1a6702 --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertDenyPaymentSuccessMessagePresent.php @@ -0,0 +1,45 @@ +getMessagesBlock()->getSuccessMessage() + ); + } + + /** + * @inheritdoc + */ + public function toString() + { + return 'Success deny payment message is present.'; + } +} diff --git a/dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertRefundOrderStatusInCommentsHistory.php b/dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertRefundOrderStatusInCommentsHistory.php new file mode 100644 index 0000000000000..89faffc8ec072 --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Sales/Test/Constraint/AssertRefundOrderStatusInCommentsHistory.php @@ -0,0 +1,48 @@ +open(); + $salesOrder->getSalesOrderGrid()->searchAndOpen(['id' => $order->getId()]); + \PHPUnit_Framework_Assert::assertContains( + $salesOrderView->getOrderForm()->getOrderInfoBlock()->getOrderStatus(), + $salesOrderView->getOrderHistoryBlock()->getStatus() + ); + } + + /** + * Returns string representation of successful assertion. + * + * @return string + */ + public function toString() + { + return "Message with appropriate order status is available in Comments History section."; + } +} diff --git a/dev/tests/functional/tests/app/Magento/Sales/Test/TestStep/SubmitOrderNegativeStep.php b/dev/tests/functional/tests/app/Magento/Sales/Test/TestStep/SubmitOrderNegativeStep.php new file mode 100644 index 0000000000000..ece554eee9c9c --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Sales/Test/TestStep/SubmitOrderNegativeStep.php @@ -0,0 +1,43 @@ +orderCreateIndex = $orderCreateIndex; + } + + /** + * Fill Sales Data. + * + * @return void + */ + public function run() + { + $this->orderCreateIndex->getCreateBlock()->submitOrder(); + } +} diff --git a/dev/tests/functional/tests/app/Magento/Vault/Test/Block/CreditCards.php b/dev/tests/functional/tests/app/Magento/Vault/Test/Block/StoredPayments.php similarity index 75% rename from dev/tests/functional/tests/app/Magento/Vault/Test/Block/CreditCards.php rename to dev/tests/functional/tests/app/Magento/Vault/Test/Block/StoredPayments.php index 1869cf3673f2f..3aad566537fbb 100644 --- a/dev/tests/functional/tests/app/Magento/Vault/Test/Block/CreditCards.php +++ b/dev/tests/functional/tests/app/Magento/Vault/Test/Block/StoredPayments.php @@ -10,7 +10,7 @@ use Magento\Mtf\Client\Locator; use Magento\Mtf\Fixture\InjectableFixture; -class CreditCards extends Block +class StoredPayments extends Block { /** * Delete button locator for popup window. @@ -19,6 +19,13 @@ class CreditCards extends Block */ private $deleteButton = './/*[@data-type="popup"]//span[text()="Delete"]'; + /** + * Delete link for stored payment method. + * + * @var string + */ + private $deleteStoredPayment = '.delete'; + /** * Delete saved credit card. * @@ -32,6 +39,17 @@ public function deleteCreditCard(ElementInterface $creditCard) $this->browser->selectWindow(); } + /** + * Delete Stored Payment Method. + */ + public function deleteStoredPayment() + { + $this->browser->find($this->deleteStoredPayment)->click(); + $this->browser->selectWindow(); + $this->browser->find($this->deleteButton, Locator::SELECTOR_XPATH)->click(); + $this->browser->selectWindow(); + } + /** * Get saved credit cards on My Credit Cards page. * diff --git a/dev/tests/functional/tests/app/Magento/Vault/Test/Constraint/AssertStoredPaymentDeletedMessage.php b/dev/tests/functional/tests/app/Magento/Vault/Test/Constraint/AssertStoredPaymentDeletedMessage.php new file mode 100644 index 0000000000000..7679c870b726c --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Vault/Test/Constraint/AssertStoredPaymentDeletedMessage.php @@ -0,0 +1,44 @@ +getMessagesBlock()->getSuccessMessage(), + 'Message of success deletion of stored payment method is not present or wrong.' + ); + } + + /** + * Returns string representation of successful assertion. + * + * @return string + */ + public function toString() + { + return 'Success message on Store Payment Methods page is correct.'; + } +} diff --git a/dev/tests/functional/tests/app/Magento/Vault/Test/Page/MyCreditCards.xml b/dev/tests/functional/tests/app/Magento/Vault/Test/Page/StoredPaymentMethods.xml similarity index 65% rename from dev/tests/functional/tests/app/Magento/Vault/Test/Page/MyCreditCards.xml rename to dev/tests/functional/tests/app/Magento/Vault/Test/Page/StoredPaymentMethods.xml index 3b2396ece7d12..2baf7d7d57fd7 100644 --- a/dev/tests/functional/tests/app/Magento/Vault/Test/Page/MyCreditCards.xml +++ b/dev/tests/functional/tests/app/Magento/Vault/Test/Page/StoredPaymentMethods.xml @@ -6,8 +6,8 @@ */ --> - - + + diff --git a/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/CreateVaultOrderBackendTest.php b/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/CreateVaultOrderBackendTest.php index 37d0fdc81c5aa..a5194b3915191 100644 --- a/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/CreateVaultOrderBackendTest.php +++ b/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/CreateVaultOrderBackendTest.php @@ -30,15 +30,15 @@ * 15. Select any available payment token. * 16. Place order. * - * @group Order_Management_(CS) + * @group Order_Management * @ZephyrId MAGETWO-48127, MAGETWO-48091 */ class CreateVaultOrderBackendTest extends Scenario { /* tags */ const MVP = 'yes'; - const DOMAIN = 'CS'; const TEST_TYPE = 'acceptance_test, extended_acceptance_test, 3rd_party_test'; + const SEVERITY = 'S0'; /* end tags */ /** diff --git a/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/DeleteSavedCreditCardTest.php b/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/DeleteSavedCreditCardTest.php index 43497e821f6a9..e6462e4697aa6 100644 --- a/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/DeleteSavedCreditCardTest.php +++ b/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/DeleteSavedCreditCardTest.php @@ -23,22 +23,40 @@ * 6. Go to One page Checkout * 7. Perform assertions. * - * @group Vault_(CS) + * @group Vault * @ZephyrId MAGETWO-54059, MAGETWO-54072, MAGETWO-54068, MAGETWO-54015, MAGETWO-54011 + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class DeleteSavedCreditCardTest extends Injectable { /* tags */ const MVP = 'yes'; - const DOMAIN = 'CS'; const TEST_TYPE = '3rd_party_test'; + const SEVERITY = 'S1'; /* end tags */ + /** + * Page for one page checkout. + * + * @var CheckoutOnepage + */ + private $checkoutOnepage; + + /** + * Injection data. + * + * @param CheckoutOnepage $checkoutOnepage + * @return void + */ + public function __inject(CheckoutOnepage $checkoutOnepage) + { + $this->checkoutOnepage = $checkoutOnepage; + } + /** * Runs delete saved credit card test. * * @param AssertCreditCardNotPresentOnCheckout $assertCreditCardNotPresentOnCheckout - * @param CheckoutOnepage $checkoutOnepage * @param $products * @param $configData * @param $customer @@ -47,10 +65,10 @@ class DeleteSavedCreditCardTest extends Injectable * @param $shipping * @param array $payments * @param $creditCardSave + * @return void */ public function test( AssertCreditCardNotPresentOnCheckout $assertCreditCardNotPresentOnCheckout, - CheckoutOnepage $checkoutOnepage, $products, $configData, $customer, @@ -69,22 +87,22 @@ public function test( foreach ($payments as $key => $payment) { $this->addToCart($products); $this->proceedToCheckout(); - if($key < 1) { // if this is the first order to be placed + if ($key < 1) { // if this is the first order to be placed $this->selectCheckoutMethod($checkoutMethod, $customer); $this->fillShippingAddress($shippingAddress); } $this->fillShippingMethod($shipping); if ($key >= 2) { // if this order will be placed via stored credit card - $this->useSavedCreditCard($payment); + $this->useSavedCreditCard($payment['vault']); } else { $this->selectPaymentMethod($payment, $payment['creditCardClass'], $payment['creditCard']); $this->saveCreditCard($payment, $creditCardSave); } $this->placeOrder(); } - // Delete credit cards from My Account and verify they are not available on checkout + // Delete credit cards from Stored Payment Methods and verify they are not available on checkout $paymentsCount = count($payments); - for($i = 2; $i < $paymentsCount; $i++) { + for ($i = 2; $i < $paymentsCount; $i++) { $deletedCard = $this->deleteCreditCardFromMyAccount( $customer, $payments[$i]['creditCard'], @@ -94,7 +112,7 @@ public function test( $this->proceedToCheckout(); $this->fillShippingMethod($shipping); $assertCreditCardNotPresentOnCheckout->processAssert( - $checkoutOnepage, + $this->checkoutOnepage, $deletedCard['deletedCreditCard'] ); } @@ -244,7 +262,7 @@ protected function saveCreditCard($payment, $creditCardSave) ); $saveCreditCardStep->run(); } - + /** * @return void */ @@ -255,7 +273,7 @@ protected function fillBillingInformation() ); $fillBillingInformationStep->run(); } - + /** * @return void */ @@ -273,8 +291,8 @@ protected function placeOrder() protected function useSavedCreditCard($payment) { $useSavedCreditCardStep = ObjectManager::getInstance()->create( - \Magento\Vault\Test\TestStep\UseSavedCreditCardStep::class, - ['payment' => $payment] + \Magento\Vault\Test\TestStep\UseSavedPaymentMethodStep::class, + ['vault' => $payment] ); $useSavedCreditCardStep->run(); } diff --git a/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/DeleteSavedCreditCardTest.xml b/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/DeleteSavedCreditCardTest.xml index ecbed706005b4..ac69bfb9f47e4 100644 --- a/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/DeleteSavedCreditCardTest.xml +++ b/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/DeleteSavedCreditCardTest.xml @@ -8,7 +8,7 @@ - catalogProductSimple::product_10_dollar + catalogProductSimple::product_10_dollar default US_address_1_without_email login @@ -35,6 +35,9 @@ visa_braintree + + braintree_cc_vault + payflowpro @@ -42,11 +45,14 @@ amex_default + + payflowpro_cc_vault + Yes braintree, payflowpro, braintree_use_vault, payflowpro_use_vault - test_type:3rd_party_test + test_type:3rd_party_test, severity:S1 diff --git a/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/ReorderUsingVaultTest.php b/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/ReorderUsingVaultTest.php new file mode 100644 index 0000000000000..e426662d30e54 --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/ReorderUsingVaultTest.php @@ -0,0 +1,52 @@ +executeScenario(); + } +} diff --git a/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/UseVaultOnCheckoutTest.php b/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/UseVaultOnCheckoutTest.php index 39332d9c657ab..fb8b3575ee72e 100644 --- a/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/UseVaultOnCheckoutTest.php +++ b/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/UseVaultOnCheckoutTest.php @@ -31,15 +31,15 @@ * 12. Click Place Order button. * 13. Perform assertions. * - * @group One_Page_Checkout_(CS) + * @group One_Page_Checkout * @ZephyrId MAGETWO-46530 */ class UseVaultOnCheckoutTest extends Scenario { /* tags */ const MVP = 'yes'; - const DOMAIN = 'CS'; const TEST_TYPE = '3rd_party_test'; + const SEVERITY = 'S0'; /* end tags */ /** diff --git a/dev/tests/functional/tests/app/Magento/Vault/Test/TestStep/DeleteCreditCardFromMyAccountStep.php b/dev/tests/functional/tests/app/Magento/Vault/Test/TestStep/DeleteCreditCardFromMyAccountStep.php index beb644a6ba224..c3cb46347dd8c 100644 --- a/dev/tests/functional/tests/app/Magento/Vault/Test/TestStep/DeleteCreditCardFromMyAccountStep.php +++ b/dev/tests/functional/tests/app/Magento/Vault/Test/TestStep/DeleteCreditCardFromMyAccountStep.php @@ -11,9 +11,12 @@ use Magento\Mtf\Fixture\InjectableFixture; use Magento\Mtf\ObjectManager; use Magento\Mtf\TestStep\TestStepInterface; -use Magento\Vault\Test\Constraint\AssertCreditCardDeletedMessage; -use Magento\Vault\Test\Page\MyCreditCards; +use Magento\Vault\Test\Constraint\AssertStoredPaymentDeletedMessage; +use Magento\Vault\Test\Page\StoredPaymentMethods; +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ class DeleteCreditCardFromMyAccountStep implements TestStepInterface { /** @@ -42,43 +45,43 @@ class DeleteCreditCardFromMyAccountStep implements TestStepInterface private $creditCard; /** - * @var AssertCreditCardDeletedMessage + * @var AssertStoredPaymentDeletedMessage */ - private $assertCreditCardDeletedMessage; + private $assertStoredPaymentDeletedMessage; /** - * @var $myCreditCardsPage + * @var StoredPaymentMethods */ - private $myCreditCardsPage; + private $storedPaymentMethodsPage; /** * DeleteCreditCardFromMyAccountStep constructor. * - * @param MyCreditCards $myCreditCardsPage + * @param StoredPaymentMethods $storedPaymentMethodsPage * @param Customer $customer * @param ObjectManager $objectManager * @param CustomerAccountIndex $customerAccountIndex * @param FixtureFactory $fixtureFactory - * @param AssertCreditCardDeletedMessage $assertCreditCardDeletedMessage + * @param AssertStoredPaymentDeletedMessage $assertStoredPaymentDeletedMessage * @param array $creditCard * @param string $creditCardClass */ public function __construct( - MyCreditCards $myCreditCardsPage, + StoredPaymentMethods $storedPaymentMethodsPage, Customer $customer, ObjectManager $objectManager, CustomerAccountIndex $customerAccountIndex, FixtureFactory $fixtureFactory, - AssertCreditCardDeletedMessage $assertCreditCardDeletedMessage, + AssertStoredPaymentDeletedMessage $assertStoredPaymentDeletedMessage, array $creditCard, $creditCardClass = 'credit_card' ) { - $this->myCreditCardsPage = $myCreditCardsPage; + $this->storedPaymentMethodsPage = $storedPaymentMethodsPage; $this->customer = $customer; $this->objectManager = $objectManager; $this->customerAccountIndex = $customerAccountIndex; $this->fixtureFactory = $fixtureFactory; - $this->assertCreditCardDeletedMessage = $assertCreditCardDeletedMessage; + $this->assertStoredPaymentDeletedMessage = $assertStoredPaymentDeletedMessage; $this->creditCard = $fixtureFactory->createByCode($creditCardClass, ['dataset' => $creditCard['dataset']]); } @@ -93,18 +96,18 @@ public function run() \Magento\Customer\Test\TestStep\LoginCustomerOnFrontendStep::class, ['customer' => $this->customer] )->run(); - $this->customerAccountIndex->getAccountMenuBlock()->openMenuItem('My Credit Cards'); - $myCreditCardsBlock = $this->myCreditCardsPage->getCreditCardsBlock(); + $this->customerAccountIndex->getAccountMenuBlock()->openMenuItem('Stored Payment Methods'); + $storedPaymentsBlock = $this->storedPaymentMethodsPage->getStoredPaymentsBlock(); $creditCardData = $this->creditCard->getData(); $creditCardNumber = preg_grep('/([a-z]+)_number/', array_flip($creditCardData)); $lastFourDigits = substr(key($creditCardNumber), -4, 4); - $availableCreditCards = $myCreditCardsBlock->getCreditCards(); + $availableCreditCards = $storedPaymentsBlock->getCreditCards(); if (key_exists($lastFourDigits, $availableCreditCards)) { - $myCreditCardsBlock->deleteCreditCard($availableCreditCards[$lastFourDigits]); + $storedPaymentsBlock->deleteCreditCard($availableCreditCards[$lastFourDigits]); } - $this->assertCreditCardDeletedMessage->processAssert($this->myCreditCardsPage); + $this->assertStoredPaymentDeletedMessage->processAssert($this->storedPaymentMethodsPage); return ['deletedCreditCard' => $lastFourDigits]; } diff --git a/dev/tests/functional/tests/app/Magento/Vault/Test/TestStep/DeleteStoredPaymentStep.php b/dev/tests/functional/tests/app/Magento/Vault/Test/TestStep/DeleteStoredPaymentStep.php new file mode 100644 index 0000000000000..b2b857f9e36d8 --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Vault/Test/TestStep/DeleteStoredPaymentStep.php @@ -0,0 +1,50 @@ +storedPaymentMethodsPage = $storedPaymentMethodsPage; + $this->customerAccountIndex = $customerAccountIndex; + } + + /** + * @inheritdoc + * + * @return array + */ + public function run() + { + $this->customerAccountIndex->open(); + $this->customerAccountIndex->getAccountMenuBlock()->openMenuItem('Stored Payment Methods'); + $storedPaymentsBlock = $this->storedPaymentMethodsPage->getStoredPaymentsBlock(); + $storedPaymentsBlock->deleteStoredPayment(); + } +} diff --git a/dev/tests/functional/tests/app/Magento/Vault/Test/TestStep/UseSavedPaymentMethodStep.php b/dev/tests/functional/tests/app/Magento/Vault/Test/TestStep/UseSavedPaymentMethodStep.php new file mode 100644 index 0000000000000..1470bde4f77e5 --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Vault/Test/TestStep/UseSavedPaymentMethodStep.php @@ -0,0 +1,51 @@ +checkoutOnepage = $checkoutOnepage; + $this->vault = $vault; + } + + /** + * Run step that selects saved credit card. + * + * @return void + */ + public function run() + { + $this->checkoutOnepage->getPaymentBlock()->selectPaymentMethod($this->vault); + } +} diff --git a/dev/tests/functional/tests/app/Magento/Vault/Test/TestStep/UseVaultPaymentTokenStep.php b/dev/tests/functional/tests/app/Magento/Vault/Test/TestStep/UseVaultPaymentTokenStep.php index ad693923955d4..066dc7786d892 100644 --- a/dev/tests/functional/tests/app/Magento/Vault/Test/TestStep/UseVaultPaymentTokenStep.php +++ b/dev/tests/functional/tests/app/Magento/Vault/Test/TestStep/UseVaultPaymentTokenStep.php @@ -17,20 +17,20 @@ class UseVaultPaymentTokenStep implements TestStepInterface * @var OrderCreateIndex */ private $orderCreatePage; - + /** * @var array */ - private $payment; + private $vault; /** * @param OrderCreateIndex $orderCreateIndex - * @param array $payment + * @param array $vault */ - public function __construct(OrderCreateIndex $orderCreateIndex, array $payment) + public function __construct(OrderCreateIndex $orderCreateIndex, array $vault) { $this->orderCreatePage = $orderCreateIndex; - $this->payment = $payment; + $this->vault = $vault; } /** @@ -39,8 +39,7 @@ public function __construct(OrderCreateIndex $orderCreateIndex, array $payment) public function run() { $block = $this->orderCreatePage->getCreateBlock(); - $this->payment['method'] .= '_cc_vault'; - $block->selectPaymentMethod($this->payment); - $block->selectVaultToken('token_switcher_' . $this->payment['method']); + $block->selectPaymentMethod($this->vault); + $block->selectVaultToken('token_switcher_' . $this->vault['method']); } } diff --git a/dev/tests/functional/tests/app/Magento/Vault/Test/etc/di.xml b/dev/tests/functional/tests/app/Magento/Vault/Test/etc/di.xml new file mode 100644 index 0000000000000..aba54057312ea --- /dev/null +++ b/dev/tests/functional/tests/app/Magento/Vault/Test/etc/di.xml @@ -0,0 +1,19 @@ + + + + + + S2 + + + + + S1 + + + diff --git a/dev/tests/functional/tests/app/Magento/Vault/Test/etc/testcase.xml b/dev/tests/functional/tests/app/Magento/Vault/Test/etc/testcase.xml index a804e4ac34555..cd34b96648208 100644 --- a/dev/tests/functional/tests/app/Magento/Vault/Test/etc/testcase.xml +++ b/dev/tests/functional/tests/app/Magento/Vault/Test/etc/testcase.xml @@ -23,8 +23,8 @@ - - + + @@ -37,7 +37,8 @@ - + + @@ -45,4 +46,22 @@ + + + + + + + + + + + + + + + + + + From 4c40a74b7823ece09fa777493ebb237cf076f28a Mon Sep 17 00:00:00 2001 From: Ievgen Sentiabov Date: Wed, 26 Oct 2016 12:38:50 +0300 Subject: [PATCH 03/19] MAGETWO-59832: Move Braintree and Vault module changes - Fixed failed static tests --- app/code/Magento/Braintree/composer.json | 1 + .../credit-card-data.js | 3 +- .../credit-card-number-validator.js | 7 +++++ .../credit-card-type.js | 8 +++++ .../luhn10-validator.js | 10 ++++--- .../credit-card-validation/cvv-validator.js | 13 ++++++-- .../expiration-date-validator.js | 12 ++++++-- .../expiration-month-validator.js | 6 ++++ .../expiration-year-validator.js | 11 +++++-- .../expiration-date-validator/parse-date.js | 5 ++-- .../model/credit-card-validation/validator.js | 30 ++++++++++--------- .../view/frontend/layout/customer_account.xml | 2 +- 12 files changed, 80 insertions(+), 28 deletions(-) diff --git a/app/code/Magento/Braintree/composer.json b/app/code/Magento/Braintree/composer.json index 1d256221702f7..5d0d179363310 100644 --- a/app/code/Magento/Braintree/composer.json +++ b/app/code/Magento/Braintree/composer.json @@ -17,6 +17,7 @@ "magento/module-quote": "100.1.*", "magento/module-paypal": "100.1.*", "magento/module-theme": "100.1.*", + "magento/module-ui": "100.1.*", "braintree/braintree_php": "3.7.0" }, "suggest": { diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-data.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-data.js index 64a00a2b3d67f..1b3b1451626c0 100644 --- a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-data.js +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-data.js @@ -6,8 +6,9 @@ /*global alert*/ define( [], - function() { + function () { 'use strict'; + return { creditCard: null, creditCardNumber: null, diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator.js index 60d278c45b795..43521190004cb 100644 --- a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator.js +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator.js @@ -13,6 +13,13 @@ define( function (utils, luhn10, creditCardTypes) { 'use strict'; + /** + * Validation result wrapper + * @param {Object} card + * @param {Boolean} isPotentiallyValid + * @param {Boolean} isValid + * @returns {Object} + */ function resultWrapper(card, isPotentiallyValid, isValid) { return { card: card, diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator/credit-card-type.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator/credit-card-type.js index b02c324485582..3a2abe84c2671 100644 --- a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator/credit-card-type.js +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator/credit-card-type.js @@ -11,6 +11,7 @@ define( ], function ($, utils) { 'use strict'; + var types = [ { title: 'Visa', @@ -113,7 +114,13 @@ define( } } ]; + return { + /** + * Get credit card type + * @param {String} cardNumber + * @returns {Array} + */ getCardTypes: function (cardNumber) { var i, value, result = []; @@ -133,6 +140,7 @@ define( result.push($.extend(true, {}, value)); } } + return result; } } diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator/luhn10-validator.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator/luhn10-validator.js index 54da68c65c06d..75f7fa23b06c2 100644 --- a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator/luhn10-validator.js +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator/luhn10-validator.js @@ -6,17 +6,19 @@ /*global alert*/ define( [], - function() { + function () { 'use strict'; + /** * Luhn algorithm verification */ - return function(a, b, c, d, e) { - for(d = +a[b = a.length-1], e = 0; b--;) { + return function (a, b, c, d, e) { + for (d = +a[b = a.length - 1], e = 0; b--;) { c = +a[b]; d += ++e % 2 ? 2 * c % 10 + (c > 4) : c; } - return !(d%10) + + return !(d % 10) }; } ); diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/cvv-validator.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/cvv-validator.js index 5688f50aa865b..56a3efa6bbdaa 100644 --- a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/cvv-validator.js +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/cvv-validator.js @@ -6,9 +6,15 @@ /*global alert*/ define( [], - function() { + function () { 'use strict'; + /** + * Validation result wrapper + * @param {Boolean} isValid + * @param {Boolean} isPotentiallyValid + * @returns {Object} + */ function resultWrapper(isValid, isPotentiallyValid) { return { isValid: isValid, @@ -20,19 +26,22 @@ define( * CVV number validation * validate digit count fot CVV code */ - return function(value, maxLength) { + return function (value, maxLength) { var DEFAULT_LENGTH = 3; maxLength = maxLength || DEFAULT_LENGTH; if (!/^\d*$/.test(value)) { return resultWrapper(false, false); } + if (value.length === maxLength) { return resultWrapper(true, true); } + if (value.length < maxLength) { return resultWrapper(false, true); } + if (value.length > maxLength) { return resultWrapper(false, false); } diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator.js index 6661a595b8bc2..9beae84efa913 100644 --- a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator.js +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator.js @@ -11,9 +11,17 @@ define( 'Magento_Payment/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator', 'Magento_Payment/js/model/credit-card-validation/expiration-date-validator/expiration-year-validator' ], - function(utils, parseDate, expirationMonth, expirationYear) { + function (utils, parseDate, expirationMonth, expirationYear) { 'use strict'; + /** + * Validation result wrapper + * @param {Boolean} isValid + * @param {Boolean} isPotentiallyValid + * @param {String} month + * @param {String} year + * @returns {Object} + */ function resultWrapper(isValid, isPotentiallyValid, month, year) { return { isValid: isValid, @@ -23,7 +31,7 @@ define( }; } - return function(value) { + return function (value) { var date, monthValid, yearValid; diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator.js index 03b4ebcdec683..77560f13a3428 100644 --- a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator.js +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator.js @@ -9,6 +9,12 @@ define( function () { 'use strict'; + /** + * Validation result wrapper + * @param {Boolean} isValid + * @param {Boolean} isPotentiallyValid + * @returns {Object} + */ function resultWrapper(isValid, isPotentiallyValid) { return { isValid: isValid, diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/expiration-year-validator.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/expiration-year-validator.js index 38494ccbe9c06..1116288f6edff 100644 --- a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/expiration-year-validator.js +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/expiration-year-validator.js @@ -6,9 +6,15 @@ /*global alert*/ define( [], - function() { + function () { 'use strict'; + /** + * Validation result wrapper + * @param {Boolean} isValid + * @param {Boolean} isPotentiallyValid + * @returns {Object} + */ function resultWrapper(isValid, isPotentiallyValid) { return { isValid: isValid, @@ -16,7 +22,7 @@ define( }; } - return function(value) { + return function (value) { var currentYear = new Date().getFullYear(), len = value.length, valid, @@ -36,6 +42,7 @@ define( value = parseInt(value, 10); valid = value >= currentYear && value <= currentYear + expMaxLifetime; + return resultWrapper(valid, valid); }; } diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/parse-date.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/parse-date.js index 057eb1491f27c..2108a97d0ec25 100644 --- a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/parse-date.js +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/parse-date.js @@ -6,9 +6,10 @@ /*global alert*/ define( [], - function() { + function () { 'use strict'; - return function(value) { + + return function (value) { var month, len; if (value.match('/')) { diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/validator.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/validator.js index 4a733dd155a22..de7847577e46c 100644 --- a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/validator.js +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/validator.js @@ -19,7 +19,7 @@ factory(jQuery); } }(function ($, cvvValidator, creditCardNumberValidator, expirationDateValidator, monthValidator, creditCardData) { - "use strict"; + 'use strict'; $.each({ 'validate-card-type': [ @@ -38,6 +38,7 @@ return true; } } + return false; } }, @@ -46,10 +47,10 @@ 'validate-card-number': [ /** * Validate credit card number based on mod 10 - * @param number - credit card number - * @return {boolean} + * @param {String} number - credit card number + * @return {Boolean} */ - function (number) { + function (number) { return creditCardNumberValidator(number).isValid; }, $.mage.__('Please enter a valid credit card number.') @@ -57,10 +58,10 @@ 'validate-card-date': [ /** * Validate credit card number based on mod 10 - * @param date - month - * @return {boolean} + * @param {String} date - month + * @return {Boolean} */ - function (date) { + function (date) { return monthValidator(date).isValid; }, $.mage.__('Incorrect credit card expiration month.') @@ -68,11 +69,12 @@ 'validate-card-cvv': [ /** * Validate credit card number based on mod 10 - * @param cvv - month - * @return {boolean} + * @param {String} cvv - month + * @return {Boolean} */ - function (cvv) { + function (cvv) { var maxLength = creditCardData.creditCard ? creditCardData.creditCard.code.size : 3; + return cvvValidator(cvv, maxLength).isValid; }, $.mage.__('Please enter a valid credit card verification number.') @@ -80,10 +82,10 @@ 'validate-card-year': [ /** * Validate credit card number based on mod 10 - * @param date - month - * @return {boolean} + * @param {String} date - month + * @return {Boolean} */ - function (date) { + function (date) { return monthValidator(date).isValid; }, $.mage.__('Incorrect credit card expiration year.') @@ -93,4 +95,4 @@ rule.unshift(i); $.validator.addMethod.apply($.validator, rule); }); -})); \ No newline at end of file +})); diff --git a/app/code/Magento/Vault/view/frontend/layout/customer_account.xml b/app/code/Magento/Vault/view/frontend/layout/customer_account.xml index 1fb8805239f0a..2042721d9d387 100644 --- a/app/code/Magento/Vault/view/frontend/layout/customer_account.xml +++ b/app/code/Magento/Vault/view/frontend/layout/customer_account.xml @@ -11,7 +11,7 @@ vault/cards/listaction - My Credit Cards + Stored Payment Methods From af48a68fdff475fabb92e60baf46aba852b9f2f0 Mon Sep 17 00:00:00 2001 From: Ievgen Sentiabov Date: Wed, 26 Oct 2016 13:00:00 +0300 Subject: [PATCH 04/19] MAGETWO-59832: Move Braintree and Vault module changes - Fixed failed js static tests --- .../credit-card-data.js | 2 +- .../credit-card-type.js | 2 +- .../luhn10-validator.js | 2 +- .../credit-card-validation/cvv-validator.js | 1 + .../expiration-date-validator.js | 2 +- .../expiration-month-validator.js | 2 +- .../expiration-date-validator/parse-date.js | 4 +- .../model/credit-card-validation/validator.js | 6 + .../credit-card-data.js | 19 --- .../credit-card-number-validator.js | 72 --------- .../credit-card-type.js | 140 ------------------ .../luhn10-validator.js | 22 --- .../credit-card-validation/cvv-validator.js | 41 ----- .../expiration-date-validator.js | 51 ------- .../expiration-month-validator.js | 41 ----- .../expiration-year-validator.js | 42 ------ .../expiration-date-validator/parse-date.js | 32 ---- .../model/credit-card-validation/validator.js | 95 ------------ .../Test/Js/_files/blacklist/magento.txt | 11 +- 19 files changed, 15 insertions(+), 572 deletions(-) delete mode 100644 app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/credit-card-data.js delete mode 100644 app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/credit-card-number-validator.js delete mode 100644 app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/credit-card-number-validator/credit-card-type.js delete mode 100644 app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/credit-card-number-validator/luhn10-validator.js delete mode 100644 app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/cvv-validator.js delete mode 100644 app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/expiration-date-validator.js delete mode 100644 app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator.js delete mode 100644 app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/expiration-date-validator/expiration-year-validator.js delete mode 100644 app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/expiration-date-validator/parse-date.js delete mode 100644 app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/validator.js diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-data.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-data.js index 1b3b1451626c0..5e4ccb061985c 100644 --- a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-data.js +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-data.js @@ -15,6 +15,6 @@ define( expirationMonth: null, expirationYear: null, cvvCode: null - } + }; } ); diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator/credit-card-type.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator/credit-card-type.js index 3a2abe84c2671..07e192c4b3f1f 100644 --- a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator/credit-card-type.js +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator/credit-card-type.js @@ -143,6 +143,6 @@ define( return result; } - } + }; } ); diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator/luhn10-validator.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator/luhn10-validator.js index 75f7fa23b06c2..e8dc3a35edea9 100644 --- a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator/luhn10-validator.js +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/credit-card-number-validator/luhn10-validator.js @@ -18,7 +18,7 @@ define( d += ++e % 2 ? 2 * c % 10 + (c > 4) : c; } - return !(d % 10) + return !(d % 10); }; } ); diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/cvv-validator.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/cvv-validator.js index 56a3efa6bbdaa..1a8b8df2c220f 100644 --- a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/cvv-validator.js +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/cvv-validator.js @@ -28,6 +28,7 @@ define( */ return function (value, maxLength) { var DEFAULT_LENGTH = 3; + maxLength = maxLength || DEFAULT_LENGTH; if (!/^\d*$/.test(value)) { diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator.js index 9beae84efa913..5e73f87f4e9ea 100644 --- a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator.js +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator.js @@ -54,6 +54,6 @@ define( } return resultWrapper(false, false, null, null); - } + }; } ); diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator.js index 77560f13a3428..fcf4100c18d3b 100644 --- a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator.js +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator.js @@ -26,7 +26,7 @@ define( var month, monthValid; - if ((value.replace(/\s/g, '') === '') || (value === '0')) { + if (value.replace(/\s/g, '') === '' || value === '0') { return resultWrapper(false, true); } diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/parse-date.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/parse-date.js index 2108a97d0ec25..6e445f779b7d5 100644 --- a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/parse-date.js +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/expiration-date-validator/parse-date.js @@ -21,13 +21,13 @@ define( }; } - len = (value[0] === '0' || value.length > 5 || value.length === 4 || value.length === 3) ? 2 : 1; + len = value[0] === '0' || value.length > 5 || value.length === 4 || value.length === 3 ? 2 : 1; month = value.substr(0, len); return { month: month, year: value.substr(month.length, 4) }; - } + }; } ); diff --git a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/validator.js b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/validator.js index de7847577e46c..9720a2fcf058c 100644 --- a/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/validator.js +++ b/app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/validator.js @@ -5,6 +5,8 @@ /*jshint browser:true jquery:true*/ /*global alert*/ (function (factory) { + 'use strict'; + if (typeof define === 'function' && define.amd) { define([ 'jquery', @@ -45,6 +47,7 @@ $.mage.__('Please enter a valid credit card type number.') ], 'validate-card-number': [ + /** * Validate credit card number based on mod 10 * @param {String} number - credit card number @@ -56,6 +59,7 @@ $.mage.__('Please enter a valid credit card number.') ], 'validate-card-date': [ + /** * Validate credit card number based on mod 10 * @param {String} date - month @@ -67,6 +71,7 @@ $.mage.__('Incorrect credit card expiration month.') ], 'validate-card-cvv': [ + /** * Validate credit card number based on mod 10 * @param {String} cvv - month @@ -80,6 +85,7 @@ $.mage.__('Please enter a valid credit card verification number.') ], 'validate-card-year': [ + /** * Validate credit card number based on mod 10 * @param {String} date - month diff --git a/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/credit-card-data.js b/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/credit-card-data.js deleted file mode 100644 index 64a00a2b3d67f..0000000000000 --- a/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/credit-card-data.js +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright © 2016 Magento. All rights reserved. - * See COPYING.txt for license details. - */ -/*jshint browser:true jquery:true*/ -/*global alert*/ -define( - [], - function() { - 'use strict'; - return { - creditCard: null, - creditCardNumber: null, - expirationMonth: null, - expirationYear: null, - cvvCode: null - } - } -); diff --git a/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/credit-card-number-validator.js b/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/credit-card-number-validator.js deleted file mode 100644 index 60d278c45b795..0000000000000 --- a/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/credit-card-number-validator.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright © 2016 Magento. All rights reserved. - * See COPYING.txt for license details. - */ -/*jshint browser:true jquery:true*/ -/*global alert*/ -define( - [ - 'mageUtils', - 'Magento_Payment/js/model/credit-card-validation/credit-card-number-validator/luhn10-validator', - 'Magento_Payment/js/model/credit-card-validation/credit-card-number-validator/credit-card-type' - ], - function (utils, luhn10, creditCardTypes) { - 'use strict'; - - function resultWrapper(card, isPotentiallyValid, isValid) { - return { - card: card, - isValid: isValid, - isPotentiallyValid: isPotentiallyValid - }; - } - - return function (value) { - var potentialTypes, - cardType, - valid, - i, - maxLength; - - if (utils.isEmpty(value)) { - return resultWrapper(null, false, false); - } - - value = value.replace(/\-|\s/g, ''); - - if (!/^\d*$/.test(value)) { - return resultWrapper(null, false, false); - } - - potentialTypes = creditCardTypes.getCardTypes(value); - - if (potentialTypes.length === 0) { - return resultWrapper(null, false, false); - } else if (potentialTypes.length !== 1) { - return resultWrapper(null, true, false); - } - - cardType = potentialTypes[0]; - - if (cardType.type === 'unionpay') { // UnionPay is not Luhn 10 compliant - valid = true; - } else { - valid = luhn10(value); - } - - for (i = 0; i < cardType.lengths.length; i++) { - if (cardType.lengths[i] === value.length) { - return resultWrapper(cardType, valid, valid); - } - } - - maxLength = Math.max.apply(null, cardType.lengths); - - if (value.length < maxLength) { - return resultWrapper(cardType, true, false); - } - - return resultWrapper(cardType, false, false); - }; - } -); diff --git a/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/credit-card-number-validator/credit-card-type.js b/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/credit-card-number-validator/credit-card-type.js deleted file mode 100644 index 5635d6d3ae0a1..0000000000000 --- a/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/credit-card-number-validator/credit-card-type.js +++ /dev/null @@ -1,140 +0,0 @@ -/** - * Copyright © 2016 Magento. All rights reserved. - * See COPYING.txt for license details. - */ -/*jshint browser:true jquery:true*/ -/*global alert*/ -define( - [ - 'jquery', - 'mageUtils' - ], - function ($, utils) { - 'use strict'; - var types = [ - { - title: 'Visa', - type: 'VI', - pattern: '^4\\d*$', - gaps: [4, 8, 12], - lengths: [16], - code: { - name: 'CVV', - size: 3 - } - }, - { - title: 'MasterCard', - type: 'MC', - pattern: '^5([1-5]\\d*)?$', - gaps: [4, 8, 12], - lengths: [16], - code: { - name: 'CVC', - size: 3 - } - }, - { - title: 'American Express', - type: 'AE', - pattern: '^3([47]\\d*)?$', - isAmex: true, - gaps: [4, 10], - lengths: [15], - code: { - name: 'CID', - size: 4 - } - }, - { - title: 'Diners', - type: 'DN', - pattern: '^3((0([0-5]\\d*)?)|[689]\\d*)?$', - gaps: [4, 10], - lengths: [14], - code: { - name: 'CVV', - size: 3 - } - }, - { - title: 'Discover', - type: 'DI', - pattern: '^6(0|01|011\\d*|5\\d*|4|4[4-9]\\d*)?$', - gaps: [4, 8, 12], - lengths: [16], - code: { - name: 'CID', - size: 3 - } - }, - { - title: 'JCB', - type: 'JCB', - pattern: '^((2|21|213|2131\\d*)|(1|18|180|1800\\d*)|(3|35\\d*))$', - gaps: [4, 8, 12], - lengths: [16], - code: { - name: 'CVV', - size: 3 - } - }, - { - title: 'UnionPay', - type: 'UN', - pattern: '^6(2\\d*)?$', - gaps: [4, 8, 12], - lengths: [16, 17, 18, 19], - code: { - name: 'CVN', - size: 3 - } - }, - { - title: 'Maestro International', - type: 'MI', - pattern: '^(5(0|[6-9])|63|67(?!59|6770|6774))\\d*$', - gaps: [4, 8, 12], - lengths: [12, 13, 14, 15, 16, 17, 18, 19], - code: { - name: 'CVC', - size: 3 - } - }, - { - title: 'Maestro Domestic', - type: 'MD', - pattern: '^6759(?!24|38|40|6[3-9]|70|76)|676770|676774\\d*$', - gaps: [4, 8, 12], - lengths: [12, 13, 14, 15, 16, 17, 18, 19], - code: { - name: 'CVC', - size: 3 - } - } - ]; - return { - getCardTypes: function (cardNumber) { - var i, value, - result = []; - - if (utils.isEmpty(cardNumber)) { - return result; - } - - if (cardNumber === '') { - return $.extend(true, {}, types); - } - - for (i = 0; i < types.length; i++) { - value = types[i]; - - if (new RegExp(value.pattern).test(cardNumber)) { - result.push($.extend(true, {}, value)); - } - } - return result; - } - } - } -); diff --git a/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/credit-card-number-validator/luhn10-validator.js b/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/credit-card-number-validator/luhn10-validator.js deleted file mode 100644 index 54da68c65c06d..0000000000000 --- a/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/credit-card-number-validator/luhn10-validator.js +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Copyright © 2016 Magento. All rights reserved. - * See COPYING.txt for license details. - */ -/*jshint browser:true jquery:true*/ -/*global alert*/ -define( - [], - function() { - 'use strict'; - /** - * Luhn algorithm verification - */ - return function(a, b, c, d, e) { - for(d = +a[b = a.length-1], e = 0; b--;) { - c = +a[b]; - d += ++e % 2 ? 2 * c % 10 + (c > 4) : c; - } - return !(d%10) - }; - } -); diff --git a/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/cvv-validator.js b/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/cvv-validator.js deleted file mode 100644 index 5688f50aa865b..0000000000000 --- a/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/cvv-validator.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright © 2016 Magento. All rights reserved. - * See COPYING.txt for license details. - */ -/*jshint browser:true jquery:true*/ -/*global alert*/ -define( - [], - function() { - 'use strict'; - - function resultWrapper(isValid, isPotentiallyValid) { - return { - isValid: isValid, - isPotentiallyValid: isPotentiallyValid - }; - } - - /** - * CVV number validation - * validate digit count fot CVV code - */ - return function(value, maxLength) { - var DEFAULT_LENGTH = 3; - maxLength = maxLength || DEFAULT_LENGTH; - - if (!/^\d*$/.test(value)) { - return resultWrapper(false, false); - } - if (value.length === maxLength) { - return resultWrapper(true, true); - } - if (value.length < maxLength) { - return resultWrapper(false, true); - } - if (value.length > maxLength) { - return resultWrapper(false, false); - } - }; - } -); diff --git a/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/expiration-date-validator.js b/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/expiration-date-validator.js deleted file mode 100644 index 6661a595b8bc2..0000000000000 --- a/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/expiration-date-validator.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright © 2016 Magento. All rights reserved. - * See COPYING.txt for license details. - */ -/*jshint browser:true jquery:true*/ -/*global alert*/ -define( - [ - 'mageUtils', - 'Magento_Payment/js/model/credit-card-validation/expiration-date-validator/parse-date', - 'Magento_Payment/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator', - 'Magento_Payment/js/model/credit-card-validation/expiration-date-validator/expiration-year-validator' - ], - function(utils, parseDate, expirationMonth, expirationYear) { - 'use strict'; - - function resultWrapper(isValid, isPotentiallyValid, month, year) { - return { - isValid: isValid, - isPotentiallyValid: isPotentiallyValid, - month: month, - year: year - }; - } - - return function(value) { - var date, - monthValid, - yearValid; - - if (utils.isEmpty(value)) { - return resultWrapper(false, false, null, null); - } - - value = value.replace(/^(\d\d) (\d\d(\d\d)?)$/, '$1/$2'); - date = parseDate(value); - monthValid = expirationMonth(date.month); - yearValid = expirationYear(date.year); - - if (monthValid.isValid && yearValid.isValid) { - return resultWrapper(true, true, date.month, date.year); - } - - if (monthValid.isPotentiallyValid && yearValid.isPotentiallyValid) { - return resultWrapper(false, true, null, null); - } - - return resultWrapper(false, false, null, null); - } - } -); diff --git a/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator.js b/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator.js deleted file mode 100644 index 03b4ebcdec683..0000000000000 --- a/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright © 2016 Magento. All rights reserved. - * See COPYING.txt for license details. - */ -/*jshint browser:true jquery:true*/ -/*global alert*/ -define( - [], - function () { - 'use strict'; - - function resultWrapper(isValid, isPotentiallyValid) { - return { - isValid: isValid, - isPotentiallyValid: isPotentiallyValid - }; - } - - return function (value) { - var month, - monthValid; - - if ((value.replace(/\s/g, '') === '') || (value === '0')) { - return resultWrapper(false, true); - } - - if (!/^\d*$/.test(value)) { - return resultWrapper(false, false); - } - - if (isNaN(value)) { - return resultWrapper(false, false); - } - - month = parseInt(value, 10); - monthValid = month > 0 && month < 13; - - return resultWrapper(monthValid, monthValid); - }; - } -); diff --git a/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/expiration-date-validator/expiration-year-validator.js b/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/expiration-date-validator/expiration-year-validator.js deleted file mode 100644 index 38494ccbe9c06..0000000000000 --- a/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/expiration-date-validator/expiration-year-validator.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright © 2016 Magento. All rights reserved. - * See COPYING.txt for license details. - */ -/*jshint browser:true jquery:true*/ -/*global alert*/ -define( - [], - function() { - 'use strict'; - - function resultWrapper(isValid, isPotentiallyValid) { - return { - isValid: isValid, - isPotentiallyValid: isPotentiallyValid - }; - } - - return function(value) { - var currentYear = new Date().getFullYear(), - len = value.length, - valid, - expMaxLifetime = 19; - - if (value.replace(/\s/g, '') === '') { - return resultWrapper(false, true); - } - - if (!/^\d*$/.test(value)) { - return resultWrapper(false, false); - } - - if (len !== 4) { - return resultWrapper(false, true); - } - - value = parseInt(value, 10); - valid = value >= currentYear && value <= currentYear + expMaxLifetime; - return resultWrapper(valid, valid); - }; - } -); diff --git a/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/expiration-date-validator/parse-date.js b/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/expiration-date-validator/parse-date.js deleted file mode 100644 index 057eb1491f27c..0000000000000 --- a/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/expiration-date-validator/parse-date.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright © 2016 Magento. All rights reserved. - * See COPYING.txt for license details. - */ -/*jshint browser:true jquery:true*/ -/*global alert*/ -define( - [], - function() { - 'use strict'; - return function(value) { - var month, len; - - if (value.match('/')) { - value = value.split(/\s*\/\s*/g); - - return { - month: value[0], - year: value.slice(1).join() - }; - } - - len = (value[0] === '0' || value.length > 5 || value.length === 4 || value.length === 3) ? 2 : 1; - month = value.substr(0, len); - - return { - month: month, - year: value.substr(month.length, 4) - }; - } - } -); diff --git a/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/validator.js b/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/validator.js deleted file mode 100644 index e859a03491cba..0000000000000 --- a/app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/validator.js +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Copyright © 2016 Magento. All rights reserved. - * See COPYING.txt for license details. - */ -/*jshint browser:true jquery:true*/ -/*global alert*/ -(function (factory) { - if (typeof define === 'function' && define.amd) { - define([ - 'jquery', - 'Magento_Payment/js/model/credit-card-validation/cvv-validator', - 'Magento_Payment/js/model/credit-card-validation/credit-card-number-validator', - 'Magento_Payment/js/model/credit-card-validation/expiration-date-validator/expiration-year-validator', - 'Magento_Payment/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator', - 'Magento_Payment/js/model/credit-card-validation/credit-card-data' - ], factory); - } else { - factory(jQuery); - } -}(function ($, cvvValidator, creditCardNumberValidator, expirationDateValidator, monthValidator, creditCardData) { - "use strict"; - - $.each({ - 'validate-card-type': [ - function (number, item, allowedTypes) { - var cardInfo, - i, - l; - - if (!creditCardNumberValidator(number).isValid) { - return false; - } else { - cardInfo = creditCardNumberValidator(number).card; - - for (i = 0, l = allowedTypes.length; i < l; i++) { - if (cardInfo.title == allowedTypes[i].type) { - return true; - } - } - return false; - } - }, - 'Please enter a valid credit card type number.' - ], - 'validate-card-number': [ - /** - * Validate credit card number based on mod 10 - * @param number - credit card number - * @return {boolean} - */ - function (number) { - return creditCardNumberValidator(number).isValid; - }, - 'Please enter a valid credit card number.' - ], - 'validate-card-date': [ - /** - * Validate credit card number based on mod 10 - * @param date - month - * @return {boolean} - */ - function (date) { - return monthValidator(date).isValid; - }, - 'Incorrect credit card expiration month.' - ], - 'validate-card-cvv': [ - /** - * Validate credit card number based on mod 10 - * @param cvv - month - * @return {boolean} - */ - function (cvv) { - var maxLength = creditCardData.creditCard ? creditCardData.creditCard.code.size : 3; - return cvvValidator(cvv, maxLength).isValid; - }, - 'Please enter a valid credit card verification number.' - ], - 'validate-card-year': [ - /** - * Validate credit card number based on mod 10 - * @param date - month - * @return {boolean} - */ - function (date) { - return monthValidator(date).isValid; - }, - 'Incorrect credit card expiration year.' - ] - - }, function (i, rule) { - rule.unshift(i); - $.validator.addMethod.apply($.validator, rule); - }); -})); \ No newline at end of file diff --git a/dev/tests/static/testsuite/Magento/Test/Js/_files/blacklist/magento.txt b/dev/tests/static/testsuite/Magento/Test/Js/_files/blacklist/magento.txt index 1d1cb4ba2767a..356ec726f5180 100644 --- a/dev/tests/static/testsuite/Magento/Test/Js/_files/blacklist/magento.txt +++ b/dev/tests/static/testsuite/Magento/Test/Js/_files/blacklist/magento.txt @@ -218,16 +218,7 @@ app/code/Magento/PageCache/view/frontend/web/js/page-cache.js app/code/Magento/Payment/view/adminhtml/web/transparent.js app/code/Magento/Payment/view/frontend/requirejs-config.js app/code/Magento/Payment/view/frontend/web/cc-type.js -app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/credit-card-data.js -app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/credit-card-number-validator.js -app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/credit-card-number-validator/credit-card-type.js -app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/credit-card-number-validator/luhn10-validator.js -app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/cvv-validator.js -app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/expiration-date-validator.js -app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/expiration-date-validator/expiration-month-validator.js -app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/expiration-date-validator/expiration-year-validator.js -app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/expiration-date-validator/parse-date.js -app/code/Magento/Payment/view/frontend/web/js/model/credit-card-validation/validator.js +app/code/Magento/Payment/view/base/web/js/model/credit-card-validation/validator.js app/code/Magento/Payment/view/frontend/web/js/view/payment/cc-form.js app/code/Magento/Payment/view/frontend/web/js/view/payment/iframe.js app/code/Magento/Payment/view/frontend/web/js/view/payment/method-renderer/free-method.js From 808f886dbb06a1ce8f7bc121cc44af4773d7f3f7 Mon Sep 17 00:00:00 2001 From: Iurii Ivashchenko Date: Wed, 26 Oct 2016 16:16:25 +0300 Subject: [PATCH 05/19] MAGETWO-59835: Port PayPal Best Practice to Separate Saved Tokens to 2.1 --- .../web/js/model/payment/method-group.js | 31 ++++ .../view/frontend/web/js/view/payment/list.js | 141 ++++++++++++++---- .../web/template/payment-methods/list.html | 20 ++- .../view/frontend/web/template/payment.html | 1 - .../view/base/web/js/lib/core/collection.js | 8 + .../frontend/web/js/view/payment/vault.js | 43 +++--- .../css/source/module/checkout/_payments.less | 39 +++-- .../css/source/module/checkout/_payments.less | 38 +++-- 8 files changed, 238 insertions(+), 83 deletions(-) create mode 100644 app/code/Magento/Checkout/view/frontend/web/js/model/payment/method-group.js diff --git a/app/code/Magento/Checkout/view/frontend/web/js/model/payment/method-group.js b/app/code/Magento/Checkout/view/frontend/web/js/model/payment/method-group.js new file mode 100644 index 0000000000000..4236a215d7359 --- /dev/null +++ b/app/code/Magento/Checkout/view/frontend/web/js/model/payment/method-group.js @@ -0,0 +1,31 @@ +/** + * Copyright © 2016 Magento. All rights reserved. + * See COPYING.txt for license details. + */ + +define([ + 'uiElement', + 'mage/translate' +], function (Element, $t) { + 'use strict'; + + var DEFAULT_GROUP_ALIAS = 'default'; + + return Element.extend({ + defaults: { + alias: DEFAULT_GROUP_ALIAS, + title: $t('Payment Method'), + sortOrder: 100, + displayArea: 'payment-methods-items-${ $.alias }' + }, + + /** + * Checks if group instance is default + * + * @returns {Boolean} + */ + isDefault: function () { + return this.alias === DEFAULT_GROUP_ALIAS; + } + }); +}); diff --git a/app/code/Magento/Checkout/view/frontend/web/js/view/payment/list.js b/app/code/Magento/Checkout/view/frontend/web/js/view/payment/list.js index 18f6b8479c229..918d305ee031b 100644 --- a/app/code/Magento/Checkout/view/frontend/web/js/view/payment/list.js +++ b/app/code/Magento/Checkout/view/frontend/web/js/view/payment/list.js @@ -10,14 +10,22 @@ define([ 'Magento_Checkout/js/model/payment/method-list', 'Magento_Checkout/js/model/payment/renderer-list', 'uiLayout', - 'Magento_Checkout/js/model/checkout-data-resolver' -], function (_, ko, utils, Component, paymentMethods, rendererList, layout, checkoutDataResolver) { + 'Magento_Checkout/js/model/checkout-data-resolver', + 'mage/translate', + 'uiRegistry' +], function (_, ko, utils, Component, paymentMethods, rendererList, layout, checkoutDataResolver, $t, registry) { 'use strict'; return Component.extend({ defaults: { template: 'Magento_Checkout/payment-methods/list', - visible: paymentMethods().length > 0 + visible: paymentMethods().length > 0, + configDefaultGroup: { + name: 'methodGroup', + component: 'Magento_Checkout/js/model/payment/method-group' + }, + paymentGroupsList: [], + defaultGroupTitle: $t('Select a new payment method') }, /** @@ -26,7 +34,7 @@ define([ * @returns {Component} Chainable. */ initialize: function () { - this._super().initChildren(); + this._super().initDefaulGroup().initChildren(); paymentMethods.subscribe( function (changes) { checkoutDataResolver.resolvePaymentMethod(); @@ -47,6 +55,27 @@ define([ return this; }, + /** @inheritdoc */ + initObservable: function () { + this._super(). + observe(['paymentGroupsList']); + + return this; + }, + + /** + * Creates default group + * + * @returns {Component} Chainable. + */ + initDefaulGroup: function() { + layout([ + this.configDefaultGroup + ]); + + return this; + }, + /** * Create renders for child payment methods. * @@ -77,7 +106,7 @@ define([ rendererTemplate = { parent: '${ $.$data.parentName }', name: '${ $.$data.name }', - displayArea: 'payment-method-items', + displayArea: payment.displayArea, component: payment.component }; rendererComponent = utils.template(rendererTemplate, templateData); @@ -95,49 +124,105 @@ define([ * @param {Object} paymentMethodData */ createRenderer: function (paymentMethodData) { - var isRendererForMethod = false; + var isRendererForMethod = false, + currentGroup; + + registry.get(this.configDefaultGroup.name, function (defaultGroup) { + _.each(rendererList(), function (renderer) { - _.find(rendererList(), function (renderer) { + if (renderer.hasOwnProperty('typeComparatorCallback') && + typeof renderer.typeComparatorCallback == 'function' + ) { + isRendererForMethod = renderer.typeComparatorCallback(renderer.type, paymentMethodData.method); + } else { + isRendererForMethod = renderer.type === paymentMethodData.method; + } - if (renderer.hasOwnProperty('typeComparatorCallback') && - typeof renderer.typeComparatorCallback == 'function' - ) { - isRendererForMethod = renderer.typeComparatorCallback(renderer.type, paymentMethodData.method); - } else { - isRendererForMethod = renderer.type === paymentMethodData.method; - } + if (isRendererForMethod) { + currentGroup = renderer.group ? renderer.group : defaultGroup; - if (isRendererForMethod) { - layout( - [ + this.collectPaymentGroups(currentGroup); + + layout([ this.createComponent( { config: renderer.config, component: renderer.component, name: renderer.type, method: paymentMethodData.method, - item: paymentMethodData + item: paymentMethodData, + displayArea: currentGroup.displayArea } - ) - ] - ); - } + )]); + } + }.bind(this)); }.bind(this)); }, + /** + * Collects unique groups of available payment methods + * + * @param {Object} group + */ + collectPaymentGroups: function (group) { + var groupsList = this.paymentGroupsList(), + isGroupExists = _.some(groupsList, function (existsGroup) { + return existsGroup.alias === group.alias; + }); + + if (!isGroupExists) { + groupsList.push(group); + groupsList = _.sortBy(groupsList, function (existsGroup) { + return existsGroup.sortOrder; + }); + this.paymentGroupsList(groupsList); + } + }, + + /** + * Returns payment group title + * + * @param {Object} group + * @returns {String} + */ + getGroupTitle: function (group) { + var title = group().title; + + if (group().isDefault() && this.paymentGroupsList().length > 1) { + title = this.defaultGroupTitle; + } + + return title + ':'; + }, + + /** + * Checks if at least one payment method available + * + * @returns {String} + */ + isPaymentMethodsAvailable: function () { + return _.some(this.paymentGroupsList(), function (group) { + return this.getRegion(group.displayArea)().length; + }, this); + }, + /** * Remove view renderer. * * @param {String} paymentMethodCode */ removeRenderer: function (paymentMethodCode) { - var items = this.getRegion('payment-method-items'); + var items; + + _.each(this.paymentGroupsList(), function (group) { + items = this.getRegion(group.displayArea); - _.find(items(), function (value) { - if (value.item.method.indexOf(paymentMethodCode) === 0) { - value.disposeSubscriptions(); - value.destroy(); - } + _.find(items(), function (value) { + if (value.item.method.indexOf(paymentMethodCode) === 0) { + value.disposeSubscriptions(); + value.destroy(); + } + }); }, this); } }); diff --git a/app/code/Magento/Checkout/view/frontend/web/template/payment-methods/list.html b/app/code/Magento/Checkout/view/frontend/web/template/payment-methods/list.html index 66769f37386d6..f6c41c62eeca6 100644 --- a/app/code/Magento/Checkout/view/frontend/web/template/payment-methods/list.html +++ b/app/code/Magento/Checkout/view/frontend/web/template/payment-methods/list.html @@ -4,9 +4,19 @@ * See COPYING.txt for license details. */ --> -
- - - +
+
+
+
+ +
+
+
-
diff --git a/app/code/Magento/Checkout/view/frontend/web/template/payment.html b/app/code/Magento/Checkout/view/frontend/web/template/payment.html index 292ece611e6b6..46467839da3fb 100644 --- a/app/code/Magento/Checkout/view/frontend/web/template/payment.html +++ b/app/code/Magento/Checkout/view/frontend/web/template/payment.html @@ -5,7 +5,6 @@ */ -->