1
0
mirror of synced 2024-12-05 03:16:04 +03:00

update module (#5)

* add delivery price

* Update events.php

* fix cron task

* fix cron task

* fix customer

* fix order number

* update module
This commit is contained in:
Vitaly Artemev 2017-03-13 13:58:33 +03:00 committed by Alex Lushpai
parent e0c23b0852
commit 90bda4ea1d
17 changed files with 454 additions and 427 deletions

32
classes/modules/RetailCRM/__admin.php Normal file → Executable file
View File

@ -23,8 +23,7 @@ abstract class __RetailCRM_adm extends baseModuleAdmin
if (!empty($apiKey) && !empty($crmUrl)) { if (!empty($apiKey) && !empty($crmUrl)) {
$api = new RCrmProxy( $api = new RCrmProxy(
$config->get('retailcrm', 'crmUrl'), $config->get('retailcrm', 'crmUrl'),
$config->get('retailcrm', 'apiKey'), $config->get('retailcrm', 'apiKey')
__DIR__ . '/../../../retailcrm.error.log'
); );
if($api->paymentTypesList() !== false) { if($api->paymentTypesList() !== false) {
@ -36,7 +35,7 @@ abstract class __RetailCRM_adm extends baseModuleAdmin
$umiPaymentTypes = new selector('objects'); $umiPaymentTypes = new selector('objects');
$umiPaymentTypes->types('object-type')->name('emarket', 'payment'); $umiPaymentTypes->types('object-type')->name('emarket', 'payment');
$map = $this->getRelationMap($config->get('retailcrm', 'orderPaymentTypeMap')); $map = RCrmHelpers::getRelationMap($config->get('retailcrm', 'orderPaymentTypeMap'));
$orderPaymentsMapping = array(); $orderPaymentsMapping = array();
foreach ($umiPaymentTypes->result() as $umiPaymentType) { foreach ($umiPaymentTypes->result() as $umiPaymentType) {
@ -46,7 +45,7 @@ abstract class __RetailCRM_adm extends baseModuleAdmin
$translations['order-payment-type-' . $umiPaymentTypeId] = $umiPaymentTypeName; $translations['order-payment-type-' . $umiPaymentTypeId] = $umiPaymentTypeName;
$orderPaymentsMapping['select:order-payment-type-' . $umiPaymentTypeId] = array(); $orderPaymentsMapping['select:order-payment-type-' . $umiPaymentTypeId] = array();
$orderPaymentsMapping['select:order-payment-type-' . $umiPaymentTypeId]['value'] = $this->getRelationByMap($map, $orderPaymentsMapping['select:order-payment-type-' . $umiPaymentTypeId]['value'] = RCrmHelpers::getRelationByMap($map,
$umiPaymentTypeId); $umiPaymentTypeId);
$orderPaymentsMapping['select:order-payment-type-' . $umiPaymentTypeId]['none'] = ''; $orderPaymentsMapping['select:order-payment-type-' . $umiPaymentTypeId]['none'] = '';
@ -63,7 +62,7 @@ abstract class __RetailCRM_adm extends baseModuleAdmin
$umiDeliveryTypes = new selector('objects'); $umiDeliveryTypes = new selector('objects');
$umiDeliveryTypes->types('object-type')->name('emarket', 'delivery'); $umiDeliveryTypes->types('object-type')->name('emarket', 'delivery');
$map = $this->getRelationMap($config->get('retailcrm', 'orderDeliveryTypeMap')); $map = RCrmHelpers::getRelationMap($config->get('retailcrm', 'orderDeliveryTypeMap'));
$orderDeliveryTypesMapping = array(); $orderDeliveryTypesMapping = array();
foreach ($umiDeliveryTypes as $umiDeliveryType) { foreach ($umiDeliveryTypes as $umiDeliveryType) {
@ -73,7 +72,7 @@ abstract class __RetailCRM_adm extends baseModuleAdmin
$translations['order-delivery-type-' . $umiDeliveryTypeId] = $umiDeliveryTypeName; $translations['order-delivery-type-' . $umiDeliveryTypeId] = $umiDeliveryTypeName;
$orderDeliveryTypesMapping['select:order-delivery-type-' . $umiDeliveryTypeId] = array(); $orderDeliveryTypesMapping['select:order-delivery-type-' . $umiDeliveryTypeId] = array();
$orderDeliveryTypesMapping['select:order-delivery-type-' . $umiDeliveryTypeId]['value'] = $this->getRelationByMap($map, $orderDeliveryTypesMapping['select:order-delivery-type-' . $umiDeliveryTypeId]['value'] = RCrmHelpers::getRelationByMap($map,
$umiDeliveryTypeId); $umiDeliveryTypeId);
$orderDeliveryTypesMapping['select:order-delivery-type-' . $umiDeliveryTypeId]['none'] = ''; $orderDeliveryTypesMapping['select:order-delivery-type-' . $umiDeliveryTypeId]['none'] = '';
@ -91,7 +90,7 @@ abstract class __RetailCRM_adm extends baseModuleAdmin
$umiPaymentStatuses = new selector('objects'); $umiPaymentStatuses = new selector('objects');
$umiPaymentStatuses->types('object-type')->name('emarket', 'order_payment_status'); $umiPaymentStatuses->types('object-type')->name('emarket', 'order_payment_status');
$map = $this->getRelationMap($config->get('retailcrm', 'orderPaymentStatusMap')); $map = RCrmHelpers::getRelationMap($config->get('retailcrm', 'orderPaymentStatusMap'));
$orderPaymentStatusesMapping = array(); $orderPaymentStatusesMapping = array();
foreach ($umiPaymentStatuses->result() as $umiPaymentStatus) { foreach ($umiPaymentStatuses->result() as $umiPaymentStatus) {
@ -101,7 +100,7 @@ abstract class __RetailCRM_adm extends baseModuleAdmin
$translations['order-payment-status-' . $umiPaymentStatusId] = $umiPaymentStatusName; $translations['order-payment-status-' . $umiPaymentStatusId] = $umiPaymentStatusName;
$orderPaymentStatusesMapping['select:order-payment-status-' . $umiPaymentStatusId] = array(); $orderPaymentStatusesMapping['select:order-payment-status-' . $umiPaymentStatusId] = array();
$orderPaymentStatusesMapping['select:order-payment-status-' . $umiPaymentStatusId]['value'] = $this->getRelationByMap($map, $orderPaymentStatusesMapping['select:order-payment-status-' . $umiPaymentStatusId]['value'] = RCrmHelpers::getRelationByMap($map,
$umiPaymentStatusId); $umiPaymentStatusId);
$orderPaymentStatusesMapping['select:order-payment-status-' . $umiPaymentStatusId]['none'] = ''; $orderPaymentStatusesMapping['select:order-payment-status-' . $umiPaymentStatusId]['none'] = '';
@ -118,26 +117,29 @@ abstract class __RetailCRM_adm extends baseModuleAdmin
$umiOrderStatuses = new selector('objects'); $umiOrderStatuses = new selector('objects');
$umiOrderStatuses->types('object-type')->name('emarket', 'order_status'); $umiOrderStatuses->types('object-type')->name('emarket', 'order_status');
$map = $this->getRelationMap($config->get('retailcrm', 'orderStatusMap')); $map = RCrmHelpers::getRelationMap($config->get('retailcrm', 'orderStatusMap'));
$params['orderStatusesMapping'] = array(); $params['orderStatusesMapping'] = array();
foreach ($umiOrderStatuses->result() as $umiOrderStatus) { foreach ($umiOrderStatuses->result() as $umiOrderStatus) {
$translations['order-status-' . $umiOrderStatus->getPropByName('codename')->getValue()] = $umiOrderStatus->getName(); $codeName = $umiOrderStatus->getValue('codename');
$params['orderStatusesMapping']['select:order-status-' . $umiOrderStatus->getPropByName('codename')->getValue()] = array(); $translations['order-status-' . $codeName] = $umiOrderStatus->getName();
$params['orderStatusesMapping']['select:order-status-' . $umiOrderStatus->getPropByName('codename')->getValue()]['value'] = $this->getRelationByMap($map,
$umiOrderStatus->getPropByName('codename')->getValue()); $params['orderStatusesMapping']['select:order-status-' . $codeName] = array();
$params['orderStatusesMapping']['select:order-status-' . $codeName]['value'] = RCrmHelpers::getRelationByMap($map, $codeName);
$params['orderStatusesMapping']['select:order-status-' . $codeName]['none'] = '';
$params['orderStatusesMapping']['select:order-status-' . $umiOrderStatus->getPropByName('codename')->getValue()]['none'] = '';
foreach ($crmOrderStatuses as $crmOrderStatus) { foreach ($crmOrderStatuses as $crmOrderStatus) {
$params['orderStatusesMapping']['select:order-status-' . $umiOrderStatus->getPropByName('codename')->getValue()][$crmOrderStatus['code']] = $crmOrderStatus['name']; $params['orderStatusesMapping']['select:order-status-' . $codeName][$crmOrderStatus['code']] = $crmOrderStatus['name'];
} }
} }
$params['guidesMapping']['select:country'] = array(); $params['guidesMapping']['select:country'] = array();
$params['guidesMapping']['select:country']['value'] = $config->get('retailcrm', 'countryGuideId'); $params['guidesMapping']['select:country']['value'] = $config->get('retailcrm', 'countryGuideId');
$params['guidesMapping']['select:country']['none'] = ''; $params['guidesMapping']['select:country']['none'] = '';
$objectTypes = umiObjectTypesCollection::getInstance(); $objectTypes = umiObjectTypesCollection::getInstance();
foreach ($objectTypes->getGuidesList() as $guideId => $guideName) { foreach ($objectTypes->getGuidesList() as $guideId => $guideName) {
$params['guidesMapping']['select:country'][$guideId] = $guideName; $params['guidesMapping']['select:country'][$guideId] = $guideName;
} }

0
classes/modules/RetailCRM/__events.php Normal file → Executable file
View File

35
classes/modules/RetailCRM/class.php Normal file → Executable file
View File

@ -4,32 +4,33 @@ class RetailCRM extends def_module {
{ {
parent::__construct(); parent::__construct();
if (cmsController::getInstance()->getCurrentMode() == "admin") { if (cmsController::getInstance()->getCurrentMode() == 'admin') {
$this->__loadLib("__admin.php"); $this->__loadLib('__admin.php');
$this->__implement("__RetailCRM_adm"); $this->__implement('__RetailCRM_adm');
} }
$this->__loadLib("../emarket/includes.php"); // Подключаем модуль интернет магазина
cmsController::getInstance()->getModule("emarket");
// RetailCRM classes // RetailCRM classes
$this->__loadLib("classes/retailcrm/RCrmActions.php"); $this->__loadLib('classes/retailcrm/RCrmActions.php');
$this->__loadLib("classes/retailcrm/RCrmApiClient.php"); $this->__loadLib('classes/retailcrm/RCrmApiClient.php');
$this->__loadLib("classes/retailcrm/RCrmApiResponse.php"); $this->__loadLib('classes/retailcrm/RCrmApiResponse.php');
$this->__loadLib("classes/retailcrm/RCrmHistory.php"); $this->__loadLib('classes/retailcrm/RCrmHistory.php');
$this->__loadLib("classes/retailcrm/RCrmHttpClient.php"); $this->__loadLib('classes/retailcrm/RCrmHttpClient.php');
$this->__loadLib("classes/retailcrm/RCrmIcml.php"); $this->__loadLib('classes/retailcrm/RCrmIcml.php');
$this->__loadLib("classes/retailcrm/RCrmProxy.php"); $this->__loadLib('classes/retailcrm/RCrmProxy.php');
// Exceptions // Exceptions
$this->__loadLib("classes/retailcrm/RCrmCurlException.php"); $this->__loadLib('classes/retailcrm/RCrmCurlException.php');
$this->__loadLib("classes/retailcrm/RCrmJsonException.php"); $this->__loadLib('classes/retailcrm/RCrmJsonException.php');
// Helpers // Helpers
$this->__loadLib("classes/retailcrm/RCrmHelpers.php"); $this->__loadLib('classes/retailcrm/RCrmHelpers.php');
$this->__implement("RCrmHelpers"); $this->__implement('RCrmHelpers');
// Events // Events
$this->__loadLib("__events.php"); $this->__loadLib('__events.php');
$this->__implement("__RetailCRM_events"); $this->__implement('__RetailCRM_events');
} }
} }

View File

@ -2,75 +2,82 @@
class RCrmActions class RCrmActions
{ {
public static function orderSend($orderId, $mode = 'create') { /**
* @param int $orderId
*/
public static function orderSend($orderId) {
/** @var RCrmApiClient $api */ /** @var RCrmApiClient $api */
$objects = umiObjectsCollection::getInstance(); $objects = umiObjectsCollection::getInstance();
$order = order::get($orderId); $orderObj = order::get($orderId);
if (!$order) { if (!$orderObj) {
return; return;
} }
// Проверяем был ли вызов из апи // Проверяем был ли вызов из апи
$regedit = regedit::getInstance(); $regedit = regedit::getInstance();
$time = $regedit->getVal('//modules/RetailCRM/IgnoreObjectUpdateEvent/' . $order->getObject()->getId()); $time = $regedit->getVal('//modules/RetailCRM/IgnoreObjectUpdateEvent/' . $orderObj->getObject()->getId());
if ($time == $order->getObject()->getUpdateTime() OR $time + 1 == $order->getObject()->getUpdateTime()) { if ($time == $orderObj->getObject()->getUpdateTime() OR $time + 1 == $orderObj->getObject()->getUpdateTime()) {
return; return;
} }
$config = mainConfiguration::getInstance(); $config = mainConfiguration::getInstance();
$umiOrderStatusCode = order::getCodeByStatus($order->getOrderStatus()); $umiOrderStatusCode = order::getCodeByStatus($orderObj->getOrderStatus());
$retailcrm = new RetailCRM; $relationMap = RCrmHelpers::getRelationMap($config->get('retailcrm', 'orderStatusMap'));
$crmOrderStatusCode = RCrmHelpers::getRelationByMap($relationMap, $umiOrderStatusCode);
$relationMap = $retailcrm->getRelationMap($config->get('retailcrm', 'orderStatusMap'));
$crmOrderStatusCode = $retailcrm->getRelationByMap($relationMap, $umiOrderStatusCode);
if (!$crmOrderStatusCode) { if (!$crmOrderStatusCode) {
return; return;
} }
$umiOrderPaymentType = $order->getObject()->getValue('payment_id'); $umiOrderPaymentType = $orderObj->getObject()->getValue('payment_id');
$relationOrderPaymentTypesMap = $retailcrm->getRelationMap($config->get('retailcrm', 'orderPaymentTypeMap')); $relationOrderPaymentTypesMap = RCrmHelpers::getRelationMap($config->get('retailcrm', 'orderPaymentTypeMap'));
$crmOrderPaymentType = $retailcrm->getRelationByMap($relationOrderPaymentTypesMap, $umiOrderPaymentType); $crmOrderPaymentType = RCrmHelpers::getRelationByMap($relationOrderPaymentTypesMap, $umiOrderPaymentType);
$umiOrderPaymentStatus = $order->getObject()->getValue('payment_status_id'); $umiOrderPaymentStatus = $orderObj->getObject()->getValue('payment_status_id');
$relationOrderPaymentStatusesMap = $retailcrm->getRelationMap($config->get('retailcrm', 'orderPaymentStatusMap')); $relationOrderPaymentStatusesMap = RCrmHelpers::getRelationMap($config->get('retailcrm', 'orderPaymentStatusMap'));
$crmOrderPaymentStatus = $retailcrm->getRelationByMap($relationOrderPaymentStatusesMap, $umiOrderPaymentStatus); $crmOrderPaymentStatus = RCrmHelpers::getRelationByMap($relationOrderPaymentStatusesMap, $umiOrderPaymentStatus);
$umiOrderDeliveryId = $order->getObject()->getValue('delivery_id'); $umiOrderDeliveryId = $orderObj->getObject()->getValue('delivery_id');
$relationOrderDeliveryTypesMap = $retailcrm->getRelationMap($config->get('retailcrm', 'orderDeliveryTypeMap')); $relationOrderDeliveryTypesMap = RCrmHelpers::getRelationMap($config->get('retailcrm', 'orderDeliveryTypeMap'));
$crmOrderDeliveryType = $retailcrm->getRelationByMap($relationOrderDeliveryTypesMap, $umiOrderDeliveryId); $crmOrderDeliveryType = RCrmHelpers::getRelationByMap($relationOrderDeliveryTypesMap, $umiOrderDeliveryId);
$customer = new umiObject($order->getCustomerId()); $customer = new umiObject($orderObj->getCustomerId());
$orderItems = $order->getItems(); $orderItemsObj = $orderObj->getItems();
$orderItemsToCrm = array(); $orderItems = array();
foreach ($orderItems as $orderItem) { foreach ($orderItemsObj as $orderItem) {
/** @var optionedOrderItem $orderItem */ /** @var optionedOrderItem $orderItem */
$itemProperties = array(); $itemProperties = array();
foreach ($orderItem->getOptions() as $option) {
$option = new umiObject($option['option-id']); if (get_class($orderItem) == 'optionedOrderItem') {
$itemProperties[] = array( foreach ($orderItem->getOptions() as $option) {
'name' => $option->getType()->getName(), $option = new umiObject($option['option-id']);
'value' => $option->getName() $itemProperties[] = array(
); 'name' => $option->getType()->getName(),
'value' => $option->getName()
);
}
} }
$optionGroups = $orderItem->getItemElement()->getObject()->getType()->getFieldsGroupByName('catalog_option_props')->getFields(); $optionGroups = $orderItem->getItemElement()->getObject()->getType()->getFieldsGroupByName('catalog_option_props')->getFields();
$optionGuidesToGroups = array(); $optionGuidesToGroups = array();
foreach ($optionGroups as $optionGroup) { foreach ($optionGroups as $optionGroup) {
/** @var umiField $optionGroup */ /** @var umiField $optionGroup */
$optionGuidesToGroups[$optionGroup->getGuideId()] = $optionGroup->getId(); $optionGuidesToGroups[$optionGroup->getGuideId()] = $optionGroup->getId();
} }
$options = array(); $options = array();
foreach ($orderItem->getOptions() as $option) {
$option = $objects->getObject($option['option-id']); if (get_class($orderItem) == 'optionedOrderItem') {
$options[] = $optionGuidesToGroups[$option->getTypeId()] . '_' . $option->getId(); foreach ($orderItem->getOptions() as $option) {
$option = $objects->getObject($option['option-id']);
$options[] = $optionGuidesToGroups[$option->getTypeId()] . '_' . $option->getId();
}
} }
$product = $orderItem->getItemElement(); $product = $orderItem->getItemElement();
@ -81,11 +88,25 @@ class RCrmActions
$productId = $product->getId(); $productId = $product->getId();
} }
$orderItemsToCrm[] = array( if (get_class($orderItem) == 'optionedOrderItem') {
$productName = $product->getName();
} else {
$productName = $orderItem->getName();
}
if ($orderItem->getDiscount()) {
$discount = $orderItem->getDiscount();
} else if ($orderItem->getValue('item_discount_value')) {
$discount = $orderItem->getValue('item_discount_value');
} else {
$discount = 0;
}
$orderItems[] = array(
'initialPrice' => $orderItem->getItemPrice(), 'initialPrice' => $orderItem->getItemPrice(),
'discount' => $orderItem->getDiscount(), 'discount' => $discount,
'quantity' => $orderItem->getAmount(), 'quantity' => $orderItem->getAmount(),
'productName' => $product->getName(), 'productName' => $productName,
'properties' => $itemProperties, 'properties' => $itemProperties,
'offer' => array( 'offer' => array(
'externalId' => $productId 'externalId' => $productId
@ -94,31 +115,36 @@ class RCrmActions
} }
/* One click order */ /* One click order */
if ($order->getObject()->getValue('purchaser_one_click') !== null) { if ($orderObj->getObject()->getValue('purchaser_one_click') !== null) {
$oneClickObj = new umiObject($order->getObject()->getValue('purchaser_one_click')); $oneClickObj = new umiObject($orderObj->getObject()->getValue('purchaser_one_click'));
$orderToCrm = array( $order = array(
'number' => $order->getObject()->getValue('number'), 'number' => $orderObj->getObject()->getValue('number'),
'externalId' => $order->getId(), 'externalId' => $orderObj->getId(),
'lastName' => $oneClickObj->getValue('lname'),
'firstName' => $oneClickObj->getValue('fname'),
'patronymic' => $oneClickObj->getValue('father_name'),
'phone' => $oneClickObj->getValue('phone'), 'phone' => $oneClickObj->getValue('phone'),
'customer' => array( 'customer' => array(
'externalId' => $customer->getId() 'externalId' => $customer->getId()
), ),
'paymentType' => $crmOrderPaymentType, 'items' => $orderItems,
'paymentStatus' => $crmOrderPaymentStatus,
'status' => $crmOrderStatusCode,
'items' => $orderItemsToCrm,
'orderMethod' => 'one-click' 'orderMethod' => 'one-click'
); );
} else { } else {
if ($order->getObject()->getValue('delivery_address') !== null) { if ($orderObj->getObject()->getValue('delivery_address') !== null) {
$deliveryObjId = $order->getObject()->getValue('delivery_address'); $deliveryObjId = $orderObj->getObject()->getValue('delivery_address');
$deliveryObj = new umiObject($deliveryObjId); $deliveryObj = new umiObject($deliveryObjId);
if ($deliveryObj->getValue('country') !== false) { if ($deliveryObj->getValue('country') !== null) {
$deliveryCountryObjId = $deliveryObj->getValue('country'); $deliveryCountryObjId = $deliveryObj->getValue('country');
$deliveryCountryObj = new umiObject($deliveryCountryObjId);
$deliveryCountryIsoCode = $deliveryCountryObj->getValue('country_iso_code'); try {
$deliveryCountryObj = new umiObject($deliveryCountryObjId);
$deliveryCountryIsoCode = $deliveryCountryObj->getValue('country_iso_code');
} catch (Exception $e) {
$deliveryCountryIsoCode = '';
}
} else { } else {
$deliveryCountryIsoCode = ''; $deliveryCountryIsoCode = '';
} }
@ -152,7 +178,7 @@ class RCrmActions
$deliveryCity = ''; $deliveryCity = '';
} }
$addressToCrm = array( $deliveryAddress = array(
'countryIso' => $deliveryCountryIsoCode, 'countryIso' => $deliveryCountryIsoCode,
'index' => $deliveryIndex, 'index' => $deliveryIndex,
'region' => $deliveryRegion, 'region' => $deliveryRegion,
@ -163,111 +189,142 @@ class RCrmActions
'house' => $deliveryHouse, 'house' => $deliveryHouse,
'notes' => $deliveryNotes 'notes' => $deliveryNotes
); );
} else { } else {
$addressToCrm = array(); $deliveryAddress = array();
} }
$orderToCrm = array( $order = array(
'number' => $order->getObject()->getValue('number'), 'number' => $orderObj->getObject()->getValue('number'),
'externalId' => $order->getId(), 'externalId' => $orderObj->getId(),
'lastName' => $customer->getValue('lname'), 'lastName' => $customer->getValue('lname'),
'firstName' => $customer->getValue('fname'), 'firstName' => $customer->getValue('fname'),
'patronymic' => $customer->getValue('father_name'), 'patronymic' => $customer->getValue('father_name'),
'phone' => $customer->getValue('phone'), 'phone' => $customer->getValue('phone'),
'email' => $customer->getValue('email'),
'customer' => array( 'customer' => array(
'externalId' => $customer->getId() 'externalId' => $customer->getId()
), ),
'paymentType' => $crmOrderPaymentType, 'items' => $orderItems,
'paymentStatus' => $crmOrderPaymentStatus,
'status' => $crmOrderStatusCode,
'items' => $orderItemsToCrm,
'delivery' => array( 'delivery' => array(
'address' => $addressToCrm, 'address' => $deliveryAddress,
'code' => $crmOrderDeliveryType
) )
); );
} }
if ($crmOrderStatusCode && $crmOrderStatusCode != 'none') {
$order['status'] = $crmOrderStatusCode;
}
if ($crmOrderDeliveryType && $crmOrderDeliveryType != 'none') {
$order['delivery']['code'] = $crmOrderDeliveryType;
}
if ($crmOrderPaymentType && $crmOrderPaymentType != 'none') {
$order['paymentType'] = $crmOrderPaymentType;
}
if ($crmOrderPaymentStatus && $crmOrderPaymentStatus != 'none') {
$order['paymentStatus'] = $crmOrderPaymentStatus;
}
if ($customer->getTypeGUID() == 'emarket-customer') {
$email = $customer->getValue('email');
} else if ($customer->getTypeGUID() == 'users-user') {
$email = $customer->getValue('e-mail');
} else {
$email = '';
}
if ($email = filter_var($email, FILTER_VALIDATE_EMAIL)) {
$order['email'] = $email;
}
if ($deliveryCost = $orderObj->getValue('delivery_price')) {
$order['delivery']['cost'] = $deliveryCost;
}
// TODO: есть возможность учитывать домен // TODO: есть возможность учитывать домен
$api = new RCrmProxy( $api = new RCrmProxy(
$config->get('retailcrm', 'crmUrl'), $config->get('retailcrm', 'crmUrl'),
$config->get('retailcrm', 'apiKey'), $config->get('retailcrm', 'apiKey')
__DIR__ . '/../../../retailcrm.error.log'
); );
if ($mode == 'create') { $response = $api->ordersGet($order['externalId']);
$orderToCrm = self::customerPrepare($orderToCrm); $order = self::customerPrepare($order);
$api->ordersCreate($orderToCrm);
} else if ($mode == 'edit') { if ($response->isSuccessful()) {
$api->ordersEdit($orderToCrm); $api->ordersEdit($order);
} else {
$api->ordersCreate($order);
} }
} }
public static function customerPrepare($orderToCrm) { /**
* @param array $order
* @return array
*/
public static function customerPrepare(array $order) {
$config = mainConfiguration::getInstance(); $config = mainConfiguration::getInstance();
/** @var RCrmApiClient $api */
$api = new RCrmProxy( $api = new RCrmProxy(
$config->get('retailcrm', 'crmUrl'), $config->get('retailcrm', 'crmUrl'),
$config->get('retailcrm', 'apiKey'), $config->get('retailcrm', 'apiKey')
__DIR__ . '/../../../retailcrm.error.log'
); );
$crmCustomer = $api->customersGet($orderToCrm['customer']['externalId']); $crmCustomer = $api->customersGet(
$order['customer']['externalId']
);
if (!$crmCustomer) { if (!$crmCustomer->isSuccessful()) {
$crmCustomers = $api->customersList(array( $crmCustomers = $api->customersList(array(
'name' => $orderToCrm['phone'], 'name' => $order['phone'],
'email' => $orderToCrm['email'] 'email' => $order['email']
)); ));
$foundedCustomerExternalId = false; $foundedCustomerExternalId = false;
if ($crmCustomers) { if ($crmCustomers->isSuccessful()) {
/** @var RCrmApiResponse $crmCustomers */ $crmCustomers = $crmCustomers->offsetGet('customers');
$crmCustomers = $crmCustomers->getCustomers();
if (count($crmCustomers) > 0) { if (count($crmCustomers) > 0) {
foreach ($crmCustomers as $crmCustomer) { foreach ($crmCustomers as $crmCustomer) {
if (isset($crmCustomer['externalId']) && $crmCustomer['externalId'] > 0) { if (isset($crmCustomer['externalId']) && $crmCustomer['externalId'] > 0) {
$foundedCustomerExternalId = true; $foundedCustomerExternalId = true;
$orderToCrm['customer']['externalId'] = $crmCustomer['externalId']; $order['customer']['externalId'] = $crmCustomer['externalId'];
break; break;
} }
} }
if (!$foundedCustomerExternalId) { if (!$foundedCustomerExternalId) {
$crmCustomer = $crmCustomers[0];
$status = $api->customersFixExternalIds(array( $status = $api->customersFixExternalIds(array(
'id' => $crmCustomer['id'], 'id' => $crmCustomers[0]['id'],
'externalId' => $crmCustomer['externalId'] 'externalId' => $crmCustomers[0]['externalId']
)); ));
if (!$status) { if (!$status->isSuccessful()) {
unset($orderToCrm['customer']); unset($order['customer']);
} }
} }
} else { } else {
$status = $api->customersCreate(array( $status = $api->customersCreate(array(
'externalId' => $orderToCrm['customer']['externalId'], 'externalId' => $order['customer']['externalId'],
'firstName' => $orderToCrm['firstName'], 'firstName' => $order['firstName'],
'lastName' => $orderToCrm['lastName'], 'lastName' => $order['lastName'],
'patronymic' => $orderToCrm['patronymic'], 'patronymic' => $order['patronymic'],
'email' => $orderToCrm['email'], 'email' => $order['email'],
'phones' => array( 'phones' => array(
'number' => $orderToCrm['phone'] 'number' => $order['phone']
) )
)); ));
if (!$status) { if (!$status->isSuccessful()) {
unset($orderToCrm['customer']); unset($order['customer']);
} }
} }
} else { } else {
unset($orderToCrm['customer']); unset($order['customer']);
} }
} }
return $orderToCrm; return $order;
} }
} }

View File

View File

View File

View File

@ -1,13 +1,13 @@
<?php <?php
abstract class RCrmHelpers class RCrmHelpers
{ {
/** /**
* @param $mapArr array * @param $mapArr array
* @return array * @return array
*/ */
public function getRelationMap($mapArr) public static function getRelationMap($mapArr)
{ {
if (empty($mapArr)) { if (empty($mapArr)) {
return array(); return array();
@ -28,7 +28,7 @@ abstract class RCrmHelpers
* @param $reversed bool * @param $reversed bool
* @return string|null * @return string|null
*/ */
public function getRelationByMap($map, $item, $reversed = false) public static function getRelationByMap($map, $item, $reversed = false)
{ {
if (!$reversed) { if (!$reversed) {
if (isset($map[$item]) && !empty($map[$item])) { if (isset($map[$item]) && !empty($map[$item])) {
@ -50,7 +50,7 @@ abstract class RCrmHelpers
* @param $orderHistory array * @param $orderHistory array
* @return array * @return array
*/ */
public function getAssemblyOrder($orderHistory) public static function getAssemblyOrder($orderHistory)
{ {
if (file_exists(__DIR__ . '/../../data/objects.xml')) { if (file_exists(__DIR__ . '/../../data/objects.xml')) {
$objects = simplexml_load_file(__DIR__ . '/../../data/objects.xml'); $objects = simplexml_load_file(__DIR__ . '/../../data/objects.xml');
@ -62,7 +62,7 @@ abstract class RCrmHelpers
$orders = array(); $orders = array();
foreach ($orderHistory as $change) { foreach ($orderHistory as $change) {
$change['order'] = $this->removeEmpty($change['order']); $change['order'] = self::removeEmpty($change['order']);
$orderId = $change['order']['id']; $orderId = $change['order']['id'];
@ -106,24 +106,24 @@ abstract class RCrmHelpers
$orders[$orderId]['items'][$itemId]['deleted'] = true; $orders[$orderId]['items'][$itemId]['deleted'] = true;
} }
if (!$orders[$orderId]['items'][$itemId]['created'] && $fields['item'][$change['field']]) { if (!$orders[$orderId]['items'][$itemId]['created'] && isset($fields['item']) && $fields['item'][$change['field']]) {
$orders[$orderId]['items'][$itemId][$fields['item'][$change['field']]] = $change['newValue']; $orders[$orderId]['items'][$itemId][$fields['item'][$change['field']]] = $change['newValue'];
} }
} else { } else {
if (isset($fields['delivery'][$change['field']]) && $fields['delivery'][$change['field']] == 'service') { if (isset($fields['delivery'][$change['field']]) && $fields['delivery'][$change['field']] == 'service') {
$orders[$orderId]['delivery']['service']['code'] = $this->historyNewValue($change['newValue']); $orders[$orderId]['delivery']['service']['code'] = self::historyNewValue($change['newValue']);
} elseif (isset($fields['delivery'][$change['field']])) { } elseif (isset($fields['delivery'][$change['field']])) {
$orders[$orderId]['delivery'][$fields['delivery'][$change['field']]] = $this->historyNewValue($change['newValue']); $orders[$orderId]['delivery'][$fields['delivery'][$change['field']]] = self::historyNewValue($change['newValue']);
} elseif (isset($fields['orderAddress'][$change['field']])) { } elseif (isset($fields['orderAddress'][$change['field']])) {
$orders[$orderId]['delivery']['address'][$fields['orderAddress'][$change['field']]] = $change['newValue']; $orders[$orderId]['delivery']['address'][$fields['orderAddress'][$change['field']]] = $change['newValue'];
} elseif (isset($fields['integrationDelivery'][$change['field']])) { } elseif (isset($fields['integrationDelivery'][$change['field']])) {
$orders[$orderId]['delivery']['service'][$fields['integrationDelivery'][$change['field']]] = $this->historyNewValue($change['newValue']); $orders[$orderId]['delivery']['service'][$fields['integrationDelivery'][$change['field']]] = self::historyNewValue($change['newValue']);
} elseif (isset($fields['customerContragent'][$change['field']])) { } elseif (isset($fields['customerContragent'][$change['field']])) {
$orders[$orderId][$fields['customerContragent'][$change['field']]] = $this->historyNewValue($change['newValue']); $orders[$orderId][$fields['customerContragent'][$change['field']]] = self::historyNewValue($change['newValue']);
} elseif (strripos($change['field'], 'custom_') !== false) { } elseif (strripos($change['field'], 'custom_') !== false) {
$orders[$orderId]['customFields'][str_replace('custom_', '', $change['field'])] = $this->historyNewValue($change['newValue']); $orders[$orderId]['customFields'][str_replace('custom_', '', $change['field'])] = self::historyNewValue($change['newValue']);
} elseif (isset($fields['order'][$change['field']])) { } elseif (isset($fields['order'][$change['field']])) {
$orders[$orderId][$fields['order'][$change['field']]] = $this->historyNewValue($change['newValue']); $orders[$orderId][$fields['order'][$change['field']]] = self::historyNewValue($change['newValue']);
} }
if (isset($change['created'])) { if (isset($change['created'])) {
@ -143,7 +143,7 @@ abstract class RCrmHelpers
* @param $value mixed * @param $value mixed
* @return string * @return string
*/ */
public function historyNewValue($value) public static function historyNewValue($value)
{ {
if (isset($value['code'])) { if (isset($value['code'])) {
return $value['code']; return $value['code'];
@ -156,14 +156,14 @@ abstract class RCrmHelpers
* @param $inputArray mixed * @param $inputArray mixed
* @return array * @return array
*/ */
public function removeEmpty($inputArray) public static function removeEmpty($inputArray)
{ {
$outputArray = array(); $outputArray = array();
if (!empty($inputArray)) { if (!empty($inputArray)) {
foreach ($inputArray as $key => $element) { foreach ($inputArray as $key => $element) {
if (!empty($element) || $element === 0 || $element === '0') { if (!empty($element) || $element === 0 || $element === '0') {
if (is_array($element)) { if (is_array($element)) {
$element = $this->removeEmpty($element); $element = self::removeEmpty($element);
} }
$outputArray[$key] = $element; $outputArray[$key] = $element;
} }

View File

@ -5,20 +5,21 @@ class RCrmHistory
/** @var RCrmApiClient $api */ /** @var RCrmApiClient $api */
private $api = null; private $api = null;
/**
* RCrmHistory constructor.
*/
public function __construct() public function __construct()
{ {
$config = mainConfiguration::getInstance(); $config = mainConfiguration::getInstance();
$this->api = new RCrmProxy( $this->api = new RCrmProxy(
$config->get('retailcrm', 'crmUrl'), $config->get('retailcrm', 'crmUrl'),
$config->get('retailcrm', 'apiKey'), $config->get('retailcrm', 'apiKey')
__DIR__ . '/../../../retailcrm.error.log'
); );
} }
public function runOrders() public function runOrders()
{ {
$retailcrm = new RetailCRM;
$regedit = regedit::getInstance(); $regedit = regedit::getInstance();
$config = mainConfiguration::getInstance(); $config = mainConfiguration::getInstance();
@ -35,7 +36,7 @@ class RCrmHistory
$response = $this->api->ordersHistory(array('sinceId' => $historyLastId), $historyPage); $response = $this->api->ordersHistory(array('sinceId' => $historyLastId), $historyPage);
$historyPage++; $historyPage++;
if (!is_null($response) && count($response['history'])) { if ($response->isSuccessful() && count($response['history'])) {
$historyArray = array_merge($historyArray, $response['history']); $historyArray = array_merge($historyArray, $response['history']);
} else { } else {
break; break;
@ -45,7 +46,7 @@ class RCrmHistory
if (count($historyArray)) { if (count($historyArray)) {
$lastChange = end($historyArray); $lastChange = end($historyArray);
$crmOrders = $retailcrm->getAssemblyOrder($historyArray); $crmOrders = RCrmHelpers::getAssemblyOrder($historyArray);
$objectTypes = umiObjectTypesCollection::getInstance(); $objectTypes = umiObjectTypesCollection::getInstance();
$objects = umiObjectsCollection::getInstance(); $objects = umiObjectsCollection::getInstance();
@ -65,12 +66,32 @@ class RCrmHistory
$order = order::create(); $order = order::create();
/* Order create date */ /* Order create date */
$order->getObject()->getPropByName('order_date')->setValue(umiDate::getTimeStamp($crmOrder['createdAt'])); $order->getObject()->setValue('order_date', umiDate::getTimeStamp($crmOrder['createdAt']));
if (!empty($crmOrder['number'])) {
$order->setName($crmOrder['number']);
} else {
$order->generateNumber();
$order->setName($order->getName() . ' ' . $crmOrder['id'] . "-retailcrm");
}
$this->api->ordersFixExternalIds(array(
array(
'id' => $crmOrder['id'],
'externalId' => $order->getId()
)
));
}
if (!$order) {
continue;
}
if (isset($crmOrder['customer'])) {
$crmCustomer = $crmOrder['customer']; $crmCustomer = $crmOrder['customer'];
if (isset($crmCustomer['externalId']) && $crmCustomer['externalId'] > 0) { if (isset($crmCustomer['externalId']) && $crmCustomer['externalId'] > 0) {
// TODO: проверить существует ли такой пользователь в системе, если нет, то создать, т.к. принимая customer externalId мы считаем, что такой пользователь уже есть // TODO: проверить существует ли такой пользователь в системе, если нет, то создать, т.к. принимая customer externalId мы считаем, что такой пользователь уже есть
$order->getObject()->getPropByName('customer_id')->setValue($crmCustomer['externalId']); $order->getObject()->setValue('customer_id', $crmCustomer['externalId']);
} else { } else {
$customer = $objects->getObjectByName($crmCustomer['id'] . '-retailcrm'); $customer = $objects->getObjectByName($crmCustomer['id'] . '-retailcrm');
@ -90,23 +111,31 @@ class RCrmHistory
$expirations->add($customerId, customer::$defaultExpiration); $expirations->add($customerId, customer::$defaultExpiration);
if (!empty($crmCustomer['firstName'])) { if (!empty($crmCustomer['firstName'])) {
$customer->getPropByName('fname')->setValue($crmCustomer['firstName']); $customer->setValue('fname', $crmCustomer['firstName']);
} }
if (!empty($crmCustomer['lastName'])) { if (!empty($crmCustomer['lastName'])) {
$customer->getPropByName('lname')->setValue($crmCustomer['lastName']); $customer->setValue('lname', $crmCustomer['lastName']);
} }
if (!empty($crmCustomer['patronymic'])) { if (!empty($crmCustomer['patronymic'])) {
$customer->getPropByName('father_name')->setValue($crmCustomer['patronymic']); $customer->setValue('father_name', $crmCustomer['patronymic']);
} }
if (!empty($crmCustomer['email'])) { if (!empty($crmCustomer['email'])) {
$customer->getPropByName('email')->setValue($crmCustomer['email']); if ($customer->getTypeGUID() == 'emarket-customer') {
$customer->setValue('email', $crmCustomer['email']);
} else {
if ($customer->getTypeGUID() == 'users-user') {
$customer->setValue('e-mail', $crmCustomer['email']);
} else {
$customer->setValue('email', $crmCustomer['email']);
}
}
} }
if (isset($crmCustomer['phones']) && count($crmCustomer['phones']) > 0) { if (isset($crmCustomer['phones']) && count($crmCustomer['phones']) > 0) {
$customer->getPropByName('phone')->setValue($crmCustomer['phones'][0]['number']); $customer->setValue('phone', $crmCustomer['phones'][0]['number']);
} }
if (isset($crmCustomer['address'])) { if (isset($crmCustomer['address'])) {
@ -133,56 +162,61 @@ class RCrmHistory
$countryCode = $country->getValue('country_iso_code'); $countryCode = $country->getValue('country_iso_code');
if ($crmCustomerAddress['countryIso'] == $countryCode) { if ($crmCustomerAddress['countryIso'] == $countryCode) {
$deliveryObject->getPropByName('country')->setValue($country->getId()); $deliveryObject->setValue('country', $country->getId());
break; break;
} }
} }
} }
if (!empty($crmCustomerAddress['index'])) { if (!empty($crmCustomerAddress['index'])) {
$deliveryObject->getPropByName('index')->setValue($crmCustomerAddress['index']); $deliveryObject->setValue('index', $crmCustomerAddress['index']);
} }
if (!empty($crmCustomerAddress['region'])) { if (!empty($crmCustomerAddress['region'])) {
$deliveryObject->getPropByName('region')->setValue($crmCustomerAddress['region']); $deliveryObject->setValue('region', $crmCustomerAddress['region']);
} }
if (!empty($crmCustomerAddress['city'])) { if (!empty($crmCustomerAddress['city'])) {
$deliveryObject->getPropByName('city')->setValue($crmCustomerAddress['city']); $deliveryObject->setValue('city', $crmCustomerAddress['city']);
} }
if (!empty($crmCustomerAddress['street'])) { if (!empty($crmCustomerAddress['street'])) {
$deliveryObject->getPropByName('street')->setValue($crmCustomerAddress['street']); $deliveryObject->setValue('street', $crmCustomerAddress['street']);
} }
if (!empty($crmCustomerAddress['building'])) { if (!empty($crmCustomerAddress['building'])) {
$deliveryObject->getPropByName('house')->setValue($crmCustomerAddress['building']); $deliveryObject->setValue('house', $crmCustomerAddress['building']);
} }
if (!empty($crmCustomerAddress['flat'])) { if (!empty($crmCustomerAddress['flat'])) {
$deliveryObject->getPropByName('flat')->setValue($crmCustomerAddress['flat']); $deliveryObject->setValue('flat', $crmCustomerAddress['flat']);
} }
$deliveryAddresses = array( $deliveryAddresses = array(
0 => $deliveryObject->getId() 0 => $deliveryObject->getId()
); );
$customer->getPropByName('delivery_addresses')->setValue($deliveryAddresses); $customer->setValue('delivery_addresses', $deliveryAddresses);
} }
} }
$order->getObject()->getPropByName('customer_id')->setValue($customer->getId()); $order->getObject()->setValue('customer_id', $customer->getId());
} }
}
if (isset($crmOrder['items']) && count($crmOrder['items']) > 0) {
$orderItems = $order->getItems(); $orderItems = $order->getItems();
foreach ($orderItems as $orderItem) { foreach ($orderItems as $orderItem) {
$order->removeItem($orderItem); $order->removeItem($orderItem);
} }
$crmItems = $crmOrder['items']; $crmOrderForItems = $this->api->ordersGet($crmOrder['externalId'])->offsetGet('order');
$crmItems = $crmOrderForItems['items'];
foreach ($crmItems as $crmItem) { foreach ($crmItems as $crmItem) {
if (isset($crmItem['deleted']) && $crmItem['deleted'] == true) { if (isset($crmItem['deleted']) && $crmItem['deleted'] == true) {
continue; continue;
} }
if (!isset($crmItem['offer']['externalId'])) { if (!isset($crmItem['offer']['externalId'])) {
continue; continue;
} }
@ -195,6 +229,7 @@ class RCrmHistory
$itemOptions = $data[1]; $itemOptions = $data[1];
$itemOptions = explode('-', $itemOptions); $itemOptions = explode('-', $itemOptions);
foreach ($itemOptions as $itemOption) { foreach ($itemOptions as $itemOption) {
$itemOption = explode('_', $itemOption); $itemOption = explode('_', $itemOption);
$itemOptionGroupId = $itemOption[0]; $itemOptionGroupId = $itemOption[0];
@ -209,255 +244,121 @@ class RCrmHistory
/** @var optionedOrderItem $orderItem */ /** @var optionedOrderItem $orderItem */
$orderItem->setAmount($crmItem['quantity']); $orderItem->setAmount($crmItem['quantity']);
$order->appendItem($orderItem); $order->appendItem($orderItem);
} }
if (isset($crmOrder['paymentType'])) {
$relationOrderPaymentTypesMap = $retailcrm->getRelationMap($config->get('retailcrm', 'orderPaymentTypeMap'));
$umiOrderPaymentType = $retailcrm->getRelationByMap($relationOrderPaymentTypesMap, $crmOrder['paymentType'], true);
$order->getObject()->getPropByName('payment_id')->setValue($umiOrderPaymentType);
}
if (isset($crmOrder['paymentStatus'])) {
$relationOrderPaymentStatusesMap = $retailcrm->getRelationMap($config->get('retailcrm', 'orderPaymentStatusMap'));
$umiOrderPaymentStatus = $retailcrm->getRelationByMap($relationOrderPaymentStatusesMap, $crmOrder['paymentStatus'], true);
$order->getObject()->getPropByName('payment_status_id')->setValue($umiOrderPaymentStatus);
}
if (isset($crmOrder['delivery']['cost'])) {
$order->getObject()->getPropByName('delivery_price')->setValue($crmOrder['delivery']['cost']);
}
if (isset($crmOrder['delivery']['code'])) {
$relationOrderDeliveryTypesMap = $retailcrm->getRelationMap($config->get('retailcrm', 'orderDeliveryTypeMap'));
$umiOrderDeliveryType = $retailcrm->getRelationByMap($relationOrderDeliveryTypesMap, $crmOrder['delivery']['code'], true);
$order->getObject()->getPropByName('delivery_id')->setValue($umiOrderDeliveryType);
}
if (isset($crmOrder['delivery']['address']) && count($crmOrder['delivery']['address'])) {
$crmDeliveryAddress = $crmOrder['delivery']['address'];
$deliveryTypeId = $objectTypes->getTypeIdByGUID('emarket-deliveryaddress');
$deliveryObjectId = $objects->addObject('Address for order ' . $order->getId(), $deliveryTypeId);
$deliveryObject = $objects->getObject($deliveryObjectId);
if (!empty($crmDeliveryAddress['countryIso'])) {
$selector = new selector('objects');
try {
$selector->types('object-type')->id($config->get('retailcrm', 'countryGuideId'));
$countries = $selector->result();
foreach ($countries as $country) {
/** @var umiObject $country */
$countryCode = $country->getValue('country_iso_code');
if ($crmDeliveryAddress['countryIso'] == $countryCode) {
$deliveryObject->getPropByName('country')->setValue($country->getId());
break;
}
}
} catch (selectorException $e) {}
}
if (!empty($crmDeliveryAddress['index'])) {
$deliveryObject->getPropByName('index')->setValue($crmDeliveryAddress['index']);
}
if (!empty($crmDeliveryAddress['region'])) {
$deliveryObject->getPropByName('region')->setValue($crmDeliveryAddress['region']);
}
if (!empty($crmDeliveryAddress['city'])) {
$deliveryObject->getPropByName('city')->setValue($crmDeliveryAddress['city']);
}
if (!empty($crmDeliveryAddress['street'])) {
$deliveryObject->getPropByName('street')->setValue($crmDeliveryAddress['street']);
}
if (!empty($crmDeliveryAddress['building'])) {
$deliveryObject->getPropByName('house')->setValue($crmDeliveryAddress['building']);
}
if (!empty($crmDeliveryAddress['flat'])) {
$deliveryObject->getPropByName('flat')->setValue($crmDeliveryAddress['flat']);
}
$order->getObject()->getPropByName('delivery_address')->setValue($deliveryObject->getId());
}
if (!empty($crmOrder['number'])) {
$order->setName($crmOrder['number']);
} else {
$order->generateNumber();
$order->setName($order->getName() . ' ' . $crmOrder['id'] . "-retailcrm");
}
$this->api->ordersFixExternalIds(array(
array(
'id' => $crmOrder['id'],
'externalId' => $order->getId()
)
));
} else {
if (!$order) {
continue;
}
if (isset($crmOrder['items']) && count($crmOrder['items']) > 0) {
$orderItems = $order->getItems();
foreach ($orderItems as $orderItem) {
$order->removeItem($orderItem);
}
$crmOrderForItems = $this->api->ordersGet($crmOrder['externalId'])->getOrder();
$crmItems = $crmOrderForItems['items'];
foreach ($crmItems as $crmItem) {
if (isset($crmItem['deleted']) && $crmItem['deleted'] == true) {
continue;
}
if (!isset($crmItem['offer']['externalId'])) {
continue;
}
if (mb_strpos($crmItem['offer']['externalId'], '#')) {
$data = explode('#', $crmItem['offer']['externalId']);
$itemId = $data[0];
$orderItem = orderItem::create($itemId);
$itemOptions = $data[1];
$itemOptions = explode('-', $itemOptions);
foreach ($itemOptions as $itemOption) {
$itemOption = explode('_', $itemOption);
$itemOptionGroupId = $itemOption[0];
$itemOptionValue = $itemOption[1];
$itemOptionObject = new umiField($itemOptionGroupId);
$orderItem->appendOption($itemOptionObject->getName(), $itemOptionValue);
}
} else {
$orderItem = orderItem::create($crmItem['offer']['externalId']);
}
/** @var optionedOrderItem $orderItem */
$orderItem->setAmount($crmItem['quantity']);
$order->appendItem($orderItem);
}
}
$customer = $objects->getObject($order->getCustomerId());
if (isset($crmOrder['phone'])) {
$customer->getPropByName('phone')->setValue($crmOrder['phone']);
}
if (isset($crmOrder['lastName'])) {
$customer->getPropByName('lname')->setValue($crmOrder['lastName']);
}
if (isset($crmOrder['firstName'])) {
$customer->getPropByName('fname')->setValue($crmOrder['firstName']);
}
if (isset($crmOrder['patronymic'])) {
$customer->getPropByName('father_name')->setValue($crmOrder['patronymic']);
}
if (isset($crmOrder['e-mail'])) {
$customer->getPropByName('e-mail')->setValue($crmOrder['e-mail']);
}
if (isset($crmOrder['paymentType'])) {
$relationOrderPaymentTypesMap = $retailcrm->getRelationMap($config->get('retailcrm', 'orderPaymentTypeMap'));
$umiOrderPaymentType = $retailcrm->getRelationByMap($relationOrderPaymentTypesMap, $crmOrder['paymentType'], true);
$order->getObject()->getPropByName('payment_id')->setValue($umiOrderPaymentType);
}
if (isset($crmOrder['paymentStatus'])) {
$relationOrderPaymentStatusesMap = $retailcrm->getRelationMap($config->get('retailcrm', 'orderPaymentStatusMap'));
$umiOrderPaymentStatus = $retailcrm->getRelationByMap($relationOrderPaymentStatusesMap, $crmOrder['paymentStatus'], true);
$order->getObject()->getPropByName('payment_status_id')->setValue($umiOrderPaymentStatus);
}
if (isset($crmOrder['delivery']['cost'])) {
$order->getObject()->getPropByName('delivery_price')->setValue($crmOrder['delivery']['cost']);
}
if (isset($crmOrder['delivery']['code'])) {
$relationOrderDeliveryTypesMap = $retailcrm->getRelationMap($config->get('retailcrm', 'orderDeliveryTypeMap'));
$umiOrderDeliveryType = $retailcrm->getRelationByMap($relationOrderDeliveryTypesMap, $crmOrder['delivery']['code'], true);
$order->getObject()->getPropByName('delivery_id')->setValue($umiOrderDeliveryType);
}
if (isset($crmOrder['delivery']['address']) && count($crmOrder['delivery']['address'])) {
$crmDeliveryAddress = $crmOrder['delivery']['address'];
$deliveryTypeId = $objectTypes->getTypeIdByGUID('emarket-deliveryaddress');
$deliveryObject = $objects->getObjectByName('Address for order ' . $order->getId());
if (!$deliveryObject) {
$deliveryObjectId = $objects->addObject('Address for order ' . $order->getId(), $deliveryTypeId);
$deliveryObject = $objects->getObject($deliveryObjectId);
}
if (!empty($crmDeliveryAddress['countryIso'])) {
$selector = new selector('objects');
$selector->types('object-type')->id($config->get('retailcrm', 'countryGuideId'));
$countries = $selector->result();
foreach ($countries as $country) {
/** @var umiObject $country */
$countryCode = $country->getValue('country_iso_code');
if ($crmDeliveryAddress['countryIso'] == $countryCode) {
$deliveryObject->getPropByName('country')->setValue($country->getId());
break;
}
}
}
if (!empty($crmDeliveryAddress['index'])) {
$deliveryObject->getPropByName('index')->setValue($crmDeliveryAddress['index']);
}
if (!empty($crmDeliveryAddress['region'])) {
$deliveryObject->getPropByName('region')->setValue($crmDeliveryAddress['region']);
}
if (!empty($crmDeliveryAddress['city'])) {
$deliveryObject->getPropByName('city')->setValue($crmDeliveryAddress['city']);
}
if (!empty($crmDeliveryAddress['street'])) {
$deliveryObject->getPropByName('street')->setValue($crmDeliveryAddress['street']);
}
if (!empty($crmDeliveryAddress['building'])) {
$deliveryObject->getPropByName('house')->setValue($crmDeliveryAddress['building']);
}
if (!empty($crmDeliveryAddress['flat'])) {
$deliveryObject->getPropByName('flat')->setValue($crmDeliveryAddress['flat']);
}
$order->getObject()->getPropByName('delivery_address')->setValue($deliveryObject->getId());
}
} }
if (!$order) { $customer = $objects->getObject($order->getCustomerId());
continue;
if (isset($crmOrder['phone'])) {
$customer->setValue('phone', $crmOrder['phone']);
}
if (isset($crmOrder['lastName'])) {
$customer->setValue('lname', $crmOrder['lastName']);
}
if (isset($crmOrder['firstName'])) {
$customer->setValue('fname', $crmOrder['firstName']);
}
if (isset($crmOrder['patronymic'])) {
$customer->setValue('father_name', $crmOrder['patronymic']);
}
if (!empty($crmCustomer['email'])) {
if ($customer->getTypeGUID() == 'emarket-customer') {
$customer->setValue('email', $crmCustomer['email']);
} else if ($customer->getTypeGUID() == 'users-user') {
$customer->setValue('e-mail', $crmCustomer['email']);
} else {
$customer->setValue('email', $crmCustomer['email']);
}
}
if (isset($crmOrder['paymentType'])) {
$relationOrderPaymentTypesMap = RCrmHelpers::getRelationMap($config->get('retailcrm', 'orderPaymentTypeMap'));
$umiOrderPaymentType = RCrmHelpers::getRelationByMap($relationOrderPaymentTypesMap, $crmOrder['paymentType'], true);
$order->getObject()->setValue('payment_id', $umiOrderPaymentType);
}
if (isset($crmOrder['paymentStatus'])) {
$relationOrderPaymentStatusesMap = RCrmHelpers::getRelationMap($config->get('retailcrm', 'orderPaymentStatusMap'));
$umiOrderPaymentStatus = RCrmHelpers::getRelationByMap($relationOrderPaymentStatusesMap, $crmOrder['paymentStatus'], true);
$order->getObject()->setValue('payment_status_id', $umiOrderPaymentStatus);
}
if (isset($crmOrder['delivery']['cost'])) {
$order->getObject()->setValue('delivery_price', $crmOrder['delivery']['cost']);
}
if (isset($crmOrder['delivery']['code'])) {
$relationOrderDeliveryTypesMap = RCrmHelpers::getRelationMap($config->get('retailcrm', 'orderDeliveryTypeMap'));
$umiOrderDeliveryType = RCrmHelpers::getRelationByMap($relationOrderDeliveryTypesMap, $crmOrder['delivery']['code'], true);
$order->getObject()->setValue('delivery_id', $umiOrderDeliveryType);
}
if (isset($crmOrder['delivery']['address']) && count($crmOrder['delivery']['address'])) {
$crmDeliveryAddress = $crmOrder['delivery']['address'];
$deliveryTypeId = $objectTypes->getTypeIdByGUID('emarket-deliveryaddress');
$deliveryObject = $objects->getObjectByName('Address for order ' . $order->getId());
if (!$deliveryObject) {
$deliveryObjectId = $objects->addObject('Address for order ' . $order->getId(), $deliveryTypeId);
$deliveryObject = $objects->getObject($deliveryObjectId);
}
if (!empty($crmDeliveryAddress['countryIso'])) {
$selector = new selector('objects');
$selector->types('object-type')->id($config->get('retailcrm', 'countryGuideId'));
$countries = $selector->result();
foreach ($countries as $country) {
/** @var umiObject $country */
$countryCode = $country->getValue('country_iso_code');
if ($crmDeliveryAddress['countryIso'] == $countryCode) {
$deliveryObject->setValue('country', $country->getId());
break;
}
}
}
if (!empty($crmDeliveryAddress['index'])) {
$deliveryObject->setValue('index', $crmDeliveryAddress['index']);
}
if (!empty($crmDeliveryAddress['region'])) {
$deliveryObject->setValue('region', $crmDeliveryAddress['region']);
}
if (!empty($crmDeliveryAddress['city'])) {
$deliveryObject->setValue('city', $crmDeliveryAddress['city']);
}
if (!empty($crmDeliveryAddress['street'])) {
$deliveryObject->setValue('street', $crmDeliveryAddress['street']);
}
if (!empty($crmDeliveryAddress['building'])) {
$deliveryObject->setValue('house', $crmDeliveryAddress['building']);
}
if (!empty($crmDeliveryAddress['flat'])) {
$deliveryObject->setValue('flat', $crmDeliveryAddress['flat']);
}
$order->getObject()->setValue('delivery_address', $deliveryObject->getId());
} }
$regedit->setVal('//modules/RetailCRM/IgnoreObjectUpdateEvent/' . $order->getObject()->getId(), time()); $regedit->setVal('//modules/RetailCRM/IgnoreObjectUpdateEvent/' . $order->getObject()->getId(), time());
if (isset($crmOrder['status'])) { if (isset($crmOrder['status'])) {
$relationMap = $retailcrm->getRelationMap($config->get('retailcrm', 'orderStatusMap')); $relationMap = RCrmHelpers::getRelationMap($config->get('retailcrm', 'orderStatusMap'));
$umiOrderStatusCode = $retailcrm->getRelationByMap($relationMap, $crmOrder['status'], true); $umiOrderStatusCode = RCrmHelpers::getRelationByMap($relationMap, $crmOrder['status'], true);
if ($umiOrderStatusCode) { if ($umiOrderStatusCode) {
// меняем дату редактирования заказа, для того, чтобы его не перехватил хенлдер и не выплюнул обратно в црм // меняем дату редактирования заказа, для того, чтобы его не перехватил хенлдер и не выплюнул обратно в црм
$order->getObject()->setUpdateTime(time()); $order->getObject()->setUpdateTime(time());

View File

View File

@ -287,9 +287,7 @@ class RCrmIcml
if (is_array($photos) && count($photos)) { if (is_array($photos) && count($photos)) {
$photo = reset($photos); $photo = reset($photos);
$photoPath = $this->shopUrl . $photo->getFilePath(true); $photoPath = $this->shopUrl . $photo->getFilePath(true);
$e->appendChild($this->dd->createElement('picture'))->appendChild($this->dd->createTextNode($photoPath));
$e->appendChild($this->dd->createElement('picture'))
->appendChild($this->dd->createTextNode($photoPath));
} }
} }

View File

100
classes/modules/RetailCRM/classes/retailcrm/RCrmProxy.php Normal file → Executable file
View File

@ -7,36 +7,104 @@
class RCrmProxy class RCrmProxy
{ {
private $api; private $api;
private $log;
public function __construct($url, $key, $log) /**
* Методы API которые не надо логировать
* @var array
*/
private $ignoreMethods = array(
'customersList',
'customersGet',
'ordersList',
'ordersGet',
);
/**
* Методы API трассировку которых надо логировать
* @var array
*/
private $traceMethods = array(
'customersCreate',
'customersEdit',
'ordersCreate',
'ordersEdit',
);
/**
* RCrmProxy constructor.
* @param string $apiUrl
* @param string $apiKey
*/
public function __construct($apiUrl, $apiKey)
{ {
$this->api = new RCrmApiClient($url, $key); $this->api = new RCrmApiClient($apiUrl, $apiKey);
$this->log = $log;
} }
/**
* @param $method
* @param $arguments
* @return bool|RCrmApiResponse
*/
public function __call($method, $arguments) public function __call($method, $arguments)
{ {
$accessLog = date('H:m:i') . ' [' . $method . '] -> ' . json_encode($arguments) . "\n";
error_log($accessLog, 3, $this->log);
try { try {
$response = call_user_func_array(array($this->api, $method), $arguments); $response = call_user_func_array(array($this->api, $method), $arguments);
if (!$response->isSuccessful()) {
error_log("[$method] " . $response->getErrorMsg() . "\n", 3, $this->log); if (!in_array($method, $this->ignoreMethods)) {
if (isset($response['errors'])) { $this->writeLog($method, $response);
$error = implode("\n", $response['errors']);
error_log($error . "\n", 3, $this->log);
}
$response = false;
} }
return $response; return $response;
} catch (RCrmCurlException $e) { } catch (RCrmCurlException $e) {
error_log("[$method] " . $e->getMessage() . "\n", 3, $this->log); $this->writeLog($method, $e->getMessage());
return false; return false;
} catch (RCrmJsonException $e) { } catch (RCrmJsonException $e) {
error_log("[$method] " . $e->getMessage() . "\n", 3, $this->log); $this->writeLog($method, $e->getMessage());
return false; return false;
} }
} }
/**
* @param string $method
* @param mixed $data
* @return bool
*/
private function writeLog($method, $data)
{
$path = realpath(__DIR__ . '/../../logs/');
$file = $path . '/' . $method . '.log';
if (!file_exists($path)) {
mkdir($path);
}
if (file_exists($file)) {
if (filesize($file) > 1024 * 1024 * 10) {
unlink($file);
}
}
$logArray = array(
'time' => date('Y-m-d H:i:s'),
'data' => $data
);
if (in_array($method, $this->traceMethods)) {
$traces = debug_backtrace();
foreach ($traces as $i => $trace) {
if ($i == 0) {
unset($traces[$i]);
continue;
}
unset($traces[$i]['args']);
unset($traces[$i]['object']);
}
$logArray['trace'] = array_reverse($traces);
}
return file_put_contents($file, print_r($logArray, true) . "\n\n", FILE_APPEND);
}
} }

0
classes/modules/RetailCRM/data/objects.xml Normal file → Executable file
View File

2
classes/modules/RetailCRM/events.php Normal file → Executable file
View File

@ -4,7 +4,7 @@
'history' => 'onCronSyncHistory', 'history' => 'onCronSyncHistory',
); );
if (isset($_SERVER['argv'][2]) || isset($eventHandlers[$_SERVER['argv'][2]])) { if (isset($_SERVER['argv']) && (isset($_SERVER['argv'][2]) || isset($eventHandlers[$_SERVER['argv'][2]]))) {
new umiEventListener('cron', 'RetailCRM', $eventHandlers[$_SERVER['argv'][2]]); new umiEventListener('cron', 'RetailCRM', $eventHandlers[$_SERVER['argv'][2]]);
} }

0
classes/modules/RetailCRM/i18n.php Normal file → Executable file
View File

0
classes/modules/RetailCRM/install.php Normal file → Executable file
View File