Source

eqsupport / protected / controllers / IncidenciaController.php

Full commit
<?php

class IncidenciaController extends CController
{
	const PAGE_SIZE=10;

	/**
	 * @var string specifies the default action to be 'list'.
	 */
	public $defaultAction='list';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', 
				'actions'=>array('create', 'buscarcliente', 'generarecibo', 'list','show'),
				'users'=>array('@'),
			),
			array('allow', 
				'actions'=>array('admin', 'create', 'update'),
				'expression'=>'Yii::app()->user->getState("role")==Usuario::ROLE_ADMINISTRADOR',
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Shows a particular model.
	 */
	public function actionShow()
	{
        $resolution = array();

        $incidencia = $this->loadIncidencia();
        $evaluacion = $this->nuevaEvaluacion($incidencia);

        if ($incidencia->estado == 3 && Yii::app()->user->getState("role")==Usuario::ROLE_RECEPCION) {
            $resolution = array(
                ''=>'--------',
                '8'=>'Entregado',
            );
        }

        //Only to technical roles.
        if (Yii::app()->user->getState("role")==Usuario::ROLE_TECNICO) {
            $resolution = array(
                '0'=>'No Garantía',
                '1'=>'Garantía',
                '2'=>'En cobro',
                '3' => 'Listo para entrega'
            );
        }

        $this->render('show',array(
            'model'=>$incidencia,
            'evaluacion'=>$evaluacion,
            'resolution'=>$resolution,
        ));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionCreate()
	{
		$model=new Incidencia;
        $model->fecha_ingreso = date('Y-m-d H:i:s');
        $model->activo = 1;
        $model->estado = 9;

		if(isset($_POST['Incidencia']))
		{
            $nombre_cliente = $_POST['Incidencia']['cliente_id'];
			$model->attributes=$_POST['Incidencia'];
            $model->cliente_id = $this->getClienteId($nombre_cliente);

			if($model->save())
				$this->redirect(array('show','id'=>$model->id));

		}
        if($model->errors) 
            $model->cliente_id = $nombre_cliente;
		$this->render('create',array('model'=>$model));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'list' page.
	 */
	public function actionDelete()
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadIncidencia()->delete();
			$this->redirect(array('list'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionList()
	{
        $criteria=new CDbCriteria;
		$issue=new Incidencia;

        $criteria->join = 'LEFT JOIN eqsupport_cliente AS c ON t.cliente_id = c.id';

        $criteria->condition = 't.activo = :status';
        $criteria->params = array(':status'=>Incidencia::STATUS_OPEN);

        if (isset($_POST['Incidencia'])) {
            if(!isset($_POST['Incidencia']['activo'])){
                $criteria->params = array(':status'=>Incidencia::STATUS_CLOSED);
            }

            if($_POST['Incidencia']['id'] != NULL){
                $criteria->condition .= ' AND t.id = :number';
                $criteria->params = array_merge($criteria->params, array(':number'=>$_POST['Incidencia']['id']));
            }

            if($_POST['Incidencia']['cliente'] != NULL){
                $criteria->addSearchCondition('c.nombre', $_POST['Incidencia']['cliente']);
            }
        }

        $criteria->order = 'fecha_ingreso DESC';

		$pages=new CPagination(Incidencia::model()->count($criteria));
		$pages->pageSize=self::PAGE_SIZE;
		$pages->applyLimit($criteria);

		$models=Incidencia::model()->findAll($criteria);

		$this->render('list',array(
			'issue'=>$issue,
			'models'=>$models,
			'pages'=>$pages,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$this->processAdminCommand();

		$criteria=new CDbCriteria;

		$pages=new CPagination(Incidencia::model()->count($criteria));
		$pages->pageSize=self::PAGE_SIZE;
		$pages->applyLimit($criteria);

		$sort=new CSort('Incidencia');
		$sort->applyOrder($criteria);

		$models=Incidencia::model()->findAll($criteria);

		$this->render('admin',array(
			'models'=>$models,
			'pages'=>$pages,
			'sort'=>$sort,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
	 */
	public function loadIncidencia($id=null)
	{
		if($this->_model===null)
		{
			if($id!==null || isset($_GET['id']))
				$this->_model=Incidencia::model()->findbyPk($id!==null ? $id : $_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}

	/**
	 * Executes any command triggered on the admin page.
	 */
	protected function processAdminCommand()
	{
		if(isset($_POST['command'], $_POST['id']) && $_POST['command']==='delete')
		{
			$this->loadIncidencia($_POST['id'])->delete();
			// reload the current page to avoid duplicated delete actions
			$this->refresh();
		}
	}


    /**
     * Try to get customer's names through ajax.
     **/
    public function actionBuscarcliente()
    {
        if (Yii::app()->request->isAjaxRequest && isset($_GET['q'])) {

            $nombres = '';
            $criteria=new CDbCriteria;

            $criteria->select='nombre';
            $criteria->condition='nombre LIKE :name';
            $criteria->params = array(':name' => "%".$_GET['q']."%");

            $clientes = Cliente::model()->findAll($criteria);
            foreach ($clientes as $cliente) {
                $nombres .= $cliente->getAttribute('nombre')."\n";
            }

            echo $nombres;
        }
    }



    /**
     * Returns cliente_id with name given and if cliente
     * doesn't exist creates one.
     **/
    public function getClienteId($nombre)
    {
            $criteria = new CDbCriteria();
            $cliente_id='';

            $criteria->select = 'id';
            $criteria->condition = 'nombre=:name'; 
            $criteria->params = array(":name" => $nombre);
            $clientes = Cliente::model()->findAll($criteria);

            if (!$clientes) {
                $new_cliente = new Cliente;
                $new_cliente->nombre = $nombre;
                if($new_cliente->save())
                    $cliente_id = $new_cliente->getAttribute('id');

            }else{

                foreach ($clientes as $cliente_escogido) {
                    $cliente_id = $cliente_escogido->getAttribute('id');
                }
            }
            return $cliente_id;
    }

    /**
     * Creates evaluations or comments, observations.
     **/

    protected function nuevaEvaluacion($incidencia)
    {
        $evaluacion = new TrazaIncidencia;

        if(isset($_POST['TrazaIncidencia']) && isset($_POST['Incidencia']))
        {
            $evaluacion->attributes=$_POST['TrazaIncidencia'];
            $abierta = $_POST['Incidencia']['activo'];
            $valor = isset($_POST['Incidencia']['valor']) ? $_POST['Incidencia']['valor'] : NULL;

            if (isset($_POST['Incidencia']['estado'])) {
                $estado = $_POST['Incidencia']['estado'];

                switch ($estado) {
                    case '1':
                        $evaluacion->observacion .= "\nEquipo aceptado por garantía.";
                        break;
                    case '2':
                        $formatter = new CNumberFormatter('es');
                        $evaluacion->observacion .= sprintf("\n Valor de cobro %s.", $formatter->formatCurrency($valor, 'COP'));
                        break;
                    case '3':
                        $evaluacion->observacion .= "\nEquipo listo para entrega.";
                        break;
                    case '8':
                        $evaluacion->observacion .= "\nEquipo entregado al cliente.";
                        break;
                    default:
                        $estado = $incidencia->estado;
                        break;

                }

            }else {
                $estado = $incidencia->estado;
            }

            if (!$abierta){
                $evaluacion->observacion .= " Se cierra la incidencia.";
            }

            if($incidencia->agregarEvaluacion($evaluacion, $estado, $abierta, $valor))
            {
                $this->refresh();
            }
        }
        return $evaluacion;
    }


    /**
     * Try to get customer's names through ajax.
     **/
    public function actionGenerarecibo()
    {
            if (isset($_GET['inc'])){
                $_SERVER['DOCUMENT_ROOT'] = Yii::app()->basePath;

                //Get issue
                $incidencia = $this->loadIncidencia($_GET['inc']);

                //Initialize pdf object
                $pdf = Yii::createComponent('ETcPdf',
                'P', 'cm', 'Letter', true, 'UTF-8');

                // set document information
                $pdf->SetCreator(PDF_CREATOR);
                $pdf->SetSubject('Garantia');
                $pdf->SetKeywords('RCM, PDF, garantia, recibo, soporte');

                $pdf->setPrintHeader(false);

                // set default monospaced font
                $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

                //set image scale factor
                $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

                //Define font type and size
                $pdf->SetFont('times', '', 10, '', true);

                //Create the first page
                $pdf->AddPage();

                //Load Content
                $html = $this->renderPartial('invoice', array(
                    'incidencia'=>$incidencia
                    ), true);

                for ($i = 0; $i <= 1; $i++) {
                    //Writting html content
                    $pdf->writeHTMLCell($w=0, $h=0, $x='', $y='', $html, $border=0, 
                        $ln=1, $fill=0, $reseth=true, $align='', $autopadding=true);
                }

                //Making the pdf file.
                $pdf->Output(sprintf('issue_%s.pdf', $incidencia->id), 'I');
            }
            return null;
    }
}