Exemplo n.º 1
0
 /**
  * Set persistent data to customer session
  *
  * @param \Magento\Framework\Event\Observer $observer
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  *
  * @return $this
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     if (!$this->_persistentData->canProcess($observer) || !$this->_persistentData->isShoppingCartPersist()) {
         return $this;
     }
     if ($this->_persistentSession->isPersistent() && !$this->_customerSession->isLoggedIn()) {
         /** @var  \Magento\Customer\Api\Data\CustomerInterface $customer */
         $customer = $this->customerRepository->getById($this->_persistentSession->getSession()->getCustomerId());
         if ($defaultShipping = $customer->getDefaultShipping()) {
             /** @var  \Magento\Customer\Model\Data\Address $address */
             $address = $this->addressRepository->getById($defaultShipping);
             if ($address) {
                 $this->_customerSession->setDefaultTaxShippingAddress(['country_id' => $address->getCountryId(), 'region_id' => $address->getRegion() ? $address->getRegionId() : null, 'postcode' => $address->getPostcode()]);
             }
         }
         if ($defaultBilling = $customer->getDefaultBilling()) {
             $address = $this->addressRepository->getById($defaultBilling);
             if ($address) {
                 $this->_customerSession->setDefaultTaxBillingAddress(['country_id' => $address->getCountryId(), 'region_id' => $address->getRegion() ? $address->getRegionId() : null, 'postcode' => $address->getPostcode()]);
             }
         }
         $this->_customerSession->setCustomerId($customer->getId())->setCustomerGroupId($customer->getGroupId());
     }
     return $this;
 }
 /**
  * @return void
  */
 public function testExecute()
 {
     $formId = 'user_login';
     $login = '******';
     $loginParams = ['username' => $login];
     $customerId = 7;
     $redirectUrl = 'http://magento.com/customer/account/login/';
     $captchaValue = 'some-value';
     $captcha = $this->getMock('Magento\\Captcha\\Model\\DefaultModel', [], [], '', false);
     $captcha->expects($this->once())->method('isRequired')->with($login)->willReturn(true);
     $captcha->expects($this->once())->method('isCorrect')->with($captchaValue)->willReturn(false);
     $captcha->expects($this->once())->method('logAttempt')->with($login);
     $this->helperMock->expects($this->once())->method('getCaptcha')->with($formId)->willReturn($captcha);
     $response = $this->getMock('Magento\\Framework\\App\\Response\\Http', [], [], '', false);
     $response->expects($this->once())->method('setRedirect')->with($redirectUrl);
     $request = $this->getMock('Magento\\Framework\\App\\Request\\Http', [], [], '', false);
     $request->expects($this->any())->method('getPost')->with('login')->willReturn($loginParams);
     $controller = $this->getMock('Magento\\Framework\\App\\Action\\Action', [], [], '', false);
     $controller->expects($this->any())->method('getRequest')->will($this->returnValue($request));
     $controller->expects($this->any())->method('getResponse')->will($this->returnValue($response));
     $this->captchaStringResolverMock->expects($this->once())->method('resolve')->with($request, $formId)->willReturn($captchaValue);
     $customerDataMock = $this->getMock('\\Magento\\Customer\\Model\\Data\\Customer', ['getId'], [], '', false);
     $customerDataMock->expects($this->once())->method('getId')->willReturn($customerId);
     $this->customerRepositoryMock->expects($this->once())->method('get')->with($login)->willReturn($customerDataMock);
     $this->authenticationMock->expects($this->once())->method('processAuthenticationFailure')->with($customerId);
     $this->messageManagerMock->expects($this->once())->method('addError')->with(__('Incorrect CAPTCHA'));
     $this->actionFlagMock->expects($this->once())->method('set')->with('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);
     $this->customerSessionMock->expects($this->once())->method('setUsername')->with($login);
     $this->customerSessionMock->expects($this->once())->method('getBeforeAuthUrl')->willReturn(false);
     $this->customerUrlMock->expects($this->once())->method('getLoginUrl')->willReturn($redirectUrl);
     $this->observer->execute(new \Magento\Framework\Event\Observer(['controller_action' => $controller]));
 }
 /**
  * @magentoDataFixture Magento/Customer/_files/customer.php
  */
 public function testGetCustomerAttributeMetadata()
 {
     // Expect these attributes to exist but do not check the value
     $expectAttrsWOutVals = ['created_at', 'updated_at'];
     // Expect these attributes to exist and check the value - values come from _files/customer.php
     $expectAttrsWithVals = ['id' => 1, 'website_id' => 1, 'store_id' => 1, 'group_id' => 1, 'prefix' => 'Mr.', 'firstname' => 'John', 'middlename' => 'A', 'lastname' => 'Smith', 'suffix' => 'Esq.', 'email' => '*****@*****.**', 'default_billing' => '1', 'default_shipping' => '1', 'disable_auto_group_change' => 0, 'taxvat' => '12', 'gender' => 0];
     $customer = $this->customerRepository->getById(1);
     $this->assertNotNull($customer);
     $attributes = $this->_extensibleDataObjectConverter->toFlatArray($customer, [], '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     $this->assertNotEmpty($attributes);
     foreach ($attributes as $attributeCode => $attributeValue) {
         $this->assertNotNull($attributeCode);
         $this->assertNotNull($attributeValue);
         $attributeMetadata = $this->_service->getAttributeMetadata($attributeCode);
         $attrMetadataCode = $attributeMetadata->getAttributeCode();
         $this->assertSame($attributeCode, $attrMetadataCode);
         if (($key = array_search($attrMetadataCode, $expectAttrsWOutVals)) !== false) {
             unset($expectAttrsWOutVals[$key]);
         } else {
             $this->assertArrayHasKey($attrMetadataCode, $expectAttrsWithVals);
             $this->assertSame($expectAttrsWithVals[$attrMetadataCode], $attributeValue, "Failed for {$attrMetadataCode}");
             unset($expectAttrsWithVals[$attrMetadataCode]);
         }
     }
     $this->assertEmpty($expectAttrsWOutVals);
     $this->assertEmpty($expectAttrsWithVals);
 }
 /**
  * Ensure that fixture customer and his addresses are deleted.
  */
 protected function tearDown()
 {
     /** @var \Magento\Framework\Registry $registry */
     $registry = Bootstrap::getObjectManager()->get('Magento\\Framework\\Registry');
     $registry->unregister('isSecureArea');
     $registry->register('isSecureArea', true);
     try {
         $fixtureFirstAddressId = 1;
         $this->addressRepository->deleteById($fixtureFirstAddressId);
     } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
         /** First address fixture was not used */
     }
     try {
         $fixtureSecondAddressId = 2;
         $this->addressRepository->deleteById($fixtureSecondAddressId);
     } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
         /** Second address fixture was not used */
     }
     try {
         $fixtureCustomerId = 1;
         $this->customerRepository->deleteById($fixtureCustomerId);
     } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
         /** Customer fixture was not used */
     }
     $registry->unregister('isSecureArea');
     $registry->register('isSecureArea', false);
     parent::tearDown();
 }
Exemplo n.º 5
0
 /**
  * Reset forgotten password
  *
  * Used to handle data received from reset forgotten password form
  *
  * @return \Magento\Framework\Controller\Result\Redirect
  */
 public function execute()
 {
     /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
     $resultRedirect = $this->resultRedirectFactory->create();
     $resetPasswordToken = (string) $this->getRequest()->getQuery('token');
     $customerId = (int) $this->getRequest()->getQuery('id');
     $password = (string) $this->getRequest()->getPost('password');
     $passwordConfirmation = (string) $this->getRequest()->getPost('password_confirmation');
     if ($password !== $passwordConfirmation) {
         $this->messageManager->addError(__("New Password and Confirm New Password values didn't match."));
         $resultRedirect->setPath('*/*/createPassword', ['id' => $customerId, 'token' => $resetPasswordToken]);
         return $resultRedirect;
     }
     if (iconv_strlen($password) <= 0) {
         $this->messageManager->addError(__('New password field cannot be empty.'));
         $resultRedirect->setPath('*/*/createPassword', ['id' => $customerId, 'token' => $resetPasswordToken]);
         return $resultRedirect;
     }
     try {
         $customerEmail = $this->customerRepository->getById($customerId)->getEmail();
         $this->accountManagement->resetPassword($customerEmail, $resetPasswordToken, $password);
         $this->messageManager->addSuccess(__('Your password has been updated.'));
         $resultRedirect->setPath('*/*/login');
         return $resultRedirect;
     } catch (\Exception $exception) {
         $this->messageManager->addError(__('There was an error saving the new password.'));
         $resultRedirect->setPath('*/*/createPassword', ['id' => $customerId, 'token' => $resetPasswordToken]);
         return $resultRedirect;
     }
 }
Exemplo n.º 6
0
 /**
  * Retrieve Shared Wishlist Customer instance
  *
  * @return \Magento\Customer\Api\Data\CustomerInterface
  */
 public function getWishlistCustomer()
 {
     if ($this->_customer === null) {
         $this->_customer = $this->customerRepository->getById($this->_getWishlist()->getCustomerId());
     }
     return $this->_customer;
 }
Exemplo n.º 7
0
 /**
  * {@inheritdoc}
  */
 public function install(array $fixtures)
 {
     foreach ($fixtures as $file) {
         $fileName = $this->fixtureManager->getFixture($file);
         if (!file_exists($fileName)) {
             continue;
         }
         $rows = $this->csvReader->getData($fileName);
         $header = array_shift($rows);
         $isFirst = true;
         foreach ($rows as $row) {
             $data = [];
             foreach ($row as $key => $value) {
                 $data[$header[$key]] = $value;
             }
             $row = $data;
             if ($isFirst) {
                 $customer = $this->customerRepository->get($row['customer_email']);
                 if (!$customer->getId()) {
                     continue;
                 }
                 /** @var \Magento\Sales\Model\ResourceModel\Collection $orderCollection */
                 $orderCollection = $this->orderCollectionFactory->create();
                 $orderCollection->addFilter('customer_id', $customer->getId());
                 if ($orderCollection->count() > 0) {
                     break;
                 }
             }
             $isFirst = false;
             $orderData = $this->converter->convertRow($row);
             $this->orderProcessor->createOrder($orderData);
         }
     }
 }
 /**
  * @param InfoInterface $payment
  * @param float $amount
  * @return $this
  * @throws LocalizedException
  */
 public function capture(InfoInterface $payment, $amount)
 {
     parent::capture($payment, $amount);
     $customerId = $payment->getOrder()->getCustomerId();
     $customer = $this->customerRepository->getById($customerId);
     $openpayCustomerId = $customer->getCustomAttribute('openpay_customer_id')->getValue();
     $cardId = $payment->getAdditionalInformation('customer_card_id');
     $deviceSessionId = $payment->getAdditionalInformation('device_session_id');
     $order = $payment->getOrder();
     $currency = $order->getOrderCurrencyCode();
     $useOrderId = $this->getConfigData('useOrderId');
     $paymentLeyend = $this->getConfigData('paymentLeyend');
     $orderId = $order->getIncrementId();
     $params = ['source_id' => $cardId, 'method' => self::OPENPAY_PAYMENT_METHOD_CARD, 'amount' => $amount, 'currency' => $currency, 'description' => __($paymentLeyend)->getText(), 'order_id' => $useOrderId ? $orderId : null, 'device_session_id' => $deviceSessionId];
     try {
         $transaction = $this->chargeAdapter->chargeCustomerCard($openpayCustomerId, $params);
         $payment->setTransactionId($transaction->getId())->setIsTransactionClosed(0);
         $this->openpayCustomerRepository->clearCustomerCache($openpayCustomerId);
     } catch (OpenpayException $e) {
         $this->debugData(['request' => $params, 'exception' => $e->getMessage()]);
         $this->_logger->error(__('Payment capturing error.'));
         throw new LocalizedException(new Phrase('[' . $e->getErrorCode() . ']' . $e->getMessage()));
     }
     return $this;
 }
Exemplo n.º 9
0
 /**
  * Confirm customer account by id and confirmation key
  *
  * @return \Magento\Framework\Controller\Result\Redirect
  */
 public function execute()
 {
     /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
     $resultRedirect = $this->resultRedirectFactory->create();
     if ($this->_getSession()->isLoggedIn()) {
         $resultRedirect->setPath('*/*/');
         return $resultRedirect;
     }
     try {
         $customerId = $this->getRequest()->getParam('id', false);
         $key = $this->getRequest()->getParam('key', false);
         if (empty($customerId) || empty($key)) {
             throw new \Exception(__('Bad request.'));
         }
         // log in and send greeting email
         $customerEmail = $this->customerRepository->getById($customerId)->getEmail();
         $customer = $this->customerAccountManagement->activate($customerEmail, $key);
         $this->_getSession()->setCustomerDataAsLoggedIn($customer);
         $this->messageManager->addSuccess($this->getSuccessMessage());
         $resultRedirect->setUrl($this->getSuccessRedirect());
         return $resultRedirect;
     } catch (StateException $e) {
         $this->messageManager->addException($e, __('This confirmation key is invalid or has expired.'));
     } catch (\Exception $e) {
         $this->messageManager->addException($e, __('There was an error confirming the account'));
     }
     // die unhappy
     $url = $this->urlModel->getUrl('*/*/index', ['_secure' => true]);
     $resultRedirect->setUrl($this->_redirect->error($url));
     return $resultRedirect;
 }
Exemplo n.º 10
0
 /**
  * Save newsletter subscription preference action
  *
  * @return void|null
  */
 public function executeInternal()
 {
     if (!$this->formKeyValidator->validate($this->getRequest())) {
         return $this->_redirect('customer/account/');
     }
     $customerId = $this->_customerSession->getCustomerId();
     if ($customerId === null) {
         $this->messageManager->addError(__('Something went wrong while saving your subscription.'));
     } else {
         try {
             $customer = $this->customerRepository->getById($customerId);
             $storeId = $this->storeManager->getStore()->getId();
             $customer->setStoreId($storeId);
             $this->customerRepository->save($customer);
             if ((bool) $this->getRequest()->getParam('is_subscribed', false)) {
                 $this->subscriberFactory->create()->subscribeCustomerById($customerId);
                 $this->messageManager->addSuccess(__('We saved the subscription.'));
             } else {
                 $this->subscriberFactory->create()->unsubscribeCustomerById($customerId);
                 $this->messageManager->addSuccess(__('We removed the subscription.'));
             }
         } catch (\Exception $e) {
             $this->messageManager->addError(__('Something went wrong while saving your subscription.'));
         }
     }
     $this->_redirect('customer/account/');
 }
Exemplo n.º 11
0
 protected function execute(\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface $output)
 {
     $def = $this->manTrans->begin();
     try {
         foreach ($this->DEFAULT_DWNL_TREE as $custId => $parentId) {
             $first = 'User' . $custId;
             $last = 'Last';
             $email = "customer_{$custId}@test.com";
             if ($custId != $parentId) {
                 /* save parent ID to registry */
                 $referralCode = $this->mapCustomerMageIdByIndex[$parentId];
                 $this->toolReferral->replaceCodeInRegistry($referralCode);
             }
             /** @var \Magento\Customer\Api\Data\CustomerInterface $customer */
             $customer = $this->_manObj->create(\Magento\Customer\Api\Data\CustomerInterface::class);
             $customer->setEmail($email);
             $customer->setFirstname($first);
             $customer->setLastname($last);
             /* MOBI-427: change group ID for retail customers */
             if (in_array($custId, $this->GROUP_RETAIL)) {
                 $customer->setGroupId(BusinessCodesManager::M_CUST_GROUP_RETAIL);
             }
             /** @var \Magento\Customer\Api\Data\CustomerInterface $saved */
             $saved = $this->repoCustomer->save($customer, $this->DEFAULT_PASSWORD_HASH);
             $this->mapCustomerMageIdByIndex[$custId] = $saved->getId();
             $this->mapCustomerIndexByMageId[$saved->getId()] = $custId;
         }
         /* MOBI-426 : rename customer groups according to Generic App scheme. */
         $this->subCustomerGroups->renameGroups();
         $this->manTrans->commit($def);
     } finally {
         // transaction will be rolled back if commit is not done (otherwise - do nothing)
         $this->manTrans->end($def);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function run()
 {
     $this->logger->log('Installing orders:');
     foreach ($this->fixtures as $file) {
         $fileName = $this->fixtureHelper->getPath($file);
         $csvReader = $this->csvReaderFactory->create(['fileName' => $fileName, 'mode' => 'r']);
         $isFirst = true;
         foreach ($csvReader as $row) {
             if ($isFirst) {
                 $customer = $this->customerRepository->get($row['customer_email']);
                 if (!$customer->getId()) {
                     continue;
                 }
                 /** @var \Magento\Sales\Model\Resource\Collection $orderCollection */
                 $orderCollection = $this->orderCollectionFactory->create();
                 $orderCollection->addFilter('customer_id', $customer->getId());
                 if ($orderCollection->count() > 0) {
                     break;
                 }
             }
             $isFirst = false;
             $orderData = $this->converter->convertRow($row);
             $this->orderProcessor->createOrder($orderData);
             $this->logger->logInline('.');
         }
     }
 }
Exemplo n.º 13
0
 /**
  * Validates the fields in a specified address data object.
  *
  * @param \Magento\Quote\Api\Data\AddressInterface $addressData The address data object.
  * @return bool
  * @throws \Magento\Framework\Exception\InputException The specified address belongs to another customer.
  * @throws \Magento\Framework\Exception\NoSuchEntityException The specified customer ID or address ID is not valid.
  */
 public function validate(\Magento\Quote\Api\Data\AddressInterface $addressData)
 {
     //validate customer id
     if ($addressData->getCustomerId()) {
         $customer = $this->customerRepository->getById($addressData->getCustomerId());
         if (!$customer->getId()) {
             throw new \Magento\Framework\Exception\NoSuchEntityException(__('Invalid customer id %1', $addressData->getCustomerId()));
         }
     }
     if ($addressData->getCustomerAddressId()) {
         try {
             $this->addressRepository->getById($addressData->getCustomerAddressId());
         } catch (NoSuchEntityException $e) {
             throw new \Magento\Framework\Exception\NoSuchEntityException(__('Invalid address id %1', $addressData->getId()));
         }
         $applicableAddressIds = array_map(function ($address) {
             /** @var \Magento\Customer\Api\Data\AddressInterface $address */
             return $address->getId();
         }, $this->customerRepository->getById($addressData->getCustomerId())->getAddresses());
         if (!in_array($addressData->getCustomerAddressId(), $applicableAddressIds)) {
             throw new \Magento\Framework\Exception\NoSuchEntityException(__('Invalid address id %1', $addressData->getCustomerAddressId()));
         }
     }
     return true;
 }
Exemplo n.º 14
0
 public function testSubscribe()
 {
     $email = '*****@*****.**';
     $this->resource->expects($this->any())->method('loadByEmail')->willReturn(['subscriber_status' => 3, 'subscriber_email' => $email, 'name' => 'subscriber_name']);
     $this->resource->expects($this->any())->method('getIdFieldName')->willReturn('id_field');
     $this->scopeConfig->expects($this->any())->method('getValue')->willReturn(true);
     $this->customerSession->expects($this->any())->method('isLoggedIn')->willReturn(true);
     $customerDataModel = $this->getMock('\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     $this->customerSession->expects($this->any())->method('getCustomerDataObject')->willReturn($customerDataModel);
     $this->customerSession->expects($this->any())->method('getCustomerId')->willReturn(1);
     $customerDataModel->expects($this->any())->method('getEmail')->willReturn($email);
     $this->customerRepository->expects($this->any())->method('getById')->willReturn($customerDataModel);
     $customerDataModel->expects($this->any())->method('getStoreId')->willReturn(1);
     $customerDataModel->expects($this->any())->method('getId')->willReturn(1);
     $this->transportBuilder->expects($this->any())->method('setTemplateIdentifier')->willReturnSelf();
     $this->transportBuilder->expects($this->any())->method('setTemplateOptions')->willReturnSelf();
     $this->transportBuilder->expects($this->any())->method('setTemplateVars')->willReturnSelf();
     $this->transportBuilder->expects($this->any())->method('setFrom')->willReturnSelf();
     $this->transportBuilder->expects($this->any())->method('addTo')->willReturnSelf();
     $storeModel = $this->getMock('\\Magento\\Store\\Model\\Store', ['getId'], [], '', false);
     $this->scopeConfig->expects($this->any())->method('getValue')->willReturn('*****@*****.**');
     $this->storeManager->expects($this->any())->method('getStore')->willReturn($storeModel);
     $storeModel->expects($this->any())->method('getId')->willReturn(1);
     $transport = $this->getMock('\\Magento\\Framework\\Mail\\TransportInterface');
     $this->transportBuilder->expects($this->any())->method('getTransport')->willReturn($transport);
     $transport->expects($this->any())->method('sendMessage')->willReturnSelf();
     $inlineTranslation = $this->getMock('Magento\\Framework\\Translate\\Inline\\StateInterface');
     $inlineTranslation->expects($this->any())->method('resume')->willReturnSelf();
     $this->resource->expects($this->atLeastOnce())->method('save')->willReturnSelf();
     $this->assertEquals(1, $this->subscriber->subscribe($email));
 }
Exemplo n.º 15
0
 /**
  * Load search results
  *
  * @return $this
  */
 public function load()
 {
     $result = [];
     if (!$this->hasStart() || !$this->hasLimit() || !$this->hasQuery()) {
         $this->setResults($result);
         return $this;
     }
     $this->searchCriteriaBuilder->setCurrentPage($this->getStart());
     $this->searchCriteriaBuilder->setPageSize($this->getLimit());
     $searchFields = ['firstname', 'lastname', 'company'];
     $filters = [];
     foreach ($searchFields as $field) {
         $filters[] = $this->filterBuilder->setField($field)->setConditionType('like')->setValue($this->getQuery() . '%')->create();
     }
     $this->searchCriteriaBuilder->addFilters($filters);
     $searchCriteria = $this->searchCriteriaBuilder->create();
     $searchResults = $this->customerRepository->getList($searchCriteria);
     foreach ($searchResults->getItems() as $customer) {
         $customerAddresses = $customer->getAddresses();
         /** Look for a company name defined in default billing address */
         $company = null;
         foreach ($customerAddresses as $customerAddress) {
             if ($customerAddress->getId() == $customer->getDefaultBilling()) {
                 $company = $customerAddress->getCompany();
                 break;
             }
         }
         $result[] = ['id' => 'customer/1/' . $customer->getId(), 'type' => __('Customer'), 'name' => $this->_customerViewHelper->getCustomerName($customer), 'description' => $company, 'url' => $this->_adminhtmlData->getUrl('customer/index/edit', ['id' => $customer->getId()])];
     }
     $this->setResults($result);
     return $this;
 }
Exemplo n.º 16
0
 /**
  * Emulate 'welcome' block with persistent data
  *
  * @param \Magento\Framework\View\Element\AbstractBlock $block
  * @return $this
  */
 public function emulateWelcomeBlock($block)
 {
     $escapedName = $this->_escaper->escapeHtml($this->_customerViewHelper->getCustomerName($this->customerRepository->getById($this->_persistentSession->getSession()->getCustomerId())), null);
     $this->_applyAccountLinksPersistentData();
     $welcomeMessage = __('Welcome, %1!', $escapedName) . ' ' . $this->_layout->getBlock('header.additional')->toHtml();
     $block->setWelcome($welcomeMessage);
     return $this;
 }
 /**
  * Unlock customer on success login attempt.
  * @param \Magento\Framework\Event\Observer $observer
  * @return $this
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     /** @var \Magento\Customer\Model\Customer $model */
     $customerModel = $observer->getEvent()->getData('model');
     $customer = $this->customerRepository->getById($customerModel->getId());
     $this->accountManagementHelper->processUnlockData($customer->getId());
     $this->customerRepository->save($customer);
     return $this;
 }
Exemplo n.º 18
0
 /**
  * Return the full name of the customer currently logged in
  *
  * @return string|null
  */
 public function getCustomerName()
 {
     try {
         $customer = $this->customerRepository->getById($this->currentCustomer->getCustomerId());
         return $this->escapeHtml($this->_viewHelper->getCustomerName($customer));
     } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
         return null;
     }
 }
Exemplo n.º 19
0
 /**
  * Change customer password action
  *
  * @return \Magento\Framework\Controller\Result\Redirect
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 public function execute()
 {
     /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
     $resultRedirect = $this->resultRedirectFactory->create();
     if (!$this->formKeyValidator->validate($this->getRequest())) {
         $resultRedirect->setPath('*/*/edit');
         return $resultRedirect;
     }
     if ($this->getRequest()->isPost()) {
         $customerId = $this->_getSession()->getCustomerId();
         $customer = $this->customerExtractor->extract('customer_account_edit', $this->_request);
         $customer->setId($customerId);
         if ($customer->getAddresses() == null) {
             $customer->setAddresses($this->customerRepository->getById($customerId)->getAddresses());
         }
         if ($this->getRequest()->getParam('change_password')) {
             $currPass = $this->getRequest()->getPost('current_password');
             $newPass = $this->getRequest()->getPost('password');
             $confPass = $this->getRequest()->getPost('password_confirmation');
             if (strlen($newPass)) {
                 if ($newPass == $confPass) {
                     try {
                         $customerEmail = $this->customerRepository->getById($customerId)->getEmail();
                         $this->customerAccountManagement->changePassword($customerEmail, $currPass, $newPass);
                     } catch (AuthenticationException $e) {
                         $this->messageManager->addError($e->getMessage());
                     } catch (\Exception $e) {
                         $this->messageManager->addException($e, __('Something went wrong while changing the password.'));
                     }
                 } else {
                     $this->messageManager->addError(__('Confirm your new password.'));
                 }
             } else {
                 $this->messageManager->addError(__('Please enter new password.'));
             }
         }
         try {
             $this->customerRepository->save($customer);
         } catch (AuthenticationException $e) {
             $this->messageManager->addError($e->getMessage());
         } catch (InputException $e) {
             $this->messageManager->addException($e, __('Invalid input'));
         } catch (\Exception $e) {
             $this->messageManager->addException($e, __('We can\'t save the customer.') . $e->getMessage() . '<pre>' . $e->getTraceAsString() . '</pre>');
         }
         if ($this->messageManager->getMessages()->getCount() > 0) {
             $this->_getSession()->setCustomerFormData($this->getRequest()->getPostValue());
             $resultRedirect->setPath('*/*/edit');
             return $resultRedirect;
         }
         $this->messageManager->addSuccess(__('You saved the account information.'));
         $resultRedirect->setPath('customer/account');
         return $resultRedirect;
     }
     $resultRedirect->setPath('*/*/edit');
     return $resultRedirect;
 }
 /**
  * Customer locking implementation
  *
  * @param \Magento\Framework\Event\Observer $observer
  * @return $this
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     $username = $observer->getEvent()->getData('username');
     $customer = $this->customerRepository->get($username);
     if ($customer && $customer->getId()) {
         $this->accountManagementHelper->processCustomerLockoutData($customer->getId());
         $this->customerRepository->save($customer);
     }
     return $this;
 }
Exemplo n.º 21
0
 /**
  * @param AbstractAction $subject
  * @param RequestInterface $request
  * @return void
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function beforeDispatch(AbstractAction $subject, RequestInterface $request)
 {
     if ($this->state->getAreaCode() == Area::AREA_FRONTEND && $request->isPost() && $this->notificationStorage->isExists(NotificationStorage::UPDATE_CUSTOMER_SESSION, $this->session->getCustomerId())) {
         $customer = $this->customerRepository->getById($this->session->getCustomerId());
         $this->session->setCustomerData($customer);
         $this->session->setCustomerGroupId($customer->getGroupId());
         $this->session->regenerateId();
         $this->notificationStorage->remove(NotificationStorage::UPDATE_CUSTOMER_SESSION, $customer->getId());
     }
 }
Exemplo n.º 22
0
 public function testSaveActionWithException()
 {
     $this->formKeyValidatorMock->expects($this->once())->method('validate')->will($this->returnValue(true));
     $this->customerSessionMock->expects($this->any())->method('getCustomerId')->will($this->returnValue(1));
     $this->customerRepositoryMock->expects($this->any())->method('getById')->will($this->throwException(new NoSuchEntityException(__(NoSuchEntityException::MESSAGE_SINGLE_FIELD, ['fieldName' => 'customerId', 'value' => 'value']))));
     $this->redirectMock->expects($this->once())->method('redirect')->with($this->responseMock, 'customer/account/', []);
     $this->messageManagerMock->expects($this->never())->method('addSuccess');
     $this->messageManagerMock->expects($this->once())->method('addError')->with('Something went wrong while saving your subscription.');
     $this->action->execute();
 }
 /**
  * @return \Magento\Customer\Api\Data\CustomerInterface
  */
 protected function loadSource()
 {
     if ($this->isBackendOrder()) {
         // For backend orders
         $customerId = $this->objectManager->get('Magento\\Backend\\Model\\Session\\Quote')->getQuote()->getCustomerId();
     } else {
         $customerId = $this->objectManager->get('Magento\\Customer\\Model\\Session')->getCustomerId();
     }
     return $this->customerRepository->getById($customerId);
 }
 /**
  * Set persistent data to customer session
  *
  * @param \Magento\Framework\Event\Observer $observer
  * @return $this
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     if (!$this->_persistentData->canProcess($observer) || !$this->_persistentData->isShoppingCartPersist()) {
         return $this;
     }
     if ($this->_persistentSession->isPersistent() && !$this->_customerSession->isLoggedIn()) {
         $customer = $this->customerRepository->getById($this->_persistentSession->getSession()->getCustomerId());
         $this->_customerSession->setCustomerId($customer->getId())->setCustomerGroupId($customer->getGroupId());
     }
     return $this;
 }
Exemplo n.º 25
0
 /**
  * Verify that the specified customer has the same default billing and shipping address.
  *
  * @magentoDataFixture Magento/Customer/_files/customer.php
  * @magentoDataFixture Magento/Customer/_files/customer_address.php
  */
 public function testGetPrimaryAddressesBillingShippingSame()
 {
     $customer = $this->customerRepository->getById(1);
     $this->customerSession->setCustomerId(1);
     $addresses = $this->block->getPrimaryAddresses();
     $this->assertCount(1, $addresses);
     $address = $addresses[0];
     $this->assertInstanceOf('Magento\\Customer\\Api\\Data\\AddressInterface', $address);
     $this->assertEquals((int) $customer->getDefaultBilling(), $address->getId());
     $this->assertEquals((int) $customer->getDefaultShipping(), $address->getId());
 }
Exemplo n.º 26
0
 /**
  * @magentoDataFixture Magento/Customer/_files/customer.php
  */
 public function testMassAssignGroupAction()
 {
     $customer = $this->customerRepository->getById(1);
     $this->assertEquals(1, $customer->getGroupId());
     $this->getRequest()->setParam('group', 0)->setPostValue('namespace', 'customer_listing')->setPostValue('selected', [1]);
     $this->dispatch('backend/customer/index/massAssignGroup');
     $this->assertSessionMessages($this->equalTo(['A total of 1 record(s) were updated.']), \Magento\Framework\Message\MessageInterface::TYPE_SUCCESS);
     $this->assertRedirect($this->stringStartsWith($this->baseControllerUrl));
     $customer = $this->customerRepository->getById(1);
     $this->assertEquals(0, $customer->getGroupId());
 }
 /**
  * Adds New Relic custom parameters per request for store, website, and logged in user if applicable
  *
  * @param Observer $observer
  * @return void
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function execute(Observer $observer)
 {
     if ($this->config->isNewRelicEnabled()) {
         $this->newRelicWrapper->addCustomParameter(Config::STORE, $this->storeManager->getStore()->getName());
         $this->newRelicWrapper->addCustomParameter(Config::WEBSITE, $this->storeManager->getWebsite()->getName());
         if ($this->customerSession->isLoggedIn()) {
             $customer = $this->customerRepository->getById($this->customerSession->getCustomerId());
             $this->newRelicWrapper->addCustomParameter(Config::CUSTOMER_ID, $customer->getId());
             $this->newRelicWrapper->addCustomParameter(Config::CUSTOMER_NAME, $customer->getFirstname() . ' ' . $customer->getLastname());
         }
     }
 }
 /**
  * @magentoAppArea frontend
  * @magentoConfigFixture current_store persistent/options/shopping_cart 1
  * @magentoConfigFixture current_store persistent/options/logout_clear 0
  * @magentoConfigFixture current_store persistent/options/enabled 1
  */
 public function testEmulateCustomer()
 {
     $observer = new \Magento\Framework\Event\Observer();
     $this->_customerSession->loginById(1);
     $this->_customerSession->logout();
     $this->assertNull($this->_customerSession->getCustomerId());
     $this->assertEquals(\Magento\Customer\Model\GroupManagement::NOT_LOGGED_IN_ID, $this->_customerSession->getCustomerGroupId());
     $this->_observer->execute($observer);
     $customer = $this->customerRepository->getById($this->_persistentSessionHelper->getSession()->getCustomerId());
     $this->assertEquals($customer->getId(), $this->_customerSession->getCustomerId());
     $this->assertEquals($customer->getGroupId(), $this->_customerSession->getCustomerGroupId());
 }
Exemplo n.º 29
0
 /**
  * @magentoDataFixture Magento/Customer/_files/customer.php
  */
 public function testGetHtml()
 {
     $customer = $this->_customerRepository->getById(1);
     $data = ['account' => $customer->__toArray()];
     $this->_context->getBackendSession()->setCustomerData($data);
     $this->_block = $this->_objectManager->get('Magento\\Framework\\View\\LayoutInterface')->createBlock('Magento\\Customer\\Block\\Adminhtml\\Edit\\Tab\\Carts', '', ['context' => $this->_context]);
     $html = $this->_block->toHtml();
     $this->assertContains("<div id=\"customer_cart_grid1\"", $html);
     $this->assertRegExp('/<div class=".*admin__data-grid-toolbar"/', $html);
     $this->assertContains("customer_cart_grid1JsObject = new varienGrid('customer_cart_grid1',", $html);
     $this->assertContains("backend/customer/cart_product_composite_cart/configure/website_id/1", $html);
 }
 /**
  * Upgrade customer password hash when customer has logged in
  *
  * @param \Magento\Framework\Event\Observer $observer
  * @return void
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     $password = $observer->getEvent()->getData('password');
     /** @var \Magento\Customer\Model\Customer $model */
     $model = $observer->getEvent()->getData('model');
     $customer = $this->customerRepository->getById($model->getId());
     $customerSecure = $this->customerRegistry->retrieveSecureData($model->getId());
     if (!$this->encryptor->validateHashVersion($customerSecure->getPasswordHash(), true)) {
         $customerSecure->setPasswordHash($this->encryptor->getHash($password, true));
         $this->customerRepository->save($customer);
     }
 }