/**
  * Genera array con los clientes del la ruta para el
  * comercial y dia indicado
  *
  * @param integer $idComercial
  * @param integer $dia
  * @return <type>
  */
 public function listAction($idComercial = '', $dia = '')
 {
     if ($idComercial == '') {
         $idComercial = $this->request[2];
     }
     if ($dia == '') {
         $dia = $this->request[3];
     }
     $this->values['listado']['dia'] = $dia;
     // Busco los clientes del comercial indicado y sucursal actual
     // que aun no estén asignados al día solicitado
     $cliente = new Clientes();
     $rutasVentas = new RutasVentas();
     $filtro = "IDComercial='{$idComercial}'\n                        AND IDSucursal='{$_SESSION['suc']}'\n                        AND IDCliente NOT IN\n                            (SELECT IDCliente FROM {$rutasVentas->getDataBaseName()}.{$rutasVentas->getTableName()}\n                            WHERE IDComercial='{$idComercial}' AND Dia='{$dia}')";
     $clientes = $cliente->cargaCondicion("IDCliente as Id, RazonSocial as Value", $filtro, "RazonSocial ASC");
     $this->values['listado']['clientes'] = $clientes;
     array_unshift($this->values['listado']['clientes'], array('Id' => '', 'Value' => ':: Indique un cliente'));
     // Busco las zonas de los clientes del comercial indicado y sucursal actual
     // que aun no estén asignados al día solicitado
     $zona = new Zonas();
     $em = new EntityManager($cliente->getConectionName());
     if ($em->getDbLink()) {
         $query = "SELECT DISTINCT t1.IDZona as Id, t2.Zona as Value \n                        FROM \n                            {$cliente->getDataBaseName()}.{$cliente->getTableName()} as t1, \n                            {$zona->getDataBaseName()}.{$zona->getTableName()} as t2\n                        WHERE t1.IDZona=t2.IDZona\n                        AND t1.IDComercial='{$idComercial}'\n                        AND t1.IDSucursal='{$_SESSION['suc']}'\n                        AND t1.IDCliente NOT IN\n                            (SELECT IDCliente FROM {$rutasVentas->getDataBaseName()}.{$rutasVentas->getTableName()}\n                            WHERE IDComercial='{$idComercial}' AND Dia='{$dia}')\n                        ORDER BY t2.Zona ASC";
         $em->query($query);
         $rows = $em->fetchResult();
         $em->desConecta();
     }
     $this->values['listado']['zonas'] = $rows;
     array_unshift($this->values['listado']['zonas'], array('Id' => '', 'Value' => ':: Indique una Zona'));
     //-----------------------------------------------
     // Lleno los clientes asignados al comercial y día
     // ordenados por Zona
     // -----------------------------------------------
     $em = new EntityManager($cliente->getConectionName());
     if ($em->getDbLink()) {
         $query = "SELECT t1.Id \n                        FROM \n                            {$rutasVentas->getDataBaseName()}.{$rutasVentas->getTableName()} as t1,\n                            {$cliente->getDataBaseName()}.{$cliente->getTableName()} as t2\n                        WHERE t1.IDCliente=t2.IDCliente\n                        AND t2.IDSucursal='{$_SESSION['suc']}'\n                        AND t1.IDComercial='{$idComercial}'\n                        AND t1.Dia='{$dia}'\n                        ORDER BY t1.OrdenCliente,t1.IDZona";
         $em->query($query);
         $rows = $em->fetchResult();
         $em->desConecta();
     }
     unset($em);
     unset($em);
     unset($cliente);
     unset($zona);
     unset($rutasVentas);
     foreach ($rows as $row) {
         $lineas[] = new $this->parentEntity($row['Id']);
     }
     //-----------------------------------------------
     $template = $this->entity . '/list.html.twig';
     $this->values['linkBy']['value'] = $idComercial;
     $this->values['listado']['data'] = $lineas;
     $this->values['listado']['nClientes'] = count($lineas);
     unset($lis);
     unset($lineas);
     return array('template' => $template, 'values' => $this->values);
 }
Ejemplo n.º 2
0
 /**
  * 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;
 }
 /**
  * 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);
 }
Ejemplo n.º 4
0
 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;
 }
Ejemplo n.º 5
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;
 }
Ejemplo n.º 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;
 }
 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);
 }
Ejemplo n.º 8
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;
 }
Ejemplo n.º 9
0
 /**
  * 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;
 }
Ejemplo n.º 10
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;
 }
Ejemplo n.º 11
0
 /**
  * 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;
 }
Ejemplo n.º 12
0
 /**
  * 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;
 }
 /**
  * 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();
 }
Ejemplo n.º 14
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;
 }
Ejemplo n.º 15
0
 static function RecibosAgrupados($filtro)
 {
     $recibos = new RecibosClientes();
     $clientes = new Clientes();
     $tablaRecibos = $recibos->getDataBaseName() . "." . $recibos->getTableName();
     $tablaClientes = $clientes->getDataBaseName() . "." . $clientes->getTableName();
     $em = new EntityManager($recibos->getConectionName());
     if ($em->getDbLink()) {
         $filtro .= " and (Remesar='1') and (CHAR_LENGTH(r.Iban)>23) and (r.Iban<>'ES8200000000000000000000')";
         $query = "select r.IDCliente," . "sum(r.Importe) importe," . "r.Iban iban, " . "r.Bic bic, " . "r.Mandato idMandato, " . "r.FechaMandato fechaMandato " . "from {$tablaRecibos} as r " . "left join {$tablaClientes} as c on r.IDCliente=c.IDCliente " . "where {$filtro} " . "group by r.IDCliente,r.Iban " . "having sum(r.Importe)>0 " . "order by c.RazonSocial,r.Vencimiento ASC";
         $em->query($query);
         $rows = $em->fetchResult();
     }
     unset($em);
     unset($recibos);
     unset($clientes);
     $total = 0;
     foreach ($rows as $row) {
         $cliente = new Clientes($row['IDCliente']);
         $total += $row['importe'];
         $recibos[] = array('numeroFactura' => 'Varias', 'importe' => $row['importe'], 'idMandato' => $row['idMandato'], 'fechaMandato' => $row['fechaMandato'], 'bic' => $row['bic'] == '' ? "BBBBESPP" : $row['bic'], 'iban' => $row['iban'], 'razonSocial' => $cliente->getRazonSocial(), 'direccion1' => $cliente->getDireccion(), 'direccion2' => $cliente->getIDPoblacion()->getMunicipio() . " " . $cliente->getCodigoPostal() . " " . $cliente->getIDProvincia()->getProvincia(), 'pais' => $cliente->getIDPais()->getCodigo(), 'texto' => "Varias Facturas");
     }
     unset($cliente);
     return array('nRecibos' => count($rows), 'importeTotal' => $total, 'recibos' => $recibos);
 }
Ejemplo n.º 16
0
 /**
  * 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;
 }
 /**
  * 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);
 }
Ejemplo n.º 18
0
 /**
  * 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;
 }
Ejemplo n.º 19
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;
 }
Ejemplo n.º 20
0
 /**
  * Anula la confirmación del pedido
  * Pasando del estado CONFIRMADO (1) a PTE. CONFIRMAR (0)
  * Solo se tienen en cuenta los artículos inventariables.
  * Anula del registro de existencias las cantidades pendientes de entrada
  */
 public function anulaConfirmacion()
 {
     // Si está confirmado
     if ($this->getIDEstado()->getIDTipo() == 1) {
         $lineas = new PedidosLineas();
         $tablaLineas = $lineas->getDataBaseName() . "." . $lineas->getTableName();
         $articulos = new Articulos();
         $tablaArticulos = $articulos->getDataBaseName() . "." . $articulos->getTableName();
         $em = new EntityManager($this->getConectionName());
         $query = "SELECT t1.IDArticulo, t1.IDAlmacen, sum(t1.Unidades) as Entrando, t1.UnidadMedida\n                        FROM {$tablaLineas} as t1, {$tablaArticulos} as t2\n                        WHERE t1.IDPedido='{$this->IDPedido}'\n                            AND t1.IDEstado='1'\n                            AND t1.IDArticulo=t2.IDArticulo\n                            AND t2.Inventario='1'\n                        GROUP BY t1.IDArticulo, t1.IDAlmacen, t1.UnidadMedida";
         $em->query($query);
         $rows = $em->fetchResult();
         $em->desConecta();
         // Quitar previsión de entrada
         $exi = new Existencias();
         foreach ($rows as $row) {
             $exi->quitaEntrando($row['IDAlmacen'], $row['IDArticulo'], $row['Entrando'], $row['UnidadMedida'], $this->Deposito);
         }
         unset($exi);
         // Marcar como NO CONFIRMADAS las líneas de pedido y
         // quitar la eventual asignación de lotes y UnidadesRecbidas
         $lineas->queryUpdate(array("IDEstado" => 0), "IDPedido='{$this->IDPedido}' and IDEstado='1'");
         // Borrar las eventuales líneas de recepción
         $recepciones = new Recepciones();
         $recepciones->queryDelete("Entidad='PedidosCab' and IDEntidad='{$this->IDPedido}'");
         // Anular la reserva en la cabecera del pedido
         // y quitar la fecha prevista de entrega y las posibles incidencias
         $this->setIDEstado(0);
         $this->setFechaEntrega('00/00/0000');
         $this->setIncidencias('');
         $this->save();
     }
 }
 /**
  * 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);
 }
Ejemplo n.º 22
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;
 }
 /**
  * Crea las líneas de recepciones relativas al traspaso
  *
  * @param integer $idTraspaso
  */
 public function cargaLineasTraspaso($idTraspaso)
 {
     // Cargo las lineas dl traspaso que no están recibidas y cuyos artículos son inventariables.
     // Borro las eventuales líneas de recepción que no están recibidas
     $traspasosLineas = new TraspasosLineas();
     $rows = array();
     $em = new EntityManager($traspasosLineas->getConectionName());
     if ($em->getDbLink()) {
         $query = "select l.IDLinea\n                    from {$em->getDataBase()}.ErpTraspasosLineas l, {$em->getDataBase()}.ErpArticulos a\n                    where l.IDTraspaso = '{$idTraspaso}' and\n                          l.IDEstado = '2' and\n                          l.Tipo = '0' and\n                          l.IDArticulo = a.IDArticulo and\n                          a.Inventario = '1'\n                    order by IDLinea ASC;";
         $em->query($query);
         $rows = $em->fetchResult();
         $query = "delete from ErpRecepciones where Entidad='TraspasosCab' and IDEntidad='{$idTraspaso}' and Recepcionada='0'";
         $em->query($query);
         $em->desConecta();
     }
     unset($em);
     unset($traspasosLineas);
     // Por cada lína de traspaso crea una línea de recepción
     foreach ($rows as $row) {
         $this->creaLineaRecepcion('TraspasosCab', $idTraspaso, new TraspasosLineas($row['IDLinea']));
     }
 }
Ejemplo n.º 24
0
 /**
  * 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();
     }
 }
Ejemplo n.º 25
0
 /**
  * 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;
 }
Ejemplo n.º 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->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;
 }
Ejemplo n.º 27
0
 /**
  * Anula la confirmacion de la orden de traspaso, que consiste en:
  *
  *  1.- Quitar la reserva de mercancia en el registro de existencias sin indicar lote ni ubicacion
  *      solo para aquellos artículos que estén sujetos a inventario
  *  2.- Poner la cabecera de la orden de traspaso y sus lineas en estado PTE. DE CONFIRMAR (0)
  *
  */
 public function anulaConfirmacion()
 {
     // Si está confirmado
     if ($this->getIDEstado()->getIDTipo() == 1) {
         $em = new EntityManager($this->getConectionName());
         $query = "SELECT t1.IDArticulo, t1.IDAlmacen, t1.Unidades, t1.UnidadMedida\n                        FROM {$this->_dataBaseName}.ErpTraspasosLineas as t1, ErpArticulos as t2\n                        WHERE t1.IDTraspaso='{$this->IDTraspaso}'\n                            AND t1.Tipo='0'\n                            AND t1.IDEstado='1'\n                            AND t1.IDArticulo=t2.IDArticulo\n                            AND t2.Inventario='1'";
         $em->query($query);
         $rows = $em->fetchResult();
         $em->desConecta();
         // Quitar las reservas
         $exi = new Existencias();
         foreach ($rows as $row) {
             $exi->quitaReserva($row['IDAlmacen'], $row['IDArticulo'], $row['Unidades'], $row['UnidadMedida']);
         }
         unset($exi);
         // Poner en estado de PTE DE CONFIRMAR las líneas de la orden de traspaso de tipo 0 (salida)
         $lineas = new TraspasosLineas();
         $lineas->queryUpdate(array("IDEstado" => 0), "IDTraspaso='{$this->IDTraspaso}' and IDEstado='1' and Tipo='0'");
         unset($lineas);
         // Borrar las eventuales lineas de expedicion
         $expediciones = new Expediciones();
         $expediciones->queryDelete("Entidad='TraspasosCab' and IDEntidad='{$this->IDTraspaso}'");
         unset($expediciones);
         // Anular la reserva en la cabecera de la orden de traspaso
         $this->setIDEstado(0);
         $this->save();
     }
 }
 private function recalcula($idAlmacen)
 {
     // Poner las reservadas y el entrando a cero
     $stock = new Existencias();
     $stock->queryUpdate(array("Reservadas" => 0, "Entrando" => 0), "IDAlmacen='{$idAlmacen}'");
     // Borrar los registros de stock que estén a cero
     $stock->queryDelete("IDAlmacen='{$idAlmacen}' and Reales=0 and Pales=0 and Cajas=0 and Reservadas=0 and Entrando=0");
     // Calcular las reservas de los artículos inventariables
     $lineas = new AlbaranesLineas();
     $articulos = new Articulos();
     $tablaLineas = $lineas->getDataBaseName() . "." . $lineas->getTableName();
     $tablaArticulos = $articulos->getDataBaseName() . "." . $articulos->getTableName();
     unset($lineas);
     unset($articulos);
     $query = "select l.IDArticulo,a.Codigo,l.Descripcion, sum(l.Unidades) Unidades,l.UnidadMedida ";
     $query .= "from {$tablaLineas} as l ";
     $query .= "join {$tablaArticulos} as a on l.IDArticulo=a.IDArticulo ";
     $query .= "where l.IDEstado='1' and a.Inventario='1' ";
     $query .= "group by l.IDArticulo";
     $em = new EntityManager($_SESSION['project']['conection']);
     $em->query($query);
     $rows = $em->fetchResult();
     $em->desConecta();
     unset($em);
     $resultado['reservas'] = $rows;
     foreach ($rows as $row) {
         $stock = new Existencias();
         $stock->hazReserva($idAlmacen, $row['IDArticulo'], $row['Unidades'], $row['UnidadMedida']);
     }
     // Calcular el entrando de los artículos inventariables
     $lineas = new PedidosLineas();
     $articulos = new Articulos();
     $tablaLineas = $lineas->getDataBaseName() . "." . $lineas->getTableName();
     $tablaArticulos = $articulos->getDataBaseName() . "." . $articulos->getTableName();
     unset($lineas);
     unset($articulos);
     $query = "select l.IDArticulo,a.Codigo,l.Descripcion,sum(l.Unidades) Unidades,l.UnidadMedida ";
     $query .= "from {$tablaLineas} as l ";
     $query .= "join {$tablaArticulos} as a on l.IDArticulo=a.IDArticulo ";
     $query .= "where l.IDEstado='1' and a.Inventario='1' ";
     $query .= "group by l.IDArticulo";
     $em = new EntityManager($_SESSION['project']['conection']);
     $em->query($query);
     $rows = $em->fetchResult();
     $em->desConecta();
     unset($em);
     $resultado['entrando'] = $rows;
     foreach ($rows as $row) {
         $stock = new Existencias();
         $stock->hazEntrando($idAlmacen, $row['IDArticulo'], $row['Unidades'], $row['UnidadMedida']);
     }
     return $resultado;
 }
Ejemplo n.º 29
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;
 }
Ejemplo n.º 30
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);
 }