Your IP : 216.73.216.79


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

<?php

namespace app\controllers;

use Yii;
use app\models\GrnParent;
use app\models\GrnParentSearch;
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 yii\helpers\Html;
use app\models\Log;
use app\models\LogSearch;
use app\models\Customer;
use app\models\Company;
use app\models\StockLog;
use app\models\DeliveryOrder;
use app\models\DeliveryOrderItem;
use app\models\Grn;
use app\models\Product;
use app\models\CreditnoteItem;
use app\models\ParamList;

/**
 * GrnparentController implements the CRUD actions for GrnParent model.
 */
class GrnparentController extends Controller {

    public $menu_id = 48;

    /**
     * {@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 GrnParent models.
     * @return mixed
     */
    public function actionIndex() {
        $searchModel = new GrnParentSearch();
        $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 GrnParent 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 GrnParent model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $model = new GrnParent();
        $model->received_dt = 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()) && $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=grnparent/update&uuid=$model->uuid';});");
        }
        return $this->render('create', ['model' => $model, 'menu_id' => $this->menu_id]);
    }

    /**
     * Updates an existing GrnParent 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->save()) {
            if (!empty($_POST['item_id'])) {
                $item_arr = $_POST['item_id'];
                foreach ($item_arr as $item_id) {
                    if (($modelItem = Grn::findOne($item_id)) !== null) {
                        $modelItem->quantity = $_POST['item_quantity_' . $item_id];
                        $modelItem->remarks = $_POST['item_remarks_' . $item_id];
                        $modelItem->received_dt = $model->received_dt;
                        $modelItem->save();

                        if (!empty($model->cn_id)) {
                            if (($modelCnItem = CreditnoteItem::findOne(['doc_id' => $model->cn_id, 'product_id' => $modelItem->product_id, 'type' => 'product'])) !== null) {
                                $modelCnItem->quantity = $modelItem->quantity;
                                $total = number_format((float) ($modelItem->quantity * $modelCnItem->unit_price), 2, '.', ',');
                                $modelCnItem->total = $total;
                                $modelCnItem->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=grnparent/update&uuid=$model->uuid';});");
        }
        return $this->render('update', ['model' => $model, 'menu_id' => $this->menu_id]);
    }

    /**
     * Deletes an existing GrnParent 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) {
        $this->findModel($id)->delete();

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

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

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

    public function actionGetdodetails() {
        $id = $_POST['id'];
        $output = '';
        if (($model = DeliveryOrder::findOne($id)) !== null) {
            $Company = new Company;
            $output.= $model->company_id . '<->' . $Company->getname($model->company_id);
            $output.= '<->' . $model->customer_id . '<->' . $model->customer_name . '<->';
        }
        return $output;
    }

    public function actionGetproductlist() {
        $do_id = $_POST['do_id'];
        $parent_id = $_POST['parent_id'];
        $model = DeliveryOrderItem::find()->where(['=', 'doc_id', $do_id])->orderBy(['id' => SORT_ASC])->all();
        $count = 0;
        $output = '';
        if (!empty($model)) {
            foreach ($model as $row) {
                $count++;
                $Product = new Product();
                if (($modelItem = Grn::findOne(['parent_id' => $parent_id, 'product_id' => $row->product_id])) === null) {
                    $output.= '<div class="col-6">
                        <label class="kt-checkbox">
                            <input type="checkbox" value="' . $row->product_id . '" class="product_id"> ' . $Product->getname($row->product_id) . '
                            <span></span>
                        </label>
                    </div>';
                }
            }
        }
        if ($count == 0)
            return 'All product has been added to the GRN or no product found under this company';
        else
            return '<div class="row">' . $output . '</div><div class="kt-font-bold kt-font-danger" id="error_message">Please select at lease one (1) product</div>';
    }

    public function actionAddproduct() {
        $output = '';
        $do_id = $_POST['do_id'];
        $cust_id = $_POST['cust_id'];
        $com_id = $_POST['com_id'];
        $received_dt = $_POST['received_dt'];
        $parent_id = $_POST['parent_id'];

        $Product = new Product();
        $DeliveryOrderItem = new DeliveryOrderItem();

        if (!empty($_POST['items'])) {
            foreach ($_POST['items'] as $item) {
                //insert into grn
                $model = new Grn();
                $model->do_id = $do_id;
                $model->cust_id = $cust_id;
                $model->com_id = $com_id;
                $model->product_id = $item;
                $model->quantity = 0;
                $model->received_dt = $received_dt;
                $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();
                $model->parent_id = $parent_id;
                $model->status_inspection = 'pending';
                $model->owner_type = $DeliveryOrderItem->getownertype($model->do_id, $model->product_id);
                $model->owner_id = $DeliveryOrderItem->getownerid($model->do_id, $model->product_id);

                if ($model->save()) {
                    if (($modelparent = GrnParent::findOne($parent_id)) !== null) {
                        $cn_id = $modelparent->cn_id;
                        if (!empty($cn_id)) {
                            $Product = new Product();
                            $ParamList = new ParamList();
                            $modelcnitem = new CreditnoteItem();

                            $modelcnitem->doc_id = $cn_id;
                            $modelcnitem->type = 'product';
                            $modelcnitem->product_id = $model->product_id;
                            $modelcnitem->quantity = 0;
                            $modelcnitem->discount = '0';
                            $modelcnitem->uom = $ParamList->getlabel(9, $Product->getuom($model->product_id));
                            $modelcnitem->unit_price = $Product->getprice($model->product_id);
                            $modelcnitem->total = '0.00';
                            $modelcnitem->created_dt = date("Y-m-d H:i:s");
                            $modelcnitem->created_by = Yii::$app->user->identity->id;
                            $modelcnitem->updated_dt = date("Y-m-d H:i:s");
                            $modelcnitem->updated_by = Yii::$app->user->identity->id;
                            $modelcnitem->save();
                        }
                    }
                    //insert into stock_log
                    $modelStockLog = new StockLog();
                    $modelStockLog->product_id = $model->product_id;
                    $modelStockLog->action_type = 'stockin';
                    $modelStockLog->table_related = 'grn';
                    $modelStockLog->data_id = $model->id;
                    $modelStockLog->company_id = $model->com_id;
                    $modelStockLog->do_no = $modelStockLog->getdono($modelStockLog->table_related, $modelStockLog->data_id);
                    $modelStockLog->action_by = Yii::$app->user->identity->id;
                    $modelStockLog->action_datetime = date("Y-m-d H:i:s");
                    $modelStockLog->owner_type = $model->owner_type;
                    $modelStockLog->owner_id = $model->owner_id;
                    
                    if ($modelStockLog->save()) {
                        //return output
                        $output.='<tr id="rowItem_' . $model->id . '">
                            <td style="vertical-align:middle;">
                                <input type="hidden" value="' . $model->id . '" name="item_id[]">
                                ' . $Product->getname($model->product_id) . '
                            </td>
                            <td style="vertical-align:middle;">' . ucwords($model->status_inspection) . '</td>
                            <td style="vertical-align:middle;">' . $DeliveryOrderItem->getqtysend($model->do_id, $model->product_id) . '</td>
                            <td><input type="text" class="form-control" value="' . $model->quantity . '" name="item_quantity_' . $model->id . '"></td>
                            <td><input type="text" class="form-control" value="' . $model->remarks . '" name="item_remarks_' . $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>';
                    }
                }
            }
        }
        return $output;
    }

    public function actionDeleteproduct() {
        $id = $_POST['id'];
        $status = 'success';
        if (($model = Grn::findOne($id)) !== null) {
            //delete from stock_log
            if (!Yii::$app->db->createCommand("DELETE FROM stock_log WHERE action_type='stockin' AND table_related='grn' AND data_id=$id")->execute()) {
                $status = 'failed';
            }

            //delete from creditnote_item
            if (($modelparent = GrnParent::findOne($model->parent_id)) !== null) {
                $cn_id = $modelparent->cn_id;
                if (!empty($cn_id)) {
                    if (!Yii::$app->db->createCommand("DELETE FROM creditnote_item WHERE doc_id=$cn_id AND product_id=$model->product_id AND type='product'")->execute()) {
                        $status = 'failed';
                    }
                }
            }

            //delete from grn
            if (!Yii::$app->db->createCommand("DELETE FROM grn WHERE id=$id")->execute()) {
                $status = 'failed';
            }
        }
        return $status;
    }

}