КОРЗИНА / Корзина «В один клик»

Заметка создана: 02 апреля 2025 г.

В данном решении за основу взята стандартная ТДС1 «Интернет-магазин корзина» из релиза 6.1.2. Все заложенные возможности стандартной корзины сохранены.
1 ТДС – аббв. от Типовая динамическая страница.
2 ЦА – аббв. от Центр администрирования.
 
ВНИМАНИЕ! Если возникают ошибки в работе данного решения, установленного в релиз HostCMS v.6, отличающийся от вышеуказанного, необходимо написать разработчикам CMS-Modules для устранения проблем с совместимостью.
Все шаги оформления заказа объединены на одной странице. Пользователю достаточно заполнить необходимые данные и один раз нажать «Оформить заказ».
Списки платежных систем и форм оплаты обновляются посредством AJAX-технологии при каждом изменении пользователем значимых данных. Поэтому решение предназначено только для пользователей, у которых в браузере не отключен JavaScript.
 
 
Установка решения на HostCMS v.6
 

  1. Необходимо перейти в раздел «Типовые динамические страницы» ЦА2 .
     
  2. В разделе ТДС «Интернет-магазин» скопировать стандартную ТДС «Интернет-магазин корзина» (код 7), кликнув на пиктограмме .
     
  3. Отредактировать копию ТДС, кликнув на пиктограмме . Перейти на вкладку «Код страницы» и вставить php-код из файла lib.php вместо содержимого поля «PHP код типовой динамической страницы». Перейти на вкладку «Настройки страницы» и вставить php-код из файла lib_config.php вместо содержимого поля «Настройки типовой динамической страницы». Сохранить изменения, нажатием кнопки  "применить".
     
  4. Необходимо перейти в раздел «Структура сайта» ЦА.
     
  5. Отредактировать узел структуры «Корзина», который по умолчанию находится внутри узла структуры «Интернет-магазин» (код 42 в релизе 6.1.2). В качестве Типовой динамической страницы, необходимо указать ТДС из п.3. Указать значения параметров ТДС, исходя из нужд Вашего проекта (можно оставить значения, которые были у узла струтуры «Корзина»). Сохранить изменения, нажатием кнопки  "применить" .
     
  6. Отредактировать XSL-шаблоны «МагазинКорзина», «МагазинАдресДоставки», «МагазинДоставки» и «МагазинПлатежнаяСистема» с учетом следующих требований:
    a. Обязательно в используемых XSL-шаблонах следует удалить теги <form> и </form>.
    b. Следует удалить кнопки перехода на следующий шаг во всех шаблонах, кроме «МагазинПлатежнаяСистема».

    Для XSL-шаблоны «МагазинКорзина», это фрагмент кода:

    <xsl:if test="count(shop_cart[postpone = 0]) and siteuser_id > 0 or siteuser_id = 0">
    <input name="step" value="1" type="hidden" />
    <input value="Оформить заказ" type="submit" class="button"/>
    </xsl:if>

    Для XSL-шаблоны «МагазинАдресДоставки», это фрагмент кода:

    <div class="row">
    <div class="caption"></div>
    <div class="field">
    <input name="step" value="2" type="hidden" />
    <input value="Далее →" type="submit" class="button" />
    </div>
    </div>


    Для XSL-шаблоны «МагазинДоставки», это фрагмент кода:

    <input name="step" value="3" type="hidden" />
    <input value="Далее →" type="submit" class="button" />
  7. Проверить работу 


ВОЗМОЖНЫЕ ОШИБКИ:



При возникновении ошибки:

Exception: The method 'shop_delivery_id' does not exist in
'Shop_Payment_System_Controller_Show'
29 modules/core/exception.php
110 modules/core/servant/properties.php
458 hostcmsfiles/lib/lib_47/lib_47.php
268 modules/lib/model.php
100 modules/core/page.php
4 templates/template14/template.htm
83 modules/template/model.php
100 modules/core/page.php
129 templates/template13/template.htm
83 modules/template/model.php
100 modules/core/page.php
363 modules/core/command/controller/default.php
188 modules/core/router/route.php
205 index.php


Закомментировать строку в типовой, где присутствует ->shop_delivery_id(....

При отсутствии Городов в АдресеДоставки (Корзина)
 
В настройках типовой сделать правку. Заменить:

$aArray = array('…');
foreach ($aObjects as $Object)
{
$aArray['_' .$Object->id] = $Object->name;
}

на 

$aArray = array('…');
foreach ($aObjects as $Object)
{
$aArray[$Object->id] = $Object->name;//'_' .
}

В XSL Адрес Доставки заменить

<SCRIPT type="text/javascript">
$(function() {
$.loadLocations('<xsl:value-of select="/shop/url" />cart/', $('#shop_country_id').val());
});
</SCRIPT>

на 

<script>
$(function() {
$('#shop_country_id').change();
//$.loadLocations('<xsl:value-of select="/shop/url" />cart/', $('#shop_country_id option[selected]').val());
});
</script>

Если используется проверка заполнения формы, то скрипт расположить в Макете, а  onSubmit = "return Formdata(this)" добавить в коде Типовой корзины в строке:
          echo '<form method="post" action="./" id="cmsm-form-cart"  onSubmit = "return Formdata(this)">';


LIB.PHP

для v.6.8.0 и выше
Код ТДС

<?php


$Shop_Cart_Controller_Show = Core_Page::instance()->object;


$oShop = $Shop_Cart_Controller_Show->getEntity();


Shop_Payment_System_Handler::checkAfterContent($oShop);


Shop_Delivery_Handler::checkAfterContent($oShop);


// ------------------------------------------------
// Вывод информации о статусе платежа после его совершения и перенаправления с платежной системы
// ------------------------------------------------
if (isset($_REQUEST['payment']) || (isset($_GET['action']) && ($_GET['action'] == 'PaymentSuccess' || $_GET['action'] == 'PaymentFail')) || isset($_REQUEST['pg_order_id']))
{
     // Получаем ID заказа
     if (isset($_REQUEST['order_id']))
     {
          $order_id = intval(Core_Array::getRequest('order_id'));
     }
     //от Яндекса
     elseif(isset($_GET['orderNumber']))
     {
          $order_id = intval(Core_Array::getGet('orderNumber'));
     }
     //от PayPal
     elseif(isset($_REQUEST['invoice']))
     {
          $oShop_Order = Core_Entity::factory('Shop_Order')->getByGuid(Core_Array::getRequest('invoice'));
          $order_id = $oShop_Order ? intval($oShop_Order->id) : NULL;
     }
     //от IntellectMoney
     elseif(isset($_REQUEST['orderId']))
     {
          $order_id = intval(Core_Array::getGet('orderId'));
     }
     //от Platron
     elseif(isset($_REQUEST['pg_order_id']))
     {
          $order_id = intval(Core_Array::getRequest('pg_order_id'));
     }
     else
     {
          $order_id = intval(Core_Array::getRequest('InvId'));
     }


     $oShop_Order = Core_Entity::factory('Shop_Order')->find($order_id);


     if (Core::moduleIsActive('siteuser'))
     {
          $siteuser_id = 0;


          $oSiteuser = Core_Entity::factory('Siteuser')->getCurrent();
          if ($oSiteuser)
          {
               $siteuser_id = $oSiteuser->id;
          }
     }
     else
     {
          $siteuser_id = FALSE;
     }


     // Если заказ принадлежит текущему авторизированному пользователю
     if ($oShop_Order->siteuser_id == $siteuser_id)
     {
          if (Core_Array::getRequest('payment') == 'success' || Core_Array::getRequest('action') == 'PaymentSuccess' || Core_Array::getRequest('pg_order_id') > 0)
          {
               ?><h1>Подтверждение платежа</h1>
               <p>Спасибо, информация об оплате заказа <strong>№ <?php echo $oShop_Order->invoice?></strong>
получена.</p>
               <?php
          }
          else
          {
               ?><h1>Платеж не получен</h1>
               <p>К сожалению при оплате заказа <strong>№ <?php echo $oShop_Order->invoice?></strong> произошла ошибка.</p>
               <?php
          }
     }
     // Для случаев, когда отключен модуль "Пользователи сайта"
     elseif ($siteuser_id === FALSE)
     {
          ?><h1>Подтверждение платежа</h1>
          <p>Благодарим за посещение нашего магазина!</p>
          <?php
     }
     else
     {
          ?><h1>Ошибка</h1>
          <p>Неверный номер заказа!</p>
          <?php
     }


     // Прерываем выполнение типовой динамической страницы
     return TRUE;
}



$xslName = Core_Array::get(Core_Page::instance()->libParams, 'cartXsl');


Core_Session::start();


if (Core_Array::getPost('oneStepCheckout'))
{
    // Сбрасываем информацию о последнем заказе
    $_SESSION['last_order_id'] = 0;


    // Оформление в один шаг
    $Shop_Cart_Controller = Shop_Cart_Controller::instance();
    $aShop_Cart = $Shop_Cart_Controller->getAll($oShop);
    foreach ($aShop_Cart as $oShop_Cart)
    {
        $Shop_Cart_Controller
            ->shop_item_id($oShop_Cart->shop_item_id)
            ->delete();
    }


    $shop_item_id = intval(Core_Array::getRequest('shop_item_id'));


    if ($shop_item_id)
    {
        Shop_Cart_Controller::instance()
            ->shop_item_id($shop_item_id)
            ->quantity(floatval(Core_Array::getRequest('count', 1)))
            ->add();
    }


    $_SESSION['hostcmsOrder'] = array();


    $_SESSION['hostcmsOrder']['shop_country_id'] = intval(Core_Array::getPost('shop_country_id', 0));
    $_SESSION['hostcmsOrder']['shop_country_location_id'] = intval(Core_Array::getPost('shop_country_location_id', 0));
    $_SESSION['hostcmsOrder']['shop_country_location_city_id'] = intval(Core_Array::getPost('shop_country_location_city_id', 0));
    $_SESSION['hostcmsOrder']['shop_country_location_city_area_id'] = intval(Core_Array::getPost('shop_country_location_city_area_id', 0));
    $_SESSION['hostcmsOrder']['postcode'] = Core_Str::stripTags(strval(Core_Array::getPost('postcode')));
    $_SESSION['hostcmsOrder']['address'] = Core_Str::stripTags(strval(Core_Array::getPost('address')));
    $_SESSION['hostcmsOrder']['house'] = Core_Str::stripTags(strval(Core_Array::getPost('house')));
    $_SESSION['hostcmsOrder']['flat'] = Core_Str::stripTags(strval(Core_Array::getPost('flat')));
    $_SESSION['hostcmsOrder']['surname'] = Core_Str::stripTags(strval(Core_Array::getPost('surname')));
    $_SESSION['hostcmsOrder']['name'] = Core_Str::stripTags(strval(Core_Array::getPost('name')));
    $_SESSION['hostcmsOrder']['patronymic'] = Core_Str::stripTags(strval(Core_Array::getPost('patronymic')));
    $_SESSION['hostcmsOrder']['phone'] = Core_Str::stripTags(strval(Core_Array::getPost('phone')));
    $_SESSION['hostcmsOrder']['email'] = Core_Str::stripTags(strval(Core_Array::getPost('email')));
    $_SESSION['hostcmsOrder']['description'] = Core_Str::stripTags(strval(Core_Array::getPost('description')));


    // Additional order properties
    $_SESSION['hostcmsOrder']['properties'] = array();


    $oShop_Order_Property_List = Core_Entity::factory('Shop_Order_Property_List', $oShop->id);


    $aProperties = $oShop_Order_Property_List->Properties->findAll();
    foreach ($aProperties as $oProperty)
    {
        // Св-во может иметь несколько значений
        $aPropertiesValue = Core_Array::getPost('property_' . $oProperty->id);


        if (!is_null($aPropertiesValue))
        {
            !is_array($aPropertiesValue) && $aPropertiesValue = array($aPropertiesValue);
            foreach ($aPropertiesValue as $sPropertyValue)
            {
                $_SESSION['hostcmsOrder']['properties'][] = array($oProperty->id, $sPropertyValue);
            }
        }
    }


    $shop_delivery_condition_id = strval(Core_Array::getPost('shop_delivery_condition_id', 0));


    if (is_numeric($shop_delivery_condition_id))
    {
        $_SESSION['hostcmsOrder']['shop_delivery_condition_id'] = intval($shop_delivery_condition_id);


        $oShop_Delivery_Condition = Core_Entity::factory('Shop_Delivery_Condition', $_SESSION['hostcmsOrder']['shop_delivery_condition_id']);
        $_SESSION['hostcmsOrder']['shop_delivery_id'] = $oShop_Delivery_Condition->shop_delivery_id;
    }


    $_POST['step'] = 4;
}


// Проверяем наличие товара в корзины
$Shop_Cart_Controller = Shop_Cart_Controller::instance();
$aShop_Cart = $Shop_Cart_Controller->getAll($oShop);


switch (Core_Array::getPost('recount') || !count($aShop_Cart) ? 0 : Core_Array::getPost('step'))
{
     // Окончание оформления заказа
     case 4:
          // Сбрасываем информацию о последнем заказе
          $_SESSION['last_order_id'] = 0;
         
          // Заполнение данных доставки
          $_SESSION['hostcmsOrder']['shop_country_id'] = intval(Core_Array::getPost('shop_country_id', 0));
          $_SESSION['hostcmsOrder']['shop_country_location_id'] = intval(Core_Array::getPost('shop_country_location_id', 0));
          $_SESSION['hostcmsOrder']['shop_country_location_city_id'] = intval(Core_Array::getPost('shop_country_location_city_id', 0));
          $_SESSION['hostcmsOrder']['shop_country_location_city_area_id'] = intval(Core_Array::getPost('shop_country_location_city_area_id', 0));
          $_SESSION['hostcmsOrder']['postcode'] = strval(Core_Array::getPost('postcode'));
          $_SESSION['hostcmsOrder']['address'] = strval(Core_Array::getPost('address'));
          $_SESSION['hostcmsOrder']['surname'] = strval(Core_Array::getPost('surname'));
          $_SESSION['hostcmsOrder']['name'] = strval(Core_Array::getPost('name'));
          $_SESSION['hostcmsOrder']['patronymic'] = strval(Core_Array::getPost('patronymic'));
          $_SESSION['hostcmsOrder']['company'] = strval(Core_Array::getPost('company'));
          $_SESSION['hostcmsOrder']['phone'] = strval(Core_Array::getPost('phone'));
          $_SESSION['hostcmsOrder']['fax'] = strval(Core_Array::getPost('fax'));
          $_SESSION['hostcmsOrder']['email'] = strval(Core_Array::getPost('email'));
          $_SESSION['hostcmsOrder']['description'] = strval(Core_Array::getPost('description'));
          $_SESSION['hostcmsOrder']['tin'] = strval(Core_Array::getPost('tin'));
          $_SESSION['hostcmsOrder']['kpp'] = strval(Core_Array::getPost('kpp'));


          // Additional order properties
          $_SESSION['hostcmsOrder']['properties'] = array();


          $oShop_Order_Property_List = Core_Entity::factory('Shop_Order_Property_List', $oShop->id);


          $aProperties = $oShop_Order_Property_List->Properties->findAll();
          foreach ($aProperties as $oProperty){
               // Св-во может иметь несколько значений
               $aPropertiesValue = Core_Array::getPost('property_' . $oProperty->id);


               if (!is_null($aPropertiesValue))
               {
                    !is_array($aPropertiesValue) && $aPropertiesValue = array($aPropertiesValue);
                    foreach ($aPropertiesValue as $sPropertyValue)
                    {
                         $_SESSION['hostcmsOrder']['properties'][] = array($oProperty->id, $sPropertyValue);
                    }
               }
          }
          //~~ Заполнение данных доставки
    
          // Выбор условия доставки
          $shop_delivery_condition_id = strval(Core_Array::getPost('shop_delivery_condition_id', 0));


          if (is_numeric($shop_delivery_condition_id))
          {
               $_SESSION['hostcmsOrder']['shop_delivery_condition_id'] = intval($shop_delivery_condition_id);
          }
          else
          {
               $_SESSION['hostcmsOrder']['shop_delivery_condition_id'] = 0;


               // в shop_delivery_condition_id тогда "123#", ID элемента массива в сессии, в котором
               // хранится стоимость доставки, налог, название специфичного условия доставки
               list($shopDeliveryInSession) = explode('#', $shop_delivery_condition_id);


               if (isset($_SESSION['hostcmsOrder']['deliveries'][$shopDeliveryInSession]))
               {
                    $aTmp = $_SESSION['hostcmsOrder']['deliveries'][$shopDeliveryInSession];


                    $_SESSION['hostcmsOrder']['shop_delivery_id'] = $aTmp['shop_delivery_id'];
                    $_SESSION['hostcmsOrder']['shop_delivery_price'] = $aTmp['price'];
                    $_SESSION['hostcmsOrder']['shop_delivery_rate'] = $aTmp['rate'];
                    $_SESSION['hostcmsOrder']['shop_delivery_name'] = $aTmp['name'];
               }
          }
          //~~ Выбор условия доставки
    
          // Выбор формы оплаты
          $shop_payment_system_id = $_SESSION['hostcmsOrder']['shop_payment_system_id'] = intval(Core_Array::getPost('shop_payment_system_id', 0));


          // Если выбрана платежная система
          if ($_SESSION['hostcmsOrder']['shop_payment_system_id'])
          {
               Shop_Payment_System_Handler::factory(
                    Core_Entity::factory('Shop_Payment_System', $shop_payment_system_id)
               )
               ->orderParams($_SESSION['hostcmsOrder'])
               ->execute();
          }
          else
          {
               ?><h1>Ошибка! Не указана ни одна платежная система.</h1><?php
          }
          //~~ Выбор формы оплаты
     break;    
     // Адрес доставки
     case 1:
     // Способ доставки
     case 2:
     // Форма оплаты
     case 3:
     default:
          echo '<form method="post" action="./" id="cmsm-form-cart">';
          echo '<scr'.strtolower('I').'pt>';
          echo '$(function(){
               $("#cmsm-form-cart").on("change", "select[name=shop_country_id], select[name=shop_country_location_id], select[name=shop_country_location_city_id], select[name=shop_country_location_city_area_id], input[name=postcode], input[name=coupon_text]", function(){
                    $.loadingScreen("show"); // Крутилка         
                    $.ajax({
                         url: "./",
                         type: "GET",
                         data: ({"CMSMajaxLoadDelivery" : 1, "shop_country_id" : $("select[name=shop_country_id] :selected").val(), "shop_country_location_id" : $("select[name=shop_country_location_id] :selected").val(), "shop_country_location_city_id" : $("select[name=shop_country_location_city_id] :selected").val(), "shop_country_location_city_area_id" : $("select[name=shop_country_location_city_area_id] :selected").val(), "postcode" : $("input[name=postcode]").val(), "coupon_text" : $("input[name=coupon_text]").val()}),
                         dataType: "html",
                         success: function(html){
                              $("#shop-delivery-block").empty().append(html);
                              $.loadingScreen("hide"); // Убираем крутилку
                              $("input[name=shop_delivery_condition_id]").change();
                         }
                    });
                    return true;
               });
              
               $("#cmsm-form-cart").on("change", "input[name=shop_delivery_condition_id]", function(){
                    $.loadingScreen("show"); // Крутилка         
                    $.ajax({
                         url: "./",
                         type: "GET",
                         data: ({"CMSMajaxLoadPayment" : 1, "shop_delivery_condition_id" : $("input[name=shop_delivery_condition_id]:checked").val()}),
                         dataType: "html",
                         success: function(html){
                              $("#shop-payment-block").empty().append(html);
                              $.loadingScreen("hide"); // Убираем крутилку
                         }
                    });
                    return true;
               });
              
               if ($("select[name=shop_country_id]").change())
                    $("input[name=shop_delivery_condition_id]").change();
          });
          ';
          echo '</sc'.'ri'.strtolower('PT').'>';
          // Корзина
          $Shop_Cart_Controller_Show
               ->couponText(Core_Array::get(Core_Array::get($_SESSION, 'hostcmsOrder', array()), 'coupon_text'))
               ->xsl(
                    Core_Entity::factory('Xsl')->getByName($xslName)
               )
               ->itemsProperties(TRUE)
               ->show();
         
          // Корзина не пуста


          if (count($aShop_Cart)){
         echo ' <h3>Оформление заказа <br /><span class="small">(выберите свой город, чтобы увидеть все доставки)</span></h3><div class="order">';
         echo '<div id="shop-address-block" class="col-xs-12 col-md-4 box2 match-height">';
               // Адрес доставки
               $Shop_Address_Controller_Show = new Shop_Address_Controller_Show($oShop);
               $Shop_Address_Controller_Show->xsl(
                         Core_Entity::factory('Xsl')->getByName(
                              Core_Array::get(Core_Page::instance()->libParams, 'deliveryAddressXsl')
                         )
                    )
                    ->show();
                echo '</div>';


               echo '<div id="shop-delivery-block" class="col-xs-12 col-md-4 box2 match-height">';
               // Способ доставки
               $Shop_Delivery_Controller_Show = new Shop_Delivery_Controller_Show($oShop);
               $Shop_Delivery_Controller_Show
                    ->shop_country_id(Core_Array::get(Core_Array::get($_SESSION, 'hostcmsOrder', array()), 'shop_country_id'))
                    ->shop_country_location_id(Core_Array::get(Core_Array::get($_SESSION, 'hostcmsOrder', array()), 'shop_country_location_id'))
                    ->shop_country_location_city_id(Core_Array::get(Core_Array::get($_SESSION, 'hostcmsOrder', array()), 'shop_country_location_city_id'))
                    ->shop_country_location_city_area_id(Core_Array::get(Core_Array::get($_SESSION, 'hostcmsOrder', array()), 'shop_country_location_city_area_id'))
                    ->couponText(Core_Array::get(Core_Array::get($_SESSION, 'hostcmsOrder', array()), 'coupon_text'))
                    ->setUp()
                    ->xsl(
                         Core_Entity::factory('Xsl')->getByName(
                              Core_Array::get(Core_Page::instance()->libParams, 'deliveryXsl')
                         )
                    )
                    ->show();
               echo '</div>';
              
               echo '<div id="shop-payment-block" class="col-xs-12 col-md-4 box2 match-height">';
               // Форма оплаты
               $oShop_Delivery_Condition = Core_Entity::factory('Shop_Delivery_Condition', Core_Array::get(Core_Array::get($_SESSION, 'hostcmsOrder', array()), 'shop_delivery_condition_id'));


               $Shop_Payment_System_Controller_Show = new Shop_Payment_System_Controller_Show($oShop);
               $Shop_Payment_System_Controller_Show
                    ->shop_delivery_id($oShop_Delivery_Condition->shop_delivery_id)
                    ->xsl(
                         Core_Entity::factory('Xsl')->getByName(
                              Core_Array::get(Core_Page::instance()->libParams, 'paymentSystemXsl')
                         )
                    )
                    ->show();
               echo '</div>';
          }


          echo '</div></form>';
}


// Блок авторизации пользователя
if (Core::moduleIsActive('siteuser'))
{
     $oSiteuser = Core_Entity::factory('Siteuser')->getCurrent();


     if (is_null($oSiteuser))
     {
          // Авторизация
          $Siteuser_Controller_Show = new Siteuser_Controller_Show(
               Core_Entity::factory('Siteuser')
          );


          $Siteuser_Controller_Show
               ->location(Core::$url['path'])
               ->xsl(
                    Core_Entity::factory('Xsl')->getByName(Core_Array::get(Core_Page::instance()->libParams, 'userAuthorizationXsl'))
               )
               ->show();


          // Регистрация
          $Siteuser_Controller_Show = new Siteuser_Controller_Show(
               Core_Entity::factory('Siteuser')
          );


          $Siteuser_Controller_Show->xsl(
                    Core_Entity::factory('Xsl')->getByName(Core_Array::get(Core_Page::instance()->libParams, 'userRegistrationXsl'))
               )
               ->location(Core::$url['path'])
               ->fastRegistration(TRUE)
               ->itemsProperties(TRUE)
               ->properties(TRUE)
               //->showMaillists(TRUE)
               ->show();
     }
}

Код настроек ТДС
 

<?php


$oShop = Core_Entity::factory('Shop', Core_Array::get(Core_Page::instance()->libParams, 'shopId'));


// Проверять остаток на складе при добавлении в корзину
$bCheckStock = FALSE;


Shop_Payment_System_Handler::checkBeforeContent($oShop);


Shop_Delivery_Handler::checkBeforeContent($oShop);


// Добавление товара в корзину
if (Core_Array::getRequest('add'))
{
     $shop_item_id = intval(Core_Array::getRequest('add'));


     if ($shop_item_id)
     {
          $oShop_Cart_Controller = Shop_Cart_Controller::instance();
          $oShop_Cart_Controller
               ->shop_item_id($shop_item_id)
               ->quantity(Core_Array::getRequest('count', 1))
               ->add();
     }


     // Ajax
     if (Core_Array::getRequest('_', FALSE))
     {
          ob_start();


          // Краткая корзина
          $Shop_Cart_Controller_Show = new Shop_Cart_Controller_Show(
               $oShop
          );
          $Shop_Cart_Controller_Show
               ->xsl(
                    Core_Entity::factory('Xsl')->getByName(
                         Core_Array::get(Core_Page::instance()->libParams, 'littleCartXsl')
                    )
               )
               ->couponText(Core_Array::get($_SESSION, 'coupon_text'))
               ->show();


          echo json_encode(ob_get_clean());
          exit();
     }
}




// Быстрый заказ в 1 клик
if (!is_null(Core_Array::getRequest('oneStepCheckout')))
{
    $shop_item_id = intval(Core_Array::getRequest('shop_item_id'));


    $Shop_Cart_Controller_Onestep = new Shop_Cart_Controller_Onestep($oShop);


    // Генерация окна с заказом в 1 клик
    if (!is_null(Core_Array::getRequest('showDialog'))
            && Core_Array::getRequest('_', FALSE)
            && $shop_item_id
    )
    {
        ob_start();


        $oneStepXslName = Core_Array::get(Core_Page::instance()->libParams, 'oneStepXsl');


        $iQuantity = Core_Array::getRequest('count', 1);


        $Shop_Cart_Controller_Onestep
            ->xsl(
                Core_Entity::factory('Xsl')->getByName($oneStepXslName)
            )
            ->shop_item_id($shop_item_id)
            ->quantity($iQuantity);


        $Shop_Cart_Controller_Onestep->addEntity(
            Core::factory('Core_Xml_Entity')
                ->name('count')->value($iQuantity)
        );


        $Shop_Cart_Controller_Onestep->show();


        echo json_encode(array('html' => ob_get_clean(), 'id' => $shop_item_id));
        exit();
    }


    // Список доставок
    if (!is_null(Core_Array::getRequest('showDelivery')))
    {
        $shop_country_id = Core_Array::getRequest('shop_country_id', 0);
        $shop_country_location_id = Core_Array::getRequest('shop_country_location_id', 0);
        $shop_country_location_city_id = Core_Array::getRequest('shop_country_location_city_id', 0);
        $shop_country_location_city_area_id = Core_Array::getRequest('shop_country_location_city_area_id', 0);


        $oShop_Item = Core_Entity::factory('Shop_Item')->find($shop_item_id);
        if (!is_null($oShop_Item->id))
        {
            $aTotal = $Shop_Cart_Controller_Onestep->quantity(Core_Array::getRequest('count', 1))->calculatePrice($oShop_Item);


            $aDelivery = $Shop_Cart_Controller_Onestep->showDelivery($shop_country_id, $shop_country_location_id, $shop_country_location_city_id, $shop_country_location_city_area_id, $aTotal['weight'], $aTotal['amount']);


            echo json_encode(array('delivery' => $aDelivery));
            exit();
        }
    }


    // Список платежных систем
    if (!is_null(Core_Array::getRequest('showPaymentSystem')))
    {
        $shop_delivery_condition_id = strval(Core_Array::getGet('shop_delivery_condition_id', 0));


        $aPaymentSystems = array();
        if (is_numeric($shop_delivery_condition_id))
        {
            $oShop_Delivery_Condition = Core_Entity::factory('Shop_Delivery_Condition', $shop_delivery_condition_id);


            $aPaymentSystems = $Shop_Cart_Controller_Onestep->showPaymentSystem($oShop_Delivery_Condition->shop_delivery_id);
        }


        echo json_encode(array('payment_systems' => $aPaymentSystems));
        exit();
    }
}




if (Core_Array::getGet('action') == 'repeat')
{
     $guid = Core_Array::getGet('guid');
     if (strlen($guid))
     {
          $oShop_Order = $oShop->Shop_Orders->getByGuid($guid);


          if (!is_null($oShop_Order))
          {
               $aShop_Order_Items = $oShop_Order->Shop_Order_Items->findAll();


               $oShop_Cart_Controller = Shop_Cart_Controller::instance();


               foreach ($aShop_Order_Items as $oShop_Order_Item)
               {
                    $oShop_Order_Item->shop_item_id && $oShop_Cart_Controller
                         ->shop_item_id($oShop_Order_Item->shop_item_id)
                         ->quantity($oShop_Order_Item->quantity)
                         ->add();
               }
          }
     }
}


if (!is_null(Core_Array::getGet('ajaxLoad')))
{
    if (!is_null(Core_Array::getGet('city_name')))
    {
        $shop_country_id = intval(Core_Array::getGet('shop_country_id'));


        $aArray = array('…');


        $oCurrent_Shop_Country_Location_Cities = Core_Entity::factory('Shop_Country_Location_City');
        $oCurrent_Shop_Country_Location_Cities->queryBuilder()
            ->join('shop_country_locations', 'shop_country_locations.id', '=', 'shop_country_location_cities.shop_country_location_id')
            ->where('shop_country_locations.shop_country_id', '=', $shop_country_id);


        $oCurrent_Shop_Country_Location_City = $oCurrent_Shop_Country_Location_Cities->getByName(strval(Core_Array::getGet('city_name')));


        if (!is_null($oCurrent_Shop_Country_Location_City))
        {
            $aCities = $oCurrent_Shop_Country_Location_City
                ->Shop_Country_Location
                ->Shop_Country_Location_Cities
                ->findAll(FALSE);


            foreach ($aCities as $Object)
            {
                $aArray['cities']['_' . $Object->id] = $Object->getName();
            }


            $aArray['result'] = array(
                'shop_country_location_id' => $oCurrent_Shop_Country_Location_City->shop_country_location_id,
                'shop_country_location_city_id' => $oCurrent_Shop_Country_Location_City->id
            );
        }


        Core::showJson($aArray);
    }


    $aObjects = array();


    if (Core_Array::getGet('shop_country_id'))
    {
        $oShop_Country_Location = Core_Entity::factory('Shop_Country_Location');
        $oShop_Country_Location
            ->queryBuilder()
            ->where('shop_country_id', '=', intval(Core_Array::getGet('shop_country_id')));
        $aObjects = $oShop_Country_Location->findAll();
    }
    elseif (Core_Array::getGet('shop_country_location_id'))
    {
        $oShop_Country_Location_City = Core_Entity::factory('Shop_Country_Location_City');
        $oShop_Country_Location_City
            ->queryBuilder()
            ->where('shop_country_location_id', '=', intval(Core_Array::getGet('shop_country_location_id')));
        $aObjects = $oShop_Country_Location_City->findAll();
    }
    elseif (Core_Array::getGet('shop_country_location_city_id'))
    {
        $oShop_Country_Location_City_Area = Core_Entity::factory('Shop_Country_Location_City_Area');
        $oShop_Country_Location_City_Area
            ->queryBuilder()
            ->where('shop_country_location_city_id', '=', intval(Core_Array::getGet('shop_country_location_city_id')));
        $aObjects = $oShop_Country_Location_City_Area->findAll();
    }


    $aArray = array('…');
    foreach ($aObjects as $Object)
    {
        //$aArray['_' . $Object->id] = $Object->name;
        $aArray['_' . $Object->id] = $Object->getName();
    }


    Core::showJson($aArray);
}


if (!is_null(Core_Array::getGet('CMSMajaxLoadDelivery'))){
     // Способ доставки
     $Shop_Delivery_Controller_Show = new Shop_Delivery_Controller_Show($oShop);
     $Shop_Delivery_Controller_Show
          ->shop_country_id(intval(Core_Array::getGet('shop_country_id', 0)))
          ->shop_country_location_id(intval(Core_Array::getGet('shop_country_location_id', 0)))
          ->shop_country_location_city_id(intval(Core_Array::getGet('shop_country_location_city_id', 0)))
          ->shop_country_location_city_area_id(intval(Core_Array::getGet('shop_country_location_city_area_id', 0)))
          ->couponText(trim(strval(Core_Array::getGet('coupon_text', Core_Array::get(Core_Array::get($_SESSION, 'hostcmsOrder', array()), 'coupon_text')))))
          ->postcode(strval(Core_Array::getGet('postcode')))
          ->setUp()
          ->xsl(
               Core_Entity::factory('Xsl')->getByName(
                    Core_Array::get(Core_Page::instance()->libParams, 'deliveryXsl')
               )
          )
          ->show();
     exit();
}


if (!is_null(Core_Array::getGet('CMSMajaxLoadPayment'))){
     // Форма оплаты
     $oShop_Delivery_Condition = Core_Entity::factory('Shop_Delivery_Condition', intval(Core_Array::getGet('shop_delivery_condition_id', 0)));


     $Shop_Payment_System_Controller_Show = new Shop_Payment_System_Controller_Show($oShop);
     $Shop_Payment_System_Controller_Show
          ->shop_delivery_id($oShop_Delivery_Condition->shop_delivery_id)
          ->xsl(
               Core_Entity::factory('Xsl')->getByName(
                    Core_Array::get(Core_Page::instance()->libParams, 'paymentSystemXsl')
               )
          )
          ->show();
     exit();
}


// Удаление товара из корзины
if (Core_Array::getGet('delete'))
{
    $shop_item_id = intval(Core_Array::getGet('delete'));


    if ($shop_item_id)
    {
        $oShop_Cart_Controller = Shop_Cart_Controller::instance();
        $oShop_Cart_Controller
            ->shop_item_id($shop_item_id)
            ->delete();
    }
}


// Запоминаем купон
if (!is_null(Core_Array::getRequest('coupon_text')))
{
    Core_Session::start();
    $_SESSION['hostcmsOrder']['coupon_text'] = trim(strval(Core_Array::getRequest('coupon_text')));
}


if (Core_Array::getPost('recount') || Core_Array::getPost('step') == 1)
{
    $oShop_Cart_Controller = Shop_Cart_Controller::instance();
    $aCart = $oShop_Cart_Controller->getAll($oShop);


    // Склад по умолчанию
    $oShop_Warehouse = $oShop->Shop_Warehouses->getDefault();


    foreach ($aCart as $oShop_Cart)
    {
        $quantity = Core_Array::getPost('quantity_' . $oShop_Cart->shop_item_id);


        // Количество было передано
        if (!is_null($quantity))
        {
            $oShop_Cart_Controller
                ->clear()
                ->checkStock($bCheckStock)
                ->shop_item_id($oShop_Cart->shop_item_id)
                ->quantity($quantity)
                ->postpone(is_null(Core_Array::getPost('postpone_' . $oShop_Cart->shop_item_id)) ? 0 : 1)
                ->shop_warehouse_id(
                    Core_Array::getPost('warehouse_' . $oShop_Cart->shop_item_id, !is_null($oShop_Warehouse) ? $oShop_Warehouse->id : 0)
                )
                ->update();
        }
    }
}


$Shop_Cart_Controller_Show = new Shop_Cart_Controller_Show($oShop);


Core_Page::instance()->object = $Shop_Cart_Controller_Show;