/**
  * 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;
 }
 public function getOpciones($de, $nivel)
 {
     $rows = array();
     $em = new EntityManager($this->getConectionName());
     if ($em->getDbLink()) {
         $query = "\n                select m.Id,m.CodigoApp,m.Titulo ,p.NombreModulo, p.Funcionalidades, m.Icon\n                from {$this->getDataBaseName()}.AgtPermisos as p, {$this->getDataBaseName()}.AgtModulos as m\n                where m.NombreModulo = p.NombreModulo and m.BelongsTo='{$de}' and m.Nivel='{$nivel}' and\n                p.IdPerfil = '{$this->getIdPerfil()->getId()}' AND\n                LOCATE('AC',p.Funcionalidades)\n                order by m.Id ASC";
         //echo $query,"<br/>";
         $em->query($query);
         $rows = $em->fetchResult();
     } else {
         echo "NO HAY CONEXION CON LA BASE DE DATOS";
     }
     unset($em);
     return $rows;
 }
Exemple #6
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;
 }
 /**
  * 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);
 }
 /**
  * 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 #15
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;
 }
Exemple #16
0
 /**
  * Devuelve un array con los articulos correspondientes
  * a la familia indicada, o en su defecto a la familia actual.
  *
  * Si se indica $entidadRelacionada e $idEntidadRelacionada, se añade un elmento más que indica
  * si cada articulo está relacionado con $entidadRelacionada e $idEntidadRelacionada
  *
  * El array tiene los siguientes elementos:
  * 
  * - Id: El id del articulo
  * - Value: La descripcion del articulo
  * - Pvp: Precio de venta SIN impuestos
  * - PvpConImpuestos: Precio de venta CON impuestos
  * - PrimaryKeyMD5: la primarykey MD5
  * - Publish: TRUE/FALSE
  * - estaRelacionado: El id de la eventual relacion
  * 
  * @param integer $idFamilia El id de la familia
  * @param array $optArticulos Array de opciones de articulos
  * @param string $idEntidadRelacionada La entidad con la que existe una posible relación
  * @param integer $idEntidadRelacionada El id de entidad con la que existe una posible relación
  * @return array Array Id, Value de articulos
  */
 public function getArticulos($idFamilia = '', $optArticulos = array(), $entidadRelacionada = '', $idEntidadRelacionada = '')
 {
     if ($idFamilia == '') {
         $idFamilia = $this->IDFamilia;
     }
     $articulos = array();
     $em = new EntityManager($_SESSION['project']['conection']);
     if ($em->getDbLink()) {
         $select = "select a.IDArticulo as Id,a.Descripcion as Value,a.Pvp,a.Pvp*(1+i.Iva/100) as PvpConImpuestos,i.Iva,a.PrimaryKeyMD5,a.Publish from ErpArticulos a left join ErpTiposIva i on a.IDIva=i.IDIva";
         $where = "a.IDCategoria='{$idFamilia}' or a.IDFamilia='{$idFamilia}' or a.IDSubfamilia='{$idFamilia}'";
         $articulos = $em->getResult("a", $select, $where);
         if ($entidadRelacionada) {
             foreach ($articulos as $key => $articulo) {
                 $relacion = new CpanRelaciones();
                 $articulos[$key]['estaRelacionado'] = $relacion->getIdRelacion('ErpArticulos', $articulo['Id'], $entidadRelacionada, $idEntidadRelacionada);
             }
             unset($relacion);
         }
         if ($optArticulos['conImagenes']) {
             foreach ($articulos as $key => $item) {
                 $articulo = new Articulos($item['Id']);
                 $objetosImagen = $articulo->getDocuments();
                 if (count($objetosImagen)) {
                     foreach ($objetosImagen as $imagen) {
                         $articulos[$key]['imagenes'][] = $imagen->getPathName();
                     }
                 } else {
                     $articulos[$key]['imagenes'] = array();
                 }
             }
             unset($articulo);
         }
     }
     return $articulos;
 }
 /**
  * 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 \ErpArticulos array de objetos Articulos
  */
 public function getArticulos($idRegla, $nItems = 999999)
 {
     $array = array();
     if ($nItems <= 0) {
         $nItems = 999999;
     }
     $articulos = new Articulos();
     $tablaArticulos = $articulos->getTableName();
     unset($articulos);
     $em = new EntityManager($this->getConectionName());
     if ($em->getDbLink()) {
         $query = "\n                SELECT a.IDArticulo as Id\n                FROM {$em->getDataBase()}.{$this->getTableName()} r, {$em->getDataBase()}.{$tablaArticulos} a\n                WHERE r.IDRegla='{$idRegla}' AND r.IDArticulo=a.IDArticulo AND a.Publish='1' AND a.Vigente='1' AND a.Deleted='0'\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;
 }
 /**
  * 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;
 }
 /**
  * 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();
 }
 private function SustituyeValores($master, $variables)
 {
     $documento = $this->textoPlantilla;
     if ($this->queryDetail) {
         $linkValue = $master[$this->circulares[$this->idCircular]['linkColumn']];
         $query = str_replace("LINKVALUE", $linkValue, $this->queryDetail);
         $em = new EntityManager($_SESSION['project']['conection']);
         if ($em->getDbLink()) {
             $em->query($query);
             $detail = $em->fetchResult();
         }
         unset($em);
         // Buscar el bloque de detalle
         $inicio = stristr($this->textoPlantilla, $this->separadorDetailOpen);
         $bloqueDetail = stristr($inicio, $this->separadorDetailClose, true);
         $bloqueDetail = str_replace($this->separadorDetailOpen, "", $bloqueDetail);
         $bloqueDetailEnmarcado = $this->separadorDetailOpen . $bloqueDetail . $this->separadorDetailClose;
         $textoDetail = "";
         foreach ($detail as $registro) {
             $registroDetail = $bloqueDetail;
             foreach ($variables['db'] as $key => $value) {
                 $registroDetail = str_replace($this->separadorOpen . $key . $this->separadorClose, utf8_decode($registro[$value]), $registroDetail);
             }
             foreach ($variables['libres'] as $key => $value) {
                 $registroDetail = str_replace($this->separadorOpen . $key . $this->separadorClose, $value, $registroDetail);
             }
             $textoDetail .= $registroDetail;
         }
         //echo $textoDetail, "<br/>";
         $documento = str_replace($bloqueDetailEnmarcado, $textoDetail, $documento);
     }
     foreach ($variables['db'] as $key => $value) {
         $documento = str_replace($this->separadorOpen . $key . $this->separadorClose, utf8_decode($master[$value]), $documento);
     }
     foreach ($variables['libres'] as $key => $value) {
         $documento = str_replace($this->separadorOpen . $key . $this->separadorClose, $value, $documento);
     }
     return $documento;
 }
 /**
  * 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;
 }
 /**
  * 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
  *
  * Si es por GET los parametros vienen en:
  *
  *  posicion 2 (idArticulo), 3 (idCliente), 4 (periodo)
  *
  * @return array El template y los datos
  */
 public function HistoricoVentasAction()
 {
     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'];
             break;
         case 'POST':
             $idArticulo = $this->request['idArticulo'];
             if ($idArticulo == '0') {
                 $idArticulo = '';
             }
             $idCliente = $this->request['idCliente'];
             if ($idCliente == '0') {
                 $idCliente = '';
             }
             $periodo = $this->request['periodo'];
             break;
     }
     // Construir la parte del filtro que depende del periodo
     switch ($periodo) {
         case '':
             $periodo = 0;
         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();
     $albaran = new AlbaranesCab();
     $albaranTabla = $albaran->getDataBaseName() . "." . $albaran->getTableName();
     unset($albaran);
     $lineas = new AlbaranesLineas();
     $lineasTabla = $lineas->getDataBaseName() . "." . $lineas->getTableName();
     unset($lineas);
     // Calcular el total de unidades vendidas y el precio medio de venta
     // No tiene en cuenta los albaranes que no están confirmados
     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, {$albaranTabla} as t2";
             $query .= " WHERE t1.IDAlbaran=t2.IDAlbaran AND t2.IDEstado<>'0' 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'];
     }
     $this->values['datos'] = array('idsucursal' => $_SESSION['usuarioPortal']['SucursalActiva']['Id'], 'articulo' => $articulo, 'cliente' => $cliente, 'unidades' => $unidades, 'periodo' => $periodo, 'periodos' => $this->periodos, 'precioMedio' => number_format($precioMedio, 3));
     // Obtener el litado histórico de ventas para el articulo y cliente
     // Solo muestra los albaranes que están confirmador o facturados
     $em = new EntityManager($articulo->getConectionName());
     if ($em->getDbLink()) {
         $query = "SELECT t2.IDLinea,t1.IDAlbaran,t1.NumeroAlbaran,t1.PrimaryKeyMD5,DATE_FORMAT(t1.Fecha,'%d-%m-%Y') as Fecha,t1.IDEstado,t1.IDFactura,t2.Descripcion,t2.Unidades,t2.Precio,t2.Descuento,t2.Importe,t2.IDPromocion\n                FROM {$albaranTabla} as t1, {$lineasTabla} as t2";
         if ($idCliente !== '') {
             $query .= ", {$clienteTabla} as t3";
         }
         if ($idArticulo !== '') {
             $query .= ", {$articuloTabla} as t4";
         }
         $query .= " WHERE t1.IDAlbaran=t2.IDAlbaran";
         if ($idCliente !== '') {
             $query .= " AND t1.IDCliente=t3.IDCliente AND t1.IDCliente='{$idCliente}' ";
         }
         if ($idArticulo !== '') {
             $query .= " AND t2.IDArticulo=t4.IDArticulo AND t2.IDArticulo='{$idArticulo}'";
         }
         $query .= "\n                AND t1.IDEstado<>'0'\n                AND t1.Fecha>='{$desdeFecha}'\n                ORDER BY t1.Fecha DESC, t1.IDAlbaran DESC";
         $em->query($query);
         //echo $query;
         $rows = $em->fetchResult();
         $em->desConecta();
     }
     // Recorro el array de resultados y convierto (si procede) la columna IDPromocion
     // en un objeto promocion para tener todos los datos de la promocion en el template.
     foreach ($rows as $key => $value) {
         $rows[$key]['Estado'] = new EstadosAlbaranes($value['IDEstado']);
         if ($value['IDFactura']) {
             $rows[$key]['Factura'] = new FemitidasCab($value['IDFactura']);
         }
         if ($value['IDPromocion']) {
             $rows[$key]['IDPromocion'] = new Promociones($value['IDPromocion']);
         }
     }
     $this->values['listado'] = $rows;
     unset($em);
     unset($articulo);
     unset($cliente);
     return array('template' => '_Emergente/historicoVentas.html.twig', 'values' => $this->values);
 }
Exemple #23
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);
 }
 /**
  * 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;
 }
 /**
  * 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;
 }
Exemple #27
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);
 }
 /**
  * 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);
 }
Exemple #29
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;
 }
 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']);
 }