Your IP : 216.73.216.79


Current Path : /var/www/html/project/controllers/
Upload File :
Current File : /var/www/html/project/controllers/TasksController.php

<?php

namespace app\controllers;

use Yii;
use app\models\Tasks;
use app\models\TasksSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\models\Log;
use app\models\LogSearch;
use app\models\Projects;
use yii\helpers\Url;
use yii\web\UploadedFile;
use app\models\User;
use yii\db\Expression;

/**
 * TasksController implements the CRUD actions for Tasks model.
 */
class TasksController extends Controller {

    /**
     * {@inheritdoc}
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function actionCalendar($project_id = '', $assign_to = '') {
        return $this->render('calendar', ['project_id' => $project_id, 'assign_to' => $assign_to]);
    }

    public function actionChartcurve($id) {
        if (($modelproject = Projects::findOne($id)) !== null) {
            $projectName = $modelproject->name;
            $projectStart = $modelproject->start_dt;
            $projectEnd = $modelproject->end_dt;
        }
        $xAxis = "";
        $seriesPlan = "";
        $seriesActual = "";
        $model = Tasks::find()
                ->where(['tasks.deleted_status' => '0'])
                ->andwhere(['project_id' => $id])
                ->andwhere(['=', 'task_type', 'step'])
                ->orderBy(['task_full_no' => SORT_ASC])
                ->all();
        if (!empty($model)) {
            foreach ($model as $row) {
                $xAxis .= "'" . $row->task_name . "',";
                $seriesPlan .= "Date.parse('" . $row->start_dt . "'),";
                $actual_start_dt = '0000-00-00';
                if (!empty($row->actual_start_dt))
                    $actual_start_dt = $row->actual_start_dt;
                $seriesActual .= "Date.parse('" . $actual_start_dt . "'),";
            }
        }
        return $this->render('chartcurve', [
                    'projectName' => $projectName,
                    'projectStart' => $projectStart,
                    'projectEnd' => $projectEnd,
                    'xAxis' => $xAxis,
                    'seriesPlan' => $seriesPlan,
                    'seriesActual' => $seriesActual
        ]);
    }

    public function actionChart($id) {
        $Projects = new Projects();
        $User = new User();
        $projectName = $Projects->getname($id);
        $chartSeries = "";
        $adhocTaskList = "";
        $model = Tasks::find()
                        ->where(['tasks.deleted_status' => '0'])
                        ->andwhere(['project_id' => $id])
                        ->orderBy(['id' => SORT_ASC])->all();
        if (!empty($model)) {
            foreach ($model as $row) {

                if ($row->task_type == 'phase') {

                    $total_task = (int) Yii::$app->db->createCommand("SELECT COUNT(*) FROM tasks WHERE project_id=$id AND deleted_status=0 AND parent_id=$row->id")->queryScalar();
                    $total_task_percentage = (float) Yii::$app->db->createCommand("SELECT SUM(percentage_complete) FROM tasks WHERE project_id=$id AND deleted_status=0 AND parent_id=$row->id")->queryScalar();
                    $phase_percentage = number_format((($total_task_percentage / $total_task) / 100), 2);

                    $chartSeries .= "{
                        type:'phase',
                        name: '" . $row->task_name . "',
                        id: 'parent" . $row->id . "',
                        owner:'(see each task for more details)',
                        color:'#d59000',
                        completed: {amount: " . $phase_percentage . ",fill: '#1175bc'},
                    },";
                }
                $start_dt = "Date.UTC(" . date("Y", strtotime($row->start_dt)) . ", " . (date("n", strtotime($row->start_dt)) - 1) . ", " . date("j", strtotime($row->start_dt)) . ", 0, 0, 0)";
                $end_dt = "Date.UTC(" . date("Y", strtotime($row->end_dt)) . ", " . (date("n", strtotime($row->end_dt)) - 1) . ", " . date("j", strtotime($row->end_dt)) . ", 23, 0, 0)";
                $task_percentage = 0;
                if (!empty($row->percentage_complete)) {
                    $task_percentage = $row->percentage_complete / 100;
                }
                if ($row->task_type == 'step') {
                    $chartSeries .= "{
                        type:'step',
                        start: " . $start_dt . ",
                        end: " . $end_dt . ",
                        name: '" . $row->task_name . "',
                        owner: '" . $User->getusername($row->assign_to) . "',
                        parent: 'parent" . $row->parent_id . "',
                        color:'#ffb822',
                        completed: {amount: " . $task_percentage . ",fill: '#11bcae'},
                    },";
                }
                if ($row->task_type == 'adhoc') {
                    $adhocTaskList .= "{
                        type:'adhoc',
                        start: " . $start_dt . ",
                        end: " . $end_dt . ",
                        name: '" . $row->task_name . "',
                        owner: '" . $User->getusername($row->assign_to) . "',
                        parent: 'parent0',
                        color:'#ffb822',
                        completed: {amount: " . $task_percentage . ",fill: '#11bcae'},
                    },";
                }

                if (!empty($adhocTaskList)) {
                    $total_task = (int) Yii::$app->db->createCommand("SELECT COUNT(*) FROM tasks WHERE project_id=$id AND deleted_status=0 AND task_type='adhoc'")->queryScalar();
                    $total_task_percentage = (float) Yii::$app->db->createCommand("SELECT SUM(percentage_complete) FROM tasks WHERE project_id=$id AND deleted_status=0 AND task_type='adhoc'")->queryScalar();
                    $phase_percentage = ($total_task_percentage / $total_task) / 100;

                    $chartSeries .= "{
                        type:'adhoc',
                        name: 'Adhoc Task',
                        id: 'parent0',
                        owner:'(see each task for more details)',
                        color:'#d59000',
                        completed: {amount: " . $phase_percentage . ",fill: '#1175bc'},
                    }," . $adhocTaskList;
                }
            }
        }
        return $this->render('chart', ['projectName' => $projectName, 'chartSeries' => $chartSeries]);
    }

    public function actionGettasklist($project_id = '', $user_id = '') {
        $User = new User();
        $Projects = new Projects();
        $taskList = [];
        $query = Tasks::find()
                ->innerJoin('projects', 'tasks.project_id=projects.id')
                ->where(['tasks.deleted_status' => '0'])
                ->andwhere(['!=', 'tasks.task_type', 'phase'])
                ->andwhere(['=', 'projects.status', '1']);
        if (!empty($project_id))
            $query->andwhere(['=', 'tasks.project_id', $project_id]);
        if (!empty($user_id)) {
            $query->andwhere(new Expression('FIND_IN_SET(:assign_to_find, assign_to)'))->addParams([':assign_to_find' => $user_id]);
        }
        $query->orderBy(['projects.name' => SORT_ASC]);
        $model = $query->all();
        if (!empty($model)) {
            foreach ($model as $row) {
                $task = [];
                $task['title'] = $Projects->getname($row->project_id) . ' : ' . $row->task_name;
                $task['start'] = $row->start_dt;
                $task['end'] = date('Y-m-d', strtotime($row->end_dt . ' +1 day'));

                $assign_to = '';
                $assign_to_arr = explode(',', $row->assign_to);
                if (!empty($assign_to_arr)) {
                    foreach ($assign_to_arr as $assignID) {
                        $assign_to .= $User->getusername($assignID) . '<br>';
                    }
                }

                $description = '<p><b>Project Name</b><br>' . $Projects->getname($row->project_id) . '</p>
                    <p><b>Task Name</b><br>' . $row->task_name . '</p>
                    <p><b>Assign To</b><br>' . $assign_to . '</p>
                    <p><b>Date Task</b><br>' . date("d M Y", strtotime($row->start_dt)) . ' until ' . date("d M Y", strtotime($row->end_dt)) . '</p>
                    <p><b>Status</b><br>' . ucfirst($row->task_status) . '</p>';
                $task['description'] = $description;
                $taskList[] = $task;
            }
        }

        header('Content-Type: application/json');
        \Yii::$app->response->data = json_encode($taskList);
    }

    /**
     * Lists all Tasks models.
     * @return mixed
     */
    public function actionIndex() {
        \yii\helpers\Url::remember();
        $searchModel = new TasksSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

    /**
     * Displays a single Tasks 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 Tasks model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $model = new Tasks();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

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

    /**
     * Updates an existing Tasks 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()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

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

    /**
     * Deletes an existing Tasks 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 = $_POST['id'];
        $status = 'failed';
        $model = Tasks::findOne($id);
        if (!empty($model)) {
            $model->deleted_status = 1;
            if ($model->save(false)) {

                Tasks::updateAll(['deleted_status' => 1,], ['=', 'parent_id', $model->id]);

                $Log = new Log();
                $Log->insertlog('task', 'delete', $model->id);
                $status = 'success';
            }
        }
        return $status;
    }

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

        throw new NotFoundHttpException('The requested page does not exist.');
    }

    public function actionStart($id) {

        if (($model = Tasks::findOne($id)) !== null) {
            $parent_id = $model->parent_id;
            $model->task_status = 'on-going';
            if (empty($model->actual_start_date))
                $model->actual_start_dt = date("Y-m-d");
            $model->save(false);

            while ($parent_id != NULL) {
                if (($model2 = Tasks::findOne($parent_id)) !== null) {
                    $model2->task_status = 'on-going';
                    $model2->save(false);
                    $parent_id = $model2->parent_id;
                }
            }

            if (($model3 = Projects::findOne($model->project_id)) !== null) {
                $model3->progress = 'On-going';
                $model3->save(false);
            }

            //insert into log
            $Log = new Log();
            $Log->insertlog('task', 'start', $model->id);
        }
        //return $this->redirect(['index']);
        return $this->goBack();
    }

    public function actionComplete($id) {
        if (($model = Tasks::findOne($id)) !== null) {
            $parent_id = $model->parent_id;
            $model->task_status = 'complete';
            if (empty($model->actual_end_dt))
                $model->actual_end_dt = date("Y-m-d");
            if (empty($model->percentage_complete))
                $model->percentage_complete = '100';

            $model->save(false);

            while ($parent_id != NULL) {
                if (($model2 = Tasks::findOne($parent_id)) !== null) {

                    $counttask = Tasks::find()->where(['parent_id' => $model2->id])->andwhere(['!=', 'task_status', 'complete'])->count();
                    if ($counttask == 0) {
                        $model2->task_status = 'complete';
                        $model2->save(false);
                    }
                    $parent_id = $model2->parent_id;
                }
            }

            $checkprojects = Tasks::find()
                    ->where(['project_id' => $model->project_id])
                    ->andwhere(['!=', 'task_status', 'complete'])
                    ->andwhere(['=', 'deleted_status', 0])
                    ->andwhere(['!=', 'task_type', 'adhoc'])
                    ->count();
            if ($checkprojects == 0) {
                if (($model3 = Projects::findOne($model->project_id)) !== null) {
                    $model3->progress = 'Complete';
                    $model3->save(false);
                }
            }

            $Log = new Log();
            $Log->insertlog('task', 'complete', $model->id);
        }
        return $this->goBack();
    }

    public function actionDashboard($type = '') {
        \yii\helpers\Url::remember();
        $searchModel = new TasksSearch();
        if (empty(Yii::$app->request->queryParams['TasksSearch']['task_status'])) {
            $searchModel->task_status = ['pending', 'on-going'];
        }
        $dataProvider = $searchModel->searchdashboard(Yii::$app->request->queryParams, $type);
        return $this->render('dashboard', [
                    'searchModel' => $searchModel,
                    'dataProvider' => $dataProvider,
                    'type' => $type
        ]);
    }

    public function actionIndexadhoc() {
        \yii\helpers\Url::remember();
        $searchModel = new TasksSearch();
        $dataProvider = $searchModel->searchadhoc(Yii::$app->request->queryParams);

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

    public function actionDeleteadhoc() {
        $id = $_POST['id'];
        $status = 'failed';
        $model = Tasks::findOne($id);
        if (!empty($model)) {
            $model->deleted_status = 1;
            if ($model->save(false)) {
                $Log = new Log();
                $Log->insertlog('task', 'delete', $model->id);
                $status = 'success';
            }
        }
        return $status;
    }

    public function actionCreateadhoc() {
        $model = new Tasks();
        $model->scenario = 'manageadhoc';
        $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->task_type = 'adhoc';
        $model->task_status = 'pending';
        $model->deleted_status = '0';
        $model->duration = '1';
        $model->start_dt = date("Y-m-d");
        $model->end_dt = date("Y-m-d");
        if ($model->load(Yii::$app->request->post())) {

            $model->file = UploadedFile::getInstance($model, 'file');
            if (!empty($model->file)) {
                $file_name = 'uploads/' . date("YmdHis") . '.' . $model->file->extension;
                if ($model->file->saveAs($file_name))
                    $model->file_url = $file_name;
            }
            if ($model->save()) {
                $Log = new Log();
                $Log->insertlog('task', 'create', $model->id);
                $this->getView()->registerJs("swal.fire({
                position: 'center-center',type: 'success',title: 'Data has been saved',showConfirmButton: false,timer: 1500,
                }).then(function(result){window.location = '" . Url::to(['tasks/indexadhoc']) . "';});");
            }
        }
        return $this->render('createadhoc', ['model' => $model,]);
    }

    public function actionUpdateadhoc($id) {
        $model = $this->findModel($id);
        $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 = 'uploads/' . date("YmdHis") . '.' . $model->file->extension;
                if ($model->file->saveAs($file_name))
                    $model->file_url = $file_name;
            }

            if ($model->save()) {
                $Log = new Log();
                $Log->insertlog('task', 'update', $model->id);
                $this->getView()->registerJs("swal.fire({
                position: 'center-center',type: 'success',title: 'Data has been saved',showConfirmButton: false,timer: 1500,
                }).then(function(result){window.location = '" . Url::to(['tasks/indexadhoc']) . "';});");
            }
        }

        return $this->render('updateadhoc', ['model' => $model,]);
    }
    
    
    public function actionManagemodules($parent_id) {
        if (isset($_POST) && !empty($_POST)) {
            //add new
            if (!empty($_POST['new_module_id'])) {
                foreach ($_POST['new_module_id'] as $new_module_id) {
                    $model = new Tasks();
                    $model->task_type = 'module';
                    $model->parent_id = $parent_id;
                    $model->task_name = $_POST['new_module_name_' . $new_module_id];
                    $model->sort = $_POST['new_module_sort_' . $new_module_id];
                    $model->task_status = $_POST['new_module_status_' . $new_module_id];
                    $model->percentage_complete = $_POST['new_module_percentage_' . $new_module_id];
                    $model->remarks = $_POST['new_module_remarks_' . $new_module_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->save(false);
                }
            }
            //update record
            if (!empty($_POST['old_module_id'])) {
                foreach ($_POST['old_module_id'] as $old_module_id) {
                    if (($model = Tasks::findOne($old_module_id)) !== null) {
                        $model->task_name = $_POST['old_module_name_' . $old_module_id];
                        $model->sort = $_POST['old_module_sort_' . $old_module_id];
                        $model->task_status = $_POST['old_module_status_' . $old_module_id];
                        $model->percentage_complete = $_POST['old_module_percentage_' . $old_module_id];
                        $model->remarks = $_POST['old_module_remarks_' . $old_module_id];
                        $model->updated_dt = date("Y-m-d H:i:s");
                        $model->updated_by = Yii::$app->user->identity->id;
                        $model->save(false);
                    }
                }
            }

            $this->getView()->registerJs("swal.fire({
                position: 'center-center',type: 'success',title: 'Data has been saved',showConfirmButton: false,timer: 1500,
                }).then(function(result){window.location = '" . Url::to(['tasks/index']) . "';});");
        }

        return $this->render('managemodules');
    }

    public function actionDeletemodule($id) {
        if (($model = Tasks::findOne($id)) !== null) {
            $model->delete();
        }
    }

}