VariantCountController.php 11.8 KB
<?php
    
    namespace artbox\stock\controllers;
    
    use artbox\stock\models\Shop;
    use Yii;
    use artbox\stock\models\VariantToShop;
    use yii\data\ActiveDataProvider;
    use yii\web\Controller;
    use yii\web\NotFoundHttpException;
    use yii\filters\VerbFilter;
    use artbox\catalog\models\Variant;
    use yii\web\Response;
    use PHPExcel_IOFactory;
    use yii\filters\AccessControl;
    
    
    /**
     * VariantCountController implements the CRUD actions for VariantToShop model.
     */
    class VariantCountController extends Controller
    {
        /**
         * @inheritdoc
         */
        public function getViewPath()
        {
            return '@artbox/stock/views/variant-count';
        }
        public function behaviors()
        {
            return [
                'verbs' => [
                    'class'   => VerbFilter::className(),
                    'actions' => [
                        'delete' => [ 'POST' ],
                    ],
                ],
                'access' => [
                    'class' => AccessControl::className(),
                    'rules' => [
                        [
                            'actions' => [
                                'login',
                                'error',
                            ],
                            'allow'   => true,
                        ],
                        [
                            'allow' => true,
                            'roles' => [ '@' ],
                        ],
                    ],
                ],
            ];
        }
        
        /**
         * Lists all VariantToShop models.
         * @param int|null $shop_id
         * @return mixed
         */
        public function actionIndex($shop_id)
        {
            $dataProvider = new ActiveDataProvider(
                [
                    'query' => VariantToShop::find()
                                            ->with(
                                                [
                                                    'variant',
                                                    'variant.lang',
                                                    'shop',
                                                    'shop.lang',
                                                ]
                                            )
                                            ->where([ 'shop_id' => $shop_id ]),
                ]
            );
            
            return $this->render(
                'index',
                [
                    'dataProvider' => $dataProvider,
                    'shop_id'      => $shop_id,
                ]
            );
        }
        
        /**
         * Displays a single VariantToShop model.
         *
         * @param integer $variant_id
         * @param integer $shop_id
         *
         * @return mixed
         */
        public function actionView($variant_id, $shop_id)
        {
            return $this->render(
                'view',
                [
                    'model' => $this->findModel($variant_id, $shop_id),
                ]
            );
        }
        
        /**
         * Creates a new VariantToShop model.
         * If creation is successful, the browser will be redirected to the 'view' page.
         * @param int|null $shop_id
         * @return mixed
         */
        public function actionCreate($shop_id)
        {
            $model = new VariantToShop();
            $shop = Shop::find()
                        ->with([ 'lang' ])
                        ->where([ 'id' => $shop_id ])
                        ->one();
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return $this->redirect(
                    [
                        'view',
                        'variant_id' => $model->variant_id,
                        'shop_id'    => $model->shop_id,
                    ]
                );
            } else {
                return $this->render(
                    'create',
                    [
                        'model' => $model,
                        'shop'  => $shop,
                    ]
                );
            }
        }
        
        /**
         * Updates an existing VariantToShop model.
         * If update is successful, the browser will be redirected to the 'view' page.
         *
         * @param integer $variant_id
         * @param integer $shop_id
         *
         * @return mixed
         */
        public function actionUpdate($variant_id, $shop_id)
        {
            $model = $this->findModel($variant_id, $shop_id);
            $shop = Shop::find()
                        ->with([ 'lang' ])
                        ->where([ 'id' => $shop_id ])
                        ->one();
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return $this->redirect(
                    [
                        'view',
                        'variant_id' => $model->variant_id,
                        'shop_id'    => $model->shop_id,
                    ]
                );
            } else {
                return $this->render(
                    'update',
                    [
                        'model' => $model,
                        'shop'  => $shop,
                    ]
                );
            }
        }
        
        /**
         * Deletes an existing VariantToShop model.
         * If deletion is successful, the browser will be redirected to the 'index' page.
         *
         * @param integer $variant_id
         * @param integer $shop_id
         *
         * @return mixed
         */
        public function actionDelete($variant_id, $shop_id)
        {
            $this->findModel($variant_id, $shop_id)
                 ->delete();
            
            return $this->redirect([ 'index' ]);
        }
        
        /**
         * Finds the VariantToShop model based on its primary key value.
         * If the model is not found, a 404 HTTP exception will be thrown.
         *
         * @param integer $variant_id
         * @param integer $shop_id
         *
         * @return VariantToShop the loaded model
         * @throws NotFoundHttpException if the model cannot be found
         */
        protected function findModel($variant_id, $shop_id)
        {
            if (( $model = VariantToShop::findOne(
                    [
                        'variant_id' => $variant_id,
                        'shop_id'    => $shop_id,
                    ]
                ) ) !== null
            ) {
                return $model;
            } else {
                throw new NotFoundHttpException('The requested page does not exist.');
            }
        }
        
        /**
         * Select Variants for list
         * @param string   $q
         * @param int|null $shop_id
         *
         * @return array
         */
        
        public function actionList(string $q = null, $shop_id)
        {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $out = [
                'results' => [
                    'id'   => '',
                    'text' => '',
                ],
            ];
            if (!is_null($q)) {
                $not = VariantToShop::find()
                                    ->select('variant_id')
                                    ->where([ 'shop_id' => $shop_id ])->asArray()->all();
                $out[ 'results' ] = Variant::find()
                                           ->select(
                                               [
                                                   'variant.id as id',
                                                   'variant.sku as text',
                                               ]
                                           )
                                           ->where(
                                               [
                                                   'like',
                                                   'variant.sku',
                                                   $q,
                                               ]
                                           )
                                           ->andWhere(
                                               [
                                                   'NOT IN',
                                                   'variant.id',
                                                   $not,
                                               ]
                                           )
                                           ->limit(20)
                                           ->asArray()
                                           ->all();
            }
            return $out;
        }
    
        /**
         * Show import form action
         * @param $shop_id
         *
         * @return string
         */
        
        public function actionImport($shop_id){
            return $this->render(
                'import',
                [
                    "shop_id" => $shop_id,
                ]
            );
        }
        /**
         * Upload file action
         * @param $shop_id
         *
         * @return array
         */
    
        public function actionUpload($shop_id)
        {
            \Yii::$app->response->format = Response::FORMAT_JSON;
        
            $error = false;
            $files = [];
        
            $uploaddir = \Yii::getAlias('@storage/');
            foreach ($_FILES as $file) {
                if (move_uploaded_file($file[ 'tmp_name' ], $uploaddir . 'import_stock.xlsx')) {
                    $files[] = $uploaddir . $file[ 'name' ];
                    chmod($uploaddir . 'import_stock.xlsx', 0777);
                } else {
                    $error = true;
                }
            }
        
            $data = ( $error ) ? [ 'error' => 'There was an error uploading your files' ] : [ 'files' => $files ];
        
            $this->populateImportTable($shop_id);
        
            return $data;
        }
        /**
         * insert variants to stock
         * @param $shop_id
         */
    
    
        protected function populateImportTable($shop_id)
        {
            $xlsx = PHPExcel_IOFactory::load(\Yii::getAlias('@storage/import_stock.xlsx'));
            $xlsx->setActiveSheetIndex(0);
            $sheet = $xlsx->getActiveSheet();
            $rowIterator = $sheet->getRowIterator();
            $j = 0;
            $count = []; $sku = [];
            foreach ($rowIterator as $row) {
                $j++;
                $cellIterator = $row->getCellIterator();
                $row = [];
                $i = 0;
                foreach ($cellIterator as $cell) {
                    /**
                     * @var \PHPExcel_Cell $cell
                     */
                    $i++;
                    $row[ $i ] = $cell->getValue();
                    if ($i > 1) {
                        break;
                    }
                }
                $sku[]   = $row[1];
                if (is_numeric($row[2])){
                    $count[] = $row[2];
                }
                
    
                if (empty($row[ 1 ])) {
                    break;
                }
                
            }
            $ids = Variant::find()->select('id')->where(['in', 'sku', $sku])->asArray()->column();
            $insert = [];
            foreach ($ids as $key => $val){
               $insert[$key] = [$val,$count[$key], $shop_id];
           }
           VariantToShop::deleteAll(['shop_id' => $shop_id]);
    
            $db = \Yii::$app->db;
            $db->createCommand()
               ->batchInsert(
                   'variant_to_shop',
                   [
                       'variant_id',
                       'count',
                       'shop_id'
                   ],
                   $insert
               )
               ->execute();
           
        }
    }