Ejemplo n.º 1
0
 private function nueva_factura_proveedor()
 {
     $continuar = TRUE;
     $proveedor = $this->proveedor->get($_POST['proveedor']);
     if (!$proveedor) {
         $this->new_error_msg('Proveedor 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_proveedor();
     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'], $_POST['hora']);
         $factura->codproveedor = $proveedor->codproveedor;
         $factura->nombre = $_POST['nombre'];
         $factura->cifnif = $_POST['cifnif'];
         $factura->codalmacen = $almacen->codalmacen;
         $factura->codpago = $forma_pago->codpago;
         $factura->coddivisa = $divisa->coddivisa;
         $factura->tasaconv = $divisa->tasaconv_compra;
         if ($_POST['tasaconv'] != '') {
             $factura->tasaconv = floatval($_POST['tasaconv']);
         }
         $factura->codagente = $this->agente->codagente;
         $factura->numproveedor = $_POST['numproveedor'];
         $factura->observaciones = $_POST['observaciones'];
         if ($forma_pago->genrecibos == 'Pagados') {
             $factura->pagada = TRUE;
         }
         $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_proveedor();
                         $linea->idfactura = $factura->idfactura;
                         $linea->descripcion = $_POST['desc_' . $i];
                         if (!$serie->siniva and $proveedor->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) {
                                 if (isset($_POST['costemedio'])) {
                                     if ($articulo->costemedio == 0) {
                                         $articulo->costemedio = $linea->pvptotal / $linea->cantidad;
                                     } else {
                                         $articulo->costemedio = $articulo->get_costemedio();
                                         if ($articulo->costemedio == 0) {
                                             $articulo->costemedio = $linea->pvptotal / $linea->cantidad;
                                         }
                                     }
                                     $this->actualizar_precio_proveedor($factura->codproveedor, $linea);
                                 }
                                 if (isset($_POST['stock'])) {
                                     $articulo->sum_stock($factura->codalmacen, $linea->cantidad);
                                 } else {
                                     if (isset($_POST['costemedio'])) {
                                         $articulo->save();
                                     }
                                 }
                             }
                             $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 el controlador y la vista (" . $factura->total . " frente a " . $_POST['atotal'] . "). 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 Proveedor ' . $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!");
             }
         }
     }
 }
 private function nueva_factura_proveedor()
 {
     $continuar = TRUE;
     $proveedor = $this->proveedor->get($_POST['proveedor']);
     if ($proveedor) {
         $this->save_codproveedor($proveedor->codproveedor);
     } else {
         $this->new_error_msg('Proveedor 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_proveedor();
     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->codproveedor = $proveedor->codproveedor;
         $factura->nombre = $proveedor->nombrecomercial;
         $factura->cifnif = $proveedor->cifnif;
         $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->numproveedor = $_POST['numproveedor'];
         $factura->observaciones = $_POST['observaciones'];
         $factura->irpf = $serie->irpf;
         if ($forma_pago->genrecibos == 'Pagados') {
             $factura->pagada = TRUE;
         }
         foreach ($proveedor->get_direcciones() as $d) {
             if ($d->domfacturacion) {
                 $factura->codproveedor = $proveedor->codproveedor;
                 $factura->cifnif = $proveedor->cifnif;
                 $factura->nombre = $proveedor->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->codproveedor)) {
             $this->new_error_msg("No hay ninguna dirección asociada al proveedor.");
         } 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_proveedor();
                             $linea->idfactura = $factura->idfactura;
                             $linea->referencia = $articulo->referencia;
                             $linea->descripcion = $_POST['desc_' . $i];
                             $linea->irpf = $factura->irpf;
                             if (!$serie->siniva and $proveedor->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->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()) {
                                 /// sumamos al stock
                                 $articulo->sum_stock($factura->codalmacen, $linea->cantidad);
                                 if ($articulo->costemedio == 0) {
                                     $articulo->costemedio = $linea->pvptotal / $linea->cantidad;
                                     $articulo->save();
                                 }
                                 $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['atotal']) - $factura->total) > 0.01) {
                         $this->new_error_msg("El total difiere entre el controlador y la vista (" . $factura->total . " frente a " . $_POST['atotal'] . "). 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 Proveedor ' . $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_proveedor()
 {
     $continuar = TRUE;
     $proveedor = $this->proveedor->get($_POST['proveedor']);
     if ($proveedor) {
         $this->save_codproveedor($proveedor->codproveedor);
     } else {
         $this->new_error_msg('Proveedor no encontrado.');
         $continuar = FALSE;
     }
     if (isset($_POST['almacen'])) {
         $almacen = $this->almacen->get($_POST['almacen']);
         if ($almacen) {
             $this->save_codalmacen($almacen->codalmacen);
         } else {
             $this->new_error_msg('Almacén no encontrado.');
             $continuar = FALSE;
         }
     }
     $factura = new factura_proveedor();
     $eje0 = new ejercicio();
     $ejercicio = $eje0->get_by_fecha($_POST['fecha']);
     if ($ejercicio) {
         $this->save_codejercicio($ejercicio->codejercicio);
     } else {
         $this->autorizar_factura = 1;
         //      $this->new_error_msg('Ejercicio no encontrado.1');
         header('Location: ' . $factura->url_list() . '&nueva=2');
         $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;
     }
     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;
     }
     $a = strlen(substr($_POST['fecha'], 6));
     if ($a != 4) {
         $continuar = FALSE;
     }
     if ($continuar) {
         $factura->fecha = $_POST['fecha'];
         $fecha_factura = $_POST['fecha'];
         $factura->hora = $_POST['hora'];
         $factura->codproveedor = $proveedor->codproveedor;
         $factura->nombre = $proveedor->razonsocial;
         $factura->idpagodevol = 0;
         $factura->cifnif = $proveedor->cifnif;
         $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_compra;
         $factura->tipo = $_POST['tipo'];
         $factura->cai = $_POST['cai'];
         $factura->caivence = $_POST['caivence'];
         if ($_POST['tasaconv'] != '') {
             $factura->tasaconv = floatval($_POST['tasaconv']);
         }
         $factura->codagente = $this->agente->codagente;
         $factura->numproveedor = $_POST['tipo'] . '/' . $_POST['numproveedor'];
         $factura->observaciones = $_POST['observaciones'];
         $factura->irpf = $serie->irpf;
         if ($forma_pago->genrecibos == 'Pagados') {
             //            $factura->pagada = TRUE;
         }
         if ($factura->save()) {
             $art0 = new articulo();
             $inventario = new inventario();
             $n = floatval($_POST['numlineas']);
             for ($i = 0; $i < $n; $i++) {
                 if (isset($_POST['referencia_' . $i])) {
                     $linea = new linea_factura_proveedor();
                     $linea->idfactura = $factura->idfactura;
                     $this->id_factura = $factura->idfactura;
                     $linea->descripcion = $_POST['desc_' . $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]);
                     $postot = strlen($_POST['subcuenta_' . $i]);
                     $poscad = strpos($_POST['subcuenta_' . $i], '/');
                     $posid = strpos($_POST['subcuenta_' . $i], '%');
                     $subcuencod = substr($_POST['subcuenta_' . $i], 0, $poscad);
                     $subcuendes = substr($_POST['subcuenta_' . $i], $poscad + 1, $posid - $postot);
                     $idsubcuen = substr($_POST['subcuenta_' . $i], $posid + 1);
                     $linea->codsubcuenta = $subcuencod;
                     $linea->subcuentadesc = $subcuendes;
                     $linea->idsubcuenta = $idsubcuen;
                     $articulo = $art0->get($_POST['referencia_' . $i]);
                     ////////////////////////////////////////////////////////////////////////
                     ////  GUARDA subcuenta en articulo cuando se carga la factura
                     ////////////////////////////////////////////////////
                     $artval = $this->artsubcuentas->get_ref($_POST['referencia_' . $i]);
                     if ($artval != $subcuencod || $subcuencod == NULL) {
                         if ($_POST['tipo'] == 'B' || $_POST['tipo'] == 'F' || $_POST['tipo'] == 'T' || $_POST['tipo'] == 'Q' || $_POST['tipo'] == 'C' || $_POST['tipo'] == 'D') {
                             $this->artsubcuentas->guarda_subcuenta_comp($_POST['referencia_' . $i], $subcuencod, $subcuendes);
                         } else {
                             $this->artsubcuentas->guarda_subcuenta_dev($_POST['referencia_' . $i], $subcuencod, $subcuendes);
                         }
                     }
                     //////////////////////////////////////////////////////////////////
                     ////////////////////////////////////////////////////////////////
                     if ($articulo) {
                         $linea->referencia = $articulo->referencia;
                     }
                     if ($linea->save()) {
                         if ($articulo) {
                             if (isset($_POST['costemedio'])) {
                                 if ($articulo->costemedio == 0) {
                                     $articulo->costemedio = $linea->pvptotal / $linea->cantidad;
                                 } else {
                                     $articulo->costemedio = $articulo->get_costemedio();
                                     if ($articulo->costemedio == 0) {
                                         $articulo->costemedio = $linea->pvptotal / $linea->cantidad;
                                     }
                                 }
                                 $this->actualizar_precio_proveedor($factura->codproveedor, $linea);
                             }
                             if (isset($_POST['stock'])) {
                                 $articulo->sum_stock($factura->codalmacen, $linea->cantidad);
                                 if ($articulo) {
                                     $inventario->inventario_agregar($factura->codalmacen, $linea->referencia, $linea->cantidad, $linea->pvpunitario);
                                 }
                             } else {
                                 if (isset($_POST['costemedio'])) {
                                     $articulo->save();
                                 }
                             }
                         }
                         $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) {
                 $factura->fecha = $fecha_factura;
                 /// 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 el controlador y la vista (" . $factura->total . " frente a " . $_POST['atotal'] . "). Debes informar del error.");
                     $factura->delete();
                 } else {
                     if ($factura->save()) {
                         ///////// GENERA  ASIENTO
                         //                  $this->generar_asiento($factura);
                         //                  $this->new_message("<a href='".$factura->url()."'>Factura</a> guardada correctamente.");
                         //             $this->new_change('Factura Proveedor '.$factura->codigo, $factura->url(), TRUE);
                         $this->autorizar_factura = 1;
                         $this->new_error_msg('Factura Guardada');
                         if ($_POST['redir'] == 'TRUE') {
                             header('Location: ' . $factura->url_list() . '&nueva=1');
                         }
                     } else {
                         $this->new_error_msg("¡Imposible actualizar la <a href='" . $factura->url() . "'>factura</a>!");
                     }
                 }
             } else {
                 $this->new_message("Factura eliminada correctamente.");
             }
         } else {
             $this->new_error_msg("¡Imposible guardar la factura!");
         }
     }
 }
 private function generar_factura($albaranes)
 {
     $continuar = TRUE;
     $factura = new factura_proveedor();
     $factura->codagente = $this->user->codagente;
     $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->irpf = $albaranes[0]->irpf;
     $factura->numproveedor = $_POST['numfactproveedor'];
     $factura->tipo = $_POST['comprobante'];
     $factura->observaciones = $albaranes[0]->observaciones;
     /// 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 actualizados del proveedor
     $proveedor = $this->proveedor->get($albaranes[0]->codproveedor);
     if ($proveedor) {
         $factura->cifnif = $proveedor->cifnif;
         $factura->codproveedor = $proveedor->codproveedor;
         $factura->nombre = $proveedor->razonsocial;
         $factura->cai = $proveedor->cai;
         $factura->caivence = $proveedor->caivence;
     }
     /// 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_proveedor();
                         $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;
                         $n->codsubcuenta = $l->codsubcuenta;
                         $n->idsubcuenta = $l->idsubcuenta;
                         $n->subcuentadesc = $l->subcuentadesc;
                         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!");
             }
         }
     }
 }