Your IP : 216.73.216.79


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

<?php

namespace app\controllers;

use Yii;
use app\models\Quotation;
use app\models\QuotationSearch;
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\Customer;
use app\models\Company;
use app\models\ParamList;
use kartik\mpdf\Pdf;
use app\models\User;
use app\models\Notes;
use app\models\QuotationItem;

/**
 * QuotationController implements the CRUD actions for Quotation model.
 */
class QuotationController extends Controller {

    public $menu_id = 42;

    /**
     * {@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 Quotation models.
     * @return mixed
     */
    public function actionIndex() {
        $searchModel = new QuotationSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('index', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'menu_id' => $this->menu_id]);
    }

    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]);
    }

    /**
     * Displays a single Quotation 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),
        ]);
    }

    /**
     * Creates a new Quotation model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $Company = new Company();
        $model = new Quotation();
        $model->doc_date = date("Y-m-d");
        $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())) {
            $countdoc = (int) Quotation::find()->where(['company_id' => $model->company_id])->count() + 1;
            $model->doc_no = $Company->getshortcode($model->company_id) . '/QUO/' . date("y") . '/' . sprintf("%05d", $countdoc);
            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: 1500,}).then(function(result){window.location = 'index.php?r=quotation/update&uuid=$model->uuid';});");
            }
        }
        return $this->render('create', ['model' => $model, 'menu_id' => $this->menu_id]);
    }

    /**
     * Updates an existing Quotation 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())) {
            if ($model->save()) {

                //update item
                if (!empty($_POST['item_no'])) {
                    foreach ($_POST['item_no'] as $item_id) {
                        if (($modelItem = QuotationItem::findOne($item_id)) !== null) {
                            $modelItem->product_name = $_POST['product_name_' . $item_id];
                            $modelItem->uom = $_POST['uom_' . $item_id];
                            $modelItem->quantity = $_POST['quantity_' . $item_id];
                            $modelItem->unit_price = $_POST['unit_price_' . $item_id];
                            $modelItem->total_price = $_POST['total_price_' . $item_id];
                            $modelItem->sorting = $_POST['sorting_' . $item_id];
                            $modelItem->updated_dt = date("Y-m-d H:i:s");
                            $modelItem->updated_by = Yii::$app->user->identity->id;
                            $modelItem->save(false);
                        }
                    }
                }

                $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: 1500,}).then(function(result){window.location = 'index.php?r=quotation/update&uuid=$model->uuid';});");
            }
        }
        return $this->render('update', ['model' => $model, 'menu_id' => $this->menu_id]);
    }

    /**
     * Deletes an existing Quotation 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 Quotation 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 Quotation the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($uuid) {
        if (($model = Quotation::findOne(['uuid' => $uuid])) !== null) {
            return $model;
        }
        throw new NotFoundHttpException('The requested page does not exist.');
    }

    public function actionGetcustomerdetails() {
        $id = $_POST['id'];
        $output = '';
        if (($model = Customer::findOne($id)) !== null) {
            $output = $model->name . '<->' .
                    $model->address1 . '<->' .
                    $model->address2 . '<->' .
                    $model->postcode . '<->' .
                    $model->city . '<->' .
                    $model->state . '<->' .
                    $model->contact_name . '<->' .
                    $model->contact_no;
        }
        return $output;
    }

    public function actionAddproduct() {
        $model = new QuotationItem();
        $model->doc_id = $_POST['doc_id'];
        $model->product_name = $_POST['product_name'];
        $model->quantity = $_POST['quantity'];
        $model->uom = $_POST['uom'];
        $model->unit_price = $_POST['unit_price'];
        $model->total_price = $_POST['total_price'];
        $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;
        if ($model->save())
            return '1';
        else
            return '0';
    }

    public function actionAdditem() {
        $model = new QuotationItem();
        $model->doc_id = $_POST['doc_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);
        return '<tr id="rowitem_' . $model->id . '">
            <td>
                <input type="hidden" value="' . $model->id . '" name="item_no[]">
                <input type="text" class="form-control" value="' . $model->sorting . '" name="sorting_' . $model->id . '">
            </td>
            <td><textarea class="form-control" rows="3" name="product_name_' . $model->id . '">' . $model->product_name . '</textarea></td>
            <td><input type="text" class="form-control" name="uom_' . $model->id . '" value="' . $model->uom . '"></td>
            <td><input type="text" class="form-control" name="quantity_' . $model->id . '" value="' . $model->quantity . '"></td>
            <td><input type="text" class="form-control" name="unit_price_' . $model->id . '" value="' . $model->unit_price . '"></td>
            <td><input type="text" class="form-control" name="total_price_' . $model->id . '" value="' . $model->total_price . '"></td>
            <td style="text-align:center;">
                <i class="fas fa-trash-alt kt-font-danger" style="cursor:pointer;" title="Delete product" onclick="deleteproduct(' . $model->id . ')"></i>
            </td>
        </tr>';
    }

    public function actionDeleteproduct() {
        $id = $_POST['id'];
        $status = 'failed';
        if (QuotationItem::findOne($id)->delete())
            $status = 'success';
        return $status;
    }

    public function actionGetproductlist() {
        $doc_id = $_POST['doc_id'];
        $output = '';
        $model = QuotationItem::find()->where(['doc_id' => $doc_id])->orderBy(['id' => SORT_ASC])->all();
        if (!empty($model)) {
            $count = 0;
            $output .= '<table class="table table-bordered table-striped">
                <thead>
                    <tr class="thead-dark">
                        <th width="1%">No</th>
                        <th>Description</th>
                        <th width="10%">Qty</th>
                        <th width="10%">UoM</th>
                        <th width="10%">Unit Price</th>
                        <th width="10%">Total</th>
                        <th width="1%">Action</th>
                    </tr>
                </thead><tbody>';
            foreach ($model as $row) {
                $count++;
                $output .= '<tr>
                        <td>' . $count . '</td>
                        <td>' . $row->product_name . '</td>
                        <td>' . number_format($row->quantity) . '</td>
                        <td>' . $row->uom . '</td>
                        <td>RM ' . number_format((float) $row->unit_price, 2, '.', ',') . '</td>
                        <td>RM ' . number_format((float) $row->total_price, 2, '.', ',') . '</td>
                        <td align="center"><i class="fas fa-trash-alt kt-font-danger" style="cursor:pointer;" title="Delete product" onclick="deleteproduct(' . $row->id . ')"></i></td>
                    </tr>';
            }
            $output .= '</tbody></table>';
        }
        return $output;
    }

    public function actionDownload($uuid) {
        $ParamList = new ParamList();
        $User = new User();
        $Notes = new Notes();
        $model = $this->findModel($uuid);
        if (!empty($model)) {
            $modelcom = Company::findOne($model->company_id);
            if (!empty($modelcom)) {

                $company_address = $modelcom->address1 . ' ' .
                        $modelcom->address2 . '<br>' .
                        $modelcom->postcode . ' ' .
                        $modelcom->city . ' ' . $ParamList->getlabel(3, $modelcom->state);

                $header = '<table id="table-header" border="0" width="100%" cellpadding="0" cellspacing="0">
                    <tr>
                        <td><img src="uploads/' . $modelcom->logo . '" height="50"></td>
                        <td align="right"><b>' . strtoupper($modelcom->name) . '</b><br/>' . strtoupper($company_address) . '</td>
                    </tr>
                </table>';
                $content = '<br><table border="0" width="100%" cellpadding="0" cellspacing="0">
                        <tr>
                            <td width="50%" valign="top">
                                <br/><br/>
                                <table cellpadding="0" cellspacing="0">
                                    <tr>
                                        <td valign="top">To</td>
                                        <td valign="top">&nbsp;&nbsp;:&nbsp;&nbsp;</td>
                                        <td valign="top">' . strtoupper($model->customer_name) . '<br>' . strtoupper($model->customer_address1 . ' ' . $model->customer_address2 . ' ' . $model->customer_postcode . ' ' . $model->customer_city . ' ' . $ParamList->getlabel(3, $model->customer_state)) . '</td>
                                    </tr>
                                    <tr>
                                        <td valign="top">Attention</td>
                                        <td valign="top">&nbsp;&nbsp;:&nbsp;&nbsp;</td>
                                        <td valign="top">' . strtoupper($model->customer_pic) . '</td>
                                    </tr>
                                </table>
                            </td>
                            <td width="20%">&nbsp;</td>
                            <td width="30%" valign="top" align="right">
                                <table cellpadding="0" cellspacing="0" style="padding-right:1em;">
                                    <tr><td colspan="3" align="center"><h4><b>QUOTATION</b></h4><br/><br/></td></tr>
                                    <tr>
                                        <td valign="top">Date</td>
                                        <td valign="top">&nbsp;&nbsp;:&nbsp;&nbsp;</td>
                                        <td valign="top" align="left">' . strtoupper(date("dS M Y", strtotime($model->doc_date))) . '</td>
                                    </tr>
                                    <tr>
                                        <td valign="top" style="white-space:nowrap;">Quotation No</td>
                                        <td valign="top">&nbsp;&nbsp;:&nbsp;&nbsp;</td>
                                        <td valign="top" align="left">' . strtoupper($model->doc_no) . '</td>
                                    </tr>
                                    <tr>
                                        <td valign="top">Valid until</td>
                                        <td valign="top">&nbsp;&nbsp;:&nbsp;&nbsp;</td>
                                        <td valign="top" align="left">' . strtoupper(date("dS M Y", strtotime($model->valid_dt))) . '</td>
                                    </tr>';
                if (!empty($model->waranty_start)) {
                    $content .= '<tr>
                                        <td valign="top">Warranty</td>
                                        <td valign="top">&nbsp;&nbsp;:&nbsp;&nbsp;</td>
                                        <td valign="top" align="left">' . strtoupper(date("dS M Y", strtotime($model->waranty_start)) . ' until ' . date("dS M Y", strtotime($model->waranty_end))) . '</td>
                                    </tr>';
                }
                $content .= '<tr>
                                        <td valign="top">Prepared by</td>
                                        <td valign="top">&nbsp;&nbsp;:&nbsp;&nbsp;</td>
                                        <td valign="top" align="left">' . strtoupper($User->getusername($model->created_by)) . '</td>
                                    </tr>
                                    <tr>
                                        <td valign="top">Contact No</td>
                                        <td valign="top">&nbsp;&nbsp;:&nbsp;&nbsp;</td>
                                        <td valign="top" align="left">' . $User->getuserphone($model->created_by) . '</td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table><br>';
                $content .= '<table width="100%" cellpadding="5" cellspacing="1" border="0" style="background-color:black;" id="table-product">
                        <thead>
                            <tr>
                                <th align="center" width="5%">No</th>
                                <th align="center">Description</th>
                                <th align="center" width="10%">Qty</th>
                                <th align="center" width="10%">UoM</th>
                                <th align="center" width="13%">Unit Price</th>
                                <th align="center" width="13%">Total</th>
                            </tr>
                        </thead>
                        <tbody>';
                $modelItem = QuotationItem::find()->where(['doc_id' => $model->id])->orderBy(['sorting' => SORT_ASC])->all();
                $grandtotal = 0;
                $totalprice = 0;
                if (!empty($modelItem)) {
                    $countItem = 0;

                    foreach ($modelItem as $rowItem) {
                        $countItem++;
                        $content .= '<tr>
                                <td align="center">' . $countItem . '</td>
                                <td>' . str_replace(PHP_EOL, "<br>", $rowItem->product_name) . '</td>
                                <td align="center">' . $rowItem->quantity . '</td>
                                <td align="center">' . $rowItem->uom . '</td>
                                <td align="right">RM ' . number_format((float) $rowItem->unit_price, 2, '.', ',') . '</td>
                                <td align="right">RM ' . number_format((float) $rowItem->total_price, 2, '.', ',') . '</td>
                            </tr>';
                        $grandtotal += $rowItem->total_price;
                        $totalprice += $rowItem->total_price;
                    }
                } else {
                    $content .= '<tr><td colspan="6">No record found</td></tr>';
                }

                $company_stamp = '<tr><td align="center" height="110"></td></tr>';
                if (!empty($modelcom->stamp))
                    $company_stamp = '<tr><td align="center"><img src="uploads/' . $modelcom->stamp . '" height="100"></td></tr>';

                $content .= '</tbody><tfoot>';

                if ($model->tax_status == 1) {
                    $content .= '<tr>
                            <td colspan="5" align="right">Total Price</td>
                            <td align="right"><b>RM ' . number_format((float) $totalprice, 2, '.', ',') . '</b></td>
                        </tr>';
                    $priceaddtax =  $model->tax_percentage / 100 * $totalprice;
                    $content .= '<tr>
                            <td colspan="5" align="right">' . $model->tax_name . ' (' . $model->tax_percentage . '%)</td>
                            <td align="right"><b>RM ' . number_format((float) $priceaddtax, 2, '.', ',') . '</b></td>
                        </tr>';
                    $grandtotal+= $priceaddtax;
                }
                $content .= '<tr>
                            <td colspan="5" align="right">Grand Total</td>
                            <td align="right"><b>RM ' . number_format((float) $grandtotal, 2, '.', ',') . '</b></td>
                        </tr></tfoot>';


                $content .= '</table>';
                $content .= '<br><div>' . $Notes->getnotes('Quotation', $modelcom->id) . '</div>';


                $content .= '<br><br>Approved By<br><br><br><br><table width="40%"><tr><td style="border-top:1px solid black;"></td></tr></table>';
                if (!empty($model->approved_by)) {

                    $modelApproved = User::findOne($model->approved_by);
                    if (!empty($modelApproved)) {
                        $content .= $modelApproved->name;
                        if (!empty($modelApproved->designation))
                            $content .= '<br>' . $modelApproved->designation;
                        $content .= '<br>Phone : +601' . $modelApproved->phone;
                        $content .= '<br>Email : ' . $modelApproved->email;
                    }
                }



                /* $footer = '<table id="table-footer" border="0" width="100%" cellpadding="0" cellspacing="0">
                  <tr><td align="center">' . $modelcom->address1 . ' ' .
                  $modelcom->address2 . ' ' .
                  $modelcom->postcode . ' ' .
                  $modelcom->city . ' ' . $ParamList->getlabel(3, $modelcom->state) . '
                  </td>
                  </tr>
                  </table>'; */
                $footer = $modelcom->website;

                // setup kartik\mpdf\Pdf component
                $pdf = new Pdf([
                    'mode' => Pdf::MODE_CORE,
                    'filename' => 'Quotation ' . $model->doc_no . '.pdf',
                    'format' => Pdf::FORMAT_A4,
                    'orientation' => Pdf::ORIENT_PORTRAIT,
                    'destination' => Pdf::DEST_BROWSER,
                    'cssFile' => '@vendor/kartik-v/yii2-mpdf/src/assets/kv-mpdf-bootstrap.min.css',
                    'cssInline' => 'body,table td{font-size:11px;Arial, Helvetica, sans-serif;line-height:1.7em;}
                        #table-header{padding-bottom:10px;}
                        #table-footer{padding-top:10px;}
                        #table-product th{background-color:black;color:white;text-align:center;}
                        #table-product tr:nth-child(odd) td{background-color:white;}
                        #table-product tr:nth-child(even) td{background-color:whitesmoke;}',
                    'methods' => ['SetHeader' => [$header], 'SetFooter' => $footer],
                    'content' => $content,
                    'options' => ['setAutoTopMargin' => 'stretch'],
                ]);
                return $pdf->render();
            }
        }
    }

}