Your IP : 216.73.216.79


Current Path : /var/www/html/slaas/backend/controllers/dashboard/
Upload File :
Current File : /var/www/html/slaas/backend/controllers/dashboard/DashboardController.php

<?php

namespace backend\controllers\dashboard;

use Yii;
use backend\models\dashboard\DmgDashboard;
use backend\models\dashboard\DmgDashboardSearch;
use backend\modules\mimin\components\AccessControl;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
// use yii\filters\AccessControl;   
use common\components\AccessRule;

/**
 * DashboardController implements the CRUD actions for DmgDashboard model.
 */
class DashboardController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all DmgDashboard models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new DmgDashboardSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

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

    /**
     * Creates a new DmgDashboard model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new DmgDashboard();

        if ($model->load(Yii::$app->request->post())) {

            /* roles */
            $roles = implode(',',Yii::$app->request->post('DmgDashboard')['dmg_dashboard_role']);
            $model->dmg_dashboard_role = $roles;
            if($model->save()){    
                return $this->redirect(['index']);
            }else{
                return $this->render('create', [
                    'model' => $model,
                ]);
            }
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing DmgDashboard model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {
            /* roles */
            $roles = implode(',',Yii::$app->request->post('DmgDashboard')['dmg_dashboard_role']);
            $model->dmg_dashboard_role = $roles;
            if($model->save()){    
                return $this->redirect(['index']);
            }else{
               return $this->render('create', [
                    'model' => $model,
                ]);
            }
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

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

        return $this->redirect(['index']);
    }

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

        throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
    }

    public function actionGetFieldName($table)
    {       
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $db_connection = Yii::$app->db;
        $dbSchema = $db_connection->schema;
        $tables = $dbSchema->getTableSchema($table);
        $columns = [];
        foreach($tables->columns as $column)
        {
            $columns[] = $column->name;
        }

        echo json_encode($columns);
    }

    public function actionGetDashboard()
    {
        Yii::$app->response->format = \Yii\web\Response::FORMAT_JSON;
        $dashboard = DmgDashboard::find()->asArray()->all();
        $data = [];
        $i = 0;
        
        foreach ($dashboard as $dash) {
            $role = explode(',', $dash['dmg_dashboard_role']);
            
            if (array_intersect($role, \Yii::$app->user->identity->StaffRoles)) {

                if( $dash['dmg_dashboard_table'] == "SQL_QUERIES" && !empty($dash['dmg_dashboard_sql_panel_count']) ){
                    /*sql*/
                    $query = Yii::$app->db->createCommand($dash['dmg_dashboard_sql_panel_count'])->queryOne();
                    $data[]['count'] = $query['cnt'];

                }else{

            		/* query builder */
                    if($dash['dmg_dashboard_method'] == 1){
                        $row = (new \yii\db\Query())
                        ->select('*,SUM('.$dash["dmg_dashboard_sum_column"].') AS total')
                        ->from($dash['dmg_dashboard_table']);
                    }else{
                            $row = (new \yii\db\Query())
                        ->select('*')
                        ->from($dash['dmg_dashboard_table']);
                    }
                    
                    /* where year */
                    if($dash['dmg_dashboard_grouping'] != 1 )
                    $row -> where("YEAR(". $dash['dmg_dashboard_column'] ." ) = ".date('Y'));

                    /* break */
                    if (!empty($dash['dmg_dashboard_condition'])) {
                        $condition = explode(';', $dash['dmg_dashboard_condition']);
                        foreach ($condition  as $cond) {
                            $row -> andWhere($cond);
                        }
                    }

                    $rowdata  = $row->one();
                    if($dash['dmg_dashboard_method'] == 1) $data[]['count'] = $rowdata['total']; else $data[]['count'] = $row->count();
                }
                
                $data[$i]['title']    = $dash['dmg_dashboard_title'];
                $data[$i]['subtitle'] = $dash['dmg_dashboard_subtitle'];
                $data[$i]['label']    = $dash['dmg_dashboard_label'];
                $data[$i]['color']    = $dash['dmg_dashboard_label_color'];
                $data[$i]['role']     = $dash['dmg_dashboard_role'];
                $i++;
            } 
        }
        return $this->asJson($data);
    }

    public function actionGetGraph()
    {   
        Yii::$app->response->format = \Yii\web\Response::FORMAT_JSON;
        $dashboard = DmgDashboard::find()->asArray()->all();
        $rGroupData = [];
        $rCountData = [];
        $data = [];
        $i = 0;
        foreach ($dashboard as $dash) {

            $role = explode(',',$dash['dmg_dashboard_role']);

            if(array_intersect($role,\Yii::$app->user->identity->StaffRoles)){
                
                if( $dash['dmg_dashboard_table'] == "SQL_QUERIES" ){
                    /*sql*/
                    $query = Yii::$app->db->createCommand($dash['dmg_dashboard_sql_graph_count'])->queryAll();

                    /* arrange count into arrays */
                    $rmonth = [];
                    foreach ($query as $qval) {
                        $rmonth[$qval['mth']] = $qval['cnt'];
                    }
                    // sort to 12 month
                    $rCountData = [];
                    for ($ii=1; $ii <= 12; $ii++) {
                        $rCountData[] = isset($rmonth[$ii]) ? $rmonth[$ii] : 0;
                    }
                }else{
	            	/* exit if dashboard type from groupable form */
                    if ($dash['dmg_dashboard_grouping'] == 1) {
                        continue;
                    }

                    /* query builder*/
                    if($dash['dmg_dashboard_method'] == 1){
                            $row = (new \yii\db\Query())
                            ->select(['SUM('.$dash["dmg_dashboard_sum_column"].') AS count',$dash['dmg_dashboard_column']])
                            ->from($dash['dmg_dashboard_table']);
                    }else{
                            $row = (new \yii\db\Query())
                            ->select(['COUNT(*) AS count',$dash['dmg_dashboard_column']])
                            ->from($dash['dmg_dashboard_table']);
                    }
                    
                    /* where year */
                    $row -> where("YEAR(". $dash['dmg_dashboard_column'] ." ) = ".date('Y'));

                    /* break */
                    if (!empty($dash['dmg_dashboard_condition'])) {
                        $condition = explode(';', $dash['dmg_dashboard_condition']);
                        foreach ($condition  as $cond) {
                            $row -> andWhere($cond);
                        }
                    }
                    
                    /* query month on based database type */
                    $dbtype = Yii::$app->db->getDriverName();
                    
                    if ($dbtype == "mysql" || $dbtype == "mariaDb" || $dbtype == "mssql") {
                        $row->groupBy('MONTH('.$dash['dmg_dashboard_column'].')');
                    }
                    $results = $row->all();
                    /*assign date into array*/
                    $rCountData = [];
                    foreach ($results as $rData) {

                        $month = date('M Y', strtotime($rData[$dash['dmg_dashboard_column']]));
                        $monthint = date('m', strtotime($rData[$dash['dmg_dashboard_column']]));

                        if (!in_array($month, $rGroupData)) {
                            $rGroupData[]   = date('M Y', strtotime($rData[$dash['dmg_dashboard_column']]));
                        }
                        /* fill in zeros for month without records */
                        for ($z = 0; $z < ((int) $monthint - 1); $z++) {
                            if (!isset($rCountData[$z])) {
                                $rCountData[] = "0";
                            }
                        }
                        $rCountData[]= $rData['count'];
                    }
                }
                
                if (!empty($rCountData)) {
                    $data[$i]['data']   = $rCountData;
                    $data[$i]['label']  = $dash['dmg_dashboard_title'];
                    $data[$i]['backgroundColor'] = $dash['dmg_dashboard_label_color'];
                    $data[$i]['type']   = $dash['dmg_dashboard_chart_type'];
                    $data[$i]['fill'] = "false";
                    $i++;
                }
            }
        }
        return $this->asJson($data);
    }
}