예제 #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!");
         }
     }
 }
예제 #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 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!");
             }
         }
     }
 }
예제 #4
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 . "!");
             }
         }
     }
 }
예제 #5
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!");
                 }
             }
         }
     }
 }
 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!");
             }
         }
     }
 }
예제 #10
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 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!");
             }
         }
     }
 }