/**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = MaterialesServicios::find();
     // Join para la relacion
     $query->joinWith(['cuenta0']);
     $query->joinWith(['presentacion0']);
     $query->joinWith(['unidadMedida']);
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     //Ordenamiento
     $dataProvider->sort->attributes['nombrePresentacion'] = ['asc' => ['presentacion.nombre' => SORT_ASC], 'desc' => ['presentacion.nombre' => SORT_DESC]];
     $dataProvider->sort->attributes['nombreUnidadMedida'] = ['asc' => ['unidad_medida.unidad_medida' => SORT_ASC], 'desc' => ['unidad_medida.unidad_medida' => SORT_DESC]];
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id, 'cuenta' => $this->cuenta, 'partida' => $this->partida, 'generica' => $this->generica, 'especifica' => $this->especifica, 'subespecifica' => $this->subespecifica, 'unidad_medida' => $this->unidad_medida, 'presentacion' => $this->presentacion, 'precio' => $this->precio, 'iva' => $this->iva, 'materiales_servicios.estatus' => $this->estatus]);
     $query->andFilterWhere(['materiales_servicios.estatus' => $this->nombreEstatus]);
     $query->andFilterWhere(['like', 'nombre', $this->nombre]);
     $query->andFilterWhere(['like', 'presentacion.nombre', $this->nombrePresentacion]);
     $query->andFilterWhere(['like', 'unidad_medida.unidad_medida', $this->nombreUnidadMedida]);
     return $dataProvider;
 }
 /**
  * Updates an existing ProyectoPedido model.
  * For ajax request will return json object
  * and for non-ajax request if update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id
  * @return mixed
  */
 public function actionUpdate($id)
 {
     $request = Yii::$app->request;
     $model = $this->findModel($id);
     //autocomplete
     $materiales = MaterialesServicios::find()->select(['nombre', 'id', 'precio', 'iva'])->all();
     //Arreglo de precios, iva, etc con id del material/servicio
     $precios = json_encode(ArrayHelper::toArray(ArrayHelper::index($materiales, 'id')));
     if ($request->isAjax) {
         /*
          *   Process for ajax request
          */
         Yii::$app->response->format = Response::FORMAT_JSON;
         if ($request->isGet) {
             return ['title' => "Pedido", 'content' => $this->renderAjax('update', ['model' => $this->findModel($id), 'materiales' => $materiales, 'precios' => $precios]), 'footer' => Html::button('Cerrar', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) . Html::button('Guardar', ['class' => 'btn btn-primary', 'type' => "submit"])];
         } else {
             if ($model->load($request->post()) && $model->save()) {
                 return ['forceReload' => 'true', 'title' => "Pedido", 'content' => $this->renderAjax('view', ['model' => $this->findModel($id), 'materiales' => $materiales, 'precios' => $precios]), 'footer' => Html::button('Cerrar', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) . Html::a('Editar', ['update', 'id' => $id], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])];
             } else {
                 return ['title' => "Pedido", 'content' => $this->renderAjax('update', ['model' => $this->findModel($id), 'materiales' => $materiales, 'precios' => $precios]), 'footer' => Html::button('Cerrar', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) . Html::button('Guardar', ['class' => 'btn btn-primary', 'type' => "submit"])];
             }
         }
     } else {
         /*
          *   Process for non-ajax request
          */
         if ($model->load($request->post()) && $model->save()) {
             return $this->redirect(['view', 'id' => $model->id]);
         } else {
             return $this->render('update', ['model' => $model, 'materiales' => $materiales, 'precios' => $precios]);
         }
     }
 }
 /**
  * Importar Materiales o Servicios.
  * Se recibe el stream de un archivo CSV. Se lee cada linea del archivo
  * y se separa cada columna en un arreglo. Cada elemento del arreglo se utilizara
  * para buscar los modelos asociados al registro a insertar/modificar.
  * @return mixed
  */
 public function actionImportar()
 {
     $request = Yii::$app->request;
     $modelo = new UploadForm();
     if ($request->isPost) {
         $archivo = file($_FILES['UploadForm']['tmp_name']['importFile']);
         $transaccion = MaterialesServicios::getDb()->beginTransaction();
         try {
             //Por cada linea leida
             foreach ($archivo as $llave => $valor) {
                 //Ignorar el encabezado
                 if ($llave == 0) {
                     continue;
                 }
                 //Separar las columnas de la linea leida
                 $exploded = explode(',', str_replace('"', '', $valor));
                 /* Llaves foraneas */
                 //Preparar la llave compuesta
                 $cuenta = substr($exploded[0], 0, 1);
                 $partida = substr($exploded[0], 1, 2);
                 $generica = substr($exploded[0], 3, 2);
                 $especifica = substr($exploded[0], 5, 2);
                 $subespecifica = substr($exploded[0], 7, 2);
                 //echo $cuenta."\n".$partida."\n".$generica."\n".$especifica."\n".$subespecifica;exit;
                 //Unidad de medida $exploded[2]
                 $unidad_medida = UnidadMedida::find()->where('unidad_medida LIKE "%:unidad_medida%"')->addParams([':unidad_medida' => $exploded[2]])->one();
                 //Presentacion $exploded[3]
                 $presentacion = Presentacion::find()->where('nombre LIKE "%:presentacion%"')->addParams([':presentacion' => $exploded[3]])->one();
                 //Buscar el modelo. Material o servicio $exploded[1]
                 $ms = MaterialesServicios::find()->where(['nombre' => $exploded[1], 'cuenta' => $cuenta, 'partida' => $partida, 'generica' => $generica, 'especifica' => $especifica, 'subespecifica' => $subespecifica])->one();
                 //Si no se encuentra un material o servicio
                 if ($ms == null) {
                     //Modelo nuevo a insertar
                     $ms = new MaterialesServicios();
                 }
                 //Asignar variables
                 $ms->cuenta = $cuenta;
                 $ms->partida = $partida;
                 $ms->generica = $generica;
                 $ms->especifica = $especifica;
                 $ms->subespecifica = $subespecifica;
                 $ms->nombre = $exploded[1];
                 $ms->unidad_medida = $unidad_medida != null ? $unidad_medida->id : null;
                 $ms->presentacion = $presentacion != null ? $presentacion->id : null;
                 $ms->precio = $exploded[4];
                 $ms->iva = 12;
                 //IVA 12%
                 $ms->estatus = 1;
                 //1 Activo, 0 Inactivo
                 $ms->save();
             }
             //Se insertan o modifican los registros
             $transaccion->commit();
             //Mensaje de exito
             Yii::$app->session->setFlash('importado', '<div class="alert alert-success">Registros importados exitosamente.</div>');
             return $this->refresh();
         } catch (\Exception $e) {
             //Falla la insercion o modificacion de registros
             //Se cancela la transaccion
             $transaccion->rollBack();
             //Mensaje de error
             Yii::$app->session->setFlash('importado', '<div class="alert alert-danger">' . $e . '</div>');
         }
     }
     //La vista
     return $this->render('importar', ['modelo' => $modelo]);
 }
 public function actionLlenarprecio()
 {
     $request = Yii::$app->request;
     if ($request->isAjax) {
         Yii::$app->response->format = Response::FORMAT_JSON;
         if ($request->isPost) {
             //Acciones Especificas
             $ace = MaterialesServicios::find()->select(["precio", "iva"])->where(['id' => $request->post('id')])->asArray()->all();
             if ($ace != null) {
                 return $ace;
             } else {
                 return 0;
             }
         }
     }
 }