3 Commits
tests ... 1.03

Author SHA1 Message Date
rmontanana
8ffd97b474 Versión 1.03:
incluye: borrados ficheros innecesarios y recolocado upgrade.php en sql

Terminado el mantenimiento con:
-Control de la url de vuelta
-funcionamiento correcto de la cadena de búsqueda con la ordenación, edición, etc.
-funcionamiento correcto de la paginación y el orden con la edición, borrado, etc.
-mensaje de inserción de registros con nuevo formato y redirección con tiempo.

Arreglado que salía mantenimiento de Artículos cuando se solicitaba Matenimiento de Elementos.
2014-03-12 10:56:53 +01:00
rmontanana
caae389c93 AportaContenido: Arreglado el mensaje de Mantenimiento de Elementos que aparecía de artículos.
Mantenimiento, Sql y *xml: Arreglado el mantenimiento para que gestione bien la URL y trabaje bien el paginador y la cadena de búsqueda coordinado con la edición, las inserciones y el borrado. También se han añadido mensajes mejorados en Mantenimiento.
2014-03-12 09:24:17 +01:00
rmontanana
42eb01c27e Mejora en la visualización de la tabla de Configuración en resoluciones pequeñas. 2014-03-11 13:21:16 +01:00
13 changed files with 226 additions and 544 deletions

View File

@@ -144,8 +144,8 @@ class AportaContenido {
return "Menú Principal";
case 'principal':
return "Pantalla Inicial";
case 'elementos':
case 'articulos': $opcion = "artículos";
case 'elementos':
case 'ubicaciones':
case 'usuarios':
case 'test':

View File

@@ -171,7 +171,7 @@
$cristal=$this->estilo=="cristal"?'selected':' ';
$normal=$this->plantilla=="normal"? 'selected':' ';
$bootstrap=$this->plantilla=="bootstrap" ? 'selected':' ';
$salida='<center><div class="col-sm-4 col-md-6"><form name="configura" method="post">';
$salida='<center><div class="col-sm-8 col-md-8"><form name="configura" method="post">';
//$salida.='<p align="center"><table border=1 class="tablaDatos"><tbody>';
$salida.='<p align="center"><table border=2 class="table table-hover"><tbody>';
$salida.='<th colspan=2 class="info"><center><b>Preferencias</b></center></th>';

View File

@@ -1,147 +0,0 @@
<?php
/**
* @package Inventario
* @copyright Copyright (c) 2008, Ricardo Montañana Gómez
* @license http://www.gnu.org/licenses/gpl-3.0.txt
* This file is part of Inventario.
* Inventario is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Inventario is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Inventario. If not, see <http://www.gnu.org/licenses/>.
*
*/
class InformeInventario {
private $bdd;
public function __construct($baseDatos)
{
$this->bdd=$baseDatos;
}
public function ejecuta()
{
$opc=$_GET['opc'];
switch ($opc) {
case 'Ubicacion':return $this->formularioUbicacion();
case 'listarUbicacion':return $this->listarUbicacion();
case 'listarArticulo':return $this->listarArticulo();
case 'Articulo':return $this->formularioArticulo();
case 'Total':return $this->inventarioTotal();
}
}
private function listarUbicacion()
{
$fichero="xml/inventarioUbicacion.xml";
$salida="tmp/inventarioUbicacion.xml";
$plantilla=file_get_contents($fichero)
or die('Fallo en la apertura de la plantilla '.$fichero);
$comando="select * from Ubicaciones where id='".$_POST['id']."';";
$resultado=$this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->bdd->mensajeError($comando);
}
$fila=$this->bdd->procesaResultado();
$plantilla=str_replace("{id}",$_POST['id'],$plantilla);
$plantilla=str_replace("{Descripcion}",utf8_encode($fila['Descripcion']),$plantilla);
file_put_contents($salida,$plantilla)
or die('Fallo en la escritura de la plantilla '.$salida);
$informe=new InformePDF($this->bdd,$salida,true);
}
private function listarArticulo()
{
$fichero="xml/inventarioArticulo.xml";
$salida="tmp/inventarioArticulo.xml";
$plantilla=file_get_contents($fichero)
or die('Fallo en la apertura de la plantilla '.$fichero);
$comando="select * from Articulos where id='".$_POST['id']."';";
$resultado=$this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->bdd->mensajeError($comando);
}
$fila=$this->bdd->procesaResultado();
$plantilla=str_replace("{id}",$_POST['id'],$plantilla);
$plantilla=str_replace("{Descripcion}",utf8_encode($fila['descripcion']),$plantilla);
$plantilla=str_replace("{Marca}",utf8_encode($fila['marca']),$plantilla);
$plantilla=str_replace("{Modelo}",utf8_encode($fila['modelo']),$plantilla);
file_put_contents($salida,$plantilla)
or die('Fallo en la escritura de la plantilla '.$salida);
$informe=new InformePDF($this->bdd,$salida,true);
}
private function listaUbicaciones()
{
$salida="<select name=\"id\">\n";
$comando="select * from Ubicaciones order by Descripcion";
$resultado=$this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->bdd->mensajeError($comando);
}
while($fila=$this->bdd->procesaResultado()) {
$salida.="<option value=".$fila['id'].">".$fila['Descripcion']."</option><br>\n";
}
$salida.="</select>\n";
return $salida;
}
private function listaArticulos()
{
$salida="<select name=\"id\">\n";
$comando="select * from Articulos order by descripcion, marca, modelo";
$resultado=$this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->bdd->mensajeError($comando);
}
while($fila=$this->bdd->procesaResultado()) {
$salida.="<option value=".$fila['id'].">".$fila['descripcion']."-".$fila['marca']."-".$fila['modelo']."</option><br>\n";
}
$salida.="</select>\n";
return $salida;
}
private function formulario($accion,$etiqueta,$lista)
{
$salida='<form name="mantenimiento.form" method="post" action="'.$accion.'">'."\n";
$salida.="<fieldset style=\"width: 96%;\"><p><legend style=\"color: red;\"><b>Elige $etiqueta</b></legend>\n";
$salida.="<br><br><label>$etiqueta</label>";
$salida.=$lista;
$salida.="<br><br></fieldset><p>";
$salida.='<p align="center"><button type=submit>Aceptar</button></p><br>'."\n";
return $salida;
}
private function formularioUbicacion()
{
//Genera un formulario con las ubicaciones disponibles.
$accion="index.php?informeInventario&opc=listarUbicacion";
return $this->formulario($accion,'Ubicaci&oacute;n',$this->listaUbicaciones());
}
private function formularioArticulo()
{
$accion="index.php?informeInventario&opc=listarArticulo";
return $this->formulario($accion,'Art&iacute;culo',$this->listaArticulos());
}
private function inventarioTotal()
{
$fichero="xml/inventarioUbicacion.xml";
$salida="tmp/inventarioUbicacion.xml";
$comando="select * from Ubicaciones where id='".$_POST['id']."';";
$resultado=$this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->bdd->mensajeError($comando);
}
$salidaTotal='';
while ($fila=$this->bdd->procesaResultado()) {
$plantilla=file_get_contents($fichero)
or die('Fallo en la apertura de la plantilla '.$fichero);
$plantilla=str_replace("{id}",$_POST['id'],$plantilla);
$plantilla=str_replace("{Descripcion}",utf8_encode($fila['Descripcion']),$plantilla);
file_put_contents($salida,$plantilla)
or die('Fallo en la escritura de la plantilla '.$salida);
$salidaTotal+=$salida;
}
$informe=new InformePDF($this->bdd,$salidaTotal,true);
}
}
?>

View File

@@ -1,85 +0,0 @@
<?php
/**
* genera un documento PDF a partir de una descripción dada en un archivo XML
* @author Ricardo Montañana <rmontanana@gmail.com>
* @version 1.0
* @package Inventario
* @copyright Copyright (c) 2008, Ricardo Montañana
* @package Inventario
* @copyright Copyright (c) 2008, Ricardo Montañana Gómez
* @license http://www.gnu.org/licenses/gpl-3.0.txt
* This file is part of Inventario.
* Inventario is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Inventario is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Inventario. If not, see <http://www.gnu.org/licenses/>.
*
*/
class InformePDF
{
/**
*
* @var basedatos Controlador de la base de datos
*/
private $bdd;
/**
* El constructor recibe como argumento el nombre del archivo XML con la definición, encargándose de recuperarla y guardar toda la información localmente
* @param basedatos $bdd manejador de la base de datos
* @param string $definicion fichero con la definición del informe en XML
* @param boolean $registrado usuario registrado si/no
* @return ficheroPDF
*/
public function __construct($bdd,$definicion,$registrado)
{
if (!$registrado) {
return 'Debe registrarse para acceder a este apartado';
}
$this->bdd=$bdd;
// Recuperamos la definición del informe
$def=simplexml_load_file($definicion);
//print_r($def);echo $bdd;die();
// Iniciamos la creación del documento
$pdf=new Pdf_mysql_table($this->bdd->obtieneManejador(),(string)$def->Pagina['Orientacion'],
(string)$def->Pagina['Formato'],
(string)$def->Titulo['Texto'],(string)$def->Pagina->Cabecera);
echo $def->Titulo.$def->Cabecera;
$pdf->Open();
$pdf->setAuthor(utf8_decode(AUTOR));
$pdf->setCreator(html_entity_decode(APLICACION));
$pdf->setSubject(utf8_decode($def->Titulo));
$pdf->setAutoPageBreak(true,10);
$this->bdd->ejecuta(trim($def->Datos->Consulta));
$filas=$this->bdd->procesaResultado();
$pdf->AddPage();
// Recuperamos los datos del cuerpo
foreach($def->Pagina->Cuerpo->Col as $columna) {
$pdf->AddCol((string)$columna['Nombre'],(string)$columna['Ancho'],
(string)$columna['Titulo'],(string)$columna['Ajuste'],
(string)$columna['Total']);
}
$prop=array('HeaderColor'=>array(255,150,100),
'color1'=>array(210,245,255),
'color2'=>array(255,255,210),
'padding'=>2);
$pdf->Table($def->Datos->Consulta,$prop);
$pdf->Close();
// Obtenemos el documento y su longitud
$documento=$pdf->Output('','S');
$longitud=strlen($documento);
// y lo enviamos como resultado
header("Content-type: application/pdf");
header("Content-length: $longitud");
header("Content-Disposition: inline; filename=Informe.pdf");
echo $documento;
}
}
?>

View File

@@ -29,7 +29,6 @@ class Mantenimiento {
private $descripcion;
protected $bdd;
protected $url;
protected $cabecera;
protected $tabla;
protected $cadenaBusqueda;
protected $campos = array();
@@ -37,39 +36,85 @@ class Mantenimiento {
protected $campoBusca = "Descripcion";
protected $comandoConsulta = "";
protected $perfil;
protected $datosURL = array();
protected $datosURLb = array(); //para hacer una copia
public function __construct($baseDatos, $perfil, $nombre) {
public function __construct($baseDatos, $perfil, $nombre)
{
$this->bdd = $baseDatos;
$this->url = "index.php?$nombre&opc=inicial";
$this->cabecera = 'Location: ' . $this->url;
$this->url = "index.php?$nombre";
//$this->datosURL['']
$this->tabla = ucfirst($nombre);
$this->perfil = $perfil;
$this->cargaDatosURL();
}
public function ejecuta() {
$opc = $_GET['opc'];
$id = $_GET['id'];
$orden = isset($_GET['orden']) ? $_GET['orden'] : '';
$sentido = isset($_GET['sentido']) ? $_GET['sentido'] : 'asc';
//Sólo tiene sentido para las modificaciones.
//Es la página donde estaba el registro
$pag = isset($_GET['pag']) ? $_GET['pag'] : '0';
$this->cadenaBusqueda = $_GET['buscar'];
/**
* Carga en los atributos de la clase los datos de la URL
* Los datos constantes en la URL son:
* - opc = {inicial, editar, eliminar, nuevo, insertar, modificar, borrar}
* - orden = {id, ... } nombre del campo por el que se ordena la visualización
* - sentido = {asc, desc}
* - pag = nº página 0, 1, 2, ...
* Los datos opcionales de la URL son:
* - buscar = cadena de búsqueda
* - id = nº de la clave necesario para la edición o el borrado
*/
public function cargaDatosURL()
{
$this->datosURL['opc'] = isset($_GET['opc']) ? $_GET['opc'] : 'inicial';
$this->datosURL['orden'] = isset($_GET['orden']) ? $_GET['orden'] : 'id';
$this->datosURL['sentido'] = isset($_GET['sentido']) ? $_GET['sentido'] : 'asc';
$this->datosURL['pag'] = isset($_GET['pag']) ? $_GET['pag'] : '0';
$this->cadenaBusqueda = isset($_GET['buscar']) ? $_GET['buscar'] : null;
$this->cadenaBusqueda = isset($_POST['buscar']) ? $_POST['buscar'] : $this->cadenaBusqueda;
$this->datosURL['buscar'] = $this->cadenaBusqueda;
$this->datosURL['id'] = isset($_GET['id']) ? $_GET['id'] : null;
}
public function backupURL()
{
$this->datosURLb = $this->datosURL;
}
public function restoreURL()
{
$this->datosURL = $this->datosURLb;
}
//Monta una URL con los datos cargados en los atributos de la clase
private function montaURL()
{
//Primero los datos obligatorios
$opc = "&opc=" . $this->datosURL['opc'];
$orden = "&orden=" . $this->datosURL['orden'];
$sentido = "&sentido=" . $this->datosURL['sentido'];
$pag = "&pag=" . $this->datosURL['pag'];
//Ahora los datos opcionales
$buscar = isset($this->cadenaBusqueda) ? "&buscar=$this->cadenaBusqueda" : null;
$id = isset($this->datosURL['id']) ? "&id=" . $this->datosURL['id'] : null;
$enlace = $this->url . $opc . $orden . $sentido . $pag . $buscar . $id;
return $enlace;
}
public function ejecuta()
{
$this->obtenerCampos();
$this->obtieneClavesForaneas();
switch ($opc) {
case 'inicial':return $this->consulta($id, $orden, $sentido);
case 'editar':return $this->muestra($id, EDICION, $pag, $orden, $sentido);
case 'eliminar':return $this->muestra($id, BORRADO);
case 'nuevo':return $this->muestra(null, ANADIR);
switch ($this->datosURL['opc']) {
case 'inicial':return $this->consulta();
case 'editar':return $this->muestra(EDICION);
case 'eliminar':return $this->muestra(BORRADO);
case 'nuevo':return $this->muestra(ANADIR);
case 'insertar':return $this->insertar();
case 'modificar':return $this->modificar($id, $pag, $orden, $sentido);
case 'borrar':return $this->borrar($id);
default:return 'La clase Mantenimiento No entiende lo solicitado.';
case 'modificar':return $this->modificar();
case 'borrar':return $this->borrar();
default: return "La clase Mantenimiento No entiende lo solicitado [" . $this->datosURL['opc'] . "]";
}
}
protected function obtieneClavesForaneas() {
protected function obtieneClavesForaneas()
{
$salida = null;
foreach ($this->campos as $clave => $valor) {
$trozos = explode(",", $valor["Comment"]);
@@ -87,20 +132,21 @@ class Mantenimiento {
$this->foraneas = $salida;
}
private function consulta($pagina, $orden, $sentido) {
private function consulta()
{
$orden = $this->datosURL['orden'];
$sentido = $this->datosURL['sentido'];
//Calcula los números de página anterior y siguiente.
$pagina = $pagina + 0;
$pagina = $this->datosURL['pag'];
$pagSigte = $pagina <= 0 ? 1 : $pagina + 1;
$pagAnt = $pagSigte - 2;
$pagAnt = $pagSigte - 2 < 0 ? 0 : $pagSigte -2;
$pagFwd = $pagSigte + 3;
$pagRew = $pagAnt - 3 < 0 ? $pagAnt : $pagAnt - 3;
$pagRew = $pagAnt - 3 < 0 ? 0 : $pagAnt - 3;
//Tengo que procesar la cabecera antes de lo de la cadena de búsqueda por el tema de las búsquedas
$cabecera = $this->cabeceraTabla();
//Trata con la cadena de búsqueda
$this->cadenaBusqueda = isset($_POST['buscar']) ? $_POST['buscar'] : $this->cadenaBusqueda;
//Trata con la cadena de búsqueda si viene del post debe quedarse con ella sino con la del get y si no está definida => vacía
if (isset($this->cadenaBusqueda) && strlen($this->cadenaBusqueda)) {
$sufijo = " where $this->campoBusca like '%" . $this->bdd->filtra($this->cadenaBusqueda) . "%'";
$sufijoEnlace = "&buscar=" . $this->cadenaBusqueda;
$comando = str_replace('{buscar}', $sufijo, $this->comandoConsulta);
} else {
$comando = str_replace('{buscar}', '', $this->comandoConsulta);
@@ -114,35 +160,34 @@ class Mantenimiento {
}
//Introduce un botón para hacer búsquedas y el número de la página
$salida = $this->enlaceBusqueda($pagSigte);
//Esta orden de centrado se cierra en el pie de la tabla
//$salida.='<center><h4>P&aacute;gina ' . $pagSigte . '</h4>';
// $salida .='<div class="nav-bar navbar-fixed"><ul class="nav nav-pills nav-stacked">
// <li class="active">
// <a href="#">
// <span class="badge pull-right">' . $pagSigte . '</span>
// P&aacute;gina
// </a>
// </li>
// </ul></div>';
$salida.= $cabecera;
//Consulta paginada de todas las tuplas
$comando = str_replace('{inferior}', ($pagAnt + 1) * NUMFILAS, $comando);
$comando = str_replace('{inferior}', $pagina * NUMFILAS, $comando);
$comando = str_replace('{superior}', NUMFILAS, $comando);
//$salida.=$comando;
$tabla = strtolower($this->tabla);
$this->bdd->ejecuta($comando);
$numRegistros = $this->bdd->numeroTotalTuplas();
//Si el número de la página fwd es mayor que el total de páginas lo establece a éste
if (NUMFILAS > 0) {
$totalPags = (int) ($numRegistros / NUMFILAS) - 1;
if ($numRegistros % NUMFILAS) {
$totalPags++;
}
} else {
$totalPags = 0;
}
$pagFwd = $pagFwd > $totalPags ? $totalPags : $pagFwd;
if ($this->bdd->numeroTuplas() == 0) {
if ($pagSigte > 1) {
// Si no hay datos en la consulta y no es la primera página,
// carga la página inicial
header('Location: ' . $this->url);
// carga la página final
$this->datosURL['pag'] = $totalPags;
header('Location: ' . $this->montaURL());
} else {
$salida = "<p align=\"center\"><center><h2>No hay registros</h2></center></p><br>";
}
}
//$salida.=print_r($this->perfil);
//$salida.=$comando;
//var_dump($this->campos);
while ($fila = $this->bdd->procesaResultado()) {
$salida.='<tr align="center" bottom="middle">';
foreach ($fila as $clave => $valor) {
@@ -169,37 +214,56 @@ class Mantenimiento {
}
//Añade el icono de editar
if ($this->perfil['Modificacion']) {
$salida.='<td><a href="index.php?' . $tabla . '&opc=editar&id=' . $id . "&pag=" . $pagina . $sufijoOrden .
//$salida.='<td><a href="index.php?' . $tabla . '&opc=editar&id=' . $id . "&pag=" . $pagina . $sufijoOrden . $sufijoEnlace .
$this->backupURL(); $this->datosURL['opc'] = "editar"; $this->datosURL['id'] = $id;
$salida.='<td><a href="' . $this->montaURL() .
'"><img title="Editar" src="img/' . ESTILO . '/editar.png" alt="editar"></a>';
$this->restoreURL();
}
//Añade el icono de eliminar
if ($this->perfil['Borrado']) {
$salida.='&nbsp;&nbsp;<a href="index.php?' . $tabla . '&opc=eliminar&id=' . $id .
//$salida.='&nbsp;&nbsp;<a href="index.php?' . $tabla . '&opc=eliminar&id=' . $id . $sufijoEnlace .
$this->backupURL(); $this->datosURL['opc'] = "eliminar"; $this->datosURL['id'] = $id;
$salida.='&nbsp;&nbsp;<a href="' . $this->montaURL() .
'"><img title="Eliminar" src="img/' . ESTILO . '/eliminar.png" alt="eliminar"></a></td></tr>' . "\n";
$this->restoreURL();
}
}
$salida.="</tbody></table></center></p>";
//Añade botones de comandos
$enlace = '<a href="' . $this->url . $sufijoOrden . '&id=';
if ($this->bdd->numeroTuplas()) {
$anterior = $enlace . $pagAnt . $sufijoEnlace . "\"><img title=\"Pag. Anterior\" alt=\"anterior\" src=\"img/" . ESTILO . "/anterior.png\"></a>\n";
$siguiente = $enlace . $pagSigte . $sufijoEnlace . "\"><img title=\"Pag. Siguiente\" alt=\"siguiente\" src=\"img/" . ESTILO . "/siguiente.png\"></a>\n";
$fwd = $enlace . $pagFwd . $sufijoEnlace . "\"><img title=\"+5 Pags.\" alt=\"mas5p\" src=\"img/" . ESTILO . "/fwd.png\"></a>\n";
$rew = $enlace . $pagRew . $sufijoEnlace . "\"><img title=\"-5 Pags.\" alt=\"menos5p\" src=\"img/" . ESTILO . "/rew.png\"></a>\n";
if (strlen($orden) > 0) {
$az = '<a href="' . $this->url . '&orden=' . $orden . '&sentido=asc"><img alt="asc" title="Orden ascendente" src="img/' . ESTILO . '/ascendente.png"></a>';
$za = '<a href="' . $this->url . '&orden=' . $orden . '&sentido=desc"><img alt="desc" title="Orden descendente" src="img/' . ESTILO . '/descendente.png"></a>';
} else {
$az = $za = '';
}
if ($numRegistros) {
$this->backupURL();
$this->datosURL['pag'] = $pagAnt;
$anterior = $this->montaURL();
$this->datosURL['pag'] = $pagSigte;
$siguiente = $this->montaURL();
$this->datosURL['pag'] = $pagFwd;
$fwd = $this->montaURL();
$this->datosURL['pag'] = $pagRew;
$rew = $this->montaURL();
$anterior = '<a href="' . $anterior . "\"><img title=\"Pag. Anterior\" alt=\"anterior\" src=\"img/" . ESTILO . "/anterior.png\"></a>\n";
$siguiente = '<a href="' . $siguiente . "\"><img title=\"Pag. Siguiente\" alt=\"siguiente\" src=\"img/" . ESTILO . "/siguiente.png\"></a>\n";
$fwd = '<a href="' . $fwd . "\"><img title=\"+4 Pags.\" alt=\"mas4pags\" src=\"img/" . ESTILO . "/fwd.png\"></a>\n";
$rew = '<a href="' . $rew . "\"><img title=\"-4 Pags.\" alt=\"menos4pags\" src=\"img/" . ESTILO . "/rew.png\"></a>\n";
$this->restoreURL();
$this->datosURL['sentido'] = "asc";
$az = $this->montaURL();
$az = '<a href="' . $az . '"><img alt="asc" title="Orden ascendente" src="img/' . ESTILO . '/ascendente.png"></a>';
$this->datosURL['sentido'] = "desc";
$za = $this->montaURL();
$za = '<a href="' . $za . '"><img alt="desc" title="Orden descendente" src="img/' . ESTILO . '/descendente.png"></a>';
$this->restoreURL();
if ($this->perfil['Informe']) {
$informe = '<a href="index.php?' . $tabla . '&opc=informe" target="_blank"><img src="img/' . ESTILO . '/informe.png" alt="informe" title="Informe pdf"></a>';
} else {
$informe = "";
}
$this->restoreURL();
}
if ($this->perfil['Alta']) {
$anadir = '<a href="index.php?' . $tabla . '&opc=nuevo">' .
$this->datosURL['opc'] = 'nuevo';
$anadir = '<a href="' . $this->montaURL() . '">' .
'<img title="A&ntilde;adir registro" alt="nuevo" src="img/' . ESTILO . '/nuevo.png"></a>';
} else {
$anadir = "";
@@ -209,39 +273,35 @@ class Mantenimiento {
return $salida;
}
private function enlaceBusqueda($pagina) {
//$salida = '<p align="center">';
//$salida .='<center><form name="busqueda" method="POST"><input type="text" class="form-control" name="buscar"';
//$salida .='value="' . $this->cadenaBusqueda . '" size="40" /><input type="submit" class="btn btn-primary" value="Buscar" name=';
//$salida .='"Buscar" />';
//$salida .= '</form></center>';
//$salida.='</p>';
private function enlaceBusqueda($pagina)
{
$valor = isset($this->cadenaBusqueda) ? 'value="' . $this->cadenaBusqueda . '"' : '';
$salida = '<form name="busqueda" method="POST"><div class="col-sm-4 col-lg-6"><div class="input-group">
<input type="text" name="buscar" placeholder="Descripci&oacute;n" class="form-control">
<input type="text" name="buscar" placeholder="Descripci&oacute;n" class="form-control" ' . $valor . '>
<span class="input-group-btn"><button class="btn btn-primary" type="button">Buscar</button>
</span></div></div></form>';
//$salida .= '<div class="col-lg-1 pull-right"><ul class="nav nav-pills nav-stacked "><li class="active">
// <a href="#"><span class="badge pull-right">'.$pagina.'</span>P&aacute;gina</a></li></ul></div>';
$salida .= '<button class="btn btn-info pull-right" type="button">P&aacute;gina <span class="badge">'
. $pagina . '</span></button>';
// $salida .= '<div class="progress progress-striped">
// <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%">
// P&aacute;gina 5 de 6<span class="sr-only">20% Complete</span>
// </div>
//</div>';
return $salida;
}
protected function borrar($id) {
protected function borrar()
{
//@todo hay que tener en cuenta aquí la cadena de búsqueda y la página en la url
$id = $this->datosURL['id'];
$comando = "delete from " . $this->tabla . " where id=\"$id\"";
if (!$this->bdd->ejecuta($comando)) {
return $this->errorBD($comando);
}
header('Location: ' . $this->url);
$this->datosURL['opc'] = 'inicial';
$this->datosURL['id'] = null;
$url = $this->montaURL();
header('Location: ' . $url);
return;
}
protected function insertar() {
protected function insertar()
{
$comando = "insert into " . $this->tabla . " (";
$lista = explode("&", $_POST['listacampos']);
$primero = true;
@@ -275,7 +335,7 @@ class Mantenimiento {
if (empty($_POST[$campo])) {
$valor = "0";
}
$valor = $_POST[$campo] == "on" ? '1' : $valor;
$valor = $_POST[$campo] == "on" ? '1' : $valor;
} else {
$valor = $_POST[$campo] == "" ? "null" : '"' . $_POST[$campo] . '"';
}
@@ -285,19 +345,23 @@ class Mantenimiento {
if (!$this->bdd->ejecuta($comando)) {
return $this->errorBD($comando);
}
list($enlace, $resto) = explode("&", $this->url);
$enlace.="&opc=inicial";
return "<h1><a href=\"$enlace\">Se ha insertado el registro con la clave " . $this->bdd->ultimoId() . "</a></h1>";
$this->datosURL['opc'] = 'inicial';
$this->datosURL['id'] = null;
$cabecera = "refresh:".PAUSA.";url=".$this->montaURL();
header($cabecera);
return $this->panelMensaje("Se ha insertado el registro con la clave " . $this->bdd->ultimoId(), "info", "Informaci&oacute;n");
//return "<h1><a href=\"".$this->montaURL()."\">Se ha insertado el registro con la clave " . $this->bdd->ultimoId() . "</a></h1>";
}
protected function modificar($id, $pag, $orden, $sentido) {
protected function modificar()
{
//Los datos a utilizar para actualizar la tupla vienen en $_POST.
//La lista de atributos de la tupla viene en el campo oculto listacampos
//print_r($_GET);
//echo "id=$id pag=$pag orden=$orden sentido=$sentido";die();
//@todo hay que tener en cuenta aquí la página en la que se encuentra y la cadena de búsqueda
$comando = "update " . $this->tabla . " set ";
$lista = explode("&", $_POST['listacampos']);
//var_dump($lista);
$primero = true;
foreach ($lista as $campo) {
if ($campo == "id" || $campo == "")
@@ -323,20 +387,20 @@ class Mantenimiento {
}
}
}
$comando.=" where id=\"$id\"";
$comando.=" where id=\"" . $this->datosURL['id'] . "\"";
if (!$this->bdd->ejecuta($comando)) {
return $this->errorBD($comando);
}
list($enlace, $resto) = explode("&", $this->url);
$enlace.="&opc=inicial&orden=" . $orden . "&sentido=" . $sentido . "&id=" . $pag;
//echo $comando;
header('Location: ' . $enlace);
$this->datosURL['id'] = null;
$this->datosURL['opc'] = inicial;
header('Location: ' . $this->montaURL());
return;
}
protected function muestra($id, $tipoAccion, $pag = "", $orden = "", $sentido = "") {
if (isset($id)) {
protected function muestra($tipoAccion)
{
$id = $this->datosURL['id'];
if ($tipoAccion != ANADIR) {
$comando = "select * from " . $this->tabla . " where id='$id'";
$resultado = $this->bdd->ejecuta($comando);
if (!$resultado) {
@@ -346,29 +410,14 @@ class Mantenimiento {
} else {
$fila = null;
}
//list($tipo,$valor)=explode($columna["Type"]);
$accion = "index.php?" . strtolower($this->tabla) . "&id=$id&opc=";
switch ($tipoAccion) {
case EDICION:
$accion.="modificar";
$accion.=isset($pag) ? "&pag=$pag" : '';
$accion.=isset($orden) ? "&orden=$orden" : '';
$accion.=isset($sentido) ? "&sentido=$sentido" : '';
break;
case BORRADO:
$accion.="borrar";
break;
case ANADIR:
$accion.="insertar";
break;
}
//Genera un formulario con los datos de la tupla seleccionada.
return $this->formularioCampos($accion, $tipoAccion, $fila);
return $this->formularioCampos($tipoAccion, $fila);
}
//Función que genera un campo de lista con los valores de descripción de la
//tabla a la cual pertenece la clave foránea.
protected function generaLista($datos, $campo, $valorInicial, $modo) {
protected function generaLista($datos, $campo, $valorInicial, $modo)
{
$salida = "<select class=\"form-control\" name=\"$campo\">\n";
list($tabla, $atributos) = explode(",", $datos);
$atributos = str_replace("/", ",", $atributos);
@@ -401,7 +450,8 @@ class Mantenimiento {
return $salida;
}
private function obtenerCampos() {
private function obtenerCampos()
{
//Si hay un fichero de descripción xml lo utiliza.
$nombre = "xml/mantenimiento" . $this->tabla . ".xml";
if (file_exists($nombre)) {
@@ -420,11 +470,12 @@ class Mantenimiento {
$this->campos[$datos[$i]["Field"]]["Campo"] = $datos[$i]["Field"];
$this->campos[$datos[$i]["Field"]]["Editable"] = "si";
}
$this->comandoConsulta = "select * from " . $this->tabla . " {buscar} {orden} limit {inferior},{superior}";
$this->comandoConsulta = "select SQL_CALC_FOUND_ROWS * from " . $this->tabla . " {buscar} {orden} limit {inferior},{superior}";
}
}
private function cabeceraTabla() {
private function cabeceraTabla()
{
//$salida = '<p align="center"><table border=1 class="tablaDatos"><tbody>';
$salida = '<p align="center"><table border=1 class="table table-striped table-bordered table-condensed table-hover"><tbody>';
foreach ($this->campos as $clave => $datos) {
@@ -444,7 +495,10 @@ class Mantenimiento {
$clave = str_ireplace("ubicacion", "Ubicaci&oacute;n", $clave);
$clave = str_ireplace("articulo", "Art&iacute;culo", $clave);
if ($ordenable) {
$salida.="<th><b><a title=\"Establece orden por $clave \" href=\"$this->url&orden=" . strtolower($clave2) . "\"> " . ucfirst($clave) . " </a></b></th>\n";
$this->backupURL();
$this->datosURL['orden'] = $clave2;
$salida.="<th><b><a title=\"Establece orden por $clave \" href=\"". $this->montaURL() . "\"> " . ucfirst($clave) . " </a></b></th>\n";
$this->restoreURL();
} else {
$salida.='<th><b>' . ucfirst($clave) . '</b></th>' . "\n";
}
@@ -456,14 +510,26 @@ class Mantenimiento {
/**
*
* @param string $accion URL de la acción del POST
* @param string $tipo ANADIR,EDITAR,BORRADO
* @param string $tipo ANADIR,EDICION,BORRADO
* @param array $datos Vector con los datos del registro
* @return array lista de campos y formulario de entrada
*/
private function formularioCampos($accion, $tipo, $datos) {
private function formularioCampos($tipo, $datos)
{
$modo = $tipo == BORRADO ? "readonly" : "";
$nfechas = 0;
switch ($tipo) {
case ANADIR:
$this->datosURL['opc'] = "insertar"; $this->datosURL['id'] = null;
break;
case EDICION:
$this->datosURL['opc'] = "modificar";
break;
case BORRADO:
$this->datosURL['opc'] = "borrar";
break;
}
$accion = $this->montaURL();
$salida.='<div class="col-sm-8"><form name="mantenimiento.form" class="form-horizontal" role="form" method="post" action="' . $accion . '">' . "\n";
$salida.="<fieldset style=\"width: 96%;\"><p><legend style=\"color: red;\"><b>$tipo</b></legend>\n";
foreach ($this->campos as $clave => $valor) {
@@ -487,7 +553,7 @@ class Mantenimiento {
$tipoCampo = $valor['Type'];
//Si es un campo fecha u hora y está insertando pone la fecha actual o la hora actual
if ($tipo == ANADIR) {
if (stripos($tipoCampo, "echa")<>0 || stripos($tipoCampo, "ate")<>0) {
if (stripos($tipoCampo, "echa") <> 0 || stripos($tipoCampo, "ate") <> 0) {
$valorDato = strftime("%Y/%m/%d");
}
}
@@ -497,9 +563,6 @@ class Mantenimiento {
$tamano = "19";
$tipo_campo = "datetime";
$nfechas++;
//
//Prueba
//
$salida .= '<div class="input-group date" id="datetimepicker' . $nfechas . '">
<input type="text" name="' . $campo . '" data-format="YYYY/MM/DD" value="' . $valorDato . '" ' . $modoEfectivo . ' class="form-control" />
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span>
@@ -524,7 +587,6 @@ class Mantenimiento {
}
if ($tipoCampo == "Boolean(1)") {
$checked = $valorDato == '1' ? 'checked' : '';
//$salida .= '<div class="checkbox">';
$modocheck = $modoEfectivo == "readonly" ? 'onclick="javascript: return false;" readonly ' : '';
$salida .= '<input type="checkbox" name="' . $campo . '" ' . $checked . ' ' . $modocheck . ' class="form-control">';
$salida .= '</div></div>';
@@ -543,21 +605,33 @@ class Mantenimiento {
$salida .= '<input name="listacampos" type="hidden" value="' . $campos . "\">\n";
$salida .= "</fieldset><p>";
$salida .= '<center>';
$salida .= '<button type="button" onClick="location.href=' . "'$this->url'" . '" class="btn btn-info">Volver</button>';
$this->datosURL['opc'] = 'inicial';
$salida .= '<button type="button" onClick="location.href=' . "'" . $this->montaURL() . "'" . '" class="btn btn-info">Volver</button>';
$salida .= '&nbsp;&nbsp;<button type="reset" class="btn btn-danger">Cancelar</button>';
$salida .= '&nbsp;&nbsp;<button type=submit class="btn btn-primary">Aceptar</button>';
$salida .= '<br></center></div>';
return $salida;
}
protected function errorBD($comando, $mensaje = "") {
if (!$mensaje) {
return "<h1>No pudo ejecutar correctamente el comando $comando error=" . $this->bdd->mensajeError() . " </h1>";
protected function errorBD($comando, $texto = "", $tipo = "danger", $cabecera = "&iexcl;Atenci&oacute;n!")
{
if (!$texto) {
$texto = "No pudo ejecutar correctamente el comando $comando error=" . $this->bdd->mensajeError();
} else {
return "<h1>$mensaje error=" . $this->bdd->mensajeError() . "</h1>";
$texto = "$texto error=" . $this->bdd->mensajeError();
}
return $this->panelMensaje($texto, "danger", $cabecera="&iexcl;Error!");
}
private function panelMensaje($info, $tipo = "danger", $cabecera = "&iexcl;Atenci&oacute;n!") {
$mensaje = '<div class="panel panel-' . $tipo . '"><div class="panel-heading">';
$mensaje .= '<h3 class="panel-title">' . $cabecera . '</h3></div>';
$mensaje .= '<div class="panel-body">';
$mensaje .= $info;
$mensaje .= '</div>';
$mensaje .= '</div>';
return $mensaje;
}
}
?>

16
Sql.php
View File

@@ -152,6 +152,22 @@ class Sql {
public function numeroTuplas() {
return $this->numero;
}
/**
* Devuelve el número de tuplas total si se ha hecho una consulta select
* con SELECT SQL_CALC_FOUND_ROWS * ...
* @return integer Número de tuplas.
*/
public function numeroTotalTuplas()
{
$comando = "select found_rows();";
if (!$peticion=$this->bdd->query($comando)) {
$this->error=true;
$this->mensajeError='No pudo ejecutar la petici&oacute;n: '.$comando;
return false;
}
$numero = $peticion->fetch_row();
return $numero[0] ;
}
/**
* Devuelve la condición de error de la última petición
* @return boolean condición de error.

View File

@@ -22,10 +22,10 @@
*/
define('AUTOR','Ricardo Montañana Gómez');
define('SERVIDOR','localhost'); //Ubicación del servidor MySQL
define('BASEDATOS','Inventario4'); //Nombre de la base de datos.
define('BASEDATOS','Inventario2'); //Nombre de la base de datos.
define('USUARIO','test'); //Usuario con permisos de lectura/escritura en la base de datos
define('CLAVE','tset'); //contraseña del usuario.
define('VERSION','1.02');
define('VERSION','1.03');
define('PROGRAMA','Gesti&oacute;n de Inventario.');
define('CENTRO','I.E.S.O. Pascual Serrano');
define('APLICACION',PROGRAMA.VERSION);

View File

@@ -1,3 +0,0 @@
<?
phpinfo();
?>

View File

@@ -22,8 +22,8 @@
$host="localhost";
$baseAnt="Inventario";
$baseNueva="Inventario2";
$usuario="root";
$claveUsuario="galeote";
$usuario="test";
$claveUsuario="tset";
$probar=false;

View File

@@ -1,55 +0,0 @@
<?php
/**
* Test de la clase Sql
*/
include 'Sql.php';
$bd=new Sql("localhost","test","tset","Inventario2");
if ($bd->error()) {
die("Error al conectar\n");
}
if (!$bd->ejecuta("select * from Articulos limit 0,10")) {
die("No pudo ejecutar consulta. ".$bd->mensajeError()."\n");
}
echo "Hay ".$bd->numeroTuplas()." registros.<br>\n";
while ($datos=$bd->procesaResultado()) {
foreach($datos as $clave => $valor) {
echo "[$clave]=[$valor] ";
}
echo "<br>\n";
}
$datos=$bd->estructura("Elementos");
for ($i=0;$i<count($datos);$i++) {
$campos[$datos[$i]["Field"]]=$datos[$i];
}
//print_r($datos);
echo "Hay ".count($campos)." tuplas.";
foreach($campos as $clave => $valor) {
$trozos=explode(",",$valor["Comment"]);
//echo "Trozos=";print_r($trozos);//print_r($campos);
foreach($trozos as $trozo) {
if (strstr($trozo,"foreign")) {
$temp=substr($trozo,8,-1);
list($tabla,$atributo)=explode(";",$temp);
$salida[$clave]=$tabla.",".$atributo;
echo "[$clave],[$tabla],[$atributo]<br>\n";
$existen=true;
}
}
}
/*for ($i=0;$i<count($datos);$i++) {
echo $datos[$i]["Field"]."<br>";
/*foreach($datos[$i] as $clave => $valor) {
echo "[$clave]=[$valor] ";
}
echo "<br>\n";
}*/
if ($bd->error()) {
echo $bd->mensajeError();
}
?>

View File

@@ -1,118 +0,0 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
// Timer Bar - Version 1.0
// Author: Brian Gosselin of http://scriptasylum.com
// Script featured on http://www.dynamicdrive.com
var loadedcolor='darkgray' ; // PROGRESS BAR COLOR
var unloadedcolor='lightgrey'; // COLOR OF UNLOADED AREA
var bordercolor='navy'; // COLOR OF THE BORDER
var barheight=15; // HEIGHT OF PROGRESS BAR IN PIXELS
var barwidth=300; // WIDTH OF THE BAR IN PIXELS
var waitTime=5; // NUMBER OF SECONDS FOR PROGRESSBAR
// THE FUNCTION BELOW CONTAINS THE ACTION(S) TAKEN ONCE BAR REACHES 100%.
// IF NO ACTION IS DESIRED, TAKE EVERYTHING OUT FROM BETWEEN THE CURLY BRACES ({})
// BUT LEAVE THE FUNCTION NAME AND CURLY BRACES IN PLACE.
// PRESENTLY, IT IS SET TO DO NOTHING, BUT CAN BE CHANGED EASILY.
// TO CAUSE A REDIRECT TO ANOTHER PAGE, INSERT THE FOLLOWING LINE:
// window.location="http://redirect_page.html";
// JUST CHANGE THE ACTUAL URL OF COURSE :)
// @todo prueba
/**
*@todo prueba
*TODO prueba
*@todo: prueba
*/
var action=function()
{
alert("Welcome to Dynamic Drive!");
//window.location="http://www.dynamicdrive.com
}
//*****************************************************//
//********** DO NOT EDIT BEYOND THIS POINT **********//
//*****************************************************//
var ns4=(document.layers)?true:false;
var ie4=(document.all)?true:false;
var blocksize=(barwidth-2)/waitTime/10;
var loaded=0;
var PBouter;
var PBdone;
var PBbckgnd;
var Pid=0;
var txt='';
if(ns4){
txt+='<table border=0 cellpadding=0 cellspacing=0><tr><td>';
txt+='<ilayer name="PBouter" visibility="hide" height="'+barheight+'" width="'+barwidth+'" onmouseup="hidebar()">';
txt+='<layer width="'+barwidth+'" height="'+barheight+'" bgcolor="'+bordercolor+'" top="0" left="0"></layer>';
txt+='<layer width="'+(barwidth-2)+'" height="'+(barheight-2)+'" bgcolor="'+unloadedcolor+'" top="1" left="1"></layer>';
txt+='<layer name="PBdone" width="'+(barwidth-2)+'" height="'+(barheight-2)+'" bgcolor="'+loadedcolor+'" top="1" left="1"></layer>';
txt+='</ilayer>';
txt+='</td></tr></table>';
}else{
txt+='<div id="PBouter" onmouseup="hidebar()" style="position:relative; visibility:hidden; background-color:'+bordercolor+'; width:'+barwidth+'px; height:'+barheight+'px;">';
txt+='<div style="position:absolute; top:1px; left:1px; width:'+(barwidth-2)+'px; height:'+(barheight-2)+'px; background-color:'+unloadedcolor+'; font-size:1px;"></div>';
txt+='<div id="PBdone" style="position:absolute; top:1px; left:1px; width:0px; height:'+(barheight-2)+'px; background-color:'+loadedcolor+'; font-size:1px;"></div>';
txt+='</div>';
}
document.write(txt);
function incrCount(){
window.status="Loading...";
loaded++;
if(loaded<0)loaded=0;
if(loaded>=waitTime*10){
clearInterval(Pid);
loaded=waitTime*10;
setTimeout('hidebar()',100);
}
resizeEl(PBdone, 0, blocksize*loaded, barheight-2, 0);
}
function hidebar(){
clearInterval(Pid);
window.status='';
//if(ns4)PBouter.visibility="hide";
//else PBouter.style.visibility="hidden";
action();
}
//THIS FUNCTION BY MIKE HALL OF BRAINJAR.COM
function findlayer(name,doc){
var i,layer;
for(i=0;i<doc.layers.length;i++){
layer=doc.layers[i];
if(layer.name==name)return layer;
if(layer.document.layers.length>0)
if((layer=findlayer(name,layer.document))!=null)
return layer;
}
return null;
}
function progressBarInit(){
PBouter=(ns4)?findlayer('PBouter',document):(ie4)?document.all['PBouter']:document.getElementById('PBouter');
PBdone=(ns4)?PBouter.document.layers['PBdone']:(ie4)?document.all['PBdone']:document.getElementById('PBdone');
resizeEl(PBdone,0,0,barheight-2,0);
if(ns4)PBouter.visibility="show";
else PBouter.style.visibility="visible";
Pid=setInterval('incrCount()',95);
}
function resizeEl(id,t,r,b,l){
if(ns4){
id.clip.left=l;
id.clip.top=t;
id.clip.right=r;
id.clip.bottom=b;
}else id.style.width=r+'px';
}
window.onload=progressBarInit;

View File

@@ -2,7 +2,7 @@
<Mantenimiento>
<Titulo>Mantenimiento de Elementos</Titulo>
<Consulta>
SELECT E.id as id,U.Descripcion as ubicacion,A.Descripcion as articulo,A.Marca as marca,A.Modelo as modelo,E.numserie as numserie,
SELECT SQL_CALC_FOUND_ROWS E.id as id,U.Descripcion as ubicacion,A.Descripcion as articulo,A.Marca as marca,A.Modelo as modelo,E.numserie as numserie,
DATE_FORMAT(E.fechacompra, '%d/%m/%Y') as fechaCompra,E.cantidad as cantidad
FROM Elementos E inner join Articulos A on E.id_articulo=A.id inner join
Ubicaciones U on E.id_ubicacion=U.id {buscar} {orden} limit {inferior},{superior};

View File

@@ -2,7 +2,7 @@
<Mantenimiento>
<Titulo>Mantenimiento de Usuarios</Titulo>
<Consulta>
SELECT id, nombre, clave, idSesion, alta, modificacion, borrado, consulta, informe, usuarios, config
SELECT SQL_CALC_FOUND_ROWS id, nombre, clave, idSesion, alta, modificacion, borrado, consulta, informe, usuarios, config
FROM Usuarios {buscar} {orden} limit {inferior}, {superior};
</Consulta>
<Campos>