コード例 #1
0
ファイル: class.php プロジェクト: ASDAFF/gpbitrix
/**
 * событие вызывается перед отправкой письма о новом заказе
 * @param $orderID
 * @param $eventName
 * @param $arFields
 */
function bxModifySaleMails($order_id, &$eventName, &$arFieldsEmail)
{
                                             
    //unset($_SESSION['OnBeforeOrderAddHandler']);
    //$_SESSION['OnBeforeOrderAddHandler']['bxModifySaleMails']='bxModifySaleMails';
    //$_SESSION['OnBeforeOrderAddHandler']['id']=$order_id;
    //$_SESSION['OnBeforeOrderAddHandler']['arFields']=$arFieldsorder_old;
    $basket_props="";
    $post['INFO']="";
    $id_product=array();
    if(
        (CModule::IncludeModule("main"))
        &&
        (CModule::IncludeModule("iblock"))
        &&
        (CModule::IncludeModule("catalog"))
        &&
        (CModule::IncludeModule("sale"))
    ){


        /**
         * получаем параметры сформировавшегося старого заказа
         */
        $arFieldsorder_old = CSaleOrder::GetByID($order_id);
        /*
        echo "<pre>";
        var_dump($arFieldsorder_old);die();
        echo "</pre>";*/
        /**
         * выборка свойства сформировавшегося заказа по id заказа
         */
        $db_props = CSaleOrderPropsValue::GetOrderProps($order_id);
        $arFields_props = array();

        while ($arProps = $db_props->Fetch())
        {
            $arFields_props_old[$arProps['CODE']]=$arProps;

        }
        //_debug($arFields_props_old);

        /**
         * выборка из корзины по id заказа
         * получаем масси id продукта
         */
         
         $rsUser = CUser::GetByID(CUser::GetID());
         $arUser = $rsUser->Fetch();
         /*if (!$ORDER_ID = CSaleOrder::Add(array(
                                        "LID"              => SITE_ID,
                                        "PERSON_TYPE_ID"   => 1,
                                        "PAYED"            => "N",
                                        "CANCELED"         => "N",
                                        "STATUS_ID"        => "N",
                                        "PRICE"            => 0,
                                        "CURRENCY"         => CSaleLang::GetLangCurrency(SITE_ID),
                                        "USER_ID"          => $arUser['ID'],
                                        "PAY_SYSTEM_ID"    => $arFieldsorder_old['PAY_SYSTEM_ID'],
                                        "PRICE_DELIVERY"   => 0,
                                        "DELIVERY_ID"      => $arFieldsorder_old['DELIVERY_ID'],
                                        "DISCOUNT_VALUE"   => $arFieldsorder_old['DISCOUNT_VALUE'],
                                        "TAX_VALUE"        => $arFieldsorder_old['TAX_VALUE'],
                                        "USER_DESCRIPTION" => $post['INFO']
         ))){

                                        $rows['msg'] = 'Ошибка создания заказа';
                                        $fail          = true;
        }else{
                                        $rows['msg']=$ORDER_ID;
                                        //continue;
        }*/

        $dbBasketItems = CSaleBasket::GetList(
            array("ID" => "ASC"),
            array(
                "LID" => SITE_ID,
                "ORDER_ID" => $order_id
            ),
            false,
            false,
            array()
        );
        while ($arItem = $dbBasketItems->Fetch()){
            $id_product[] = $arItem['PRODUCT_ID'];
            $products_basket[$arItem['PRODUCT_ID']]=$arItem;
        }
        
        foreach($products_basket as $product){
            $price_product+=$product['PRICE']*$product['QUANTITY'];
            $products_descriptions.=$product['NAME']." - ".$product['QUANTITY']." шт: ".intval($product['PRICE'])." руб <br/>";
        
        }
        $price_product+=$arFieldsorder_old["PRICE_DELIVERY"];
        //$_SESSION['OnBeforeOrderAddHandler']['products_basket']=$products_basket;

        /**
         * получаем массив id партнеров из продукта
         */
        //var_dump($id_product);die();         

        if($id_product){
            $id_partner=array();
            $partner_product=array();
            $arSelect = Array("ID", "NAME","IBLOCK_ID","PROPERTY_PARTNER");
            $arFilter = Array("ID"=>$id_product, "ACTIVE"=>"Y");
            $res = CIBlockElement::GetList(Array(), $arFilter, false, false, $arSelect);
            
            while($ob = $res->GetNextElement())
            {
                $arFields = $ob->GetFields();
                $partner_product[$arFields['PROPERTY_PARTNER_VALUE']][]=$products_basket[$arFields['ID']];
                if($arFields['PROPERTY_PARTNER_VALUE']){
                    $id_partner[]=$arFields['PROPERTY_PARTNER_VALUE'];
                }
            }
            //$_SESSION['OnBeforeOrderAddHandler']['id_partner']=$id_partner;

            /**
             * получаем массив данных партнера
             */
         
            if($id_partner){
                            
                            
                $delivery_sum = null;
                $arSelect2 = Array("ID", "IBLOCK_ID", "NAME","PROPERTY_*");
                $arFilter2 = Array("IBLOCK_ID"=>9, "ACTIVE"=>"Y","ID"=>$id_partner,);
                $res2 = CIBlockElement::GetList(Array(), $arFilter2, false, false, $arSelect2);
                /**
                 * eсли в выборке корзине в продуктах больше чем один партнер
                 * то разбиваем заказ по количеству партнеров
                 */
                if (intval($res2->SelectedRowsCount())>0){
                    while($ob2 = $res2->GetNextElement()){
                        $arFields_partners = $ob2->GetFields();
                        $arProperties_partners = $ob2->GetProperties();
                        //_debug($arProperties_partners);
                        //$price_product=0;
                        //$products_descriptions="";
                        $arEventFields=array();
                        //echo $arFields_partners['ID'];
                        
                        
                        if($partner_product[$arFields_partners['ID']]){

                            $i=0;
                            $size_of_productpartner=sizeof($partner_product[$arFields_partners['ID']]);
                            foreach($partner_product[$arFields_partners['ID']] as $key_price=>$item_price){
                                //_debug($item_price);
                                $quantity=1;
                                /**
                                 * формируем новый пустой заказ
                                 */
                                if(!$i){


                                    if (!$ORDER_ID = CSaleOrder::Add(array(
                                        "LID"              => SITE_ID,
                                        "PERSON_TYPE_ID"   => 1,
                                        "PAYED"            => "N",
                                        "CANCELED"         => "N",
                                        "STATUS_ID"        => "N",
                                        "PRICE"            => 0,
                                        "CURRENCY"         => CSaleLang::GetLangCurrency(SITE_ID),
                                        "USER_ID"          => $arUser['ID'],
                                        "PAY_SYSTEM_ID"    => $arFieldsorder_old['PAY_SYSTEM_ID'],
                                        "PRICE_DELIVERY"   => 0,
                                        "DELIVERY_ID"      => $arFieldsorder_old['DELIVERY_ID'],
                                        "DISCOUNT_VALUE"   => $arFieldsorder_old['DISCOUNT_VALUE'],
                                        "TAX_VALUE"        => $arFieldsorder_old['TAX_VALUE'],
                                        "USER_DESCRIPTION" => $post['INFO']
                                    ))){

                                        $rows['msg'] = 'Ошибка создания заказа';
                                        $fail          = true;
                                    }else{
                                        $rows['msg']=$ORDER_ID;
                                        //continue;
                                    }
                                }

                                /**
                                 * добавляем по id заказа в корзину товары партнера
                                 */
                                if (!Add2BasketByProductID($item_price['PRODUCT_ID'], $item_price['QUANTITY'], array(
                                    'ORDER_ID' => $ORDER_ID,
                                ), $basket_props)) {
                                    $rows['err'] = 'Ошибка добавления товара в заказ';
                                    $fail          = true;
                                }

                                /*$price_product+=$item_price['PRICE']*$item_price['QUANTITY'];
                                $products_descriptions.=$item_price['NAME']." - ".$item_price['QUANTITY']." шт: ".intval($item_price['PRICE'])." руб <br/>";
                                */


                                $i++;
                                /**
                                 * обновляем параметры нового заказа на актуальные
                                 */
                                if($size_of_productpartner==$i){
                                    if (!$fail) {
                                        $dbBasketItems = CSaleBasket::GetList(
                                            array("NAME" => "ASC", "ID" => "ASC"), array(
                                                "LID"      => SITE_ID,
                                                "ORDER_ID" => $ORDER_ID
                                            ), false, false, array(
                                                "ID", "NAME", "QUANTITY", "CURRENCY", "CAN_BUY", "PRICE", "WEIGHT", "DISCOUNT_PRICE"
                                            )
                                        );

                                        $summ          = $weight        = 0;
                                        $strOrderList  = "";


                                        $arBasket      = array();
                                        while ($arBasketItems = $dbBasketItems->GetNext()) {
                                            $strOrderList .= $arBasketItems["NAME"] . " - " . $arBasketItems["QUANTITY"] . " шт на " . SaleFormatCurrency($arBasketItems["PRICE"] * $arBasketItems["QUANTITY"], $arBasketItems["CURRENCY"]);
                                            $strOrderList .= "\n";
                                            $rows['summ']=$summ += roundEx($arBasketItems["PRICE"], SALE_VALUE_PRECISION) * DoubleVal($arBasketItems["QUANTITY"]);
                                            $weight += doubleval($arBasketItems['WEIGHT']);
                                            $arBasket[] = $arBasketItems;
                                        }
                                        $arOrderForDiscount = array(
                                            'SITE_ID'      => SITE_ID,
                                            'USER_ID'      => $arUser['ID'],
                                            'ORDER_PRICE'  => $summ,
                                            'ORDER_WEIGHT' => $weight,
                                            'BASKET_ITEMS' => $arBasket,
                                        );
                                        $arDiscountOptions  = array();
                                        $arDiscountErrors   = array();
                                        CSaleDiscount::DoProcessOrder($arOrderForDiscount, $arDiscountOptions, $arDiscountErrors);
                                        if($_REQUEST['comment'])
                                            $arOrderForDiscount['COMMENTS'] = $_REQUEST['comment'];
                                        if($arProperties_partners['DOSTAVKA']['VALUE']){
                                            $arOrderForDiscount["PRICE_DELIVERY"] = $arProperties_partners['DOSTAVKA']['VALUE'];
                                            $arOrderForDiscount["DELIVERY_ID"] = 3;
                                            $summ += intval($arProperties_partners['DOSTAVKA']['VALUE']);
                                            $arOrderForDiscount['ORDER_PRICE']=$summ;
                                        }
                                        $arOrderForDiscount['PRICE_BEFORE'] = $summ;
                                        $arOrderForDiscount['PRICE']        = $summ;
                                        $arOrderForDiscount['WEIGHT']       = $arOrderForDiscount['ORDER_WEIGHT'];
                                        /**
                                         * обновляем заказ
                                         */
                                        if (!CSaleOrder::Update($ORDER_ID, $arOrderForDiscount)) {
                                            $rows['err'] = 'Ошибка расчета цены заказа.';
                                            $fail          = true;
                                        }else{

                                            /**
                                             * перезагружаем свойства заказ из старого
                                             */
                                            $db_props_new = CSaleOrderPropsValue::GetOrderProps($ORDER_ID);
                                            $arFields_props_new = array();
                                            while ($arProps_new = $db_props_new->Fetch())
                                            {
                                                //_debug($arProps_new);
                                                foreach($arFields_props_old as $key_props_old=>$item_props_old){
                                                    if($arProps_new['CODE']==$key_props_old){
                                                        CSaleOrderPropsValue::Update($arProps_new['ID'], array("VALUE"=>$item_props_old['VALUE']));
                                                        unset($arFields_props_old[$key_props_old]);
                                                    }
                                                }

                                            }
                                            if(sizeof($arFields_props_old)>0){
                                                foreach($arFields_props_old as $key_props_old2=>$item_props_old2){
                                                    CSaleOrderPropsValue::Add(array(
                                                        'NAME'           => $item_props_old2['NAME'],
                                                        'CODE'           => $item_props_old2['CODE'],
                                                        'ORDER_PROPS_ID' => $item_props_old2['ORDER_PROPS_ID'],
                                                        'ORDER_ID'       => $ORDER_ID,
                                                        'VALUE'          => $item_props_old2['VALUE']
                                                    ));
                                                }
                                            }
                                            /**
                                             * добавляем в свойство заказа id партнера для дальнейшей фильтрации по партнерским заказам
                                             */
                                            CSaleOrderPropsValue::Add(array(
                                                'NAME'           => "Привязка по партнеру",
                                                'CODE'           => "PATNERID",
                                                'ORDER_PROPS_ID' => 21,
                                                'ORDER_ID'       => $ORDER_ID,
                                                'VALUE'          => $arFields_partners['ID']
                                            ));


                                            //$price_product+=$arProperties_partners['DOSTAVKA']['VALUE'];
                                            //$price_product+=$arFieldsorder_old["PRICE_DELIVERY"];
                                            /**
                                             * отправляем данные о товаре Партнерам
                                             */
           
                                            if($arFields_partners['NAME']){  //если есть партнер у товара                              
                                                $arEventFields = Array(
                                                    "ORDER_ID"=> $ORDER_ID,
                                                    "ORDER_DATE"=> date("d.m.Y H:i:s"),
                                                    "ORDER_USER"=> $arFields_partners['NAME'],
                                                    "PRICE"=> $price_product,
                                                    "EMAIL"=> $arProperties_partners['EMAIL']['VALUE'],
                                                    "ORDER_LIST"=> $products_descriptions,
                                                    //"DELIVERY_PRICE"=>$arProperties_partners['DOSTAVKA']['VALUE']
                                                    "DELIVERY_PRICE"=>$arFieldsorder_old["PRICE_DELIVERY"]
                                                );
                                                $event = new CEvent;
                                                $event->SendImmediate("SALE_NEW_ORDERPARTNER", SITE_ID, $arEventFields);
                                            }
                                            
                                            
                                        }
                                    }
                                    //                        if(!$fail){
                                    //                            $ar_res_product=CCatalogProduct::GetByID($PRODUCT['ID']);
                                    //                            $arFields_quant = array(
                                    //                                'QUANTITY' => $ar_res_product['QUANTITY']-1
                                    //                            );
                                    //                            CCatalogProduct::Update($PRODUCT['ID'], $arFields_quant);
                                    //                        }

                                }

                            }
                        }
                    }
                    /**
                     * удаляем старый заказ после разбивки на новые
                     */
                    if($ORDER_ID ){
                        CSaleOrder::Delete($order_id);
                    }
                }
            }
            
            
            $arEventFields = Array(
                "ORDER_ID" =>$order_id,
                "ORDER_DATE" =>date("d.m.Y H:i:s"),
                "ORDER_USER" =>$arUser['NAME'],
                "PRICE" =>$price_product,
                "EMAIL" => $arUser['EMAIL'],
                "ORDER_LIST" =>$products_descriptions,
                "DELIVERY_PRICE"=>$arFieldsorder_old["PRICE_DELIVERY"]
            );
            $event = new CEvent;
            $event->SendImmediate("SALE_NEW_BILET", SITE_ID, $arEventFields); 
            
            
        }
    }
    //$_SESSION['OnBeforeOrderAddHandler']['rows']=$rows;
    return false;

}
コード例 #2
0
ファイル: component.php プロジェクト: Hawkart/megatv
 if ($arResult['ERROR'] == '') {
     $dbBaket = CSaleBasket::GetList(array(), array('FUSER_ID' => CSaleBasket::GetBasketUserID(), 'LID' => SITE_ID, 'ORDER_ID' => 'NULL'));
     while ($arBasket = $dbBaket->GetNext()) {
         if ($arBasket['CATALOG_XML_ID'] != '' && strpos($arBasket['CATALOG_XML_ID'], '@') !== false) {
             list($amount, $curr) = explode('@', $arBasket['CATALOG_XML_ID']);
             if ($curr == $arResult['REQUEST_ACCOUNT']) {
                 CSaleBasket::Delete($arBasket['ID']);
             }
         }
     }
     if ($arParams['PAY_IMMED']) {
         CSaleBasket::DeleteAll(CSaleBasket::GetBasketUserID());
     }
     CSaleBasket::Add(array('PRODUCT_ID' => $arResult['CURRENCIES'][$arResult['REQUEST_ACCOUNT']]['ID'], 'PRICE' => CCurrencyRates::ConvertCurrency($arResult['MONEY_OFF'], $arResult['REQUEST_ACCOUNT'], $arResult['LANG_CURRENCY']), 'CURRENCY' => $arResult['LANG_CURRENCY'], 'QUANTITY' => 1, 'LID' => LANG, 'DELAY' => 'N', 'CAN_BUY' => 'Y', 'NAME' => GetMessage('SPT_NAME_IN_CART', array('#VALUE#' => SaleFormatCurrency($arResult['REQUEST_AMOUNT'], $arResult['REQUEST_ACCOUNT']))), 'MODULE' => 'asd.money', 'DETAIL_PAGE_URL' => '', 'CATALOG_XML_ID' => $arResult['REQUEST_AMOUNT'] . '@' . $arResult['REQUEST_ACCOUNT']));
     if ($arParams['PAY_IMMED']) {
         $ORDER_ID = CSaleOrder::Add(array('LID' => SITE_ID, 'PERSON_TYPE_ID' => $arParams['PERSON_TYPE'], 'PRICE' => CCurrencyRates::ConvertCurrency($arResult['MONEY_OFF'], $arResult['REQUEST_ACCOUNT'], $arResult['LANG_CURRENCY']), 'CURRENCY' => $arResult['LANG_CURRENCY'], 'PAY_SYSTEM_ID' => $arResult['REQUEST_PAY_SYSTEM'], 'USER_ID' => $USER->getID()));
         if ($ORDER_ID > 0) {
             $arOrder = CSaleOrder::GetByID($ORDER_ID);
             CSaleBasket::OrderBasket($ORDER_ID);
         }
         $arPaySysAction = $arResult['PAY_SYSTEMS'][$arResult['REQUEST_PAY_SYSTEM']];
         if (strlen($arPaySysAction['ACTION_FILE']) > 0) {
             CSalePaySystemAction::InitParamArrays($arOrder, $ORDER_ID, $arPaySysAction['PARAMS']);
             $pathToAction = $_SERVER['DOCUMENT_ROOT'] . $arPaySysAction['ACTION_FILE'];
             $pathToAction = rtrim(str_replace('\\', '/', $pathToAction), '/');
             if (file_exists($pathToAction)) {
                 if (is_dir($pathToAction)) {
                     if (file_exists($pathToAction . '/payment.php')) {
                         include $pathToAction . '/payment.php';
                     }
                 } else {
コード例 #3
0
ファイル: order.php プロジェクト: akniyev/itprom_dobrohost
 /**
  *
  *
  */
 public static function DoSaveOrder(&$arOrder, $arAdditionalFields, $orderId, &$arErrors, $arCoupons = array(), $arStoreBarcodeOrderFormData = array(), $bSaveBarcodes = false)
 {
     global $APPLICATION;
     $orderId = (int) $orderId;
     $isNew = $orderId <= 0;
     $isOrderConverted = \Bitrix\Main\Config\Option::get("main", "~sale_converted_15", 'N');
     $arFields = array("ID" => $arOrder["ID"], "LID" => $arOrder["SITE_ID"], "PERSON_TYPE_ID" => $arOrder["PERSON_TYPE_ID"], "PRICE" => $arOrder["PRICE"], "CURRENCY" => $arOrder["CURRENCY"], "USER_ID" => $arOrder["USER_ID"], "PAY_SYSTEM_ID" => $arOrder["PAY_SYSTEM_ID"], "PRICE_DELIVERY" => $arOrder["DELIVERY_PRICE"], "DELIVERY_ID" => strlen($arOrder["DELIVERY_ID"]) > 0 ? $arOrder["DELIVERY_ID"] : false, "DISCOUNT_VALUE" => $arOrder["DISCOUNT_PRICE"], "TAX_VALUE" => $arOrder["TAX_VALUE"], "TRACKING_NUMBER" => $arOrder["TRACKING_NUMBER"]);
     if ($arOrder["DELIVERY_PRICE"] == $arOrder["PRICE_DELIVERY"] && isset($arOrder['PRICE_DELIVERY_DIFF']) && floatval($arOrder['PRICE_DELIVERY_DIFF']) > 0) {
         $arFields["DELIVERY_PRICE"] = $arOrder['PRICE_DELIVERY_DIFF'] + $arOrder["PRICE_DELIVERY"];
     }
     if ($orderId <= 0) {
         $arFields["PAYED"] = "N";
         $arFields["CANCELED"] = "N";
         $arFields["STATUS_ID"] = "N";
     }
     $arFields = array_merge($arFields, $arAdditionalFields);
     if (!$arOrder['LOCATION_IN_CODES']) {
         // it comes from places like crm_invoice`s Add() and tells us if we need to convert location props from ID to CODE
         static::TranslateLocationPropertyValues($arOrder["PERSON_TYPE_ID"], $arOrder["ORDER_PROP"]);
     }
     unset($arOrder['LOCATION_IN_CODES']);
     if ($isOrderConverted == "Y") {
         $orderFields = array_merge($arOrder, $arFields, $arAdditionalFields);
         if (isset($orderFields['CUSTOM_DISCOUNT_PRICE']) && $orderFields['CUSTOM_DISCOUNT_PRICE'] === true) {
             Sale\Compatible\DiscountCompatibility::reInit(Sale\Compatible\DiscountCompatibility::MODE_DISABLED);
         }
         if (!empty($arStoreBarcodeOrderFormData)) {
             $orderFields['BARCODE_LIST'] = $arStoreBarcodeOrderFormData;
         }
         $orderFields['BARCODE_SAVE'] = $bSaveBarcodes;
         if ($orderId > 0) {
             $orderFields['ID'] = $orderId;
         }
         /** @var Sale\Result $r */
         $r = Sale\Compatible\OrderCompatibility::modifyOrder(Sale\Compatible\OrderCompatibility::ORDER_COMPAT_ACTION_SAVE, $orderFields);
         if ($r->isSuccess()) {
             $orderId = $r->getId();
         } else {
             foreach ($r->getErrorMessages() as $error) {
                 $arErrors[] = $error;
                 $APPLICATION->ThrowException($error);
             }
             return false;
         }
     } else {
         if ($orderId > 0) {
             $orderId = CSaleOrder::Update($orderId, $arFields);
         } else {
             if (COption::GetOptionString("sale", "product_reserve_condition", "O") == "O") {
                 $arFields["RESERVED"] = "Y";
             }
             $orderId = CSaleOrder::Add($arFields);
         }
         $orderId = (int) $orderId;
         if ($orderId <= 0) {
             if ($ex = $APPLICATION->GetException()) {
                 $arErrors[] = $ex->GetString();
             } else {
                 $arErrors[] = Loc::getMessage("SOA_ERROR_ORDER");
             }
         }
         if (!empty($arErrors)) {
             return null;
         }
         CSaleBasket::DoSaveOrderBasket($orderId, $arOrder["SITE_ID"], $arOrder["USER_ID"], $arOrder["BASKET_ITEMS"], $arErrors, $arCoupons, $arStoreBarcodeOrderFormData, $bSaveBarcodes);
         CSaleTax::DoSaveOrderTax($orderId, $arOrder["TAX_LIST"], $arErrors);
         CSaleOrderProps::DoSaveOrderProps($orderId, $arOrder["PERSON_TYPE_ID"], $arOrder["ORDER_PROP"], $arErrors);
         Sale\DiscountCouponsManager::finalApply();
         Sale\DiscountCouponsManager::saveApplied();
         foreach (GetModuleEvents("sale", "OnOrderSave", true) as $arEvent) {
             ExecuteModuleEventEx($arEvent, array($orderId, $arFields, $arOrder, $isNew));
         }
     }
     return $orderId;
 }
コード例 #4
0
ファイル: history.php プロジェクト: Ksenobyte/bitrix-module
            '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 (\IntaroCrm\Exception\CurlException $e) {
                ICrmOrderActions::eventLog(
                    'ICrmOrderActions::orderHistory', 'RetailCrm\RestApi::orderFixExternalIds::CurlException',
                    $e->getCode() . ': ' . $e->getMessage()
                );

                die();
            }
        }
        $order['externalId'] = $externalId;
    }
コード例 #5
0
ファイル: step1.php プロジェクト: ASDAFF/entask.ru
		function __MakeOrder($prdCnt=1, $arData = Array())
		{
			global $APPLICATION, $USER, $DB;
			CModule::IncludeModule("iblock");
			CModule::IncludeModule("sale");
			CModule::IncludeModule("catalog");
			$arPrd = Array();
			$dbItem = CIBlockElement::GetList(Array("PROPERTY_MORE_PHOTO" => "DESC", "ID" => "ASC"), Array("IBLOCK_TYPE" => "offers", "IBLOCK_SITE_ID" => WIZARD_SITE_ID, "PROPERTY_NEWPRODUCT" => false), false, Array("nTopCount" => 10), Array("ID", "IBLOCK_ID", "XML_ID", "NAME", "DETAIL_PAGE_URL", "IBLOCK_XML_ID"));
			while($arItem = $dbItem->GetNext())
				$arPrd[] = $arItem;

			if(!empty($arPrd))
			{
				for($i=0; $i<$prdCnt;$i++)
				{
					$prdID = $arPrd[mt_rand(0, 9)];
					$arProduct = CCatalogProduct::GetByID($prdID["ID"]);
					$CALLBACK_FUNC = "";
					$arCallbackPrice = CSaleBasket::ReReadPrice($CALLBACK_FUNC, "catalog", $prdID["ID"], 1);

					$arFields = array(
							"PRODUCT_ID" => $prdID["ID"],
							"PRODUCT_PRICE_ID" => $arCallbackPrice["PRODUCT_PRICE_ID"],
							"PRICE" => $arCallbackPrice["PRICE"],
							"CURRENCY" => $arCallbackPrice["CURRENCY"],
							"WEIGHT" => $arProduct["WEIGHT"],
							"QUANTITY" => 1,
							"LID" => WIZARD_SITE_ID,
							"DELAY" => "N",
							"CAN_BUY" => "Y",
							"NAME" => $prdID["NAME"],
							"CALLBACK_FUNC" => $CALLBACK_FUNC,
							"MODULE" => "catalog",
							"PRODUCT_PROVIDER_CLASS" => "CCatalogProductProvider",
							"ORDER_CALLBACK_FUNC" => "",
							"CANCEL_CALLBACK_FUNC" => "",
							"PAY_CALLBACK_FUNC" => "",
							"DETAIL_PAGE_URL" => $prdID["DETAIL_PAGE_URL"],
							"CATALOG_XML_ID" => $prdID["IBLOCK_XML_ID"],
							"PRODUCT_XML_ID" => $prdID["XML_ID"],
							"VAT_RATE" => $arCallbackPrice['VAT_RATE'],
						);
					$addres = CSaleBasket::Add($arFields);
				}

				$arOrder = Array(
						"LID" => $arData["SITE_ID"],
						"PERSON_TYPE_ID" => $arData["PERSON_TYPE_ID"],
						"PAYED" => "N",
						"CANCELED" => "N",
						"STATUS_ID" => "N",
						"PRICE" => 1,
						"CURRENCY" => $arData["CURRENCY"],
						"USER_ID" => $arData["USER_ID"],
						"PAY_SYSTEM_ID" => $arData["PAY_SYSTEM_ID"],
						//"PRICE_DELIVERY" => $arData["PRICE_DELIVERY"],
						//"DELIVERY_ID" => $arData["DELIVERY_ID"],
					);

				$dbFUserListTmp = CSaleUser::GetList(array("USER_ID" => $arData["USER_ID"]));
				if(empty($dbFUserListTmp))
				{
					$arFields = array(
							"=DATE_INSERT" => $DB->GetNowFunction(),
							"=DATE_UPDATE" => $DB->GetNowFunction(),
							"USER_ID" => $arData["USER_ID"]
						);

					$ID = CSaleUser::_Add($arFields);
				}

				$orderID = CSaleOrder::Add($arOrder);
				CSaleBasket::OrderBasket($orderID, CSaleBasket::GetBasketUserID(), WIZARD_SITE_ID);
				$dbBasketItems = CSaleBasket::GetList(
						array("NAME" => "ASC"),
						array(
								"FUSER_ID" => CSaleBasket::GetBasketUserID(),
								"LID" => WIZARD_SITE_ID,
								"ORDER_ID" => $orderID
							),
						false,
						false,
						array("ID", "CALLBACK_FUNC", "MODULE", "PRODUCT_ID", "QUANTITY", "DELAY", "CAN_BUY", "PRICE", "WEIGHT", "NAME")
					);
				$ORDER_PRICE = 0;
				while ($arBasketItems = $dbBasketItems->GetNext())
				{
					$ORDER_PRICE += roundEx($arBasketItems["PRICE"], SALE_VALUE_PRECISION) * DoubleVal($arBasketItems["QUANTITY"]);
				}

				$totalOrderPrice = $ORDER_PRICE + $arData["PRICE_DELIVERY"];
				CSaleOrder::Update($orderID, Array("PRICE" => $totalOrderPrice));
				foreach($arData["PROPS"] as $val)
				{
					$arFields = Array(
							"ORDER_ID" => $orderID,
							"ORDER_PROPS_ID" => $val["ID"],
							"NAME" => $val["NAME"],
							"CODE" => $val["CODE"],
							"VALUE" => $val["VALUE"],
						);
					CSaleOrderPropsValue::Add($arFields);
				}
				return $orderID;
			}
		}
コード例 #6
0
             $arFields["PAY_VOUCHER_NUM"] = $arOrder["PAY_VOUCHER_NUM"];
             $arFields["PAY_VOUCHER_DATE"] = $arOrder["PAY_VOUCHER_DATE"];
             $arFields["DELIVERY_DOC_NUM"] = $arOrder["DELIVERY_DOC_NUM"];
             $arFields["DELIVERY_DOC_DATE"] = $arOrder["DELIVERY_DOC_DATE"];
             $arFields["EMP_PAYED_ID"] = $arOrder["EMP_PAYED_ID"];
             $arFields["CANCELED"] = $arOrder["CANCELED"];
             $arFields["REASON_CANCELED"] = $arOrder["REASON_CANCELED"];
             $arFields["DATE_CANCELED"] = $arOrder["DATE_CANCELED"];
             $arFields["EMP_CANCELED_ID"] = $arOrder["EMP_CANCELED_ID"];
             $arFields["STATUS_ID"] = $arOrder["STATUS_ID"];
             $arFields["DATE_STATUS"] = $arOrder["DATE_STATUS"];
             $arFields["EMP_STATUS_ID"] = $arOrder["EMP_STATUS_ID"];
             $arFields["ALLOW_DELIVERY"] = $arOrder["ALLOW_DELIVERY"];
             $arFields["DATE_ALLOW_DELIVERY"] = $arOrder["DATE_ALLOW_DELIVERY"];
             $arFields["EMP_ALLOW_DELIVERY_ID"] = $arOrder["EMP_ALLOW_DELIVERY_ID"];
             $arIDs[$i] = CSaleOrder::Add($arFields);
             $arIDs[$i] = IntVal($arIDs[$i]);
             $res = $arIDs[$i] > 0;
         }
         if (!$res) {
             if ($ex = $APPLICATION->GetException()) {
                 $errorMessage .= $ex->GetString();
             } else {
                 $errorMessage .= GetMessage("SOE_ERROR_UPDATE") . ". ";
             }
         }
     }
 }
 if (StrLen($errorMessage) <= 0) {
     for ($i = 0; $i < count($arIDs); $i++) {
         if (IntVal($arIDs[$i]) > 0 && strlen($STATUS_ID) > 0 && $arOrder["STATUS_ID"] != $STATUS_ID) {
コード例 #7
0
ファイル: component.php プロジェクト: ASDAFF/entask.ru
				// add Guest ID
				if (CModule::IncludeModule("statistic"))
					$arFields["STAT_GID"] = CStatistic::GetEventParam();

				$affiliateID = CSaleAffiliate::GetAffiliate();
				if ($affiliateID > 0)
				{
					$dbAffiliat = CSaleAffiliate::GetList(array(), array("SITE_ID" => SITE_ID, "ID" => $affiliateID));
					$arAffiliates = $dbAffiliat->Fetch();
					if (count($arAffiliates) > 1)
						$arFields["AFFILIATE_ID"] = $affiliateID;
				}
				else
					$arFields["AFFILIATE_ID"] = false;

				$arResult["ORDER_ID"] = CSaleOrder::Add($arFields);
				$arResult["ORDER_ID"] = IntVal($arResult["ORDER_ID"]);
				if ($arResult["ORDER_ID"] <= 0)
				{
					if($ex = $APPLICATION->GetException())
						$arResult["ERROR"][] = $ex->GetString();
					else
						$arResult["ERROR"][] = GetMessage("SOA_ERROR_ORDER");
				}
				else
				{
					$arOrder = CSaleOrder::GetByID($arResult["ORDER_ID"]);
				}

				if (empty($arResult["ERROR"]))
				{
コード例 #8
0
                            $USER_DESCRIPTION .= $valProps['NAME'] . ' - ' . sestHL::getByIdHL(HL_BuyVariant, $valProps['VALUE'], true, 'UF_NAME') . ';';
                        } elseif ($valProps['CODE'] == 'HL_TypeLicenceIdB') {
                            $USER_DESCRIPTION .= $valProps['NAME'] . ' - ' . sestHL::getByIdHL(HL_TypeLicence, $valProps['VALUE'], true, 'UF_NAME') . ';';
                        } elseif ($valProps['CODE'] == 'HL_PeriodOfLicenceB') {
                            $USER_DESCRIPTION .= $valProps['NAME'] . ' - ' . sestHL::getByIdHL(HL_PeriodOfLicence, $valProps['VALUE'], true, 'UF_NAME') . ';';
                        } elseif ($valProps['CODE'] == 'HL_VersionB') {
                            $USER_DESCRIPTION .= $valProps['NAME'] . ' - ' . sestHL::getByIdHL(HL_Version, $valProps['VALUE'], true, 'UF_NAME') . ';';
                        }
                    }
                }
            }
            $index += 1;
        }
        //dd($USER_DESCRIPTION);
        $arFields = array("LID" => "s1", "PERSON_TYPE_ID" => 1, "PAYED" => "N", "CANCELED" => "N", "STATUS_ID" => "N", "PRICE" => $totalSum, "CURRENCY" => "UAH", "USER_ID" => IntVal($USER->GetID()), "PAY_SYSTEM_ID" => 1, "PRICE_DELIVERY" => 1, "DELIVERY_ID" => 1, "DISCOUNT_VALUE" => 0.0, "TAX_VALUE" => 0.0, "USER_DESCRIPTION" => $USER_DESCRIPTION);
        $ORDER_ID = CSaleOrder::Add($arFields);
        if ($ORDER_ID) {
            global $USER;
            $arEventFields = array("EMAIL" => $USER->GetEmail(), "ORDER_ID" => $ORDER_ID, "PRICE" => $_GET['totalSum']);
            CEvent::SendImmediate("SALE_NEW_ORDER_SEST", "s1", $arEventFields);
            //привязал корзину к заказу
            CSaleBasket::OrderBasket($ORDER_ID, 0, SITE_ID);
            //$_SESSION["SALE_USER_ID"]
            foreach ($arrCleanProducts as $key => $value) {
                $res = CSaleBasket::Update($value->elementBaskId, array('QUANTITY' => $value->quantity, 'PRICE' => $value->oneSum));
            }
        } else {
            //dd(bad);
        }
    }
}
コード例 #9
0
ファイル: order.php プロジェクト: ASDAFF/mp
<?php

require_once $_SERVER['DOCUMENT_ROOT'] . "/bitrix/modules/main/include/prolog_before.php";
CModule::IncludeModule("sale");
if (isset($_GET['order_basket'])) {
    $dbBasketItems = CSaleBasket::GetList(false, array("FUSER_ID" => CSaleBasket::GetBasketUserID(), "LID" => SITE_ID, "ORDER_ID" => "NULL"), false, false, array("ID", "QUANTITY", "PRICE"));
    $price = 0;
    while ($item = $dbBasketItems->Fetch()) {
        $price += intval($item['QUANTITY']) * $item['PRICE'];
    }
    $arFields = array("LID" => 's1', "PERSON_TYPE_ID" => 1, "PAYED" => "N", "CANCELED" => "N", "STATUS_ID" => "N", "PRICE" => $price, "CURRENCY" => "RUB", "USER_ID" => intval($USER->GetId()), "PAY_SYSTEM_ID" => 1, "USER_DESCRIPTION" => "");
    $orderId = CSaleOrder::Add($arFields);
    if (false === $orderId) {
        return false;
    }
    $user = CUser::GetByID($USER->GetId())->Fetch();
    $ar = array('ORDER_ID' => $orderId, 'ORDER_PROPS_ID' => 2, "NAME" => "Адрес доставки", "CODE" => "delivery_address", 'VALUE' => $user['PERSONAL_STREET']);
    CSaleOrderPropsValue::Add($ar);
    CSaleBasket::OrderBasket($orderId, $_SESSION["SALE_USER_ID"], SITE_ID);
    $tmp = explode(',', $user['NAME']);
    $eventFields = array('NAME' => $tmp[0], 'EMAIL' => $user['EMAIL']);
    $eventName = $user['PERSONAL_CITY'] == 'Москва' ? 'NEW_ORDER_MOSCOW' : 'NEW_ORDER_RUSSIA';
    CEvent::Send($eventName, 's1', $eventFields);
    CEvent::Send('NEW_ORDER_ADMIN', 's1', array());
    return true;
}
コード例 #10
0
ファイル: recurring.php プロジェクト: ASDAFF/bxApiDocs
	/**
	 * <p>Метод осуществляет продление подписки с кодом ID.</p> <p><b>Примечание</b>. Метод использует внутреннюю транзакцию. Если у вас используется <b>MySQL</b> и <b>InnoDB</b>, и ранее была открыта транзакция, то ее необходимо закрыть до подключения метода.</p>
	 *
	 *
	 *
	 *
	 * @param int $ID  Код записи с информацией о продлении.
	 *
	 *
	 *
	 * @return bool <p>Метод возвращает <i>true</i> в случае успешного продления или <i>false</i>
	 * в случае ошибки.</p><br><br>
	 *
	 * @static
	 * @link http://dev.1c-bitrix.ru/api_help/sale/classes/csalerecurring/csalerecurring.nextpayment.php
	 * @author Bitrix
	 */
	public static function NextPayment($ID)
	{
		global $DB;
		global $USER;

		$ID = IntVal($ID);
		if ($ID <= 0)
		{
			$GLOBALS["APPLICATION"]->ThrowException(GetMessage("SKGR_NO_RECID"), "NO_RECORD_ID");
			return False;
		}

		$arRecur = CSaleRecurring::GetByID($ID);
		if (!$arRecur)
		{
			$GLOBALS["APPLICATION"]->ThrowException(str_replace("#ID#", $ID, GetMessage("SKGR_NO_RECID1")), "NO_RECORD");
			return False;
		}

		$arOrder = CSaleOrder::GetByID($arRecur["ORDER_ID"]);
		if (!$arOrder)
		{
			$GLOBALS["APPLICATION"]->ThrowException(str_replace("#ID#", $arRecur["ORDER_ID"], GetMessage("SKGR_NO_ORDER1")), "NO_ORDER");
			return False;
		}


		$bSuccess = True;
		$newOrderID = IntVal($arRecur["ORDER_ID"]);

		/** @var $productProvider IBXSaleProductProvider */
		if ($productProvider = CSaleBasket::GetProductProvider($arRecur))
		{
			$arProduct = $productProvider::RecurringOrderProduct(array(
				"PRODUCT_ID" => $arRecur["PRODUCT_ID"],
				"USER_ID"    => $arOrder["USER_ID"]
			));
		}
		else
		{
			$arProduct = CSaleRecurring::ExecuteCallbackFunction(
					$arRecur["CALLBACK_FUNC"],
					$arRecur["MODULE"],
					$arRecur["PRODUCT_ID"],
					$arOrder["USER_ID"]
				);
		}

		if (!$arProduct || !is_array($arProduct) || count($arProduct) <= 0)
		{
			CSaleRecurring::CancelRecurring($arRecur["ID"], "Y", "Product is not found");

			/*
			$arFields = array(
					"CANCELED" => "Y",
					"DATE_CANCELED" => Date(CDatabase::DateFormatToPHP(CLang::GetDateFormat("FULL", LANG))),
					"CANCELED_REASON" => "Product is not found"
				);
			CSaleRecurring::Update($arRecur["ID"], $arFields);
			*/
			//CSaleRecurring::Delete($arRecur["ID"]);

			return True;
		}

		if ($arProduct["WITHOUT_ORDER"] == "Y" || $arRecur["SUCCESS_PAYMENT"] == "Y")
		{
			$baseSiteCurrency = CSaleLang::GetLangCurrency($arOrder["LID"]);
			$productPrice = roundEx(CCurrencyRates::ConvertCurrency($arProduct["PRICE"], $arProduct["CURRENCY"], $baseSiteCurrency), SALE_VALUE_PRECISION);

			// Delivery
			$deliveryPrice = 0;
			$deliveryID = 0;
			$arOrder["DELIVERY_ID"] = IntVal($arOrder["DELIVERY_ID"]);
			if ($arOrder["DELIVERY_ID"] > 0)
			{
				$deliveryLocation = 0;
				$dbOrderPropValues = CSaleOrderPropsValue::GetList(
						array(),
						array(
								"ORDER_ID" => $arRecur["ORDER_ID"],
								"PROP_IS_LOCATION" => "Y"
							),
						false,
						false,
						array("VALUE")
					);
				if ($arOrderPropValues = $dbOrderPropValues->Fetch())
					$deliveryLocation = IntVal($arOrderPropValues["VALUE"]);

				$dbDelivery = CSaleDelivery::GetList(
						array("SORT" => "ASC", "NAME" => "ASC"),
						array(
								"LID" => $arOrder["LID"],
								"WEIGHT" => DoubleVal($arProduct["WEIGHT"]) * DoubleVal($arProduct["QUANTITY"]), // Changed by Sigurd, 2007-08-16
								"ORDER_PRICE" => $productPrice * DoubleVal($arProduct["QUANTITY"]),
								"ACTIVE" => "Y",
								"LOCATION" => $deliveryLocation
							)
					);
				while ($arDelivery = $dbDelivery->Fetch())
				{
					$deliveryPriceTmp = roundEx(CCurrencyRates::ConvertCurrency($arDelivery["PRICE"], $arDelivery["CURRENCY"], $baseSiteCurrency), SALE_VALUE_PRECISION);
					if (IntVal($arDelivery["ID"]) == $arOrder["DELIVERY_ID"])
					{
						$deliveryID = IntVal($arDelivery["ID"]);
						$deliveryPrice = $deliveryPriceTmp;
						break;
					}
					if ($deliveryPriceTmp < $deliveryPrice || $deliveryID <= 0)
					{
						$deliveryID = IntVal($arDelivery["ID"]);
						$deliveryPrice = $deliveryPriceTmp;
					}
				}

				if ($deliveryID <= 0)
				{
					$GLOBALS["APPLICATION"]->ThrowException(GetMessage("SKGR_NO_DELIVERY"), "NO_DELIVERY");
					return False;
				}
			}

			// Sale discounts
			$discount = 0;
			$discountPrice = $productPrice;
			$discountProduct = 0;
			$dbDiscount = CSaleDiscount::GetList(
					array("SORT" => "ASC"),
					array(
							"LID" => $arOrder["LID"],
							"ACTIVE" => "Y",
							"!>ACTIVE_FROM" => Date($DB->DateFormatToPHP(CSite::GetDateFormat("FULL"))),
							"!<ACTIVE_TO" => Date($DB->DateFormatToPHP(CSite::GetDateFormat("FULL"))),
							"<=PRICE_FROM" => $productPrice,
							">=PRICE_TO" => $productPrice,
							"USER_GROUPS" => $USER->GetUserGroup($arOrder['USER_ID']),
						)
				);
			if ($arDiscount = $dbDiscount->Fetch())
			{
				if ($arDiscount["DISCOUNT_TYPE"] == "P")
				{
					$discountProduct = roundEx($productPrice * $arDiscount["DISCOUNT_VALUE"] / 100, SALE_VALUE_PRECISION);
					$discount = roundEx($discountProduct * DoubleVal($arProduct["QUANTITY"]), SALE_VALUE_PRECISION); // Changed by Sigurd, 2007-08-16
					$discountPrice = $productPrice - $discountProduct;
				}
				else
				{
					$discountValue = CCurrencyRates::ConvertCurrency($arDiscount["DISCOUNT_VALUE"], $arDiscount["CURRENCY"], $baseSiteCurrency);
					$discountValue = roundEx($discountValue, SALE_VALUE_PRECISION);

					$discountProduct = roundEx(1.0 * $discountValue / DoubleVal($arProduct["QUANTITY"]), SALE_VALUE_PRECISION);// Changed by Sigurd, 2007-08-16
					$discount = roundEx($curDiscount * DoubleVal($arProduct["QUANTITY"]), SALE_VALUE_PRECISION);
					$discountPrice = $productPrice - $discountProduct;
				}
			}

			$bUseVat = false;
			$vatRate = 0;
			if(DoubleVal($arProduct["VAT_RATE"]) > 0)
			{
				$bUseVat = true;
				$vatRate = $arProduct["VAT_RATE"];
			}

			// Tax
			$arTaxExempt = array();
			$dbUserGroups = CUser::GetUserGroupEx($arOrder["USER_ID"]);
			while ($arUserGroups = $dbUserGroups->Fetch())
			{
				$dbTaxExemptTmp = CSaleTax::GetExemptList(array("GROUP_ID" => $arUserGroups["GROUP_ID"]));
				while ($arTaxExemptTmp = $dbTaxExemptTmp->Fetch())
				{
					$arTaxExemptTmp["TAX_ID"] = IntVal($arTaxExemptTmp["TAX_ID"]);
					if (!in_array($arTaxExemptTmp["TAX_ID"], $arTaxExempt))
						$arTaxExempt[] = $arTaxExemptTmp["TAX_ID"];
				}
			}

			$taxPrice = 0;
			$taxVatPrice = 0;
			if(!$bUseVat)
			{
				$taxLocation = 0;
				$dbOrderPropValues = CSaleOrderPropsValue::GetList(
						array(),
						array(
								"ORDER_ID" => $arRecur["ORDER_ID"],
								"PROP_IS_LOCATION4TAX" => "Y"
							),
						false,
						false,
						array("VALUE")
					);
				if ($arOrderPropValues = $dbOrderPropValues->Fetch())
					$taxLocation = IntVal($arOrderPropValues["VALUE"]);

				$arTaxList = array();
				$dbTaxRateTmp = CSaleTaxRate::GetList(
						array("APPLY_ORDER" => "ASC"),
						array(
								"LID" => $arOrder["LID"],
								"PERSON_TYPE_ID" => $arOrder["PERSON_TYPE_ID"],
								"ACTIVE" => "Y",
								"LOCATION" => $taxLocation
							)
					);
				while ($arTaxRateTmp = $dbTaxRateTmp->Fetch())
				{
					if (!in_array(IntVal($arTaxRateTmp["TAX_ID"]), $arTaxExempt))
					{
						$arTaxList[] = $arTaxRateTmp;
					}
				}
			}
			else
			{
				$arTaxList[] = Array(
							"ID" => 0,
							"TAX_NAME" => GetMessage("SKGR_VAT"),
							"IS_PERCENT" => "Y",
							"VALUE" => $vatRate*100,
							"VALUE_MONEY" => 0,
							"APPLY_ORDER" => 100,
							"IS_IN_PRICE" => "Y",
							"CODE" => "VAT"
				);
			}


			$arTaxSums = array();

			if (!empty($arTaxList))
			{
				if(!$bUseVat)
				{
					$taxPriceTmp = CSaleOrderTax::CountTaxes(
							$discountPrice * DoubleVal($arProduct["QUANTITY"]),
							$arTaxList,
							$baseSiteCurrency
						);

					for ($di = 0, $intCount = count($arTaxList); $di < $intCount; $di++)
					{
						$arTaxList[$di]["VALUE_MONEY"] += $arTaxList[$di]["TAX_VAL"];
					}

					for ($di = 0, $intCount = count($arTaxList); $di < $intCount; $di++)
					{
						$arTaxSums[$arTaxList[$di]["TAX_ID"]]["VALUE"] = $arTaxList[$di]["VALUE_MONEY"];
						$arTaxSums[$arTaxList[$di]["TAX_ID"]]["NAME"] = $arTaxList[$di]["NAME"];
						if ($arTaxList[$di]["IS_IN_PRICE"] != "Y")
						{
							$taxPrice += $arTaxList[$di]["VALUE_MONEY"];
						}
					}
				}
				else
				{
					$arTaxList[0]["VALUE_MONEY"] = (($discountPrice / ($vatRate +1)) * $vatRate) * DoubleVal($arProduct["QUANTITY"]);
					$taxVatPrice = $arTaxList[0]["VALUE_MONEY"];
				}
			}


			// Changed by Sigurd, 2007-08-16
			$totalOrderPrice = $discountPrice * DoubleVal($arProduct["QUANTITY"]) + $deliveryPrice + $taxPrice;

			$arProduct["WITHOUT_ORDER"] = (($arProduct["WITHOUT_ORDER"]=="Y") ? "Y" : "N");
			if ($arProduct["WITHOUT_ORDER"] == "N")
			{
				$DB->StartTransaction();

				// Saving
				$arSaleUser = CSaleUser::GetList(Array(), Array("USER_ID" => $arOrder["USER_ID"]));
				if(!empty($arSaleUser))
				{
					$currentFUser = $arSaleUser["ID"];
				}
				else
				{
					$currentFUser = CSaleUser::_Add(
							array(
									"=DATE_INSERT" => $DB->GetNowFunction(),
									"=DATE_UPDATE" => $DB->GetNowFunction(),
									"USER_ID" => $arOrder["USER_ID"]
								)
						);
				}

				$arFields = array(
						"FUSER_ID" => $currentFUser,
						"PRODUCT_ID" => $arProduct["PRODUCT_ID"],
						"PRODUCT_NAME" => $arProduct["PRODUCT_NAME"],
						"PRODUCT_URL" => $arProduct["PRODUCT_URL"],
						"PRODUCT_PRICE_ID" => $arProduct["PRODUCT_PRICE_ID"],
						"PRICE" => $arProduct["PRICE"],
						"CURRENCY" => $arProduct["CURRENCY"],
						"WEIGHT" => $arProduct["WEIGHT"],
						"QUANTITY" => $arProduct["QUANTITY"],
						"LID" => $arOrder["LID"],
						"DELAY" => "N",
						"CAN_BUY" => "Y",
						"NAME" => $arProduct["NAME"],
						"CALLBACK_FUNC" => $arProduct["CALLBACK_FUNC"],
						"ORDER_CALLBACK_FUNC" => $arProduct["ORDER_CALLBACK_FUNC"],
						"CANCEL_CALLBACK_FUNC" => $arProduct["CANCEL_CALLBACK_FUNC"],
						"PAY_CALLBACK_FUNC" => $arProduct["PAY_CALLBACK_FUNC"],
						"PRODUCT_PROVIDER_CLASS" => $arProduct["PRODUCT_PROVIDER_CLASS"],
						"MODULE" => $arRecur["MODULE"],
						"NOTES" => $arProduct["CATALOG_GROUP_NAME"],
						"DETAIL_PAGE_URL" => $arProduct["DETAIL_PAGE_URL"],
						"VATE_RATE" => $arProduct["VATE_RATE"],
						"PRODUCT_XML_ID" => $arProduct["PRODUCT_XML_ID"],
						"RENEWAL" => "Y"
					);

				$basketID = CSaleBasket::Add($arFields);

				$basketID = IntVal($basketID);
				if ($basketID <= 0)
					$bSuccess = False;

				if ($bSuccess)
				{
					if (CModule::IncludeModule("statistic"))
						CStatistic::Set_Event("eStore", "add2basket", $arFields["PRODUCT_ID"]);

					$arFields = array(
							"LID" => $arOrder["LID"],
							"PERSON_TYPE_ID" => $arOrder["PERSON_TYPE_ID"],
							"PAYED" => "N",
							"CANCELED" => "N",
							"STATUS_ID" => "N",
							"PRICE_DELIVERY" => $deliveryPrice,
							"ALLOW_DELIVERY" => "N",
							"PRICE" => $totalOrderPrice,
							"CURRENCY" => $baseSiteCurrency,
							"DISCOUNT_VALUE" => $discount,
							"USER_ID" => $arOrder["USER_ID"],
							"PAY_SYSTEM_ID" => $arOrder["PAY_SYSTEM_ID"],
							"DELIVERY_ID" => $deliveryID,
							"USER_DESCRIPTION" => $arOrder["USER_DESCRIPTION"],
							"TAX_VALUE" => (($bUseVat)? $taxVatPrice : $taxPrice),
							"STAT_GID" => $arOrder["STAT_GID"],
							"RECURRING_ID" => $arRecur["ID"]
						);

					$newOrderID = CSaleOrder::Add($arFields);

					$newOrderID = IntVal($newOrderID);
					if ($newOrderID <= 0)
						$bSuccess = False;
				}

				if ($bSuccess)
				{
					$arDiscounts = array();
					$arDiscounts[$basketID] = $discountProduct;
					CSaleBasket::OrderBasket($newOrderID, $currentFUser, $arOrder["LID"], $arDiscounts);
				}

				if ($bSuccess)
				{
					for ($it = 0, $intCount = count($arTaxList); $it < $intCount; $it++)
					{
						$arFields = array(
							"ORDER_ID" => $newOrderID,
							"TAX_NAME" => $arTaxList[$it]["TAX_NAME"],
							"IS_PERCENT" => $arTaxList[$it]["IS_PERCENT"],
							"VALUE" => ($arTaxList[$it]["IS_PERCENT"]=="Y") ? $arTaxList[$it]["VALUE"] : RoundEx(CCurrencyRates::ConvertCurrency($arTaxList[$it]["VALUE"], $arTaxList[$it]["CURRENCY"], $baseSiteCurrency), 2),
							"VALUE_MONEY" => $arTaxList[$it]["VALUE_MONEY"],
							"APPLY_ORDER" => $arTaxList[$it]["APPLY_ORDER"],
							"IS_IN_PRICE" => $arTaxList[$it]["IS_IN_PRICE"],
							"CODE" => $arTaxList[$it]["CODE"]
							);
						CSaleOrderTax::Add($arFields);
					}

					$dbOrderPropValues = CSaleOrderPropsValue::GetList(
							array(),
							array("ORDER_ID" => $arRecur["ORDER_ID"]),
							false,
							false,
							array("ORDER_PROPS_ID", "NAME", "CODE", "VALUE", "PROP_IS_PAYER", "PROP_IS_EMAIL")
						);
					while ($arOrderPropValues = $dbOrderPropValues->Fetch())
					{
						$arFields = array(
							"ORDER_ID" => $newOrderID,
							"ORDER_PROPS_ID" => $arOrderPropValues["ORDER_PROPS_ID"],
							"NAME" => $arOrderPropValues["NAME"],
							"CODE" => $arOrderPropValues["CODE"],
							"VALUE" => $arOrderPropValues["VALUE"]
							);
						CSaleOrderPropsValue::Add($arFields);

						if ($arOrderPropValues["PROP_IS_PAYER"] == "Y")
							$payerName = $arOrderPropValues["VALUE"];
						if ($arOrderPropValues["PROP_IS_EMAIL"] == "Y")
							$payerEMail = $arOrderPropValues["VALUE"];
					}
				}

				if ($bSuccess)
				{
					if (CModule::IncludeModule("statistic"))
						CStatistic::Set_Event("eStore", "order_create", $newOrderID);
				}

				if ($bSuccess)
				{
					$strOrderList = "";
					$dbBasketTmp = CSaleBasket::GetList(
						array("NAME" => "ASC"),
						array("ORDER_ID" => $newOrderID)
					);
					while ($arBasketTmp = $dbBasketTmp->Fetch())
					{
						$strOrderList .= $arBasketTmp["NAME"]." - ".$arBasketTmp["QUANTITY"]." ".GetMessage("SALE_QUANTITY_UNIT");
						$strOrderList .= "\n";
					}

					if (strlen($payerName) <= 0 || strlen($payerEMail) <= 0)
					{
						$dbUser = CUser::GetByID($arOrder["USER_ID"]);
						if ($arUser = $dbUser->Fetch())
						{
							if (strlen($payerName) <= 0)
								$payerName = $arUser["NAME"].((strlen($arUser["NAME"])<=0 || strlen($arUser["LAST_NAME"])<=0) ? "" : " ").$arUser["LAST_NAME"];
							if (strlen($payerEMail) <= 0)
								$payerEMail = $arUser["EMAIL"];
						}
					}

					$arFields = Array(
						"ORDER_ID" => $newOrderID,
						"ORDER_DATE" => Date($DB->DateFormatToPHP(CLang::GetDateFormat("SHORT", $arOrder["LID"]))),
						"ORDER_USER" => $payerName,
						"PRICE" => SaleFormatCurrency($totalOrderPrice, $baseSiteCurrency),
						"BCC" => COption::GetOptionString("sale", "order_email", "order@".$SERVER_NAME),
						"EMAIL" => $payerEMail,
						"ORDER_LIST" => $strOrderList,
						"SALE_EMAIL" => COption::GetOptionString("sale", "order_email", "order@".$SERVER_NAME)
					);
					$eventName = "SALE_NEW_ORDER_RECURRING";

					$bSend = true;
					foreach(GetModuleEvents("sale", "OnOrderRecurringSendEmail", true) as $arEvent)
					{
						if (ExecuteModuleEventEx($arEvent, Array($newOrderID, &$eventName, &$arFields))===false)
							$bSend = false;
					}

					if($bSend)
					{
						$event = new CEvent;
						$event->Send($eventName, $arOrder["LID"], $arFields, "N");
					}
				}

				if ($bSuccess)
					$DB->Commit();
				else
					$DB->Rollback();
			}
		}
		else
		{
			$totalOrderPrice = $arOrder["PRICE"];
			$baseSiteCurrency = $arOrder["CURRENCY"];
		}

		$res = False;
		if ($bSuccess)
		{
			$res = CSaleUserAccount::Pay($arOrder["USER_ID"], $totalOrderPrice, $baseSiteCurrency, $newOrderID, True);
			if ($res)
			{
				if ($arProduct["WITHOUT_ORDER"] == "N")
				{
					CSaleOrder::PayOrder($newOrderID, "Y", False, False, $arRecur["ID"]);
					CSaleOrder::DeliverOrder($newOrderID, "Y", $arRecur["ID"]);
					CSaleOrder::DeductOrder($newOrderID, "Y", "", true, array(), $arRecur["ID"]);
				}
				else
				{
					/** @var $productProvider IBXSaleProductProvider */
					if ($productProvider = CSaleBasket::GetProductProvider($arProduct))
					{
						$r = $productProvider::DeliverProduct(array(
							"PRODUCT_ID" => $arProduct["PRODUCT_ID"],
							"USER_ID"    => $arOrder["USER_ID"],
							"PAID"       => true
						));
					}
					else
					{
						$r = CSaleBasket::ExecuteCallbackFunction(
							$arProduct["PAY_CALLBACK_FUNC"],
							$arRecur["MODULE"],
							$arProduct["PRODUCT_ID"],
							$arOrder["USER_ID"],
							true
						);
					}
				}

				$arFields = array(
					"ORDER_ID" => $newOrderID,
					"PRODUCT_NAME" => $arProduct["PRODUCT_NAME"],
					"PRODUCT_URL" => $arProduct["PRODUCT_URL"],
					"PRICE_TYPE" => $arProduct["PRICE_TYPE"],
					"RECUR_SCHEME_TYPE" => $arProduct["RECUR_SCHEME_TYPE"],
					"RECUR_SCHEME_LENGTH" => $arProduct["RECUR_SCHEME_LENGTH"],
					"WITHOUT_ORDER" => $arProduct["WITHOUT_ORDER"],
					"PRIOR_DATE" => Date($GLOBALS["DB"]->DateFormatToPHP(CLang::GetDateFormat("FULL", SITE_ID))),
					"NEXT_DATE" => $arProduct["NEXT_DATE"],
					"REMAINING_ATTEMPTS" => (Defined("SALE_PROC_REC_ATTEMPTS") ? SALE_PROC_REC_ATTEMPTS : 3),
					"SUCCESS_PAYMENT" => "Y"
				);

				CSaleRecurring::Update($arRecur["ID"], $arFields);
			}
			else
			{
				$arFields = array(
						"ORDER_ID" => $newOrderID,
						"PRODUCT_NAME" => $arProduct["PRODUCT_NAME"],
						"PRODUCT_URL" => $arProduct["PRODUCT_URL"],
						"PRICE_TYPE" => $arProduct["PRICE_TYPE"],
						"RECUR_SCHEME_LENGTH" => $arProduct["RECUR_SCHEME_LENGTH"],
						"RECUR_SCHEME_TYPE" => $arProduct["RECUR_SCHEME_TYPE"],
						"WITHOUT_ORDER" => $arProduct["WITHOUT_ORDER"],
						"NEXT_DATE" => Date($GLOBALS["DB"]->DateFormatToPHP(CLang::GetDateFormat("FULL", SITE_ID)), time() + SALE_PROC_REC_TIME + CTimeZone::GetOffset()),
						"REMAINING_ATTEMPTS" => (IntVal($arRecur["REMAINING_ATTEMPTS"]) - 1),
						"SUCCESS_PAYMENT" => "N"
					);
				CSaleRecurring::Update($arRecur["ID"], $arFields);

				if ((IntVal($arRecur["REMAINING_ATTEMPTS"]) - 1) <= 0)
				{
					CSaleRecurring::CancelRecurring($arRecur["ID"], "Y", "Can't pay order");
					/*
					$arFields["CANCELED"] = "Y";
					$arFields["DATE_CANCELED"] = Date(CDatabase::DateFormatToPHP(CLang::GetDateFormat("FULL", LANG)));
					$arFields["CANCELED_REASON"] = "Can't pay order";
					*/
				}
			}
		}

		return $res;
	}
コード例 #11
0
ファイル: order.php プロジェクト: DarneoStudio/bitrix
 /**
  *
  *
  */
 public static function DoSaveOrder(&$arOrder, $arAdditionalFields, $orderId, &$arErrors, $arCoupons = array(), $arStoreBarcodeOrderFormData = array(), $bSaveBarcodes = false)
 {
     global $APPLICATION;
     $orderId = (int) $orderId;
     $isNew = $orderId <= 0;
     $isOrderConverted = \Bitrix\Main\Config\Option::get("main", "~sale_converted_15", 'N');
     $arFields = array("ID" => $arOrder["ID"], "LID" => $arOrder["SITE_ID"], "PERSON_TYPE_ID" => $arOrder["PERSON_TYPE_ID"], "PRICE" => $arOrder["PRICE"], "CURRENCY" => $arOrder["CURRENCY"], "USER_ID" => $arOrder["USER_ID"], "PAY_SYSTEM_ID" => $arOrder["PAY_SYSTEM_ID"], "PRICE_DELIVERY" => $arOrder["DELIVERY_PRICE"], "DELIVERY_ID" => strlen($arOrder["DELIVERY_ID"]) > 0 ? $arOrder["DELIVERY_ID"] : false, "DISCOUNT_VALUE" => $arOrder["DISCOUNT_PRICE"], "TAX_VALUE" => $arOrder["TAX_VALUE"], "TRACKING_NUMBER" => $arOrder["TRACKING_NUMBER"]);
     if ($arOrder["DELIVERY_PRICE"] == $arOrder["PRICE_DELIVERY"] && isset($arOrder['PRICE_DELIVERY_DIFF']) && floatval($arOrder['PRICE_DELIVERY_DIFF']) > 0) {
         $arFields["DELIVERY_PRICE"] = $arOrder['PRICE_DELIVERY_DIFF'] + $arOrder["PRICE_DELIVERY"];
     }
     if ($orderId <= 0) {
         $arFields["PAYED"] = "N";
         $arFields["CANCELED"] = "N";
         $arFields["STATUS_ID"] = "N";
     }
     $arFields = array_merge($arFields, $arAdditionalFields);
     if (!$arOrder['LOCATION_IN_CODES']) {
         // it comes from places like crm_invoice`s Add() and tells us if we need to convert location props from ID to CODE
         static::TranslateLocationPropertyValues($arOrder["PERSON_TYPE_ID"], $arOrder["ORDER_PROP"]);
     }
     unset($arOrder['LOCATION_IN_CODES']);
     if ($isOrderConverted == "Y") {
         $orderFields = array_merge($arOrder, $arFields, $arAdditionalFields);
         if (!empty($arStoreBarcodeOrderFormData)) {
             $orderFields['BARCODE_LIST'] = $arStoreBarcodeOrderFormData;
         }
         $orderFields['BARCODE_SAVE'] = $bSaveBarcodes;
         if ($orderId > 0) {
             $orderFields['ID'] = $orderId;
         }
         /** @var Sale\Result $r */
         $r = Sale\Compatible\OrderCompatibility::modifyOrder(Sale\Compatible\OrderCompatibility::ORDER_COMPAT_ACTION_SAVE, $orderFields);
         if ($r->isSuccess()) {
             $orderId = $r->getId();
         } else {
             foreach ($r->getErrorMessages() as $error) {
                 $arErrors[] = $error;
                 $APPLICATION->ThrowException($error);
             }
             return false;
         }
     } else {
         if ($orderId > 0) {
             $orderId = CSaleOrder::Update($orderId, $arFields);
         } else {
             if (COption::GetOptionString("sale", "product_reserve_condition", "O") == "O") {
                 $arFields["RESERVED"] = "Y";
             }
             $orderId = CSaleOrder::Add($arFields);
         }
         $orderId = (int) $orderId;
         if ($orderId <= 0) {
             if ($ex = $APPLICATION->GetException()) {
                 $arErrors[] = $ex->GetString();
             } else {
                 $arErrors[] = Loc::getMessage("SOA_ERROR_ORDER");
             }
         }
         if (!empty($arErrors)) {
             return null;
         }
         CSaleBasket::DoSaveOrderBasket($orderId, $arOrder["SITE_ID"], $arOrder["USER_ID"], $arOrder["BASKET_ITEMS"], $arErrors, $arCoupons, $arStoreBarcodeOrderFormData, $bSaveBarcodes);
         CSaleTax::DoSaveOrderTax($orderId, $arOrder["TAX_LIST"], $arErrors);
         CSaleOrderProps::DoSaveOrderProps($orderId, $arOrder["PERSON_TYPE_ID"], $arOrder["ORDER_PROP"], $arErrors);
         Sale\DiscountCouponsManager::finalApply();
         Sale\DiscountCouponsManager::saveApplied();
         foreach (GetModuleEvents("sale", "OnOrderSave", true) as $arEvent) {
             ExecuteModuleEventEx($arEvent, array($orderId, $arFields, $arOrder, $isNew));
         }
     }
     /*
     			// mail message
     			if (empty($arResult["ERROR"]))
     			{
     				$strOrderList = "";
     				$dbBasketItems = CSaleBasket::GetList(
     						array("NAME" => "ASC"),
     						array("ORDER_ID" => $arResult["ORDER_ID"]),
     						false,
     						false,
     						array("ID", "NAME", "QUANTITY", "PRICE", "CURRENCY")
     					);
     				while ($arBasketItems = $dbBasketItems->Fetch())
     				{
     					$strOrderList .= $arBasketItems["NAME"]." - ".$arBasketItems["QUANTITY"]." ".Loc::getMessage("SOA_SHT").": ".SaleFormatCurrency($arBasketItems["PRICE"], $arBasketItems["CURRENCY"]);
     					$strOrderList .= "\n";
     				}
     
     				$arFields = Array(
     					"ORDER_ID" => $arResult["ORDER_ID"],
     					"ORDER_DATE" => Date($DB->DateFormatToPHP(CLang::GetDateFormat("SHORT", SITE_ID))),
     					"ORDER_USER" => ( (strlen($arUserResult["PAYER_NAME"]) > 0) ? $arUserResult["PAYER_NAME"] : $USER->GetFullName() ),
     					"PRICE" => SaleFormatCurrency($totalOrderPrice, $arResult["BASE_LANG_CURRENCY"]),
     					"BCC" => COption::GetOptionString("sale", "order_email", "order@".$SERVER_NAME),
     					"EMAIL" => (strlen($arUserResult["USER_EMAIL"])>0 ? $arUserResult["USER_EMAIL"] : $USER->GetEmail()),
     					"ORDER_LIST" => $strOrderList,
     					"SALE_EMAIL" => COption::GetOptionString("sale", "order_email", "order@".$SERVER_NAME),
     					"DELIVERY_PRICE" => $arResult["DELIVERY_PRICE"],
     				);
     				$eventName = "SALE_NEW_ORDER";
     
     				$bSend = true;
     				foreach(GetModuleEvents("sale", "OnOrderNewSendEmail", true) as $arEvent)
     					if (ExecuteModuleEventEx($arEvent, Array($arResult["ORDER_ID"], &$eventName, &$arFields))===false)
     						$bSend = false;
     
     				if($bSend)
     				{
     					$event = new CEvent;
     					$event->Send($eventName, SITE_ID, $arFields, "N");
     				}
     			}
     
     			if(CModule::IncludeModule("statistic"))
     			{
     				$event1 = "eStore";
     				$event2 = "order_confirm";
     				$event3 = $arResult["ORDER_ID"];
     
     				$e = $event1."/".$event2."/".$event3;
     
     				if(!is_array($_SESSION["ORDER_EVENTS"]) || (is_array($_SESSION["ORDER_EVENTS"]) && !in_array($e, $_SESSION["ORDER_EVENTS"])))
     				{
     						CStatistic::Set_Event($event1, $event2, $event3);
     						$_SESSION["ORDER_EVENTS"][] = $e;
     				}
     			}
     			$arOrder = CSaleOrder::GetByID($arResult["ORDER_ID"]);
     			foreach(GetModuleEvents("sale", "OnSaleComponentOrderOneStepComplete", true) as $arEvent)
     				ExecuteModuleEventEx($arEvent, Array($arResult["ORDER_ID"], $arOrder));
     */
     return $orderId;
 }
コード例 #12
0
ファイル: class.php プロジェクト: ASDAFF/order_click
    public static function AddProduct ($idProduct, $quantity, $arRewriteFields, $arProductParams, $userId, $currency, $personType, $clearCart) {
		if (CModule::IncludeModule("catalog")) {
			
			global $DB;
			global $USER;
				
			if ($clearCart == "Y" && (int)$idProduct > 0) {
				CSaleBasket::DeleteAll(CSaleBasket::GetBasketUserID());
			}
			
			if (Add2BasketByProductID( $idProduct, $quantity, $arRewriteFields, $arProductParams)) { // В корзину
			
				// Получаю параметры корзины
				$dbBasketItems = CSaleBasket::GetList(array("NAME" => "ASC", "ID" => "ASC"), array("FUSER_ID" => CSaleBasket::GetBasketUserID(), "ORDER_ID" => "NULL"), false, false, array("ID", "PRODUCT_ID", "QUANTITY", "DELAY", "CAN_BUY", "PRICE", "NAME"));
				while ($arItems = $dbBasketItems->Fetch())	{
						$arBasketItems[] = $arItems;
				}
				
				foreach ($arBasketItems as $valBasketItems) {
					$productPriceSumm = $productPriceSumm + ((int)$valBasketItems["QUANTITY"]*(int)$valBasketItems["PRICE"]);
				}
				
				
				$strOrderList = "";

				foreach ($arBasketItems as $arItem)
				{
					$measureText = (isset($arItem["MEASURE_TEXT"]) && strlen($arItem["MEASURE_TEXT"])) ? $arItem["MEASURE_TEXT"] : GetMessage("SOA_SHT");

					$strOrderList .= $arItem["NAME"]." - ".$arItem["QUANTITY"]." ".$measureText.": ".SaleFormatCurrency($arItem["PRICE"], $arItem["CURRENCY"]);
					$strOrderList .= "\n";
				}
				
				
				// Создаю заказ
				$arOrderFields = array(
					"LID" => SITE_ID,
					"PERSON_TYPE_ID" => $personType,
					"PAYED" => "N",
					"CANCELED" => "N",
					"STATUS_ID" => "N",
					"PRICE" => $productPriceSumm,
					"CURRENCY" => $currency,
					"USER_ID" => $userId,
					"USER_DESCRIPTION" => "",
					"ADDITIONAL_INFO" => ""
				);
				
				$ORDER_ID = CSaleOrder::Add($arOrderFields);
				
				// Привязываем товары из корзины текущего пользователя к заказу			
				
				CSaleBasket::OrderBasket($ORDER_ID, CSaleBasket::GetBasketUserID(), SITE_ID, false);

				$rsUser = CUser::GetByID($userId);
				$arUser = $rsUser->Fetch();
				
				$arFields = Array(
					"ORDER_ID" => $ORDER_ID,
					"ORDER_DATE" => Date($DB->DateFormatToPHP(CLang::GetDateFormat("SHORT", SITE_ID))),
					"ORDER_USER" => $arUser["NAME"],
					"PRICE" => $productPriceSumm,
					"BCC" => COption::GetOptionString("sale", "order_email", "order@".$SERVER_NAME),
					"EMAIL" => (strlen($arUserResult["USER_EMAIL"])>0 ? $arUserResult["USER_EMAIL"] : $USER->GetEmail()),
					"ORDER_LIST" => $strOrderList,
					"SALE_EMAIL" => COption::GetOptionString("sale", "order_email", "order@".$SERVER_NAME),
						
				);

				$eventName = "SALE_NEW_ORDER";

					$event = new CEvent;
					$event->Send($eventName, SITE_ID, $arFields, "N");
					
				
				return $ORDER_ID;
				
			}

			
		} else {
			return false;
		}
	}
コード例 #13
0
ファイル: step1.php プロジェクト: webgksupport/alpina
 function __MakeOrder($prdCnt = 1, $arData = array())
 {
     global $APPLICATION, $USER, $DB;
     CModule::IncludeModule("iblock");
     CModule::IncludeModule("sale");
     CModule::IncludeModule("catalog");
     $arPrd = array();
     $dbItem = CIBlockElement::GetList(array(), array("IBLOCK_TYPE" => "offers", "IBLOCK_SITE_ID" => WIZARD_SITE_ID, "PROPERTY_NEWPRODUCT" => false), false, array("nTopCount" => 100), array("ID", "IBLOCK_ID", "XML_ID", "NAME", "DETAIL_PAGE_URL", "IBLOCK_XML_ID"));
     while ($arItem = $dbItem->GetNext()) {
         $arPrd[] = $arItem;
     }
     if (!empty($arPrd)) {
         $arOrder = array("LID" => $arData["SITE_ID"], "PERSON_TYPE_ID" => $arData["PERSON_TYPE_ID"], "PAYED" => "N", "CANCELED" => "N", "STATUS_ID" => "N", "PRICE" => 1, "CURRENCY" => $arData["CURRENCY"], "USER_ID" => $arData["USER_ID"], "PAY_SYSTEM_ID" => $arData["PAY_SYSTEM_ID"]);
         $fuserID = 0;
         $dbFUserListTmp = CSaleUser::GetList(array("USER_ID" => $arData["USER_ID"]));
         if (empty($dbFUserListTmp)) {
             $arFields = array("=DATE_INSERT" => $DB->GetNowFunction(), "=DATE_UPDATE" => $DB->GetNowFunction(), "USER_ID" => $arData["USER_ID"]);
             $fuserID = CSaleUser::_Add($arFields);
         } else {
             $fuserID = $dbFUserListTmp['ID'];
         }
         $orderID = CSaleOrder::Add($arOrder);
         CCatalogProduct::setPriceVatIncludeMode(true);
         CCatalogProduct::setUsedCurrency(CSaleLang::GetLangCurrency(WIZARD_SITE_ID));
         CCatalogProduct::setUseDiscount(true);
         for ($i = 0; $i < $prdCnt; $i++) {
             $prdID = $arPrd[mt_rand(20, 99)];
             $arProduct = CCatalogProduct::GetByID($prdID["ID"]);
             $arPrice = CCatalogProduct::GetOptimalPrice($prdID["ID"], 1, array(2), 'N', array(), WIZARD_SITE_ID, array());
             $arFields = array("IGNORE_CALLBACK_FUNC" => "Y", "PRODUCT_ID" => $prdID["ID"], "PRODUCT_PRICE_ID" => $arPrice['PRICE']['ID'], "BASE_PRICE" => $arPrice['RESULT_PRICE']['BASE_PRICE'], "PRICE" => $arPrice['RESULT_PRICE']['DISCOUNT_PRICE'], "VAT_RATE" => $arPrice['PRICE']['VAT_RATE'], "CURRENCY" => $arPrice['RESULT_PRICE']['CURRENCY'], "WEIGHT" => $arProduct["WEIGHT"], "DIMENSIONS" => serialize(array("WIDTH" => $arProduct["WIDTH"], "HEIGHT" => $arProduct["HEIGHT"], "LENGTH" => $arProduct["LENGTH"])), "QUANTITY" => 1, "LID" => WIZARD_SITE_ID, "DELAY" => "N", "CAN_BUY" => "Y", "NAME" => $prdID["NAME"], "CALLBACK_FUNC" => "", "MODULE" => "catalog", "PRODUCT_PROVIDER_CLASS" => "CCatalogProductProvider", "ORDER_CALLBACK_FUNC" => "", "CANCEL_CALLBACK_FUNC" => "", "PAY_CALLBACK_FUNC" => "", "DETAIL_PAGE_URL" => $prdID["DETAIL_PAGE_URL"], "CATALOG_XML_ID" => $prdID["IBLOCK_XML_ID"], "PRODUCT_XML_ID" => $prdID["XML_ID"], "NOTES" => $arPrice["PRICE"]["CATALOG_GROUP_NAME"], "FUSER_ID" => $fuserID, "ORDER_ID" => $orderID);
             $addres = CSaleBasket::Add($arFields);
         }
         $dbBasketItems = CSaleBasket::GetList(array(), array("ORDER_ID" => $orderID), false, false, array("ID", "QUANTITY", "PRICE"));
         $ORDER_PRICE = 0;
         while ($arBasketItems = $dbBasketItems->GetNext()) {
             $ORDER_PRICE += roundEx($arBasketItems["PRICE"], SALE_VALUE_PRECISION) * DoubleVal($arBasketItems["QUANTITY"]);
         }
         $totalOrderPrice = $ORDER_PRICE + $arData["PRICE_DELIVERY"];
         CSaleOrder::Update($orderID, array("PRICE" => $totalOrderPrice));
         foreach ($arData["PROPS"] as $val) {
             $arFields = array("ORDER_ID" => $orderID, "ORDER_PROPS_ID" => $val["ID"], "NAME" => $val["NAME"], "CODE" => $val["CODE"], "VALUE" => $val["VALUE"]);
             CSaleOrderPropsValue::Add($arFields);
         }
         return $orderID;
     }
 }
コード例 #14
0
 /**
  *
  * 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;
 }
コード例 #15
-1
ファイル: order.php プロジェクト: k-kalashnikov/geekcon_new
 static function DoSaveOrder(&$arOrder, $arAdditionalFields, $orderId, &$arErrors, $arCoupons = array(), $arStoreBarcodeOrderFormData = array(), $bSaveBarcodes = false)
 {
     global $APPLICATION;
     $orderId = intval($orderId);
     $arFields = array("LID" => $arOrder["SITE_ID"], "PERSON_TYPE_ID" => $arOrder["PERSON_TYPE_ID"], "PRICE" => $arOrder["PRICE"], "CURRENCY" => $arOrder["CURRENCY"], "USER_ID" => $arOrder["USER_ID"], "PAY_SYSTEM_ID" => $arOrder["PAY_SYSTEM_ID"], "PRICE_DELIVERY" => $arOrder["DELIVERY_PRICE"], "DELIVERY_ID" => strlen($arOrder["DELIVERY_ID"]) > 0 ? $arOrder["DELIVERY_ID"] : false, "DISCOUNT_VALUE" => $arOrder["DISCOUNT_PRICE"], "TAX_VALUE" => $arOrder["TAX_VALUE"]);
     if ($orderId <= 0) {
         $arFields["PAYED"] = "N";
         $arFields["CANCELED"] = "N";
         $arFields["STATUS_ID"] = "N";
     }
     $arFields = array_merge($arFields, $arAdditionalFields);
     if ($orderId > 0) {
         $orderId = CSaleOrder::Update($orderId, $arFields);
     } else {
         if (COption::GetOptionString("sale", "product_reserve_condition", "O") == "O") {
             $arFields["RESERVED"] = "Y";
         }
         $orderId = CSaleOrder::Add($arFields);
     }
     $orderId = intval($orderId);
     if ($orderId <= 0) {
         if ($ex = $APPLICATION->GetException()) {
             $arErrors[] = $ex->GetString();
         } else {
             $arErrors[] = GetMessage("SOA_ERROR_ORDER");
         }
     }
     if (count($arErrors) > 0) {
         return null;
     }
     CSaleBasket::DoSaveOrderBasket($orderId, $arOrder["SITE_ID"], $arOrder["USER_ID"], $arOrder["BASKET_ITEMS"], $arErrors, $arCoupons, $arStoreBarcodeOrderFormData, $bSaveBarcodes);
     CSaleTax::DoSaveOrderTax($orderId, $arOrder["TAX_LIST"], $arErrors);
     CSaleOrderProps::DoSaveOrderProps($orderId, $arOrder["PERSON_TYPE_ID"], $arOrder["ORDER_PROP"], $arErrors);
     /*
     			// mail message
     			if (empty($arResult["ERROR"]))
     			{
     				$strOrderList = "";
     				$dbBasketItems = CSaleBasket::GetList(
     						array("NAME" => "ASC"),
     						array("ORDER_ID" => $arResult["ORDER_ID"]),
     						false,
     						false,
     						array("ID", "NAME", "QUANTITY", "PRICE", "CURRENCY")
     					);
     				while ($arBasketItems = $dbBasketItems->Fetch())
     				{
     					$strOrderList .= $arBasketItems["NAME"]." - ".$arBasketItems["QUANTITY"]." ".GetMessage("SOA_SHT").": ".SaleFormatCurrency($arBasketItems["PRICE"], $arBasketItems["CURRENCY"]);
     					$strOrderList .= "\n";
     				}
     
     				$arFields = Array(
     					"ORDER_ID" => $arResult["ORDER_ID"],
     					"ORDER_DATE" => Date($DB->DateFormatToPHP(CLang::GetDateFormat("SHORT", SITE_ID))),
     					"ORDER_USER" => ( (strlen($arUserResult["PAYER_NAME"]) > 0) ? $arUserResult["PAYER_NAME"] : $USER->GetFullName() ),
     					"PRICE" => SaleFormatCurrency($totalOrderPrice, $arResult["BASE_LANG_CURRENCY"]),
     					"BCC" => COption::GetOptionString("sale", "order_email", "order@".$SERVER_NAME),
     					"EMAIL" => (strlen($arUserResult["USER_EMAIL"])>0 ? $arUserResult["USER_EMAIL"] : $USER->GetEmail()),
     					"ORDER_LIST" => $strOrderList,
     					"SALE_EMAIL" => COption::GetOptionString("sale", "order_email", "order@".$SERVER_NAME),
     					"DELIVERY_PRICE" => $arResult["DELIVERY_PRICE"],
     				);
     				$eventName = "SALE_NEW_ORDER";
     
     				$bSend = true;
     				foreach(GetModuleEvents("sale", "OnOrderNewSendEmail", true) as $arEvent)
     					if (ExecuteModuleEventEx($arEvent, Array($arResult["ORDER_ID"], &$eventName, &$arFields))===false)
     						$bSend = false;
     
     				if($bSend)
     				{
     					$event = new CEvent;
     					$event->Send($eventName, SITE_ID, $arFields, "N");
     				}
     			}
     
     			if(CModule::IncludeModule("statistic"))
     			{
     				$event1 = "eStore";
     				$event2 = "order_confirm";
     				$event3 = $arResult["ORDER_ID"];
     
     				$e = $event1."/".$event2."/".$event3;
     
     				if(!is_array($_SESSION["ORDER_EVENTS"]) || (is_array($_SESSION["ORDER_EVENTS"]) && !in_array($e, $_SESSION["ORDER_EVENTS"])))
     				{
     						CStatistic::Set_Event($event1, $event2, $event3);
     						$_SESSION["ORDER_EVENTS"][] = $e;
     				}
     			}
     			$arOrder = CSaleOrder::GetByID($arResult["ORDER_ID"]);
     			foreach(GetModuleEvents("sale", "OnSaleComponentOrderOneStepComplete", true) as $arEvent)
     				ExecuteModuleEventEx($arEvent, Array($arResult["ORDER_ID"], $arOrder));
     */
     return $orderId;
 }