# События (хуки) и др

#### 1. Хуки для контроллеров корзины

Т.к. в корзине в 1 шаг все блоки подгружаются ajax и для облегчения интеграции (исключаем работу в ТДС) их формирование идет в файле **MegaPost\_Command\_Controller**, который нельзя модифицировать, но можно использовать хуки ([подробнее](https://www.hostcms.ru/documentation/modules/core/events/))

{% code lineNumbers="true" fullWidth="true" %}

```php
// хук для доступа к Shop_Cart_Controller_Show
class My_MegaPost
{
    static public function onBeforeCartShow($controller, $args)
    {
        $Shop_Cart_Controller_Show = $args[0];
        
        $Shop_Cart_Controller_Show
            ->itemsProperties(FALSE)
            ->checkStock(TRUE);
    }
}

Core_Event::attach('MegaPost_Command_Controller.onBeforeCartShow', array('My_MegaPost', 'onBeforeCartShow'));

// хук для доступа к MegaPost_Shop_Delivery_Controller_Show
class My_MegaPost
{
    static public function onBeforeDeliveryShow($controller, $args)
    {
        $Shop_Delivery_Controller_Show = $args[0];
        
        $Shop_Delivery_Controller_Show
            ->shopDeliveries()
                ->queryBuilder()
                    ->where('shop_deliveries.id','NOT IN', array(123))
		    ->setOr()
		    ->where('shop_deliveries.id','IN', array(456));
    }
}

Core_Event::attach('MegaPost_Command_Controller.onBeforeDeliveryShow', array('My_MegaPost', 'onBeforeDeliveryShow'));

// хук для доступа к Shop_Payment_System_Controller_Show
class My_MegaPost
{
    static public function onBeforePaymentSystemShow($controller, $args)
    {
        $Shop_Payment_System_Controller_Show = $args[0];
        
        $Shop_Payment_System_Controller_Show
            ->shopPaymentSystems()
                ->queryBuilder()
                    ->where('shop_payment_systems.id','NOT IN', array(123))
		    ->setOr()
		    ->where('shop_payment_systems.id','IN', array(456));
    }
}

Core_Event::attach('MegaPost_Command_Controller.onBeforePaymentSystemShow', array('My_MegaPost', 'onBeforePaymentSystemShow'));
```

{% endcode %}

#### 2. Остаток на складе

Указать для корзины для всего сайта без хуков и ТДС проверку остатка на складе, можно разместив в файле **bootstrap.php** следующий код

{% code lineNumbers="true" fullWidth="true" %}

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

$oShop_Cart_Controller = Shop_Cart_Controller::instance();
$oShop_Cart_Controller->checkStock($bCheckStock);
```

{% endcode %}

#### 3. Изменение данных расчета доставок

Данный хук позволяет для каждого расчета, получить и изменить данные перед передачей в корзину или вовсе не выводить его (нужно вернуть `FALSE`)

{% code lineNumbers="true" fullWidth="true" %}

```php
class My_MegaPost
{
    static public function onAfterHandlerObject($handler, $args)
    {
        list($object, $Megapost_Condition) = $args;
        
        // доставка ID 1 && курьер && тариф
        if($handler->shop_delivery_id == 1 && $objcet->type == 0 && $objcet->tariffId == 2)
        {
            $objcet->price = 0; // изменим цену
        }
		
    	return NULL; // возвращает объект с данными расчета
    	// return FALSE; // не возвращает расчет
    }
}

Core_Event::attach('Megapost_Handler.onAfterHandlerObject', array('My_MegaPost', 'onAfterHandlerObject'));
```

{% endcode %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://support.morozovpimnev.ru/megapost/sobytiya-khuki-i-dr.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
