Your IP : 216.73.216.79


Current Path : /var/www/html/helpdesk/controllers/
Upload File :
Current File : /var/www/html/helpdesk/controllers/TicketController.php

<?php

namespace app\controllers;

use Yii;
use app\models\Ticket;
use app\models\TicketSearch;
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 app\models\Projects;
use yii\web\UploadedFile;
use app\models\User;
use app\models\ParamList;
use app\models\Messages;

/**
 * TicketController implements the CRUD actions for Ticket model.
 */
class TicketController extends Controller {

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

    public function actionIndex() {
        $searchModel = new TicketSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('index', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider,]);
    }

    public function actionIndexadmin() {
        $searchModel = new TicketSearch();
        $dataProvider = $searchModel->searchadmin(Yii::$app->request->queryParams);
        return $this->render('indexadmin', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider,]);
    }

    public function actionIndexstaff() {
        $searchModel = new TicketSearch();
        $dataProvider = $searchModel->searchstaff(Yii::$app->request->queryParams);
        return $this->render('indexstaff', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider,]);
    }

    public function actionView($uuid) {
        $model = $this->findModel($uuid);
        return $this->render('view', ['model' => $model]);
    }

    public function actionViewadmin($uuid) {
        $model = $this->findModel($uuid);
        if ($model->load(Yii::$app->request->post())) {
            $model->updated_at = date("Y-m-d H:i:s");
            $model->updated_by = Yii::$app->user->identity->id;
            if ($model->save()) {
                $Log = new Log();
                $Log->insertlog('ticket', 'update', $model->id);
                $this->getView()->registerJs("swal.fire({position: 'center-center',type: 'success',title: 'Ticket have been updated',showConfirmButton: false,timer: 1500,}).then(function(result){window.location = '" . Url::toRoute('ticket/indexadmin') . "';});");
            }
        }
        return $this->render('viewadmin', ['model' => $model]);
    }

    public function actionViewstaff($uuid) {
        $model = $this->findModel($uuid);
        if ($model->load(Yii::$app->request->post())) {
            $model->updated_at = date("Y-m-d H:i:s");
            $model->updated_by = Yii::$app->user->identity->id;
            if ($model->save()) {
                $Log = new Log();
                $Log->insertlog('ticket', 'update', $model->id);
                $this->getView()->registerJs("swal.fire({position: 'center-center',type: 'success',title: 'Ticket have been updated',showConfirmButton: false,timer: 1500,}).then(function(result){window.location = '" . Url::toRoute('ticket/indexstaff') . "';});");
            }
        }
        return $this->render('viewstaff', ['model' => $model]);
    }

    /**
     * Creates a new Ticket model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $ParamList = new ParamList();
        $model = new Ticket();
        $model->uuid = Uuid::uuid4();
        $model->submit_at = date("Y-m-d H:i:s");
        $model->user_id = Yii::$app->user->identity->id;
        $model->ticket_status = 'open';
        $model->staff_status = 'pending';
        $model->level = 'low';
        if ($model->load(Yii::$app->request->post())) {

            $attachment = '';
            $model->file_attach = UploadedFile::getInstance($model, 'file_attach');
            if (!empty($model->file_attach)) {
                $file_name = 'uploads/' . date("YmdHis") . '.' . $model->file_attach->extension;
                if ($model->file_attach->saveAs($file_name)) {
                    $model->file_attach = $file_name;
                    $attachment = '<a href="https://helpdesk.dynaweb4.work/web/' . $model->file_attach . '">Click here to view attachment</a>';
                }
            }

            $project_name = '';
            $staff_pic = [];
            if (!empty($model->project_id)) {
                if (($model2 = Projects::findOne($model->project_id)) !== null) {

                    $project_name = $model2->name;

                    $model->staff_pic = $model2->pic1;
                    $model->staff_pic2 = $model2->pic2;
                    if (!empty($model->staff_pic))
                        $staff_pic[] = $model->staff_pic;
                    if (!empty($model->staff_pic2))
                        $staff_pic[] = $model->staff_pic2;
                }
            }

            if ($model->save()) {

                $ticket_no = strtoupper('HELP-' . date('M') . '-' . date('Y') . '-' . sprintf("%04d", $model->id));

                //update ticket_no
                if (($modelUpdate = Ticket::findOne(['uuid' => $model->uuid])) !== null) {
                    $modelUpdate->ticket_no = $ticket_no;
                    if ($modelUpdate->save()) {

                        $modelPic = User::find()->where(['IN', 'id', $staff_pic])->all();
                        if (!empty($modelPic)) {
                            foreach ($modelPic as $rowPic) {
                                //send email
                                $email_content = '<html>
                                    <body>
                                        <div style="font-family: \'Century Gothic\', CenturyGothic, AppleGothic, sans-serif; font-size: 14px;background-color:rgb(234,234,234);padding:2em 0;">
                                            <div style="width:70%;background-color:white;margin:0 auto;padding:5em 5em 5em 5em;border:1px solid #ccc;">
                                                <p>Hi ' . $rowPic->name . ',</p>
                                                <p>New ticket has been submit at Blunet Helpdesk System and assign to you as below:</p>
                                                <table border="1" cellpadding="5" cellspacing="0">
                                                    <tr>
                                                        <td>Project Title</td>
                                                        <td>' . $project_name . '</td>
                                                    </tr>
                                                    <tr>
                                                        <td>Type</td>
                                                        <td>' . $ParamList->getlabel(40, $model->type) . '</td>
                                                    </tr>
                                                    <tr>
                                                        <td>Problem Summary</td>
                                                        <td>' . $model->summary . '</td>
                                                    </tr>
                                                    <tr>
                                                        <td>Problem Details</td>
                                                        <td>' . $model->details . '</td>
                                                    </tr>
                                                    <tr>
                                                        <td>Attachment</td>
                                                        <td>' . $attachment . '</td>
                                                    </tr>
                                                </table>
                                                <p>Please login into Blunet Helpdesk System for more information</p>
                                                <p>- Admin -</p>
                                            </div>
                                        </div>
                                    </body>
                                </html>';
                                Yii::$app->mailer->compose()
                                        ->setFrom(Yii::$app->params['senderEmail'])
                                        ->setTo($rowPic->email)
                                        ->setSubject('Helpdesk : New Ticket')
                                        ->setHtmlBody($email_content)
                                        ->send();
                            }
                        }

                        $Messages = new Messages();
                        $Messages->ticket_id = $model->id;
                        $Messages->user_id = Yii::$app->user->identity->id;
                        $Messages->msg = $model->summary;
                        $Messages->send_at = date("Y-m-d H:i:s");
                        $Messages->save(false);


                        $Log = new Log();
                        $Log->insertlog('ticket', 'create', $model->id);
                        $this->getView()->registerJs("swal.fire({position: 'center-center',type: 'success',title: 'Ticket have been created',showConfirmButton: false,timer: 1500,}).then(function(result){window.location = '" . Url::toRoute('ticket/index') . "';});");
                    }
                }
            }
        }
        return $this->render('create', ['model' => $model,]);
    }

    /**
     * Updates an existing Ticket 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($id, $uuid) {
        $model = $this->findModel($id, $uuid);

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

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

    /**
     * Deletes an existing Ticket 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 Ticket 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 Ticket the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($uuid) {
        if (($model = Ticket::findOne(['uuid' => $uuid])) !== null) {
            return $model;
        }

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

    public function actionCloseticket($id) {
        $output = "";
        if (($model = Ticket::findOne($id)) !== null) {
            $model->ticket_status = 'closed';
            $model->staff_status = 'done';
            
            $model->closed_at = date("Y-m-d H:i:s");
            $model->closed_by = Yii::$app->user->identity->id;
            
            if ($model->save(false)) {

                $user_arr[] = $model->user_id;
                if (!empty($model->staff_pic))
                    $user_arr[] = $model->staff_pic;
                if (!empty($model->staff_pic2))
                    $user_arr[] = $model->staff_pic2;

                $modelUser = User::find()->where(['IN', 'id', $user_arr])->all();
                if (!empty($modelUser)) {
                    foreach ($modelUser as $rowUser) {
                        //send email
                        $email_content = '<html>
                            <body>
                                <div style="font-family: \'Century Gothic\', CenturyGothic, AppleGothic, sans-serif; font-size: 14px;background-color:rgb(234,234,234);padding:2em 0;">
                                    <div style="width:70%;background-color:white;margin:0 auto;padding:5em 5em 5em 5em;border:1px solid #ccc;">
                                        <p>Hi ' . $rowUser->name . ',</p>
                                        <p>Ticket <b>' . $model->ticket_no . '</b> has been closed.</p>
                                        <p>Please login into Blunet Helpdesk System for more information</p>
                                        <p>- Admin -</p>
                                    </div>
                                </div>
                            </body>
                        </html>';
                        Yii::$app->mailer->compose()
                                ->setFrom(Yii::$app->params['senderEmail'])
                                ->setTo($rowUser->email)
                                ->setSubject('Helpdesk : Closed Ticket')
                                ->setHtmlBody($email_content)
                                ->send();
                    }
                }


                $Log = new Log();
                $Log->insertlog('ticket', 'closed', $model->id);
                $output = 'success';
            } else
                $output = 'failed';
        }
        return $output;
    }

    public function actionSendmessage() {
        $ticket_id = $_POST['ticket_id'];
        $ticket_uuid = $_POST['ticket_uuid'];
        $msg = $_POST['msg'];

        $Messages = new Messages();
        $Messages->ticket_id = $ticket_id;
        $Messages->user_id = Yii::$app->user->identity->id;
        $Messages->msg = $msg;
        $Messages->send_at = date("Y-m-d H:i:s");
        $Messages->save(false);

        if (($model = Ticket::findOne($ticket_id)) !== null) {

            $user_arr[] = $model->user_id;
            if (!empty($model->staff_pic))
                $user_arr[] = $model->staff_pic;
            if (!empty($model->staff_pic2))
                $user_arr[] = $model->staff_pic2;
            $User = new User();
            $modelUser = User::find()->where(['IN', 'id', $user_arr])->all();
            if (!empty($modelUser)) {
                foreach ($modelUser as $rowUser) {
                    //send email
                    $email_content = '<html>
                            <body>
                                <div style="font-family: \'Century Gothic\', CenturyGothic, AppleGothic, sans-serif; font-size: 14px;background-color:rgb(234,234,234);padding:2em 0;">
                                    <div style="width:70%;background-color:white;margin:0 auto;padding:5em 5em 5em 5em;border:1px solid #ccc;">
                                        <p>Hi ' . $rowUser->name . ',</p>
                                        <p>Below is the new message for ticket <b>' . $model->ticket_no . '</b> send from <b>' . $User->getusername($Messages->user_id) . '</b></p>
                                        <p><b><i>"' . $Messages->msg . '"</i></b></p>
                                        <p>Please login into Blunet Helpdesk System for more information</p>
                                        <p>- Admin -</p>
                                    </div>
                                </div>
                            </body>
                        </html>';
                    Yii::$app->mailer->compose()
                            ->setFrom(Yii::$app->params['senderEmail'])
                            ->setTo($rowUser->email)
                            ->setSubject('Helpdesk : New Message')
                            ->setHtmlBody($email_content)
                            ->send();
                }
            }
        }


        if (Yii::$app->user->identity->role == 'ADMIN')
            return $this->redirect(['viewadmin', 'uuid' => $ticket_uuid]);
        else if (Yii::$app->user->identity->role == 'STAFF')
            return $this->redirect(['viewstaff', 'uuid' => $ticket_uuid]);
        else
            return $this->redirect(['view', 'uuid' => $ticket_uuid]);
    }

}