protected function process()
 {
     /// ¿El usuario tiene permiso para eliminar en esta página?
     $this->allow_delete = $this->user->allow_delete_on(__CLASS__);
     /**
      * Si hay alguna extensión de tipo config y texto button_plazos,
      * mostramos un botón con enlace a la página de la extensión.
      */
     $this->button_plazos = FALSE;
     foreach ($this->extensions as $ext) {
         if ($ext->type == 'config' and $ext->text == 'button_plazos') {
             $this->button_plazos = $ext->from;
             break;
         }
     }
     $cuentab = new cuenta_banco();
     $this->cuentas_banco = $cuentab->all_from_empresa();
     $this->forma_pago = new forma_pago();
     if (isset($_POST['codpago'])) {
         $fp0 = $this->forma_pago->get($_POST['codpago']);
         if (!$fp0) {
             $fp0 = new forma_pago();
             $fp0->codpago = $_POST['codpago'];
         }
         $fp0->descripcion = $_POST['descripcion'];
         $fp0->genrecibos = $_POST['genrecibos'];
         $fp0->vencimiento = $_POST['vencimiento'];
         $fp0->domiciliado = isset($_POST['domiciliado']);
         $fp0->codcuenta = NULL;
         if ($_POST['codcuenta'] != '') {
             $fp0->codcuenta = $_POST['codcuenta'];
         }
         if ($fp0->codpago == '' or $fp0->descripcion == '') {
             $this->new_error_msg('Debes poner algún nombre a la forma de pago.');
         } else {
             if ($fp0->save()) {
                 $this->new_message('Forma pago ' . $fp0->codpago . ' guardada correctamente.');
             } else {
                 $this->new_error_msg('Error al guardar la forma pago.');
             }
         }
     } else {
         if (isset($_GET['delete'])) {
             $fp0 = $this->forma_pago->get($_GET['delete']);
             if ($fp0) {
                 if (!$this->user->admin) {
                     $this->new_error_msg('Sólo un administrador puede eliminar formas de pago.');
                 } else {
                     if ($fp0->delete()) {
                         $this->new_message('Forma de pago ' . $fp0->codpago . ' eliminada correctamente.');
                     } else {
                         $this->new_error_msg('Error al eliminar la forma de pago ' . $fp0->codpago . '.');
                     }
                 }
             } else {
                 $this->new_error_msg('Forma de pago no encontrada.');
             }
         }
     }
 }
示例#2
0
 private function generar_pdf_factura($tipo = 'simple', $archivo = FALSE)
 {
     if (!$archivo) {
         /// desactivamos la plantilla HTML
         $this->template = FALSE;
     }
     /// Creamos el PDF y escribimos sus metadatos
     $pdf_doc = new fs_pdf();
     $pdf_doc->pdf->addInfo('Title', ucfirst(FS_FACTURA) . ' ' . $this->factura->codigo);
     $pdf_doc->pdf->addInfo('Subject', ucfirst(FS_FACTURA) . ' ' . $this->factura->codigo);
     $pdf_doc->pdf->addInfo('Author', $this->empresa->nombre);
     $lineas = $this->factura->get_lineas();
     $lineas_iva = $this->factura->get_lineas_iva();
     if ($lineas) {
         $lineasfact = count($lineas);
         $linea_actual = 0;
         $pagina = 1;
         // Imprimimos las páginas necesarias
         while ($linea_actual < $lineasfact) {
             $lppag = 35;
             /// líneas por página
             /// salto de página
             if ($linea_actual > 0) {
                 $pdf_doc->pdf->ezNewPage();
             }
             /*
              * Creamos la cabecera de la página, en este caso para el modelo carta
              */
             if ($tipo == 'carta') {
                 $direccion = $this->factura->nombrecliente . "\n" . $this->factura->direccion;
                 if ($this->factura->codpostal and $this->factura->ciudad) {
                     $direccion .= "\n CP: " . $this->factura->codpostal . ' ' . $this->factura->ciudad;
                 } else {
                     if ($this->factura->ciudad) {
                         $direccion .= "\n" . $this->factura->ciudad;
                     }
                 }
                 if ($this->factura->provincia) {
                     $direccion .= "\n(" . $this->factura->provincia . ")";
                 }
                 $pdf_doc->pdf->ezText("\n\n", 10);
                 $pdf_doc->new_table();
                 $pdf_doc->add_table_row(array('campos' => "<b>" . ucfirst(FS_FACTURA) . ":</b>\n<b>Fecha:</b>\n<b>" . FS_CIFNIF . ":</b>", 'factura' => $this->factura->codigo . "\n" . $this->factura->fecha . "\n" . $this->factura->cifnif, 'cliente' => $this->fix_html($direccion)));
                 $pdf_doc->save_table(array('cols' => array('campos' => array('justification' => 'right', 'width' => 100), 'factura' => array('justification' => 'left'), 'cliente' => array('justification' => 'right')), 'showLines' => 0, 'width' => 520));
                 $pdf_doc->pdf->ezText("\n\n\n", 14);
             } else {
                 /// ¿Añadimos el logo?
                 if (file_exists('tmp/' . FS_TMP_NAME . 'logo.png')) {
                     if (function_exists('imagecreatefromstring')) {
                         $pdf_doc->pdf->ezImage('tmp/' . FS_TMP_NAME . 'logo.png', 0, 200, 'none');
                         $lppag -= 2;
                         /// si metemos el logo, caben menos líneas
                     } else {
                         die('ERROR: no se encuentra la función imagecreatefromstring(). ' . 'Y por tanto no se puede usar el logotipo en los documentos.');
                     }
                 } else {
                     $pdf_doc->pdf->ezText("<b>" . $this->empresa->nombre . "</b>", 16, array('justification' => 'center'));
                     $pdf_doc->pdf->ezText(FS_CIFNIF . ": " . $this->empresa->cifnif, 8, array('justification' => 'center'));
                     $direccion = $this->empresa->direccion;
                     if ($this->empresa->codpostal) {
                         $direccion .= ' - ' . $this->empresa->codpostal;
                     }
                     if ($this->empresa->ciudad) {
                         $direccion .= ' - ' . $this->empresa->ciudad;
                     }
                     if ($this->empresa->provincia) {
                         $direccion .= ' (' . $this->empresa->provincia . ')';
                     }
                     if ($this->empresa->telefono) {
                         $direccion .= ' - Teléfono: ' . $this->empresa->telefono;
                     }
                     $pdf_doc->pdf->ezText($this->fix_html($direccion), 9, array('justification' => 'center'));
                 }
                 /*
                  * Esta es la tabla con los datos del cliente:
                  * Factura:             Fecha:
                  * Cliente:             CIF/NIF:
                  * Dirección:           Teléfonos:
                  */
                 $pdf_doc->new_table();
                 $pdf_doc->add_table_row(array('campo1' => "<b>" . ucfirst(FS_FACTURA) . ":</b>", 'dato1' => $this->factura->codigo, 'campo2' => "<b>Fecha:</b>", 'dato2' => $this->factura->fecha));
                 $pdf_doc->add_table_row(array('campo1' => "<b>Cliente:</b>", 'dato1' => $this->fix_html($this->factura->nombrecliente), 'campo2' => "<b>" . FS_CIFNIF . ":</b>", 'dato2' => $this->factura->cifnif));
                 $pdf_doc->add_table_row(array('campo1' => "<b>Dirección:</b>", 'dato1' => $this->factura->direccion . ' CP: ' . $this->factura->codpostal . ' - ' . $this->factura->ciudad . ' (' . $this->factura->provincia . ')', 'campo2' => "<b>Teléfonos:</b>", 'dato2' => $this->cliente->telefono1 . '  ' . $this->cliente->telefono2));
                 $pdf_doc->save_table(array('cols' => array('campo1' => array('justification' => 'right'), 'dato1' => array('justification' => 'left'), 'campo2' => array('justification' => 'right'), 'dato2' => array('justification' => 'left')), 'showLines' => 0, 'width' => 520, 'shaded' => 0));
                 $pdf_doc->pdf->ezText("\n", 10);
                 /// en el tipo 'firma' caben menos líneas
                 if ($tipo == 'firma') {
                     $lppag -= 3;
                 }
             }
             /*
              * Creamos la tabla con las lineas de la factura:
              * 
              * Descripción    Cantidad  PVP   DTO    Importe
              */
             $columnas = array('alb' => '<b>' . ucfirst(FS_ALBARAN) . '</b>', 'descripcion' => '<b>Descripción</b>', 'cantidad' => '<b>Cantidad</b>', 'pvp' => '<b>PVP</b>', 'dto' => '<b>DTO</b>', 'importe' => '<b>Importe</b>');
             if (!$this->impresion['print_alb']) {
                 unset($columnas['alb']);
             }
             if (!$this->impresion['print_dto']) {
                 unset($columnas['dto']);
             }
             $pdf_doc->new_table();
             $pdf_doc->add_table_header($columnas);
             for ($i = $linea_actual; $linea_actual < $lppag + $i and $linea_actual < $lineasfact;) {
                 $descripcion = $this->fix_html($lineas[$linea_actual]->descripcion);
                 if ($this->impresion['print_ref'] and !is_null($lineas[$linea_actual]->referencia)) {
                     $descripcion = '<b>' . $lineas[$linea_actual]->referencia . '</b> ' . $descripcion;
                 }
                 $fila = array('alb' => $lineas[$linea_actual]->albaran_numero(), 'descripcion' => $descripcion, 'cantidad' => $lineas[$linea_actual]->cantidad, 'pvp' => $this->show_precio($lineas[$linea_actual]->pvpunitario, $this->factura->coddivisa), 'dto' => $this->show_numero($lineas[$linea_actual]->dtopor, 0) . " %", 'importe' => $this->show_precio($lineas[$linea_actual]->pvptotal, $this->factura->coddivisa));
                 $pdf_doc->add_table_row($fila);
                 $linea_actual++;
             }
             $pdf_doc->save_table(array('fontSize' => 8, 'cols' => array('cantidad' => array('justification' => 'right'), 'pvp' => array('justification' => 'right'), 'dto' => array('justification' => 'right'), 'importe' => array('justification' => 'right')), 'width' => 520, 'shaded' => 0));
             if ($linea_actual == count($lineas)) {
                 /*
                  * Añadimos la parte de la firma y las observaciones,
                  * para el tipo 'firma'
                  */
                 if ($tipo == 'firma') {
                     $pdf_doc->pdf->ezText("\n", 9);
                     $pdf_doc->new_table();
                     $pdf_doc->add_table_header(array('campo1' => "<b>Observaciones</b>", 'campo2' => "<b>Firma</b>"));
                     $pdf_doc->add_table_row(array('campo1' => $this->fix_html($this->factura->observaciones), 'campo2' => ""));
                     $pdf_doc->save_table(array('cols' => array('campo1' => array('justification' => 'left'), 'campo2' => array('justification' => 'right', 'width' => 100)), 'showLines' => 4, 'width' => 530, 'shaded' => 0));
                 } else {
                     if ($this->factura->observaciones != '') {
                         $pdf_doc->pdf->ezText("\n" . $this->fix_html($this->factura->observaciones), 9);
                     }
                 }
                 if (!$this->factura->pagada) {
                     $fp0 = new forma_pago();
                     $forma_pago = $fp0->get($this->factura->codpago);
                     if ($forma_pago) {
                         if (is_null($forma_pago->codcuenta)) {
                             $pdf_doc->pdf->ezText("\n<b>Forma de pago</b>: " . $forma_pago->descripcion . "\n<b>Vencimiento</b>: " . $this->factura->vencimiento, 9);
                         } else {
                             $texto_pago = "\n<b>Forma de pago</b>: " . $forma_pago->descripcion;
                             if ($forma_pago->domiciliado) {
                                 $cbc0 = new cuenta_banco_cliente();
                                 $encontrada = FALSE;
                                 foreach ($cbc0->all_from_cliente($this->factura->codcliente) as $cbc) {
                                     if ($cbc->iban) {
                                         $texto_pago .= "\n<b>Domiciliado en</b>: " . $cbc->iban;
                                     } else {
                                         $texto_pago .= "\n<b>Domiciliado en</b>: " . $cbc->swift;
                                     }
                                     $encontrada = TRUE;
                                     break;
                                 }
                                 if (!$encontrada) {
                                     $texto_pago .= "\n<b>El cliente no tiene cuenta bancaria asignada.</b>";
                                 }
                             } else {
                                 $cb0 = new cuenta_banco();
                                 $cuenta_banco = $cb0->get($forma_pago->codcuenta);
                                 if ($cuenta_banco) {
                                     if ($cuenta_banco->iban) {
                                         $texto_pago .= "\n<b>IBAN</b>: " . $cuenta_banco->iban;
                                     } else {
                                         $texto_pago .= "\n<b>SWIFT o BIC</b>: " . $cuenta_banco->swift;
                                     }
                                 }
                             }
                             $texto_pago .= "\n<b>Vencimiento</b>: " . $this->factura->vencimiento;
                             $pdf_doc->pdf->ezText($texto_pago, 9);
                         }
                     }
                 }
             }
             $pdf_doc->set_y(80);
             /*
              * Rellenamos la última tabla de la página:
              * 
              * Página            Neto    IVA   Total
              */
             $pdf_doc->new_table();
             $titulo = array('pagina' => '<b>Página</b>', 'neto' => '<b>Neto</b>');
             $fila = array('pagina' => $pagina . '/' . ceil(count($lineas) / $lppag), 'neto' => $this->show_precio($this->factura->neto, $this->factura->coddivisa));
             $opciones = array('cols' => array('neto' => array('justification' => 'right')), 'showLines' => 4, 'width' => 520);
             foreach ($lineas_iva as $li) {
                 $imp = $this->impuesto->get($li->codimpuesto);
                 if ($imp) {
                     $titulo['iva' . $li->iva] = '<b>' . $imp->descripcion . '</b>';
                 } else {
                     $titulo['iva' . $li->iva] = '<b>' . FS_IVA . ' ' . $li->iva . '%</b>';
                 }
                 $fila['iva' . $li->iva] = $this->show_precio($li->totaliva, $this->factura->coddivisa);
                 if ($li->totalrecargo != 0) {
                     $fila['iva' . $li->iva] .= ' (RE: ' . $this->show_precio($li->totalrecargo, $this->factura->coddivisa) . ')';
                 }
                 $opciones['cols']['iva' . $li->iva] = array('justification' => 'right');
             }
             if ($this->factura->totalirpf != 0) {
                 $titulo['irpf'] = '<b>' . FS_IRPF . ' ' . $this->factura->irpf . '%</b>';
                 $fila['irpf'] = $this->show_precio(0 - $this->factura->totalirpf);
                 $opciones['cols']['irpf'] = array('justification' => 'right');
             }
             $titulo['liquido'] = '<b>Total</b>';
             $fila['liquido'] = $this->show_precio($this->factura->total, $this->factura->coddivisa);
             $opciones['cols']['liquido'] = array('justification' => 'right');
             $pdf_doc->add_table_header($titulo);
             $pdf_doc->add_table_row($fila);
             $pdf_doc->save_table($opciones);
             /// pié de página para la factura
             $pdf_doc->pdf->addText(10, 10, 8, $pdf_doc->center_text($this->fix_html($this->empresa->pie_factura), 153), 0, 1.5);
             $pagina++;
         }
     }
     if ($archivo) {
         if (!file_exists('tmp/' . FS_TMP_NAME . 'enviar')) {
             mkdir('tmp/' . FS_TMP_NAME . 'enviar');
         }
         $pdf_doc->save('tmp/' . FS_TMP_NAME . 'enviar/' . $archivo);
     } else {
         $pdf_doc->show();
     }
 }
示例#3
0
 protected function private_core()
 {
     $this->almacen = new almacen();
     $this->cuenta_banco = new cuenta_banco();
     $this->divisa = new divisa();
     $this->ejercicio = new ejercicio();
     $this->forma_pago = new forma_pago();
     $this->serie = new serie();
     $this->pais = new pais();
     $fsvar = new fs_var();
     /// obtenemos los datos de configuración del email
     $this->mail = array('mail_host' => 'smtp.gmail.com', 'mail_port' => '465', 'mail_enc' => 'ssl', 'mail_user' => '', 'mail_low_security' => FALSE);
     $this->mail = $fsvar->array_get($this->mail, FALSE);
     /// obtenemos los datos de configuración de impresión
     $this->impresion = array('print_ref' => '1', 'print_dto' => '1', 'print_alb' => '0', 'print_formapago' => '1');
     $this->impresion = $fsvar->array_get($this->impresion, FALSE);
     if (isset($_POST['cifnif'])) {
         /// guardamos los datos de la empresa
         $this->empresa->nombre = $_POST['nombre'];
         $this->empresa->nombrecorto = $_POST['nombrecorto'];
         $this->empresa->cifnif = $_POST['cifnif'];
         $this->empresa->administrador = $_POST['administrador'];
         $this->empresa->codpais = $_POST['codpais'];
         $this->empresa->provincia = $_POST['provincia'];
         $this->empresa->ciudad = $_POST['ciudad'];
         $this->empresa->direccion = $_POST['direccion'];
         $this->empresa->codpostal = $_POST['codpostal'];
         $this->empresa->telefono = $_POST['telefono'];
         $this->empresa->fax = $_POST['fax'];
         $this->empresa->web = $_POST['web'];
         $this->empresa->email = $_POST['email'];
         $this->empresa->email_firma = $_POST['email_firma'];
         $this->empresa->email_password = $_POST['email_password'];
         $this->empresa->lema = $_POST['lema'];
         $this->empresa->horario = $_POST['horario'];
         $this->empresa->contintegrada = isset($_POST['contintegrada']);
         $this->empresa->codejercicio = $_POST['codejercicio'];
         $this->empresa->codserie = $_POST['codserie'];
         $this->empresa->coddivisa = $_POST['coddivisa'];
         $this->empresa->codpago = $_POST['codpago'];
         $this->empresa->codalmacen = $_POST['codalmacen'];
         $this->empresa->pie_factura = $_POST['pie_factura'];
         $this->empresa->recequivalencia = isset($_POST['recequivalencia']);
         if ($this->empresa->save()) {
             /// guardamos las opciones por defecto de almacén y forma de pago
             $this->save_codalmacen($_POST['codalmacen']);
             $this->save_codpago($_POST['codpago']);
             $this->new_message('Datos guardados correctamente.');
             if (!$this->empresa->contintegrada) {
                 $this->new_message('¿Quieres activar la <b>contabilidad integrada</b>?' . ' Haz clic en la sección <a href="#facturacion">facturación</a>.');
             }
             $step = $fsvar->simple_get('install_step');
             if ($step == 2) {
                 $step = 3;
                 $fsvar->simple_save('install_step', $step);
             }
             if ($step == 3 and $this->empresa->contintegrada) {
                 $this->new_message('Recuerda que tienes que <a href="index.php?page=contabilidad_ejercicio&cod=' . $this->empresa->codejercicio . '">importar los datos del ejercicio</a>.');
             }
         } else {
             $this->new_error_msg('Error al guardar los datos.');
         }
         /// guardamos los datos del email
         if (isset($_POST['mail_host'])) {
             $this->mail['mail_host'] = 'smtp.gmail.com';
             if ($_POST['mail_host'] != '') {
                 $this->mail['mail_host'] = $_POST['mail_host'];
             }
             $this->mail['mail_port'] = '465';
             if ($_POST['mail_port'] != '') {
                 $this->mail['mail_port'] = $_POST['mail_port'];
             }
             $this->mail['mail_enc'] = strtolower($_POST['mail_enc']);
             $this->mail['mail_user'] = $_POST['mail_user'];
             $this->mail['mail_low_security'] = isset($_POST['mail_low_security']);
             $fsvar->array_save($this->mail);
             $this->mail_test();
         }
         /// guardamos los datos de impresión
         $this->impresion['print_ref'] = isset($_POST['print_ref']) ? 1 : 0;
         $this->impresion['print_dto'] = isset($_POST['print_dto']) ? 1 : 0;
         $this->impresion['print_alb'] = isset($_POST['print_alb']) ? 1 : 0;
         $this->impresion['print_formapago'] = isset($_POST['print_formapago']) ? 1 : 0;
         $fsvar->array_save($this->impresion);
     } else {
         if (isset($_POST['nombre'])) {
             /// guardamos solamente lo básico, ya que facturacion_base no está activado
             $this->empresa->nombre = $_POST['nombre'];
             $this->empresa->nombrecorto = $_POST['nombrecorto'];
             $this->empresa->web = $_POST['web'];
             $this->empresa->email = $_POST['email'];
             $this->empresa->email_firma = $_POST['email_firma'];
             $this->empresa->email_password = $_POST['email_password'];
             if ($this->empresa->save()) {
                 $this->new_message('Datos guardados correctamente.');
             } else {
                 $this->new_error_msg('Error al guardar los datos.');
             }
             /// guardamos los datos del email
             if (isset($_POST['mail_host'])) {
                 $this->mail['mail_host'] = 'smtp.gmail.com';
                 if ($_POST['mail_host'] != '') {
                     $this->mail['mail_host'] = $_POST['mail_host'];
                 }
                 $this->mail['mail_port'] = '465';
                 if ($_POST['mail_port'] != '') {
                     $this->mail['mail_port'] = $_POST['mail_port'];
                 }
                 $this->mail['mail_enc'] = strtolower($_POST['mail_enc']);
                 $this->mail['mail_user'] = $_POST['mail_user'];
                 $this->mail['mail_low_security'] = isset($_POST['mail_low_security']);
                 $fsvar->array_save($this->mail);
                 $this->mail_test();
             }
         } else {
             if (isset($_POST['logo'])) {
                 if (is_uploaded_file($_FILES['fimagen']['tmp_name'])) {
                     $this->delete_logo();
                     if (substr(strtolower($_FILES['fimagen']['name']), -3) == 'png') {
                         copy($_FILES['fimagen']['tmp_name'], "tmp/" . FS_TMP_NAME . "logo.png");
                     } else {
                         copy($_FILES['fimagen']['tmp_name'], "tmp/" . FS_TMP_NAME . "logo.jpg");
                     }
                     $this->new_message('Logotipo guardado correctamente.');
                 }
             } else {
                 if (isset($_GET['delete_logo'])) {
                     $this->delete_logo();
                 } else {
                     if (isset($_GET['delete_cuenta'])) {
                         $cuenta = $this->cuenta_banco->get($_GET['delete_cuenta']);
                         if ($cuenta) {
                             if ($cuenta->delete()) {
                                 $this->new_message('Cuenta bancaria eliminada correctamente.');
                             } else {
                                 $this->new_error_msg('Imposible eliminar la cuenta bancaria.');
                             }
                         } else {
                             $this->new_error_msg('Cuenta bancaria no encontrada.');
                         }
                     } else {
                         if (isset($_POST['iban'])) {
                             if (isset($_POST['codcuenta'])) {
                                 $cuentab = $this->cuenta_banco->get($_POST['codcuenta']);
                             } else {
                                 $cuentab = new cuenta_banco();
                             }
                             $cuentab->descripcion = $_POST['descripcion'];
                             $cuentab->iban = $_POST['iban'];
                             $cuentab->swift = $_POST['swift'];
                             if (isset($_POST['codsubcuenta'])) {
                                 $cuentab->codsubcuenta = $_POST['codsubcuenta'];
                             }
                             if ($cuentab->save()) {
                                 $this->new_message('Cuenta bancaria guardada correctamente.');
                             } else {
                                 $this->new_error_msg('Imposible guardar la cuenta bancaria.');
                             }
                         }
                     }
                 }
             }
         }
     }
     $this->facturacion_base = in_array('facturacion_base', $GLOBALS['plugins']);
     $this->logo = FALSE;
     if (file_exists('tmp/' . FS_TMP_NAME . 'logo.png')) {
         $this->logo = 'tmp/' . FS_TMP_NAME . 'logo.png';
     } else {
         if (file_exists('tmp/' . FS_TMP_NAME . 'logo.jpg')) {
             $this->logo = 'tmp/' . FS_TMP_NAME . 'logo.jpg';
         }
     }
 }
 protected function private_core()
 {
     /// ¿El usuario tiene permiso para eliminar en esta página?
     $this->allow_delete = $this->user->allow_delete_on(__CLASS__);
     /**
      * Si hay alguna extensión de tipo config y texto button_plazos,
      * mostramos un botón con enlace a la página de la extensión.
      */
     $this->button_plazos = FALSE;
     foreach ($this->extensions as $ext) {
         if ($ext->type == 'config' and $ext->text == 'button_plazos') {
             $this->button_plazos = $ext->from;
             break;
         }
     }
     $cuentab = new cuenta_banco();
     $this->cuentas_banco = $cuentab->all_from_empresa();
     $this->forma_pago = new forma_pago();
     if (isset($_POST['codpago'])) {
         /// crear/modificar forma de pago
         $nueva = FALSE;
         $fp0 = $this->forma_pago->get($_POST['codpago']);
         if (!$fp0) {
             $fp0 = new forma_pago();
             $fp0->codpago = $_POST['codpago'];
             $nueva = TRUE;
         }
         $fp0->descripcion = $_POST['descripcion'];
         $fp0->genrecibos = $_POST['genrecibos'];
         $fp0->vencimiento = $_POST['vencimiento'];
         $fp0->codcuenta = NULL;
         if ($_POST['codcuenta'] != '') {
             $fp0->codcuenta = $_POST['codcuenta'];
         }
         $fp0->domiciliado = FALSE;
         if (isset($_POST['domiciliado'])) {
             if (is_null($fp0->codcuenta)) {
                 $this->new_error_msg('Para marcar una forma de pago como domiciliada,' . ' también tienes que seleccionar una cuenta bancaria.');
             } else {
                 $fp0->domiciliado = TRUE;
             }
         }
         if ($fp0->codpago == '' or $fp0->descripcion == '') {
             $this->new_error_msg('Debes poner algún nombre a la forma de pago.');
         } else {
             if ($fp0->save()) {
                 $this->new_message('Forma de pago ' . $fp0->codpago . ' guardada correctamente.');
                 if ($nueva and $this->button_plazos and $fp0->genrecibos == 'Emitidos') {
                     header('Location: index.php?page=' . $this->button_plazos . '&cod=' . $fp0->codpago . '&nueva=TRUE');
                 }
             } else {
                 $this->new_error_msg('Error al guardar la forma pago.');
             }
         }
     } else {
         if (isset($_GET['delete'])) {
             $fp0 = $this->forma_pago->get($_GET['delete']);
             if ($fp0) {
                 if (!$this->user->admin) {
                     $this->new_error_msg('Sólo un administrador puede eliminar formas de pago.');
                 } else {
                     if ($fp0->delete()) {
                         $this->new_message('Forma de pago ' . $fp0->codpago . ' eliminada correctamente.');
                     } else {
                         $this->new_error_msg('Error al eliminar la forma de pago ' . $fp0->codpago . '.');
                     }
                 }
             } else {
                 $this->new_error_msg('Forma de pago no encontrada.');
             }
         }
     }
 }
 private function generar_pdf_factura($tipo = 'simple', $archivo = FALSE)
 {
     $divi = new divisa();
     if (!$archivo) {
         /// desactivamos la plantilla HTML
         $this->template = FALSE;
     }
     /// Creamos el PDF y escribimos sus metadatos
     $pdf_doc = new fs_pdf();
     $pdf_doc->pdf->addInfo('Title', ucfirst(FS_FACTURA) . ' ' . $this->factura->codigo);
     $pdf_doc->pdf->addInfo('Subject', ucfirst(FS_FACTURA) . ' ' . $this->factura->codigo);
     $pdf_doc->pdf->addInfo('Author', $this->empresa->nombre);
     $lineas = $this->factura->get_lineas();
     $lineas_iva = $this->factura->get_lineas_iva();
     if ($lineas) {
         $lineasfact = count($lineas);
         $linea_actual = 0;
         $pagina = 1;
         ///////////////////////////////////////////////////////////////////////////////////
         ////////////////////   PARA FACTURA PREIMPRESA
         ////////////////////////////////////////////////////////////////////////////////////
         if ($tipo == 'firma') {
             $numFactura = $this->factura->numero2;
             $fecha = $this->factura->fecha;
             $nomCliente = $this->factura->nombrecliente;
             $dirCliente = $this->direccioncli->direccion;
             $cpCliente = $this->factura->codpostal;
             $locCliente = $this->direccioncli->ciudad;
             $provincia = $this->direccioncli->provincia;
             $telCliente1 = $this->cliente->telefono1;
             $telCliente2 = $this->cliente->telefono2;
             $catIVA = $this->cliente->regimeniva;
             $numCuit = '88-88888888-888 ';
             $ingBrutos = '1234-567890-1234-5678-90';
             $this->simbdivisa = $divi->get($this->factura->coddivisa);
             $uMoneda = $this->simbdivisa->simbolo;
             //Unidad de Moneda
             $cheqNum = '8888-8888-8888-8888 ';
             $cheqBanco = 'Banco Internacional y Nacional';
             $cheqImporte = '7789.99';
             $anticipo = '3854.88';
             $anticipoDetalle = 'Detalle por si hay algo anotar del anticipo';
             $efectivo = '38888.88';
             $efectivoDetalle = 'Detalle por si hay algo anotar del efectivo';
             $tarjDebito = '48888.88';
             $debitoDetalle = 'Visa Nº 8888-8888-8888-8888-8888';
             $tarjCredito = '48888.88';
             $creditoDetalle = 'Master Card Nº 9888-8888-8888-8888-8888';
             $linea_arranque = -10;
             $linea_fin = 0;
             $cant_pag = intval($lineasfact / 10);
             if ($lineasfact / 10 - intval($lineasfact / 10) > 0) {
                 $cant_pag = $cant_pag + 1;
             }
             for ($j = 0; $j < $cant_pag; $j++) {
                 if ($lineasfact - $linea_fin < 10) {
                     $linea_menor = ($lineasfact / 10 - intval($lineasfact / 10)) * 10;
                     $linea_fin = $linea_fin + $linea_menor;
                 } else {
                     $linea_fin = $linea_fin + 10;
                 }
                 $linea_arranque = $linea_arranque + 10;
                 if ($j != 0) {
                     $pdf_doc->pdf->ezNewPage();
                 }
                 $pdf_doc->pdf->addTextWrap(430, 773, 400, 16, $numFactura, 'left');
                 ////// Nº  FACTURA
                 $pdf_doc->pdf->addTextWrap(390, 698, 200, 14, $fecha);
                 $pdf_doc->pdf->addTextWrap(111, 648, 470, 14, $nomCliente);
                 $pdf_doc->pdf->addTextWrap(111, 633, 470, 10, $dirCliente . ' CP: ' . $cpCliente);
                 $pdf_doc->pdf->addTextWrap(111, 619, 280, 10, $locCliente . ' - ' . $provincia);
                 $pdf_doc->pdf->addTextWrap(444, 619, 200, 9, $telCliente1 . " / " . $telCliente2);
                 $pdf_doc->pdf->addTextWrap(132, 589, 200, 9, $catIVA);
                 //			$pdf_doc->pdf->addTextWrap		CUIT
                 //			$pdf_doc->pdf->addTextWrap		ING BRUTOS
                 //////////////////////////////////////////////////////////////////////////////////////
                 //////////////   CONTENIDO  DESCRIPCIÓN
                 //////////////////////////////////////////////////////////////////////////////////////
                 //Variable X p encolumnar importe
                 $varImporte = '465';
                 $Sub_Total = 0;
                 for ($i = $linea_arranque; $i < $linea_fin; $i++) {
                     //				$pdf_doc->pdf->addTextWrap(55,518-(22*($i-$linea_arranque)), 25, 12,number_format($lineas[$i]->cantidad, 0, ',', ' '),'right');
                     $pdf_doc->pdf->addTextWrap(85, 518 - 22 * ($i - $linea_arranque), 300, 12, $this->fix_html($lineas[$i]->descripcion), 'left');
                     //				$pdf_doc->pdf->addTextWrap(390,518-(22*($i-$linea_arranque)), 410, 12,$uMoneda.'  '.number_format($lineas[$i]->pvpunitario, 2, ',', 'right'));
                     //				$pdf_doc->pdf->addTextWrap(370,518-(22*($i-$linea_arranque)), 90, 12,$uMoneda.'  '.number_format($lineas[$i]->pvpunitario, 2, ',', ' '),'right');
                     //				$pdf_doc->pdf->addTextWrap(390,518-(22*($i-$linea_arranque)), 410, 12,$uMoneda.'  '.number_format($lineas[$i]->pvpunitario, 2, ',', 'right'));
                     $pdf_doc->pdf->addTextWrap($varImporte, 518 - 22 * ($i - $linea_arranque), 90, 12, number_format($lineas[$i]->pvptotal, 2, ',', ' '), 'right');
                     $Sub_Total = $Sub_Total + $lineas[$i]->pvptotal;
                 }
                 $pdf_doc->pdf->addTextWrap($varImporte - 10, 270, 90, 12, number_format($Sub_Total, 2, ',', ' '), 'right');
                 ////////////////////////////////////////////////////////////////////////////
                 ////////////    Pie
                 //
                 /*			$pdf_doc->new_table();
                             $pdf_doc->add_table_row(
                                array(
                                    'campo1' => "Cheque",
                                    'dato1' => $cheqNum,
                                    'campo2' => "Importe",
                                    'dato2' => $cheqImporte
                                )
                             );
                             $pdf_doc->add_table_row(
                                array(
                                    'campo1' => "Anticipo",
                                    'dato1' => $anticipoDetalle,
                                    'campo2' => "Efectivo",
                                    'dato2' => $efectivo
                                )
                             );
                 */
                 $pdf_doc->save_table(array('cols' => array('campo1' => array('justification' => 'right'), 'dato1' => array('justification' => 'left'), 'campo2' => array('justification' => 'right'), 'dato2' => array('justification' => 'left')), 'showLines' => 0, 'width' => 520, 'shaded' => 0));
                 $pdf_doc->pdf->ezText("\n", 10);
                 $valores = $cheqImporte + $anticipo + $efectivo + $tarjDebito + $tarjCredito;
                 /*		
                 			$pdf_doc->pdf->addTextWrap(111,195, 150, 12,$cheqNum);
                 			$pdf_doc->pdf->addTextWrap(283,195, 200, 12,$cheqBanco);
                 			$pdf_doc->pdf->addTextWrap($varImporte,190, 90, 12,$cheqImporte,'right');
                 			$pdf_doc->pdf->addTextWrap(111,166, 370, 12,$anticipoDetalle);
                 			$pdf_doc->pdf->addTextWrap($varImporte,161, 90, 12,$anticipo,'right');
                 			$pdf_doc->pdf->addTextWrap($varImporte,132, 90, 12,$efectivo,'right');
                 			$pdf_doc->pdf->addTextWrap(111,137, 370, 12,$efectivoDetalle);       
                 			$pdf_doc->pdf->addTextWrap($varImporte,104, 90, 12,$tarjDebito,'right');
                 			$pdf_doc->pdf->addTextWrap(140,109, 350, 12,$debitoDetalle);       
                 			$pdf_doc->pdf->addTextWrap($varImporte,76, 90, 12,$tarjCredito,'right');
                 			$pdf_doc->pdf->addTextWrap(140,81,350, 12,$creditoDetalle);
                 			$pdf_doc->pdf->addTextWrap($varImporte,48, 35, 12,$valores,'right');
                 */
                 $linea_actual++;
             }
         } else {
             // Imprimimos las páginas necesarias
             while ($linea_actual < $lineasfact) {
                 $lppag = 35;
                 /// líneas por página
                 /// salto de página
                 if ($linea_actual > 0) {
                     $pdf_doc->pdf->ezNewPage();
                 }
                 /*
                  * Creamos la cabecera de la página, en este caso para el modelo carta
                  */
                 if ($tipo == 'carta') {
                     $direccion = $this->factura->nombrecliente . "\n" . $this->factura->direccion;
                     if ($this->factura->codpostal and $this->factura->ciudad) {
                         $direccion .= "\n CP: " . $this->factura->codpostal . ' ' . $this->factura->ciudad;
                     } else {
                         if ($this->factura->ciudad) {
                             $direccion .= "\n" . $this->factura->ciudad;
                         }
                     }
                     if ($this->factura->provincia) {
                         $direccion .= "\n(" . $this->factura->provincia . ")";
                     }
                     $pdf_doc->pdf->ezText("\n\n", 10);
                     $pdf_doc->new_table();
                     $pdf_doc->add_table_row(array('campos' => "<b>" . ucfirst(FS_FACTURA) . ":</b>\n<b>Fecha:</b>\n<b>" . FS_CIFNIF . ":</b>", 'factura' => $this->factura->codigo . "\n" . $this->factura->fecha . "\n" . $this->factura->cifnif, 'cliente' => $this->fix_html($direccion)));
                     $pdf_doc->save_table(array('cols' => array('campos' => array('justification' => 'right', 'width' => 100), 'factura' => array('justification' => 'left'), 'cliente' => array('justification' => 'right')), 'showLines' => 0, 'width' => 520));
                     $pdf_doc->pdf->ezText("\n\n\n", 14);
                 } else {
                     /// ¿Añadimos el logo?
                     if (file_exists('tmp/' . FS_TMP_NAME . 'logo.png')) {
                         if (function_exists('imagecreatefromstring')) {
                             $pdf_doc->pdf->ezImage('tmp/' . FS_TMP_NAME . 'logo.png', 0, 200, 'none');
                             $lppag -= 2;
                             /// si metemos el logo, caben menos líneas
                         } else {
                             die('ERROR: no se encuentra la función imagecreatefromstring(). ' . 'Y por tanto no se puede usar el logotipo en los documentos.');
                         }
                     } else {
                         $pdf_doc->pdf->ezText("<b>" . $this->empresa->nombre . "</b>", 16, array('justification' => 'center'));
                         $pdf_doc->pdf->ezText(FS_CIFNIF . ": " . $this->empresa->cifnif, 8, array('justification' => 'center'));
                         $direccion = $this->empresa->direccion;
                         if ($this->empresa->codpostal) {
                             $direccion .= ' - ' . $this->empresa->codpostal;
                         }
                         if ($this->empresa->ciudad) {
                             $direccion .= ' - ' . $this->empresa->ciudad;
                         }
                         if ($this->empresa->provincia) {
                             $direccion .= ' (' . $this->empresa->provincia . ')';
                         }
                         if ($this->empresa->telefono) {
                             $direccion .= ' - Teléfono: ' . $this->empresa->telefono;
                         }
                         $pdf_doc->pdf->ezText($this->fix_html($direccion), 9, array('justification' => 'center'));
                     }
                     ////////////////////
                     //// CLIENTES  /////
                     /*
                      * Esta es la tabla con los datos del cliente:
                      * Factura:             Fecha:
                      * Cliente:             CIF/NIF:
                      * Dirección:           Teléfonos:
                      */
                     $pdf_doc->new_table();
                     $pdf_doc->add_table_row(array('campo1' => "<b>" . ucfirst(FS_FACTURA) . ":</b>", 'dato1' => $this->factura->codigo, 'campo2' => "<b>Fecha:</b>", 'dato2' => $this->factura->fecha));
                     $pdf_doc->add_table_row(array('campo1' => "<b>Cliente:</b>", 'dato1' => $this->fix_html($this->factura->nombrecliente), 'campo2' => "<b>" . FS_CIFNIF . ":</b>", 'dato2' => $this->factura->cifnif));
                     $pdf_doc->add_table_row(array('campo1' => "<b>Dirección:</b>", 'dato1' => $this->factura->direccion . ' CP: ' . $this->factura->codpostal . ' - ' . $this->factura->ciudad . ' (' . $this->factura->provincia . ')', 'campo2' => "<b>Teléfonos:</b>", 'dato2' => $this->cliente->telefono1 . '  ' . $this->cliente->telefono2));
                     $pdf_doc->save_table(array('cols' => array('campo1' => array('justification' => 'right'), 'dato1' => array('justification' => 'left'), 'campo2' => array('justification' => 'right'), 'dato2' => array('justification' => 'left')), 'showLines' => 0, 'width' => 520, 'shaded' => 0));
                     $pdf_doc->pdf->ezText("\n", 10);
                     /// en el tipo 'firma' caben menos líneas
                     if ($tipo == 'firma') {
                         $lppag -= 3;
                     }
                 }
                 /*
                  * Creamos la tabla con las lineas de la factura:
                  * 
                  * Descripción    Cantidad  PVP   DTO    Importe
                  */
                 $columnas = array('alb' => '<b>' . ucfirst(FS_ALBARAN) . '</b>', 'descripcion' => '<b>Descripción</b>', 'cantidad' => '<b>Cantidad</b>', 'pvp' => '<b>PVP</b>', 'dto' => '<b>DTO</b>', 'importe' => '<b>Importe</b>');
                 if (!$this->impresion['print_alb']) {
                     unset($columnas['alb']);
                 }
                 if (!$this->impresion['print_dto']) {
                     unset($columnas['dto']);
                 }
                 $pdf_doc->new_table();
                 $pdf_doc->add_table_header($columnas);
                 for ($i = $linea_actual; $linea_actual < $lppag + $i and $linea_actual < $lineasfact;) {
                     $descripcion = $this->fix_html($lineas[$linea_actual]->descripcion);
                     if ($this->impresion['print_ref'] and !is_null($lineas[$linea_actual]->referencia)) {
                         $descripcion = '<b>' . $lineas[$linea_actual]->referencia . '</b> ' . $descripcion;
                     }
                     //////////////////
                     //////// CONTENIDO
                     //////////////////
                     $fila = array('alb' => $lineas[$linea_actual]->albaran_numero(), 'descripcion' => $descripcion, 'cantidad' => $lineas[$linea_actual]->cantidad, 'pvp' => $this->show_precio($lineas[$linea_actual]->pvpunitario, $this->factura->coddivisa), 'dto' => $this->show_numero($lineas[$linea_actual]->dtopor, 0) . " %", 'importe' => $this->show_precio($lineas[$linea_actual]->pvptotal, $this->factura->coddivisa));
                     $pdf_doc->add_table_row($fila);
                     $linea_actual++;
                 }
                 $pdf_doc->save_table(array('fontSize' => 8, 'cols' => array('cantidad' => array('justification' => 'right'), 'pvp' => array('justification' => 'right'), 'dto' => array('justification' => 'right'), 'importe' => array('justification' => 'right')), 'width' => 520, 'shaded' => 0));
                 if ($linea_actual == count($lineas)) {
                     ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                     ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                     /*
                      * Añadimos la parte de la firma y las observaciones,
                      * para el tipo 'firma'
                      */
                     if ($tipo == 'firma') {
                         $pdf_doc->pdf->ezText("\n", 9);
                         $pdf_doc->new_table();
                         $pdf_doc->add_table_header(array('campo1' => "<b>Observaciones</b>", 'campo2' => "<b>Firma</b>"));
                         $pdf_doc->add_table_row(array('campo1' => $this->fix_html($this->factura->observaciones), 'campo2' => ""));
                         $pdf_doc->save_table(array('cols' => array('campo1' => array('justification' => 'left'), 'campo2' => array('justification' => 'right', 'width' => 100)), 'showLines' => 4, 'width' => 530, 'shaded' => 0));
                     } else {
                         if ($this->factura->observaciones != '') {
                             $pdf_doc->pdf->ezText("\n" . $this->fix_html($this->factura->observaciones), 9);
                         }
                     }
                     if (!$this->factura->pagada) {
                         $fp0 = new forma_pago();
                         $forma_pago = $fp0->get($this->factura->codpago);
                         if ($forma_pago) {
                             if (is_null($forma_pago->codcuenta)) {
                                 $pdf_doc->pdf->ezText("\n<b>Forma de pago</b>: " . $forma_pago->descripcion . "\n<b>Vencimiento</b>: " . $this->factura->vencimiento, 9);
                             } else {
                                 $texto_pago = "\n<b>Forma de pago</b>: " . $forma_pago->descripcion;
                                 if ($forma_pago->domiciliado) {
                                     $cbc0 = new cuenta_banco_cliente();
                                     $encontrada = FALSE;
                                     foreach ($cbc0->all_from_cliente($this->factura->codcliente) as $cbc) {
                                         if ($cbc->iban) {
                                             $texto_pago .= "\n<b>Domiciliado en</b>: " . $cbc->iban;
                                         } else {
                                             $texto_pago .= "\n<b>Domiciliado en</b>: " . $cbc->swift;
                                         }
                                         $encontrada = TRUE;
                                         break;
                                     }
                                     if (!$encontrada) {
                                         $texto_pago .= "\n<b>El cliente no tiene cuenta bancaria asignada.</b>";
                                     }
                                 } else {
                                     $cb0 = new cuenta_banco();
                                     $cuenta_banco = $cb0->get($forma_pago->codcuenta);
                                     if ($cuenta_banco) {
                                         if ($cuenta_banco->iban) {
                                             $texto_pago .= "\n<b>IBAN</b>: " . $cuenta_banco->iban;
                                         } else {
                                             $texto_pago .= "\n<b>SWIFT o BIC</b>: " . $cuenta_banco->swift;
                                         }
                                     }
                                 }
                                 $texto_pago .= "\n<b>Vencimiento</b>: " . $this->factura->vencimiento;
                                 $pdf_doc->pdf->ezText($texto_pago, 9);
                             }
                         }
                     }
                 }
                 $pdf_doc->set_y(80);
                 /*
                  * Rellenamos la última tabla de la página:
                  * 
                  * Página            Neto    IVA   Total
                  */
                 $pdf_doc->new_table();
                 $titulo = array('pagina' => '<b>Página</b>', 'neto' => '<b>Neto</b>');
                 $fila = array('pagina' => $pagina . '/' . ceil(count($lineas) / $lppag), 'neto' => $this->show_precio($this->factura->neto, $this->factura->coddivisa));
                 $opciones = array('cols' => array('neto' => array('justification' => 'right')), 'showLines' => 4, 'width' => 520);
                 foreach ($lineas_iva as $li) {
                     $imp = $this->impuesto->get($li->codimpuesto);
                     if ($imp) {
                         $titulo['iva' . $li->iva] = '<b>' . $imp->descripcion . '</b>';
                     } else {
                         $titulo['iva' . $li->iva] = '<b>' . FS_IVA . ' ' . $li->iva . '%</b>';
                     }
                     $fila['iva' . $li->iva] = $this->show_precio($li->totaliva, $this->factura->coddivisa);
                     if ($li->totalrecargo != 0) {
                         $fila['iva' . $li->iva] .= ' (RE: ' . $this->show_precio($li->totalrecargo, $this->factura->coddivisa) . ')';
                     }
                     $opciones['cols']['iva' . $li->iva] = array('justification' => 'right');
                 }
                 if ($this->factura->totalirpf != 0) {
                     $titulo['irpf'] = '<b>' . FS_IRPF . ' ' . $this->factura->irpf . '%</b>';
                     $fila['irpf'] = $this->show_precio(0 - $this->factura->totalirpf);
                     $opciones['cols']['irpf'] = array('justification' => 'right');
                 }
                 $titulo['liquido'] = '<b>Total</b>';
                 $fila['liquido'] = $this->show_precio($this->factura->total, $this->factura->coddivisa);
                 $opciones['cols']['liquido'] = array('justification' => 'right');
                 $pdf_doc->add_table_header($titulo);
                 $pdf_doc->add_table_row($fila);
                 $pdf_doc->save_table($opciones);
                 /// pié de página para la factura
                 $pdf_doc->pdf->addText(10, 10, 8, $pdf_doc->center_text($this->fix_html($this->empresa->pie_factura), 153), 0, 1.5);
                 $pagina++;
                 ///////////////////////////////////////////////////
             }
             ////////// FIN DE IF DE FIRMA
         }
     } else {
         $pdf_doc->pdf->ezText('¡' . ucfirst(FS_FACTURA) . ' sin líneas!', 20);
     }
     if ($archivo) {
         if (!file_exists('tmp/' . FS_TMP_NAME . 'enviar')) {
             mkdir('tmp/' . FS_TMP_NAME . 'enviar');
         }
         $pdf_doc->save('tmp/' . FS_TMP_NAME . 'enviar/' . $archivo);
     } else {
         $pdf_doc->show(FS_FACTURA . '_' . $this->factura->codigo . '.pdf');
     }
 }
 private function generar_pdf_factura($tipo = 'simple', $archivo = FALSE)
 {
     if (!$archivo) {
         /// desactivamos la plantilla HTML
         $this->template = FALSE;
     }
     /// Creamos el PDF y escribimos sus metadatos
     $pdf_doc = new fs_pdf();
     $pdf_doc->pdf->addInfo('Title', ucfirst(FS_FACTURA) . ' ' . $this->factura->codigo);
     $pdf_doc->pdf->addInfo('Subject', ucfirst(FS_FACTURA) . ' ' . $this->factura->codigo);
     $pdf_doc->pdf->addInfo('Author', $this->empresa->nombre);
     $lineas = $this->factura->get_lineas();
     $lineas_iva = $this->factura->get_lineas_iva();
     if ($lineas) {
         $lineasfact = count($lineas);
         $linea_actual = 0;
         $pagina = 1;
         // Imprimimos las páginas necesarias
         while ($linea_actual < $lineasfact) {
             $lppag = 35;
             /// líneas por página
             /// salto de página
             if ($linea_actual > 0) {
                 $pdf_doc->pdf->ezNewPage();
             }
             /*
              * Creamos la cabecera de la página, en este caso para el modelo carta
              */
             if ($tipo == 'carta') {
                 $this->generar_pdf_cabecera($pdf_doc, $lppag);
                 $direccion = $this->factura->nombrecliente . "\n" . $this->factura->direccion;
                 if ($this->factura->codpostal and $this->factura->ciudad) {
                     $direccion .= "\n CP: " . $this->factura->codpostal . ' ' . $this->factura->ciudad;
                 } else {
                     if ($this->factura->ciudad) {
                         $direccion .= "\n" . $this->factura->ciudad;
                     }
                 }
                 if ($this->factura->provincia) {
                     $direccion .= "\n(" . $this->factura->provincia . ")";
                 }
                 $pdf_doc->new_table();
                 $pdf_doc->add_table_row(array('campos' => "<b>" . ucfirst(FS_FACTURA) . ":</b>\n<b>Fecha:</b>\n<b>" . FS_CIFNIF . ":</b>", 'factura' => $this->factura->codigo . "\n" . $this->factura->fecha . "\n" . $this->factura->cifnif, 'cliente' => $this->fix_html($direccion)));
                 $pdf_doc->save_table(array('cols' => array('campos' => array('justification' => 'right', 'width' => 100), 'factura' => array('justification' => 'left'), 'cliente' => array('justification' => 'right')), 'showLines' => 0, 'width' => 520));
                 $pdf_doc->pdf->ezText("\n\n\n", 14);
             } else {
                 $this->generar_pdf_cabecera($pdf_doc, $lppag);
                 /*
                  * Esta es la tabla con los datos del cliente:
                  * Factura:             Fecha:
                  * Cliente:             CIF/NIF:
                  * Dirección:           Teléfonos:
                  */
                 $pdf_doc->new_table();
                 if ($this->factura->idfacturarect) {
                     $pdf_doc->add_table_row(array('campo1' => "<b>" . ucfirst(FS_FACTURA_RECTIFICATIVA) . ":</b>", 'dato1' => $this->factura->codigo, 'campo2' => "<b>Fecha:</b>", 'dato2' => $this->factura->fecha));
                     $pdf_doc->add_table_row(array('campo1' => "<b>Original:</b>", 'dato1' => $this->factura->codigorect, 'campo2' => '', 'dato2' => ''));
                 } else {
                     $pdf_doc->add_table_row(array('campo1' => "<b>" . ucfirst(FS_FACTURA) . ":</b>", 'dato1' => $this->factura->codigo, 'campo2' => "<b>Fecha:</b>", 'dato2' => $this->factura->fecha));
                 }
                 $pdf_doc->add_table_row(array('campo1' => "<b>Cliente:</b>", 'dato1' => $this->fix_html($this->factura->nombrecliente), 'campo2' => "<b>" . FS_CIFNIF . ":</b>", 'dato2' => $this->factura->cifnif));
                 $pdf_doc->add_table_row(array('campo1' => "<b>Dirección:</b>", 'dato1' => $this->factura->direccion . ' CP: ' . $this->factura->codpostal . ' - ' . $this->factura->ciudad . ' (' . $this->factura->provincia . ')', 'campo2' => "<b>Teléfonos:</b>", 'dato2' => $this->cliente->telefono1 . '  ' . $this->cliente->telefono2));
                 $pdf_doc->save_table(array('cols' => array('campo1' => array('justification' => 'right'), 'dato1' => array('justification' => 'left'), 'campo2' => array('justification' => 'right'), 'dato2' => array('justification' => 'left')), 'showLines' => 0, 'width' => 520, 'shaded' => 0));
                 $pdf_doc->pdf->ezText("\n", 10);
             }
             $this->generar_pdf_lineas($pdf_doc, $lineas, $linea_actual, $lppag, $this->factura);
             if ($linea_actual == count($lineas)) {
                 if ($this->factura->observaciones != '') {
                     $pdf_doc->pdf->ezText("\n" . $this->fix_html($this->factura->observaciones), 9);
                 }
                 if (!$this->factura->pagada and $this->impresion['print_formapago']) {
                     $fp0 = new forma_pago();
                     $forma_pago = $fp0->get($this->factura->codpago);
                     if ($forma_pago) {
                         $texto_pago = "\n<b>Forma de pago</b>: " . $forma_pago->descripcion;
                         if ($forma_pago->domiciliado) {
                             $cbc0 = new cuenta_banco_cliente();
                             $encontrada = FALSE;
                             foreach ($cbc0->all_from_cliente($this->factura->codcliente) as $cbc) {
                                 $texto_pago .= "\n<b>Domiciliado en</b>: ";
                                 if ($cbc->iban) {
                                     $texto_pago .= $cbc->iban;
                                 }
                                 if ($cbc->swift) {
                                     $texto_pago .= "  <b>SWIFT/BIC</b>: " . $cbc->swift;
                                 }
                                 $encontrada = TRUE;
                                 break;
                             }
                             if (!$encontrada) {
                                 $texto_pago .= "\n<b>El cliente no tiene cuenta bancaria asignada.</b>";
                             }
                         } else {
                             if ($forma_pago->codcuenta) {
                                 $cb0 = new cuenta_banco();
                                 $cuenta_banco = $cb0->get($forma_pago->codcuenta);
                                 if ($cuenta_banco) {
                                     if ($cuenta_banco->iban) {
                                         $texto_pago .= "\n<b>IBAN</b>: " . $cuenta_banco->iban;
                                     }
                                     if ($cuenta_banco->swift) {
                                         $texto_pago .= "\n<b>SWIFT o BIC</b>: " . $cuenta_banco->swift;
                                     }
                                 }
                             }
                         }
                         $texto_pago .= "\n<b>Vencimiento</b>: " . $this->factura->vencimiento;
                         $pdf_doc->pdf->ezText($texto_pago, 9);
                     }
                 }
             }
             $pdf_doc->set_y(80);
             /*
              * Rellenamos la última tabla de la página:
              * 
              * Página            Neto    IVA   Total
              */
             $pdf_doc->new_table();
             $titulo = array('pagina' => '<b>Página</b>', 'neto' => '<b>Neto</b>');
             $fila = array('pagina' => $pagina . '/' . ceil(count($lineas) / $lppag), 'neto' => $this->show_precio($this->factura->neto, $this->factura->coddivisa));
             $opciones = array('cols' => array('neto' => array('justification' => 'right')), 'showLines' => 4, 'width' => 520);
             foreach ($lineas_iva as $li) {
                 $imp = $this->impuesto->get($li->codimpuesto);
                 if ($imp) {
                     $titulo['iva' . $li->iva] = '<b>' . $imp->descripcion . '</b>';
                 } else {
                     $titulo['iva' . $li->iva] = '<b>' . FS_IVA . ' ' . $li->iva . '%</b>';
                 }
                 $fila['iva' . $li->iva] = $this->show_precio($li->totaliva, $this->factura->coddivisa);
                 if ($li->totalrecargo != 0) {
                     $fila['iva' . $li->iva] .= ' (RE: ' . $this->show_precio($li->totalrecargo, $this->factura->coddivisa) . ')';
                 }
                 $opciones['cols']['iva' . $li->iva] = array('justification' => 'right');
             }
             if ($this->factura->totalirpf != 0) {
                 $titulo['irpf'] = '<b>' . FS_IRPF . ' ' . $this->factura->irpf . '%</b>';
                 $fila['irpf'] = $this->show_precio($this->factura->totalirpf);
                 $opciones['cols']['irpf'] = array('justification' => 'right');
             }
             $titulo['liquido'] = '<b>Total</b>';
             $fila['liquido'] = $this->show_precio($this->factura->total, $this->factura->coddivisa);
             $opciones['cols']['liquido'] = array('justification' => 'right');
             $pdf_doc->add_table_header($titulo);
             $pdf_doc->add_table_row($fila);
             $pdf_doc->save_table($opciones);
             /// pié de página para la factura
             $pdf_doc->pdf->addText(10, 10, 8, $pdf_doc->center_text($this->fix_html($this->empresa->pie_factura), 153), 0, 1.5);
             $pagina++;
         }
     } else {
         $pdf_doc->pdf->ezText('¡' . ucfirst(FS_FACTURA) . ' sin líneas!', 20);
     }
     if ($archivo) {
         if (!file_exists('tmp/' . FS_TMP_NAME . 'enviar')) {
             mkdir('tmp/' . FS_TMP_NAME . 'enviar');
         }
         $pdf_doc->save('tmp/' . FS_TMP_NAME . 'enviar/' . $archivo);
     } else {
         $pdf_doc->show(FS_FACTURA . '_' . $this->factura->codigo . '.pdf');
     }
 }
 protected function process()
 {
     $this->almacen = new almacen();
     $this->cuenta_banco = new cuenta_banco();
     $this->divisa = new divisa();
     $this->ejercicio = new ejercicio();
     $this->forma_pago = new forma_pago();
     $this->serie = new serie();
     $this->pais = new pais();
     /// obtenemos los datos de configuración del email
     $this->mail = array('mail_host' => 'smtp.gmail.com', 'mail_port' => '465', 'mail_enc' => 'ssl', 'mail_user' => '');
     $fsvar = new fs_var();
     $this->mail = $fsvar->array_get($this->mail, FALSE);
     if (isset($_POST['nombre'])) {
         /*
          * Guardamos los elementos por defecto
          */
         $this->save_codalmacen($_POST['codalmacen']);
         $this->save_coddivisa($_POST['coddivisa']);
         $this->save_codejercicio($_POST['codejercicio']);
         $this->save_codpago($_POST['codpago']);
         $this->save_codserie($_POST['codserie']);
         $this->save_codpais($_POST['codpais']);
         /// guardamos los datos de la empresa
         $this->empresa->nombre = $_POST['nombre'];
         $this->empresa->nombrecorto = $_POST['nombrecorto'];
         $this->empresa->cifnif = $_POST['cifnif'];
         $this->empresa->administrador = $_POST['administrador'];
         $this->empresa->codpais = $_POST['codpais'];
         $this->empresa->provincia = $_POST['provincia'];
         $this->empresa->ciudad = $_POST['ciudad'];
         $this->empresa->direccion = $_POST['direccion'];
         $this->empresa->codpostal = $_POST['codpostal'];
         $this->empresa->telefono = $_POST['telefono'];
         $this->empresa->fax = $_POST['fax'];
         $this->empresa->web = $_POST['web'];
         $this->empresa->email = $_POST['email'];
         $this->empresa->email_firma = $_POST['email_firma'];
         $this->empresa->email_password = $_POST['email_password'];
         $this->empresa->lema = $_POST['lema'];
         $this->empresa->horario = $_POST['horario'];
         $this->empresa->contintegrada = isset($_POST['contintegrada']);
         $this->empresa->codejercicio = $_POST['codejercicio'];
         $this->empresa->codserie = $_POST['codserie'];
         $this->empresa->coddivisa = $_POST['coddivisa'];
         $this->empresa->codpago = $_POST['codpago'];
         $this->empresa->codalmacen = $_POST['codalmacen'];
         $this->empresa->pie_factura = $_POST['pie_factura'];
         $this->empresa->recequivalencia = isset($_POST['recequivalencia']);
         if ($this->empresa->save()) {
             $this->new_message('Datos guardados correctamente.');
             $step = $fsvar->simple_get('install_step');
             if ($step == 2) {
                 if (in_array('facturacion_base', $GLOBALS['plugins'])) {
                     $this->new_message('Y por último tienes que <a href="index.php?page=contabilidad_ejercicio&cod=' . $this->empresa->codejercicio . '">importar los datos del ejercicio</a>.');
                 }
                 $fsvar->simple_save('install_step', 3);
             }
         } else {
             $this->new_error_msg('Error al guardar los datos.');
         }
         /// guardamos los datos del email
         if (isset($_POST['mail_host'])) {
             if ($_POST['mail_host'] == '') {
                 $this->mail['mail_host'] = 'smtp.gmail.com';
             } else {
                 $this->mail['mail_host'] = $_POST['mail_host'];
             }
             if ($_POST['mail_port'] == '') {
                 $this->mail['mail_port'] = '465';
             } else {
                 $this->mail['mail_port'] = $_POST['mail_port'];
             }
             $this->mail['mail_enc'] = strtolower($_POST['mail_enc']);
             $this->mail['mail_user'] = $_POST['mail_user'];
             $fsvar->array_save($this->mail);
             $this->mail_test();
         }
     } else {
         if (isset($_POST['logo'])) {
             if (is_uploaded_file($_FILES['fimagen']['tmp_name'])) {
                 copy($_FILES['fimagen']['tmp_name'], "tmp/" . FS_TMP_NAME . "logo.png");
                 $this->new_message('Logotipo guardado correctamente.');
             }
         } else {
             if (isset($_GET['delete_logo'])) {
                 if (file_exists('tmp/' . FS_TMP_NAME . 'logo.png')) {
                     unlink('tmp/' . FS_TMP_NAME . 'logo.png');
                     $this->new_message('Logotipo borrado correctamente.');
                 }
             } else {
                 if (isset($_GET['delete_cuenta'])) {
                     $cuenta = $this->cuenta_banco->get($_GET['delete_cuenta']);
                     if ($cuenta) {
                         if ($cuenta->delete()) {
                             $this->new_message('Cuenta bancaria eliminada correctamente.');
                         } else {
                             $this->new_error_msg('Imposible eliminar la cuenta bancaria.');
                         }
                     } else {
                         $this->new_error_msg('Cuenta bancaria no encontrada.');
                     }
                 } else {
                     if (isset($_POST['iban'])) {
                         if (isset($_POST['codcuenta'])) {
                             $cuentab = $this->cuenta_banco->get($_POST['codcuenta']);
                         } else {
                             $cuentab = new cuenta_banco();
                         }
                         $cuentab->descripcion = $_POST['descripcion'];
                         if ($_POST['ciban'] != '') {
                             $cuentab->iban = $cuentab->calcular_iban($_POST['ciban']);
                         } else {
                             $cuentab->iban = $_POST['iban'];
                         }
                         $cuentab->swift = $_POST['swift'];
                         if ($cuentab->save()) {
                             $this->new_message('Cuenta bancaria guardada correctamente.');
                         } else {
                             $this->new_error_msg('Imposible guardar la cuenta bancaria.');
                         }
                     }
                 }
             }
         }
     }
     $this->logo = file_exists('tmp/' . FS_TMP_NAME . 'logo.png');
 }
 protected function process()
 {
     $this->show_fs_toolbar = FALSE;
     $this->almacen = new almacen();
     $this->cuenta_banco = new cuenta_banco();
     $this->divisa = new divisa();
     $this->ejercicio = new ejercicio();
     $this->forma_pago = new forma_pago();
     $this->serie = new serie();
     $this->pais = new pais();
     /// obtenemos los datos de configuración del email
     $this->mail = array('mail_host' => 'smtp.gmail.com', 'mail_port' => '465', 'mail_enc' => 'ssl', 'mail_user' => '');
     $fsvar = new fs_var();
     $this->mail = $fsvar->array_get($this->mail, FALSE);
     if (isset($_POST['nombre'])) {
         /*
          * Guardamos los elementos por defecto
          */
         $this->save_codalmacen($_POST['codalmacen']);
         $this->save_coddivisa($_POST['coddivisa']);
         $this->save_codejercicio($_POST['codejercicio']);
         $this->save_codpago($_POST['codpago']);
         $this->save_codserie($_POST['codserie']);
         $this->save_codpais($_POST['codpais']);
         /// guardamos los datos de la empresa
         $this->empresa->nombre = $_POST['nombre'];
         $this->empresa->nombrecorto = $_POST['nombrecorto'];
         $this->empresa->cifnif = $_POST['cifnif'];
         $this->empresa->administrador = $_POST['administrador'];
         $this->empresa->codpais = $_POST['codpais'];
         $this->empresa->provincia = $_POST['provincia'];
         $this->empresa->ciudad = $_POST['ciudad'];
         $this->empresa->direccion = $_POST['direccion'];
         $this->empresa->codpostal = $_POST['codpostal'];
         $this->empresa->telefono = $_POST['telefono'];
         $this->empresa->fax = $_POST['fax'];
         $this->empresa->web = $_POST['web'];
         $this->empresa->email = $_POST['email'];
         $this->empresa->email_firma = $_POST['email_firma'];
         $this->empresa->email_password = $_POST['email_password'];
         $this->empresa->lema = $_POST['lema'];
         $this->empresa->horario = $_POST['horario'];
         $this->empresa->contintegrada = isset($_POST['contintegrada']);
         $this->empresa->codejercicio = $_POST['codejercicio'];
         $this->empresa->codserie = $_POST['codserie'];
         $this->empresa->coddivisa = $_POST['coddivisa'];
         $this->empresa->codpago = $_POST['codpago'];
         $this->empresa->codalmacen = $_POST['codalmacen'];
         $this->empresa->pie_factura = $_POST['pie_factura'];
         $this->empresa->recequivalencia = isset($_POST['recequivalencia']);
         if ($this->empresa->save()) {
             $this->new_message('Datos guardados correctamente.');
             $eje0 = $this->ejercicio->get_by_fecha($this->today());
             if ($eje0) {
                 $this->new_message('Ahora es el momento de <a href="' . $eje0->url() . '">
               importar los datos del ejercicio fiscal</a>, si todavía no lo has hecho.');
             }
         } else {
             $this->new_error_msg('Error al guardar los datos.');
         }
         /// guardamos los datos del email
         if (isset($_POST['mail_host'])) {
             if ($_POST['mail_host'] == '') {
                 $this->mail['mail_host'] = 'smtp.gmail.com';
             } else {
                 $this->mail['mail_host'] = $_POST['mail_host'];
             }
             if ($_POST['mail_port'] == '') {
                 $this->mail['mail_port'] = '465';
             } else {
                 $this->mail['mail_port'] = $_POST['mail_port'];
             }
             $this->mail['mail_enc'] = strtolower($_POST['mail_enc']);
             $this->mail['mail_user'] = $_POST['mail_user'];
             $fsvar->array_save($this->mail);
         }
     } else {
         if (isset($_POST['logo'])) {
             if (is_uploaded_file($_FILES['fimagen']['tmp_name'])) {
                 copy($_FILES['fimagen']['tmp_name'], "tmp/" . FS_TMP_NAME . "logo.png");
                 $this->new_message('Logotipo guardado correctamente.');
             }
         } else {
             if (isset($_GET['delete_logo'])) {
                 if (file_exists('tmp/' . FS_TMP_NAME . 'logo.png')) {
                     unlink('tmp/' . FS_TMP_NAME . 'logo.png');
                     $this->new_message('Logotipo borrado correctamente.');
                 }
             } else {
                 if (isset($_GET['delete_cuenta'])) {
                     $cuenta = $this->cuenta_banco->get($_GET['delete_cuenta']);
                     if ($cuenta) {
                         if ($cuenta->delete()) {
                             $this->new_message('Cuenta bancaria eliminada correctamente.');
                         } else {
                             $this->new_error_msg('Imposible eliminar la cuenta bancaria.');
                         }
                     } else {
                         $this->new_error_msg('Cuenta bancaria no encontrada.');
                     }
                 } else {
                     if (isset($_POST['iban'])) {
                         if (isset($_POST['codcuenta'])) {
                             $cuentab = $this->cuenta_banco->get($_POST['codcuenta']);
                         } else {
                             $cuentab = new cuenta_banco();
                         }
                         $cuentab->descripcion = $_POST['descripcion'];
                         if ($_POST['ciban'] != '') {
                             $cuentab->iban = $this->calcular_iban($_POST['ciban']);
                         } else {
                             $cuentab->iban = $_POST['iban'];
                         }
                         if ($cuentab->save()) {
                             $this->new_message('Cuenta bancaria guardada correctamente.');
                         } else {
                             $this->new_error_msg('Imposible guardar la cuenta bancaria.');
                         }
                     }
                 }
             }
         }
     }
     // Bank account stuff ENDS
     $this->logo = file_exists('tmp/' . FS_TMP_NAME . 'logo.png');
 }
 private function _genera_formapago()
 {
     $texto_pago = array();
     $fp0 = new forma_pago();
     $forma_pago = $fp0->get($this->factura->codpago);
     if ($forma_pago) {
         $texto_pago[] = $forma_pago->descripcion;
         if ($forma_pago->domiciliado) {
             $cbc0 = new cuenta_banco_cliente();
             $encontrada = FALSE;
             foreach ($cbc0->all_from_cliente($this->factura->codcliente) as $cbc) {
                 $tmp_textopago = "Domiciliado en: ";
                 if ($cbc->iban) {
                     $texto_pago[] = $tmp_textopago . $cbc->iban(TRUE);
                 }
                 if ($cbc->swift) {
                     $texto_pago[] = "SWIFT/BIC: " . $cbc->swift;
                 }
                 $encontrada = TRUE;
                 break;
             }
             if (!$encontrada) {
                 $texto_pago[] = "Cliente sin cuenta bancaria asignada";
             }
         } else {
             if ($forma_pago->codcuenta) {
                 $cb0 = new cuenta_banco();
                 $cuenta_banco = $cb0->get($forma_pago->codcuenta);
                 if ($cuenta_banco) {
                     if ($cuenta_banco->iban) {
                         $texto_pago[] = "IBAN: " . $cuenta_banco->iban(TRUE);
                     }
                     if ($cuenta_banco->swift) {
                         $texto_pago[] = "SWIFT o BIC: " . $cuenta_banco->swift;
                     }
                 }
             }
         }
         $texto_pago[] = "Vencimiento: " . $this->factura->vencimiento;
     }
     return $texto_pago;
 }
示例#10
0
 private function get_subcuentas()
 {
     $this->ejercicio = FALSE;
     $this->subcuenta_pro = FALSE;
     $this->subcuentas_pago = array();
     $subcuenta = new subcuenta();
     $pro = new proveedor();
     $this->proveedor = $pro->get($this->recibo->codproveedor);
     if ($this->proveedor) {
         $eje0 = new ejercicio();
         if (isset($_POST['fecha'])) {
             $this->ejercicio = $eje0->get_by_fecha($_POST['fecha']);
         } else {
             $this->ejercicio = $eje0->get_by_fecha($this->today());
         }
         if ($this->ejercicio) {
             $this->subcuenta_pro = $this->proveedor->get_subcuenta($this->ejercicio->codejercicio);
             /// añadimos la subcuenta de la cuenta bancaria
             $cb0 = new cuenta_banco();
             $fp0 = new forma_pago();
             $formap = $fp0->get($this->recibo->codpago);
             if ($formap) {
                 if ($formap->codcuenta) {
                     $cuentab = $cb0->get($formap->codcuenta);
                     if ($cuentab) {
                         $subc = $subcuenta->get_by_codigo($cuentab->codsubcuenta, $this->ejercicio->codejercicio);
                         if ($subc) {
                             $this->subcuentas_pago[] = $subc;
                         }
                     }
                 }
             }
             /// añadimos todas las subcuentas de caja
             $sql = "SELECT * FROM co_subcuentas WHERE idcuenta IN " . "(SELECT idcuenta FROM co_cuentas WHERE codejercicio = " . $this->ejercicio->var2str($this->ejercicio->codejercicio) . " AND idcuentaesp = 'CAJA');";
             $data = $this->db->select($sql);
             if ($data) {
                 foreach ($data as $d) {
                     $this->subcuentas_pago[] = new subcuenta($d);
                 }
             }
         } else {
             $this->new_error_msg('Ejercicio no encontrado.');
         }
     }
 }