Your IP : 216.73.216.79


Current Path : /var/www/html/crm/controllers/
Upload File :
Current File : /var/www/html/crm/controllers/ProductController.php

<?php

namespace app\controllers;

use Yii;
use app\models\Product;
use app\models\ProductSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;
use yii\helpers\Url;
use app\models\Log;
use app\models\LogSearch;
use yii\web\UploadedFile;
use app\models\Company;
use app\models\Brand;

/**
 * ProductController implements the CRUD actions for Product model.
 */
class ProductController extends Controller {

    public $menu_id = 2;

    /**
     * {@inheritdoc}
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
            'access' => [
                'class' => \yii\filters\AccessControl::className(),
                'only' => ['index', 'create', 'update', 'view'],
                'rules' => [
                    // allow authenticated users
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                // everything else is denied
                ],
            ],
        ];
    }

    /**
     * Lists all Product models.
     * @return mixed
     */
    public function actionIndex() {
        $searchModel = new ProductSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('index', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'menu_id' => $this->menu_id]);
    }

    public function actionOverview() {
        $searchModel = new ProductSearch();
        $dataProvider = $searchModel->overview(Yii::$app->request->queryParams);
        return $this->render('overview', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'menu_id' => 55]);
    }

    /**
     * Displays a single Product model.
     * @param integer $id
     * @param string $uuid
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id, $uuid) {
        return $this->render('view', [ 'model' => $this->findModel($id, $uuid),]);
    }

    public function actionLog($uuid) {
        $searchModel = new LogSearch();
        $searchModel->menu_id = $this->menu_id;
        $searchModel->data_uuid = $uuid;
        $dataProvider = $searchModel->log(Yii::$app->request->queryParams);
        return $this->render('log', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'menu_id' => $this->menu_id]);
    }

    /**
     * Creates a new Product model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate($copy_uuid = '', $com_id = '') {
        $model = new Product();
        if (!empty($com_id))
            $model->com_id = $com_id;
        if ($copy_uuid != '') {
            if (($modelcopy = Product::findOne(['uuid' => $copy_uuid])) !== null) {
                $model->name = $modelcopy->name;
                $model->brand_id = $modelcopy->brand_id;
                $model->cat_id = $modelcopy->cat_id;
                $model->sku = $modelcopy->sku;
                $model->uom = $modelcopy->uom;
                $model->cost = $modelcopy->cost;
                $model->retail_price = $modelcopy->retail_price;
                $model->selling_price = $modelcopy->selling_price;
                $model->vendor_id = $modelcopy->vendor_id;
                $model->com_id = $modelcopy->com_id;
                $model->weblink = $modelcopy->weblink;
                $model->descr = $modelcopy->descr;
                $model->benefits = $modelcopy->benefits;
                $model->keywords = $modelcopy->keywords;
                $model->duplicate_id = $modelcopy->id;
            }
        }
        $model->created_dt = date("Y-m-d H:i:s");
        $model->created_by = Yii::$app->user->identity->id;
        $model->updated_dt = date("Y-m-d H:i:s");
        $model->updated_by = Yii::$app->user->identity->id;
        $model->uuid = Uuid::uuid4();
        $model->status = 1;
        if ($model->load(Yii::$app->request->post())) {

            $model->file = UploadedFile::getInstance($model, 'file');
            if (!empty($model->file)) {
                $file_name = $model->uuid . '-' . date("YmdHis") . '.' . $model->file->extension;
                if ($model->file->saveAs('uploads/product/' . $file_name))
                    $model->photo = $file_name;
            }

            if ($model->save()) {
                $Log = new Log();
                $Log->insertlog($this->menu_id, 'create', $model->uuid);

                $this->getView()->registerJs("swal.fire({position: 'center-center',type: 'success',title: 'Data has been saved',showConfirmButton: false,timer: 4000,}).then(function(result){window.location = '" . Url::toRoute('product/index') . "';});");
            }
        }
        return $this->render('create', ['model' => $model, 'menu_id' => $this->menu_id]);
    }

    /**
     * Updates an existing Product model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @param string $uuid
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($uuid) {
        $model = $this->findModel($uuid);
        $model->updated_dt = date("Y-m-d H:i:s");
        $model->updated_by = Yii::$app->user->identity->id;
        if ($model->load(Yii::$app->request->post())) {

            $model->file = UploadedFile::getInstance($model, 'file');
            if (!empty($model->file)) {
                $file_name = $model->uuid . '-' . date("YmdHis") . '.' . $model->file->extension;
                if ($model->file->saveAs('uploads/product/' . $file_name))
                    $model->photo = $file_name;
            }

            if ($model->save()) {
                $Log = new Log();
                $Log->insertlog($this->menu_id, 'create', $model->uuid);

                $this->getView()->registerJs("swal.fire({position: 'center-center',type: 'success',title: 'Data has been saved',showConfirmButton: false,timer: 4000,}).then(function(result){window.location = '" . Url::toRoute('product/index') . "';});");
            }
        }
        return $this->render('update', ['model' => $model, 'menu_id' => $this->menu_id]);
    }

    /**
     * Deletes an existing Product model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @param string $uuid
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
//    public function actionDelete($id, $uuid) {
//        $this->findModel($id, $uuid)->delete();
//
//        return $this->redirect(['index']);
//    }

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

    public function actionGetparentlist() {
        $brand_id = $_POST['brand_id'];
        $product_id = $_POST['product_id'];
        $output = '';
        $query = Product::find()->where(['=', 'status', '1'])
                ->andwhere(['=', 'parent_id', '0'])
                ->andwhere(['=', 'brand_id', $brand_id]);
        if ($product_id != '')
            $query->andwhere(['!=', 'id', $product_id]);
        $query->orderBy(['name' => SORT_ASC]);
        $model = $query->all();
        if (!empty($model)) {
            foreach ($model as $row) {
                $output.= '<option value="' . $row->id . '">' . $row->name . '</option>';
            }
        }
        return $output;
    }

    public function actionDelete() {
        $id = $_POST['id'];
        $status = 'failed';
        $model = Product::findOne($id);
        if (!empty($model)) {
            $model->status = 0;
            if ($model->save()) {
                $Log = new Log();
                $Log->insertlog($this->menu_id, 'delete', $model->uuid);
                $status = 'success';
            }
        }
        return $status;
    }

    public function actionListforstock() {
        $brand_id = $_POST['brand_id'];
        $com_id = $_POST['com_id'];
        $vendor_id = $_POST['vendor_id'];
        $output = '';
        $model = Product::find()
                        ->where(['=', 'status', '1'])
                        ->andwhere(['=', 'brand_id', $brand_id])
                        ->andwhere(['=', 'vendor_id', $vendor_id])
                        ->andwhere(['=', 'com_id', $com_id])
                        ->orderBy(['name' => SORT_ASC])->all();
        if (!empty($model)) {
            foreach ($model as $row) {
                $output.= '<option value="' . $row->id . '">' . $row->name . '</option>';
            }
        }
        return $output;
    }

    public function actionGetproductdetails() {
        $id = $_POST['id'];
        $output = '';
        if (($model = Product::findOne($id)) !== null) {
            $output = $model->uom . '<->' . $model->selling_price;
        }
        return $output;
    }

    public function actionGetsku() {
        $product_no = 0;
        $company_id = $_POST['company_id'];
        $product_id = $_POST['product_id'];
        $Company = new Company();
        if ($product_id != '') {
            $product_no = (int) $product_id;
        } else {
            $product_no = Yii::$app->db->createCommand("SELECT `AUTO_INCREMENT` FROM  INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME='product'")->queryScalar();
        }
        $output = $Company->getshortcode($company_id) . '-' . sprintf("%06d", $product_no);
        return $output;
    }

    public function actionStockalertlist($search_vendor = '', array $search_brand = [], $search_keyword = '') {
        return $this->render('stockalertlist', ['menu_id' => 84, 'search_vendor' => $search_vendor, 'search_brand' => $search_brand, 'search_keyword' => $search_keyword]);
    }

    public function actionGetbrandlist() {
        $sme_id = $_POST['sme_id'];
        $output = '';
        $model = Brand::find()->where(['status' => '1'])->andwhere(['sme_id' => $sme_id])->orderBy(['name' => SORT_ASC])->all();
        if (!empty($model)) {
            foreach ($model as $row) {
                $output .= '<option value="' . $row->id . '">' . $row->name . '</option>';
            }
        }
        return $output;
    }

    public function actionUpdatestockalert() {
        $output = 'failed';
        if (($model = Product::findOne($_POST['product_id'])) !== null) {
            $model->stock_alert = $_POST['stock_alert'];
            $model->updated_dt = date("Y-m-d H:i:s");
            $model->updated_by = Yii::$app->user->identity->id;
            if ($model->save(false))
                $output = 'success';
        }
        return $output;
    }

    public function actionGetproductlist() {
        $brand_id = $_POST['brand_id'];
        $output = '';
        $model = Product::find()->where(['status' => '1'])->andwhere(['brand_id' => $brand_id])->orderBy(['name' => SORT_ASC])->all();
        if (!empty($model)) {
            foreach ($model as $row) {
                $output .= '<option value="' . $row->id . '">' . $row->name . '</option>';
            }
        }
        return $output;
    }

}