. */ class Csv { /** * @var string Nombre del fichero csv */ private $nombre; /** * @var FILE manejador del fichero */ private $fichero = null; /** * @var xml conulta asociada a este fichero */ private $consulta; /** * @var database Controlador de la base de datos */ private $bdd; /** * @var int Número de registros en el fichero csv */ private $numRegistros; /** * @var array Cabecera del archivo csv */ private $cabecera; /** * @var array los datos del fichero csv en memoria */ private $datosFichero; /** * Indices a los campos correspondientes. */ private $idElemento; private $idArticulo; private $idUbicacion; private $fechaCompra; private $cantidad; private $cantidadReal; private $nSerie; /** * // El constructor necesita saber cuál es la opción actual. * /** * Constructor de la clase. * * @param BaseDatos $baseDatos Manejador de la base de datos */ public function __construct($baseDatos) { $this->bdd = $baseDatos; } /** * Crea un fichero csv con el nombre especificado. * * @param string $fichero Nombre del fichero */ public function crea($fichero) { $this->nombre = $fichero; $this->fichero = fopen($this->nombre, 'w') or die('No puedo abrir '.$this->nombre.' para escritura.'); } /** * @param array $datos escribe la línea en el archivo */ public function escribeLinea($datos) { fputcsv($this->fichero, $datos, ',', '"') or die('No puedo escribir en el fichero csv'); } public function __destruct() { $this->cierra(); } public function cierra() { fclose($this->fichero) or die('No puedo cerrar el archivo csv'); } /** * @param string $fichero Archivo xml que contiene la definición de la consulta */ public function ejecutaConsulta($fichero) { $consulta = simplexml_load_file($fichero) or die('No puedo cargar el fichero xml '.$fichero.' al csv'); // Escribe la cabecera del fichero $this->escribeLinea([$consulta->Pagina->Cabecera, $consulta->Titulo['id'], $consulta->Titulo['Texto']]); foreach ($consulta->Pagina->Cuerpo->Col as $campo) { $campos[] = $campo['Titulo']; } $this->escribeLinea($campos); // Escribe los datos de los campos $this->bdd->ejecuta($consulta->Datos->Consulta); while ($fila = $this->bdd->procesaResultado()) { $campos = []; foreach ($consulta->Pagina->Cuerpo->Col as $campo) { $campos[] = $fila[(string) $campo['Nombre']]; } $this->escribeLinea($campos); } } /** * @param string $ficheroCSV Nombre del archivo csv */ public function cargaCSV($ficheroCSV) { $this->nombre = $ficheroCSV; $this->fichero = fopen($this->nombre, 'r') or die('No puedo abrir el archivo '.$this->nombre.' para lectura.'); list($archivo, $idCabecera, $cabecera) = fgetcsv($this->fichero); while ($linea = fgetcsv($this->fichero)) { $datosFichero[] = $linea; } $this->cabecera[] = $archivo; $this->cabecera[] = $idCabecera; $this->cabecera[] = $cabecera; $this->datosFichero = $datosFichero; } /** * Muestra un resumen de los datos del fichero csv cargado por pantalla. */ public function resumen() { //$mensaje .= $mensaje = '

Archivo [inventario'.$this->cabecera[0].']

'; $mensaje .= '

id=['.$this->cabecera[1].'] Descripción=['.$this->cabecera[2].']


'; $mensaje .= ''; foreach ($this->datosFichero[0] as $campo) { $dato = $campo; $mensaje .= ""; } $mensaje .= ''; $mensaje .= ''; $this->cargaIndices($this->datosFichero[0]); //echo "$mensaje contar Datosfichero=[".count($datosFichero)."]"; for ($i = 1; $i < count($this->datosFichero); $i++) { $mensaje .= ''; $primero = true; foreach ($this->datosFichero[$i] as $dato) { if ($primero) { $primero = false; switch ($dato) { case 'S': $estado = '-Baja-'; $color = 'danger'; break; case 'Alta': $estado = '-Alta-'; $color = 'primary'; break; case 'N': $estado = $this->compruebaCantidades($i); if ($estado != 0) { $color = 'warning'; if ($estado > 0) { $estado = '+'.$estado; } } else { $estado = 'igual'; $color = 'info'; } break; default: throw new Exception("El archivo csv tiene un formato incorrecto.
Bajas=[$dato]"); } } $mensaje .= ''; } $mensaje .= ''; $mensaje .= ''; } $mensaje .= '
$datoAcción
'.$dato.'


'; $mensaje .= $this->panelMensaje('Si se produce cualquier error en el procesamiento del fichero, no se aplicará ningún cambio en la base de datos.'); $mensaje .= '
'; return $mensaje; } /** * @param $array línea de datos del fichero csv para comprobar las cantidades si se han modificado o no * * @return string */ private function compruebaCantidades($i) { //$ultimo = count($datos); return $this->datosFichero[$i][$this->cantidadReal] - $this->datosFichero[$i][$this->cantidad]; } private function panelMensaje($info, $tipo = 'danger', $cabecera = '¡Atención!') { $mensaje = '
'; $mensaje .= '

'.$cabecera.'

'; $mensaje .= '
'; $mensaje .= $info; $mensaje .= '
'; $mensaje .= '
'; return $mensaje; } private function escribeLog($comando) { $fp = fopen($this->nombre.'.log', 'a'); $linea = strftime('%Y/%m/%d').'|'.$this->nombre.'|'.$comando; fwrite($fp, $linea."\n"); fclose($fp); } private function bajaElemento($i) { $id = $this->datosFichero[$i][$this->idElemento]; $comando = 'delete from Elementos where id="'.$id.'";'; $this->escribeLog($comando); if (!$this->bdd->ejecuta($comando)) { throw new Exception('Baja-'.$this->bdd->mensajeError, $this->bdd->error); } } private function modificaElemento($i) { $id = $this->datosFichero[$i][$this->idElemento]; $comando = 'update Elementos set Cantidad='.$this->datosFichero[$i][$this->cantidadReal].' where id="'.$id.'";'; $this->escribeLog($comando); if (!$this->bdd->ejecuta($comando)) { throw new Exception('Modifica-'.$this->bdd->mensajeError, $this->bdd->error); } } private function altaElemento($i) { if ($this->cabecera[0] == 'Articulo') { $idUbicacion = $this->datosFichero[$i][$this->idUbicacion]; $idArticulo = $this->cabecera[1]; $comando = 'select id from Ubicaciones where Descripcion="'.$this->datosFichero[$i][$this->desUbicacion].'";'; } else { $idUbicacion = $this->cabecera[1]; $idArticulo = $this->datosFichero[$i][$this->idArticulo]; } $idArt = $datosFichero[$i]; $comando = 'insert into Elementos () values (null,'.$idArticulo.','.$idUbicacion.',"'.$this->datosFichero[$i][$this->nSerie]; $comando .= '",'.$this->datosFichero[$i][$this->cantidadReal].',"'.$this->datosFichero[$i][$this->fechaCompra].'");'; $this->escribeLog($comando); if (!$this->bdd->ejecuta($comando)) { throw new Exception('Alta-'.$this->bdd->mensajeError, $this->bdd->error); } } private function cargaIndices($campos) { for ($i = 0; $i < count($campos); $i++) { switch ($campos[$i]) { case 'Cant. Real': $this->cantidadReal = $i; break; case 'Fecha C.': $this->fechaCompra = $i; break; case 'idUbic': $this->idUbicacion = $i; break; case 'idArt': $this->idArticulo = $i; break; case 'idElem': $this->idElemento = $i; break; case 'Cantidad': $this->cantidad = $i; break; case 'N Serie': $this->nSerie = $i; break; } } //$this->EscribeFic("Cantreal=[$this->cantidadReal] fechacompra=[$this->fechaCompra] ubicacion=[$this->idUbicacion] articulo=[$this->idArticulo]"); //$this->EscribeFic("idElemento=[$this->idElemento] Cantidad=[$this->cantidad] nserie=[$this->nserie]"); } /** * Procesa contra la base de datos todas las acciones del archivo. */ public function ejecutaFichero() { $this->cargaIndices($this->datosFichero[0]); //Realiza una transacción para que no se ejecute parcialmente una actualización try { $this->bdd->comienzaTransaccion(); $acciones = 0; for ($i = 1; $i < count($this->datosFichero); $i++) { switch ($this->datosFichero[$i][0]) { case 'S': $this->bajaElemento($i); $acciones++; break; case 'Alta': $this->altaElemento($i); $acciones++; break; case 'N': if ($this->compruebaCantidades($i) != 0) { $this->modificaElemento($i); $acciones++; } break; default: throw new Exception('Acción no reconocida en la importacion ['.$this->datosFichero[0].']'); } } $mensaje = "Se han procesado correctamente $acciones acciones en la Base de Datos."; $this->bdd->confirmaTransaccion(); return $this->panelMensaje($mensaje, 'success', 'Información'); } catch (Exception $e) { $this->bdd->abortaTransaccion(); $mensaje = 'Se ha producido el error ['.$e->getMessage().']
NO se ha realizado ningún cambio en la Base de Datos.'; return $this->panelMensaje($mensaje); } } private function ejecutaFichero2() { echo ''; for ($i = 1; $i < 80; $i++) { //sleep(1); $progreso = $i; echo ''; //echo str_repeat(' ',1024*64); flush(); //echo '$(".bar").css("width", "'.$progreso.'");'; } } }