/**
  * Borrar todas las relaciones existentes con la entidad e
  * id de entidad origen
  * 
  * @param integer $entidadOrigen El nombre la entidad origen
  * @param integer $idOrigen El id de la entidad origen
  */
 public function eraseRelaciones($entidadOrigen, $idOrigen)
 {
     $em = new EntityManager($this->getConectionName());
     if ($em->getDbLink()) {
         $query = "delete from {$this->getDataBaseName()}.{$this->getTableName()} WHERE EntidadOrigen='{$entidadOrigen}' AND IdEntidadOrigen='{$idOrigen}'";
         $em->query($query);
         $em->desConecta();
     }
     unset($em);
 }
 /**
  * Devuelve un array con las agencias de transporte que operan en
  * la zona de transporte en curso.
  *
  * Se entiende por 'operar', que tenga alguna tarifa en la
  * tabla de portes.
  *
  * @return array (Id,Value)
  */
 public function getAgenciasOperadoras()
 {
     $rows = array();
     $em = new EntityManager($this->getConectionName());
     if ($em->getDbLink()) {
         $query = "\n                SELECT DISTINCT tp.IDAgencia AS Id, ag.Agencia AS Value\n                FROM ErpTablaPortes as tp, ErpAgencias as ag\n                WHERE\n                  tp.IDZona='{$this->IDZona}' AND\n                  tp.IDAgencia=zt.IDAgencia\n                ORDER BY ag.Agencia ASC";
         $em->query($query);
         $rows = $em->fetchResult();
         $em->desConecta();
     }
     return $rows;
 }
 /**
  * Antes de insertar hay que comprobar que no se exceda
  * el número máximo de banners permitido por zona
  */
 public function validaLogico()
 {
     parent::validaLogico();
     if ($this->getPrimaryKeyValue() == '') {
         // Voy a insertar
         $zona = new SldZonas($this->IdZona);
         $slider = new SldSliders();
         $rows = $slider->cargaCondicion("count(Id) as nMax", "IdZona='{$this->IdZona}'");
         if ($zona->getNumeroMaximoSliders() > 0 and $zona->getNumeroMaximoSliders() < $rows[0]['nMax'] + 1) {
             $this->_errores[] = "Se ha superado el número de sliders para la zona {$zona->getTitulo()}. Consulte con el administrador de la web";
         }
         unset($slider);
         unset($zona);
     }
     $filtro = $this->getPrimaryKeyValue() == '' ? '1' : "Id<>'{$this->getPrimaryKeyValue()}'";
     $sld = new SldSliders();
     $rows = $sld->cargaCondicion("distinct IdTipo", $filtro);
     unset($sld);
     foreach ($rows as $row) {
         $tiposExistentes[$row['IdTipo']] = true;
     }
     // Comprobar la jerarquía de los sliders
     $query = "";
     if ($this->IdTipo > '0') {
         if ($tiposExistentes['1']) {
             $this->_errores[] = "Ya existe un slider fijo para toda la WEB";
         } else {
             if ($this->IdTipo == '1') {
                 $this->_alertas[] = "Los posibles sliders fijos que hubiese pasan a ser variables";
                 $query = "UPDATE {$this->getDataBaseName()}.SldSliders SET IdTipo='0' WHERE IdTipo>'0'";
             }
             if ($this->IdTipo == '2' and $tiposExistentes['2']) {
                 $query = "UPDATE {$this->getDataBaseName()}.SldSliders SET IdTipo='0' WHERE IdTipo='{$this->IdTipo}'";
                 $this->_alertas[] = "Ya existía un slider fijo para el HOME, ha sido cambiado";
             }
             if ($this->IdTipo == '3' and $tiposExistentes['3']) {
                 $query = "UPDATE {$this->getDataBaseName()}.SldSliders SET IdTipo='0' WHERE IdTipo='{$this->IdTipo}'";
                 $this->_alertas[] = "Ya existía un slider fijo para la WEB excepto el HOME, ha sido cambiado";
             }
             if ($query) {
                 $em = new EntityManager($this->getConectionName());
                 if ($em->getDbLink()) {
                     $em->query($query);
                     //echo $query;
                 }
                 $em->desConecta();
                 unset($em);
             }
         }
     }
 }
Exemple #4
0
 /**
  * Devuelve un array con los tpvs de la sucursal indicada
  * o en su defecto la sucursal en curso
  *
  * @param integer $idSucursal
  * @return array
  */
 public function fetchAll($idSucursal = '', $default = true)
 {
     if ($idSucursal == '') {
         $idSucursal = $_SESSION['suc'];
     }
     $em = new EntityManager($this->getConectionName());
     $link = $em->getDbLink();
     if (is_resource($link)) {
         $query = "select IDTpv as Id, Nombre as Value from {$this->getDataBaseName()}.{$this->getTableName()} where IDSucursal='" . $idSucursal . "'";
         $em->query($query);
         $tpvs = $em->fetchResult();
         $em->desConecta();
     }
     return $tpvs;
 }
Exemple #5
0
 /**
  * Devuelve un array con las Zonas de transporte donde opera la agencia
  * en curso.
  *
  * Se entiende por 'operar', que tenga alguna tarifa en la
  * tabla de portes.
  *
  * @return array (Id,Value)
  */
 public function getZonasOperacion()
 {
     $rows = array();
     $zonas = new ZonasTransporte();
     $tablaZonas = $zonas->getDataBaseName() . "." . $zonas->getTableName();
     $portes = new TablaPortes();
     $tablaPortes = $portes->getDataBaseName() . "." . $portes->getTableName();
     $em = new EntityManager($zonas->getConectionName());
     if ($em->getDbLink()) {
         $query = "\n                SELECT DISTINCT tp.IDZona AS Id, zt.Zona AS Value\n                FROM \n                  {$tablaPortes} as tp, \n                  {$tablaZonas} as zt\n                WHERE\n                  tp.IDAgencia='{$this->IDAgencia}' AND\n                  tp.IDZona=zt.IDZona\n                ORDER BY zt.Zona ASC";
         $em->query($query);
         $rows = $em->fetchResult();
         $em->desConecta();
     }
     return $rows;
 }
 public function listadoAction($aditionalFilter = '')
 {
     $pdf = new PDF("P", 'mm', "A4");
     $pdf->SetTopMargin(15);
     $pdf->SetLeftMargin(10);
     $pdf->AliasNbPages();
     $pdf->SetFillColor(210);
     $per = new Permisos();
     $em = new EntityManager($per->getConectionName());
     $query = "select t1.IdPerfil,t1.Permisos,t4.Perfil,t2.Titulo as Opcion,t3.Titulo as SubOpcion\n                from AgtPermisos as t1,menu as t2, submenu as t3, perfiles as t4\n                where t1.IDOpcion=t2.IDOpcion\n                and t1.IDOpcion=t3.IDOpcion\n                and t3.Id=t1.IDSubOpcion\n                and t1.IdPerfil=t4.Id\n                order by t1.IdPerfil,t1.IDOpcion,t1.IDSubOpcion;";
     $em->query($query);
     $rows = $em->fetchResult();
     $em->desConecta();
     unset($per);
     $perant = "";
     $opcant = "";
     foreach ($rows as $row) {
         if ($perant != $row['IDPerfil']) {
             $pdf->AddPage();
             $pdf->Cell(40, 5, $row['Perfil'], 0, 0, "L", 1);
         } else {
             $pdf->Cell(40, 5, "", 0, 0, "L", 0);
         }
         $pdf->SetFillColor(240);
         if ($opcant != $row['Opcion']) {
             $pdf->Cell(30, 5, $row['Opcion'], 0, 0, "L", 1);
         } else {
             $pdf->Cell(30, 5, "", 0, 0, "L", 0);
         }
         $perant = $row['IDPerfil'];
         $opcant = $row['Opcion'];
         $pdf->Cell(40, 5, $row['SubOpcion'], 0, 0, "L", 0);
         $permisos = array('C' => substr($row['Permisos'], 0, 1), 'I' => substr($row['Permisos'], 1, 1), 'B' => substr($row['Permisos'], 2, 1), 'A' => substr($row['Permisos'], 3, 1), 'L' => substr($row['Permisos'], 4, 1), 'E' => substr($row['Permisos'], 5, 1));
         $pdf->Cell(13, 5, $permisos['C'], 0, 0, "C", 0);
         $pdf->Cell(13, 5, $permisos['I'], 0, 0, "C", 1);
         $pdf->Cell(13, 5, $permisos['B'], 0, 0, "C", 0);
         $pdf->Cell(13, 5, $permisos['A'], 0, 0, "C", 1);
         $pdf->Cell(13, 5, $permisos['L'], 0, 0, "C", 0);
         $pdf->Cell(13, 5, $permisos['E'], 0, 1, "C", 1);
         $pdf->SetFillColor(210);
     }
     $archivo = "docs/docs" . $_SESSION['emp'] . "/pdfs/" . md5(date('d-m-Y H:i:s')) . ".pdf";
     $pdf->Output($archivo, 'F');
     $this->values['archivo'] = $archivo;
     return array('template' => '_global/listadoPdf.html.twig', 'values' => $this->values);
 }
 /**
  * Quita la vinculación entre la empresa y el usuario y todos
  * los permisos que tuviera para los proyectos y apps de la empresa
  * 
  * @return boolean TRUE si el borraro se ha hecho con exito
  */
 public function erase()
 {
     $idEmpresa = $this->IdEmpresa;
     $idUsuario = $this->IdUsuario;
     $ok = parent::erase();
     if ($ok) {
         // Borrar todos los permisos de acceso del usuario-empresa
         $em = new EntityManager($this->getConectionName());
         if ($em->getDbLink()) {
             $query = "DELETE FROM {$em->getDataBase()}.PcaePermisos WHERE IdEmpresa='{$idEmpresa}' AND IdUsuario='{$idUsuario}'";
             $em->query($query);
             $this->_errores = $em->getError();
             $em->desConecta();
         }
         unset($em);
     }
     return $ok;
 }
 /**
  * Borra físicamente el registro que vincula la app al proyecto
  * y elimina todos los permisos relativos a ese proyecto y app
  * @return boolean
  */
 public function delete()
 {
     $idProyecto = $this->IdProyecto;
     $idEmpresa = $this->getIdProyecto()->getIdEmpresa()->getId();
     $idApp = $this->IdApp;
     $ok = parent::erase();
     if ($ok) {
         // Borrar todos los permisos de acceso a la app borrada
         $em = new EntityManager($this->getConectionName());
         if ($em->getDbLink()) {
             $query = "DELETE FROM {$em->getDataBase()}.PcaePermisos WHERE IdEmpresa='{$idEmpresa}' AND IdProyecto='{$idProyecto}' AND IdApp='{$idApp}'";
             $em->query($query);
             $this->_errores = $em->getError();
             $em->desConecta();
         }
         unset($em);
     }
     return $ok;
 }
Exemple #9
0
 /**
  * Valida antes del borrado
  * Devuelve TRUE o FALSE
  * Si hay errores carga el array $this->_errores
  * @return boolean
  */
 public function validaBorrado()
 {
     parent::validaBorrado();
     $em = new EntityManager("empresas");
     $link = $em->getDbLink();
     if (is_resource($link)) {
         //PERMISOS
         $query = "select count(Id) as N from permisos where IDOpcion='" . $this->IDOpcion . "' AND IDSubopcion='" . $this->getId() . "'";
         $row = $em->fetchResult();
         $n = $row[0]['N'];
         if ($n > 0) {
             $this->_errores[] = "Imposible eliminar. Hay " . $n . " permisos relacionados";
         }
         $em->desConecta();
     } else {
         $this->_errores[] = "Error conexión a la DB validando borrado de SubMenu";
     }
     return count($this->_errores) == 0;
 }
 /**
  * Descatalogar los lotes (poner no vigentes) que no tengan existencias
  * entre todos los almacenes de la empresa
  */
 public function DescatalogarAction()
 {
     if ($this->values['permisos']['permisosModulo']['UP']) {
         $lote = new Lotes();
         $tablaLotes = $lote->getDataBaseName() . "." . $lote->getTableName();
         $existencias = new Existencias();
         $tablaExistencias = $existencias->getDataBaseName() . "." . $existencias->getTableName();
         unset($existencias);
         $em = new EntityManager($lote->getConectionName());
         if ($em->getDbLink()) {
             $query = "\n                UPDATE {$tablaLotes} SET Vigente='0'\n                WHERE IDLote not in (\n                    SELECT IDLote\n                    FROM {$tablaExistencias} e\n                    WHERE (\n                        IDLote>0 AND\n                        (\n                            Reales>0 OR\n                            Reservadas>0 OR\n                            Entrando>0\n                        )\n                    )\n                    GROUP BY IDLote\n                    ORDER BY IDLote\n                );";
             $em->query($query);
             $em->desConecta();
         }
         unset($lote);
         return $this->indexAction();
     } else {
         return array('template' => '_global/forbiden.html.twig');
     }
 }
 /**
  * Asigno permiso al usuario-proyecto-app
  * 
  * Y además creo el usuario en el cpanel del proyecto.
  * 
  * @return boolean
  */
 public function create()
 {
     $id = parent::create();
     if ($id) {
         // Para saber el perfil que tiene el usuario con la empresa.
         $usuario = new PcaeUsuarios($this->IdUsuario);
         $perfil = $usuario->getPerfilEmpresa($this->IdEmpresa);
         $idPerfil = $perfil->getId();
         unset($usuario);
         unset($perfil);
         $proyectoApp = new PcaeProyectosApps();
         $filtro = "IdProyecto='{$this->IdProyecto}' AND IdApp='{$this->IdApp}'";
         $rows = $proyectoApp->cargaCondicion("*", $filtro);
         unset($proyectoApp);
         $row = $rows[0];
         if ($row['Id']) {
             $connection = array('dbEngine' => $row['DbEngine'], 'host' => $row['Host'], 'user' => $row['User'], 'password' => $row['Password'], 'dataBase' => $row['Database']);
             $em = new EntityManager($connection);
             if ($em->getDbLink()) {
                 $query = "select Id from {$connection['dataBase']}.CpanUsuarios where IdUsuario='{$this->IdUsuario}'";
                 $em->query($query);
                 $rows = $em->fetchResult();
                 $id = $rows[0]['Id'];
                 if ($id) {
                     $query = "update {$connection['dataBase']}.CpanUsuarios set IdPerfil='{$idPerfil}' where Id='{$id}'";
                     $em->query($query);
                 } else {
                     $query = "insert into {$connection['dataBase']}.CpanUsuarios (IdUsuario,IdPerfil,IdRol,IdTipoUsuario) values ('{$this->IdUsuario}','{$idPerfil}','1','1');";
                     $em->query($query);
                     $lastId = $em->getInsertId();
                     $query = "update {$connection['dataBase']}.CpanUsuarios set SortOrder='{$lastId}', PrimaryKeyMD5='" . md5($lastId) . "' WHERE Id='{$lastId}'";
                     $em->query($query);
                 }
                 $em->desConecta();
             }
             unset($em);
         }
     }
     return $id;
 }
 public function validaLogico()
 {
     parent::validaLogico();
     if (count($this->_errores) == 0) {
         if ($this->BlogOrden == 0) {
             $this->BlogOrden = $this->SortOrder;
         }
         if ($this->NoticiaOrden == 0) {
             $this->NoticiaOrden = $this->SortOrder;
         }
         // Si no es evento, borrar los posibles eventos asociados
         if ($this->Id and !$this->EsEvento) {
             $em = new EntityManager($this->getConectionName());
             if ($em->getDbLink()) {
                 $query = "delete from EvenEventos where Entidad='GconContenidos' and IdEntidad='{$this->Id}'";
                 $em->query($query);
                 $em->desConecta();
             }
             unset($em);
         }
     }
 }
 /**
  * Genera una listado por pantalla en base al filtro.
  * Puede recibir un filtro adicional
  *
  * @param string $aditionalFilter
  * @return array con el template y valores a renderizar
  */
 public function listAction($aditionalFilter = '')
 {
     $clientes = new Clientes();
     $recibos = new RecibosClientes();
     $idComercial = $this->request['filter']['valuesSelected']['5'];
     if ($this->values['permisos']['permisosModulo']['CO']) {
         if ($idComercial) {
             $this->listado->makeQuery($aditionalFilter);
             $this->listado->arrayQuery['FROM'] = str_replace(", {$clientes->getDataBaseName()}.{$clientes->getTableName()}", "", $this->listado->arrayQuery['FROM']);
             $this->listado->arrayQuery['FROM'] .= ", {$clientes->getDataBaseName()}.{$clientes->getTableName()}";
             $this->listado->arrayQuery['WHERE'] .= " AND {$recibos->getDataBaseName()}.{$recibos->getTableName()}.IDCliente={$clientes->getDataBaseName()}.{$clientes->getTableName()}.IDCliente ";
             $this->listado->arrayQuery['WHERE'] .= "AND {$clientes->getDataBaseName()}.{$clientes->getTableName()}.IDComercial='{$idComercial}'";
             $this->listado->buildQuery();
         }
         $this->values['listado'] = $this->listado->getAll($aditionalFilter);
         $this->values['filtroRemesa'] = $this->values['listado']['filter']['valuesSelected'][11];
         // Obtener total recibos y total a remesar
         $em = new EntityManager($recibos->getConectionName());
         if ($em->getDbLink()) {
             $query = "select sum(Importe) as Importe from {$this->listado->arrayQuery['FROM']} where {$this->listado->arrayQuery['WHERE']}";
             $em->query($query);
             $total = $em->fetchResult();
             $query1 = "select sum(Importe) as Importe from {$this->listado->arrayQuery['FROM']} where {$this->listado->arrayQuery['WHERE']} and Remesar='1'";
             $em->query($query1);
             $remesa = $em->fetchResult();
             $em->desConecta();
         }
         unset($em);
         $this->values['listado']['importeRecibos'] = $total[0]['Importe'];
         $this->values['listado']['importeRemesa'] = $remesa[0]['Importe'];
         $template = $this->entity . '/list.html.twig';
     } else {
         $template = "_global/forbiden.html.twig";
     }
     unset($clientes);
     unset($recibos);
     return array('template' => $template, 'values' => $this->values);
 }
Exemple #14
0
 public function getGrafico()
 {
     $em = new EntityManager($_SESSION['project']['conection']);
     $em->query($this->query);
     $rows = $em->fetchResult();
     $nRegistros = $em->numRows();
     $em->desConecta();
     unset($em);
     foreach ($rows as $value) {
         $this->datosY[] = $value[$this->columnaY];
         $this->titulosX[] = $value[$this->columnaX];
     }
     $grafico = new Graph($this->ancho, $this->alto);
     $grafico->SetScale('textlin');
     // Ajustamos los margenes del grafico-----    (left,right,top,bottom)
     $grafico->SetMargin(40, 30, 30, 40);
     // Creamos barras de datos a partir del array de datos
     $bplot = new BarPlot($this->datosY);
     // Configuramos color de las barras
     $bplot->SetFillColor('#479CC9');
     //Añadimos barra de datos al grafico
     $grafico->Add($bplot);
     // Queremos mostrar el valor numerico de la barra
     $bplot->value->Show();
     // Configuracion de los titulos
     $grafico->title->Set($this->titulo);
     $grafico->xaxis->title->Set($this->tituloX);
     $grafico->yaxis->title->Set($this->tituloY);
     $grafico->title->SetFont(FF_FONT1, FS_BOLD);
     $grafico->yaxis->title->SetFont(FF_FONT1, FS_BOLD);
     $grafico->xaxis->title->SetFont(FF_FONT1, FS_BOLD);
     $grafico->xaxis->SetTickLabels($this->titulosX);
     // Se generada el archivo con el gráfico
     $archivo = "docs/docs" . $_SESSION['emp'] . "/tmp/" . md5(date('d-m-Y H:i:s')) . ".png";
     $grafico->Stroke($archivo);
     return $archivo;
 }
 /**
  * Reordenada los elmentos
  * @return type
  */
 public function ReordenarAction()
 {
     $relaciones = new CpanRelaciones();
     $dbName = $relaciones->getDataBaseName();
     $tableName = $relaciones->getTableName();
     $filtro = "EntidadOrigen='{$this->entity}' and IdEntidadOrigen='{$this->request[$this->entity]['Id']}'";
     $em = new EntityManager($relaciones->getConectionName());
     if ($em->getDbLink()) {
         // Recorro los elementos que vienen en el acordeon, y los reordeno
         $orden = 0;
         foreach ($this->request['acordeon'] as $id => $elemento) {
             $query = "UPDATE {$dbName}.{$tableName} SET SortOrder = '{$orden}' WHERE ({$filtro}) AND (IdEntidadDestino = '{$id}')";
             $em->query($query);
             $orden += 1;
         }
         $em->desConecta();
     }
     unset($em);
     $this->request['METHOD'] = 'GET';
     $boletin = new BolBoletines($this->request[$this->entity]['Id']);
     $this->request[2] = $boletin->getPrimaryKeyMD5();
     unset($boletin);
     return $this->EditAction();
 }
Exemple #16
0
 /**
  * Devuelve los mvtos de almacén del artículo en curso para
  * el almacen y el periodo de fechas indicado.
  * 
  * Los movimientos se ordenan por almacén y descendentemente por fecha y hora
  * 
  * @param integer $idAlmacen Por defecto todos los almacenes
  * @param date $desdeFecha Por defecto todas
  * @param date $hastaFecha Por defecto todas
  * @return array
  */
 public function getMvtosAlmacen($idAlmacen = 0, $desdeFecha = '', $hastaFecha = '')
 {
     $array = array();
     $filtro = "(mv.IDArticulo='{$this->IDArticulo}')";
     $filtro .= $idAlmacen <= 0 ? " and (1)" : " and (mv.IDAlmacen='{$idAlmacen}')";
     $filtro .= $desdeFecha == '' ? " and (1)" : " and (mv.Fecha>='{$desdeFecha}')";
     $filtro .= $hastaFecha == '' ? " and (1)" : " and (mv.Fecha<='{$hastaFecha}')";
     $mvtosAlmacen = new MvtosAlmacen();
     $tablaMvtos = $mvtosAlmacen->getDataBaseName() . "." . $mvtosAlmacen->getTableName();
     $almacenes = new Almacenes();
     $tablaAlmacenes = $almacenes->getDataBaseName() . "." . $almacenes->getTableName();
     $tipos = new TiposMvtosAlmacen();
     $tablaTipos = $tipos->getDataBaseName() . "." . $tipos->getTableName();
     $em = new EntityManager($this->getConectionName());
     if ($em->getDbLink()) {
         $query = "select\n                        al.Nombre as Almacen,\n                        ti.Descripcion,\n                        ti.Signo,\n                        ti.TipoDocumento,\n                        mv.Fecha,\n                        mv.Hora,\n                        mv.IDUbicacion,\n                        mv.IDLote,\n                        mv.IDDocumento,\n                        mv.UnidadesE,\n                        mv.UnidadesS\n                      from\n                        {$tablaMvtos} as mv\n                        left join {$tablaAlmacenes} as al on mv.IDAlmacen=al.IDAlmacen                        \n                        left join {$tablaTipos} as ti on mv.IDTipo=ti.Id                        \n                      where {$filtro}\n                      order by mv.IDAlmacen,mv.Fecha DESC,mv.Hora DESC";
         $em->query($query);
         $array = $em->fetchResult();
         $em->desConecta();
     }
     unset($em);
     return $array;
 }
 /**
  * Devuelve un array con los agentes que son CAMARISTAS (ROL=3)
  * y están adscritos a la empresa y sucursal indicada.
  * Si el agente en curso es camarista, solo se mostrará el mismo.
  *
  * @param integer $idEmpresa Opcional
  * @param integer $idSucursal Opcional
  * @return array
  */
 public function getCamaristas($idEmpresa = '', $idSucursal = '')
 {
     $usuario = new Agentes($_SESSION['usuarioPortal']['Id']);
     switch ($usuario->getRol()->getIDTipo()) {
         case '3':
             // ROLL CAMARISTA
             $camaristas[] = array('Id' => $usuario->getIDAgente(), 'Value' => $usuario->getNombre());
             break;
         default:
             // RESTO DE ROLES
             if ($idEmpresa == '') {
                 $idEmpresa = $_SESSION['emp'];
             }
             if ($idSucursal == '') {
                 $idSucursal = $_SESSION['suc'];
             }
             $em = new EntityManager("empresas");
             $link = $em->getDbLink();
             if (is_resource($link)) {
                 $query = "select IDAgente as Id, Nombre as Value from agentes where " . "(Rol='3') AND " . "(Activo='1') AND ( " . "(IDEmpresa='" . $idEmpresa . "' and IDSucursal='" . $idSucursal . "') OR " . "isnull(IDEmpresa) OR " . "(IDEmpresa='" . $idEmpresa . "' AND isnull(IDSucursal)) ) ORDER BY Nombre";
                 $em->query($query);
                 $camaristas = $em->fetchResult();
                 $em->desConecta();
             }
             unset($em);
             break;
     }
     unset($usuario);
     return $camaristas;
 }
 /**
  * Genera un archivo pdf con el listado
  * @param array $parametros Array con los parámetros de configuración del listado
  * @param string $aditionalFilter
  * @return string $archivo El nombre completo (con la ruta) del archivo pdf generado
  */
 public function getPdf($parametros, $aditionalFilter = '')
 {
     set_time_limit(0);
     // Orientación de página, unidad de medida y tipo de papel
     $orientation = strtoupper(trim($parametros['orientation']));
     if ($orientation != 'P' and $orientation != 'L') {
         $orientation = 'P';
     }
     $unit = strtolower(trim($parametros['unit']));
     if ($unit != 'pt' and $unit != 'mm' and $unit != 'cm' and $unit != 'in') {
         $unit = 'mm';
     }
     $format = strtolower(trim($parametros['format']));
     if ($format != 'a4' and $format != 'a3' and $format != 'a5' and $format != 'letter' and $format != 'legal') {
         $format = 'A4';
     }
     // Márgenes: top,right,bottom,left
     $margenes = explode(',', trim($parametros['margins']));
     if (count($margenes) != 4) {
         $margenes = array('10', '10', '15', '10');
     }
     // Tipo y tamaño de letra para el cuerpo del listado
     $bodyFont = explode(',', trim($parametros['body_font']));
     if (count($bodyFont) != 3) {
         $bodyFont = array('Courier', '', '8');
     } else {
         $bodyFont[0] = trim($bodyFont[0]);
         $bodyFont[1] = trim($bodyFont[1]);
         $bodyFont[2] = trim($bodyFont[2]);
     }
     // Altura de la línea. Por defecto 4 mm.
     $lineHeight = trim($parametros['line_height']);
     if ($lineHeight <= 0) {
         $lineHeight = 4;
     }
     // Construir la leyenda del filtro
     $leyendaFiltro = array();
     if (is_array($this->filter['columnsSelected'])) {
         foreach ($this->filter['columnsSelected'] as $key => $column) {
             if ($this->filter['valuesSelected'][$key] != '') {
                 $entidad = $this->circulares[$this->idCircular]['filters'][$key]['entity'];
                 if ($entidad) {
                     $aux = explode(",", $entidad);
                     $entidad = $aux[0];
                     $idEntidad = $this->filter['valuesSelected'][$key];
                     $objeto = new $entidad($idEntidad);
                     $valor = $objeto->__toString();
                 } else {
                     $valor = $this->filter['valuesSelected'][$key];
                 }
                 $leyendaFiltro[] = array('Column' => $parametros['filters'][$key]['caption'], 'Value' => $valor);
             }
         }
     }
     // CREAR EL DOCUMENTO
     $pdf = new ListadoPDF($orientation, $unit, $format, array('title' => $parametros['title'], 'titleFont' => $bodyFont, 'columns' => $parametros['columns'], 'leyendaFiltro' => $leyendaFiltro));
     $pdf->SetTopMargin($margenes[0]);
     $pdf->SetRightMargin($margenes[1]);
     $pdf->SetLeftMargin($margenes[3]);
     $pdf->SetAuthor("Informatica ALBATRONIC, SL");
     $pdf->SetTitle($parametros['title']);
     $pdf->AliasNbPages();
     $pdf->SetFillColor(210);
     $pdf->AddPage();
     $pdf->SetAutoPageBreak(true, $margenes[2]);
     // CUERPO
     $pdf->SetFont($bodyFont[0], $bodyFont[1], $bodyFont[2]);
     $em = new EntityManager($_SESSION['project']['conection']);
     $em->query($this->query);
     $rows = $em->fetchResult();
     $nRegistros = $em->numRows();
     $em->desConecta();
     unset($em);
     $breakPage = strtoupper(trim((string) $parametros['break_page'])) == 'YES';
     // ----------------------------------------------
     // Cargo la configuración de la línea del listado
     // En el array $columnasMulticell guardo el nombre de los
     // campos que se imprimirán en Multicell y su anchura en la unidad de medida
     // establecida para calcular la altura máxima y controlar el salto de página
     // ----------------------------------------------
     $configLinea = array();
     $columnsMulticell = array();
     $caracteresLinea = 0;
     foreach ($parametros['columns'] as $key => $value) {
         $caracteres = (int) $value['length'];
         $anchoColumna = $pdf->getStringWidth(str_pad(" ", $caracteres)) + 1;
         //Le sumo 1 para que haya 1 mm de separación entre cada columna
         $caracteresLinea += $caracteres;
         $tipo = trim((string) $value['type']);
         $align = strtoupper(trim((string) $value['align']));
         if ($align != 'R' and $align != 'C' and $align != 'L' and $align != 'J') {
             $align = "L";
         }
         $formato = trim((string) $value['format']);
         $total = strtoupper(trim((string) $value['total'])) == 'YES';
         $configLinea[$value['field']] = array('field' => $value['field'], 'caracteres' => $caracteres, 'ancho' => $anchoColumna, 'align' => $align, 'formato' => $formato, 'type' => $tipo, 'total' => $total);
         if ($tipo == "text") {
             $columnsMulticell[] = array('field' => $value['field'], 'width' => $anchoColumna);
         }
     }
     // -----------------
     $valorAnterior = array();
     $subtotalRegistros = 0;
     // Itero el array con los datos para generar cada renglón del listado
     $totales = array();
     $subTotales = array();
     foreach ($rows as $row) {
         $subtotalRegistros++;
         // Control (si se ha definido) del(los) campo(s) de ruptura
         if (count($this->breakFields)) {
             // Recorro en orden inverso el array de campos de ruptura para
             // comprobar si ha cambiado el valor actual respecto al anterior.
             for ($i = 0; $i < count($this->breakFields); $i++) {
                 //for ($i = count($breakField)-1; $i >= 0 ; $i--) {
                 $columnaRuptura = $this->breakFields[$i];
                 $valorActual[$columnaRuptura] = $row[$columnaRuptura];
                 if ($valorAnterior[$columnaRuptura] != $valorActual[$columnaRuptura]) {
                     if ($valorAnterior[$columnaRuptura] != '') {
                         $this->pintaTotales($pdf, $parametros['columns'], $subTotales);
                         $subTotales = array();
                         // Pinta el subtotal de registos
                         if ($parametros['print_total_records']) {
                             $pdf->Cell(0, 4, 'Subtotal Registos ' . $subtotalRegistros, 0, 1);
                             $subtotalRegistros = 0;
                         }
                         // Cambio de página si procede
                         if ($breakPage) {
                             $pdf->AddPage();
                         }
                     }
                     // Pinto el valor del campo de ruptura
                     $pdf->SetFont($bodyFont[0], 'B', $bodyFont[2]);
                     $pdf->Cell(0, 10, $valorActual[$columnaRuptura]);
                     $pdf->Ln();
                     $pdf->SetFont($bodyFont[0], $bodyFont[1], $bodyFont[2]);
                 }
                 $valorAnterior[$columnaRuptura] = $valorActual[$columnaRuptura];
             }
         }
         $pdf->CheckLinePageBreak($lineHeight, $row, $columnsMulticell);
         // Coordenadas X e Y del renglón
         $x0 = $pdf->GetX();
         $y0 = $pdf->GetY();
         // Para controlar el desplazamiento vertical de los multicell
         $y1 = 0;
         // Recorro las columnas que componen cada renglón
         foreach ($configLinea as $value) {
             $texto = trim($row[$value['field']]);
             if ($value['formato']) {
                 if ($value['type'] == 'money') {
                     $texto = money_format($value['formato'], $texto);
                 } else {
                     $texto = sprintf($value['formato'], $texto);
                 }
             }
             if ($value['type'] == 'text') {
                 // Pinto un multicell sin recortar el texto
                 $x = $pdf->GetX() + $value['ancho'];
                 $pdf->MultiCell($value['ancho'], $lineHeight, $texto, 0, $value['align']);
                 if ($pdf->GetY() > $y1) {
                     $y1 = $pdf->GetY();
                 }
                 $pdf->SetXY($x, $y0);
             } else {
                 // Pinto una celda normal
                 $pdf->Cell($value['ancho'], $lineHeight, $pdf->DecodificaTexto($texto, $value['caracteres']), 0, 0, $value['align']);
             }
             // Calcular Eventuales totales y subtotales de cada columna
             if ($value['total']) {
                 $totales[(string) $value['field']] += (double) trim($row[$value['field']]);
                 $subTotales[(string) $value['field']] += (double) trim($row[$value['field']]);
             }
         }
         // Si ha habido algun multicell, cambio la coordenada Y
         // al desplazamiento vertical mayor producido ($y1)
         if ($y1 != 0) {
             $pdf->SetXY($margenes[3], $y1);
         } else {
             $pdf->Ln();
         }
         // Si se ha definido interlinea, se imprime a todo lo ancho
         if ($parametros['print_interline']) {
             $pdf->Cell(0, $lineHeight, str_repeat($parametros['print_interline'], $caracteresLinea + 5), 0, 1);
         }
     }
     unset($objeto);
     // Pintar los subtotales y totales si hay
     if (count($totales)) {
         if (count($this->breakFields)) {
             $this->pintaTotales($pdf, $parametros['columns'], $subTotales);
         }
         $pdf->Ln();
         $this->pintaTotales($pdf, $parametros['columns'], $totales);
     } elseif (count($this->breakFields)) {
         // Pinta el subtotal de registos
         $pdf->Cell(0, 4, 'Subtotal Registos ' . $subtotalRegistros, 0, 1);
     }
     if ($parametros['print_total_records']) {
         if (count($this->breakFields)) {
             // Pinta el subtotal de registos
             //$subtotalRegistros++;
             $pdf->Cell(0, 4, 'Subtotal Registos ' . $subtotalRegistros, 0, 1);
         }
         // Total de registros impresos
         $pdf->Ln();
         $pdf->SetFont('Arial', 'B', '8');
         $pdf->Cell(0, 4, "Total Registros: " . $nRegistros);
     }
     // Pintar el gráfico
     if (is_array($parametros['grafico'])) {
         $this->pintaGrafico($pdf, $query, $parametros);
     }
     // Leyenda a pie de la última página
     if ($parametros['comment']) {
         $pdf->SetY(-25);
         $pdf->Write(4, $parametros['comment']);
     }
     $fichero = Archivo::getTemporalFileName();
     if ($fichero) {
         $pdf->Output($fichero, 'F');
     }
     unset($objeto);
     unset($pdf);
     return $fichero;
 }
 /**
  * Devuelve un array de objetos articulos que cumplen la
  * regla $idRegla, ordenados por SortOrder ASC
  * 
  * El array tendrá $nItems elementos.
  * 
  * @param int $idRegla El id de la regla
  * @param int $nItems El número máximo de elementos a devolver. Opcional, por defecto todos.
  * @return \Articulos array de objetos Articulos
  */
 public function getArticulos($idRegla, $nItems = 999999)
 {
     $array = array();
     if ($nItems <= 0) {
         $nItems = 999999;
     }
     $em = new EntityManager($this->getConectionName());
     if ($em->getDbLink()) {
         // Condición de vigencia
         $ahora = date("Y-m-d H:i:s");
         $filtro = "(a.Deleted='0') AND (a.Publish='1') AND (a.ActiveFrom<='{$ahora}') AND ( (a.ActiveTo>='{$ahora}') or (a.ActiveTo='0000-00-00 00:00:00') )";
         $query = "\n                SELECT a.IDArticulo as Id\n                FROM {$em->getDataBase()}.ErpOrdenesArticulos r, {$em->getDataBase()}.ErpArticulos a\n                WHERE r.IDRegla='{$idRegla}' AND r.IDArticulo=a.IDArticulo AND a.Vigente='1' AND {$filtro}\n                ORDER BY r.SortOrder ASC\n                LIMIT {$nItems}";
         $em->query($query);
         $rows = $em->fetchResult();
         $em->desConecta();
     }
     unset($em);
     if (is_array($rows)) {
         foreach ($rows as $row) {
             $array[$row['Id']] = new Articulos($row['Id']);
         }
     }
     return $array;
 }
Exemple #20
0
 /**
  * Rellena el array con las opciones y las subopciones
  * según el perfil indicado
  */
 private function creaArray()
 {
     $em = new EntityManager($_SESSION['project']['conection']);
     $dblink = $em->getDbLink();
     if (is_resource($dblink)) {
         $query = "select DISTINCT t1.IDOpcion,t2.Script,t2.Titulo from ErpPermisos as t1, ErpMenu as t2 where (t1.IDPerfil='" . $this->idPerfil . "' and t1.IDOpcion=t2.IDOpcion) order by t2.Orden";
         $em->query($query);
         $rows = $em->fetchResult();
         foreach ($rows as $row) {
             $query = "select t2.* from ErpPermisos as t1,ErpSubmenu as t2 where (t1.IDPerfil='" . $this->idPerfil . "' and t1.IDOpcion='" . $row['IDOpcion'] . "' and t1.IDSubopcion<>0 and t1.IDOpcion=t2.IDOpcion and t1.IDSubopcion=t2.Id) order by t2.Orden;";
             $em->query($query);
             $rows1 = $em->fetchResult();
             foreach ($rows1 as $row1) {
                 $titulo = $row['Titulo'];
                 $subtitulo = $row1['Titulo'];
                 $this->arrayMenu[$titulo][] = array('titulo' => $subtitulo, 'route' => $row1['Script'], 'emergente' => $row1['Emergente']);
             }
         }
         $em->desConecta();
     } else {
         echo $em->getError();
     }
     unset($em);
 }
 public function cambiarOrdenAction()
 {
     $nuevoOrden = explode(",", $this->request['nuevoOrden']);
     $objeto = $this->request['CpanDocs'];
     // Recorro los elementos que vienen en el acordeon, y los reordeno
     $orden = 0;
     $doc = new CpanDocs();
     $em = new EntityManager($doc->getConectionName());
     if ($em->getDbLink()) {
         foreach ($nuevoOrden as $idDoc) {
             $query = "update {$doc->getDataBaseName()}.{$doc->getTableName()} set SortOrder='{$orden}' where Id='{$idDoc}'";
             $em->query($query);
             $orden += 1;
         }
         $em->desConecta();
     }
     unset($em);
     unset($doc);
     return $this->listPopupAction($objeto['Entity'], $objeto['IdEntity'], $objeto['Type']);
 }
 /**
  * Devuelve un array con las TRES primeras agencias que tienen tarifa
  * para la zona y cantidad de kilos indicados.
  *
  * El orden es ascendente respecto a los kilos y el importe
  *
  * La estructura del array es
  *
  *      Id => El id de la agencia
  *      Value => El nombre de la agencia
  *      Kilos => Cantidad de kilos
  *      Importe => Precio para esos kilos
  *
  * @param integer $idZona
  * @param integer $kilos
  * @return array
  */
 public function getAgenciasZona($idZona, $kilos = '0')
 {
     $rows = array();
     $agencias = new Agencias();
     $tablaAgencias = $agencias->getTableName();
     unset($agencias);
     $em = new EntityManager($_SESSION['project']['conection']);
     if ($em->getDbLink()) {
         $query = "\n                SELECT tp.IDAgencia as Id,ag.Agencia as Value,tp.Kilos as Kilos,tp.Importe as Importe\n                FROM\n                    {$this->getDataBaseName()}.{$this->getTableName()} as tp, \n                    {$this->getDataBaseName()}.{$tablaAgencias} as ag\n                WHERE\n                  tp.IDZona='{$idZona}' AND\n                  tp.IDAgencia=ag.IDAgencia AND\n                  tp.Kilos>='{$kilos}'\n                ORDER BY tp.Kilos,tp.Importe ASC\n                LIMIT 3\n                ";
         $em->query($query);
         $rows = $em->fetchResult();
         $em->desConecta();
     }
     return $rows;
 }
 /**
  * Recalcula los importes de la factura en base a sus lineas
  * Se utiliza durante el proceso de facturacion agrupada
  */
 public function recalcula()
 {
     //Si el cliente no está sujeto a iva
     //pongo el iva a cero en las líneas para evitar que por cambio
     //de cliente se aplique indebidamente
     $cliente = new Clientes($this->IDCliente);
     if ($cliente->getIva()->getIDTipo() == '0') {
         $lineas = new FemitidasLineas();
         $lineas->queryUpdate(array("Iva" => 0, "Recargo" => 0), "`IDFactura`= '{$this->IDFactura}'");
         unset($lineas);
     } elseif ($cliente->getRecargoEqu()->getIDTipo() == '0') {
         $lineas = new FemitidasLineas();
         $lineas->queryUpdate(array("Recargo" => 0), "`IDFactura`= '{$this->IDFactura}'");
         unset($lineas);
     }
     unset($cliente);
     //SI TIENE DESCUENTO, CALCULO EL PORCENTAJE QUE SUPONE RESPECTO AL IMPORTE BRUTO
     //PARA REPERCUTUIRLO PORCENTUALMENTE A CADA BASE
     $pordcto = 0;
     if ($this->getDescuento() != 0) {
         $pordcto = round(100 * ($this->getDescuento() / $this->getImporte()), 2);
     }
     //Calcular los totales, desglosados por tipo de iva.
     $this->conecta();
     if (is_resource($this->_dbLink)) {
         $lineas = new FemitidasLineas();
         $tableLineas = "{$lineas->getDataBaseName()}.{$lineas->getTableName()}";
         $articulos = new Articulos();
         $tableArticulos = "{$articulos->getDataBaseName()}.{$articulos->getTableName()}";
         unset($lineas);
         unset($articulos);
         $query = "select sum(Importe) as Bruto,sum(ImporteCosto) as Costo from {$tableLineas} where (IDFactura='" . $this->getIDFactura() . "')";
         $this->_em->query($query);
         $rows = $this->_em->fetchResult();
         $bruto = $rows[0]['Bruto'];
         $query = "select Iva,Recargo, sum(Importe) as Importe from {$tableLineas} where (IDFactura='" . $this->getIDFactura() . "') group by Iva,Recargo order by Iva";
         $this->_em->query($query);
         $rows = $this->_em->fetchResult();
         $totbases = 0;
         $totiva = 0;
         $totrec = 0;
         $bases = array();
         foreach ($rows as $key => $row) {
             $importe = $row['Importe'] * (1 - $pordcto / 100);
             $cuotaiva = round($importe * $row['Iva'] / 100, 2);
             $cuotarecargo = round($importe * $row['Recargo'] / 100, 2);
             $totbases += $importe;
             $totiva += $cuotaiva;
             $totrec += $cuotarecargo;
             $bases[$key] = array('b' => $importe, 'i' => $row['Iva'], 'ci' => $cuotaiva, 'r' => $row['Recargo'], 'cr' => $cuotarecargo);
         }
         $subtotal = $totbases + $totiva + $totrec;
         // Calcular el recargo financiero según la forma de pago
         $formaPago = new FormasPago($this->IDFP);
         $recFinanciero = $formaPago->getRecargoFinanciero();
         $cuotaRecFinanciero = $subtotal * $recFinanciero / 100;
         unset($formaPago);
         $total = $subtotal + $cuotaRecFinanciero;
         //Calcular el peso, volumen y n. de bultos de los productos inventariables
         switch ($_SESSION['ver']) {
             case '1':
                 //Cristal
                 $columna = "MtsAl";
             case '0':
                 //Estandar
             //Estandar
             default:
                 $columna = "Unidades";
         }
         $em = new EntityManager($this->getConectionName());
         $query = "select sum(a.Peso*l.{$columna}) as Peso,\n                        sum(a.Volumen*l.{$columna}) as Volumen,\n                        sum(Unidades) as Bultos \n                      from {$tableArticulos} as a,{$tableLineas} as l\n                      where (l.IDArticulo=a.IDArticulo)\n                        and (a.Inventario='1')\n                        and (l.IDFactura='{$this->IDFactura}')";
         $em->query($query);
         $rows = $em->fetchResult();
         $em->desConecta();
         $this->setImporte($bruto);
         $this->setBaseImponible1($bases[0]['b']);
         $this->setIva1($bases[0]['i']);
         $this->setCuotaIva1($bases[0]['ci']);
         $this->setRecargo1($bases[0]['r']);
         $this->setCuotaRecargo1($bases[0]['cr']);
         $this->setBaseImponible2($bases[1]['b']);
         $this->setIva2($bases[1]['i']);
         $this->setCuotaIva2($bases[1]['ci']);
         $this->setRecargo2($bases[1]['r']);
         $this->setCuotaRecargo2($bases[1]['cr']);
         $this->setBaseImponible3($bases[2]['b']);
         $this->setIva3($bases[2]['i']);
         $this->setCuotaIva3($bases[2]['ci']);
         $this->setRecargo3($bases[2]['r']);
         $this->setCuotaRecargo3($bases[2]['cr']);
         $this->setTotalBases($totbases);
         $this->setTotalIva($totiva);
         $this->setTotalRecargo($totrec);
         $this->setRecargoFinanciero($recFinanciero);
         $this->setCuotaRecargoFinanciero($cuotaRecFinanciero);
         $this->setTotal($total);
         $this->setPeso($rows[0]['Peso']);
         $this->setVolumen($rows[0]['Volumen']);
         $this->setBultos($rows[0]['Bultos']);
         $this->save();
     }
 }
Exemple #24
0
 /**
  * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  * OJO!!! ESTE METODO NO SE USA EN PRINCIPIO. HAY QUE REVISAR EL QUERY
  * YA QUE SE USAN TABLAS DE DIFERENTES BASES DE DATOS Y PARACE QUE NO ESTA BIEN
  * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  *
  * Devuelve un array con las ubicaciones disponibles en el almacén
  * Se entiende por ubicacion libre aquella que no tiene existencias
  * El array es del tipo array('Id' => , 'Value' => )
  * @return array Con las ubicaciones libres
  */
 public function getUbicacionesLibres()
 {
     $huecos = array();
     // LLamo al procedimiento almacenado 'UbicacionesLibres'
     $em = new EntityManager($this->getConectionName());
     if ($em->getDbLink()) {
         //$query = "Call UbicacionesLibres('{$this->IDAlmacen}');";
         $query = "SELECT IDUbicacion as Id, Ubicacion as Value\n                        FROM {$this->_dataBaseName}.ErpAlmacenesMapas\n                        WHERE\n                            IDAlmacen = '{$this->IDAlmacen}' AND\n                            IDUbicacion NOT IN (\n                                SELECT t1.IDUbicacion\n                                FROM ErpExistencias as t1\n                                GROUP BY t1.IDAlmacen, t1.IDUbicacion\n                                HAVING t1.IDAlmacen =  '{$this->IDAlmacen}'\n                                AND SUM( t1.Reales ) > 0\n                            )\n                        ORDER BY Ubicacion";
         $em->query($query);
         $huecos = $em->fetchResult();
         $em->desConecta();
     }
     unset($em);
     return $huecos;
 }
 /**
  * Renderiza el template _Emergente/historicoVentas.html.twig
  * mostrando las ventas realizadas a un cliente de un articulo dado en un periodo.
  *
  * La información se obtiene en base a los albaranes confimardos o facturados.
  * No se tienen en cuenta los albaranes no confirmados.
  *
  * Puede entrar por POST o por GET.
  *
  * Si es por POST los parametros vienen en:
  *
  *  idArticulo, idCliente, periodo, formato
  *
  * Si es por GET los parametros vienen en:
  *
  *  posicion 2 (idArticulo), 3 (idCliente), 4 (periodo), 5 (formato)
  *
  * @return array El template y los datos
  */
 public function HistoricoVentasAction()
 {
     $periodos = array(array('Id' => '0', 'Value' => 'Último Mes'), array('Id' => '1', 'Value' => 'Último Trimestre'), array('Id' => '2', 'Value' => 'Último Año'), array('Id' => '3', 'Value' => 'Todo'));
     switch ($this->request["METHOD"]) {
         case 'GET':
             $idArticulo = $this->request['2'];
             if ($idArticulo == '0') {
                 $idArticulo = '';
             }
             $idCliente = $this->request['3'];
             if ($idCliente == '0') {
                 $idCliente = '';
             }
             $periodo = $this->request['4'];
             $formato = $this->request['5'];
             break;
         case 'POST':
             $idArticulo = $this->request['idArticulo'];
             if ($idArticulo == '0') {
                 $idArticulo = '';
             }
             $idCliente = $this->request['idCliente'];
             if ($idCliente == '0') {
                 $idCliente = '';
             }
             $periodo = $this->request['periodo'];
             $formato = $this->request['formato'];
             break;
     }
     $formato = strtoupper($formato);
     // Construir la parte del filtro que depende del periodo
     switch ($periodo) {
         case '':
             $periodo = 1;
         case '0':
             // Ultimo mes
             $diferenciaDias = -30;
             break;
         case '1':
             // Ultimo Trimestre
             $diferenciaDias = -90;
             break;
         case '2':
             // Ultimo año
             $diferenciaDias = -365;
             break;
         case '3':
             // Todo, 20 años hacia atrás
             $diferenciaDias = -7300;
             break;
     }
     $fecha = new Fecha(date('Y-m-d'));
     $desdeFecha = $fecha->sumaDias($diferenciaDias);
     unset($fecha);
     $cliente = new Clientes($idCliente);
     $clienteTabla = $cliente->getDataBaseName() . "." . $cliente->getTableName();
     $articulo = new Articulos($idArticulo);
     $articuloTabla = $articulo->getDataBaseName() . "." . $articulo->getTableName();
     $pedido = new PedidosCab();
     $pedidoTabla = $pedido->getDataBaseName() . "." . $pedido->getTableName();
     unset($pedido);
     $lineas = new PedidosLineas();
     $lineasTabla = $lineas->getDataBaseName() . "." . $lineas->getTableName();
     unset($lineas);
     // Calcular el total de unidades vendidas y el precio medio de venta
     if ($idArticulo != '' or $idCliente != '') {
         $em = new EntityManager($articulo->getConectionName());
         if ($em->getDbLink()) {
             $query = "SELECT SUM(t1.Unidades) as Unidades, SUM(t1.Importe) as Importe\n                FROM {$lineasTabla} as t1, {$pedidoTabla} as t2";
             $query .= " WHERE t1.IdPedido=t2.Id AND t2.Fecha>='{$desdeFecha}'";
             if ($idCliente !== '') {
                 $query .= " AND  t2.IdCliente='{$idCliente}'";
             }
             if ($idArticulo !== '') {
                 $query .= " AND t1.IdArticulo='{$idArticulo}'";
             }
             $em->query($query);
             //echo $query;
             $rows = $em->fetchResult();
             $em->desConecta();
         }
         $precioMedio = $rows[0]['Unidades'] != 0 ? $rows[0]['Importe'] / $rows[0]['Unidades'] : 0;
         $unidades = $rows[0]['Unidades'] == '' ? 0 : $rows['0']['Unidades'];
     }
     $values['datos'] = array('articulo' => $articulo->iterator(), 'cliente' => $cliente->iterator(), 'unidades' => $unidades, 'periodo' => $periodo, 'periodos' => $periodos, 'precioMedio' => number_format($precioMedio, 3));
     // Obtener el litado histórico de ventas para el articulo y cliente
     $em = new EntityManager($articulo->getConectionName());
     if ($em->getDbLink()) {
         $query = "SELECT t2.Id,t1.Id NumeroPedido,t1.PrimaryKeyMD5,DATE_FORMAT(t1.Fecha,'%d-%m-%Y') as Fecha,t2.Descripcion,t2.Unidades,t2.Precio,t2.Descuento1,t2.Descuento2,t2.Descuento3,t2.Importe\n                FROM {$pedidoTabla} as t1, {$lineasTabla} as t2";
         if ($idCliente !== '') {
             $query .= ", {$clienteTabla} as t3";
         }
         if ($idArticulo !== '') {
             $query .= ", {$articuloTabla} as t4";
         }
         $query .= " WHERE t1.Id=t2.IdPedido";
         if ($idCliente !== '') {
             $query .= " AND t1.IdCliente=t3.Id AND t1.IdCliente='{$idCliente}' ";
         }
         if ($idArticulo !== '') {
             $query .= " AND t2.IdArticulo=t4.Id AND t2.IdArticulo='{$idArticulo}'";
         }
         $query .= "\n                AND t1.Fecha>='{$desdeFecha}'\n                ORDER BY t1.Fecha DESC, t1.Id DESC";
         $em->query($query);
         //echo $query;
         $rows = $em->fetchResult();
         $em->desConecta();
     }
     $values['listado'] = $rows;
     unset($em);
     unset($articulo);
     unset($cliente);
     if (in_array($formato, $this->formats)) {
         $values['status'] = '200';
         $values['statusMessage'] = "";
         switch ($formato) {
             case '':
             case 'JSON':
                 header('Content-type: application/json; charset="UTF-8"', true);
                 $template = "_global/json.twig";
                 $this->values['json'] = $values;
                 break;
             case 'HTML':
                 $this->values = $values;
                 $template = "_Emergente/historicoVentas.html.twig";
                 break;
         }
     } else {
         $this->values['json'] = array('status' => 401, 'statusMessage' => 'Format not implemented', 'result' => array());
         $template = "_global/json.twig";
     }
     return array('template' => $template, 'values' => $this->values);
 }
Exemple #26
0
 /**
  * Devuelve un array con los agentes que son CAMARISTAS (ROL=3)
  * y están adscritos a la empresa y sucursal indicada.
  * Si el agente en curso es camarista, solo se mostrará el mismo.
  *
  * @param integer $idEmpresa Opcional
  * @param integer $idSucursal Opcional
  * @return array
  */
 public function getCamaristas($idEmpresa = '', $idSucursal = '')
 {
     $usuario = new Agentes($_SESSION['usuarioPortal']['Id']);
     switch ($usuario->getIDRol()->getIDTipo()) {
         case '3':
             // ROLL CAMARISTA
             $camaristas[] = array('Id' => $usuario->getIDAgente(), 'Value' => $usuario->getNombre());
             break;
         default:
             // RESTO DE ROLES
             //if ($idEmpresa == '')
             //    $idEmpresa = $_SESSION['emp'];
             if ($idSucursal == '') {
                 $idSucursal = $_SESSION['suc'];
             }
             $em = new EntityManager($this->getConectionName());
             $link = $em->getDbLink();
             if (is_resource($link)) {
                 $query = "select IDAgente as Id, Nombre as Value from {$this->getTableName()} where " . "(a.IDAgente <> 1) AND " . "(Rol='3') AND " . "(Activo='1') AND ( " . "(IDSucursal='{$idSucursal}') OR isnull(IDSucursal))";
                 $em->query($query);
                 $camaristas = $em->fetchResult();
                 $em->desConecta();
             }
             unset($em);
             break;
     }
     unset($usuario);
     return $camaristas;
 }
 /**
  * Crea un registro nuevo
  *
  * Si viene por GET muestra un template vacio
  * Si viene por POST crea un registro
  *
  * @return array con el template y valores a renderizar
  */
 public function newAction()
 {
     if ($this->values['permisos']['permisosModulo']['IN']) {
         switch ($this->request["METHOD"]) {
             case 'GET':
                 //MOSTRAR FORMULARIO VACIO
                 //SI EN LA POSICION 2 DEL REQUEST VIENE ALGO,
                 //SE ENTIENDE QUE ES EL VALOR DE LA CLAVE PARA LINKAR CON LA ENTIDAD PADRE
                 //ESTO SE UTILIZA PARA LOS FORMULARIOS PADRE->HIJO
                 if ($this->request['2'] != '') {
                     $this->values['linkBy']['value'] = $this->request['2'];
                 }
                 $datos = new $this->entity();
                 $datos->setDefaultValues((array) $this->varEnvMod['columns']);
                 $this->values['datos'] = $datos;
                 $this->values['errores'] = array();
                 $template = $this->entity . '/new.html.twig';
                 break;
             case 'POST':
                 //CREAR NUEVO REGISTRO
                 //COGER EL LINK A LA ENTIDAD PADRE
                 if ($this->values['linkBy']['id'] != '') {
                     $this->values['linkBy']['value'] = $this->request[$this->entity][$this->values['linkBy']['id']];
                 }
                 $datos = new $this->entity();
                 $datos->bind($this->request[$this->entity]);
                 $rules = $this->form->getRules();
                 $rules['GLOBALES']['numMaxPages'] = $this->varEnvPro['numMaxPages'];
                 $rules['GLOBALES']['numMaxRecords'] = $this->varEnvMod['numMaxRecords'];
                 if ($datos->valida($rules)) {
                     $em = new EntityManager($datos->getConectionName());
                     if ($em->getDbLink()) {
                         $v = $this->request[$this->entity];
                         $columnas = "`IDAgente`,`IDRol`,`IDPerfil`,`IDSucursal`,`IDAlmacen`,`Activo`,`PrimaryKeyMD5`";
                         $valores = "'{$v['IDAgente']}','{$v['IDRol']}','{$v['IDPerfil']}','{$v['IDSucursal']}','{$v['IDAlmacen']}','{$v['Activo']}','" . md5($v['IDAgente']) . "'";
                         $query = "insert into {$datos->getDataBaseName()}.{$datos->getTableName()} ({$columnas}) VALUES ({$valores})";
                         $em->query($query);
                         $lastId = $em->getInsertId();
                         $em->desConecta();
                     }
                     $lastId = $this->request[$this->entity]['IDAgente'];
                     $this->values['errores'] = $datos->getErrores();
                     $this->values['alertas'] = $datos->getAlertas();
                     //Recargo el objeto para refrescar las propiedades que
                     //hayan podido ser objeto de algun calculo durante el proceso
                     //de guardado y pongo valores por defecto (urlamigable, etc)
                     if ($lastId and $datos->getUrlTarget() == '') {
                         $datos = new $this->entity($lastId);
                         $this->gestionUrlMeta($datos);
                         $this->values['errores'] = $datos->getErrores();
                         $this->values['alertas'] = $datos->getAlertas();
                     }
                     // Si ex buscable, actualizar la tabla de búsquedas
                     if ($lastId and $this->varEnvMod['searchable'] == '1') {
                         $this->ActualizaBusquedas($datos);
                     }
                     $this->values['datos'] = $datos;
                     $template = $this->values['errores'] ? $this->entity . '/edit.html.twig' : $this->entity . '/edit.html.twig';
                 } else {
                     $this->values['datos'] = $datos;
                     $this->values['errores'] = $datos->getErrores();
                     $this->values['alertas'] = $datos->getAlertas();
                     $template = $this->entity . '/new.html.twig';
                 }
                 break;
         }
     } else {
         $template = '_global/forbiden.html.twig';
     }
     return array('template' => $template, 'values' => $this->values);
 }
 /**
  * Proceso de facturacion.
  * Puede ser facturación separada: Una factura por cada albarán
  * o facturación agrupada: Una factura con todos los albaranes, con las siguientes salvedades:
  *
  * Se agrupan las facturas en base a la forma de pago, comercial y al flag "Facturación agrupada"
  * de la ficha del cliente.
  *
  * @return <type>
  */
 public function facturarAction()
 {
     $facturados = array();
     $filtro = $this->request['filtro'];
     $fecha = new Fecha($filtro['desdeFecha']);
     $desdeFecha = $fecha->getaaaammdd();
     $fecha = new Fecha($filtro['hastaFecha']);
     $hastaFecha = $fecha->getaaaammdd();
     unset($fecha);
     switch ($this->request['tipo']) {
         case '0':
             // Facturación individual. Se genera una factura por cada albarán
             $filter = "IDFactura='0' and IDEstado='2' and IDCliente='{$filtro['idCliente']}' and FechaEntrega>='{$desdeFecha}' and FechaEntrega<'{$hastaFecha}' and FlagFacturar='1'";
             $albaran = new AlbaranesCab();
             $rows = $albaran->cargaCondicion("IDAlbaran", $filter, "FechaEntrega ASC");
             foreach ($rows as $row) {
                 $albaran = new AlbaranesCab($row['IDAlbaran']);
                 $idFactura = $albaran->facturar(new Contadores($this->request['idContador']), $this->request['fecha']);
                 if (count($albaran->getErrores()) != 0) {
                     $this->values['errores'] = $albaran->getErrores();
                     break;
                 } else {
                     $facturados[] = $idFactura;
                 }
             }
             unset($albaran);
             break;
         case '1':
             // Agrupada. Se agrupan los albaranes por forma de pago, comercial
             $filter = "c.IDFactura='0' and c.IDEstado='2' and c.IDCliente='{$filtro['idCliente']}' and c.FechaEntrega>='{$desdeFecha}' and c.FechaEntrega<'{$hastaFecha}' and c.FlagFacturar='1'";
             //COMPRUEBO QUE NO HAYA MAS DE TRES TIPOS DE IVA ENTRE TODOS LOS ALBARANES A FACTURAR
             $albaran = new AlbaranesCab();
             $albaranTabla = $albaran->getDataBaseName() . "." . $albaran->getTableName();
             $lineas = new AlbaranesLineas();
             $lineasTabla = $lineas->getDataBaseName() . "." . $lineas->getTableName();
             $em = new EntityManager($albaran->getConectionName());
             if (!$em->getDbLink()) {
                 $this->values['errores'] = $em->getError();
                 return $this->listAction();
             }
             $query = "select l.Iva from {$lineasTabla} as l, {$albaranTabla} as c\n                        where {$filter} and c.IDAlbaran=l.IDAlbaran\n                        group by l.Iva";
             $em->query($query);
             $rows = $em->fetchResult();
             $em->desConecta();
             if (count($rows) > 3) {
                 $this->values['alertas'] = "Hay más de tres tipos de iva distintos. No se puede agrupar";
                 return $this->listAction();
             }
             $contador = new Contadores($this->request['idContador']);
             // Buscar la cuenta contable de ventas para la sucursal
             $sucursal = new Sucursales($filtro['idSucursal']);
             $ctaVentas = $sucursal->getCtaContableVentas();
             unset($sucursal);
             $cliente = new Clientes($filtro['idCliente']);
             $agruparDireccionEntrega = $cliente->getFacturacionAgrupada()->getIDTipo() == '1';
             unset($cliente);
             $query = $agruparDireccionEntrega ? "select c.IDFP,c.IDComercial, sum(c.Importe) as Importe, sum(Descuento) as Descuento from {$albaranTabla} c where {$filter} GROUP BY c.IDFP, c.IDComercial;" : "select c.IDFP,c.IDComercial, c.IDDirec, sum(c.Importe) as Importe, sum(Descuento) as Descuento from {$albaranTabla} c where {$filter} GROUP BY c.IDFP, c.IDComercial, c.IDDirec;";
             unset($cliente);
             //AGRUPO LOS ALBARANES POR FORMA DE PAGO, COMERCIAL Y (si procede) DIRECCION DE ENTREGA.
             $em = new EntityManager($albaran->getConectionName());
             $em->query($query);
             $rows = $em->fetchResult();
             $em->desConecta();
             foreach ($rows as $row) {
                 $numeroFactura = $contador->asignaContador();
                 $factura = new FemitidasCab();
                 $factura->setIDSucursal($filtro['idSucursal']);
                 $factura->setIDContador($this->request['idContador']);
                 $factura->setNumeroFactura($numeroFactura);
                 $factura->setIDAgente($_SESSION['usuarioPortal']['Id']);
                 $factura->setIDComercial($row['IDComercial']);
                 $factura->setFecha($this->request['fecha']);
                 $factura->setIDCliente($filtro['idCliente']);
                 $factura->setCuentaVentas($ctaVentas);
                 $factura->setDescuento($row['Descuento']);
                 $factura->setImporte($row['Importe']);
                 $factura->setIDFP($row['IDFP']);
                 $idFactura = $factura->create();
                 // Guardo en un array los id's de facturas generadas
                 $facturados[] = $idFactura;
                 if ($idFactura != 0) {
                     // Crear las lineas de factura
                     // No incluyo las lineas de albaran cuyas unidades sean 0
                     $em = new EntityManager($albaran->getConectionName());
                     $query = $agruparDireccionEntrega ? "select l.* from {$lineasTabla} l, {$albaranTabla} c where (c.IDAlbaran=l.IDAlbaran) and (c.IDFP='{$row['IDFP']}') and (l.Unidades<>0) and {$filter}" : "select l.* from {$lineasTabla} l, {$albaranTabla} c where (c.IDAlbaran=l.IDAlbaran) and (c.IDFP='{$row['IDFP']}') and (c.IDDirec='{$row['IDDirec']}') and (l.Unidades<>0) and {$filter}";
                     $em->query($query);
                     $lineas = $em->fetchResult();
                     $em->desConecta();
                     foreach ($lineas as $linea) {
                         $linFactura = new FemitidasLineas();
                         $linFactura->setIDFactura($idFactura);
                         $linFactura->setIDArticulo($linea['IDArticulo']);
                         $linFactura->setDescripcion($linea['Descripcion']);
                         $linFactura->setUnidades($linea['Unidades']);
                         $linFactura->setPrecio($linea['Precio']);
                         $linFactura->setDescuento($linea['Descuento']);
                         $linFactura->setImporte($linea['Importe']);
                         $linFactura->setImporteCosto($linea['ImporteCosto']);
                         $linFactura->setIDAlbaran($linea['IDAlbaran']);
                         $linFactura->setIDLineaAlbaran($linea['IDLinea']);
                         $linFactura->setIva($linea['Iva']);
                         $linFactura->setRecargo($linea['Recargo']);
                         $linFactura->setIDVenta($linea['IDVenta']);
                         $linFactura->setComisionAgente($linea['ComisionAgente']);
                         $linFactura->setComisionMontador($linea['ComisionMontador']);
                         $linFactura->setComisionar($linea['Comisionar']);
                         $linFactura->setIDAgente($_SESSION['usuarioPortal']['Id']);
                         $linFactura->setIDComercial($linea['IDComercial']);
                         $linFactura->setIDPromocion($linea['IDPromocion']);
                         $linFactura->setAltoAl($linea['AltoAl']);
                         $linFactura->setAnchoAl($linea['AnchoAl']);
                         $linFactura->setMtsAl($linea['MtsAl']);
                         $linFactura->setAltoFa($linea['AltoFa']);
                         $linFactura->setAnchoFa($linea['AnchoFa']);
                         $linFactura->setMtsFa($linea['MtsFa']);
                         if ($linFactura->create()) {
                             // Pongo el estado de la linea de albaran a "Facturado"
                             $lineaAlbaran = new AlbaranesLineas($linea['IDLinea']);
                             $lineaAlbaran->setIDEstado(3);
                             $lineaAlbaran->save();
                         } else {
                             print_r($linFactura->getErrores());
                         }
                         unset($linFactura);
                     }
                     // Totalizar la factura
                     $factura->recalcula();
                     // Crear vencimientos
                     $factura->creaVctos();
                     // Anotar en caja sin procede
                     $factura->anotaEnCaja();
                     // Actualiza las cabecera del grupo de albaranes
                     $em = new EntityManager($albaran->getConectionName());
                     $query = $agruparDireccionEntrega ? "update {$albaranTabla} c set c.IDFactura='{$idFactura}', c.IDEstado='3' where (c.IDFP='{$row['IDFP']}') and ({$filter})" : "update {$albaranTabla} c set c.IDFactura='{$idFactura}', c.IDEstado='3' where (c.IDFP='{$row['IDFP']}') and (c.IDDirec='{$row['IDDirec']}') and ({$filter})";
                     $em->query($query);
                     $em->desConecta();
                     unset($factura);
                 } else {
                     $this->values['errores'] = $factura->getErrores();
                 }
             }
             break;
     }
     if ($this->request['imprimir'] == 'on' and count($facturados) > 0) {
         $this->values['archivo'] = $this->generaPdf('FemitidasCab', $facturados);
     }
     if (count($facturados) > 0) {
         $this->values['alertas'][] = "Se han generado las siguientes facturas:";
         foreach ($facturados as $item) {
             $this->values['alertas'][] = $item;
         }
     }
     return $this->listAction();
 }
 /**
  * Devuelve un array con los proveedores que tienen pedidos pendientes
  * de facturar (IDEstado=2) en el periodo de fechas indicado y de la
  * sucursal indicada.
  *
  * El array tiene tres columnas:
  *       Id (el id del proveedor),
  *       Value (la razon social del proveedor)
  *       Total (la suma de los totales de todos sus pedidos pendientes de facturar)
  *
  * @param integer $idSucursal
  * @param date $desdeFecha Fecha en formato dd/mm/aaaa
  * @param date $hastaFecha Fecha en formato dd/mm/aaaa
  * @return array Array con los proveedores
  */
 public function fetchConPendienteDeFacturar($idSucursal, $desdeFecha, $hastaFecha)
 {
     $fecha = new Fecha($desdeFecha);
     $desdeFecha = $fecha->getaaaammdd();
     $fecha = new Fecha($hastaFecha);
     $hastaFecha = $fecha->getaaaammdd();
     unset($fecha);
     $this->conecta();
     $rows = array();
     $pedidos = new PedidosCab();
     $em = new EntityManager($pedidos->getConectionName());
     if (is_resource($em->getDbLink())) {
         $filtroSucursal = $idSucursal == '' ? "(1)" : "(a.IDSucursal='{$idSucursal}')";
         $filtro = $filtroSucursal . " and\n                      (a.Fecha>='{$desdeFecha}') and\n                      (a.Fecha<='{$hastaFecha}') and\n                      (a.IDEstado=2) and\n                      (c.IDProveedor=a.IDProveedor)";
         $query = "SELECT distinct c.IDProveedor as Id, c.RazonSocial as Value, sum(a.Total) as Total\n                        FROM \n                            `{$this->_dataBaseName}`.`{$this->_tableName}` c, \n                            `{$pedidos->getDataBaseName()}`.`{$pedidos->getTableName()}` a\n                        WHERE ( {$filtro} )\n                        GROUP BY c.IDProveedor\n                        ORDER BY c.RazonSocial";
         $em->query($query);
         $rows = $em->fetchResult();
         $em->desConecta();
         unset($em);
     }
     return $rows;
 }
Exemple #30
0
 /**
  * Genera un archivo XLSX con el listado
  * @param integer $idFormatoListado
  * @param string $aditionalFilter
  * @return string $archivo El nombre completo (con la ruta) del archivo xlsx generado
  */
 public function getXls($idFormatoListado, $aditionalFilter = '')
 {
     // CARGAR EL MOTOR PARA GENERAR ARCHIVOS EXCELS
     $config = sfYaml::load('config/config.yml');
     $config = $config['config'];
     if (file_exists($config['excel'])) {
         include_once $config['excel'];
     } else {
         die("NO SE PUEDE ENCONTRAR EL MOTOR EXCEL");
     }
     set_time_limit(0);
     // Lee la configuracion del listado $idFormatoListado y
     // la guarda en $parametros
     $formato = new Form($this->entity, 'listados.yml');
     $parametros = $formato->getFormatoListado($idFormatoListado);
     unset($formato);
     // CREAR EL DOCUMENTO
     $objPHPExcel = new PHPExcel();
     $objPHPExcel->getProperties()->setCreator("ERP Albatronic")->setTitle($parametros['title']);
     $objPHPExcel->getDefaultStyle()->getFont()->setName('Arial');
     $objPHPExcel->getDefaultStyle()->getFont()->setSize(14);
     $objPHPExcel->getActiveSheet()->setTitle($parametros['title']);
     $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $parametros['title'])->setCellValue('A3', 'Generado por ' . $_SESSION['usuarioPortal']['Nombre'])->setCellValue('A4', 'Fecha ' . date('d/m/Y H:i:s'));
     // Fila de titulos
     $columna = 'A';
     foreach ($parametros['columns'] as $column) {
         $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columna . '6', $column['title']);
         $columna++;
     }
     // Construyo el array con los datos a listar.
     // Sustituyo el ORDERBY que hay en el filtro por pantalla
     // con el que viene de los parametros del listado
     if ($this->getQuery() == '') {
         $this->filter['orderBy'] = $parametros['order_by'];
         $this->makeQuery($aditionalFilter);
     }
     $em = new EntityManager($this->form->getConection());
     $em->query($this->getQuery());
     $rows = $em->fetchResult();
     $nRegistros = $em->numRows();
     $em->desConecta();
     unset($em);
     $breakField = trim((string) $parametros['break_field']);
     if ($breakField) {
         $breakField = explode(",", $breakField);
     } else {
         $breakField = array();
     }
     $valorAnterior = '';
     // Itero el array con los datos para generar cada renglón del listado
     $totales = array();
     $subTotales = array();
     $fila = 7;
     $objPHPExcel->getDefaultStyle()->getFont()->setSize(10);
     $objeto = new $this->entity();
     foreach ($rows as $row) {
         $columna = 'A';
         $objeto->bind($row);
         // Control (si se ha definido) del campo de ruptura
         if (count($breakField)) {
             // Instancio el objeto por el que se hace el break
             $objetoBreak = $objeto->{"get{$breakField['0']}"}();
             $valorActual = $objetoBreak->__toString();
             if ($valorAnterior != $valorActual) {
                 if ($valorAnterior != '') {
                     $this->pintaTotalesExcel($objPHPExcel, $fila, $parametros['columns'], $subTotales);
                     $fila++;
                     $columna = 'A';
                     $subTotales = array();
                 }
                 // Pinto el valor del campo de ruptura y los eventuales valores
                 // adicionales que se hayan indicado en el nodo xml <break_field>
                 $texto = $valorActual;
                 for ($i = 1; $i < count($breakField); $i++) {
                     $texto .= " " . $objetoBreak->{"get{$breakField[$i]}"}();
                 }
                 $fila++;
                 $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columna . $fila, $texto);
             }
             $valorAnterior = $valorActual;
             unset($objetoBreak);
         }
         // Recorro las columnas que componen cada renglón
         $fila++;
         foreach ($parametros['columns'] as $value) {
             $formato = trim((string) $value['format']);
             $texto = trim($objeto->{"get{$value['field']}"}());
             if ($formato) {
                 $texto = sprintf($formato, $texto);
             }
             $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columna . $fila, $texto);
             // Calcular Eventuales totales y subtotales de cada columna
             if (strtoupper($value['total']) == 'YES') {
                 $totales[(string) $value['field']] += (double) $texto;
                 $subTotales[(string) $value['field']] += (double) $texto;
             }
             $columna++;
         }
     }
     unset($objeto);
     // Pintar los subtotales y totales si hay
     if (count($totales)) {
         if ($breakField) {
             $this->pintaTotalesExcel($objPHPExcel, $fila, $parametros['columns'], $subTotales);
         }
         $fila++;
         $this->pintaTotalesExcel($objPHPExcel, $fila, $parametros['columns'], $totales);
     }
     $objPHPExcel->getActiveSheet()->setTitle($parametros['title']);
     $objPHPExcel->setActiveSheetIndex(0);
     $archivo = "docs/docs" . $_SESSION['emp'] . "/xls/" . md5(date('d-m-Y H:i:s')) . ".xlsx";
     $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
     $objWriter->save($archivo);
     unset($objPHPExcel);
     return $archivo;
 }