VariantController.php 10.9 KB
<?php
    
    namespace common\modules\product\controllers;
    
    use common\modules\product\models\Product;
    use common\modules\product\models\ProductImage;
    use common\modules\product\models\ProductStock;
    use common\modules\product\models\ProductVariant;
    use common\modules\product\models\ProductVariantListSearch;
    use common\modules\product\models\Stock;
    use Yii;
    use yii\web\Controller;
    use yii\web\NotFoundHttpException;
    use yii\filters\VerbFilter;
    
    /**
     * ManageController implements the CRUD actions for ProductVariant model.
     */
    class VariantController extends Controller
    {
        
        /**
         * @inheritdoc
         */
        public function behaviors()
        {
            return [
                'verbs' => [
                    'class'   => VerbFilter::className(),
                    'actions' => [
                        'delete' => [ 'POST' ],
                    ],
                ],
            ];
        }
        
        /**
         * Lists all ProductVariant models.
         * @return mixed
         */
        public function actionIndex($product_id)
        {
            $searchModel = new ProductVariantListSearch();
            $dataProvider = $searchModel->search(Yii::$app->request->queryParams, $product_id);
            
            if(( $product = Yii::$app->request->get('product_id') ) !== NULL) {
                $product = Product::findOne($product);
            }
            
            return $this->render('index', [
                'searchModel'  => $searchModel,
                'dataProvider' => $dataProvider,
                'product'      => $product,
                'product_id'   => $product_id,
            ]);
        }
        
        /**
         * Displays a single ProductVariant model.
         *
         * @param integer $id
         *
         * @return mixed
         */
        public function actionView($id)
        {
            return $this->render('view', [
                'model' => $this->findModel($id),
            ]);
        }
        
        /**
         * Creates a new ProductVariant model.
         * If creation is successful, the browser will be redirected to the 'view' page.
         * @return mixed
         */
        public function actionCreate($product_id)
        {
            $model = new ProductVariant();
            $model->product_id = $product_id;
            $model->generateLangs();
            if($model->load(Yii::$app->request->post())) {
                $model->loadLangs(\Yii::$app->request);
                if($model->save() && $model->transactionStatus) {
                    $ProductStocks = Yii::$app->request->post('ProductStock');
                    $total_quantity = 0;
                    if(!empty( $ProductStocks ) && is_array($ProductStocks)) {
                        $model->unlinkAll('stocks', true);
                        $sorted_array = [];
                        foreach($ProductStocks as $subArray) {
                            if(!empty( $subArray[ 'name' ] ) && !empty( $subArray[ 'quantity' ] )) {
                                if(!empty( $sorted_array[ $subArray[ 'name' ] ] )) {
                                    $sorted_array[ $subArray[ 'name' ] ] += $subArray[ 'quantity' ];
                                } else {
                                    $sorted_array[ $subArray[ 'name' ] ] = $subArray[ 'quantity' ];
                                }
                            }
                        }
                        $ProductStocks = $sorted_array;
                        $stock_names = array_keys($ProductStocks);
                        $stocks = Stock::find()
                                       ->where([ 'name' => $stock_names ])
                                       ->indexBy('name')
                                       ->all();
                        foreach($ProductStocks as $name => $quantity) {
                            $quantity = (int) $quantity;
                            if(!array_key_exists($name, $stocks)) {
                                $stock = new Stock([
                                    'name' => $name,
                                ]);
                                if(!$stock->save()) {
                                    continue;
                                }
                            } else {
                                $stock = $stocks[ $name ];
                            }
                            $psModel = new ProductStock([
                                'product_id'         => $model->product_id,
                                'product_variant_id' => $model->product_variant_id,
                                'stock_id'           => $stock->stock_id,
                                'quantity'           => $quantity,
                            ]);
                            if($psModel->save()) {
                                $total_quantity += $quantity;
                            }
                        }
                    } else {
                        $model->unlinkAll('stocks', true);
                    }
                    
                    $model->stock = $total_quantity;
                    if($model->save() && $model->transactionStatus) {
                        return $this->redirect([
                            'index',
                            'product_id' => $product_id,
                        ]);
                    }
                }
            }
            $groups = $model->getTaxGroupsByLevel(1);
            return $this->render('create', [
                'model'       => $model,
                'model_langs' => $model->model_langs,
                'groups'      => $groups,
                'stocks'      => [ new ProductStock() ],
            ]);
        }
        
        /**
         * Updates an existing ProductVariant model.
         * If update is successful, the browser will be redirected to the 'view' page.
         *
         * @param integer $product_id
         * @param integer $id
         *
         * @return mixed
         */
        public function actionUpdate($product_id, $id)
        {
            $model = $this->findModel($id);
            $model->generateLangs();
            if($model->load(Yii::$app->request->post())) {
                $model->loadLangs(\Yii::$app->request);
                if($model->save() && $model->transactionStatus) {
                    $ProductStocks = Yii::$app->request->post('ProductStock');
                    $total_quantity = 0;
                    if(!empty( $ProductStocks ) && is_array($ProductStocks)) {
                        $model->unlinkAll('stocks', true);
                        $sorted_array = [];
                        foreach($ProductStocks as $subArray) {
                            if(!empty( $subArray[ 'name' ] ) && !empty( $subArray[ 'quantity' ] )) {
                                if(!empty( $sorted_array[ $subArray[ 'name' ] ] )) {
                                    $sorted_array[ $subArray[ 'name' ] ] += $subArray[ 'quantity' ];
                                } else {
                                    $sorted_array[ $subArray[ 'name' ] ] = $subArray[ 'quantity' ];
                                }
                            }
                        }
                        $ProductStocks = $sorted_array;
                        $stock_names = array_keys($ProductStocks);
                        $stocks = Stock::find()
                                       ->where([ 'name' => $stock_names ])
                                       ->indexBy('name')
                                       ->all();
                        foreach($ProductStocks as $name => $quantity) {
                            $quantity = (int) $quantity;
                            if(!array_key_exists($name, $stocks)) {
                                $stock = new Stock([
                                    'name' => $name,
                                ]);
                                if(!$stock->save()) {
                                    continue;
                                }
                            } else {
                                $stock = $stocks[ $name ];
                            }
                            $psModel = new ProductStock([
                                'product_id'         => $model->product_id,
                                'product_variant_id' => $model->product_variant_id,
                                'stock_id'           => $stock->stock_id,
                                'quantity'           => $quantity,
                            ]);
                            if($psModel->save()) {
                                $total_quantity += $quantity;
                            }
                        }
                    } else {
                        $model->unlinkAll('stocks', true);
                    }
                    $model->stock = $total_quantity;
                    if($model->save() && $model->transactionStatus) {
                        return $this->redirect([
                            'index',
                            'product_id' => $product_id,
                        ]);
                    }
                }
            }
            $groups = $model->getTaxGroupsByLevel(1);
            return $this->render('update', [
                'model'       => $model,
                'model_langs' => $model->model_langs,
                'groups'      => $groups,
                'stocks'      => ( !empty( $model->variantStocks ) ) ? $model->variantStocks : [ new ProductStock ],
            ]);
        }
        
        /**
         * Deletes an existing ProductVariant model.
         * If deletion is successful, the browser will be redirected to the 'index' page.
         *
         * @param integer $product_id
         * @param integer $id
         *
         * @return mixed
         */
        public function actionDelete($product_id, $id)
        {
            
            $this->findModel($id)
                 ->delete();
            
            return $this->redirect([
                'index',
                'product_id' => $product_id,
            ]);
        }
        
        public function actionDelimg($id)
        {
            $image = ProductImage::findOne($id);
            
            if($image) {
                $image->delete();
            }
            
            print '1';
            exit;
        }
        
        /**
         * Finds the ProductVariant model based on its primary key value.
         * If the model is not found, a 404 HTTP exception will be thrown.
         *
         * @param integer $id
         *
         * @return ProductVariant the loaded model
         * @throws NotFoundHttpException if the model cannot be found
         */
        protected function findModel($id)
        {
            if(( $model = ProductVariant::findOne($id) ) !== NULL) {
                return $model;
            } else {
                throw new NotFoundHttpException('The requested page does not exist.');
            }
        }
    }