diff --git a/Api/GooglePayRequestDataProviderInterface.php b/Api/GooglePayRequestDataProviderInterface.php new file mode 100644 index 00000000..277ba3b9 --- /dev/null +++ b/Api/GooglePayRequestDataProviderInterface.php @@ -0,0 +1,37 @@ +coreRegistry = $registry; $this->customerCollection = $customerCollectionFactory->create(); - $this->recipientRepository = new RecipientRepository(); + $this->recipientRepository = $recipientRepository; + $this->country = $country; Magento2CoreSetup::bootstrap(); + $this->init(); parent::__construct($context, []); + } + protected function init() + { $recipientData = $this->coreRegistry->registry('recipient_data'); if (!empty($recipientData)) { $this->recipient = json_decode($recipientData); $this->recipient->recipient->externalId = $this->recipient->externalId; $this->recipient->recipient->localId = $this->recipient->localId; + $this->recipient->recipient->status = $this->recipient->status; + $this->recipient->recipient->statusUpdated = $this->recipient->statusUpdated; + $this->recipient->recipient->statusLabel = $this->buildStatusLabel($this->recipient->recipient->status); $this->recipient = $this->recipient->recipient; } @@ -127,4 +152,64 @@ public function getSellers() return $this->sellers; } -} \ No newline at end of file + + /** + * @param string $countryCode + * @return array + */ + public function getAllRegionsOfCountry($countryCode = 'BR') + { + return $this->country->loadByCode($countryCode)->getRegions()->getData(); + } + + public function getLabel($key) + { + $labels = [ + 'no' => 'No', + 'yes' => 'Yes', + 'document_type' => 'Document type', + 'document_number' => 'Document number', + 'name' => 'Name', + 'mother_name' => 'Mother name', + 'email' => 'E-mail', + 'birthdate' => 'Date of birth', + 'monthly_income' => 'Monthly income', + 'profession' => 'Profession', + 'contact_type' => 'Contact type', + 'contact_number' => 'Contact number', + 'mobile_phone' => 'Mobile phone', + 'street' => 'Street', + 'number' => 'Number', + 'complement' => 'Complement', + 'neighborhood' => 'Neighborhood', + 'reference_point' => 'Reference point', + 'state' => 'State/Province', + 'city' => 'City', + 'zip' => 'Zip/Postal Code', + 'select' => 'Select', + ]; + + return __($labels[$key]); + } + + /** + * @param string|null $status + * @return string|null + */ + private function buildStatusLabel($status) + { + if (!is_string($status)) { + return $status; + } + + if ($status === CoreRecipientInterface::ACTIVE) { + $status = 'approved'; + } + + $statusWords = explode('_', $status); + $statusWords = array_map('ucfirst', $statusWords); + $statusLabel = implode(" ", $statusWords); + $statusLabel = trim($statusLabel); + return __($statusLabel); + } +} diff --git a/Block/Customer/Marketplace/Kyc.php b/Block/Customer/Marketplace/Kyc.php new file mode 100644 index 00000000..98123226 --- /dev/null +++ b/Block/Customer/Marketplace/Kyc.php @@ -0,0 +1,69 @@ +customerSession = $customerSession; + $this->collectionFactory = $collectionFactory; + parent::__construct($context, $data); + } + + + /** + * @return Recipient + */ + public function getRecipient() + { + return $this->collectionFactory->create()->addFieldToFilter( + 'external_id', + ['eq' => $this->getCustomerId()] + )->getFirstItem(); + } + + /** + * Get customerId + * + * @return int + */ + protected function getCustomerId() + { + return $this->customerSession->getCustomerId(); + } +} diff --git a/Block/Payment/Info/BaseCardInfo.php b/Block/Payment/Info/BaseCardInfo.php new file mode 100644 index 00000000..7c7a72c3 --- /dev/null +++ b/Block/Payment/Info/BaseCardInfo.php @@ -0,0 +1,78 @@ +getInfo()->getOrder()->getIncrementId(); + $platformOrder = $this->loadPlatformOrderByIncrementId($orderEntityId); + + $orderPagarmeId = $platformOrder->getPagarmeId(); + + if ($orderPagarmeId === null) { + return []; + } + + $orderObject = $this->getOrderObjectByPagarmeId($orderService, $orderPagarmeId); + + if ($orderObject === null || !is_object($orderObject)) { + return []; + } + + $charge = current($orderObject->getCharges()); + $lastFourDigitsWithDots = sprintf( + "**** **** **** %s", + $charge->getLastTransaction()->getCardData()->getLastFourDigits()->getValue() + ); + return array_merge( + $charge->getAcquirerTidCapturedAndAuthorize(), + ['tid' => $charge->getLastTransaction()->getAcquirerTid() ?? ""], + ['cardBrand' => $charge->getLastTransaction()->getCardData()->getBrand()->getName() ?? ""], + ['installments' => $this->getInfo()->getAdditionalInformation('cc_installments') ?? ""], + ['lastFour' => $lastFourDigitsWithDots], + ['acquirerMessage' => $charge->getLastTransaction()->getAcquirerMessage() ?? ""] + ); + } + + /** + * @param mixed $orderService + * @param mixed $pagarmeId + * @return mixed + */ + protected function getOrderObjectByPagarmeId($orderService, $pagarmeId) + { + $orderId = new OrderId($pagarmeId); + return $orderService->getOrderByPagarmeId($orderId); + } + /** + * @param mixed $incrementId + * @return Magento2PlatformOrderDecorator + */ + protected function loadPlatformOrderByIncrementId($incrementId) + { + $platformOrder = new Magento2PlatformOrderDecorator(); + $platformOrder->loadByIncrementId($incrementId); + return $platformOrder; + } +} diff --git a/Block/Payment/Info/BilletCreditCard.php b/Block/Payment/Info/BilletCreditCard.php index d6cefa27..bba58335 100644 --- a/Block/Payment/Info/BilletCreditCard.php +++ b/Block/Payment/Info/BilletCreditCard.php @@ -175,7 +175,7 @@ public function getTransactionInfo() if ($item->getAcquirerNsu() != 0) { $transactionList['creditCard'] = array_merge( - $orderObject->getCharges()[0]->getAcquirerTidCapturedAndAutorize(), + $orderObject->getCharges()[0]->getAcquirerTidCapturedAndAuthorize(), ['tid' => $this->getTid($orderObject->getCharges()[0])] ); diff --git a/Block/Payment/Info/CreditCard.php b/Block/Payment/Info/CreditCard.php index 8a79027e..370e536f 100644 --- a/Block/Payment/Info/CreditCard.php +++ b/Block/Payment/Info/CreditCard.php @@ -11,20 +11,12 @@ namespace Pagarme\Pagarme\Block\Payment\Info; -use Exception; -use Magento\Framework\Exception\LocalizedException; -use Magento\Payment\Block\Info\Cc; -use Pagarme\Core\Kernel\Aggregates\Charge; -use Pagarme\Core\Kernel\Exceptions\InvalidParamException; -use Pagarme\Core\Kernel\Services\OrderService; -use Pagarme\Core\Kernel\ValueObjects\Id\OrderId; +use Pagarme\Pagarme\Block\Payment\Info\BaseCardInfo; use Pagarme\Core\Payment\Aggregates\Payments\Authentication\AuthenticationStatusEnum; -use Pagarme\Pagarme\Concrete\Magento2CoreSetup; -use Pagarme\Pagarme\Concrete\Magento2PlatformOrderDecorator; -class CreditCard extends Cc +class CreditCard extends BaseCardInfo { - const TEMPLATE = 'Pagarme_Pagarme::info/creditCard.phtml'; + const TEMPLATE = 'Pagarme_Pagarme::info/card.phtml'; /** * @return void @@ -42,22 +34,6 @@ public function getCcType() return $this->getCcTypeName(); } - /** - * @return string - */ - public function getCardLast4() - { - return '**** **** **** ' . $this->getInfo()->getAdditionalInformation('cc_last_4'); - } - - /** - * @return mixed - */ - public function getCcBrand() - { - return $this->getInfo()->getAdditionalInformation('cc_type'); - } - /** * @return mixed */ @@ -66,14 +42,6 @@ public function getTitle() return $this->getInfo()->getAdditionalInformation('method_title'); } - /** - * @return mixed - */ - public function getInstallments() - { - return $this->getInfo()->getAdditionalInformation('cc_installments'); - } - public function getThreeDSStatus() { $authenticationAdditionalInformation = $this->getInfo()->getAdditionalInformation('authentication'); @@ -86,76 +54,4 @@ public function getThreeDSStatus() $authentication['trans_status'] ?? '' ); } - - /** - * @return array - * @throws InvalidParamException - * @throws LocalizedException - * @throws Exception - */ - public function getTransactionInfo() - { - Magento2CoreSetup::bootstrap(); - $orderService = new OrderService(); - - $orderEntityId = $this->getInfo()->getOrder()->getIncrementId(); - $platformOrder = $this->loadPlatformOrderByIncrementId($orderEntityId); - - $orderPagarmeId = $platformOrder->getPagarmeId(); - - if ($orderPagarmeId === null) { - return []; - } - - $orderObject = $this->getOrderObjectByPagarmeId($orderService, $orderPagarmeId); - - if ($orderObject === null || !is_object($orderObject)) { - return []; - } - - $charge = current($orderObject->getCharges()); - - return array_merge( - $charge->getAcquirerTidCapturedAndAutorize(), - ['tid' => $this->getTid($charge)] - ); - } - - /** - * @param mixed $incrementId - * @return Magento2PlatformOrderDecorator - */ - private function loadPlatformOrderByIncrementId($incrementId) - { - $platformOrder = new Magento2PlatformOrderDecorator(); - $platformOrder->loadByIncrementId($incrementId); - return $platformOrder; - } - - /** - * @param mixed $orderService - * @param mixed $pagarmeId - * @return mixed - */ - private function getOrderObjectByPagarmeId($orderService, $pagarmeId) - { - $orderId = new OrderId($pagarmeId); - return $orderService->getOrderByPagarmeId($orderId); - } - - /** - * @param \Pagarme\Core\Kernel\Aggregates\Charge $charge - * @return string|null - */ - private function getTid(Charge $charge) - { - $transaction = $charge->getLastTransaction(); - - $tid = null; - if ($transaction !== null) { - $tid = $transaction->getAcquirerTid(); - } - - return $tid; - } } diff --git a/Block/Payment/Info/Debit.php b/Block/Payment/Info/Debit.php index 81b52f39..113768c5 100644 --- a/Block/Payment/Info/Debit.php +++ b/Block/Payment/Info/Debit.php @@ -2,7 +2,21 @@ namespace Pagarme\Pagarme\Block\Payment\Info; -class Debit extends CreditCard +use Pagarme\Pagarme\Block\Payment\Info\BaseCardInfo; + +class Debit extends BaseCardInfo { + const TEMPLATE = 'Pagarme_Pagarme::info/card.phtml'; + public function _construct() + { + $this->setTemplate(self::TEMPLATE); + } + /** + * @return mixed + */ + public function getTitle() + { + return $this->getInfo()->getAdditionalInformation('method_title'); + } } diff --git a/Block/Payment/Info/GooglePay.php b/Block/Payment/Info/GooglePay.php new file mode 100644 index 00000000..4dbf9218 --- /dev/null +++ b/Block/Payment/Info/GooglePay.php @@ -0,0 +1,19 @@ +setTemplate(self::TEMPLATE); + } +} diff --git a/Block/Payment/Info/TwoCreditCard.php b/Block/Payment/Info/TwoCreditCard.php index 5474f959..a2b94dd4 100644 --- a/Block/Payment/Info/TwoCreditCard.php +++ b/Block/Payment/Info/TwoCreditCard.php @@ -159,11 +159,11 @@ public function getTransactionInfo() return [ 'card1' => array_merge( - $chargeOne->getAcquirerTidCapturedAndAutorize(), + $chargeOne->getAcquirerTidCapturedAndAuthorize(), ['tid' => $this->getTid($chargeOne)] ), 'card2' => array_merge( - $chargeTwo->getAcquirerTidCapturedAndAutorize(), + $chargeTwo->getAcquirerTidCapturedAndAuthorize(), ['tid' => $this->getTid($chargeTwo)] ) ]; diff --git a/Block/Payment/Info/Voucher.php b/Block/Payment/Info/Voucher.php index 1eb361c4..f45d675a 100644 --- a/Block/Payment/Info/Voucher.php +++ b/Block/Payment/Info/Voucher.php @@ -2,9 +2,9 @@ namespace Pagarme\Pagarme\Block\Payment\Info; -use Magento\Payment\Block\Info\Cc; +use Pagarme\Pagarme\Block\Payment\Info\BaseCardInfo; -class Voucher extends Cc +class Voucher extends BaseCardInfo { } diff --git a/Concrete/Magento2CoreSetup.php b/Concrete/Magento2CoreSetup.php index f44eda85..a61ec500 100644 --- a/Concrete/Magento2CoreSetup.php +++ b/Concrete/Magento2CoreSetup.php @@ -143,20 +143,21 @@ public function loadModuleConfigurationFromPlatform($storeConfig = null) return; } - self::fillWithGeneralConfig($configData, $storeConfig); - self::fillWithPagarmeKeys($configData, $storeConfig); - self::fillWithCardConfig($configData, $storeConfig); - self::fillWithBoletoConfig($configData, $storeConfig); - self::fillWithPixConfig($configData, $storeConfig); - self::fillWithBoletoCreditCardConfig($configData, $storeConfig); - self::fillWithTwoCreditCardsConfig($configData, $storeConfig); - self::fillWithVoucherConfig($configData, $storeConfig); - self::fillWithDebitConfig($configData, $storeConfig); - self::fillWithAddressConfig($configData, $storeConfig); - self::fillWithMultiBuyerConfig($configData, $storeConfig); - self::fillWithRecurrenceConfig($configData, $storeConfig); - self::fillWithHubConfig($configData, $storeConfig); - self::fillWithMarketplaceConfig($configData, $storeConfig); + self::fillWithGeneralConfig($configData, $storeConfig); + self::fillWithPagarmeKeys($configData, $storeConfig); + self::fillWithCardConfig($configData, $storeConfig); + self::fillWithBoletoConfig($configData, $storeConfig); + self::fillWithPixConfig($configData, $storeConfig); + self::fillWithGooglePayConfig($configData, $storeConfig); + self::fillWithBoletoCreditCardConfig($configData, $storeConfig); + self::fillWithTwoCreditCardsConfig($configData, $storeConfig); + self::fillWithVoucherConfig($configData, $storeConfig); + self::fillWithDebitConfig($configData, $storeConfig); + self::fillWithAddressConfig($configData, $storeConfig); + self::fillWithMultiBuyerConfig($configData, $storeConfig); + self::fillWithRecurrenceConfig($configData, $storeConfig); + self::fillWithHubConfig($configData, $storeConfig); + self::fillWithMarketplaceConfig($configData, $storeConfig); $configurationFactory = new ConfigurationFactory(); $config = $configurationFactory->createFromJsonData( @@ -294,6 +295,24 @@ private static function fillWithPixConfig( $configData->pixConfig = self::fillDataObj($storeConfig, $options, $pixObject, $section); } + + private static function fillWithGooglePayConfig( + stdClass $configData, + ScopeConfigInterface $storeConfig + ) { + $options = [ + 'enabled' => 'active', + 'title' => 'title', + 'merchantId' => 'merchant_id', + 'merchantName' => 'merchant_name' + ]; + + $section = 'payment/pagarme_googlepay/'; + + $googlePayObject = new \stdClass(); + + $configData->googlePayConfig = self::fillDataObj($storeConfig, $options, $googlePayObject, $section); + } static private function fillWithBoletoConfig(&$dataObj, $storeConfig) diff --git a/Concrete/Magento2PlatformOrderDecorator.php b/Concrete/Magento2PlatformOrderDecorator.php index 6db33ffb..cc079c1e 100644 --- a/Concrete/Magento2PlatformOrderDecorator.php +++ b/Concrete/Magento2PlatformOrderDecorator.php @@ -30,6 +30,7 @@ use Pagarme\Core\Payment\Aggregates\Payments\NewDebitCardPayment; use Pagarme\Core\Payment\Aggregates\Payments\NewVoucherPayment; use Pagarme\Core\Payment\Aggregates\Payments\PixPayment; +use Pagarme\Core\Payment\Aggregates\Payments\GooglePayPayment; use Pagarme\Core\Payment\Aggregates\Shipping; use Pagarme\Core\Payment\Factories\PaymentFactory; use Pagarme\Core\Payment\Repositories\CustomerRepository as CoreCustomerRepository; @@ -126,7 +127,8 @@ public function getState() public function setStatusAfterLog(OrderStatus $status) { $stringStatus = $status->getStatus(); - $this->platformOrder->setStatus($stringStatus); + $stringMagentoStatus = $this->getMagentoStatusFromCoreStatus($stringStatus); + $this->platformOrder->setStatus($stringMagentoStatus); } public function getStatus() @@ -1194,6 +1196,25 @@ private function extractPaymentDataFromPagarmePix( $paymentData[$pixDataIndex][] = $newPaymentData; } + private function extractPaymentDataFromPagarmeGooglepay( + $additionalInformation, + &$paymentData, + $payment + ) { + $newPaymentData = new stdClass(); + $newPaymentData->amount = + $this->moneyService->floatToCents($this->platformOrder->getGrandTotal()); + $newPaymentData->googlepayData = $additionalInformation['googlepayData']; + $newPaymentData->additionalInformation = ["googlepayData" => $additionalInformation['googlepayData']]; + $googlepayIndex = 'googlepay'; + if (!isset($paymentData[$googlepayIndex])) { + $paymentData[$googlepayIndex] = []; + } + + $paymentData[$googlepayIndex][] = $newPaymentData; + } + + public function getShipping() { /** @var Shipping $shipping */ @@ -1336,4 +1357,18 @@ public function handleSplitOrder() return $splitData; } + + /** + * @param string|null $coreStatus + * @return string|null + */ + private function getMagentoStatusFromCoreStatus($coreStatus) + { + $coreToMagentoStatus = [ + 'failed' => 'canceled' + ]; + + return array_key_exists($coreStatus, $coreToMagentoStatus) ? + $coreToMagentoStatus[$coreStatus] : $coreStatus; + } } diff --git a/Concrete/Magento2PlatformPaymentMethodDecorator.php b/Concrete/Magento2PlatformPaymentMethodDecorator.php index e9d5c92e..fa652e12 100644 --- a/Concrete/Magento2PlatformPaymentMethodDecorator.php +++ b/Concrete/Magento2PlatformPaymentMethodDecorator.php @@ -11,6 +11,7 @@ class Magento2PlatformPaymentMethodDecorator implements PlatformPaymentMethodInt const VOUCHER = 'voucher'; const DEBIT = "debit"; const PIX = "pix"; + const GOOGLEPAY = "googlepay"; private $paymentMethod; @@ -79,4 +80,9 @@ private function pix() { return self::PIX; } + + private function googlepay() + { + return self::GOOGLEPAY; + } } diff --git a/Controller/Adminhtml/Recipients/Create.php b/Controller/Adminhtml/Recipients/Create.php index 81ace41b..a2fbf44f 100644 --- a/Controller/Adminhtml/Recipients/Create.php +++ b/Controller/Adminhtml/Recipients/Create.php @@ -2,11 +2,7 @@ namespace Pagarme\Pagarme\Controller\Adminhtml\Recipients; -use Magento\Framework\Registry; use Magento\Framework\Controller\ResultInterface; -use Pagarme\Core\Marketplace\Services\RecipientService; -use Webkul\Marketplace\Model\SellerFactory; -use Pagarme\Pagarme\Controller\Adminhtml\Recipients\RecipientAction; class Create extends RecipientAction { @@ -17,32 +13,43 @@ class Create extends RecipientAction */ public function execute() { + $sellers = $this->sellerFactory->create()->getCollection()->load(); $sellers = $sellers->getItems(); - $this->coreRegistry->register('sellers', serialize($sellers)); $recipientId = (int)$this->getRequest()->getParam('id'); if ($recipientId) { - - $recipientService = new RecipientService(); - $recipient = $recipientService->findById($recipientId); - $externalId = $recipient->getExternalId(); - $localId = $recipient->getId(); - $recipient = $recipientService->findByPagarmeId($recipient->getPagarmeId()); - + $this->resourceModelRecipient->load($this->recipient, $recipientId); + $recipient = $this->recipientService->searchRecipient($this->recipient->getPagarmeId()); + $statusUpdated = false; + if ($this->recipient->getStatus() !== $recipient->status) { + $this->recipient->setStatus($recipient->status); + $this->resourceModelRecipient->save($this->recipient); + $statusUpdated = true; + } if (!$recipient || !$recipient->id) { $this->messageManager->addError(__('Recipient not exist.')); $this->_redirect('pagarme_pagarme/recipients/index'); return; } - $this->coreRegistry->register('recipient_data', json_encode(['recipient' => $recipient, 'externalId' => $externalId, 'localId' => $localId])); + + $this->coreRegistry->register( + 'recipient_data', + json_encode([ + 'recipient' => $recipient, + 'externalId' => $recipient->code, + 'localId' => $recipientId, + 'status' => $this->recipient->getStatus(), + 'statusUpdated' => $statusUpdated + ]) + ); } $resultPage = $this->resultPageFactory->create(); - $title = $recipientId ? __('Edit Recipient') : __('Create Recipient'); + $title = $recipientId ? __('Recipient') : __('Create Recipient'); $resultPage->getConfig()->getTitle()->prepend($title); diff --git a/Controller/Adminhtml/Recipients/Delete.php b/Controller/Adminhtml/Recipients/Delete.php index dfcb079d..a07ee049 100644 --- a/Controller/Adminhtml/Recipients/Delete.php +++ b/Controller/Adminhtml/Recipients/Delete.php @@ -32,7 +32,7 @@ public function execute() $recipientService->delete($recipientId); - $message = $this->messageFactory->create('success', _("Recipient deleted.")); + $message = $this->messageFactory->create('success', __("Recipient deleted.")); $this->messageManager->addMessage($message); $this->_redirect('pagarme_pagarme/recipients/index'); diff --git a/Controller/Adminhtml/Recipients/RecipientAction.php b/Controller/Adminhtml/Recipients/RecipientAction.php index 49a1816f..e1bbc893 100644 --- a/Controller/Adminhtml/Recipients/RecipientAction.php +++ b/Controller/Adminhtml/Recipients/RecipientAction.php @@ -4,14 +4,16 @@ use Exception; use Magento\Backend\App\Action; -use Magento\Backend\App\Action\Context; use Magento\Framework\Registry; +use Pagarme\Pagarme\Model\Recipient; +use Magento\Backend\App\Action\Context; +use Webkul\Marketplace\Model\SellerFactory; use Magento\Framework\View\Result\PageFactory; use Pagarme\Pagarme\Concrete\Magento2CoreSetup; -use Webkul\Marketplace\Model\SellerFactory; -use Magento\Framework\Message\Factory as MagentoMessageFactory; use Magento\Framework\Module\Manager as ModuleManager; - +use Pagarme\Pagarme\Service\Marketplace\RecipientService; +use Magento\Framework\Message\Factory as MagentoMessageFactory; +use Pagarme\Pagarme\Model\ResourceModel\Recipients as ResourceModelRecipient; class RecipientAction extends Action { @@ -36,6 +38,21 @@ class RecipientAction extends Action * @var ModuleManager */ private $moduleManager; + /** + * + * @var \Pagarme\Pagarme\Model\ResourceModel\Recipients + */ + protected $resourceModelRecipient; + /** + * + * @var \Pagarme\Pagarme\Model\Recipient + */ + protected $recipient; + /** + * + * @var \Pagarme\Pagarme\Service\Marketplace\RecipientService + */ + protected $recipientService; /** * @param Context $context @@ -43,6 +60,9 @@ class RecipientAction extends Action * @param PageFactory $resultPageFactory * @param MagentoMessageFactory $messageFactory * @param ModuleManager $moduleManager + * @param ResourceModelRecipient $resourceModelRecipient + * @param Recipient $recipient + * @param RecipientService $recipientService * @throws Exception */ public function __construct( @@ -50,7 +70,10 @@ public function __construct( Registry $coreRegistry, PageFactory $resultPageFactory, MagentoMessageFactory $messageFactory, - ModuleManager $moduleManager + ModuleManager $moduleManager, + ResourceModelRecipient $resourceModelRecipient, + Recipient $recipient, + RecipientService $recipientService ) { parent::__construct($context); @@ -59,7 +82,11 @@ public function __construct( $this->coreRegistry = $coreRegistry; $this->messageFactory = $messageFactory; $this->moduleManager = $moduleManager; + $this->resourceModelRecipient = $resourceModelRecipient; + $this->recipient = $recipient; + $this->recipientService = $recipientService; $this->__init(); + Magento2CoreSetup::bootstrap(); } diff --git a/Gateway/Transaction/GooglePay/Config/Config.php b/Gateway/Transaction/GooglePay/Config/Config.php new file mode 100755 index 00000000..f941f911 --- /dev/null +++ b/Gateway/Transaction/GooglePay/Config/Config.php @@ -0,0 +1,67 @@ +getConfig(static::PATH_TITLE); + + if (empty($title)) { + return __('Pagar.me Google Pay'); + } + + return $title; + } + + /** + * Return Google ID + * @return string + */ + public function getMerchantId() + { + return $this->getConfig(static::MERCHANT_ID); + } + + /** + * Return Merchant Name + * @return string + */ + public function getMerchantName() + { + return $this->getConfig(static::MERCHANT_NAME); + } + + /** + * Return Cards Brands + * @return array + */ + public function getCardBrands() + { + $brandsAllowed = []; + $creditCardBrandsSelected = explode(',', $this->getConfig(static::CARD_BRANDS)); + foreach ($creditCardBrandsSelected as $brand) { + if (in_array(strtoupper($brand), static::GOOGLE_POSSIBLE_BRANDS)) { + $brandsAllowed[] = strtoupper($brand); + } + } + return $brandsAllowed; + } +} diff --git a/Gateway/Transaction/GooglePay/Config/ConfigInterface.php b/Gateway/Transaction/GooglePay/Config/ConfigInterface.php new file mode 100755 index 00000000..c358f637 --- /dev/null +++ b/Gateway/Transaction/GooglePay/Config/ConfigInterface.php @@ -0,0 +1,34 @@ +setConfig($config); + } + + /** + * @return ConfigInterface + */ + protected function getConfig() + { + return $this->config; + } + + /** + * @param ConfigInterface $config + * @return $this + */ + protected function setConfig($config) + { + $this->config = $config; + return $this; + } + +} diff --git a/Gateway/Transaction/GooglePay/Create/Response/Validator.php b/Gateway/Transaction/GooglePay/Create/Response/Validator.php new file mode 100644 index 00000000..4b51be10 --- /dev/null +++ b/Gateway/Transaction/GooglePay/Create/Response/Validator.php @@ -0,0 +1,34 @@ +createResult($isValid, $fails); + } +} diff --git a/Helper/BuildChargeAddtionalInformationHelper.php b/Helper/BuildChargeAddtionalInformationHelper.php index 60394951..b48d1a25 100644 --- a/Helper/BuildChargeAddtionalInformationHelper.php +++ b/Helper/BuildChargeAddtionalInformationHelper.php @@ -55,7 +55,7 @@ function (Transaction $transaction) { if (empty($billetTransaction)) { $acquirerNsuCapturedAndAutorize = - $charge->getAcquirerTidCapturedAndAutorize(); + $charge->getAcquirerTidCapturedAndAuthorize(); $chargeInformation[$key]["cc_tid"] = $charge->getLastTransaction()->getAcquirerTid(); @@ -92,7 +92,7 @@ private static function buildTwoCreditcard(array $charges) $name = $nameForTwoCards[$key]; $acquirerNsuCapturedAndAutorize = - $charge->getAcquirerTidCapturedAndAutorize(); + $charge->getAcquirerTidCapturedAndAuthorize(); $chargeInformation[$key]["cc_tid{$name}"] = $charge->getLastTransaction()->getAcquirerTid(); @@ -116,7 +116,7 @@ private static function buildCreditcard(array $charges) $chargeInformation = []; foreach ($charges as $key => $charge) { $acquirerNsuCapturedAndAutorize = - $charge->getAcquirerTidCapturedAndAutorize(); + $charge->getAcquirerTidCapturedAndAuthorize(); $chargeInformation[$key]["cc_tid"] = $charge->getLastTransaction()->getAcquirerTid(); diff --git a/Model/Api/KycLinkResponse.php b/Model/Api/KycLinkResponse.php new file mode 100644 index 00000000..7c7cedc2 --- /dev/null +++ b/Model/Api/KycLinkResponse.php @@ -0,0 +1,29 @@ +_getData(self::DATA_URL); + } + + public function getQrCode() + { + return $this->_getData(self::DATA_QR_CODE); + } + + public function setUrl(string $url) + { + return $this->setData(self::DATA_URL, $url); + } + + public function setQrCode(string $qrCode) + { + return $this->setData(self::DATA_QR_CODE, $qrCode); + } +} \ No newline at end of file diff --git a/Model/Api/Recipient.php b/Model/Api/Recipient.php index f681ef86..9a232ad0 100644 --- a/Model/Api/Recipient.php +++ b/Model/Api/Recipient.php @@ -2,12 +2,19 @@ namespace Pagarme\Pagarme\Model\Api; +use Exception; +use InvalidArgumentException; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\Webapi\Rest\Request; -use Pagarme\Core\Kernel\ValueObjects\Id\RecipientId; -use Pagarme\Core\Marketplace\Services\RecipientService; -use Pagarme\Core\Recurrence\Services\PlanService; +use Pagarme\Core\Kernel\Services\LogService; +use Pagarme\Core\Marketplace\Interfaces\RecipientInterface as CoreRecipientInterface; +use Pagarme\Core\Middle\Factory\RecipientFactory as CoreRecipient; +use Pagarme\Pagarme\Api\KycLinkResponseInterfaceFactory; use Pagarme\Pagarme\Api\RecipientInterface; -use Pagarme\Pagarme\Concrete\Magento2CoreSetup; +use Pagarme\Pagarme\Model\RecipientFactory as ModelFactoryRecipient; +use Pagarme\Pagarme\Model\ResourceModel\Recipients as ResourceModelRecipient; +use Pagarme\Pagarme\Service\Marketplace\RecipientService; +use Throwable; class Recipient implements RecipientInterface { @@ -16,94 +23,163 @@ class Recipient implements RecipientInterface */ protected $request; + /** + * @var ModelFactoryRecipient + */ + protected $modelFactoryRecipient; + + /** + * @var ResourceModelRecipient + */ + protected $resourceModelRecipient; + + /** + * @var CoreRecipient + */ + protected $coreRecipient; + /** * @var RecipientService */ protected $recipientService; - public function __construct(Request $request) - { - Magento2CoreSetup::bootstrap(); + /** + * @var KycLinkResponseInterfaceFactory + */ + protected $kycLinkResponseFactory; + + public function __construct( + Request $request, + ModelFactoryRecipient $modelFactoryRecipient, + ResourceModelRecipient $resourceModelRecipient, + CoreRecipient $coreRecipient, + RecipientService $recipientService, + KycLinkResponseInterfaceFactory $kycLinkResponseFactory + ) { $this->request = $request; - $this->recipientService = new RecipientService(); + $this->modelFactoryRecipient = $modelFactoryRecipient; + $this->resourceModelRecipient = $resourceModelRecipient; + $this->coreRecipient = $coreRecipient; + $this->recipientService = $recipientService; + $this->kycLinkResponseFactory = $kycLinkResponseFactory; } /** * @return mixed + * @throws Exception */ public function saveFormData(): string { - $post = $this->request->getBodyParams(); - parse_str($post[0], $params); + $bodyParams = current($this->request->getBodyParams()); + parse_str($bodyParams, $params); + $params = $params['form']; - $form = $this->getFormattedForm($params['form']); + try { + $message = __( + "
He can now sell, but remember to check his " + . "status. He can only withdraw his sales amounts once the status is " + . "“active”
" + ); + + if (empty($params['pagarme_id'])) { + $recipientOnPagarme = $this->createOnPagarme($params); + $params['pagarme_id'] = $recipientOnPagarme->id; + $params['status'] = CoreRecipientInterface::REGISTERED; + $message = __( + "Follow the status on Pagar.me > Recipients to activate" + . " this recipient's balance movement soon!
" + ); + } + $this->saveOnPlatform($params); - if (empty($form)) { return json_encode([ - 'code' => 400, - 'message' => 'Error on save recipient' + 'code' => 200, + 'message' => $message ]); - } + } catch (Throwable $th) { + $logService = new LogService("Recipient Log", true, 1); + $logService->info($th->getMessage(), [ + 'webkul_seller' => $params['register_information']['webkul_seller'], + 'document' => $params['register_information']['document'], + 'external_id' => $params['register_information']['external_id'] - try { - $this->recipientService->saveFormRecipient($form); - } catch (\Exception $exception) { + ]); return json_encode([ 'code' => 400, - 'message' => $exception->getMessage() + 'message' => __('An error occurred while saving the recipient.') + . ' ' . __($th->getMessage()) ]); } - - return json_encode([ - 'code' => 200, - 'message' => 'Recipient saved' - ]); } - public function getFormattedForm(array $form): array + /** + * @throws Exception + */ + private function saveOnPlatform($params) { - $form['holder_document'] = preg_replace("/[^0-9]/", "", $form['holder_document'] ?? ''); - $form['document'] = preg_replace("/[^0-9]/", "", $form['document'] ?? ''); - if (isset($form['type'])) { - $form['holder_type'] = $form['type']; - } - if (isset($form['pagarme_id'])) { - $form['recipient_id'] = $form['pagarme_id']; - } + $registeredInformation = $params['register_information']; + $recipientModel = $this->modelFactoryRecipient->create(); + $recipientModel->setId(null); + $recipientModel->setExternalId($registeredInformation['external_id']); + $recipientModel->setName(empty($registeredInformation['name']) ? $registeredInformation['company_name'] : $registeredInformation['name']); + $recipientModel->setEmail($registeredInformation['email']); + $recipientModel->setDocument($registeredInformation['document']); + $recipientModel->setPagarmeId($params['pagarme_id']); + $recipientModel->setType($registeredInformation['type']); + $recipientModel->setStatus($params['status']); + $this->resourceModelRecipient->save($recipientModel); + } - return $form; + /** + * @param $recipientData + * @return mixed + */ + private function createOnPagarme($recipientData) + { + $coreRecipient = $this->coreRecipient->createRecipient($recipientData); + return $this->recipientService->createRecipient($coreRecipient); } + /** + * @return string + */ public function searchRecipient(): string { $post = $this->request->getBodyParams(); try { - $recipientId = new RecipientId($post['recipientId']); - } catch (\Exception $e) { - return json_encode([ - 'code' => 400, - 'message' => 'Invalid Pagar.me ID' - ]); - } - - try { - $recipient = $this->recipientService->findByPagarmeId($recipientId); - - if ($recipient->status != 'active') { - throw new \Exception('Recipient not active'); + $recipient = $this->recipientService->searchRecipient($post['recipientId']); + if ($recipient->status !== 'active') { + throw new InvalidArgumentException(__('Recipient not active.')); } - } catch (\Exception $e) { + } catch (Exception $e) { return json_encode([ 'code' => 404, - 'message' => $e->getMessage(), + 'message' => __($e->getMessage()), ]); } return json_encode([ 'code' => 200, - 'message' => 'Recipient finded', + 'message' => __('Recipient found.'), 'recipient' => $recipient, ]); } + + public function createKycLink(string $id) + { + $recipientModel = $this->modelFactoryRecipient->create(); + $this->resourceModelRecipient->load($recipientModel, $id); + if (empty($recipientModel->getPagarmeId())) { + throw new NoSuchEntityException(__('Recipient not founded.')); + } + $kycLink = $this->recipientService->createKycLink($recipientModel->getPagarmeId()); + if (empty($kycLink->url) || empty($kycLink->base64_qrcode)) { + throw new NoSuchEntityException(__('Failed to generate the security validation link.')); + } + $kycResponse = $this->kycLinkResponseFactory->create(); + $kycResponse->setUrl($kycLink->url) + ->setQrCode('data:image/svg+xml;base64,' . $kycLink->base64_qrcode); + return $kycResponse; + } } diff --git a/Model/PagarmeConfigProvider.php b/Model/PagarmeConfigProvider.php index 3e177702..38a4b662 100644 --- a/Model/PagarmeConfigProvider.php +++ b/Model/PagarmeConfigProvider.php @@ -51,6 +51,7 @@ class PagarmeConfigProvider implements ConfigProviderInterface const PATH_VOUCHER_ENABLED = 'payment/pagarme_voucher/active'; const PATH_DEBIT_ENABLED = 'payment/pagarme_debit/active'; + const PATH_GOOGLEPAY_ENABLED = 'payment/pagarme_googlepay/active'; const PATH_IS_PAYMENT_GATEWAY_TYPE = 'pagarme_pagarme/%s/is_payment_gateway'; @@ -63,6 +64,8 @@ class PagarmeConfigProvider implements ConfigProviderInterface const DEBIT_PAYMENT_CONFIG = 'pagarme_debit'; const PIX_PAYMENT_CONFIG = 'pagarme_pix'; + + const GOOGLEPAY_PAYMENT_CONFIG = 'pagarme_googlepay'; const VOUCHER_PAYMENT_CONFIG = 'pagarme_voucher'; @@ -386,6 +389,17 @@ public function isDebitEnabled($website = null) $website ); } + /** + * @return bool + */ + public function isGooglePayEnabled($website = null) + { + return (bool) $this->scopeConfig->getValue( + self::PATH_GOOGLEPAY_ENABLED, + ScopeInterface::SCOPE_WEBSITES, + $website + ); + } /** * @param mixed $website @@ -398,7 +412,8 @@ public function availablePaymentMethods($website = null) PaymentEnum::DEBIT_CARD => $this->isDebitEnabled($website), PaymentEnum::BILLET => $this->isAnyBilletMethodEnabled($website), PaymentEnum::CREDIT_CARD => $this->isAnyCreditCardMethodEnabled($website), - PaymentEnum::VOUCHER => $this->isVoucherEnabled($website) + PaymentEnum::VOUCHER => $this->isVoucherEnabled($website), + PaymentEnum::GOOGLEPAY => $this->isGooglePayEnabled($website) ]; } @@ -410,6 +425,7 @@ public function getConfig(): array return [ 'pagarme_is_sandbox_mode' => $this->pagarmeConfig->isSandboxMode(), 'pagarme_is_hub_enabled' => $this->pagarmeConfig->isHubEnabled(), + 'pagarme_account_id' => $this->getAccountId(), 'pagarme_customer_configs' => $this->pagarmeConfig->getPagarmeCustomerConfigs(), 'pagarme_customer_address_configs' => $this->pagarmeConfig->getPagarmeCustomerAddressConfigs() ] ; diff --git a/Model/Recipient.php b/Model/Recipient.php index 29f1688a..1e5ce179 100644 --- a/Model/Recipient.php +++ b/Model/Recipient.php @@ -2,23 +2,13 @@ namespace Pagarme\Pagarme\Model; -use Magento\Framework\DataObject\IdentityInterface; use Magento\Framework\Model\AbstractModel; -class Recipient extends AbstractModel implements IdentityInterface +class Recipient extends AbstractModel { protected function _construct() { $this->_init('Pagarme\Pagarme\Model\ResourceModel\Recipients'); } - - /** - * Return unique ID(s) for each object in system - * - * @return string[] - */ - public function getIdentities() - { - return $this->getId(); - } + } diff --git a/Model/ResourceModel/Recipients.php b/Model/ResourceModel/Recipients.php index 6a764c2e..30aacdf7 100644 --- a/Model/ResourceModel/Recipients.php +++ b/Model/ResourceModel/Recipients.php @@ -3,15 +3,10 @@ namespace Pagarme\Pagarme\Model\ResourceModel; use Magento\Framework\Model\ResourceModel\Db\AbstractDb; -use Magento\Framework\Model\ResourceModel\Db\Context; class Recipients extends AbstractDb { - public function __construct(Context $context) - { - parent::__construct($context); - } - + protected function _construct() { $this->_init('pagarme_module_core_recipients', 'id'); diff --git a/Model/Ui/GooglePay/ConfigProvider.php b/Model/Ui/GooglePay/ConfigProvider.php new file mode 100644 index 00000000..4c53106c --- /dev/null +++ b/Model/Ui/GooglePay/ConfigProvider.php @@ -0,0 +1,38 @@ +googlePayConfig = $googlePayConfig; + } + + public function getConfig() + { + return [ + 'payment' => [ + self::CODE => [ + 'active' => true, + 'title' => $this->googlePayConfig->getTitle(), + 'merchantId' => $this->googlePayConfig->getMerchantId(), + 'merchantName' => $this->googlePayConfig->getMerchantName(), + 'cardBrands' => $this->googlePayConfig->getCardBrands() + ] + ] + ]; + } +} diff --git a/Model/WebhookManagement.php b/Model/WebhookManagement.php index a1edf9cb..04da88c5 100644 --- a/Model/WebhookManagement.php +++ b/Model/WebhookManagement.php @@ -27,13 +27,21 @@ class WebhookManagement implements WebhookManagementInterface */ protected $account; + /** + * @var WebhookReceiverService + */ + protected $webhookReceiverService; + public function __construct( OrderFactory $orderFactory, - Account $account + Account $account, + WebhookReceiverService $webhookReceiverService ) { $this->orderFactory = $orderFactory; $this->account = $account; + $this->webhookReceiverService = $webhookReceiverService; } + /** * @api * @param mixed $id @@ -52,7 +60,10 @@ public function save($id, $type, $data, $account) $postData->type = $type; $postData->data = $data; - if($this->hasMagentoOrder($data) === false) { + if ( + $this->hasMagentoOrder($data) === false + && $this->isNotRecipientWebhook($type) + ) { $this->logWebhookIdCaseExistsMetadata($data, $id); return [ "message" => "Webhook Received", @@ -64,14 +75,13 @@ public function save($id, $type, $data, $account) $this->account->saveAccountIdFromWebhook($account); } - $webhookReceiverService = new WebhookReceiverService(); - return $webhookReceiverService->handle($postData); + return $this->webhookReceiverService->handle($postData); } catch (WebhookHandlerNotFoundException | WebhookAlreadyHandledException $e) { return [ "message" => $e->getMessage(), "code" => 200 ]; - } catch(AbstractPagarmeCoreException $e) { + } catch (AbstractPagarmeCoreException $e) { throw new M2WebApiException( new Phrase($e->getMessage()), 0, @@ -82,41 +92,49 @@ public function save($id, $type, $data, $account) private function logWebhookIdCaseExistsMetadata($webhookData, $webhookId) { $metadata = $this->getMetadata($webhookData); - if($metadata === false || !array_key_exists('platformVersion', $metadata)) { + if ($metadata === false || !array_key_exists('platformVersion', $metadata)) { return; } - if(strpos($metadata['platformVersion'], "Magento") !== false) { + if (strpos($metadata['platformVersion'], "Magento") !== false) { $logService = new LogService( 'Webhook', true ); $logService->info( "Webhook Received but not proccessed", - (object)['webhookId' => $webhookId - ]); + (object)[ + 'webhookId' => $webhookId + ] + ); } } private function getMetadata($data) { $metadata = false; - if(!array_key_exists('order', $data) && !array_key_exists('subscription', $data)) { + if (!array_key_exists('order', $data) && !array_key_exists('subscription', $data)) { return false; } - if(array_key_exists('metadata', $data)) { + if (array_key_exists('metadata', $data)) { $metadata = $data['metadata']; } return $metadata; } + private function hasMagentoOrder($data) { $code = 0; - if(array_key_exists('subscription', $data)) { + if (array_key_exists('subscription', $data)) { $code = $data['subscription']['code']; } - if(array_key_exists('order', $data)) { + if (array_key_exists('order', $data)) { $code = $data['order']['code']; } $order = $this->orderFactory->create()->loadByIncrementId($code); return $order->getId() ?? false; } + + private function isNotRecipientWebhook($type) + { + return strpos($type, 'recipient') === false; + } } diff --git a/Observer/GooglePayDataAssignObserver.php b/Observer/GooglePayDataAssignObserver.php new file mode 100644 index 00000000..dba12780 --- /dev/null +++ b/Observer/GooglePayDataAssignObserver.php @@ -0,0 +1,28 @@ +readMethodArgument($observer); + $info = $method->getInfoInstance(); + $data = $this->readDataArgument($observer); + + $additionalData = $data->getData(PaymentInterface::KEY_ADDITIONAL_DATA); + + if (!is_object($additionalData)) { + $additionalData = new DataObject($additionalData ?: []); + } + + $info->setAdditionalInformation('googlepayData', $additionalData->getData('googlepayData')); + + return $this; + } +} diff --git a/Observer/PaymentMethodAvailable.php b/Observer/PaymentMethodAvailable.php index a4bd73e3..a52be6ea 100644 --- a/Observer/PaymentMethodAvailable.php +++ b/Observer/PaymentMethodAvailable.php @@ -180,6 +180,9 @@ public function getAvailableConfigMethods() if ($this->pagarmeConfig->getPixConfig()->isEnabled()) { $paymentMethods[] = "pagarme_pix"; } + if ($this->pagarmeConfig->getGooglePayConfig()->isEnabled()) { + $paymentMethods[] = "pagarme_googlepay"; + } return $paymentMethods; } diff --git a/Service/Marketplace/RecipientService.php b/Service/Marketplace/RecipientService.php new file mode 100644 index 00000000..3de930b3 --- /dev/null +++ b/Service/Marketplace/RecipientService.php @@ -0,0 +1,41 @@ +coreAuth = new CoreAuth(); + } + + public function createRecipient($recipient) + { + $recipientProxy = new RecipientProxy($this->coreAuth); + return $recipientProxy->create($recipient); + } + + public function searchRecipient($recipientId) + { + $recipientProxy = new RecipientProxy($this->coreAuth); + $recipient = $recipientProxy->getFromPagarme($recipientId); + $kycStatus = $recipient->kyc_details->status ?? ''; + $recipient->status = Recipient::parseStatus($recipient->status, $kycStatus); + return $recipient; + } + + public function createKycLink($recipientId) + { + $recipientProxy = new RecipientProxy($this->coreAuth); + return $recipientProxy->createKycLink($recipientId); + } +} diff --git a/Setup/InstallSchema.php b/Setup/InstallSchema.php index 6812e249..098f2990 100755 --- a/Setup/InstallSchema.php +++ b/Setup/InstallSchema.php @@ -15,9 +15,10 @@ class InstallSchema implements InstallSchemaInterface * {@inheritdoc} */ public function install( - SchemaSetupInterface $setup, + SchemaSetupInterface $setup, ModuleContextInterface $context - ) { + ) + { $installer = $setup; $installer->startSetup(); @@ -40,14 +41,14 @@ public function install( $this->installRecurrenceCharge($setup); $this->installSubProducts($setup); $this->installProductsPlan($setup); - $this->installRecipients($setup); $setup->endSetup(); } public function installConfig( SchemaSetupInterface $installer - ) { + ) + { $tableName = $installer->getTable('pagarme_module_core_configuration'); if (!$installer->getConnection()->isTableExists($tableName)) { $configTable = $installer->getConnection() @@ -92,7 +93,8 @@ public function installConfig( public function installWebhook( SchemaSetupInterface $installer - ) { + ) + { $tableName = $installer->getTable('pagarme_module_core_webhook'); if (!$installer->getConnection()->isTableExists($tableName)) { $webhookTable = $installer->getConnection() @@ -138,7 +140,8 @@ public function installWebhook( public function installOrder( SchemaSetupInterface $installer - ) { + ) + { $tableName = $installer->getTable('pagarme_module_core_order'); if (!$installer->getConnection()->isTableExists($tableName)) { $webhookTable = $installer->getConnection() @@ -193,7 +196,8 @@ public function installOrder( public function installCharge( SchemaSetupInterface $installer - ) { + ) + { $tableName = $installer->getTable('pagarme_module_core_charge'); if (!$installer->getConnection()->isTableExists($tableName)) { $webhookTable = $installer->getConnection() @@ -315,7 +319,8 @@ public function installCharge( public function installTransaction( SchemaSetupInterface $installer - ) { + ) + { $tableName = $installer->getTable('pagarme_module_core_transaction'); if (!$installer->getConnection()->isTableExists($tableName)) { $webhookTable = $installer->getConnection() @@ -549,7 +554,7 @@ public function installCard(SchemaSetupInterface $installer) 'brand', Table::TYPE_TEXT, 255, - ['nullable' => false, 'default' => ''], + ['nullable' => false, 'default' => ''], 'Card Brand' ) ->setComment('Pagar.me Card Tokens') @@ -857,9 +862,9 @@ public function installHubToken(SchemaSetupInterface $installer) return $installer; } - public function installProductsPlan(SchemaSetupInterface $installer) + public function installProductsSubscription(SchemaSetupInterface $installer) { - $tableName = $installer->getTable('pagarme_module_core_recurrence_products_plan'); + $tableName = $installer->getTable('pagarme_module_core_recurrence_products_subscription'); if (!$installer->getConnection()->isTableExists($tableName)) { $customer = $installer->getConnection() ->newTable($tableName) @@ -875,51 +880,6 @@ public function installProductsPlan(SchemaSetupInterface $installer) ], 'ID' ) - ->addColumn( - 'interval_type', - Table::TYPE_TEXT, - 15, - [ - 'nullable' => false - ], - 'Day, week, month ou year' - ) - ->addColumn( - 'interval_count', - Table::TYPE_SMALLINT, - 2, - [ - 'nullable' => false - ], - '1 - 12' - ) - ->addColumn( - 'name', - Table::TYPE_TEXT, - 255, - [ - 'nullable' => true - ], - "Product name" - ) - ->addColumn( - 'description', - Table::TYPE_TEXT, - 500, - [ - 'nullable' => true - ], - "Product description" - ) - ->addColumn( - 'plan_id', - Table::TYPE_TEXT, - 21, - [ - 'nullable' => true - ], - "Api's id" - ) ->addColumn( 'product_id', Table::TYPE_INTEGER, @@ -939,7 +899,7 @@ public function installProductsPlan(SchemaSetupInterface $installer) "Accepts credit card" ) ->addColumn( - 'installments', + 'allow_installments', Table::TYPE_TEXT, 1, [ @@ -957,46 +917,38 @@ public function installProductsPlan(SchemaSetupInterface $installer) "Accepts boleto" ) ->addColumn( - 'billing_type', + 'sell_as_normal_product', Table::TYPE_TEXT, - 11, + 1, [ 'nullable' => false ], - "Prepaid, postpaid ou exact_day" + "Allow sell as normal product" ) ->addColumn( - 'status', + 'billing_type', Table::TYPE_TEXT, 11, [ 'nullable' => false ], - "Active, inactive ou deleted" - ) - ->addColumn( - 'trial_period_days', - Table::TYPE_TEXT, - 11, - [ - 'nullable' => true - ], - "Trial period in days" + "Prepaid, postpaid ou exact_day" ) ->addColumn( 'created_at', - \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, + Table::TYPE_TIMESTAMP, null, - ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT], + ['nullable' => false, 'default' => Table::TIMESTAMP_INIT], 'Created At' ) ->addColumn( 'updated_at', - \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, + Table::TYPE_TIMESTAMP, null, - ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE], + ['nullable' => false, 'default' => Table::TIMESTAMP_INIT_UPDATE], 'Updated At' ) + ->setComment('Product Plan Table') ->setOption('charset', 'utf8'); $installer->getConnection()->createTable($customer); @@ -1004,11 +956,14 @@ public function installProductsPlan(SchemaSetupInterface $installer) return $installer; } - public function installSubProducts(SchemaSetupInterface $installer) + public function installSubscriptionItems(SchemaSetupInterface $installer) { - $tableName = $installer->getTable('pagarme_module_core_recurrence_sub_products'); + $tableName = $installer->getTable( + 'pagarme_module_core_recurrence_subscription_items' + ); + if (!$installer->getConnection()->isTableExists($tableName)) { - $customer = $installer->getConnection() + $configTable = $installer->getConnection() ->newTable($tableName) ->addColumn( 'id', @@ -1023,177 +978,61 @@ public function installSubProducts(SchemaSetupInterface $installer) 'ID' ) ->addColumn( - 'product_id', - Table::TYPE_INTEGER, - 255, - [ - 'nullable' => false - ], - "Magento's product id" - ) - ->addColumn( - 'product_recurrence_id', - Table::TYPE_INTEGER, - 255, + 'pagarme_id', + Table::TYPE_TEXT, + null, [ 'nullable' => false ], - 'Id from table pagarme_module_core_products_(plan/subscription)' + 'format: si_xxxxxxxxxxxxxxxx' ) + ->setOption('charset', 'utf8') ->addColumn( - 'recurrence_type', + 'subscription_id', Table::TYPE_TEXT, - 255, + null, [ 'nullable' => false ], - 'Type of recurrence product (plan or subscription)' + 'format: sub_xxxxxxxxxxxxxxxx' ) + ->setOption('charset', 'utf8') ->addColumn( - 'cycles', - Table::TYPE_INTEGER, - 5, + 'code', + Table::TYPE_TEXT, + 100, [ - 'nullable' => true + 'nullable' => false, ], - 'Cycle' + 'Product code on platform' ) ->addColumn( 'quantity', Table::TYPE_INTEGER, - 255, - [ - 'nullable' => true - ], - "Quantity" - ) - ->addColumn( - 'trial_period_days', - Table::TYPE_INTEGER, - 255, - [ - 'nullable' => true - ], - "Trial period" - ) - ->addColumn( - 'created_at', - \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, - null, - ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT], - 'Created At' - ) - ->addColumn( - 'updated_at', - \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, - null, - ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE], - 'Updated At' - ) - ->addColumn( - 'pagarme_id', - Table::TYPE_TEXT, - 21, - ['nullable' => true], - 'Pagarme Id' - ) - ->setOption('charset', 'utf8'); - - $installer->getConnection()->createTable($customer); - } - return $installer; - } - - public function installProductsSubscription(SchemaSetupInterface $installer) - { - $tableName = $installer->getTable('pagarme_module_core_recurrence_products_subscription'); - if (!$installer->getConnection()->isTableExists($tableName)) { - $customer = $installer->getConnection() - ->newTable($tableName) - ->addColumn( - 'id', - Table::TYPE_INTEGER, null, [ - 'identity' => true, 'unsigned' => true, 'nullable' => false, - 'primary' => true - ], - 'ID' - ) - ->addColumn( - 'product_id', - Table::TYPE_INTEGER, - 11, - [ - 'nullable' => true - ], - "Product in Magento's table" - ) - ->addColumn( - 'credit_card', - Table::TYPE_TEXT, - 1, - [ - 'nullable' => false - ], - "Accepts credit card" - ) - ->addColumn( - 'allow_installments', - Table::TYPE_TEXT, - 1, - [ - 'nullable' => false - ], - "Accepts installments" - ) - ->addColumn( - 'boleto', - Table::TYPE_TEXT, - 1, - [ - 'nullable' => false - ], - "Accepts boleto" - ) - ->addColumn( - 'sell_as_normal_product', - Table::TYPE_TEXT, - 1, - [ - 'nullable' => false - ], - "Allow sell as normal product" - ) - ->addColumn( - 'billing_type', - Table::TYPE_TEXT, - 11, - [ - 'nullable' => false ], - "Prepaid, postpaid ou exact_day" + 'Quantity' ) ->addColumn( 'created_at', - \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, + Table::TYPE_TIMESTAMP, null, - ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT], + ['nullable' => false, 'default' => Table::TIMESTAMP_INIT], 'Created At' ) ->addColumn( 'updated_at', - \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, + Table::TYPE_TIMESTAMP, null, - ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE], + ['nullable' => false, 'default' => Table::TIMESTAMP_INIT_UPDATE], 'Updated At' ) - ->setComment('Product Plan Table') ->setOption('charset', 'utf8'); - $installer->getConnection()->createTable($customer); + $installer->getConnection()->createTable($configTable); } return $installer; } @@ -1264,16 +1103,16 @@ public function installSubscriptionRepetitions(SchemaSetupInterface $installer) ) ->addColumn( 'created_at', - \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, + Table::TYPE_TIMESTAMP, null, - ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT], + ['nullable' => false, 'default' => Table::TIMESTAMP_INIT], 'Created At' ) ->addColumn( 'updated_at', - \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, + Table::TYPE_TIMESTAMP, null, - ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE], + ['nullable' => false, 'default' => Table::TIMESTAMP_INIT_UPDATE], 'Updated At' ) ->setOption('charset', 'utf8'); @@ -1405,16 +1244,16 @@ public function installRecurrenceSubscription(SchemaSetupInterface $installer) ) ->addColumn( 'created_at', - \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, + Table::TYPE_TIMESTAMP, null, - ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT], + ['nullable' => false, 'default' => Table::TIMESTAMP_INIT], 'Created At' ) ->addColumn( 'updated_at', - \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, + Table::TYPE_TIMESTAMP, null, - ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE], + ['nullable' => false, 'default' => Table::TIMESTAMP_INIT_UPDATE], 'Updated At' ) ->setOption('charset', 'utf8'); @@ -1570,30 +1409,30 @@ public function installRecurrenceCharge(SchemaSetupInterface $installer) ->setOption('charset', 'utf8') ->addColumn( 'cycle_start', - \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, + Table::TYPE_TIMESTAMP, null, ['nullable' => false], 'Cycle Start' ) ->addColumn( 'cycle_end', - \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, + Table::TYPE_TIMESTAMP, null, ['nullable' => false], 'Cycle End' ) ->addColumn( 'created_at', - \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, + Table::TYPE_TIMESTAMP, null, - ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT], + ['nullable' => false, 'default' => Table::TIMESTAMP_INIT], 'Created At' ) ->addColumn( 'updated_at', - \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, + Table::TYPE_TIMESTAMP, null, - ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE], + ['nullable' => false, 'default' => Table::TIMESTAMP_INIT_UPDATE], 'Updated At' ) ->setOption('charset', 'utf8'); @@ -1603,14 +1442,11 @@ public function installRecurrenceCharge(SchemaSetupInterface $installer) return $installer; } - public function installSubscriptionItems(SchemaSetupInterface $installer) + public function installSubProducts(SchemaSetupInterface $installer) { - $tableName = $installer->getTable( - 'pagarme_module_core_recurrence_subscription_items' - ); - + $tableName = $installer->getTable('pagarme_module_core_recurrence_sub_products'); if (!$installer->getConnection()->isTableExists($tableName)) { - $configTable = $installer->getConnection() + $customer = $installer->getConnection() ->newTable($tableName) ->addColumn( 'id', @@ -1625,68 +1461,90 @@ public function installSubscriptionItems(SchemaSetupInterface $installer) 'ID' ) ->addColumn( - 'pagarme_id', - Table::TYPE_TEXT, - null, + 'product_id', + Table::TYPE_INTEGER, + 255, [ 'nullable' => false ], - 'format: si_xxxxxxxxxxxxxxxx' + "Magento's product id" ) - ->setOption('charset', 'utf8') ->addColumn( - 'subscription_id', - Table::TYPE_TEXT, - null, + 'product_recurrence_id', + Table::TYPE_INTEGER, + 255, [ 'nullable' => false ], - 'format: sub_xxxxxxxxxxxxxxxx' + 'Id from table pagarme_module_core_products_(plan/subscription)' ) - ->setOption('charset', 'utf8') ->addColumn( - 'code', + 'recurrence_type', Table::TYPE_TEXT, - 100, + 255, [ - 'nullable' => false, + 'nullable' => false ], - 'Product code on platform' + 'Type of recurrence product (plan or subscription)' + ) + ->addColumn( + 'cycles', + Table::TYPE_INTEGER, + 5, + [ + 'nullable' => true + ], + 'Cycle' ) ->addColumn( 'quantity', Table::TYPE_INTEGER, - null, + 255, [ - 'unsigned' => true, - 'nullable' => false, + 'nullable' => true ], - 'Quantity' + "Quantity" + ) + ->addColumn( + 'trial_period_days', + Table::TYPE_INTEGER, + 255, + [ + 'nullable' => true + ], + "Trial period" ) ->addColumn( 'created_at', - \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, + Table::TYPE_TIMESTAMP, null, - ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT], + ['nullable' => false, 'default' => Table::TIMESTAMP_INIT], 'Created At' ) ->addColumn( 'updated_at', - \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, + Table::TYPE_TIMESTAMP, null, - ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE], + ['nullable' => false, 'default' => Table::TIMESTAMP_INIT_UPDATE], 'Updated At' ) + ->addColumn( + 'pagarme_id', + Table::TYPE_TEXT, + 21, + ['nullable' => true], + 'Pagarme Id' + ) ->setOption('charset', 'utf8'); - $installer->getConnection()->createTable($configTable); + $installer->getConnection()->createTable($customer); } return $installer; } - public function installRecipients(SchemaSetupInterface $installer) + public function installProductsPlan(SchemaSetupInterface $installer) { - $tableName = $installer->getTable('pagarme_module_core_recipients'); + $tableName = $installer->getTable('pagarme_module_core_recurrence_products_plan'); if (!$installer->getConnection()->isTableExists($tableName)) { $customer = $installer->getConnection() ->newTable($tableName) @@ -1703,71 +1561,125 @@ public function installRecipients(SchemaSetupInterface $installer) 'ID' ) ->addColumn( - 'external_id', + 'interval_type', Table::TYPE_TEXT, - null, + 15, [ 'nullable' => false ], - 'External ID' + 'Day, week, month ou year' + ) + ->addColumn( + 'interval_count', + Table::TYPE_SMALLINT, + 2, + [ + 'nullable' => false + ], + '1 - 12' ) ->addColumn( 'name', Table::TYPE_TEXT, 255, + [ + 'nullable' => true + ], + "Product name" + ) + ->addColumn( + 'description', + Table::TYPE_TEXT, + 500, + [ + 'nullable' => true + ], + "Product description" + ) + ->addColumn( + 'plan_id', + Table::TYPE_TEXT, + 21, + [ + 'nullable' => true + ], + "Api's id" + ) + ->addColumn( + 'product_id', + Table::TYPE_INTEGER, + 11, + [ + 'nullable' => true + ], + "Product in Magento's table" + ) + ->addColumn( + 'credit_card', + Table::TYPE_TEXT, + 1, [ 'nullable' => false ], - 'Name' + "Accepts credit card" ) ->addColumn( - 'email', + 'installments', Table::TYPE_TEXT, - 255, + 1, [ 'nullable' => false ], - 'Email' + "Accepts installments" ) ->addColumn( - 'document_type', + 'boleto', Table::TYPE_TEXT, - 255, + 1, [ 'nullable' => false ], - 'Document Type' + "Accepts boleto" ) ->addColumn( - 'document', + 'billing_type', Table::TYPE_TEXT, - 255, + 11, [ 'nullable' => false ], - 'Document' + "Prepaid, postpaid ou exact_day" ) ->addColumn( - 'pagarme_id', + 'status', Table::TYPE_TEXT, - null, + 11, [ 'nullable' => false ], - 'format: rp_xxxxxxxxxxxxxxxx' + "Active, inactive ou deleted" + ) + ->addColumn( + 'trial_period_days', + Table::TYPE_TEXT, + 11, + [ + 'nullable' => true + ], + "Trial period in days" ) ->addColumn( 'created_at', - \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, + Table::TYPE_TIMESTAMP, null, - ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT], + ['nullable' => false, 'default' => Table::TIMESTAMP_INIT], 'Created At' ) ->addColumn( 'updated_at', - \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP, + Table::TYPE_TIMESTAMP, null, - ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE], + ['nullable' => false, 'default' => Table::TIMESTAMP_INIT_UPDATE], 'Updated At' ) ->setOption('charset', 'utf8'); diff --git a/Setup/UpgradeSchema.php b/Setup/UpgradeSchema.php index 53e51d0a..05d4b6da 100644 --- a/Setup/UpgradeSchema.php +++ b/Setup/UpgradeSchema.php @@ -3,9 +3,9 @@ namespace Pagarme\Pagarme\Setup; use Magento\Framework\DB\Ddl\Table; -use Magento\Framework\Setup\UpgradeSchemaInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\SchemaSetupInterface; +use Magento\Framework\Setup\UpgradeSchemaInterface; class UpgradeSchema implements UpgradeSchemaInterface { @@ -14,9 +14,10 @@ class UpgradeSchema implements UpgradeSchemaInterface * {@inheritdoc} */ public function upgrade( - SchemaSetupInterface $setup, + SchemaSetupInterface $setup, ModuleContextInterface $context - ) { + ) + { $setup->startSetup(); $version = $context->getVersion(); $installSchema = new InstallSchema(); @@ -25,33 +26,55 @@ public function upgrade( $setup = $installSchema->installHubToken($setup); } - if (version_compare($version, "1.2.0", "<")) { - $setup = $installSchema->installRecipients($setup); - } - if (version_compare($version, '2.2.5', '<')) { $connection = $setup->getConnection(); - $connection->addColumn( - $setup->getTable('pagarme_module_core_recurrence_products_plan'), - 'apply_discount_in_all_product_cycles', - [ - 'type' => Table::TYPE_SMALLINT, - 'length' => 1, - 'nullable' => true, - 'comment' => 'Apply products cycle to discount' - ] - ); - - $connection->addColumn( - $setup->getTable('pagarme_module_core_recurrence_products_subscription'), - 'apply_discount_in_all_product_cycles', - [ - 'type' => Table::TYPE_SMALLINT, - 'length' => 1, - 'nullable' => true, - 'comment' => 'Apply products cycle to discount' - ] - ); + if ($connection->tableColumnExists( + 'pagarme_module_core_recurrence_products_plan', + 'apply_discount_in_all_product_cycles' + ) === false) { + $connection->addColumn( + $setup->getTable('pagarme_module_core_recurrence_products_plan'), + 'apply_discount_in_all_product_cycles', + [ + 'type' => Table::TYPE_SMALLINT, + 'length' => 1, + 'nullable' => true, + 'comment' => 'Apply products cycle to discount' + ] + ); + } + + if ($connection->tableColumnExists( + 'pagarme_module_core_recurrence_products_subscription', + 'apply_discount_in_all_product_cycles' + ) === false) { + $connection->addColumn( + $setup->getTable('pagarme_module_core_recurrence_products_subscription'), + 'apply_discount_in_all_product_cycles', + [ + 'type' => Table::TYPE_SMALLINT, + 'length' => 1, + 'nullable' => true, + 'comment' => 'Apply products cycle to discount' + ] + ); + } + } + + if (version_compare($context->getVersion(), '2.5.0', '<')) { + if ($setup->getConnection()->tableColumnExists('pagarme_module_core_recipients', 'type') === false) { + $setup->getConnection()->changeColumn( + $setup->getTable('pagarme_module_core_recipients'), + 'document_type', + 'type', + [ + 'type' => Table::TYPE_TEXT, + 'length' => 11, + 'nullable' => 'false', + 'comment' => 'Recipient document type: individual (CPF) or corporation (CNPJ)' + ] + ); + } } $setup->endSetup(); diff --git a/Test/Unit/Block/Adminhtml/Marketplace/RecipientTest.php b/Test/Unit/Block/Adminhtml/Marketplace/RecipientTest.php new file mode 100644 index 00000000..c0817986 --- /dev/null +++ b/Test/Unit/Block/Adminhtml/Marketplace/RecipientTest.php @@ -0,0 +1,115 @@ +recipient = $recipient; + $recipientData->externalId = 'easd'; + $recipientData->localId = '234'; + $recipientData->status = $status; + $recipientData->statusUpdated = true; + + $registryMock = Mockery::mock(Registry::class); + $registryMock->shouldReceive('registry') + ->with('recipient_data') + ->andReturn(json_encode($recipientData)); + $registryMock->shouldReceive('registry') + ->with('sellers') + ->andReturnNull(); + + $collectionMock = Mockery::mock(Collection::class); + + $collectionFactoryMock = Mockery::mock(CollectionFactory::class); + $collectionFactoryMock->shouldReceive('create') + ->andReturn($collectionMock); + + $countryMock = Mockery::mock(Country::class); + + $moduleCoreSetupMock = Mockery::mock('alias:Pagarme\Core\Kernel\Abstractions\AbstractModuleCoreSetup'); + $moduleCoreSetupMock->shouldReceive('bootstrap') + ->andReturnSelf(); + + $recipientRepositoryMock = Mockery::mock(RecipientRepository::class); + + $recipientBlock = new Recipient( + $contextMock, + $registryMock, + $collectionFactoryMock, + $countryMock, + $recipientRepositoryMock + ); + + $editedRecipient = $recipientBlock->getEditRecipient(); + + $this->assertStringContainsString("\"statusLabel\":\"$expectedStatusLabel\"", $editedRecipient); + } + + + public function testGetEditRecipientShouldReturnEmpty() + { + $contextSpy = Mockery::spy(Context::class); + $registrySpy = Mockery::spy(Registry::class); + $collectionMock = Mockery::mock(Collection::class); + + $collectionFactoryMock = Mockery::mock(CollectionFactory::class); + $collectionFactoryMock->shouldReceive('create') + ->andReturn($collectionMock); + + $countryMock = Mockery::mock(Country::class); + + $moduleCoreSetupMock = Mockery::mock('alias:Pagarme\Core\Kernel\Abstractions\AbstractModuleCoreSetup'); + $moduleCoreSetupMock->shouldReceive('bootstrap') + ->andReturnSelf(); + + $recipientRepositoryMock = Mockery::mock(RecipientRepository::class); + + + $recipientBlock = new Recipient( + $contextSpy, + $registrySpy, + $collectionFactoryMock, + $countryMock, + $recipientRepositoryMock + ); + + $this->assertEmpty($recipientBlock->getEditRecipient()); + } + + public function statusDataProvider() + { + return [ + "Registered status" => [RecipientInterface::REGISTERED, "Registered"], + "Validation Request status" => [RecipientInterface::VALIDATION_REQUESTED, "Validation Requested"], + "Waiting for analysis status" => [RecipientInterface::WAITING_FOR_ANALYSIS, "Waiting For Analysis"], + "Active status" => [RecipientInterface::ACTIVE, "Approved"], + "Disapproved status" => [RecipientInterface::DISAPPROVED, "Disapproved"], + "Suspended status" => [RecipientInterface::SUSPENDED, "Suspended"], + "Blocked status" => [RecipientInterface::BLOCKED, "Blocked"], + "Inactive status" => [RecipientInterface::INACTIVE, "Inactive"], + ]; + } +} diff --git a/Test/Unit/Controller/Adminhtml/Recipients/CreateTest.php b/Test/Unit/Controller/Adminhtml/Recipients/CreateTest.php new file mode 100644 index 00000000..f45e5e95 --- /dev/null +++ b/Test/Unit/Controller/Adminhtml/Recipients/CreateTest.php @@ -0,0 +1,194 @@ +shouldReceive('getItems') + ->andReturn([]); + + $sellerFactoryMock = Mockery::mock('Webkul\Marketplace\Model\SellerFactory'); + $sellerFactoryMock->shouldReceive('create') + ->andReturnSelf(); + $sellerFactoryMock->shouldReceive('getCollection') + ->andReturnSelf(); + $sellerFactoryMock->shouldReceive('load') + ->andReturn($sellerCollectionMock); + + $requestMock = Mockery::mock(RequestInterface::class); + $requestMock->shouldReceive('getParam') + ->andReturn(1); + + $objectManagerMock = Mockery::mock(ObjectManagerInterface::class); + $objectManagerMock->shouldReceive('create') + ->andReturn($sellerFactoryMock); + + $contextSpy->shouldReceive('getObjectManager') + ->andReturn($objectManagerMock); + $contextSpy->shouldReceive('getRequest') + ->andReturn($requestMock); + + $registryMock = Mockery::mock(Registry::class); + $registryMock->shouldReceive('register') + ->withArgs(function ($key, $data) { + return $key === 'sellers' || ($key === 'recipient_data' && strpos($data, '"statusUpdated":true') !== false); + }) + ->andReturnSelf(); + + $pageMock = Mockery::mock(Page::class); + $pageMock->shouldReceive('getConfig') + ->andReturnSelf(); + $pageMock->shouldReceive('getTitle') + ->andReturnSelf(); + $pageMock->shouldReceive('prepend') + ->andReturnSelf(); + + $pageFactoryMock = Mockery::mock(PageFactory::class); + $pageFactoryMock->shouldReceive('create') + ->andReturn($pageMock); + + $magentoMessageFactoryMock = Mockery::mock(MagentoMessageFactory::class); + + $moduleManagerMock = Mockery::mock(ModuleManager::class); + $moduleManagerMock->shouldReceive('isEnabled') + ->andReturnTrue(); + + $resourceModelRecipientSpy = Mockery::spy(ResourceModelRecipient::class); + + $recipientSpy = Mockery::spy(Recipient::class); + $recipientSpy->shouldReceive('getStatus') + ->andReturnNull(); + + $recipientResponse = new GetRecipientResponse(); + $recipientResponse->id = 'rp_xxxxxxxxxxx'; + $recipientResponse->status = 'active'; + $recipientServiceMock = Mockery::mock(RecipientService::class); + $recipientServiceMock->shouldReceive('searchRecipient') + ->andReturn($recipientResponse); + + $moduleCoreSetupMock = Mockery::mock('alias:Pagarme\Core\Kernel\Abstractions\AbstractModuleCoreSetup'); + $moduleCoreSetupMock->shouldReceive('bootstrap') + ->andReturnSelf(); + + $createController = new Create( + $contextSpy, + $registryMock, + $pageFactoryMock, + $magentoMessageFactoryMock, + $moduleManagerMock, + $resourceModelRecipientSpy, + $recipientSpy, + $recipientServiceMock + ); + + + $this->assertInstanceOf(Page::class, $createController->execute()); + } + + public function testExecuteShouldNotUpdateRecipientStatus() + { + $contextSpy = Mockery::spy(Context::class); + + $sellerCollectionMock = Mockery::mock('Webkul\Marketplace\Model\ResourceModel\Seller\Collection'); + $sellerCollectionMock->shouldReceive('getItems') + ->andReturn([]); + + $sellerFactoryMock = Mockery::mock('Webkul\Marketplace\Model\SellerFactory'); + $sellerFactoryMock->shouldReceive('create') + ->andReturnSelf(); + $sellerFactoryMock->shouldReceive('getCollection') + ->andReturnSelf(); + $sellerFactoryMock->shouldReceive('load') + ->andReturn($sellerCollectionMock); + + $requestMock = Mockery::mock(RequestInterface::class); + $requestMock->shouldReceive('getParam') + ->andReturn(1); + + $objectManagerMock = Mockery::mock(ObjectManagerInterface::class); + $objectManagerMock->shouldReceive('create') + ->andReturn($sellerFactoryMock); + + $contextSpy->shouldReceive('getObjectManager') + ->andReturn($objectManagerMock); + $contextSpy->shouldReceive('getRequest') + ->andReturn($requestMock); + + $registryMock = Mockery::mock(Registry::class); + $registryMock->shouldReceive('register') + ->withArgs(function ($key, $data) { + return $key === 'sellers' || ($key === 'recipient_data' && strpos($data, '"statusUpdated":false') !== false); + }) + ->andReturnSelf(); + + $pageMock = Mockery::mock(Page::class); + $pageMock->shouldReceive('getConfig') + ->andReturnSelf(); + $pageMock->shouldReceive('getTitle') + ->andReturnSelf(); + $pageMock->shouldReceive('prepend') + ->andReturnSelf(); + + $pageFactoryMock = Mockery::mock(PageFactory::class); + $pageFactoryMock->shouldReceive('create') + ->andReturn($pageMock); + + $magentoMessageFactoryMock = Mockery::mock(MagentoMessageFactory::class); + + $moduleManagerMock = Mockery::mock(ModuleManager::class); + $moduleManagerMock->shouldReceive('isEnabled') + ->andReturnTrue(); + + $resourceModelRecipientSpy = Mockery::spy(ResourceModelRecipient::class); + + $recipientSpy = Mockery::spy(Recipient::class); + $recipientSpy->shouldReceive('getStatus') + ->andReturn('active'); + + $recipientResponse = new GetRecipientResponse(); + $recipientResponse->id = 'rp_xxxxxxxxxxx'; + $recipientResponse->status = 'active'; + $recipientServiceMock = Mockery::mock(RecipientService::class); + $recipientServiceMock->shouldReceive('searchRecipient') + ->andReturn($recipientResponse); + + $moduleCoreSetupMock = Mockery::mock('alias:Pagarme\Core\Kernel\Abstractions\AbstractModuleCoreSetup'); + $moduleCoreSetupMock->shouldReceive('bootstrap') + ->andReturnSelf(); + + $createController = new Create( + $contextSpy, + $registryMock, + $pageFactoryMock, + $magentoMessageFactoryMock, + $moduleManagerMock, + $resourceModelRecipientSpy, + $recipientSpy, + $recipientServiceMock + ); + + + $this->assertInstanceOf(Page::class, $createController->execute()); + } +} diff --git a/Test/Unit/Model/Api/RecipientTest.php b/Test/Unit/Model/Api/RecipientTest.php new file mode 100644 index 00000000..e180ce35 --- /dev/null +++ b/Test/Unit/Model/Api/RecipientTest.php @@ -0,0 +1,143 @@ +shouldReceive('getPagarmeId') + ->andReturn('rp_xxxxxxxxxxxxxxxx'); + + $recipientFactoryMock = Mockery::mock(RecipientFactory::class); + $recipientFactoryMock->shouldReceive('create') + ->andReturn($recipientModelMock); + + $resourceModelRecipientMock = Mockery::mock(ResourceModelRecipient::class); + $resourceModelRecipientMock->shouldReceive('load') + ->andReturnSelf(); + + $coreRecipientMock = Mockery::mock(CoreRecipient::class); + + $base64QrCode = "UGFyYWLDqW5zIHBlbGEgc3VhIGN1cmlvc2lkYWRl"; + $kycUrl = 'http://test.test/'; + $createKyLinkResponseMock = new CreateKycLinkResponse($kycUrl, $base64QrCode, '2024-04-29T09:22:08Z'); + $recipientServiceMock = Mockery::mock(RecipientService::class); + $recipientServiceMock->shouldReceive('createKycLink') + ->andReturn($createKyLinkResponseMock); + + $kycLinkResponse = new KycLinkResponse(); + $kycLinkResponseFactoryMock = Mockery::mock(KycLinkResponseInterfaceFactory::class); + $kycLinkResponseFactoryMock->shouldReceive('create') + ->andReturn($kycLinkResponse); + + $recipientModelApi = new Recipient( + $requestMock, + $recipientFactoryMock, + $resourceModelRecipientMock, + $coreRecipientMock, + $recipientServiceMock, + $kycLinkResponseFactoryMock + ); + + $result = $recipientModelApi->createKycLink(1); + + $expectedBase64QrCode = "data:image/svg+xml;base64,$base64QrCode"; + $this->assertSame($kycUrl, $result->getUrl()); + $this->assertSame($expectedBase64QrCode, $result->getQrCode()); + } + + public function testCreateKycLinkShouldNotFoundRecipient() + { + $requestMock = Mockery::mock(Request::class); + + $recipientModelMock = Mockery::mock(RecipientModel::class); + $recipientModelMock->shouldReceive('getPagarmeId') + ->andReturnNull(); + + $recipientFactoryMock = Mockery::mock(RecipientFactory::class); + $recipientFactoryMock->shouldReceive('create') + ->andReturn($recipientModelMock); + + $resourceModelRecipientMock = Mockery::mock(ResourceModelRecipient::class); + $resourceModelRecipientMock->shouldReceive('load') + ->andReturnSelf(); + + $coreRecipientMock = Mockery::mock(CoreRecipient::class); + + $recipientServiceMock = Mockery::mock(RecipientService::class); + + $kycLinkResponseFactoryMock = Mockery::mock(KycLinkResponseInterfaceFactory::class); + + $recipientModelApi = new Recipient( + $requestMock, + $recipientFactoryMock, + $resourceModelRecipientMock, + $coreRecipientMock, + $recipientServiceMock, + $kycLinkResponseFactoryMock + ); + + $this->expectException(NoSuchEntityException::class); + $this->expectExceptionMessage('Recipient not founded.'); + + $recipientModelApi->createKycLink(1); + } + + public function testCreateKycLinkShouldNotGenerateSecurityValidation() + { + $requestMock = Mockery::mock(Request::class); + + $recipientModelMock = Mockery::mock(RecipientModel::class); + $recipientModelMock->shouldReceive('getPagarmeId') + ->andReturn('rp_xxxxxxxxxxxxxxxx'); + + $recipientFactoryMock = Mockery::mock(RecipientFactory::class); + $recipientFactoryMock->shouldReceive('create') + ->andReturn($recipientModelMock); + + $resourceModelRecipientMock = Mockery::mock(ResourceModelRecipient::class); + $resourceModelRecipientMock->shouldReceive('load') + ->andReturnSelf(); + + $coreRecipientMock = Mockery::mock(CoreRecipient::class); + + $createKyLinkResponseMock = new CreateKycLinkResponse(); + $recipientServiceMock = Mockery::mock(RecipientService::class); + $recipientServiceMock->shouldReceive('createKycLink') + ->andReturn($createKyLinkResponseMock); + + $kycLinkResponseFactoryMock = Mockery::mock(KycLinkResponseInterfaceFactory::class); + + $recipientModelApi = new Recipient( + $requestMock, + $recipientFactoryMock, + $resourceModelRecipientMock, + $coreRecipientMock, + $recipientServiceMock, + $kycLinkResponseFactoryMock + ); + + $this->expectException(NoSuchEntityException::class); + $this->expectExceptionMessage('Failed to generate the security validation link.'); + + $recipientModelApi->createKycLink(1); + } +} diff --git a/Test/Unit/Model/WebhookManagementTest.php b/Test/Unit/Model/WebhookManagementTest.php new file mode 100644 index 00000000..a467806a --- /dev/null +++ b/Test/Unit/Model/WebhookManagementTest.php @@ -0,0 +1,110 @@ +shouldReceive('bootstrap') + ->andReturnSelf(); + + + $orderMock = Mockery::mock(Order::class); + $orderMock->shouldReceive('loadByIncrementId') + ->andReturnSelf(); + $orderMock->shouldReceive('getId') + ->andReturnFalse(); + + $orderFactoryMock = Mockery::mock(OrderFactory::class); + $orderFactoryMock->shouldReceive('create') + ->andReturn($orderMock); + $accountMock = Mockery::mock(Account::class); + + $webhookReceiverServiceMock = Mockery::mock(WebhookReceiverService::class); + $webhookRecipientResponse = [ + 'message' => 'Recipient updated', + 'code' => 200 + ]; + $webhookReceiverServiceMock->shouldReceive('handle') + ->once() + ->andReturn($webhookRecipientResponse); + + $webhookManagement = new WebhookManagement($orderFactoryMock, $accountMock, $webhookReceiverServiceMock); + + $id = "hook_aaaaaaaaaaaaaaaa"; + $type = "recipient.updated"; + $data = [ + "id" => 'rp_xxxxxxxxxxxxxxxx', + "name" => "Test recipient", + "email" => "test@recipient.test", + "document" => "11111111111", + "description" => "Test description", + "type" => "individual", + "payment_mode" => "bank_transfer", + "status" => "active", + "kyc_details" => + [ + "status" => "approved" + ], + ]; + + $account = [ + "id" => "acc_xxxxxxxxxxxxxxxx", + "name" => "Account Test" + ]; + $result = $webhookManagement->save($id, $type, $data, $account); + + $this->assertSame($webhookRecipientResponse, $result); + } + + + public function testSaveWithNonPlatformWebhook() + { + $moduleCoreSetupMock = Mockery::mock('alias:Pagarme\Core\Kernel\Abstractions\AbstractModuleCoreSetup'); + $moduleCoreSetupMock->shouldReceive('bootstrap') + ->andReturnSelf(); + + + $orderMock = Mockery::mock(Order::class); + $orderMock->shouldReceive('loadByIncrementId') + ->andReturnSelf(); + $orderMock->shouldReceive('getId') + ->andReturnFalse(); + + $orderFactoryMock = Mockery::mock(OrderFactory::class); + $orderFactoryMock->shouldReceive('create') + ->andReturn($orderMock); + + $accountMock = Mockery::mock(Account::class); + + $webhookReceiverServiceMock = Mockery::mock(WebhookReceiverService::class); + $expectedResponse = [ + 'message' => 'Webhook Received', + 'code' => 200 + ]; + + $webhookManagement = new WebhookManagement($orderFactoryMock, $accountMock, $webhookReceiverServiceMock); + + $id = "hook_aaaaaaaaaaaaaaaa"; + $type = "charge.paid"; + $data = []; + + $account = [ + "id" => "acc_xxxxxxxxxxxxxxxx", + "name" => "Account Test" + ]; + $result = $webhookManagement->save($id, $type, $data, $account); + + $this->assertSame($expectedResponse, $result); + } +} diff --git a/Ui/Component/Column/RecipientActions.php b/Ui/Component/Column/RecipientActions.php new file mode 100644 index 00000000..88ba2687 --- /dev/null +++ b/Ui/Component/Column/RecipientActions.php @@ -0,0 +1,14 @@ +=7.1", - "pagarme/ecommerce-module-core": "~2.4.1" + "pagarme/ecommerce-module-core": "~2.5.0" }, "require-dev": { "phpunit/phpunit": "^5 | ^6 | ^7 | ^8 | ^9", diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 2e30883f..7ffd2989 100644 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -17,6 +17,7 @@Warning! Don't forget to add your store's domain on Pagar.me dashboard
", "Aviso! Não se esqueça de adicionar o domínio da sua loja no painel do Pagar.me
" "View Integration", "Ver Integração" "Integrate With Pagar.me", "Integrar com Pagar.me" +"Access Pagar.me Dash","Acessar a Dash Pagar.me" "Important!","Importante!" "This store is linked to the Pagar.me test environment. This environment is intended for integration validation and does not generate real financial transactions.","Esta loja está vinculada ao ambiente de testes da Pagar.me. Este ambiente é destinado a validação de integração e não gera operações financeiras reais." "Show VAT Number on Storefront must be defined as "Yes" on Stores > Configuration > Customers > %sCustomer Configuration%s > Create New Account Options for Pagar.me module to work on your store.","Mostrar Número VAT na Vitrine deve ser definido como "Sim" em Lojas > Configuração > Clientes > %sConfigurações de cliente%s > Criar Novas Opções de Conta para que o módulo da Pagar.me funcione na sua loja." @@ -422,8 +423,33 @@ "Responsibility for chargebacks","Responsabilidade pelos chargebacks" "Responsibility for receiving split remainder","Responsabilidade pelo recebimento do restante da divisão" "Responsibility for receiving extras and discounts","Responsabilidade pelo recebimento de extras e descontos" +"Pagar.me Recipient","Recebedor Pagar.me" "Marketplace main recipient","Recebedor Principal do Marketplace" "Pagar.me recipient id that represents your marketplace
","ID do recebedor Pagar.me que representa seu marketplace
" +"View","Visualizar" +"Edit","Editar" +"Delete","Deletar" +"External ID","ID Externo" +"Pagar.me ID","ID Pagar.me" +"Error!","Erro!" +"Recipient registered successfully!","Recebedor cadastrado com sucesso!" +"Recipient had their status updated successfully.","Recebedor teve seu status atualizado com sucesso." +"Status updated!","Status atualizado!" + +"He can now sell, but remember to check his status. He can only withdraw his sales amounts once the status is “active”
","Ele já consegue vender, mas lembre-se de verificar o status. Ele só poderá sacar os valores de suas vendas quando o status estiver “ativo”.
" +"Follow the status on Pagar.me > Recipients to activate this recipient's balance movement soon!
","Acompanhe o status em Pagar.me > Recebedores para ativar a movimentação de saldo deste recebedor em breve!
" +"To activate your balance movement on Pagar.me, complete our security validation.","Para ativar sua movimentação de saldo no Pagar.me, complete nossa validação de segurança." +"Attention! The generated link will be valid for 20 minutes.", "Atenção! O link gerado será válido por 20 minutos." + +"Start validation","Iniciar validação" +"Point the smartphone camera to scan the QRCode.","Aponte a câmera do celular para ler o QRCode." +"Or use this %slink%s.","Ou utilize este %slink%s." +"An error occurred while saving the recipient.","Ocorreu um erro ao salvar o recebedor." +"Bank account holder name must be lower than 30 characters.","O nome do titular da conta bancária deve ter menos de 30 caracteres." +"Recipient not active.","Recebedor não está ativo." +"Recipient found.","Recebedor encontrado." +"Recipient deleted.","Recebedor excluído." +"Invalid email.","Email inválido." "Get info","Obter info" "Marketplace and Sellers","Marketplace e Vendedores" "Sellers","Vendedores" @@ -431,14 +457,37 @@ "Name","Nome" "Add New Recipient","Adicionar Novo Recebedor" "Recipient not found.","Recebedor não encontrado." -"Select webkul seller","Selecione o vendedor do webkul" +"Seller information","Informações do recebedor" +"Select Webkul seller","Selecione o vendedor do Webkul" "Search","Pesquisar" "Create","Criar" -"Use an existing Pagar.me recipient","Usar um recipiente existente na Pagar.me" -"External ID","ID externo" +"Webkul ID","ID Webkul" +"Site URL","URL do site" +"Phone numbers","Números de telefones" +"Contact type","Tipo de contato" +"Telephone","Telefone" +"Contact number","Número de contato" "Document type","Tipo do documento" -"Document number","Número do documento" +"Document number", "Número do documento" +"Personal data","Dados pessoais" +"Company data","Dados da empresa" +"Company address","Endereço da empresa" +"Mother name","Nome da mãe" +"Date of birth","Data de nascimento" +"Monthly income","Renda mensal" +"Profession","Profissão" +"Reference point","Ponto de referência" +"Trading name","Nome fantasia" +"Annual revenue","Faturamento anual" +"Founding date","Data de fundação" +"Company type","Tipo da empresa" +"Company name","Razão social" +"Managing partner","Sócio administrador" +"Managing partner phone numbers","Números de telefones do sócio administrador" +"Managing partner address","Endereço do sócio administrador" "Banking information","Informações de banco" +"The bank account holder must be the recipient (same document number).","O titular da conta bancária deve ser o recebedor (mesmo número de documento)." +"Use an existing Pagar.me recipient","Usar um recebedor existente na Pagar.me" "Holder name","Nome do titular" "Bank code","Código do banco" "Branch number","Número da agência" @@ -458,6 +507,7 @@ "Weekly","Semanalmente" "Monthly","Mensalmente" "Create Recipient","Criar Recebedor" +"Recipient","Recebedor" "Save","Salvar" "Back","Voltar" "Can't create recipient. Please review the information and try again.","Não foi possível criar o recebedor. Por favor revise os dados e tente novamente." @@ -545,3 +595,18 @@ "U - Authentication unavailable","U - Autenticação indisponível" "N - Transaction rejected by the Issuer","N - Transação rejeitada pelo Emissor" "R - Transaction rejected by Issuer (post-challenge)","R - Transação rejeitada pelo Emissor (pós-desafio)" +"Registered","Cadastrado" +"Validation Requested","Validação Solicitada" +"Waiting For Analysis","Aguardando Análise" +"Approved","Aprovado" +"Disapproved","Reprovado" +"Suspended","Suspenso" +"Blocked","Bloqueado" +"Inactive","Inativo" +"Recipient not founded.","Recebedor não encontrado." +"Failed to generate the security validation link.","Falha ao gerar o link de validação de segurança." +"Something went wrong, please try again later.","Algo deu errado, por favor tente novamente mais tarde." +"Google Pay identifier required to create successful orders, find out how to request here.", "Identificador do Google Pay necessário para criação de pedidos com sucesso, saiba como solicitar aqui." +"MerchantId Google Pay", "MerchantId Google Pay" +"Store name on Google Pay", "Nome da loja no Google Pay" +"Name of your store that will be displayed to the customer while purchasing through Google Pay.", "Nome da sua loja que será exibida ao cliente durante a compra pelo Google Pay." diff --git a/view/adminhtml/layout/pagarme_pagarme_plans_create.xml b/view/adminhtml/layout/pagarme_pagarme_plans_create.xml index e37a61f2..b8414ec6 100755 --- a/view/adminhtml/layout/pagarme_pagarme_plans_create.xml +++ b/view/adminhtml/layout/pagarme_pagarme_plans_create.xml @@ -1,7 +1,6 @@