Удобный онлайн генератор паролей

Запрет перевода сделки на определенную стадию БЕЗ предоплаты



Задача:
Запрет для сотрудников из некоторых департаментов переводить сделки из некоторых воронок в стадию "X", если сумма предоплаты (сумма значений 2х множественных полей  ) меньше 50% от суммы товаров со значением "Батут" свойства "тип товара" .
Причем, вперед нельзя, обратно можно.
обработчик в init.php
AddEventHandler("crm", "OnBeforeCrmDealUpdate", "CheckMinPO");
function CheckMinPO(&$arFields){   
    if(!empty($arFields["STAGE_ID"]) && !empty($arFields["MODIFY_BY_ID"])){       
        //сталии ДО 
        $arStartStages = [
            "C3:NEW","C3:PREPARATION", "C3:PREPAYMENT_INVOICE","C3:EXECUTING", 
            "C1:NEW","C1:PREPARATION", "C1:PREPAYMENT_INVOICE","C1:EXECUTING", 
            "C5:NEW","C5:PREPARATION", "C5:PREPAYMENT_INVOICE","C5:EXECUTING", 
            "C7:NEW","C7:PREPARATION", "C7:PREPAYMENT_INVOICE","C7:EXECUTING", 
            "C133:NEW","C133:PREPARATION", "C133:PREPAYMENT_INVOICE","C133:EXECUTING", 
        ];
        $arFailStages = [];
        $arCategoryIds = [1,3,5,7,133];
        foreach ($arCategoryIds as $categoryId) {
            $dbRow = CCrmStatus::GetList(['SORT'=>'asc'], ['ENTITY_ID'=>'DEAL_STAGE_'.$categoryId,"SEMANTICS"=>"F"]);        
            while ($row = $dbRow->fetch()) {
                $arFailStages[] = $row["STATUS_ID"];
            }    
        }
        
        if(!in_array($arFields["STAGE_ID"], $arStartStages) && !in_array($arFields["STAGE_ID"], $arFailStages)){ //если не начальные стадии и не проигранные

            $arFilter = array(
               "ID"=>$arFields["ID"], //выбираем определенную сделку по ID
               "CHECK_PERMISSIONS"=>"N" //не проверять права доступа текущего пользователя
            );            
            $arSelect = array(
               "ID",               
               "ASSIGNED_BY_ID", 
               "STAGE_ID",
               "UF_CRM_1542789083",
               "UF_CRM_1640203627"
            );            
            $res = CCrmDeal::GetList(Array(), $arFilter, $arSelect);
            if($arDeal = $res->Fetch()){               
                if(in_array($arDeal["STAGE_ID"],$arStartStages) && CModule::IncludeModule('intranet')&& CModule::IncludeModule('iblock')){//если было на начальных стадиях
                                      
                    $arUserDepartments = CIntranetUtils::GetUserDepartments($arFields["MODIFY_BY_ID"]);
                    if(  //1242, 1292, 181, 183, 1609, 1610, 1611, 1612 если из ОП
                     in_array(1242,$arUserDepartments) ||
                     in_array(1292,$arUserDepartments) ||
                     in_array(181,$arUserDepartments) ||
                     in_array(183,$arUserDepartments) ||
                     in_array(1609,$arUserDepartments) ||
                     in_array(1610,$arUserDepartments) ||
                     in_array(1611,$arUserDepartments) ||
                     in_array(1612,$arUserDepartments) 
                    ){
                      
                        //проверяем товары
                        $arFilter = array(
                           "OWNER_ID"=>$arFields["ID"], //ID сделки, лида, предложения
                           "CHECK_PERMISSIONS"=>"N" //не проверять права доступа текущего пользователя
                        );            
                        $arSelect = array( "*");            
                        $res = CCrmProductRow::GetList(['ID'=>'DESC'], $arFilter,false,false,$arSelect);     
                        $arDealProducts = [];    
                        $arProductIds = [];
                        while($arProduct = $res->Fetch()){
                           $arDealProducts[$arProduct["PRODUCT_ID"]] = $arProduct["PRICE"]*$arProduct["QUANTITY"];
                           $arProductIds[] = $arProduct["PRODUCT_ID"];
                        }
                        
                        if(!empty($arProductIds)){
                            $arFilter = Array(
                              "ID"=>$arProductIds,  
                              "IBLOCK_ID"=>28, 
                              "PROPERTY_626" =>298 //батут                              
                            );
                            $arSelect = Array("ID");
                            $res = CIBlockElement::GetList(Array("sort"=>"asc"), $arFilter, false, Array("nPageSize"=>50,"iNumPage"=>1), $arSelect);
                            $sumBatut = 0;
                            while($arItem = $res->Fetch()){
                              $sumBatut = $sumBatut + $arDealProducts[$arItem["ID"]];
                            }
                            $minPO = $sumBatut*0.5;
                            $propPO1 = $arFields["UF_CRM_1542789083"]??$arDeal["UF_CRM_1542789083"];
                            $propPO2 = $arFields["UF_CRM_1640203627"]??$arDeal["UF_CRM_1640203627"];
                            $sumPO = 0;
                           foreach($propPO1 as $itemSum){
                              $sumPO = $sumPO + $itemSum;
                           }
                           foreach($propPO2 as $itemSum){
                              $sumPO = $sumPO + $itemSum;
                           }                           
                            
                            if($sumPO < $minPO){
                                unset($arFields["STAGE_ID"]);
                                if(CModule::IncludeModule('im')){
                                    $arFieldsIm = array(
                                        "NOTIFY_TITLE" => "Сумма предоплаты меньше ".$minPO.'р.', //заголовок
                                        "MESSAGE" => 'Нельзя изменить стадию. Cумма предоплаты '.$sumPO .'р. меньше '.$minPO.'р. - 50% от суммы товаров со свойством "Батут"',
                                        "MESSAGE_TYPE" => IM_MESSAGE_SYSTEM, // IM_MESSAGE_PRIVATE, IM_MESSAGE_CHAT, IM_MESSAGE_OPEN, IM_MESSAGE_SYSTEM, IM_MESSAGE_OPEN_LINE
                                        "TO_USER_ID" => $arFields["MODIFY_BY_ID"],
                                        "FROM_USER_ID" => $arFields["MODIFY_BY_ID"],
                                        //"AUTHOR_ID" => $userIdOther, //может отличаться от FROM_USER_ID

                                        "NOTIFY_TYPE" => IM_NOTIFY_SYSTEM,  // IM_NOTIFY_CONFIRM, IM_NOTIFY_SYSTEM, IM_NOTIFY_FROM
                                        "NOTIFY_MODULE" => "main", // module id sender (ex: xmpp, main, etc)
                                        "NOTIFY_EVENT" => "manage",
                                    );
                                    CIMMessenger::Add($arFieldsIm);
                                }    
                            }
                        }
                    }
                }       
            }
        }
    }
}
Если блог был полезным, можете угостить меня "чашечкой кофе" :)

Сбер по номеру телефона +7 (953) 585-13-09 Вероника.
Спасибо!