Your IP : 216.73.216.79


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

<?php

namespace app\controllers;

use Yii;
use app\models\Purchase;
use app\models\PurchaseSearch;
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\Vendor;
use app\models\Company;
use app\models\ParamList;
use kartik\mpdf\Pdf;
use app\models\User;
use app\models\Notes;
use app\models\PurchaseItem;

/**
 * PurchaseController implements the CRUD actions for Purchase model.
 */
class PurchaseController extends Controller {

    public $menu_id = 49;

    /**
     * {@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 Purchase models.
     * @return mixed
     */
    public function actionIndex() {
        $searchModel = new PurchaseSearch();
        $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 Purchase 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 Purchase model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $Company = new Company();
        $model = new Purchase();
        $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) Purchase::find()->where(['company_id' => $model->company_id])->count() + 1;
            $model->doc_no = $Company->getshortcode($model->company_id) . '/PO/' . 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=purchase/update&uuid=$model->uuid';});");
            }
        }
        return $this->render('create', ['model' => $model, 'menu_id' => $this->menu_id]);
    }

    /**
     * Updates an existing Purchase 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()) {

                $item_arr = $_POST['item_id'];
                if (!empty($item_arr)) {
                    foreach ($item_arr as $item_id) {
                        if (($modelItem = PurchaseItem::findOne($item_id)) !== null) {
                            $modelItem->product_name = $_POST['item_productname_' . $item_id];
                            $modelItem->quantity = $_POST['item_quantity_' . $item_id];
                            $modelItem->uom = $_POST['item_uom_' . $item_id];
                            $modelItem->unit_price = $_POST['item_unitprice_' . $item_id];
                            $modelItem->discount = $_POST['item_discount_' . $item_id];
                            $modelItem->total_price = $_POST['item_totalprice_' . $item_id];
                            $modelItem->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: 1500,}).then(function(result){window.location = 'index.php?r=purchase/update&uuid=$model->uuid';});");
            }
        }
        return $this->render('update', ['model' => $model, 'menu_id' => $this->menu_id]);
    }

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

    public function actionGetvendordetails() {
        $ParamList = new ParamList();
        $id = $_POST['id'];
        $output = '';
        if (($model = Vendor::findOne($id)) !== null) {
            $output = $model->name . '<->' .
                    $model->address1 . '<->' .
                    $model->address2 . '<->' .
                    $model->postcode . '<->' .
                    $model->city . '<->' .
                    $ParamList->getlabel(3, $model->state) . '<->' .
                    $model->country . '<->' .
                    $model->contact_name . '<->' .
                    $model->contact_no;
        }
        return $output;
    }

    public function actionAddproduct() {
        $model = new PurchaseItem();
        $model->purchase_id = $_POST['purchase_id'];
        $model->quantity = 0;
        $model->unit_price = '0.00';
        $model->discount = 0;
        $model->total_price = '0.00';
        $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 '<tr id="row_' . $model->id . '">
                        <td><input type="hidden" value="' . $model->id . '" name="item_id[]"><input type="text" class="form-control" value="' . $model->product_name . '" name="item_productname_' . $model->id . '"></td>
                        <td><input type="text" class="form-control" value="' . $model->quantity . '" name="item_quantity_' . $model->id . '" onchange="updatetotal(' . $model->id . ')"></td>
                        <td><input type="text" class="form-control" value="' . $model->uom . '" name="item_uom_' . $model->id . '"></td>
                        <td><input type="text" class="form-control" value="' . $model->unit_price . '" name="item_unitprice_' . $model->id . '" onchange="updatetotal(' . $model->id . ')"></td>
                        <td><input type="text" class="form-control" value="' . $model->discount . '" name="item_discount_' . $model->id . '" onchange="updatetotal(' . $model->id . ')"></td>
                        <td><input type="text" class="form-control" value="' . $model->total_price . '" name="item_totalprice_' . $model->id . '"></td>
                        <td 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 actionGetproductlist() {
        $purchase_id = $_POST['purchase_id'];
        $output = '';
        $model = PurchaseItem::find()->where(['purchase_id' => $purchase_id])->orderBy(['id' => SORT_ASC])->all();
        if (!empty($model)) {
            foreach ($model as $row) {
                $output .= '<tr id="row_' . $row->id . '">
                        <td><input type="hidden" value="' . $row->id . '" name="item_id[]"><input type="text" class="form-control" value="' . $row->product_name . '" name="item_productname_' . $row->id . '"></td>
                        <td><input type="text" class="form-control" value="' . $row->quantity . '" name="item_quantity_' . $row->id . '" onchange="updatetotal(' . $row->id . ')"></td>
                        <td><input type="text" class="form-control" value="' . $row->uom . '" name="item_uom_' . $row->id . '"></td>
                        <td><input type="text" class="form-control" value="' . $row->unit_price . '" name="item_unitprice_' . $row->id . '" onchange="updatetotal(' . $row->id . ')"></td>
                        <td><input type="text" class="form-control" value="' . $row->discount . '" name="item_discount_' . $row->id . '" onchange="updatetotal(' . $row->id . ')"></td>
                        <td><input type="text" class="form-control" value="' . $row->total_price . '" name="item_totalprice_' . $row->id . '"></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>';
            }
        }
        return $output;
    }

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

    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)) {

                $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/>' . $modelcom->website . '</td>
                    </tr>
                </table>';

                $content = '<br><table border="0" width="100%" cellpadding="0" cellspacing="0">
                        <tr>
                            <td width="40%" valign="top">
                                <table cellpadding="0" cellspacing="0">
                                    <tr><td>&nbsp;</td></tr>
                                    <tr><td>&nbsp;</td></tr>
                                    <tr><td>&nbsp;</td></tr>
                                    <tr><td>&nbsp;</td></tr>
                                    <tr><td>&nbsp;</td></tr>
                                    <tr><td colspan="3"><b>VENDOR</b></td></tr>
                                    <tr>
                                        <td valign="top">Company Name</td>
                                        <td valign="top">&nbsp;&nbsp;:&nbsp;&nbsp;</td>
                                        <td valign="top">' . $model->vendor_name . '</td>
                                    </tr>
                                    <tr>
                                        <td valign="top">Address</td>
                                        <td valign="top">&nbsp;&nbsp;:&nbsp;&nbsp;</td>
                                        <td valign="top">' . $model->vendor_address1 . ' ' . $model->vendor_address2 . ' ' . $model->vendor_postcode . ' ' . $model->vendor_city . ' ' . $model->vendor_state . ' ' . $ParamList->getlabel(21, $model->vendor_country) . '</td>
                                    </tr>
                                    <tr>
                                        <td valign="top">Contact Person</td>
                                        <td valign="top">&nbsp;&nbsp;:&nbsp;&nbsp;</td>
                                        <td valign="top">' . $model->vendor_pic . '</td>
                                    </tr>
                                    <tr>
                                        <td valign="top">Contact No</td>
                                        <td valign="top">&nbsp;&nbsp;:&nbsp;&nbsp;</td>
                                        <td valign="top">' . $model->vendor_phone . '</td>
                                    </tr>
                                </table>
                            </td>
                            <td width="20%"></td>
                            <td width="40%" valign="top">
                                <table cellpadding="0" cellspacing="0">
                                    <tr><td colspan="3" align="center"><h4><b>PURCHASE ORDER</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">' . date("dS M Y", strtotime($model->doc_date)) . '</td>
                                    </tr>
                                    <tr>
                                        <td valign="top">PO No</td>
                                        <td valign="top">&nbsp;&nbsp;:&nbsp;&nbsp;</td>
                                        <td valign="top" align="left">' . $model->doc_no . '</td>
                                    </tr>
                                    <tr><td>&nbsp;</td></tr>
                                    <tr><td colspan="3"><b>SHIP TO</b></td></tr>
                                    <tr>
                                        <td valign="top">Company Name</td>
                                        <td valign="top">&nbsp;&nbsp;:&nbsp;&nbsp;</td>
                                        <td valign="top">' . $modelcom->name . '</td>
                                    </tr>
                                    <tr>
                                        <td valign="top">Address</td>
                                        <td valign="top">&nbsp;&nbsp;:&nbsp;&nbsp;</td>
                                        <td valign="top">' . $modelcom->address1 . ' ' . $modelcom->address2 . ' ' . $modelcom->postcode . ' ' . $modelcom->city . ' ' . $ParamList->getlabel(3, $modelcom->state) . '</td>
                                    </tr>
                                    <tr>
                                        <td valign="top">Contact Person</td>
                                        <td valign="top">&nbsp;&nbsp;:&nbsp;&nbsp;</td>
                                        <td valign="top">' . $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">' . $User->getuserphone($model->created_by) . '</td>
                                    </tr>
                                </table>    
                        </td>
                    </tr>
                    </table><br>';

                $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>';

                $content .= '<table width="100%" cellpadding="5" cellspacing="1" border="0" style="background-color:black;" id="table-product">
                        <thead>
                            <tr>
                                <th width="5%">No</th>
                                <th>Description</th>
                                <th width="10%">Qty</th>
                                <th width="10%">UoM</th>
                                <th width="10%">Unit Price</th>
                                <th width="10%">Discount</th>
                                <th width="15%">Total</th>
                            </tr>
                        </thead>
                        <tbody>';

                $modelItem = PurchaseItem::find()->where(['purchase_id' => $model->id])->orderBy(['id' => SORT_ASC])->all();
                $grandtotal = 0;
                if (!empty($modelItem)) {
                    $countItem = 0;
                    foreach ($modelItem as $rowItem) {
                        $countItem++;
                        $content .= '<tr>
                                <td align="center">' . $countItem . '</td>
                                <td>' . $rowItem->product_name . '</td>
                                <td>' . number_format($rowItem->quantity) . '</td>
                                <td>' . $rowItem->uom . '</td>
                                <td>RM ' . number_format((float) $rowItem->unit_price, 2, '.', ',') . '</td>
                                <td>' . $rowItem->discount . '%</td>
                                <td>RM ' . number_format((float) $rowItem->total_price, 2, '.', ',') . '</td>
                            </tr>';
                        $grandtotal += $rowItem->total_price;
                    }
                } else {
                    $content .= '<tr><td colspan="7">No record found</td></tr>';
                }

                $content .= '</tbody>
                    <tfoot>
                        <tr>
                            <td colspan="6" align="right">Grand Total</td>
                            <td><b>RM ' . number_format((float) $grandtotal, 2, '.', ',') . '</b></td>
                        </tr>
                    </tfoot>
                </table>';

                if (!empty($model->notes))
                    $content .= '<br/><p>Note / Reason : ' . $model->notes . '</p>';

                $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 .= Yii::$app->sharedfunction->convertMoneyToText($grandtotal) . '<hr><div style="font-size:8px;line-height:1.7em;">' . $Notes->getnotes('Purchase', $modelcom->id) . '</div>
                    <table width="40%">
                        ' . $company_stamp . '
                        <tr><td align="center" style="border-top:1px solid black;">Authorized Signature</td></tr>
                    </table>';

                // setup kartik\mpdf\Pdf component
                $pdf = new Pdf([
                    'mode' => Pdf::MODE_CORE,
                    'filename' => 'Credit Note ' . $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();
            }
        }
    }

}