1
0
mirror of synced 2024-11-22 04:56:07 +03:00

Поддержка функции добавления одинакового товара в заказ как разные товарные позиции из CRM

This commit is contained in:
gorokh 2019-09-26 16:39:02 +03:00
parent 23602a7b71
commit 06ddf9a807
7 changed files with 89 additions and 31 deletions

View File

@ -1,3 +1,6 @@
## 2019-10-26 v.2.4.2
* Поддержка функции добавления одинакового товара в заказ как разные товарные позиции из CRM
## 2018-12-25 v.2.4.1 ## 2018-12-25 v.2.4.1
* Удалена генерация externalId покупателя при заказе от незарегестрированного пользователя * Удалена генерация externalId покупателя при заказе от незарегестрированного пользователя

View File

@ -29,4 +29,4 @@ By default ICML file is being generated by module every 4 hours. You can find fi
composer require retailcrm/api-client-php ~5.0 composer require retailcrm/api-client-php ~5.0
``` ```
This module is compatible with Magento up to version 2.2.3 This module is compatible with Magento up to version 2.2.8

View File

@ -36,4 +36,4 @@ composer require retailcrm/api-client-php ~5.0
В конфигурационный файл `composer.json` вашего проекта будет добавлена библиотека [retailcrm/api-client-php](https://github.com/retailcrm/api-client-php), которая будет установлена в директорию `vendor/`. В конфигурационный файл `composer.json` вашего проекта будет добавлена библиотека [retailcrm/api-client-php](https://github.com/retailcrm/api-client-php), которая будет установлена в директорию `vendor/`.
Этот модуль совместим с Magento 2 до версии 2.2.3 Этот модуль совместим с Magento 2 до версии 2.2.8

View File

@ -1 +1 @@
2.4.1 2.4.2

View File

@ -81,9 +81,13 @@ class Payment extends \Magento\Config\Block\System\Config\Form\Fieldset
$html .= $this->_getHeaderHtml($element); $html .= $this->_getHeaderHtml($element);
if ($this->client->isConfigured()) { if ($this->client->isConfigured()) {
$paymentMethods = $this->paymentConfig->getActiveMethods(); $manager = \Magento\Framework\App\ObjectManager::getInstance();
$paymentMethodListInterface = $manager->get(\Magento\Payment\Api\PaymentMethodListInterface::class);
$storeManagerInterface = $manager->get('Magento\Store\Model\StoreManagerInterface');
$storeId = $storeManagerInterface->getStore()->getId();
$paymentMethodList = $paymentMethodListInterface->getActiveList($storeId);
foreach ($paymentMethods as $code => $payment) { foreach ($paymentMethodList as $code => $payment) {
$html .= $this->_getFieldHtml($element, $payment); $html .= $this->_getFieldHtml($element, $payment);
} }
} else { } else {
@ -137,7 +141,7 @@ class Payment extends \Magento\Config\Block\System\Config\Form\Fieldset
* Get field html * Get field html
* *
* @param \Magento\Framework\Data\Form\Element\AbstractElement $fieldset * @param \Magento\Framework\Data\Form\Element\AbstractElement $fieldset
* @param \Magento\Payment\Model\Method\AbstractMethod $payment * @param \Magento\Payment\Api\Data\PaymentMethodInterface $payment
* *
* @return string * @return string
*/ */
@ -145,9 +149,7 @@ class Payment extends \Magento\Config\Block\System\Config\Form\Fieldset
{ {
$configData = $this->getConfigData(); $configData = $this->getConfigData();
$path = 'retailcrm/' . $fieldset->getId() . '/' . $payment->getCode(); $path = 'retailcrm/' . $fieldset->getId() . '/' . $payment->getCode();
$data = isset($configData[$path]) ? $configData[$path] : []; $data = isset($configData[$path]) ? $configData[$path] : [];
$e = $this->_getDummyElement(); $e = $this->_getDummyElement();
$field = $fieldset->addField( $field = $fieldset->addField(

View File

@ -165,7 +165,7 @@ class Exchange
$shippings = $this->config->getValue('retailcrm/retailcrm_shipping'); $shippings = $this->config->getValue('retailcrm/retailcrm_shipping');
$sites = $this->helper->getMappingSites(); $sites = $this->helper->getMappingSites();
if ($sites) { if ($sites && in_array($order['site'], $sites)) {
$store = $this->storeManager->getStore($sites[$order['site']]); $store = $this->storeManager->getStore($sites[$order['site']]);
$websiteId = $store->getWebsiteId(); $websiteId = $store->getWebsiteId();
} else { } else {
@ -178,7 +178,7 @@ class Exchange
$customer->setWebsiteId($websiteId); $customer->setWebsiteId($websiteId);
if (isset($order['customer']['externalId'])) { if (isset($order['customer']['externalId'])) {
$customer->load($order['customer']['externalId']); $customer = $this->customerRepository->getById($order['customer']['externalId']);
} }
if (!$customer->getId()) { if (!$customer->getId()) {
@ -190,7 +190,7 @@ class Exchange
->setEmail($order['email']) ->setEmail($order['email'])
->setPassword($order['email']); ->setPassword($order['email']);
try { try {
$customer->save(); $this->customerRepository->save($customer);
} catch (\Exception $exception) { } catch (\Exception $exception) {
$this->logger->writeRow($exception->getMessage()); $this->logger->writeRow($exception->getMessage());
} }
@ -216,9 +216,32 @@ class Exchange
$quote->setCurrency(); $quote->setCurrency();
$quote->assignCustomer($customer); //Assign quote to customer $quote->assignCustomer($customer); //Assign quote to customer
//add items in quote $manager = \Magento\Framework\App\ObjectManager::getInstance();
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */
$productRepository = $manager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$ditems = [];
foreach ($order['items'] as $item) { foreach ($order['items'] as $item) {
$product = $this->product->load($item['offer']['externalId']); if (!isset($ditems[$item['offer']['externalId']]['quantity'])) {
$ditems[$item['offer']['externalId']] = [
'quantity' => null,
'discountTotal' => null,
'initialPrice' => null,
'price_sum' => null,
'price_item' => null
];
}
$ditems[$item['offer']['externalId']]['quantity'] += $item['quantity'];
$ditems[$item['offer']['externalId']]['discountTotal'] += $item['quantity'] * $item['discountTotal'];
$ditems[$item['offer']['externalId']]['initialPrice'] = (float)$item['initialPrice'];
$ditems[$item['offer']['externalId']]['price_sum'] = $ditems[$item['offer']['externalId']]['initialPrice'] * $ditems[$item['offer']['externalId']]['quantity'] - $ditems[$item['offer']['externalId']]['discountTotal'];
$ditems[$item['offer']['externalId']]['price_item'] = $ditems[$item['offer']['externalId']]['price_sum'] / $ditems[$item['offer']['externalId']]['quantity'];
}
//add items in quote
foreach ($ditems as $id =>$item) {
$product = $productRepository->getById($id,false, $store->getId(), false);
$product->setPrice($item['initialPrice']); $product->setPrice($item['initialPrice']);
$quote->addProduct( $quote->addProduct(
$product, $product,
@ -228,8 +251,8 @@ class Exchange
$products = []; $products = [];
foreach ($order['items'] as $item) { foreach ($ditems as $id => $item) {
$products[$item['offer']['externalId']] = ['qty' => $item['quantity']]; $products[$id] = ['product_id'=>$id,'qty' => $item['quantity']];
} }
$orderData = [ $orderData = [
@ -280,17 +303,19 @@ class Exchange
$quote->setPaymentMethod($payments[$paymentType]); $quote->setPaymentMethod($payments[$paymentType]);
$quote->setInventoryProcessed(false); $quote->setInventoryProcessed(false);
$quote->save(); /** @var \Magento\Quote\Api\CartRepositoryInterface $quoteRepository */
$quoteRepository = $manager->create(\Magento\Quote\Api\CartRepositoryInterface::class);
$quoteRepository->save($quote);
// Set Sales Order Payment // Set Sales Order Payment
$quote->getPayment()->importData(['method' => $payments[$paymentType]]); $quote->getPayment()->importData(['method' => $payments[$paymentType]]);
// Collect Totals & Save Quote // Collect Totals & Save Quote
$quote->collectTotals()->save(); $quote->collectTotals();
$quoteRepository->save($quote);
// Create Order From Quote // Create Order From Quote
$magentoOrder = $this->quoteManagement->submit($quote); $magentoOrder = $this->quoteManagement->submit($quote);
$increment_id = $magentoOrder->getId(); $increment_id = $magentoOrder->getId();
$this->api->ordersFixExternalIds( $this->api->ordersFixExternalIds(
@ -312,8 +337,8 @@ class Exchange
*/ */
private function doCreateUp($order) private function doCreateUp($order)
{ {
$manager = \Magento\Framework\App\ObjectManager::getInstance();
$this->logger->writeDump($order, 'doCreateUp'); $this->logger->writeDump($order, 'doCreateUp');
$response = $this->api->ordersGet($order['id'], $by = 'id'); $response = $this->api->ordersGet($order['id'], $by = 'id');
if (!$response->isSuccessful()) { if (!$response->isSuccessful()) {
@ -330,7 +355,7 @@ class Exchange
$region = $this->regionFactory->create(); $region = $this->regionFactory->create();
$sites = $this->helper->getMappingSites(); $sites = $this->helper->getMappingSites();
if ($sites) { if ($sites && in_array($order['site'], $sites)) {
$store = $this->storeManager->getStore($sites[$order['site']]); $store = $this->storeManager->getStore($sites[$order['site']]);
$websiteId = $store->getWebsiteId(); $websiteId = $store->getWebsiteId();
} else { } else {
@ -342,7 +367,7 @@ class Exchange
$customer->setWebsiteId($websiteId); $customer->setWebsiteId($websiteId);
if (isset($order['customer']['externalId'])) { if (isset($order['customer']['externalId'])) {
$customer->load($order['customer']['externalId']); // load customer by external id $customer = $this->customerRepository->getById($order['customer']['externalId']);
} }
//Create object of quote //Create object of quote
@ -361,9 +386,31 @@ class Exchange
$quote->setCustomerIsGuest(1); $quote->setCustomerIsGuest(1);
} }
//add items in quote $ditems = [];
foreach ($order['items'] as $item) { foreach ($order['items'] as $item) {
$product = $this->product->load($item['offer']['externalId']); if (!isset($ditems[$item['offer']['externalId']]['quantity'])) {
$ditems[$item['offer']['externalId']] = [
'quantity' => null,
'discountTotal' => null,
'initialPrice' => null,
'price_sum' => null,
'price_item' => null
];
}
$ditems[$item['offer']['externalId']]['quantity'] += $item['quantity'];
$ditems[$item['offer']['externalId']]['discountTotal'] += $item['quantity'] * $item['discountTotal'];
$ditems[$item['offer']['externalId']]['initialPrice'] = (float)$item['initialPrice'];
$ditems[$item['offer']['externalId']]['price_sum'] = $ditems[$item['offer']['externalId']]['initialPrice'] * $ditems[$item['offer']['externalId']]['quantity'] - $ditems[$item['offer']['externalId']]['discountTotal'];
$ditems[$item['offer']['externalId']]['price_item'] = $ditems[$item['offer']['externalId']]['price_sum'] / $ditems[$item['offer']['externalId']]['quantity'];
}
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */
$productRepository = $manager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
//add items in quote
foreach ($ditems as $id => $item) {
$product = $productRepository->getById($id,false, $store->getId(), false);
$product->setPrice($item['initialPrice']); $product->setPrice($item['initialPrice']);
$quote->addProduct( $quote->addProduct(
$product, $product,
@ -373,8 +420,8 @@ class Exchange
$products = []; $products = [];
foreach ($order['items'] as $item) { foreach ($ditems as $id => $item) {
$products[$item['offer']['externalId']] = ['qty' => $item['quantity']]; $products[$id] = ['product_id'=>$id,'qty' => $item['quantity']];
} }
$orderData = [ $orderData = [
@ -435,16 +482,20 @@ class Exchange
]; ];
$quote->setReservedOrderId($orderDataUp['increment_id']); $quote->setReservedOrderId($orderDataUp['increment_id']);
$quote->save(); /** @var \Magento\Quote\Api\CartRepositoryInterface $quoteRepository */
$quoteRepository = $manager->create(\Magento\Quote\Api\CartRepositoryInterface::class);
$quoteRepository->save($quote);
// Set Sales Order Payment // Set Sales Order Payment
$quote->getPayment()->importData(['method' => $payments[$paymentType]]); $quote->getPayment()->importData(['method' => $payments[$paymentType]]);
// Collect Totals & Save Quote // Collect Totals & Save Quote
$quote->collectTotals()->save(); $quote->collectTotals();
$quoteRepository->save($quote);
// Create Order From Quote // Create Order From Quote
$magentoOrder = $this->quoteManagement->submit($quote, $orderDataUp); $magentoOrder = $this->quoteManagement->submit($quote, $orderDataUp);
$oldOrder->setStatus('canceled')->save(); $oldOrder->setStatus('canceled')->save();
$increment_id = $magentoOrder->getId(); $increment_id = $magentoOrder->getId();
@ -508,11 +559,11 @@ class Exchange
foreach ($orderHistory as $change) { foreach ($orderHistory as $change) {
$orderId = $change['order']['id']; $orderId = $change['order']['id'];
$change['order'] = self::removeEmpty($change['order']); $change['order'] = self::removeEmpty($change['order']);
if (isset($change['order']['items'])) { if (isset($change['order']['items'])) {
$items = []; $items = [];
foreach ($change['order']['items'] as $item) { foreach ($change['order']['items'] as $item) {
if (isset($change['created'])) { if (isset($change['created'])) {
$item['create'] = 1; $item['create'] = 1;
@ -551,7 +602,7 @@ class Exchange
if (isset($change['item'])) { if (isset($change['item'])) {
if (isset($orders[$change['order']['id']]['items']) if (isset($orders[$change['order']['id']]['items'])
&& $orders[$change['order']['id']]['items'][$change['item']['id']] && isset($orders[$change['order']['id']]['items'][$change['item']['id']])
) { ) {
$orders[$change['order']['id']]['items'][$change['item']['id']] = array_merge( $orders[$change['order']['id']]['items'][$change['item']['id']] = array_merge(
$orders[$change['order']['id']]['items'][$change['item']['id']], $orders[$change['order']['id']]['items'][$change['item']['id']],

View File

@ -72,6 +72,8 @@ class Order implements \Retailcrm\Retailcrm\Api\OrderManagerInterface
] ]
]; ];
$codeShop = $this->config->getValue('retailcrm/retailcrm_site/default');
if ($shippingAddress->getData('country_id')) { if ($shippingAddress->getData('country_id')) {
$preparedOrder['countryIso'] = $shippingAddress->getData('country_id'); $preparedOrder['countryIso'] = $shippingAddress->getData('country_id');
} }
@ -87,7 +89,7 @@ class Order implements \Retailcrm\Retailcrm\Api\OrderManagerInterface
'type' => $this->config->getValue( 'type' => $this->config->getValue(
'retailcrm/retailcrm_payment/' . $order->getPayment()->getMethodInstance()->getCode() 'retailcrm/retailcrm_payment/' . $order->getPayment()->getMethodInstance()->getCode()
), ),
'externalId' => $order->getId(), 'externalId' => $codeShop.$order->getId(),
'order' => [ 'order' => [
'externalId' => $order->getId(), 'externalId' => $order->getId(),
] ]