public static function OnSalePayOrder($id, $paid) { if (Loader::includeModule('conversion') && ($row = \CSaleOrder::GetById($id))) { if ($paid == 'Y') { $context = DayContext::getEntityItemInstance('sale_order', $id); $context->addCurrencyCounter('sale_payment_sum_add', $row['PRICE'], $row['CURRENCY']); if (defined('ADMIN_SECTION') && ADMIN_SECTION === true) { $context->addCounter('sale_payment_add_day', 1); } else { $context->addDayCounter('sale_payment_add_day', 1); } } } }
public static function send($eventId, $arParams) { $result = false; if (!isset($arParams["ORDER"]) && isset($arParams["ORDER_ID"])) { $arParams["ORDER"] = CSaleOrder::GetById($arParams["ORDER_ID"]); } if (in_array($eventId, self::$arEvents) && isset($arParams["ORDER"]) && CModule::IncludeModule("pull")) { $arUsers = self::getSubscribers($eventId, $arParams); if (!empty($arUsers)) { $text = self::makeMessage($eventId, $arParams); $title = self::makeTitle($eventId, $arParams); $arMessages = array(); foreach ($arUsers as $userId) { if (!self::checkRights($userId, $eventId, array("ORDER_ID" => $arParams["ORDER"]["ID"]))) { continue; } $arMessages[] = array("USER_ID" => $userId, "TITLE" => $title, "APP_ID" => "BitrixAdmin", "MESSAGE" => $text, "PARAMS" => "sl_" . $arParams["ORDER"]["ID"]); } $pushMe = new CPushManager(); $result = $pushMe->SendMessage($arMessages); } } return $result; }
$order['externalId'] = $externalId; } if (isset($order['externalId']) && $order['externalId']) { // custom orderType function if (function_exists('intarocrm_set_order_type')) { $orderType = intarocrm_set_order_type($order); if ($orderType) { $optionsOrderTypes[$order['orderType']] = $orderType; } else { $optionsOrderTypes[$order['orderType']] = $defaultOrderType; } } $arFields = CSaleOrder::GetById($order['externalId']); // incorrect order if ($arFields === false || empty($arFields)) { die(); } $LID = $arFields['LID']; $userId = $arFields['USER_ID']; if(isset($order['customer']['externalId']) && !is_null($order['customer']['externalId'])) { $userId = $order['customer']['externalId']; } $rsOrderProps = CSaleOrderPropsValue::GetList(array(), array('ORDER_ID' => $arFields['ID'])); $arUpdateProps = array();
public static function execHandlerAction($orderId, $actionId) { global $DB, $USER; $arResult = array(); $arOrder = CSaleOrder::GetById($orderId); $handlerActions = CSaleDeliveryHandler::getActionsList($arOrder["DELIVERY_ID"]); if (!array_key_exists($actionId, $handlerActions)) { $arResult = array("RESULT" => "ERROR", "TEXT" => GetMessage("SALE_DHLP_HANDLER_HAS_NO_ACTION")); } $dt = new \Bitrix\Main\Type\DateTime(); $depList = \Bitrix\Sale\Internals\OrderDeliveryReqTable::getList(array('filter' => array('=ORDER_ID' => $orderId))); $dep = $depList->fetch(); if ($dep && !is_null($dep["DATE_REQUEST"])) { $arResult = array("RESULT" => "ERROR", "TEXT" => GetMessage("SALE_DHLP_HANDLER_REQUEST_ALREADY_SENT")); } if (empty($arResult)) { $arUserGroups = $USER->GetUserGroupArray(); $arOrder["ITEMS"] = array(); $dbItemsList = CSaleBasket::GetList(array("SET_PARENT_ID" => "DESC", "TYPE" => "DESC", "NAME" => "ASC"), array("ORDER_ID" => $orderId)); while ($arItem = $dbItemsList->GetNext()) { $arItem["DIMENSIONS"] = unserialize($arItem["~DIMENSIONS"]); unset($arItem["~DIMENSIONS"]); $arOrder["ITEMS"][] = $arItem; } $arResult = CSaleDeliveryHandler::executeAction($arOrder["DELIVERY_ID"], $actionId, $arOrder); if ($actionId == "REQUEST_SELF" && isset($arResult["TRACKING_NUMBER"])) { $bUserCanEditOrder = CSaleOrder::CanUserUpdateOrder($orderId, $arUserGroups); if ($bUserCanEditOrder) { if ($dep) { \Bitrix\Sale\Internals\OrderDeliveryReqTable::update($dep["ID"], array("DATE_REQUEST" => $dt)); } else { \Bitrix\Sale\Internals\OrderDeliveryReqTable::add(array("ORDER_ID" => $orderId, "DATE_REQUEST" => $dt)); } $fields = array(); if (isset($arResult["TRACKING_NUMBER"])) { $fields["TRACKING_NUMBER"] = $arResult["TRACKING_NUMBER"]; } if (isset($arResult["DELIVERY_DOC_NUM"])) { $fields["DELIVERY_DOC_NUM"] = $arResult["DELIVERY_DOC_NUM"]; $fields["DELIVERY_DOC_DATE"] = Date($DB->DateFormatToPHP(CLang::GetDateFormat("SHORT", $arOrder["LID"]))); } CSaleOrder::Update($orderId, $fields); } } CSaleOrderChange::AddRecord($orderId, "ORDER_DELIVERY_REQUEST_SENT", $arResult); } return $arResult; }
/** * * @param type $ID -- orderId * @param type $cancel -- Y / N - cancel order status * @param type $reason -- cancel reason * @return boolean */ function onSaleCancelOrder($ID, $cancel, $reason) { if (isset($GLOBALS['INTARO_CRM_FROM_HISTORY']) && $GLOBALS['INTARO_CRM_FROM_HISTORY']) { return; } if (!$ID || !$cancel) { return true; } if (!CModule::IncludeModule('iblock')) { //handle err ICrmOrderActions::eventLog('ICrmOrderEvent::onSaleCancelOrder', 'iblock', 'module not found'); return true; } if (!CModule::IncludeModule("sale")) { //handle err ICrmOrderActions::eventLog('ICrmOrderEvent::onSaleCancelOrder', 'sale', 'module not found'); return true; } if (!CModule::IncludeModule("catalog")) { //handle err ICrmOrderActions::eventLog('ICrmOrderEvent::onSaleCancelOrder', 'catalog', 'module not found'); return true; } $api_host = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_HOST_OPTION, 0); $api_key = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_KEY_OPTION, 0); //saved cat params $optionsPayStatuses = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_STATUSES, 0)); // --statuses $api = new RetailCrm\RestApi($api_host, $api_key); $order = array(); if ($cancel == 'Y') { $order = array('externalId' => (int) $ID, 'status' => $optionsPayStatuses[$cancel . $cancel], 'statusComment' => ICrmOrderActions::toJSON($reason)); } else { if ($cancel == 'N') { $arOrder = CSaleOrder::GetById((int) $ID); $order = array('externalId' => (int) $ID, 'status' => $optionsPayStatuses[$arOrder['STATUS_ID']], 'managerComment' => $arOrder['COMMENTS']); } } $log = new Logger(); $log->write($order, 'order'); try { $api->orderEdit($order); } catch (\RetailCrm\Exception\CurlException $e) { ICrmOrderActions::eventLog('ICrmOrderEvent::onSaleCancelOrder', 'RetailCrm\\RestApi::orderEdit::CurlException', $e->getCode() . ': ' . $e->getMessage()); } return true; }
public static function onSalePayOrder($id, $paid) { if (Loader::includeModule('conversion') && ($row = \CSaleOrder::GetById($id))) { $context = DayContext::getEntityItemInstance('sale_order', $id); if ($paid == 'Y') { if (defined('ADMIN_SECTION') && ADMIN_SECTION === true) { $context->addCounter('sale_payment_add_day', 1); } else { $context->addDayCounter('sale_payment_add_day', 1); } $context->addCounter('sale_payment_add', 1); $context->addCurrencyCounter('sale_payment_sum_add', $row['PRICE'], $row['CURRENCY']); } /* elseif ($paid == 'N') { if (defined('ADMIN_SECTION') && ADMIN_SECTION === true) { // TODO what if payment added by user and removed by admin -- conversion is going down!!! $context->addCounter ('sale_payment_rem_day', 1); } else { $context->addDayCounter ('sale_payment_rem_day', 1); } $context->addCounter ('sale_payment_rem' , 1); $context->addCurrencyCounter('sale_payment_sum_rem', $row['PRICE'], $row['CURRENCY']); } */ } }
function OnOrderNewSendEmailHandler($orderID, &$eventName, &$arFields) { // Поменять вид списка товаров if (!CModule::IncludeModule('sale') || !CModule::IncludeModule('catalog')) return; //global $pre_defined_variables, $DB; $arOrder = CSaleOrder::GetById($orderID); $dbBasketItems = CSaleBasket::GetList(array("NAME" => "ASC"), array("ORDER_ID" => $orderID), false, false, array("ID", "NAME", "QUANTITY", "PRICE", "CURRENCY", "DETAIL_PAGE_URL")); $strOrderList = ""; $strOrderList .= '<table width="100%">'; $strOrderList .= '<thead><tr>'; foreach(array("Название","Количество","Цена","Сумма") as $th) $strOrderList .= '<th>'.$th.'</th>'; $strOrderList .= '</tr></thead>'; $strOrderList .= '<tbody>'; $price_total = 0; $arBasketItems = array(); while ($arBasketItem = $dbBasketItems->Fetch()) { $dbProp = CSaleBasket::GetPropsList(Array("SORT" => "ASC", "NAME" => "ASC"), Array("BASKET_ID" => $arBasketItem["ID"], "!CODE" => array("CATALOG.XML_ID", "PRODUCT.XML_ID"))); while($arProp = $dbProp -> GetNext()) $arBasketItem["PROPS"][] = $arProp; $arBasketItems[] = $arBasketItem; $strOrderList .= '<tr>'; $strOrderList .= '<td>'; $strOrderList .= '<a href="http://www.zakrepi.ru'.$arBasketItem["DETAIL_PAGE_URL"].'" target="_blank">'.$arBasketItem["NAME"].'</a>'; // Из свойств товара заказа показать лишь стандартные и название филиала foreach($arBasketItem['PROPS'] as &$arProp) { $strOrderList .= '<div style="font-size:80%">'.$arProp['NAME'].': '.$arProp['VALUE'].'</div>'; } $strOrderList .= '</td>'; $strOrderList .= '<td style="text-align: center;">'.$arBasketItem["QUANTITY"].' шт.</td>'; $strOrderList .= '<td style="text-align: center;">'.SaleFormatCurrency($arBasketItem["PRICE"], $arBasketItem["CURRENCY"]).'</td>'; $strOrderList .= '<td style="text-align: center;">'.SaleFormatCurrency($arBasketItem["PRICE"] * $arBasketItem["QUANTITY"], $arBasketItem["CURRENCY"]).'</td>'; $strOrderList .= '</tr>'; $price_total += $arBasketItem["PRICE"] * $arBasketItem["QUANTITY"]; $price_currency = $arBasketItem["CURRENCY"]; } $price_total_formatted = $price_currency? SaleFormatCurrency($price_total, $price_currency): '0'; $strOrderList .= '<tr><td colspan="3" style="text-align:right;">Общая стоимость: </td><td style="text-align: center;">'.$price_total_formatted.'</td></tr>'; //Получаем стоимость доставки цену и общую сумму вместе с ценой доставки // Указываем способ доставки // $arOrder['PRICE'] - Общая стоимость $arFields['DELIVERY'] = ''; if (strlen($arOrder['DELIVERY_ID'])) { if (is_string($arOrder['DELIVERY_ID'])) { $sid = explode(":", $arOrder['DELIVERY_ID']); $dbDeliv = CSaleDeliveryHandler::GetBySID($sid[0]); $arDeliv = $dbDeliv->GetNext(); $arFields['DELIVERY'] = '<p><b>Способ доставки:</b> '.$arDeliv['NAME'].'</p>'; $price_total += $arOrder['PRICE_DELIVERY']; $strOrderList .= '<tr><td colspan="3" style="text-align:right;">Стоимость доставки: </td><td style="text-align: center;">'.SaleFormatCurrency($arOrder['PRICE_DELIVERY'], $price_currency).'</td></tr>'; $strOrderList .= '<tr><td colspan="3" style="text-align:right;">Итого: </td><td style="text-align: center;">'.SaleFormatCurrency($price_total, $price_currency).'</td></tr>'; $arFields['ALL_PRICE'] = '<p><b>Итого: </b>'.SaleFormatCurrency($price_total, $price_currency).'</p>'; } else{ $arDelivery = CSaleDelivery::GetById($arOrder['DELIVERY_ID']); if ($arDelivery) { $value = $arDelivery['NAME']; $value_name = $arDelivery['NAME']; $value_price = ''; if ($arDelivery['PRICE']<=0) { $value .= ', Бесплатно'; $value_price = 'Бесплатно'; } else { $value .= ', '.SaleFormatCurrency($arDelivery['PRICE'], $arDelivery['CURRENCY']); $value_price = SaleFormatCurrency($arDelivery['PRICE'], $arDelivery['CURRENCY']); $strOrderList .= '<tr><td colspan="3" style="text-align:right;">Стоимость доставки: </td><td style="text-align: center;">'.$value_price.'</td></tr>'; } $arFields['DELIVERY'] = '<p><b>Способ доставки:</b> '.$value_name.'</p>'; $price_total += $arDelivery['PRICE']; $strOrderList .= '<tr><td colspan="3" style="text-align:right;">Итого: </td><td style="text-align: center;">'.SaleFormatCurrency($price_total, $price_currency).'</td></tr>'; $arFields['ALL_PRICE'] = '<p><b>Итого: </b>'.SaleFormatCurrency($price_total, $price_currency).'</p>'; } } } $strOrderList .= '</tbody>'; $strOrderList .= '</table>'; $arFields["ORDER_LIST_NEW"] = $strOrderList; // Указываем свойства заказа - Начало /* $arProps = array(); $dbProps = CSaleOrderPropsValue::GetOrderProps($orderID); while ($arProp = $dbProps->Fetch()) { $arProps[$arProp['CODE']] = $arProp; $val = $arProp['VALUE']; if ($arProp['TYPE']=="LOCATION") { $v = CSaleLocation::GetByID($val); $val = $v['CITY_NAME_LANG']; } elseif (in_array($arProp['TYPE'], array("SELECT", "MULTISELECT", "RADIO"))) { $v = CSaleOrderPropsVariant::GetByValue($arProp['ORDER_PROPS_ID'], $val); $val = $v['NAME']; } $arProp['VALUE_FORMATTED'] = $val; }*/ // Получаем список исключенных свойств в зависимости от выбранной службы доставки /*$delivery_id = $arOrder['DELIVERY_ID']; $EXCLUDE_PROPS = $pre_defined_variables['ORDER_MAKE']["EXCLUDE_PROP_ON_DELIVERY_ID"]; if (array_key_exists($delivery_id, $EXCLUDE_PROPS)) $EXCLUDE_PROP = $EXCLUDE_PROPS[$delivery_id]; else $EXCLUDE_PROP = array(); $EXCLUDE_PROP = array_merge(array('AGREE'), $EXCLUDE_PROP); // Выводим свойства $strPropsList = ''; foreach($arProps as $prop_code=>&$arProp) { if (in_array($prop_code, $EXCLUDE_PROP)) continue; $strPropsList .= '<p>'; $value = strlen(trim($arProp['VALUE']))? $arProp['VALUE']: '<i>не указано</i>'; $strPropsList .= '<b>'.$arProp['NAME'].':</b> '.$value; $strPropsList .= '</p>'; } $arFields['PROPS_LIST'] = $strPropsList;*/ // Указываем свойства заказа - Конец // Указываем способ оплаты $arFields['PAY_SYSTEM'] = ''; if (strlen($arOrder['PAY_SYSTEM_ID'])) { $arPaySystem = CSalePaySystem::GetByID($arOrder['PAY_SYSTEM_ID'], $arOrder['PERSON_TYPE_ID']); if ($arPaySystem) { $value = strlen(trim($arPaySystem['PSA_NAME']))? $arPaySystem['PSA_NAME']: $arPaySystem['NAME']; if($arOrder['PAY_SYSTEM_ID'] == 1 || $arOrder['PAY_SYSTEM_ID'] == 2) { $arFields['PAY_SYSTEM'] = '<p><b>Способ оплаты:</b> <a href="http://www.zakrepi.ru/checkout/?ORDER_ID='.$orderID.'" target="_blank">'.$value.'</a></p>'; } else { $arFields['PAY_SYSTEM'] = '<p><b>Способ оплаты:</b> '.$value.'</p>'; } } } // Получаем склад, указанный при доставке $arFields['STORE_LIST'] = ''; $arFields['STORE_LIST_NEUTRAL'] = ''; $arFields['STORE_EMAIL'] = ''; $arStores = array(); if ($arOrder['DELIVERY_ID'] == 1) { $dbStores = CCatalogStore::GetList(array(), array('ID'=>1), false, false, array()); $arStore = $dbStores->Fetch(); $strStoreList = ''; if ($arStore) { // Получаем свойства склада в нужном порядке $prop_codes = array('TITLE'=>'', 'ADDRESS'=>'Адрес', 'PHONE'=>'Телефон', 'SCHEDULE'=>'Время работы'); // Выводим склад $strStoreList = '<span style="font-size: 90%">'; $have_value = false; $prev_value = false; foreach($prop_codes as $prop_code=>&$name) { if ($prev_value) { $strStoreList .= ', '; $prev_value = false; } if (strlen(trim($arStore[$prop_code]))) { $have_value = true; if (strlen($name)) { $strStoreList .= $name.': '; } $strStoreList .= trim($arStore[$prop_code]); $prev_value = true; } } $strStoreList .= '</span><br />'; // Добавляем поле списка складов в почтовый шаблон //$arFields['STORE_LIST_NEUTRAL'] = '<p>Указанный '$strStoreList; if (strlen($have_value)) { $arFields['STORE_LIST_NEUTRAL'] = '<p><b>Пункт выдачи:</b></p>' . $strStoreList; $arFields['STORE_LIST'] = '<p><b>Пожалуйста, сообщите номер вашего заказа для оплаты по адресу:</b></p>' . $strStoreList; } } } else if($arOrder['DELIVERY_ID'] > 1) { $strStoreList = ''; $arOrderProps = CSaleOrderPropsValue::GetOrderProps($arOrder['ID']); while ($arProps = $arOrderProps->Fetch()) { switch ($arProps['CODE']) { case 'CITY': $strStoreList .= $arProps['NAME'].': '.$arProps['VALUE']; break; case 'STREET': $strStoreList .= '<br/>'.$arProps['NAME'].': '.$arProps['VALUE']; break; case 'HOUSE': $strStoreList .= '<br/>'.$arProps['NAME'].': '.$arProps['VALUE']; break; case 'KORPUS': if($arProps['VALUE']!='') $strStoreList .= '<br/>'.$arProps['NAME'].': '.$arProps['VALUE']; break; case 'FLAT': if($arProps['VALUE']!='') $strStoreList .= '<br/>'.$arProps['NAME'].': '.$arProps['VALUE']; break; } } $arFields['STORE_LIST_NEUTRAL'] = '<div><p><b>Доставка по адресу:</b></p>' . $strStoreList.'</div>'; } else if(is_string($arOrder['DELIVERY_ID'])) { $strStoreList = ''; $arOrderProps = CSaleOrderPropsValue::GetOrderProps($arOrder['ID']); while ($arProps = $arOrderProps->Fetch()) { switch ($arProps['CODE']) { case 'CITY': $strStoreList .= $arProps['NAME'].': '.$arProps['VALUE']; break; case 'STREET': $strStoreList .= '<br/>'.$arProps['NAME'].': '.$arProps['VALUE']; break; case 'HOUSE': $strStoreList .= '<br/>'.$arProps['NAME'].': '.$arProps['VALUE']; break; case 'KORPUS': if($arProps['VALUE']!='') $strStoreList .= '<br/>'.$arProps['NAME'].': '.$arProps['VALUE']; break; case 'FLAT': if($arProps['VALUE']!='') $strStoreList .= '<br/>'.$arProps['NAME'].': '.$arProps['VALUE']; break; } } $arFields['STORE_LIST_NEUTRAL'] = '<div><p><b>Доставка по адресу:</b></p>' . $strStoreList.'</div>'; } //Получение данных пользователя $rsUser = CUser::GetByID($arOrder['USER_ID']); $arUser = $rsUser->Fetch(); if(in_array(5, CUser::GetUserGroup($arOrder['USER_ID']))) { $arFields['STORE_PHONE'] = $arUser['WORK_PHONE']; $arFields['STORE_NAME_USER'] = '******'.$arUser['NAME'].' '.$arUser['LAST_NAME']; } else if(in_array(6, CUser::GetUserGroup($arOrder['USER_ID']))) { $arFields['STORE_PHONE'] = $arUser['WORK_PHONE']; $arFields['STORE_NAME_USER'] = '******'.$arUser['WORK_COMPANY'].' Контактное лицо '.$arUser['UF_CONTACT_MANAGER']; } }
/** * * History update, cron usage only * @global CUser $USER * @return boolean */ public static function orderHistory() { global $USER; if (is_object($USER) == false) { $USER = new RetailUser(); } if (!CModule::IncludeModule("iblock")) { self::eventLog('ICrmOrderActions::orderHistory', 'iblock', 'module not found'); return false; } if (!CModule::IncludeModule("sale")) { self::eventLog('ICrmOrderActions::orderHistory', 'sale', 'module not found'); return false; } if (!CModule::IncludeModule("catalog")) { self::eventLog('ICrmOrderActions::orderHistory', 'catalog', 'module not found'); return false; } $api_host = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_HOST_OPTION, 0); $api_key = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_KEY_OPTION, 0); $optionsOrderTypes = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_TYPES_ARR, 0))); $optionsDelivTypes = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_DELIVERY_TYPES_ARR, 0))); $optionsPayTypes = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_TYPES, 0))); $optionsPayStatuses = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_STATUSES, 0))); // --statuses $optionsPayment = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT, 0))); $optionsOrderProps = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_PROPS, 0)); $optionsLegalDetails = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_LEGAL_DETAILS, 0)); $optionsContragentType = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_CONTRAGENT_TYPE, 0)); $optionsSitesList = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_SITES_LIST, 0)); $optionsCustomFields = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_CUSTOM_FIELDS, 0)); foreach ($optionsOrderProps as $code => $value) { if (isset($optionsLegalDetails[$code])) { $optionsOrderProps[$code] = array_merge($optionsOrderProps[$code], $optionsLegalDetails[$code]); } if (isset($optionsCustomFields[$code])) { $optionsOrderProps[$code] = array_merge($optionsOrderProps[$code], $optionsCustomFields[$code]); } $optionsOrderProps[$code]['location'] = 'LOCATION'; if (array_search('CITY', $optionsOrderProps[$code]) == false) { $optionsOrderProps[$code]['city'] = 'CITY'; } if (array_search('ZIP', $optionsOrderProps[$code]) == false) { $optionsOrderProps[$code]['index'] = 'ZIP'; } } $api = new RetailCrm\RestApi($api_host, $api_key); $dateStart = COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY_DATE, null); if (is_null($dateStart)) { $dateStart = new \DateTime(); $dateStart = $dateStart->format('Y-m-d H:i:s'); } try { $orderHistory = $api->orderHistory($dateStart); } catch (\RetailCrm\Exception\CurlException $e) { self::eventLog('ICrmOrderActions::orderHistory', 'RetailCrm\\RestApi::orderHistory::CurlException', $e->getCode() . ': ' . $e->getMessage()); return false; } $orderHistory = isset($orderHistory['orders']) ? $orderHistory['orders'] : array(); $log = new Logger(); $log->write($orderHistory, 'history'); $dateFinish = $api->getGeneratedAt(); if (is_null($dateFinish) || $dateFinish == false) { $dateFinish = new \DateTime(); } $defaultOrderType = 1; $dbOrderTypesList = CSalePersonType::GetList(array(), array("ACTIVE" => "Y")); if ($arOrderTypesList = $dbOrderTypesList->Fetch()) { $defaultOrderType = $arOrderTypesList['ID']; } $GLOBALS['INTARO_CRM_FROM_HISTORY'] = true; foreach ($orderHistory as $order) { if (function_exists('intarocrm_order_pre_persist')) { $order = intarocrm_order_pre_persist($order); } if (!isset($order['externalId'])) { // custom orderType function if (function_exists('intarocrm_set_order_type')) { $orderType = intarocrm_set_order_type($order); if ($orderType) { $optionsOrderTypes[$order['orderType']] = $orderType; } else { $optionsOrderTypes[$order['orderType']] = $defaultOrderType; } } // we dont need new orders without any customers (can check only for externalId) if (!isset($order['customer']['externalId'])) { if (!isset($order['customer']['id'])) { continue; } $registerNewUser = true; if (!isset($order['customer']['email']) || $order['customer']['email'] == '') { $login = $order['customer']['email'] = uniqid('user_' . time()) . '@crm.com'; } else { $dbUser = CUser::GetList($by = 'ID', $sort = 'ASC', array('=EMAIL' => $order['email'])); switch ($dbUser->SelectedRowsCount()) { case 0: $login = $order['customer']['email']; break; case 1: $arUser = $dbUser->Fetch(); $registeredUserID = $arUser['ID']; $registerNewUser = false; break; default: $login = uniqid('user_' . time()) . '@crm.com'; break; } } if ($registerNewUser === true) { $userPassword = uniqid(); $newUser = new CUser(); $arFields = array("NAME" => self::fromJSON($order['customer']['firstName']), "LAST_NAME" => self::fromJSON($order['customer']['lastName']), "EMAIL" => $order['customer']['email'], "LOGIN" => $login, "LID" => "ru", "ACTIVE" => "Y", "PASSWORD" => $userPassword, "CONFIRM_PASSWORD" => $userPassword); $registeredUserID = $newUser->Add($arFields); if ($registeredUserID === false) { self::eventLog('ICrmOrderActions::orderHistory', 'CUser::Register', 'Error register user'); continue; } try { $api->customerFixExternalIds(array(array('id' => $order['customer']['id'], 'externalId' => $registeredUserID))); } catch (\RetailCrm\Exception\CurlException $e) { self::eventLog('ICrmOrderActions::orderHistory', 'RetailCrm\\RestApi::customerFixExternalIds::CurlException', $e->getCode() . ': ' . $e->getMessage()); continue; } } $order['customer']['externalId'] = $registeredUserID; } // new order $newOrderFields = array('LID' => CSite::GetDefSite(), 'PERSON_TYPE_ID' => isset($optionsOrderTypes[$order['orderType']]) ? $optionsOrderTypes[$order['orderType']] : $defaultOrderType, 'PAYED' => 'N', 'CANCELED' => 'N', 'STATUS_ID' => 'N', 'PRICE' => 0, 'CURRENCY' => CCurrency::GetBaseCurrency(), 'USER_ID' => $order['customer']['externalId'], 'PAY_SYSTEM_ID' => 0, 'PRICE_DELIVERY' => 0, 'DELIVERY_ID' => 0, 'DISCOUNT_VALUE' => 0, 'USER_DESCRIPTION' => ''); if (count($optionsSitesList) > 1 && ($lid = array_search($order['site'], $optionsSitesList))) { $newOrderFields['LID'] = $lid; } $externalId = CSaleOrder::Add($newOrderFields); if (!isset($order['externalId'])) { try { $api->orderFixExternalIds(array(array('id' => $order['id'], 'externalId' => $externalId))); } catch (\RetailCrm\Exception\CurlException $e) { self::eventLog('ICrmOrderActions::orderHistory', 'RetailCrm\\RestApi::orderFixExternalIds::CurlException', $e->getCode() . ': ' . $e->getMessage()); continue; } } $order['externalId'] = $externalId; } if (isset($order['externalId']) && $order['externalId']) { // custom orderType function if (function_exists('intarocrm_set_order_type')) { $orderType = intarocrm_set_order_type($order); if ($orderType) { $optionsOrderTypes[$order['orderType']] = $orderType; } else { $optionsOrderTypes[$order['orderType']] = $defaultOrderType; } } $arFields = CSaleOrder::GetById($order['externalId']); // incorrect order if ($arFields === false || empty($arFields)) { continue; } $LID = $arFields['LID']; $userId = $arFields['USER_ID']; if (isset($order['customer']['externalId']) && !is_null($order['customer']['externalId'])) { $userId = $order['customer']['externalId']; } $rsOrderProps = CSaleOrderPropsValue::GetList(array(), array('ORDER_ID' => $arFields['ID'])); $arUpdateProps = array(); while ($ar = $rsOrderProps->Fetch()) { $prop = CSaleOrderProps::GetByID($ar['ORDER_PROPS_ID']); $arUpdateProps[$ar['CODE']] = array('ID' => $ar['ID'], 'TYPE' => $prop['TYPE'], 'VALUE' => $ar['VALUE']); } $order['fio'] = trim(implode(' ', array(isset($order['lastName']) ? $order['lastName'] : '', isset($order['firstName']) ? $order['firstName'] : '', isset($order['patronymic']) ? $order['patronymic'] : ''))); if (isset($order['delivery']['address']['city'])) { $order['location'] = $order['delivery']['address']['city']; } if (isset($order['orderType']) && isset($optionsOrderTypes[$order['orderType']])) { if (isset($optionsOrderProps[$arFields['PERSON_TYPE_ID']])) { foreach ($optionsOrderProps[$arFields['PERSON_TYPE_ID']] as $code => $value) { if (in_array($code, array_keys($order)) === false && isset($optionsOrderProps[$optionsOrderTypes[$order['orderType']]][$code])) { $order[$code] = $arUpdateProps[$optionsOrderProps[$arFields['PERSON_TYPE_ID']][$code]]['VALUE']; } } } //update ordertype CSaleOrder::Update($order['externalId'], array('PERSON_TYPE_ID' => $optionsOrderTypes[$order['orderType']])); $arProp = CSaleOrderProps::GetList(array(), array('PERSON_TYPE_ID' => $optionsOrderTypes[$order['orderType']])); $typeParam = array(); while ($ar = $arProp->Fetch()) { $typeParam[$ar['CODE']] = $ar['CODE']; } foreach (array_diff_key($arUpdateProps, $typeParam) as $code => $param) { if (isset($arUpdateProps[$code])) { CSaleOrderPropsValue::Delete($param['ID']); } } $arFields['PERSON_TYPE_ID'] = $optionsOrderTypes[$order['orderType']]; } array_walk_recursive(self::clearArr($order), 'self::recursiveUpdate', array('update' => $arUpdateProps, 'type' => $arFields['PERSON_TYPE_ID'], 'options' => $optionsOrderProps, 'orderId' => $order['externalId'])); foreach ($order['items'] as $item) { if (isset($item['deleted']) && $item['deleted']) { if ($p = CSaleBasket::GetList(array(), array('ORDER_ID' => $order['externalId'], 'PRODUCT_ID' => $item['id']))->Fetch()) { if (!CSaleBasket::Delete($p['ID'])) { self::eventLog('ICrmOrderActions::orderHistory', 'CSaleBasket::Delete', 'Error element delete'); } } else { $prp = CSaleBasket::GetPropsList(array(), array("ORDER_ID" => $order['externalId'], "CODE" => 'ID', "VALUE" => $item['id']))->Fetch(); if (!CSaleBasket::Delete($prp['BASKET_ID'])) { self::eventLog('ICrmOrderActions::orderHistory', 'CSaleBasket::Delete', 'Error castom element delete'); } } continue; } if (isset($item['offer']) === false && isset($item['offer']['externalId']) === false) { continue; } $res = CIBlockElement::GetByID($item['offer']['externalId'])->Fetch(); if ($res) { $p = CSaleBasket::GetList(array(), array('ORDER_ID' => $order['externalId'], 'PRODUCT_ID' => $item['offer']['externalId']))->Fetch(); if ($p == false) { $p = CIBlockElement::GetByID($item['offer']['externalId'])->GetNext(); $iblock = CIBlock::GetByID($p['IBLOCK_ID'])->Fetch(); $p['CATALOG_XML_ID'] = $iblock['XML_ID']; $p['PRODUCT_XML_ID'] = $p['XML_ID']; unset($p['XML_ID']); } elseif ($propResult = CSaleBasket::GetPropsList(array(''), array('BASKET_ID' => $p['ID']))) { while ($r = $propResult->Fetch()) { unset($r['ID']); unset($r['BASKET_ID']); $p['PROPS'][] = $r; } } $arProduct = array(); if (isset($item['created']) && $item['created'] == true) { $productPrice = GetCatalogProductPrice($item['offer']['externalId'], COption::GetOptionString(self::$MODULE_ID, self::$CRM_CATALOG_BASE_PRICE, 0)); $arProduct = array('FUSER_ID' => $userId, 'ORDER_ID' => $order['externalId'], 'QUANTITY' => $item['quantity'], 'CURRENCY' => $productPrice['CURRENCY'], 'LID' => $LID, 'PRODUCT_ID' => $item['offer']['externalId'], 'PRODUCT_PRICE_ID' => $p['PRODUCT_PRICE_ID'], 'WEIGHT' => $p['WEIGHT'], 'DELAY' => $p['DELAY'], 'CAN_BUY' => $p['CAN_BUY'], 'MODULE' => $p['MODULE'], 'NOTES' => $item['comment'] ?: $p['NOTES'], 'PRODUCT_PROVIDER_CLASS' => $p['PRODUCT_PROVIDER_CLASS'], 'DETAIL_PAGE_URL' => $p['DETAIL_PAGE_URL'], 'CATALOG_XML_ID' => $p['CATALOG_XML_ID'], 'PRODUCT_XML_ID' => $p['PRODUCT_XML_ID'], 'CUSTOM_PRICE' => 'Y'); } if (isset($item['isCanceled']) == false) { if (isset($item['initialPrice']) && $item['initialPrice']) { $arProduct['PRICE'] = (double) $item['initialPrice']; } if (isset($item['discount'])) { $arProduct['DISCOUNT_PRICE'] = $item['discount']; } if (isset($item['discountPercent'])) { $arProduct['DISCOUNT_VALUE'] = $item['discountPercent']; $newPrice = round($arProduct['PRICE'] / 100 * (100 - $arProduct['DISCOUNT_VALUE']), 2); $arProduct['DISCOUNT_PRICE'] = $arProduct['DISCOUNT_PRICE'] + $arProduct['PRICE'] - $newPrice; } if (isset($item['discount']) || isset($item['discountPercent'])) { $arProduct['PRICE'] -= $arProduct['DISCOUNT_PRICE']; } if (isset($item['offer']['name']) && $item['offer']['name']) { $arProduct['NAME'] = self::fromJSON($item['offer']['name']); } $arProduct = self::updateCancelProp($arProduct, 0); } elseif (isset($item['isCanceled'])) { $arProduct['PRICE'] = 0; $arProduct = self::updateCancelProp($arProduct, 1); } if (isset($item['created']) && $item['created'] == true) { if (!Add2BasketByProductID($item['offer']['externalId'], $item['quantity'], $arProduct, $p['PROPS'])) { self::eventLog('ICrmOrderActions::orderHistory', 'Add2BasketByProductID', 'Error element add'); } continue; } if (count($p['PROPS']) > 0) { $arProduct['PROPS'] = $p['PROPS']; } if (isset($item['quantity']) && $item['quantity']) { $arProduct['QUANTITY'] = $item['quantity']; } if (isset($item['offer']['name']) && $item['offer']['name']) { $arProduct['NAME'] = self::fromJSON($item['offer']['name']); } if (!CSaleBasket::Update($p['ID'], $arProduct)) { self::eventLog('ICrmOrderActions::orderHistory', 'CSaleBasket::Update', 'Error element update'); } CSaleBasket::DeleteAll($userId); } else { $arProduct = array(); if (isset($item['created']) && $item['created'] == true) { $arProduct = array('FUSER_ID' => $userId, 'ORDER_ID' => $order['externalId'], 'LID' => $LID, 'NOTES' => $item['comment']); } if (isset($item['isCanceled']) == false) { if (isset($item['initialPrice']) && $item['initialPrice']) { $arProduct['PRICE'] = (double) $item['initialPrice']; } if (isset($item['discount'])) { $arProduct['DISCOUNT_PRICE'] = $item['discount']; } if (isset($item['discountPercent'])) { $arProduct['DISCOUNT_VALUE'] = $item['discountPercent']; $newPrice = round($arProduct['PRICE'] / 100 * (100 - $arProduct['DISCOUNT_VALUE']), 2); $arProduct['DISCOUNT_PRICE'] = $arProduct['DISCOUNT_PRICE'] + $arProduct['PRICE'] - $newPrice; } if (isset($item['discount']) || isset($item['discountPercent'])) { $arProduct['PRICE'] -= $arProduct['DISCOUNT_PRICE']; } if (isset($item['offer']['name']) && $item['offer']['name']) { $arProduct['NAME'] = self::fromJSON($item['offer']['name']); } $arProduct = self::updateCancelProp($arProduct, 0); } elseif (isset($item['isCanceled'])) { $arProduct['PRICE'] = 0; $arProduct = self::updateCancelProp($arProduct, 1); } if (isset($item['quantity']) && $item['quantity']) { $arProduct['QUANTITY'] = $item['quantity']; } if (isset($item['offer']['name']) && $item['offer']['name']) { $arProduct['NAME'] = self::fromJSON($item['offer']['name']); } if (isset($item['created']) && $item['created'] == true) { $iBlocks = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_CATALOG_IBLOCKS, 0)); $iBlock = array_shift($iBlocks); $newSection = new CIBlockSection(); $newSectionFields = array("ACTIVE" => 'N', "IBLOCK_ID" => $iBlock, "NAME" => 'RetailCRM', "CODE" => 'RetailCRM'); $resSection = $newSection->Add($newSectionFields); if (!$resSection) { self::eventLog('ICrmOrderActions::orderHistory', 'CIBlockSection::Add', 'Error castom section add'); continue; } $arLoadProductArray = array("IBLOCK_SECTION_ID" => $resSection, "IBLOCK_ID" => $iBlock, "NAME" => $item['offer']['name'] ? $item['offer']['name'] : 'RetailCrmElement', "CODE" => 'RetailCrmElement', "ACTIVE" => 'Y'); $el = new CIBlockElement(); $PRODUCT_ID = $el->Add($arLoadProductArray, false, false, true); if (!$PRODUCT_ID) { self::eventLog('ICrmOrderActions::orderHistory', 'CIBlockElement::Add', 'Error castom element add'); continue; } if (!CCatalogProduct::Add(array("ID" => $PRODUCT_ID))) { self::eventLog('ICrmOrderActions::orderHistory', 'CCatalogProduct::Add', 'Error product add'); continue; } $arFields = array("PRODUCT_ID" => $PRODUCT_ID, "CATALOG_GROUP_ID" => COption::GetOptionString(self::$MODULE_ID, self::$CRM_CATALOG_BASE_PRICE, 0), "PRICE" => $item['initialPrice'] ? $item['initialPrice'] : 1, "CURRENCY" => CCurrency::GetBaseCurrency()); if (!CPrice::Add($arFields)) { self::eventLog('ICrmOrderActions::orderHistory', 'CPrice::Add', 'Error price add'); continue; } $Params = array(array('NAME' => 'id', 'CODE' => 'ID', 'VALUE' => $item['offer']['externalId'])); if (!Add2BasketByProductID($PRODUCT_ID, $item['quantity'], $arProduct, $Params)) { self::eventLog('ICrmOrderActions::orderHistory', 'Add2BasketByProductID', 'Error add to basket'); continue; } if (!CIBlockSection::Delete($resSection)) { self::eventLog('ICrmOrderActions::orderHistory', 'CIBlockSection::Delete', 'Error delete section'); continue; } continue; } $prp = CSaleBasket::GetPropsList(array(), array("ORDER_ID" => $order['externalId'], "CODE" => 'ID', "VALUE" => $item['offer']['externalId']))->Fetch(); CSaleBasket::Update($prp['BASKET_ID'], $arProduct); } } if (isset($order['delivery']) === false || isset($order['delivery']['cost']) === false) { $order['delivery']['cost'] = $arFields['PRICE_DELIVERY']; } if (isset($order['summ']) === false || $order['summ'] <= 0) { $order['summ'] = $arFields['PRICE'] - $arFields['PRICE_DELIVERY']; } $wasCanaceled = $arFields['CANCELED'] == 'Y' ? true : false; if (isset($optionsDelivTypes[$order['delivery']['code']])) { $resultDeliveryTypeId = $optionsDelivTypes[$order['delivery']['code']]; } else { $resultDeliveryTypeId = isset($order['delivery']['service']) && isset($order['delivery']['service']['code']) ? reset(explode(":", $arFields['DELIVERY_ID'], 1)) : $arFields['DELIVERY_ID']; } if (isset($order['delivery']['service']) && isset($order['delivery']['service']['code'])) { $deliveryHandler = reset(CSaleDeliveryHandler::GetBySID($resultDeliveryTypeId)->arResult); if (count($deliveryHandler) > 0 && array_key_exists($order['delivery']['service']['code'], $deliveryHandler['PROFILES'])) { $resultDeliveryTypeId = $resultDeliveryTypeId . ':' . $order['delivery']['service']['code']; } } // orderUpdate $arFields = self::clearArr(array('PRICE_DELIVERY' => $order['delivery']['cost'], 'PRICE' => $order['summ'] + (double) $order['delivery']['cost'], 'DATE_MARKED' => $order['markDatetime'], 'USER_ID' => $userId, 'PAY_SYSTEM_ID' => $optionsPayTypes[$order['paymentType']], 'DELIVERY_ID' => $resultDeliveryTypeId, 'STATUS_ID' => $optionsPayStatuses[$order['status']], 'REASON_CANCELED' => self::fromJSON($order['statusComment']), 'USER_DESCRIPTION' => self::fromJSON($order['customerComment']), 'COMMENTS' => self::fromJSON($order['managerComment']))); if (isset($order['discount'])) { $arFields['DISCOUNT_VALUE'] = $order['discount']; $arFields['PRICE'] -= $order['discount']; } if (!empty($arFields)) { CSaleOrder::Update($order['externalId'], $arFields); } if (isset($order['status']) && $order['status']) { if (isset($optionsPayStatuses[$order['status']]) && $optionsPayStatuses[$order['status']]) { // set STATUS_ID CSaleOrder::StatusOrder($order['externalId'], $optionsPayStatuses[$order['status']]); if ($wasCanaceled && $optionsPayStatuses[$order['status']] != 'YY') { CSaleOrder::CancelOrder($order['externalId'], "N", $order['statusComment']); } elseif ($optionsPayStatuses[$order['status']] == 'YY') { CSaleOrder::CancelOrder($order['externalId'], "Y", $order['statusComment']); } } } // set PAYED if (isset($order['paymentStatus']) && $order['paymentStatus'] && $optionsPayment[$order['paymentStatus']]) { CSaleOrder::PayOrder($order['externalId'], $optionsPayment[$order['paymentStatus']]); } if (function_exists('intarocrm_order_post_persist')) { intarocrm_order_post_persist($order); } } } if (count($orderHistory) > 0) { COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY_DATE, $dateFinish->format('Y-m-d H:i:s')); } $GLOBALS['INTARO_CRM_FROM_HISTORY'] = false; return true; }