InlineEdit.php 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Customer\Controller\Adminhtml\Index;
  7. use Magento\Backend\App\Action;
  8. use Magento\Customer\Api\CustomerRepositoryInterface;
  9. use Magento\Customer\Api\Data\CustomerInterface;
  10. use Magento\Customer\Model\AddressRegistry;
  11. use Magento\Customer\Model\EmailNotificationInterface;
  12. use Magento\Customer\Ui\Component\Listing\AttributeRepository;
  13. use Magento\Framework\App\Action\HttpPostActionInterface;
  14. use Magento\Framework\Exception\NoSuchEntityException;
  15. use Magento\Framework\Message\MessageInterface;
  16. use Magento\Framework\App\ObjectManager;
  17. /**
  18. * Customer inline edit action
  19. *
  20. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  21. */
  22. class InlineEdit extends \Magento\Backend\App\Action implements HttpPostActionInterface
  23. {
  24. /**
  25. * Authorization level of a basic admin session
  26. *
  27. * @see _isAllowed()
  28. */
  29. const ADMIN_RESOURCE = 'Magento_Customer::manage';
  30. /**
  31. * @var \Magento\Customer\Api\Data\CustomerInterface
  32. */
  33. private $customer;
  34. /**
  35. * @var \Magento\Customer\Api\CustomerRepositoryInterface
  36. */
  37. protected $customerRepository;
  38. /**
  39. * @var \Magento\Framework\Controller\Result\JsonFactory
  40. */
  41. protected $resultJsonFactory;
  42. /**
  43. * @var \Magento\Customer\Model\Customer\Mapper
  44. */
  45. protected $customerMapper;
  46. /**
  47. * @var \Magento\Framework\Api\DataObjectHelper
  48. */
  49. protected $dataObjectHelper;
  50. /**
  51. * @var \Psr\Log\LoggerInterface
  52. */
  53. protected $logger;
  54. /**
  55. * @var \Magento\Customer\Model\EmailNotificationInterface
  56. */
  57. private $emailNotification;
  58. /**
  59. * @var AddressRegistry
  60. */
  61. private $addressRegistry;
  62. /**
  63. * @param Action\Context $context
  64. * @param CustomerRepositoryInterface $customerRepository
  65. * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
  66. * @param \Magento\Customer\Model\Customer\Mapper $customerMapper
  67. * @param \Magento\Framework\Api\DataObjectHelper $dataObjectHelper
  68. * @param \Psr\Log\LoggerInterface $logger
  69. * @param AddressRegistry|null $addressRegistry
  70. */
  71. public function __construct(
  72. Action\Context $context,
  73. CustomerRepositoryInterface $customerRepository,
  74. \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
  75. \Magento\Customer\Model\Customer\Mapper $customerMapper,
  76. \Magento\Framework\Api\DataObjectHelper $dataObjectHelper,
  77. \Psr\Log\LoggerInterface $logger,
  78. AddressRegistry $addressRegistry = null
  79. ) {
  80. $this->customerRepository = $customerRepository;
  81. $this->resultJsonFactory = $resultJsonFactory;
  82. $this->customerMapper = $customerMapper;
  83. $this->dataObjectHelper = $dataObjectHelper;
  84. $this->logger = $logger;
  85. $this->addressRegistry = $addressRegistry ?: ObjectManager::getInstance()->get(AddressRegistry::class);
  86. parent::__construct($context);
  87. }
  88. /**
  89. * Get email notification
  90. *
  91. * @return EmailNotificationInterface
  92. * @deprecated 100.1.0
  93. */
  94. private function getEmailNotification()
  95. {
  96. if (!($this->emailNotification instanceof EmailNotificationInterface)) {
  97. return \Magento\Framework\App\ObjectManager::getInstance()->get(
  98. EmailNotificationInterface::class
  99. );
  100. } else {
  101. return $this->emailNotification;
  102. }
  103. }
  104. /**
  105. * Inline edit action execute
  106. *
  107. * @return \Magento\Framework\Controller\Result\Json
  108. * @throws \Magento\Framework\Exception\LocalizedException
  109. * @throws \Magento\Framework\Exception\NoSuchEntityException
  110. */
  111. public function execute()
  112. {
  113. /** @var \Magento\Framework\Controller\Result\Json $resultJson */
  114. $resultJson = $this->resultJsonFactory->create();
  115. $postItems = $this->getRequest()->getParam('items', []);
  116. if (!($this->getRequest()->getParam('isAjax') && count($postItems))) {
  117. return $resultJson->setData([
  118. 'messages' => [__('Please correct the data sent.')],
  119. 'error' => true,
  120. ]);
  121. }
  122. foreach (array_keys($postItems) as $customerId) {
  123. $this->setCustomer($this->customerRepository->getById($customerId));
  124. $currentCustomer = clone $this->getCustomer();
  125. if ($this->getCustomer()->getDefaultBilling()) {
  126. $this->updateDefaultBilling($this->getData($postItems[$customerId]));
  127. }
  128. $this->updateCustomer($this->getData($postItems[$customerId], true));
  129. $this->saveCustomer($this->getCustomer());
  130. $this->getEmailNotification()->credentialsChanged($this->getCustomer(), $currentCustomer->getEmail());
  131. }
  132. return $resultJson->setData([
  133. 'messages' => $this->getErrorMessages(),
  134. 'error' => $this->isErrorExists()
  135. ]);
  136. }
  137. /**
  138. * Receive entity(customer|customer_address) data from request
  139. *
  140. * @param array $data
  141. * @param mixed $isCustomerData
  142. * @return array
  143. */
  144. protected function getData(array $data, $isCustomerData = null)
  145. {
  146. $addressKeys = preg_grep(
  147. '/^(' . AttributeRepository::BILLING_ADDRESS_PREFIX . '\w+)/',
  148. array_keys($data),
  149. $isCustomerData
  150. );
  151. $result = array_intersect_key($data, array_flip($addressKeys));
  152. if ($isCustomerData === null) {
  153. foreach ($result as $key => $value) {
  154. if (strpos($key, AttributeRepository::BILLING_ADDRESS_PREFIX) !== false) {
  155. unset($result[$key]);
  156. $result[str_replace(AttributeRepository::BILLING_ADDRESS_PREFIX, '', $key)] = $value;
  157. }
  158. }
  159. }
  160. return $result;
  161. }
  162. /**
  163. * Update customer data
  164. *
  165. * @param array $data
  166. * @return void
  167. */
  168. protected function updateCustomer(array $data)
  169. {
  170. $customer = $this->getCustomer();
  171. $customerData = array_merge(
  172. $this->customerMapper->toFlatArray($customer),
  173. $data
  174. );
  175. $this->dataObjectHelper->populateWithArray(
  176. $customer,
  177. $customerData,
  178. \Magento\Customer\Api\Data\CustomerInterface::class
  179. );
  180. }
  181. /**
  182. * Update customer address data
  183. *
  184. * @param array $data
  185. * @return void
  186. */
  187. protected function updateDefaultBilling(array $data)
  188. {
  189. $addresses = $this->getCustomer()->getAddresses();
  190. /** @var \Magento\Customer\Api\Data\AddressInterface $address */
  191. foreach ($addresses as $address) {
  192. if ($address->isDefaultBilling()) {
  193. $this->dataObjectHelper->populateWithArray(
  194. $address,
  195. $this->processAddressData($data),
  196. \Magento\Customer\Api\Data\AddressInterface::class
  197. );
  198. break;
  199. }
  200. }
  201. }
  202. /**
  203. * Save customer with error catching
  204. *
  205. * @param CustomerInterface $customer
  206. * @return void
  207. */
  208. protected function saveCustomer(CustomerInterface $customer)
  209. {
  210. try {
  211. // No need to validate customer address during inline edit action
  212. $this->disableAddressValidation($customer);
  213. $this->customerRepository->save($customer);
  214. } catch (\Magento\Framework\Exception\InputException $e) {
  215. $this->getMessageManager()->addError($this->getErrorWithCustomerId($e->getMessage()));
  216. $this->logger->critical($e);
  217. } catch (\Magento\Framework\Exception\LocalizedException $e) {
  218. $this->getMessageManager()->addError($this->getErrorWithCustomerId($e->getMessage()));
  219. $this->logger->critical($e);
  220. } catch (\Exception $e) {
  221. $this->getMessageManager()->addError($this->getErrorWithCustomerId('We can\'t save the customer.'));
  222. $this->logger->critical($e);
  223. }
  224. }
  225. /**
  226. * Parse street field
  227. *
  228. * @param array $data
  229. * @return array
  230. */
  231. protected function processAddressData(array $data)
  232. {
  233. foreach (['firstname', 'lastname'] as $requiredField) {
  234. if (empty($data[$requiredField])) {
  235. $data[$requiredField] = $this->getCustomer()->{'get' . ucfirst($requiredField)}();
  236. }
  237. }
  238. return $data;
  239. }
  240. /**
  241. * Get array with errors
  242. *
  243. * @return array
  244. */
  245. protected function getErrorMessages()
  246. {
  247. $messages = [];
  248. foreach ($this->getMessageManager()->getMessages()->getErrors() as $error) {
  249. $messages[] = $error->getText();
  250. }
  251. return $messages;
  252. }
  253. /**
  254. * Check if errors exists
  255. *
  256. * @return bool
  257. */
  258. protected function isErrorExists()
  259. {
  260. return (bool)$this->getMessageManager()->getMessages(true)->getCountByType(MessageInterface::TYPE_ERROR);
  261. }
  262. /**
  263. * Set customer
  264. *
  265. * @param CustomerInterface $customer
  266. * @return $this
  267. */
  268. protected function setCustomer(CustomerInterface $customer)
  269. {
  270. $this->customer = $customer;
  271. return $this;
  272. }
  273. /**
  274. * Receive customer
  275. *
  276. * @return CustomerInterface
  277. */
  278. protected function getCustomer()
  279. {
  280. return $this->customer;
  281. }
  282. /**
  283. * Add page title to error message
  284. *
  285. * @param string $errorText
  286. * @return string
  287. */
  288. protected function getErrorWithCustomerId($errorText)
  289. {
  290. return '[Customer ID: ' . $this->getCustomer()->getId() . '] ' . __($errorText);
  291. }
  292. /**
  293. * Disable Customer Address Validation
  294. *
  295. * @param CustomerInterface $customer
  296. * @throws NoSuchEntityException
  297. */
  298. private function disableAddressValidation($customer)
  299. {
  300. foreach ($customer->getAddresses() as $address) {
  301. $addressModel = $this->addressRegistry->retrieve($address->getId());
  302. $addressModel->setShouldIgnoreValidation(true);
  303. }
  304. }
  305. }