protected function private_core()
 {
     $this->share_extensions();
     $this->cliente = FALSE;
     $this->resultados = array();
     /// recibimos el código del cliente
     if (isset($_REQUEST['cod']) and !empty($_REQUEST['cod'])) {
         $cli0 = new cliente();
         $this->cliente = $cli0->get($_REQUEST['cod']);
     }
     $this->observaciones = '';
     if (isset($_REQUEST['observaciones'])) {
         $this->observaciones = $_REQUEST['observaciones'];
     }
     $this->offset = 0;
     if (isset($_REQUEST['offset'])) {
         $this->offset = $_REQUEST['offset'];
     }
     if ($this->cliente) {
         $lineafacturacli = new linea_factura_cliente();
         $this->resultados = $lineafacturacli->search_from_cliente2($this->cliente->codcliente, $this->query, $this->observaciones, $this->offset);
     }
 }
 public function __construct($l = FALSE)
 {
     parent::__construct('lineasfacturascli');
     if (!isset(self::$facturas)) {
         self::$facturas = array();
     }
     if (!isset(self::$albaranes)) {
         self::$albaranes = array();
     }
     if ($l) {
         $this->idlinea = $this->intval($l['idlinea']);
         $this->idfactura = $this->intval($l['idfactura']);
         $this->idalbaran = $this->intval($l['idalbaran']);
         $this->referencia = $l['referencia'];
         $this->descripcion = $l['descripcion'];
         $this->cantidad = floatval($l['cantidad']);
         $this->pvpunitario = floatval($l['pvpunitario']);
         $this->pvpsindto = floatval($l['pvpsindto']);
         $this->dtopor = floatval($l['dtopor']);
         $this->dtolineal = floatval($l['dtolineal']);
         $this->pvptotal = floatval($l['pvptotal']);
         $this->codimpuesto = $l['codimpuesto'];
         $this->iva = floatval($l['iva']);
         $this->recargo = floatval($l['recargo']);
         $this->irpf = floatval($l['irpf']);
     } else {
         $this->idlinea = NULL;
         $this->idfactura = NULL;
         $this->idalbaran = NULL;
         $this->referencia = '';
         $this->descripcion = '';
         $this->cantidad = 0;
         $this->pvpunitario = 0;
         $this->pvpsindto = 0;
         $this->dtopor = 0;
         $this->dtolineal = 0;
         $this->pvptotal = 0;
         $this->codimpuesto = NULL;
         $this->iva = 0;
         $this->recargo = 0;
         $this->irpf = 0;
     }
 }
示例#3
0
 private function nueva_factura_cliente()
 {
     $continuar = TRUE;
     $cliente = $this->cliente->get($_POST['cliente']);
     if (!$cliente) {
         $this->new_error_msg('Cliente no encontrado.');
         $continuar = FALSE;
     }
     $almacen = $this->almacen->get($_POST['almacen']);
     if ($almacen) {
         $this->save_codalmacen($_POST['almacen']);
     } else {
         $this->new_error_msg('Almacén no encontrado.');
         $continuar = FALSE;
     }
     $eje0 = new ejercicio();
     $ejercicio = $eje0->get_by_fecha($_POST['fecha']);
     if (!$ejercicio) {
         $this->new_error_msg('Ejercicio no encontrado.');
         $continuar = FALSE;
     }
     $serie = $this->serie->get($_POST['serie']);
     if (!$serie) {
         $this->new_error_msg('Serie no encontrada.');
         $continuar = FALSE;
     }
     $forma_pago = $this->forma_pago->get($_POST['forma_pago']);
     if ($forma_pago) {
         $this->save_codpago($_POST['forma_pago']);
     } else {
         $this->new_error_msg('Forma de pago no encontrada.');
         $continuar = FALSE;
     }
     $divisa = $this->divisa->get($_POST['divisa']);
     if (!$divisa) {
         $this->new_error_msg('Divisa no encontrada.');
         $continuar = FALSE;
     }
     $factura = new factura_cliente();
     if ($this->duplicated_petition($_POST['petition_id'])) {
         $this->new_error_msg('Petición duplicada. Has hecho doble clic sobre el botón guardar
            y se han enviado dos peticiones. Mira en <a href="' . $factura->url() . '">Facturas</a>
            para ver si la factura se ha guardado correctamente.');
         $continuar = FALSE;
     }
     if ($continuar) {
         $factura->fecha = $_POST['fecha'];
         $factura->hora = $_POST['hora'];
         $factura->codalmacen = $almacen->codalmacen;
         $factura->codejercicio = $ejercicio->codejercicio;
         $factura->codserie = $serie->codserie;
         $factura->codpago = $forma_pago->codpago;
         $factura->coddivisa = $divisa->coddivisa;
         $factura->tasaconv = $divisa->tasaconv;
         if ($_POST['tasaconv'] != '') {
             $factura->tasaconv = floatval($_POST['tasaconv']);
         }
         $factura->codagente = $this->agente->codagente;
         $factura->observaciones = $_POST['observaciones'];
         $factura->numero2 = $_POST['numero2'];
         $factura->irpf = $serie->irpf;
         $factura->porcomision = $this->agente->porcomision;
         if ($forma_pago->genrecibos == 'Pagados') {
             $factura->pagada = TRUE;
         }
         $factura->vencimiento = Date('d-m-Y', strtotime($factura->fecha . ' ' . $forma_pago->vencimiento));
         $factura->codcliente = $cliente->codcliente;
         $factura->cifnif = $cliente->cifnif;
         $factura->nombrecliente = $cliente->razonsocial;
         $factura->ciudad = $_POST['ciudad'];
         $factura->codpais = $_POST['codpais'];
         $factura->codpostal = $_POST['codpostal'];
         $factura->direccion = $_POST['direccion'];
         $factura->provincia = $_POST['provincia'];
         if ($factura->save()) {
             $art0 = new articulo();
             $n = floatval($_POST['numlineas']);
             for ($i = 0; $i <= $n; $i++) {
                 if (isset($_POST['referencia_' . $i])) {
                     $linea = new linea_factura_cliente();
                     $linea->idfactura = $factura->idfactura;
                     $linea->descripcion = $_POST['desc_' . $i];
                     if (!$serie->siniva and $cliente->regimeniva != 'Exento') {
                         $imp0 = $this->impuesto->get_by_iva($_POST['iva_' . $i]);
                         if ($imp0) {
                             $linea->codimpuesto = $imp0->codimpuesto;
                             $linea->iva = floatval($_POST['iva_' . $i]);
                             $linea->recargo = floatval($_POST['recargo_' . $i]);
                         } else {
                             $linea->iva = floatval($_POST['iva_' . $i]);
                             $linea->recargo = floatval($_POST['recargo_' . $i]);
                         }
                     }
                     $linea->irpf = floatval($_POST['irpf_' . $i]);
                     $linea->pvpunitario = floatval($_POST['pvp_' . $i]);
                     $linea->cantidad = floatval($_POST['cantidad_' . $i]);
                     $linea->dtopor = floatval($_POST['dto_' . $i]);
                     $linea->pvpsindto = $linea->pvpunitario * $linea->cantidad;
                     $linea->pvptotal = floatval($_POST['neto_' . $i]);
                     $articulo = $art0->get($_POST['referencia_' . $i]);
                     if ($articulo) {
                         $linea->referencia = $articulo->referencia;
                     }
                     if ($linea->save()) {
                         if ($articulo and isset($_POST['stock'])) {
                             /// descontamos del stock
                             $articulo->sum_stock($factura->codalmacen, 0 - $linea->cantidad);
                         }
                         $factura->neto += $linea->pvptotal;
                         $factura->totaliva += $linea->pvptotal * $linea->iva / 100;
                         $factura->totalirpf += $linea->pvptotal * $linea->irpf / 100;
                         $factura->totalrecargo += $linea->pvptotal * $linea->recargo / 100;
                     } else {
                         $this->new_error_msg("¡Imposible guardar la linea con referencia: " . $linea->referencia);
                         $continuar = FALSE;
                     }
                 }
             }
             if ($continuar) {
                 /// redondeamos
                 $factura->neto = round($factura->neto, FS_NF0);
                 $factura->totaliva = round($factura->totaliva, FS_NF0);
                 $factura->totalirpf = round($factura->totalirpf, FS_NF0);
                 $factura->totalrecargo = round($factura->totalrecargo, FS_NF0);
                 $factura->total = $factura->neto + $factura->totaliva - $factura->totalirpf + $factura->totalrecargo;
                 if (abs(floatval($_POST['atotal']) - $factura->total) >= 0.02) {
                     $this->new_error_msg("El total difiere entre la vista y el controlador (" . $_POST['atotal'] . " frente a " . $factura->total . "). Debes informar del error.");
                     $factura->delete();
                 } else {
                     if ($factura->save()) {
                         $this->generar_asiento($factura);
                         $this->new_message("<a href='" . $factura->url() . "'>Factura</a> guardada correctamente.");
                         $this->new_change('Factura Cliente ' . $factura->codigo, $factura->url(), TRUE);
                         if ($_POST['redir'] == 'TRUE') {
                             header('Location: ' . $factura->url());
                         }
                     } else {
                         $this->new_error_msg("¡Imposible actualizar la <a href='" . $factura->url() . "'>Factura</a>!");
                     }
                 }
             } else {
                 if ($factura->delete()) {
                     $this->new_message("Factura eliminada correctamente.");
                 } else {
                     $this->new_error_msg("¡Imposible eliminar la <a href='" . $factura->url() . "'>Factura</a>!");
                 }
             }
         } else {
             $this->new_error_msg("¡Imposible guardar la Factura!");
         }
     }
 }
示例#4
0
 public function full_test($duplicados = TRUE)
 {
     $status = TRUE;
     /// comprobamos las líneas
     $neto = 0;
     $iva = 0;
     $irpf = 0;
     $recargo = 0;
     foreach ($this->get_lineas() as $l) {
         if (!$l->test()) {
             $status = FALSE;
         }
         $neto += $l->pvptotal;
         $iva += $l->pvptotal * $l->iva / 100;
         $irpf += $l->pvptotal * $l->irpf / 100;
         $recargo += $l->pvptotal * $l->recargo / 100;
     }
     $neto = round($neto, FS_NF0);
     $iva = round($iva, FS_NF0);
     $irpf = round($irpf, FS_NF0);
     $recargo = round($recargo, FS_NF0);
     $total = $neto + $iva - $irpf + $recargo;
     if (!$this->floatcmp($this->neto, $neto, FS_NF0, TRUE)) {
         $this->new_error_msg("Valor neto de " . FS_ALBARAN . " incorrecto. Valor correcto: " . $neto);
         $status = FALSE;
     } else {
         if (!$this->floatcmp($this->totaliva, $iva, FS_NF0, TRUE)) {
             $this->new_error_msg("Valor totaliva de " . FS_ALBARAN . " incorrecto. Valor correcto: " . $iva);
             $status = FALSE;
         } else {
             if (!$this->floatcmp($this->totalirpf, $irpf, FS_NF0, TRUE)) {
                 $this->new_error_msg("Valor totalirpf de " . FS_ALBARAN . " incorrecto. Valor correcto: " . $irpf);
                 $status = FALSE;
             } else {
                 if (!$this->floatcmp($this->totalrecargo, $recargo, FS_NF0, TRUE)) {
                     $this->new_error_msg("Valor totalrecargo de " . FS_ALBARAN . " incorrecto. Valor correcto: " . $recargo);
                     $status = FALSE;
                 } else {
                     if (!$this->floatcmp($this->total, $total, FS_NF0, TRUE)) {
                         $this->new_error_msg("Valor total de " . FS_ALBARAN . " incorrecto. Valor correcto: " . $total);
                         $status = FALSE;
                     } else {
                         if (!$this->floatcmp($this->totaleuros, $this->total * $this->tasaconv, FS_NF0, TRUE)) {
                             $this->new_error_msg("Valor totaleuros de " . FS_ALBARAN . " incorrecto.\n            Valor correcto: " . round($this->total * $this->tasaconv, FS_NF0));
                             $status = FALSE;
                         }
                     }
                 }
             }
         }
     }
     if ($this->total != 0) {
         /// comprobamos las facturas asociadas
         $linea_factura = new linea_factura_cliente();
         $facturas = $linea_factura->facturas_from_albaran($this->idalbaran);
         if ($facturas) {
             if (count($facturas) > 1) {
                 $msg = "Este " . FS_ALBARAN . " esta asociado a las siguientes facturas (y no debería):";
                 foreach ($facturas as $f) {
                     $msg .= " <a href='" . $f->url() . "'>" . $f->codigo . "</a>";
                 }
                 $this->new_error_msg($msg);
                 $status = FALSE;
             } else {
                 if ($facturas[0]->idfactura != $this->idfactura) {
                     $this->new_error_msg("Este " . FS_ALBARAN . " esta asociado a una <a href='" . $this->factura_url() . "'>factura</a> incorrecta. La correcta es <a href='" . $facturas[0]->url() . "'>esta</a>.");
                     $status = FALSE;
                 }
             }
         } else {
             if (isset($this->idfactura)) {
                 $this->new_error_msg("Este " . FS_ALBARAN . " esta asociado a una <a href='" . $this->factura_url() . "'>factura</a> incorrecta.");
                 $status = FALSE;
             }
         }
     }
     if ($status and $duplicados) {
         /// comprobamos si es un duplicado
         $albaranes = $this->db->select("SELECT * FROM " . $this->table_name . " WHERE fecha = " . $this->var2str($this->fecha) . "\n            AND codcliente = " . $this->var2str($this->codcliente) . " AND total = " . $this->var2str($this->total) . "\n            AND codagente = " . $this->var2str($this->codagente) . " AND numero2 = " . $this->var2str($this->numero2) . "\n            AND observaciones = " . $this->var2str($this->observaciones) . " AND idalbaran != " . $this->var2str($this->idalbaran) . ";");
         if ($albaranes) {
             foreach ($albaranes as $alb) {
                 /// comprobamos las líneas
                 $aux = $this->db->select("SELECT referencia FROM lineasalbaranescli WHERE\n                  idalbaran = " . $this->var2str($this->idalbaran) . "\n                  AND referencia NOT IN (SELECT referencia FROM lineasalbaranescli\n                  WHERE idalbaran = " . $this->var2str($alb['idalbaran']) . ");");
                 if (!$aux) {
                     $this->new_error_msg("Este " . FS_ALBARAN . " es un posible duplicado de\n                     <a href='index.php?page=ventas_albaran&id=" . $alb['idalbaran'] . "'>este otro</a>.\n                     Si no lo es, para evitar este mensaje, simplemente modifica las observaciones.");
                     $status = FALSE;
                 }
             }
         }
     }
     return $status;
 }
 private function generar_factura($albaranes)
 {
     $continuar = TRUE;
     $factura = new factura_cliente();
     $factura->automatica = TRUE;
     $factura->codalmacen = $albaranes[0]->codalmacen;
     $factura->coddivisa = $albaranes[0]->coddivisa;
     $factura->tasaconv = $albaranes[0]->tasaconv;
     $factura->codejercicio = $albaranes[0]->codejercicio;
     $factura->codpago = $albaranes[0]->codpago;
     $factura->codserie = $albaranes[0]->codserie;
     $factura->editable = FALSE;
     $factura->irpf = $albaranes[0]->irpf;
     $factura->numero2 = $albaranes[0]->numero2;
     $factura->observaciones = $albaranes[0]->observaciones;
     $factura->recfinanciero = $albaranes[0]->recfinanciero;
     /// comprobamos la forma de pago para saber si hay que marcar la factura como pagada
     $formapago = $this->forma_pago->get($factura->codpago);
     if ($formapago) {
         if ($formapago->genrecibos == 'Pagados') {
             $factura->pagada = TRUE;
         }
     }
     /// obtenemos los datos actuales del cliente, por si ha habido cambios
     $cliente = $this->cliente->get($albaranes[0]->codcliente);
     if ($cliente) {
         foreach ($cliente->get_direcciones() as $dir) {
             if ($dir->domfacturacion) {
                 $factura->apartado = $dir->apartado;
                 $factura->cifnif = $cliente->cifnif;
                 $factura->ciudad = $dir->ciudad;
                 $factura->codcliente = $cliente->codcliente;
                 $factura->coddir = $dir->id;
                 $factura->codpais = $dir->codpais;
                 $factura->codpostal = $dir->codpostal;
                 $factura->direccion = $dir->direccion;
                 $factura->nombrecliente = $cliente->nombrecomercial;
                 $factura->provincia = $dir->provincia;
                 break;
             }
         }
     }
     /// calculamos neto e iva
     foreach ($albaranes as $alb) {
         foreach ($alb->get_lineas() as $l) {
             $factura->neto += $l->pvptotal;
             $factura->totaliva += $l->pvptotal * $l->iva / 100;
             $factura->totalirpf += $l->pvptotal * $l->irpf / 100;
             $factura->totalrecargo += $l->pvptotal * $l->recargo / 100;
         }
     }
     /// redondeamos
     $factura->neto = round($factura->neto, FS_NF0);
     $factura->totaliva = round($factura->totaliva, FS_NF0);
     $factura->totalirpf = round($factura->totalirpf, FS_NF0);
     $factura->totalrecargo = round($factura->totalrecargo, FS_NF0);
     $factura->total = $factura->neto + $factura->totaliva - $factura->totalirpf + $factura->totalrecargo;
     /// asignamos la mejor fecha posible, pero dentro del ejercicio
     $ejercicio = new ejercicio();
     $eje0 = $ejercicio->get($factura->codejercicio);
     $factura->fecha = $eje0->get_best_fecha($factura->fecha);
     $regularizacion = new regularizacion_iva();
     if (!$eje0->abierto()) {
         $this->new_error_msg('El ejercicio ' . $eje0->codejercicio . ' está cerrado.');
     } else {
         if ($regularizacion->get_fecha_inside($factura->fecha)) {
             /*
              * comprobamos que la fecha de la factura no esté dentro de un periodo de
              * IVA regularizado.
              */
             $this->new_error_msg('El IVA de ese periodo ya ha sido regularizado. No se pueden añadir más facturas en esa fecha.');
         } else {
             if ($factura->save()) {
                 foreach ($albaranes as $alb) {
                     foreach ($alb->get_lineas() as $l) {
                         $n = new linea_factura_cliente();
                         $n->idalbaran = $alb->idalbaran;
                         $n->idfactura = $factura->idfactura;
                         $n->cantidad = $l->cantidad;
                         $n->codimpuesto = $l->codimpuesto;
                         $n->descripcion = $l->descripcion;
                         $n->dtolineal = $l->dtolineal;
                         $n->dtopor = $l->dtopor;
                         $n->irpf = $l->irpf;
                         $n->iva = $l->iva;
                         $n->pvpsindto = $l->pvpsindto;
                         $n->pvptotal = $l->pvptotal;
                         $n->pvpunitario = $l->pvpunitario;
                         $n->recargo = $l->recargo;
                         $n->referencia = $l->referencia;
                         if (!$n->save()) {
                             $continuar = FALSE;
                             $this->new_error_msg("¡Imposible guardar la línea el artículo " . $n->referencia . "! ");
                             break;
                         }
                     }
                 }
                 if ($continuar) {
                     foreach ($albaranes as $alb) {
                         $alb->idfactura = $factura->idfactura;
                         $alb->ptefactura = FALSE;
                         if (!$alb->save()) {
                             $this->new_error_msg("¡Imposible vincular el " . FS_ALBARAN . " con la nueva factura!");
                             $continuar = FALSE;
                             break;
                         }
                     }
                     if ($continuar) {
                         $this->generar_asiento($factura);
                     } else {
                         if ($factura->delete()) {
                             $this->new_error_msg("La factura se ha borrado.");
                         } else {
                             $this->new_error_msg("¡Imposible borrar la factura!");
                         }
                     }
                 } else {
                     if ($factura->delete()) {
                         $this->new_error_msg("La factura se ha borrado.");
                     } else {
                         $this->new_error_msg("¡Imposible borrar la factura!");
                     }
                 }
             } else {
                 $this->new_error_msg("¡Imposible guardar la factura!");
             }
         }
     }
 }
 private function nueva_factura_cliente()
 {
     $continuar = TRUE;
     $ejercicio = $this->ejercicio->get_by_fecha($_POST['fecha']);
     if (!$ejercicio) {
         $this->new_error_msg('Ejercicio no encontrado.');
         $continuar = FALSE;
     }
     $serie = $this->serie->get($_POST['serie']);
     if (!$serie) {
         $this->new_error_msg('Serie no encontrada.');
         $continuar = FALSE;
     }
     $forma_pago = $this->forma_pago->get($_POST['forma_pago']);
     if ($forma_pago) {
         $this->save_codpago($_POST['forma_pago']);
     } else {
         $this->new_error_msg('Forma de pago no encontrada.');
         $continuar = FALSE;
     }
     $divisa = $this->divisa->get($_POST['divisa']);
     if (!$divisa) {
         $this->new_error_msg('Divisa no encontrada.');
         $continuar = FALSE;
     }
     if (isset($_POST['imprimir_desc'])) {
         $this->imprimir_descripciones = TRUE;
         setcookie('imprimir_desc', TRUE, time() + FS_COOKIES_EXPIRE);
     } else {
         $this->imprimir_descripciones = FALSE;
         setcookie('imprimir_desc', FALSE, time() - FS_COOKIES_EXPIRE);
     }
     if (isset($_POST['imprimir_obs'])) {
         $this->imprimir_observaciones = TRUE;
         setcookie('imprimir_obs', TRUE, time() + FS_COOKIES_EXPIRE);
     } else {
         $this->imprimir_observaciones = FALSE;
         setcookie('imprimir_obs', FALSE, time() - FS_COOKIES_EXPIRE);
     }
     $factura = new factura_cliente();
     if ($this->duplicated_petition($_POST['petition_id'])) {
         $this->new_error_msg('Petición duplicada. Has hecho doble clic sobre el botón Guardar
            y se han enviado dos peticiones. Mira en <a href="' . $factura->url() . '">Facturas</a>
            para ver si la factura se ha guardado correctamente.');
         $continuar = FALSE;
     }
     if ($continuar) {
         $factura->fecha = $_POST['fecha'];
         $factura->codalmacen = $_POST['almacen'];
         $factura->codejercicio = $ejercicio->codejercicio;
         $factura->codserie = $serie->codserie;
         $factura->codpago = $forma_pago->codpago;
         $factura->coddivisa = $divisa->coddivisa;
         $factura->tasaconv = $divisa->tasaconv;
         if ($_POST['tasaconv'] != '') {
             $factura->tasaconv = floatval($_POST['tasaconv']);
         }
         $factura->codagente = $this->agente->codagente;
         $factura->observaciones = $_POST['observaciones'];
         $factura->numero2 = $_POST['numero2'];
         $factura->irpf = $serie->irpf;
         $factura->porcomision = $this->agente->porcomision;
         if ($forma_pago->genrecibos == 'Pagados') {
             $factura->pagada = TRUE;
         }
         $factura->vencimiento = Date('d-m-Y', strtotime($factura->fecha . ' ' . $forma_pago->vencimiento));
         foreach ($this->cliente_s->get_direcciones() as $d) {
             if ($d->domfacturacion) {
                 $factura->codcliente = $this->cliente_s->codcliente;
                 $factura->cifnif = $this->cliente_s->cifnif;
                 $factura->nombrecliente = $this->cliente_s->razonsocial;
                 $factura->apartado = $d->apartado;
                 $factura->ciudad = $d->ciudad;
                 $factura->coddir = $d->id;
                 $factura->codpais = $d->codpais;
                 $factura->codpostal = $d->codpostal;
                 $factura->direccion = $d->direccion;
                 $factura->provincia = $d->provincia;
                 break;
             }
         }
         if (is_null($factura->codcliente)) {
             $this->new_error_msg("No hay ninguna dirección asociada al cliente.");
         } else {
             if ($factura->save()) {
                 $n = floatval($_POST['numlineas']);
                 for ($i = 1; $i <= $n; $i++) {
                     if (isset($_POST['referencia_' . $i])) {
                         $articulo = $this->articulo->get($_POST['referencia_' . $i]);
                         if ($articulo) {
                             $linea = new linea_factura_cliente();
                             $linea->idfactura = $factura->idfactura;
                             $linea->referencia = $articulo->referencia;
                             $linea->descripcion = $_POST['desc_' . $i];
                             if (!$serie->siniva or $this->cliente_s->regimeniva != 'Exento') {
                                 $linea->codimpuesto = $articulo->codimpuesto;
                                 $linea->iva = floatval($_POST['iva_' . $i]);
                                 $linea->recargo = floatval($_POST['recargo_' . $i]);
                             }
                             $linea->irpf = floatval($_POST['irpf_' . $i]);
                             $linea->pvpunitario = floatval($_POST['pvp_' . $i]);
                             $linea->cantidad = floatval($_POST['cantidad_' . $i]);
                             $linea->dtopor = floatval($_POST['dto_' . $i]);
                             $linea->pvpsindto = $linea->pvpunitario * $linea->cantidad;
                             $linea->pvptotal = floatval($_POST['neto_' . $i]);
                             if ($linea->save()) {
                                 /// descontamos del stock
                                 $articulo->sum_stock($factura->codalmacen, 0 - $linea->cantidad);
                                 $factura->neto += $linea->pvptotal;
                                 $factura->totaliva += $linea->pvptotal * $linea->iva / 100;
                                 $factura->totalirpf += $linea->pvptotal * $linea->irpf / 100;
                                 $factura->totalrecargo += $linea->pvptotal * $linea->recargo / 100;
                             } else {
                                 $this->new_error_msg("¡Imposible guardar la linea con referencia: " . $linea->referencia);
                                 $continuar = FALSE;
                             }
                         } else {
                             $this->new_error_msg("Artículo no encontrado: " . $_POST['referencia_' . $i]);
                             $continuar = FALSE;
                         }
                     }
                 }
                 if ($continuar) {
                     /// redondeamos
                     $factura->neto = round($factura->neto, FS_NF0);
                     $factura->totaliva = round($factura->totaliva, FS_NF0);
                     $factura->totalirpf = round($factura->totalirpf, FS_NF0);
                     $factura->totalrecargo = round($factura->totalrecargo, FS_NF0);
                     $factura->total = $factura->neto + $factura->totaliva - $factura->totalirpf + $factura->totalrecargo;
                     if (abs(floatval($_POST['tpv_total2']) - $factura->total) >= 0.02) {
                         $this->new_error_msg("El total difiere entre la vista y el controlador (" . $_POST['tpv_total2'] . " frente a " . $factura->total . "). Debes informar del error.");
                         $factura->delete();
                     } else {
                         if ($factura->save()) {
                             $this->new_message("<a href='" . $factura->url() . "'>Factura</a> guardada correctamente.");
                             $this->generar_asiento($factura);
                             if ($_POST['regalo'] == 'TRUE') {
                                 $this->imprimir_ticket_regalo($factura);
                             } else {
                                 $this->imprimir_ticket($factura, floatval($_POST['num_tickets']));
                             }
                             /// actualizamos la caja
                             $this->caja->dinero_fin += $factura->total;
                             $this->caja->tickets += 1;
                             $this->caja->ip = $_SERVER['REMOTE_ADDR'];
                             if (!$this->caja->save()) {
                                 $this->new_error_msg("¡Imposible actualizar la caja!");
                             }
                         } else {
                             $this->new_error_msg("¡Imposible actualizar la <a href='" . $factura->url() . "'>factura</a>!");
                         }
                     }
                 } else {
                     if ($factura->delete()) {
                         $this->new_message("Factura eliminada correctamente.");
                     } else {
                         $this->new_error_msg("¡Imposible eliminar la <a href='" . $factura->url() . "'>factura</a>!");
                     }
                 }
             } else {
                 $this->new_error_msg("¡Imposible guardar la factura!");
             }
         }
     }
 }
 public function buscar_lineas()
 {
     /// cambiamos la plantilla HTML
     $this->template = 'ajax/ventas_lineas_facturas';
     $this->buscar_lineas = $_POST['buscar_lineas'];
     $linea = new linea_factura_cliente();
     if (isset($_POST['codcliente'])) {
         $this->lineas = $linea->search_from_cliente2($_POST['codcliente'], $this->buscar_lineas, $_POST['buscar_lineas_o']);
     } else {
         $this->lineas = $linea->search($this->buscar_lineas);
     }
 }
示例#8
0
 /**
  * Devulve las líneas de la factura.
  * @return linea_factura_cliente
  */
 public function get_lineas()
 {
     $linea = new linea_factura_cliente();
     return $linea->all_from_factura($this->idfactura);
 }
示例#9
0
 private function generar_factura_cliente($albaranes)
 {
     $continuar = TRUE;
     $factura = new factura_cliente();
     $factura->codagente = $albaranes[0]->codagente;
     $factura->codalmacen = $albaranes[0]->codalmacen;
     $factura->coddivisa = $albaranes[0]->coddivisa;
     $factura->tasaconv = $albaranes[0]->tasaconv;
     $factura->codpago = $albaranes[0]->codpago;
     $factura->codserie = $albaranes[0]->codserie;
     $factura->irpf = $albaranes[0]->irpf;
     $factura->numero2 = $albaranes[0]->numero2;
     $factura->observaciones = $albaranes[0]->observaciones;
     /// asignamos fecha y ejercicio usando la del albarán
     if ($_REQUEST['fecha'] == 'albaran') {
         $eje0 = $this->ejercicio->get($albaranes[0]->codejercicio);
         if ($eje0) {
             if ($eje0->abierto()) {
                 $factura->codejercicio = $albaranes[0]->codejercicio;
                 $factura->set_fecha_hora($albaranes[0]->fecha, $albaranes[0]->hora);
             }
         }
     }
     /**
      * Si se ha elegido fecha de hoy o no se ha podido usar la del albarán porque
      * el ejercicio estaba cerrado, asignamos ejercicio para hoy y usamos la mejor
      * fecha y hora.
      */
     if (is_null($factura->codejercicio)) {
         $eje0 = $this->ejercicio->get_by_fecha($factura->fecha);
         if ($eje0) {
             $factura->codejercicio = $eje0->codejercicio;
             $factura->set_fecha_hora($factura->fecha, $factura->hora);
         }
     }
     /// obtenemos los datos actuales del cliente, por si ha habido cambios
     $cliente = $this->cliente->get($albaranes[0]->codcliente);
     if ($cliente) {
         foreach ($cliente->get_direcciones() as $dir) {
             if ($dir->domfacturacion) {
                 $factura->apartado = $dir->apartado;
                 $factura->cifnif = $cliente->cifnif;
                 $factura->ciudad = $dir->ciudad;
                 $factura->codcliente = $cliente->codcliente;
                 $factura->coddir = $dir->id;
                 $factura->codpais = $dir->codpais;
                 $factura->codpostal = $dir->codpostal;
                 $factura->direccion = $dir->direccion;
                 $factura->nombrecliente = $cliente->razonsocial;
                 $factura->provincia = $dir->provincia;
                 break;
             }
         }
     }
     /// calculamos neto e iva
     foreach ($albaranes as $alb) {
         foreach ($alb->get_lineas() as $l) {
             $factura->neto += $l->pvptotal;
             $factura->totaliva += $l->pvptotal * $l->iva / 100;
             $factura->totalirpf += $l->pvptotal * $l->irpf / 100;
             $factura->totalrecargo += $l->pvptotal * $l->recargo / 100;
         }
     }
     /// redondeamos
     $factura->neto = round($factura->neto, FS_NF0);
     $factura->totaliva = round($factura->totaliva, FS_NF0);
     $factura->totalirpf = round($factura->totalirpf, FS_NF0);
     $factura->totalrecargo = round($factura->totalrecargo, FS_NF0);
     $factura->total = $factura->neto + $factura->totaliva - $factura->totalirpf + $factura->totalrecargo;
     /// comprobamos la forma de pago para saber si hay que marcar la factura como pagada
     $formapago = $this->forma_pago->get($factura->codpago);
     if ($formapago) {
         if ($formapago->genrecibos == 'Pagados') {
             $factura->pagada = TRUE;
         }
         $factura->vencimiento = Date('d-m-Y', strtotime($factura->fecha . ' ' . $formapago->vencimiento));
     }
     if (!$eje0) {
         $this->new_error_msg("Ningún ejercicio encontrado.");
     } else {
         if (!$eje0->abierto()) {
             $this->new_error_msg('El ejercicio ' . $eje0->codejercicio . ' está cerrado.');
         } else {
             if ($this->regularizacion->get_fecha_inside($factura->fecha)) {
                 /*
                  * comprobamos que la fecha de la factura no esté dentro de un periodo de
                  * IVA regularizado.
                  */
                 $this->new_error_msg('El IVA de ese periodo ya ha sido regularizado. No se pueden añadir más facturas en esa fecha.');
             } else {
                 if ($factura->save()) {
                     foreach ($albaranes as $alb) {
                         foreach ($alb->get_lineas() as $l) {
                             $n = new linea_factura_cliente();
                             $n->idalbaran = $alb->idalbaran;
                             $n->idfactura = $factura->idfactura;
                             $n->cantidad = $l->cantidad;
                             $n->codimpuesto = $l->codimpuesto;
                             $n->descripcion = $l->descripcion;
                             $n->dtopor = $l->dtopor;
                             $n->irpf = $l->irpf;
                             $n->iva = $l->iva;
                             $n->pvpsindto = $l->pvpsindto;
                             $n->pvptotal = $l->pvptotal;
                             $n->pvpunitario = $l->pvpunitario;
                             $n->recargo = $l->recargo;
                             $n->referencia = $l->referencia;
                             if (!$n->save()) {
                                 $continuar = FALSE;
                                 $this->new_error_msg("¡Imposible guardar la línea el artículo " . $n->referencia . "! ");
                                 break;
                             }
                         }
                     }
                     if ($continuar) {
                         foreach ($albaranes as $alb) {
                             $alb->idfactura = $factura->idfactura;
                             $alb->ptefactura = FALSE;
                             if (!$alb->save()) {
                                 $this->new_error_msg("¡Imposible vincular el " . FS_ALBARAN . " con la nueva factura!");
                                 $continuar = FALSE;
                                 break;
                             }
                         }
                         if ($continuar) {
                             $this->generar_asiento_cliente($factura);
                             $this->total++;
                         } else {
                             if ($factura->delete()) {
                                 $this->new_error_msg("La factura se ha borrado.");
                             } else {
                                 $this->new_error_msg("¡Imposible borrar la factura!");
                             }
                         }
                     } else {
                         if ($factura->delete()) {
                             $this->new_error_msg("La factura se ha borrado.");
                         } else {
                             $this->new_error_msg("¡Imposible borrar la factura!");
                         }
                     }
                 } else {
                     $this->new_error_msg("¡Imposible guardar la factura!");
                 }
             }
         }
     }
 }
示例#10
0
 private function generar_factura()
 {
     $factura = new factura_cliente();
     $factura->apartado = $this->albaran->apartado;
     $factura->cifnif = $this->albaran->cifnif;
     $factura->ciudad = $this->albaran->ciudad;
     $factura->codagente = $this->albaran->codagente;
     $factura->codalmacen = $this->albaran->codalmacen;
     $factura->codcliente = $this->albaran->codcliente;
     $factura->coddir = $this->albaran->coddir;
     $factura->coddivisa = $this->albaran->coddivisa;
     $factura->tasaconv = $this->albaran->tasaconv;
     $factura->codejercicio = $this->albaran->codejercicio;
     $factura->codpago = $this->albaran->codpago;
     $factura->codpais = $this->albaran->codpais;
     $factura->codpostal = $this->albaran->codpostal;
     $factura->codserie = $this->albaran->codserie;
     $factura->direccion = $this->albaran->direccion;
     $factura->neto = $this->albaran->neto;
     $factura->nombrecliente = $this->albaran->nombrecliente;
     $factura->observaciones = $this->albaran->observaciones;
     $factura->provincia = $this->albaran->provincia;
     $factura->total = $this->albaran->total;
     $factura->totaliva = $this->albaran->totaliva;
     $factura->numero2 = $this->albaran->numero2;
     $factura->irpf = $this->albaran->irpf;
     $factura->totalirpf = $this->albaran->totalirpf;
     $factura->totalrecargo = $this->albaran->totalrecargo;
     $factura->porcomision = $this->albaran->porcomision;
     /// comprobamos la forma de pago para saber si hay que marcar la factura como pagada
     $forma0 = new forma_pago();
     $formapago = $forma0->get($factura->codpago);
     if ($formapago) {
         if ($formapago->genrecibos == 'Pagados') {
             $factura->pagada = TRUE;
         }
         $factura->vencimiento = Date('d-m-Y', strtotime($factura->fecha . ' ' . $formapago->vencimiento));
     }
     /// asignamos la mejor fecha posible, pero dentro del ejercicio
     $eje0 = $this->ejercicio->get($factura->codejercicio);
     $factura->fecha = $eje0->get_best_fecha($factura->fecha);
     $regularizacion = new regularizacion_iva();
     if (!$eje0->abierto()) {
         $this->new_error_msg("El ejercicio está cerrado.");
     } else {
         if ($regularizacion->get_fecha_inside($factura->fecha)) {
             $this->new_error_msg("El IVA de ese periodo ya ha sido regularizado. No se pueden añadir más " . FS_FACTURAS . " en esa fecha.");
         } else {
             if ($factura->save()) {
                 $continuar = TRUE;
                 foreach ($this->albaran->get_lineas() as $l) {
                     $n = new linea_factura_cliente();
                     $n->idalbaran = $l->idalbaran;
                     $n->idfactura = $factura->idfactura;
                     $n->cantidad = $l->cantidad;
                     $n->codimpuesto = $l->codimpuesto;
                     $n->descripcion = $l->descripcion;
                     $n->dtopor = $l->dtopor;
                     $n->irpf = $l->irpf;
                     $n->iva = $l->iva;
                     $n->pvpsindto = $l->pvpsindto;
                     $n->pvptotal = $l->pvptotal;
                     $n->pvpunitario = $l->pvpunitario;
                     $n->recargo = $l->recargo;
                     $n->referencia = $l->referencia;
                     if (!$n->save()) {
                         $continuar = FALSE;
                         $this->new_error_msg("¡Imposible guardar la línea el artículo " . $n->referencia . "! ");
                         break;
                     }
                 }
                 if ($continuar) {
                     $this->albaran->idfactura = $factura->idfactura;
                     $this->albaran->ptefactura = FALSE;
                     if ($this->albaran->save()) {
                         $this->generar_asiento($factura);
                     } else {
                         $this->new_error_msg("¡Imposible vincular el " . FS_ALBARAN . " con la nueva " . FS_FACTURA . "!");
                         if ($factura->delete()) {
                             $this->new_error_msg("La factura se ha borrado.");
                         } else {
                             $this->new_error_msg("¡Imposible borrar la " . FS_FACTURA . "!");
                         }
                     }
                 } else {
                     if ($factura->delete()) {
                         $this->new_error_msg("La " . FS_FACTURA . " se ha borrado.");
                     } else {
                         $this->new_error_msg("¡Imposible borrar la " . FS_FACTURA . "!");
                     }
                 }
             } else {
                 $this->new_error_msg("¡Imposible guardar la " . FS_FACTURA . "!");
             }
         }
     }
 }
 private function generar_factura()
 {
     /*
      * Verificación de disponibilidad del Número de NCF para República Dominicana
      */
     //Obtenemos el tipo de comprobante a generar para el cliente
     $tipo_comprobante_d = $this->ncf_entidad_tipo->get($this->empresa->id, $this->albaran->codcliente, 'CLI');
     $tipo_comprobante = $tipo_comprobante_d->tipo_comprobante;
     if (strlen($this->albaran->cifnif) < 9 and $tipo_comprobante == '01') {
         return $this->new_error_msg('El cliente tiene un tipo de comprobante 01 pero no tiene Cédula o RNC Válido, por favor corrija esta información!');
     }
     //Con el codigo del almacen desde donde facturaremos generamos el número de NCF
     $numero_ncf = $this->ncf_rango->generate($this->empresa->id, $this->albaran->codalmacen, $tipo_comprobante, $this->albaran->codpago);
     if ($numero_ncf['NCF'] == 'NO_DISPONIBLE') {
         return $this->new_error_msg('No hay números NCF disponibles del tipo ' . $tipo_comprobante . ', el ' . FS_ALBARAN . ' no será facturado.');
     }
     $factura = new factura_cliente();
     $factura->apartado = $this->albaran->apartado;
     $factura->cifnif = $this->albaran->cifnif;
     $factura->ciudad = $this->albaran->ciudad;
     $factura->codagente = $this->albaran->codagente;
     $factura->codalmacen = $this->albaran->codalmacen;
     $factura->codcliente = $this->albaran->codcliente;
     $factura->coddir = $this->albaran->coddir;
     $factura->coddivisa = $this->albaran->coddivisa;
     $factura->tasaconv = $this->albaran->tasaconv;
     $factura->codpago = $this->albaran->codpago;
     $factura->codpais = $this->albaran->codpais;
     $factura->codpostal = $this->albaran->codpostal;
     $factura->codserie = $this->albaran->codserie;
     $factura->direccion = $this->albaran->direccion;
     $factura->neto = $this->albaran->neto;
     $factura->nombrecliente = $this->albaran->nombrecliente;
     $factura->observaciones = $this->albaran->observaciones;
     $factura->provincia = $this->albaran->provincia;
     $factura->envio_apartado = $this->albaran->envio_apartado;
     $factura->envio_apellidos = $this->albaran->envio_apellidos;
     $factura->envio_ciudad = $this->albaran->envio_ciudad;
     $factura->envio_codigo = $this->albaran->envio_codigo;
     $factura->envio_codpais = $this->albaran->envio_codpais;
     $factura->envio_codpostal = $this->albaran->envio_codpostal;
     $factura->envio_codtrans = $this->albaran->envio_codtrans;
     $factura->envio_direccion = $this->albaran->envio_direccion;
     $factura->envio_nombre = $this->albaran->envio_nombre;
     $factura->envio_provincia = $this->albaran->envio_provincia;
     $factura->total = $this->albaran->total;
     $factura->totaliva = $this->albaran->totaliva;
     $factura->numero2 = $numero_ncf['NCF'];
     $factura->irpf = $this->albaran->irpf;
     $factura->totalirpf = $this->albaran->totalirpf;
     $factura->totalrecargo = $this->albaran->totalrecargo;
     $factura->porcomision = $this->albaran->porcomision;
     if (is_null($factura->codagente)) {
         $factura->codagente = $this->user->codagente;
     }
     /// asignamos el ejercicio que corresponde a la fecha elegida
     $eje0 = $this->ejercicio->get_by_fecha($_REQUEST['facturar']);
     if ($eje0) {
         $factura->codejercicio = $eje0->codejercicio;
         $factura->set_fecha_hora($_REQUEST['facturar'], $factura->hora);
     }
     /// comprobamos la forma de pago para saber si hay que marcar la factura como pagada
     $forma0 = new forma_pago();
     $formapago = $forma0->get($factura->codpago);
     if ($formapago) {
         if ($formapago->genrecibos == 'Pagados') {
             $factura->pagada = TRUE;
         }
         $factura->vencimiento = Date('d-m-Y', strtotime($factura->fecha . ' ' . $formapago->vencimiento));
     }
     $regularizacion = new regularizacion_iva();
     if (!$eje0) {
         $this->new_error_msg("Ejercicio no encontrado o está cerrado.");
     } else {
         if (!$eje0->abierto()) {
             $this->new_error_msg("El ejercicio está cerrado.");
         } else {
             if ($regularizacion->get_fecha_inside($factura->fecha)) {
                 $this->new_error_msg("El " . FS_IVA . " de ese periodo ya ha sido regularizado. No se pueden añadir más facturas en esa fecha.");
             } else {
                 if ($factura->save()) {
                     $continuar = TRUE;
                     $ncf_controller = new helper_ncf();
                     $ncf_controller->guardar_ncf($this->empresa->id, $factura, $tipo_comprobante, $numero_ncf);
                     foreach ($this->albaran->get_lineas() as $l) {
                         $n = new linea_factura_cliente();
                         $n->idalbaran = $l->idalbaran;
                         $n->idfactura = $factura->idfactura;
                         $n->cantidad = $l->cantidad;
                         $n->codimpuesto = $l->codimpuesto;
                         $n->descripcion = $l->descripcion;
                         $n->dtopor = $l->dtopor;
                         $n->irpf = $l->irpf;
                         $n->iva = $l->iva;
                         $n->pvpsindto = $l->pvpsindto;
                         $n->pvptotal = $l->pvptotal;
                         $n->pvpunitario = $l->pvpunitario;
                         $n->recargo = $l->recargo;
                         $n->referencia = $l->referencia;
                         $n->orden = $l->orden;
                         $n->mostrar_cantidad = $l->mostrar_cantidad;
                         $n->mostrar_precio = $l->mostrar_precio;
                         if (!$n->save()) {
                             $continuar = FALSE;
                             $this->new_error_msg("¡Imposible guardar la línea el artículo " . $n->referencia . "! ");
                             break;
                         }
                     }
                     if ($continuar) {
                         $this->albaran->idfactura = $factura->idfactura;
                         $this->albaran->ptefactura = FALSE;
                         if ($this->albaran->save()) {
                             $this->generar_asiento($factura);
                         } else {
                             $this->new_error_msg("¡Imposible vincular el " . FS_ALBARAN . " con la nueva factura!");
                             if ($factura->delete()) {
                                 $this->new_error_msg("La factura se ha borrado.");
                             } else {
                                 $this->new_error_msg("¡Imposible borrar la factura!");
                             }
                         }
                     } else {
                         if ($factura->delete()) {
                             $this->new_error_msg("La factura se ha borrado.");
                         } else {
                             $this->new_error_msg("¡Imposible borrar la factura!");
                         }
                     }
                 } else {
                     $this->new_error_msg("¡Imposible guardar la factura!");
                 }
             }
         }
     }
 }
 private function nueva_factura_cliente()
 {
     $continuar = TRUE;
     $ejercicio = $this->ejercicio->get_by_fecha($_POST['fecha']);
     if (!$ejercicio) {
         $this->new_error_msg('Ejercicio no encontrado o está cerrado.');
         $continuar = FALSE;
     }
     $serie = $this->serie->get($_POST['serie']);
     if (!$serie) {
         $this->new_error_msg('Serie no encontrada.');
         $continuar = FALSE;
     }
     $forma_pago = $this->forma_pago->get($_POST['forma_pago']);
     if ($forma_pago) {
         $this->save_codpago($_POST['forma_pago']);
     } else {
         $this->new_error_msg('Forma de pago no encontrada.');
         $continuar = FALSE;
     }
     $divisa = $this->divisa->get($_POST['divisa']);
     if (!$divisa) {
         $this->new_error_msg('Divisa no encontrada.');
         $continuar = FALSE;
     }
     if (isset($_POST['imprimir_desc'])) {
         $this->imprimir_descripciones = TRUE;
         setcookie('imprimir_desc', TRUE, time() + FS_COOKIES_EXPIRE);
     } else {
         $this->imprimir_descripciones = FALSE;
         setcookie('imprimir_desc', FALSE, time() - FS_COOKIES_EXPIRE);
     }
     if (isset($_POST['imprimir_obs'])) {
         $this->imprimir_observaciones = TRUE;
         setcookie('imprimir_obs', TRUE, time() + FS_COOKIES_EXPIRE);
     } else {
         $this->imprimir_observaciones = FALSE;
         setcookie('imprimir_obs', FALSE, time() - FS_COOKIES_EXPIRE);
     }
     $factura = new factura_cliente();
     if ($this->duplicated_petition($_POST['petition_id'])) {
         $this->new_error_msg('Petición duplicada. Has hecho doble clic sobre el botón Guardar
            y se han enviado dos peticiones. Mira en <a href="' . $factura->url() . '">Facturas</a>
            para ver si la factura se ha guardado correctamente.');
         $continuar = FALSE;
     }
     if ($continuar) {
         $factura->codejercicio = $ejercicio->codejercicio;
         $factura->codserie = $serie->codserie;
         $factura->set_fecha_hora($_POST['fecha'], $factura->hora);
         $factura->codalmacen = $_POST['almacen'];
         $factura->codpago = $forma_pago->codpago;
         $factura->coddivisa = $divisa->coddivisa;
         $factura->tasaconv = $divisa->tasaconv;
         if ($_POST['tasaconv'] != '') {
             $factura->tasaconv = floatval($_POST['tasaconv']);
         }
         $factura->codagente = $this->agente->codagente;
         $factura->observaciones = $_POST['observaciones'];
         $factura->numero2 = $_POST['numero2'];
         $factura->porcomision = $this->agente->porcomision;
         if ($forma_pago->genrecibos == 'Pagados') {
             $factura->pagada = TRUE;
         }
         $factura->vencimiento = Date('d-m-Y', strtotime($factura->fecha . ' ' . $forma_pago->vencimiento));
         $factura->codcliente = $this->cliente_s->codcliente;
         $factura->cifnif = $_POST['cifnif'];
         $factura->nombrecliente = $_POST['nombrecliente'];
         $factura->ciudad = $this->empresa->ciudad;
         $factura->codpais = $this->empresa->codpais;
         $factura->codpostal = $this->empresa->codpostal;
         $factura->provincia = $this->empresa->provincia;
         foreach ($this->cliente_s->get_direcciones() as $d) {
             if ($d->domfacturacion) {
                 $factura->apartado = $d->apartado;
                 $factura->ciudad = $d->ciudad;
                 $factura->coddir = $d->id;
                 $factura->codpais = $d->codpais;
                 $factura->codpostal = $d->codpostal;
                 $factura->direccion = $d->direccion;
                 $factura->provincia = $d->provincia;
                 break;
             }
         }
         $regularizacion = new regularizacion_iva();
         if ($regularizacion->get_fecha_inside($factura->fecha)) {
             $this->new_error_msg("El " . FS_IVA . " de ese periodo ya ha sido regularizado." . " No se pueden añadir más facturas en esa fecha.");
         } else {
             if ($factura->save()) {
                 $n = floatval($_POST['numlineas']);
                 for ($i = 1; $i <= $n; $i++) {
                     if (isset($_POST['referencia_' . $i])) {
                         $articulo = $this->articulo->get($_POST['referencia_' . $i]);
                         if ($articulo) {
                             $linea = new linea_factura_cliente();
                             $linea->idfactura = $factura->idfactura;
                             $linea->referencia = $articulo->referencia;
                             $linea->descripcion = $_POST['desc_' . $i];
                             if (!$serie->siniva or $this->cliente_s->regimeniva != 'Exento') {
                                 $linea->codimpuesto = $articulo->codimpuesto;
                                 $linea->iva = floatval($_POST['iva_' . $i]);
                                 $linea->recargo = floatval($_POST['recargo_' . $i]);
                             }
                             $linea->irpf = floatval($_POST['irpf_' . $i]);
                             $linea->pvpunitario = floatval($_POST['pvp_' . $i]);
                             $linea->cantidad = floatval($_POST['cantidad_' . $i]);
                             $linea->dtopor = floatval($_POST['dto_' . $i]);
                             $linea->pvpsindto = $linea->pvpunitario * $linea->cantidad;
                             $linea->pvptotal = floatval($_POST['neto_' . $i]);
                             if ($linea->save()) {
                                 /// descontamos del stock
                                 $articulo->sum_stock($factura->codalmacen, 0 - $linea->cantidad);
                                 $factura->neto += $linea->pvptotal;
                                 $factura->totaliva += $linea->pvptotal * $linea->iva / 100;
                                 $factura->totalirpf += $linea->pvptotal * $linea->irpf / 100;
                                 $factura->totalrecargo += $linea->pvptotal * $linea->recargo / 100;
                                 if ($linea->irpf > $factura->irpf) {
                                     $factura->irpf = $linea->irpf;
                                 }
                             } else {
                                 $this->new_error_msg("¡Imposible guardar la linea con referencia: " . $linea->referencia);
                                 $continuar = FALSE;
                             }
                         } else {
                             $this->new_error_msg("Artículo no encontrado: " . $_POST['referencia_' . $i]);
                             $continuar = FALSE;
                         }
                     }
                 }
                 if ($continuar) {
                     /// redondeamos
                     $factura->neto = round($factura->neto, FS_NF0);
                     $factura->totaliva = round($factura->totaliva, FS_NF0);
                     $factura->totalirpf = round($factura->totalirpf, FS_NF0);
                     $factura->totalrecargo = round($factura->totalrecargo, FS_NF0);
                     $factura->total = $factura->neto + $factura->totaliva - $factura->totalirpf + $factura->totalrecargo;
                     if (abs(floatval($_POST['tpv_total2']) - $factura->total) >= 0.02) {
                         $this->new_error_msg("El total difiere entre la vista y el controlador (" . $_POST['tpv_total2'] . " frente a " . $factura->total . "). Debes informar del error.");
                         $factura->delete();
                     } else {
                         if ($factura->save()) {
                             /*
                              * Luego de que todo este correcto generamos el NCF la Nota de Credito
                              */
                             $tipo_comprobante = $_POST['tipo_comprobante'];
                             $numero_ncf = $this->ncf_rango->generate($this->empresa->id, $this->terminal->codalmacen, $tipo_comprobante, $factura->codpago);
                             $ncf_controller = new helper_ncf();
                             if ($numero_ncf['NCF'] == $factura->numero2) {
                                 $ncf_controller->guardar_ncf($this->empresa->id, $factura, $tipo_comprobante, $numero_ncf);
                             } else {
                                 $this->new_error_msg('Ocurrió un error al actualizar el correlativo de NCF por favor informe al contador antes de seguir facturando. La factura se grabó con el NCF ' . $factura->numero2 . ' y el NCF segun el listado debió ser ' . $numero_ncf['NCF']);
                             }
                             $this->new_message("<a href='" . $factura->url() . "'>Factura</a> guardada correctamente.");
                             $this->generar_asiento($factura);
                             if ($_POST['regalo'] == 'TRUE') {
                                 $this->imprimir_ticket_regalo($factura);
                             } else {
                                 $this->imprimir_ticket($factura, floatval($_POST['num_tickets']));
                             }
                             /// actualizamos la caja
                             $this->caja->dinero_fin += $factura->total;
                             $this->caja->tickets += 1;
                             $this->caja->ip = $_SERVER['REMOTE_ADDR'];
                             if (!$this->caja->save()) {
                                 $this->new_error_msg("¡Imposible actualizar la caja!");
                             }
                         } else {
                             $this->new_error_msg("¡Imposible actualizar la <a href='" . $factura->url() . "'>factura</a>!");
                         }
                     }
                 } else {
                     if ($factura->delete()) {
                         $this->new_message("Factura eliminada correctamente.");
                     } else {
                         $this->new_error_msg("¡Imposible eliminar la <a href='" . $factura->url() . "'>factura</a>!");
                     }
                 }
             } else {
                 $this->new_error_msg("¡Imposible guardar la factura!");
             }
         }
     }
 }
 public function rectificar_factura()
 {
     /*
      * Verificación de disponibilidad del Número de NCF para Notas de Crédito
      */
     $tipo_comprobante = '04';
     $this->ncf_rango = new ncf_rango();
     $numero_ncf = $this->ncf_rango->generate($this->empresa->id, $this->factura->codalmacen, $tipo_comprobante, $this->factura->codpago);
     if ($numero_ncf['NCF'] == 'NO_DISPONIBLE') {
         return $this->new_error_msg('No hay números NCF disponibles del tipo ' . $tipo_comprobante . ', no se podrá generar la Nota de Crédito.' . $this->factura->idfactura);
     }
     $serie = $this->serie->get($_POST['codserie']);
     if (!$serie) {
         $this->new_error_msg('Serie no encontrada.');
         $continuar = FALSE;
     }
     $motivo = \filter_input(INPUT_POST, 'motivo');
     $motivo_anulacion = $this->ncf_tipo_anulacion->get($motivo);
     $monto0 = \filter_input(INPUT_POST, 'monto');
     $monto = $monto0 > 0 ? $monto0 * -1 : $monto0;
     $impuesto0 = \filter_input(INPUT_POST, 'codimpuesto');
     $impuesto = $impuesto0 > 0 ? $impuesto0 * -1 : $impuesto0;
     $monto_total = \filter_input(INPUT_POST, 'monto_total');
     $fecha = \filter_input(INPUT_POST, 'fecha');
     $irpf = 0;
     $recargo = 0;
     $factura = clone $this->factura;
     $factura->idfactura = NULL;
     $factura->numero = NULL;
     $factura->numero2 = $numero_ncf['NCF'];
     $factura->codigo = NULL;
     $factura->idasiento = NULL;
     $factura->idfacturarect = $this->factura->idfactura;
     $factura->codigorect = $this->factura->codigo;
     $factura->fecha = $fecha;
     $factura->neto = round($monto, FS_NF0);
     $factura->totaliva = round($monto * ($impuesto / 100), FS_NF0) * -1;
     $factura->totalirpf = round($irpf, FS_NF0);
     $factura->totalrecargo = round($recargo, FS_NF0);
     $factura->total = $factura->neto + $factura->totaliva - $factura->totalirpf + $factura->totalrecargo;
     $factura->observaciones = ucfirst(FS_FACTURA_RECTIFICATIVA) . " por rectificación contable de la " . ucfirst(FS_FACTURA) . ": " . $factura->codigorect;
     if ($factura->save()) {
         $linea = new linea_factura_cliente();
         $linea->idfactura = $factura->idfactura;
         $linea->descripcion = "Rectificación de importe";
         if (!$serie->siniva and $this->cliente->regimeniva != 'Exento') {
             $imp0 = $this->impuesto->get_by_iva($impuesto);
             $linea->codimpuesto = $imp0 ? $imp0->codimpuesto : NULL;
             $linea->iva = $impuesto > 0 ? floatval($impuesto) : floatval($impuesto * -1);
             $linea->recargo = floatval($recargo);
         }
         $linea->irpf = floatval($irpf);
         $linea->pvpunitario = $monto > 0 ? floatval($monto) : floatval($monto * -1);
         $linea->cantidad = -1;
         $linea->dtopor = 0;
         $linea->pvpsindto = $linea->pvpunitario * $linea->cantidad;
         $linea->pvptotal = floatval($monto);
         if ($linea->save()) {
             $factura->get_lineas_iva();
             /*
              * Grabación del Número de NCF para República Dominicana
              */
             //Con el codigo del almacen desde donde facturaremos generamos el número de NCF
             $ncf = new helper_ncf();
             $ncf->guardar_ncf($this->empresa->id, $factura, $tipo_comprobante, $numero_ncf, $motivo_anulacion->codigo . " " . $motivo_anulacion->descripcion);
             $this->generar_asiento($factura);
             $this->new_message("<a href='" . $factura->url() . "'>Factura</a> guardada correctamente con número NCF: " . $numero_ncf['NCF']);
             $this->new_change('Factura Cliente ' . $factura->codigo, $factura->url(), TRUE);
         }
     }
 }
 private function nueva_factura_cliente()
 {
     $continuar = TRUE;
     $cliente = $this->cliente->get($_POST['cliente']);
     if ($cliente) {
         $this->save_codcliente($cliente->codcliente);
     } else {
         $this->new_error_msg('Cliente no encontrado.');
         $continuar = FALSE;
     }
     $almacen = $this->almacen->get($_POST['almacen']);
     if ($almacen) {
         $this->save_codalmacen($almacen->codalmacen);
     } else {
         $this->new_error_msg('Almacén no encontrado.');
         $continuar = FALSE;
     }
     $eje0 = new ejercicio();
     $ejercicio = $eje0->get_by_fecha($_POST['fecha']);
     if ($ejercicio) {
         $this->save_codejercicio($ejercicio->codejercicio);
     } else {
         $this->new_error_msg('Ejercicio no encontrado.');
         $continuar = FALSE;
     }
     $serie = $this->serie->get($_POST['serie']);
     if (!$serie) {
         $this->new_error_msg('Serie no encontrada.');
         $continuar = FALSE;
     }
     $forma_pago = $this->forma_pago->get($_POST['forma_pago']);
     if ($forma_pago) {
         $this->save_codpago($forma_pago->codpago);
     } else {
         $this->new_error_msg('Forma de pago no encontrada.');
         $continuar = FALSE;
     }
     $divisa = $this->divisa->get($_POST['divisa']);
     if ($divisa) {
         $this->save_coddivisa($divisa->coddivisa);
     } else {
         $this->new_error_msg('Divisa no encontrada.');
         $continuar = FALSE;
     }
     $factura = new factura_cliente();
     if ($this->duplicated_petition($_POST['petition_id'])) {
         $this->new_error_msg('Petición duplicada. Has hecho doble clic sobre el botón guardar
            y se han enviado dos peticiones. Mira en <a href="' . $factura->url() . '">Facturas</a>
            para ver si la factura se ha guardado correctamente.');
         $continuar = FALSE;
     }
     if ($continuar) {
         $factura->fecha = $_POST['fecha'];
         $factura->codalmacen = $almacen->codalmacen;
         $factura->codejercicio = $ejercicio->codejercicio;
         $factura->codserie = $serie->codserie;
         $factura->codpago = $forma_pago->codpago;
         $factura->coddivisa = $divisa->coddivisa;
         $factura->tasaconv = $divisa->tasaconv;
         $factura->codagente = $this->agente->codagente;
         $factura->observaciones = $_POST['observaciones'];
         $factura->numero2 = $_POST['numero2'];
         $factura->irpf = $serie->irpf;
         $factura->porcomision = $this->agente->porcomision;
         foreach ($cliente->get_direcciones() as $d) {
             if ($d->domfacturacion) {
                 $factura->codcliente = $cliente->codcliente;
                 $factura->cifnif = $cliente->cifnif;
                 $factura->nombrecliente = $cliente->nombrecomercial;
                 $factura->apartado = $d->apartado;
                 $factura->ciudad = $d->ciudad;
                 $factura->coddir = $d->id;
                 $factura->codpais = $d->codpais;
                 $factura->codpostal = $d->codpostal;
                 $factura->direccion = $d->direccion;
                 $factura->provincia = $d->provincia;
                 break;
             }
         }
         if (is_null($factura->codcliente)) {
             $this->new_error_msg("No hay ninguna dirección asociada al cliente.");
         } else {
             if ($factura->save()) {
                 $art0 = new articulo();
                 $n = floatval($_POST['numlineas']);
                 for ($i = 0; $i <= $n; $i++) {
                     if (isset($_POST['referencia_' . $i])) {
                         $articulo = $art0->get($_POST['referencia_' . $i]);
                         if ($articulo) {
                             $linea = new linea_factura_cliente();
                             $linea->idfactura = $factura->idfactura;
                             $linea->referencia = $articulo->referencia;
                             $linea->descripcion = $_POST['desc_' . $i];
                             if (!$serie->siniva and $cliente->regimeniva != 'Exento') {
                                 $imp0 = $this->impuesto->get_by_iva($_POST['iva_' . $i]);
                                 if ($imp0) {
                                     $linea->codimpuesto = $imp0->codimpuesto;
                                     $linea->iva = floatval($_POST['iva_' . $i]);
                                     $linea->recargo = floatval($_POST['recargo_' . $i]);
                                 } else {
                                     $linea->iva = floatval($_POST['iva_' . $i]);
                                     $linea->recargo = floatval($_POST['recargo_' . $i]);
                                 }
                             }
                             if ($linea->iva > 0) {
                                 $linea->irpf = $factura->irpf;
                             }
                             $linea->pvpunitario = floatval($_POST['pvp_' . $i]);
                             $linea->cantidad = floatval($_POST['cantidad_' . $i]);
                             $linea->dtopor = 0;
                             $linea->pvpsindto = $linea->pvpunitario * $linea->cantidad;
                             $linea->pvptotal = floatval($_POST['total_' . $i]);
                             if ($linea->save()) {
                                 /// descontamos del stock
                                 $articulo->sum_stock($factura->codalmacen, 0 - $linea->cantidad);
                                 $factura->neto += $linea->pvptotal;
                                 $factura->totaliva += $linea->pvptotal * $linea->iva / 100;
                                 $factura->totalirpf += $linea->pvptotal * $linea->irpf / 100;
                                 $factura->totalrecargo += $linea->pvptotal * $linea->recargo / 100;
                             } else {
                                 $this->new_error_msg("¡Imposible guardar la linea con referencia: " . $linea->referencia);
                                 $continuar = FALSE;
                             }
                         } else {
                             $this->new_error_msg("Artículo no encontrado: " . $_POST['referencia_' . $i]);
                             $continuar = FALSE;
                         }
                     }
                 }
                 if ($continuar) {
                     /// redondeamos
                     $factura->neto = round($factura->neto, FS_NF0);
                     $factura->totaliva = round($factura->totaliva, FS_NF0);
                     $factura->totalirpf = round($factura->totalirpf, FS_NF0);
                     $factura->totalrecargo = round($factura->totalrecargo, FS_NF0);
                     $factura->total = $factura->neto + $factura->totaliva - $factura->totalirpf + $factura->totalrecargo;
                     if ($factura->save()) {
                         $this->new_message("<a href='" . $factura->url() . "'>Factura</a> guardada correctamente.");
                         $this->new_change('Factura Cliente ' . $factura->codigo, $factura->url(), TRUE);
                     } else {
                         $this->new_error_msg("¡Imposible actualizar la <a href='" . $factura->url() . "'>Factura</a>!");
                     }
                 } else {
                     if ($factura->delete()) {
                         $this->new_message("Factura eliminada correctamente.");
                     } else {
                         $this->new_error_msg("¡Imposible eliminar la <a href='" . $factura->url() . "'>Factura</a>!");
                     }
                 }
             } else {
                 $this->new_error_msg("¡Imposible guardar la Factura!");
             }
         }
     }
 }
 private function delete_factura()
 {
     $delete = \filter_input(INPUT_GET, 'delete');
     $fact = $this->factura->get($delete);
     $motivo = \filter_input(INPUT_POST, 'motivo');
     $fecha = \filter_input(INPUT_POST, 'fecha');
     $motivo_anulacion = $this->ncf_tipo_anulacion->get($motivo);
     if ($fact) {
         $albaranes = new albaran_cliente();
         /// ¿Sumamos stock?
         $art0 = new articulo();
         foreach ($fact->get_lineas() as $linea) {
             if (is_null($linea->idalbaran)) {
                 $articulo = $art0->get($linea->referencia);
                 if ($articulo) {
                     $articulo->sum_stock($fact->codalmacen, $linea->cantidad);
                 }
             } else {
                 $idalbaran = $linea->idalbaran;
             }
         }
         if ($idalbaran) {
             $albaran0 = $albaranes->get($idalbaran);
             $new_albaran = clone $albaran0;
             $new_albaran->idalbaran = null;
             $new_albaran->idfactura = null;
             $new_albaran->observaciones = ucfirst(FS_ALBARAN) . " " . $albaran0->codigo . " anulado por eliminación de la factura asociada " . $fact->codigo;
             $new_albaran->fecha = $fecha;
             $new_albaran->neto = $new_albaran->neto * -1;
             $new_albaran->total = $new_albaran->total * -1;
             $new_albaran->totaliva = $new_albaran->totaliva * -1;
             $new_albaran->hora = \date('H:i:s');
             if ($new_albaran->save()) {
                 $linea0 = new linea_albaran_cliente();
                 $new_albaran_lineas = $linea0->all_from_albaran($idalbaran);
                 foreach ($new_albaran_lineas as $linea) {
                     $linea->idalbaran = $new_albaran->idalbaran;
                     $linea->idfactura = null;
                     $linea->idlinea = null;
                     $linea->cantidad = $linea->cantidad * -1;
                     $linea->pvptotal = $linea->pvptotal * -1;
                     $linea->pvpsindto = $linea->pvpsindto * -1;
                     $linea->save();
                 }
             }
         }
         $ncf0 = $this->ncf_ventas->get_ncf($this->empresa->id, $fact->idfactura, $fact->codcliente);
         $ncf0->motivo = $motivo_anulacion->codigo . " " . $motivo_anulacion->descripcion;
         $ncf0->estado = FALSE;
         $ncf0->usuario_modificacion = $this->user->nick;
         $ncf0->fecha_modificacion = Date('d-m-Y H:i:s');
         if ($ncf0->anular()) {
             $asiento_factura = new asiento_factura();
             $asiento_factura->soloasiento = TRUE;
             $fact_rectifica = $fact->idfacturarect;
             $factrectifica = !empty($fact->idfacturarect) ? $fact_rectifica : 'NULL';
             $fact->idfacturarect = $ncf0->tipo_comprobante == '04' ? null : $fact->idfactura;
             if ($asiento_factura->generar_asiento_venta($fact)) {
                 $this->db->exec("UPDATE facturascli set observaciones = '" . ucfirst(FS_FACTURA) . " eliminada por: " . $motivo_anulacion->descripcion . "', anulada = true, pagada = true, neto = 0, total = 0, totalirpf = 0, totaleuros = 0, totaliva = 0, idfacturarect = " . $factrectifica . " where idfactura = " . $fact->idfactura . ";");
                 $this->db->exec("DELETE FROM lineasivafactcli where idfactura = " . $fact->idfactura);
                 $fact_lineas = new linea_factura_cliente();
                 $lineas_fact = $fact_lineas->all_from_factura($fact->idfactura);
                 foreach ($lineas_fact as $linea) {
                     $linea->delete();
                 }
                 $fact->get_lineas_iva();
                 $this->new_message("<a href='" . $asiento_factura->asiento->url() . "'>Asiento</a> reversado correctamente.");
             }
             $this->new_message("<a href='" . $fact->url() . "'>Factura</a> cambiada a estado anulada por error correctamente.");
         } else {
             $this->new_error_msg("¡Imposible eliminar la factura!");
         }
     } else {
         $this->new_error_msg("Factura no encontrada.");
     }
 }
 private function nueva_factura_cliente()
 {
     $continuar = TRUE;
     $cliente = $this->cliente->get($_POST['cliente']);
     if (!$cliente) {
         $this->new_error_msg('Cliente no encontrado.');
         $continuar = FALSE;
     }
     $almacen = $this->almacen->get($_POST['almacen']);
     if ($almacen) {
         $this->save_codalmacen($_POST['almacen']);
     } else {
         $this->new_error_msg('Almacén no encontrado.');
         $continuar = FALSE;
     }
     $eje0 = new ejercicio();
     $ejercicio = $eje0->get_by_fecha($_POST['fecha']);
     if (!$ejercicio) {
         $this->new_error_msg('Ejercicio no encontrado o está cerrado.');
         $continuar = FALSE;
     }
     $serie = $this->serie->get($_POST['serie']);
     if (!$serie) {
         $this->new_error_msg('Serie no encontrada.');
         $continuar = FALSE;
     }
     $forma_pago = $this->forma_pago->get($_POST['forma_pago']);
     if ($forma_pago) {
         $this->save_codpago($_POST['forma_pago']);
     } else {
         $this->new_error_msg('Forma de pago no encontrada.');
         $continuar = FALSE;
     }
     $divisa = $this->divisa->get($_POST['divisa']);
     if (!$divisa) {
         $this->new_error_msg('Divisa no encontrada.');
         $continuar = FALSE;
     }
     $factura = new factura_cliente();
     if ($this->duplicated_petition($_POST['petition_id'])) {
         $this->new_error_msg('Petición duplicada. Has hecho doble clic sobre el botón guardar
            y se han enviado dos peticiones. Mira en <a href="' . $factura->url() . '">Facturas</a>
            para ver si la factura se ha guardado correctamente.');
         $continuar = FALSE;
     }
     /*
      * Verificación de disponibilidad del Número de NCF para República Dominicana
      */
     //Obtenemos el tipo de comprobante a generar para el cliente
     $tipo_comprobante_d = $this->ncf_entidad_tipo->get($this->empresa->id, $cliente->codcliente, 'CLI');
     $tipo_comprobante = $tipo_comprobante_d->tipo_comprobante;
     //Con el codigo del almacen desde donde facturaremos generamos el número de NCF
     $numero_ncf = $this->ncf_rango->generate($this->empresa->id, $almacen->codalmacen, $tipo_comprobante, $cliente->codpago);
     if ($numero_ncf['NCF'] == 'NO_DISPONIBLE') {
         $continuar = FALSE;
         return $this->new_error_msg('No hay números NCF disponibles del tipo ' . $tipo_comprobante . ', no se podrá generar la Factura.');
     }
     if ($continuar) {
         $factura->codejercicio = $ejercicio->codejercicio;
         $factura->codserie = $serie->codserie;
         $factura->set_fecha_hora($_POST['fecha'], $_POST['hora']);
         $factura->codalmacen = $almacen->codalmacen;
         $factura->codpago = $forma_pago->codpago;
         $factura->coddivisa = $divisa->coddivisa;
         $factura->tasaconv = $divisa->tasaconv;
         if ($_POST['tasaconv'] != '') {
             $factura->tasaconv = floatval($_POST['tasaconv']);
         }
         $factura->codagente = $this->agente->codagente;
         $factura->observaciones = $_POST['observaciones'];
         $factura->numero2 = $numero_ncf['NCF'];
         $factura->porcomision = $this->agente->porcomision;
         if ($forma_pago->genrecibos == 'Pagados') {
             $factura->pagada = TRUE;
         }
         $factura->vencimiento = Date('d-m-Y', strtotime($factura->fecha . ' ' . $forma_pago->vencimiento));
         $factura->codcliente = $cliente->codcliente;
         $factura->cifnif = $_POST['cifnif'];
         $factura->nombrecliente = $_POST['nombrecliente'];
         $factura->codpais = $_POST['codpais'];
         $factura->provincia = $_POST['provincia'];
         $factura->ciudad = $_POST['ciudad'];
         $factura->codpostal = $_POST['codpostal'];
         $factura->direccion = $_POST['direccion'];
         $factura->apartado = $_POST['apartado'];
         /// envío
         $factura->envio_nombre = $_POST['envio_nombre'];
         $factura->envio_apellidos = $_POST['envio_apellidos'];
         if ($_POST['envio_codtrans'] != '') {
             $factura->envio_codtrans = $_POST['envio_codtrans'];
         }
         $factura->envio_codigo = $_POST['envio_codigo'];
         $factura->envio_codpais = $_POST['envio_codpais'];
         $factura->envio_provincia = $_POST['envio_provincia'];
         $factura->envio_ciudad = $_POST['envio_ciudad'];
         $factura->envio_codpostal = $_POST['envio_codpostal'];
         $factura->envio_direccion = $_POST['envio_direccion'];
         $factura->envio_apartado = $_POST['envio_apartado'];
         $regularizacion = new regularizacion_iva();
         if ($regularizacion->get_fecha_inside($factura->fecha)) {
             $this->new_error_msg("El " . FS_IVA . " de ese periodo ya ha sido regularizado. No se pueden añadir más facturas en esa fecha.");
         } else {
             if ($factura->save()) {
                 $art0 = new articulo();
                 $n = floatval($_POST['numlineas']);
                 for ($i = 0; $i <= $n; $i++) {
                     if (isset($_POST['referencia_' . $i])) {
                         $linea = new linea_factura_cliente();
                         $linea->idfactura = $factura->idfactura;
                         $linea->descripcion = $_POST['desc_' . $i];
                         if (!$serie->siniva and $cliente->regimeniva != 'Exento') {
                             $imp0 = $this->impuesto->get_by_iva($_POST['iva_' . $i]);
                             if ($imp0) {
                                 $linea->codimpuesto = $imp0->codimpuesto;
                                 $linea->iva = floatval($_POST['iva_' . $i]);
                                 $linea->recargo = floatval($_POST['recargo_' . $i]);
                             } else {
                                 $linea->iva = floatval($_POST['iva_' . $i]);
                                 $linea->recargo = floatval($_POST['recargo_' . $i]);
                             }
                         }
                         $linea->irpf = floatval($_POST['irpf_' . $i]);
                         $linea->pvpunitario = floatval($_POST['pvp_' . $i]);
                         $linea->cantidad = floatval($_POST['cantidad_' . $i]);
                         $linea->dtopor = floatval($_POST['dto_' . $i]);
                         $linea->pvpsindto = $linea->pvpunitario * $linea->cantidad;
                         $linea->pvptotal = floatval($_POST['neto_' . $i]);
                         $articulo = $art0->get($_POST['referencia_' . $i]);
                         if ($articulo) {
                             $linea->referencia = $articulo->referencia;
                         }
                         if ($linea->save()) {
                             if ($articulo and isset($_POST['stock'])) {
                                 /// descontamos del stock
                                 $articulo->sum_stock($factura->codalmacen, 0 - $linea->cantidad);
                             }
                             $factura->neto += $linea->pvptotal;
                             $factura->totaliva += $linea->pvptotal * $linea->iva / 100;
                             $factura->totalirpf += $linea->pvptotal * $linea->irpf / 100;
                             $factura->totalrecargo += $linea->pvptotal * $linea->recargo / 100;
                             if ($linea->irpf > $factura->irpf) {
                                 $factura->irpf = $linea->irpf;
                             }
                         } else {
                             $this->new_error_msg("¡Imposible guardar la linea con referencia: " . $linea->referencia);
                             $continuar = FALSE;
                         }
                     }
                 }
                 if ($continuar) {
                     /// redondeamos
                     $factura->neto = round($factura->neto, FS_NF0);
                     $factura->totaliva = round($factura->totaliva, FS_NF0);
                     $factura->totalirpf = round($factura->totalirpf, FS_NF0);
                     $factura->totalrecargo = round($factura->totalrecargo, FS_NF0);
                     $factura->total = $factura->neto + $factura->totaliva - $factura->totalirpf + $factura->totalrecargo;
                     if (abs(floatval($_POST['atotal']) - $factura->total) >= 0.02) {
                         $this->new_error_msg("El total difiere entre la vista y el controlador (" . $_POST['atotal'] . " frente a " . $factura->total . "). Debes informar del error.");
                         $factura->delete();
                     } else {
                         if ($factura->save()) {
                             /*
                              * Grabación del Número de NCF para República Dominicana
                              */
                             //Con el codigo del almacen desde donde facturaremos generamos el número de NCF
                             $numero_ncf = $this->ncf_rango->generate($this->empresa->id, $factura->codalmacen, $tipo_comprobante, $factura->codpago);
                             $ncf = new helper_ncf();
                             $ncf->guardar_ncf($this->empresa->id, $factura, $tipo_comprobante, $numero_ncf);
                             $this->generar_asiento($factura);
                             $this->new_message("<a href='" . $factura->url() . "'>Factura</a> guardada correctamente con número NCF: " . $numero_ncf['NCF']);
                             $this->new_change('Factura Cliente ' . $factura->codigo, $factura->url(), TRUE);
                             if ($_POST['redir'] == 'TRUE') {
                                 header('Location: ' . $factura->url());
                             }
                         } else {
                             $this->new_error_msg("¡Imposible actualizar la <a href='" . $factura->url() . "'>Factura</a>!");
                         }
                     }
                 } else {
                     if ($factura->delete()) {
                         $this->new_message("Factura eliminada correctamente.");
                     } else {
                         $this->new_error_msg("¡Imposible eliminar la <a href='" . $factura->url() . "'>Factura</a>!");
                     }
                 }
             } else {
                 $this->new_error_msg("¡Imposible guardar la Factura!");
             }
         }
     }
 }