Your IP : 216.73.216.79


Current Path : /var/www/html/dyna-crm/controllers/
Upload File :
Current File : /var/www/html/dyna-crm/controllers/AssetdetailsController.php

<?php

namespace app\controllers;

use Yii;
use app\models\AssetDetails;
use app\models\AssetDetailsSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;
use app\models\Log;
use app\models\LogSearch;
use yii\helpers\Url;
use yii\helpers\ArrayHelper;
use yii\web\UploadedFile;
use app\models\AssetLog;
use kartik\mpdf\Pdf;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use app\models\AssetCategory;

/**
 * AssetdetailsController implements the CRUD actions for AssetDetails model.
 */
class AssetdetailsController extends Controller {

    public $menu_id = 64;

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

    /**
     * Lists all AssetDetails models.
     * @return mixed
     */
    public function actionReport() {
        return $this->render('report', ['menu_id' => 70]);
    }

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

    /**
     * Displays a single AssetDetails model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionBarcode($uuid) {
        echo "<img alt='Barcode Generator TEC-IT'
       src='https://barcode.tec-it.com/barcode.ashx?data=ABC-abc-1234&code=Code128'/>";
        //return $this->render('barcode', [
        //            'model' => $this->findModel($uuid),
        //            'menu_id' => $this->menu_id,
        //]);
    }

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

    /**
     * Creates a new AssetDetails model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $model = new AssetDetails();
        $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();
        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/asset/' . $file_name))
                    $model->img_url = $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: 2000,}).then(function(result){window.location = '" . Url::toRoute('assetdetails/index') . "';});");
            }
        }
        return $this->render('create', ['model' => $model, 'menu_id' => $this->menu_id]);
    }

    /**
     * Updates an existing AssetDetails 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($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/asset/' . $file_name))
                    $model->img_url = $file_name;
            }
            if ($model->save()) {
                $Log = new Log();
                $Log->insertlog($this->menu_id, 'update', $model->uuid);
                $this->getView()->registerJs("swal.fire({position: 'center-center',type: 'success',title: 'Data has been saved',showConfirmButton: false,timer: 2000,}).then(function(result){window.location = '" . Url::toRoute('assetdetails/index') . "';});");
            }
        }
        return $this->render('update', ['model' => $model, 'menu_id' => $this->menu_id]);
    }

    /**
     * Deletes an existing AssetDetails 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() {
        if (($model = AssetDetails::findOne($_POST['id'])) !== null) {
            $Log = new Log();
            $Log->insertlog($this->menu_id, 'delete', $model->uuid);
            if ($model->delete())
                return 'success';
        }

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

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

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

    public function actionDownloadexcel($search_name = '', $search_cat = '', $search_start_date = '', $search_end_date = '') {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        $sheet->setCellValue('A1', '#');
        $sheet->setCellValue('B1', 'Asset Name');
        $sheet->setCellValue('C1', 'Serial No');
        $sheet->setCellValue('D1', 'Category');
        $sheet->setCellValue('E1', 'Asset Value');
        $sheet->setCellValue('F1', 'Purchase Date');
        $sheet->setCellValue('G1', 'Status');
        $sheet->setCellValue('H1', 'Location');
        $sheet->getStyle("A1:H1")->getFont()->setBold(true);

        $model = AssetDetails::find()
                        ->andFilterWhere(['like', 'name', $search_name])
                        ->andFilterWhere(['like', 'cat', $search_cat])
                        ->andFilterWhere(['AND', ['>=', 'purchase_dt', $search_start_date], ['<=', 'purchase_dt', $search_end_date]])
                        ->orderBy(['name' => SORT_ASC])->all();
        $count2 = 0;
        $count = 1;
        $AssetCategory = new AssetCategory();
        $AssetDetails = new AssetDetails();
        $AssetLog = new AssetLog();

        if (!empty($model)) {
            foreach ($model as $row) {
                $count2++;
                $count++;

                $sheet->setCellValue('A' . $count, $count2);
                $sheet->setCellValue('B' . $count, $row->name);
                $sheet->setCellValue('C' . $count, $AssetDetails->getserialnumber($row->id));
                $sheet->setCellValue('D' . $count, $AssetCategory->getname($row->cat));
                $sheet->setCellValue('E' . $count, 'MYR ' . number_format((float) $row->asset_value, 2, '.', ','));
                $sheet->setCellValue('F' . $count, date("d M Y", strtotime($row->purchase_dt)));
                $sheet->setCellValue('G' . $count, $AssetLog->getstatus($row->id));
                $sheet->setCellValue('H' . $count, $AssetLog->getlocation($row->id));
            }
        }

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="Assets List.xlsx"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        die();
    }

    public function actionDownloadpdf($search_name = '', $search_cat = '', $search_start_date = '', $search_end_date = '') {
        $content = '<table class="table table-bordered table-striper">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Asset Name</th>
                    <th>Serial No</th>
                    <th>Category</th>
                    <th>Asset Value</th>
                    <th>Purchase Date</th>
                    <th>Status</th>
                    <th>Location</th>
                </tr>
            </thead>
            <tbody>';

        $model = AssetDetails::find()
                        ->andFilterWhere(['like', 'name', $search_name])
                        ->andFilterWhere(['like', 'cat', $search_cat])
                        ->andFilterWhere(['AND', ['>=', 'purchase_dt', $search_start_date], ['<=', 'purchase_dt', $search_end_date]])
                        ->orderBy(['name' => SORT_ASC])->all();
        $count = 0;
        $AssetCategory = new AssetCategory();
        $AssetDetails = new AssetDetails();
        $AssetLog = new AssetLog();

        if (!empty($model)) {
            foreach ($model as $row) {
                $count++;
                $content .= '<tr>
                        <td>' . $count . '</td>
                        <td>' . $row->name . '</td>
                        <td style="white-space:nowrap;">' . $AssetDetails->getserialnumber($row->id) . '</td>
                        <td>' . $AssetCategory->getname($row->cat) . '</td>
                        <td style="white-space:nowrap;">MYR ' . number_format((float) $row->asset_value, 2, '.', ',') . '</td>
                        <td style="white-space:nowrap;">' . date("d M Y", strtotime($row->purchase_dt)) . '</td>
                        <td>' . $AssetLog->getstatus($row->id) . '</td>
                        <td>' . $AssetLog->getlocation($row->id) . '</td>
                    </tr>';
            }
        }

        $content .= '</tbody></table>';
        $pdf = new Pdf([
            'mode' => Pdf::MODE_CORE,
            'filename' => 'Assets List.pdf',
            'format' => Pdf::FORMAT_A4,
            'orientation' => Pdf::ORIENT_LANDSCAPE,
            'destination' => Pdf::DEST_DOWNLOAD,
            'cssFile' => '@vendor/kartik-v/yii2-mpdf/src/assets/kv-mpdf-bootstrap.min.css',
            'content' => $content,
            'options' => ['setAutoTopMargin' => 'stretch'],
        ]);
        return $pdf->render();
    }

}