Exemplo n.º 1
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!");
         }
     }
 }
Exemplo n.º 2
0
 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!");
             }
         }
     }
 }
 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 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!");
             }
         }
     }
 }
 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!");
             }
         }
     }
 }