Advertisement
Guest User

ventas_imprimir-MODIF.php

a guest
Jul 24th, 2017
812
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 37.20 KB | None | 0 0
  1. <?php
  2. /*
  3.  * This file is part of facturacion_base
  4.  * Copyright (C) 2014-2017    Carlos Garcia Gomez     neorazorx@gmail.com
  5.  * Copyright (C) 2017         Francesc Pineda Segarra shawe.ewahs@gmail.com
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU Lesser General Public License as
  9.  * published by the Free Software Foundation, either version 3 of the
  10.  * License, or (at your option) any later version.
  11.  *
  12.  * This program is distributed in the hope that it will be useful,
  13.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15.  * GNU Lesser General Public License for more details.
  16.  *
  17.  * You should have received a copy of the GNU Lesser General Public License
  18.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  19.  */
  20.  
  21. require_once 'plugins/facturacion_base/extras/fs_pdf.php';
  22. require_once 'extras/phpmailer/class.phpmailer.php';
  23. require_once 'extras/phpmailer/class.smtp.php';
  24. require_model('articulo_traza.php');
  25. require_model('cliente.php');
  26. require_model('cuenta_banco.php');
  27. require_model('cuenta_banco_cliente.php');
  28. require_model('forma_pago.php');
  29. require_model('pais.php');
  30.  
  31. /**
  32.  * Esta clase agrupa los procedimientos de imprimir/enviar albaranes y facturas.
  33.  */
  34. class ventas_imprimir extends fs_controller
  35. {
  36.  
  37.     public $articulo_traza;
  38.     public $cliente;
  39.     public $documento;
  40.     public $impresion;
  41.     public $impuesto;
  42.     private $numpaginas;
  43.  
  44.     public function __construct()
  45.     {
  46.         parent::__construct(__CLASS__, 'imprimir', 'ventas', FALSE, FALSE);
  47.     }
  48.  
  49.     protected function private_core()
  50.     {
  51.         $this->cliente = FALSE;
  52.         $this->documento = FALSE;
  53.         $this->impuesto = new impuesto();
  54.  
  55.         /// obtenemos los datos de configuración de impresión
  56.         $this->impresion = array(
  57.             'print_ref' => '1',
  58.             'print_dto' => '1',
  59.             'print_alb' => '0',
  60.             'print_formapago' => '1'
  61.         );
  62.         $fsvar = new fs_var();
  63.         $this->impresion = $fsvar->array_get($this->impresion, FALSE);
  64.  
  65.         if (isset($_REQUEST['albaran']) AND isset($_REQUEST['id'])) {
  66.             $this->articulo_traza = new articulo_traza();
  67.  
  68.             $alb = new albaran_cliente();
  69.             $this->documento = $alb->get($_REQUEST['id']);
  70.             if ($this->documento) {
  71.                 $cliente = new cliente();
  72.                 $this->cliente = $cliente->get($this->documento->codcliente);
  73.             }
  74.  
  75.             if (isset($_POST['email'])) {
  76.                 $this->enviar_email('albaran');
  77.             } else
  78.                 $this->generar_pdf_albaran();
  79.         } else if (isset($_REQUEST['factura']) AND isset($_REQUEST['id'])) {
  80.             $this->articulo_traza = new articulo_traza();
  81.  
  82.             $fac = new factura_cliente();
  83.             $this->documento = $fac->get($_REQUEST['id']);
  84.             if ($this->documento) {
  85.                 $cliente = new cliente();
  86.                 $this->cliente = $cliente->get($this->documento->codcliente);
  87.             }
  88.  
  89.             if (isset($_POST['email'])) {
  90.                 $this->enviar_email('factura', $_REQUEST['tipo']);
  91.             } else
  92.                 $this->generar_pdf_factura($_REQUEST['tipo']);
  93.         }
  94.  
  95.         $this->share_extensions();
  96.     }
  97.  
  98.     private function share_extensions()
  99.     {
  100.         $extensiones = array(
  101.             array(
  102.                 'name' => 'imprimir_albaran',
  103.                 'page_from' => __CLASS__,
  104.                 'page_to' => 'ventas_albaran',
  105.                 'type' => 'pdf',
  106.                 'text' => '<span class="glyphicon glyphicon-print"></span>&nbsp; ' . ucfirst(FS_ALBARAN) . ' simple',
  107.                 'params' => '&albaran=TRUE'
  108.             ),
  109.             array(
  110.                 'name' => 'imprimir_albaran_noval',
  111.                 'page_from' => __CLASS__,
  112.                 'page_to' => 'ventas_albaran',
  113.                 'type' => 'pdf',
  114.                 'text' => '<span class="glyphicon glyphicon-print"></span>&nbsp; ' . ucfirst(FS_ALBARAN) . ' sin valorar',
  115.                 'params' => '&albaran=TRUE&noval=TRUE'
  116.             ),
  117.             array(
  118.                 'name' => 'email_albaran',
  119.                 'page_from' => __CLASS__,
  120.                 'page_to' => 'ventas_albaran',
  121.                 'type' => 'email',
  122.                 'text' => ucfirst(FS_ALBARAN) . ' simple',
  123.                 'params' => '&albaran=TRUE'
  124.             ),
  125.             array(
  126.                 'name' => 'imprimir_factura',
  127.                 'page_from' => __CLASS__,
  128.                 'page_to' => 'ventas_factura',
  129.                 'type' => 'pdf',
  130.                 'text' => '<span class="glyphicon glyphicon-print"></span>&nbsp; ' . ucfirst(FS_FACTURA) . ' simple',
  131.                 'params' => '&factura=TRUE&tipo=simple'
  132.             ),
  133.             array(
  134.                 'name' => 'imprimir_factura_carta',
  135.                 'page_from' => __CLASS__,
  136.                 'page_to' => 'ventas_factura',
  137.                 'type' => 'pdf',
  138.                 'text' => '<span class="glyphicon glyphicon-print"></span>&nbsp; Modelo carta',
  139.                 'params' => '&factura=TRUE&tipo=carta'
  140.             ),
  141.             array(
  142.                 'name' => 'email_factura',
  143.                 'page_from' => __CLASS__,
  144.                 'page_to' => 'ventas_factura',
  145.                 'type' => 'email',
  146.                 'text' => ucfirst(FS_FACTURA) . ' simple',
  147.                 'params' => '&factura=TRUE&tipo=simple'
  148.             )
  149.         );
  150.         foreach ($extensiones as $ext) {
  151.             $fsext = new fs_extension($ext);
  152.             if (!$fsext->save()) {
  153.                 $this->new_error_msg('Error al guardar la extensión ' . $ext['name']);
  154.             }
  155.         }
  156.     }
  157.  
  158.     private function generar_pdf_lineas(&$pdf_doc, &$lineas, &$linea_actual, &$lppag)
  159.     {
  160.         /// calculamos el número de páginas
  161.         if (!isset($this->numpaginas)) {
  162.             $this->numpaginas = 0;
  163.             $linea_a = 0;
  164.             while ($linea_a < count($lineas)) {
  165.                 $lppag2 = $lppag;
  166.                 foreach ($lineas as $i => $lin) {
  167.                     if ($i >= $linea_a AND $i < $linea_a + $lppag2) {
  168.                         $linea_size = 1;
  169.                        
  170.                         $len = mb_strlen($lin->descripcion.' ');    /// -------------------------- Cambiado
  171.                         if ($this->impresion['print_ref']){
  172.                         $len = mb_strlen($lin->referencia . ' ' . $lin->descripcion);
  173.                         }                                           /// -------------------------- Cambiado
  174.                         while ($len > 85) {
  175.                             $len -= 85;
  176.                             $linea_size += 0.5;
  177.                         }
  178.  
  179.                         $aux = explode("\n", $lin->descripcion);
  180.                         if (count($aux) > 1) {
  181.                             $linea_size += 0.5 * ( count($aux) - 1);
  182.                         }
  183.  
  184.                         if ($linea_size > 1) {
  185.                             $lppag2 -= $linea_size - 1;
  186.                         }
  187.                     }
  188.                 }
  189.  
  190.                 $linea_a += $lppag2;
  191.                 $this->numpaginas++;
  192.             }
  193.  
  194.             if ($this->numpaginas == 0) {
  195.                 $this->numpaginas = 1;
  196.             }
  197.         }
  198.  
  199.         if ($this->impresion['print_dto']) {
  200.             $this->impresion['print_dto'] = FALSE;
  201.  
  202.             /// leemos las líneas para ver si de verdad mostramos los descuentos
  203.             foreach ($lineas as $lin) {
  204.                 if ($lin->dtopor != 0) {
  205.                     $this->impresion['print_dto'] = TRUE;
  206.                     break;
  207.                 }
  208.             }
  209.         }
  210.  
  211.         $dec_cantidad = 0;
  212.         $multi_iva = FALSE;
  213.         $multi_re = FALSE;
  214.         $multi_irpf = FALSE;
  215.         $iva = FALSE;
  216.         $re = FALSE;
  217.         $irpf = FALSE;
  218.         /// leemos las líneas para ver si hay que mostrar los tipos de iva, re o irpf
  219.         foreach ($lineas as $i => $lin) {
  220.             if ($lin->cantidad != intval($lin->cantidad)) {
  221.                 $dec_cantidad = 2;
  222.             }
  223.  
  224.             if ($iva === FALSE) {
  225.                 $iva = $lin->iva;
  226.             } else if ($lin->iva != $iva) {
  227.                 $multi_iva = TRUE;
  228.             }
  229.  
  230.             if ($re === FALSE) {
  231.                 $re = $lin->recargo;
  232.             } else if ($lin->recargo != $re) {
  233.                 $multi_re = TRUE;
  234.             }
  235.  
  236.             if ($irpf === FALSE) {
  237.                 $irpf = $lin->irpf;
  238.             } else if ($lin->irpf != $irpf) {
  239.                 $multi_irpf = TRUE;
  240.             }
  241.  
  242.             /// restamos líneas al documento en función del tamaño de la descripción
  243.             if ($i >= $linea_actual AND $i < $linea_actual + $lppag) {
  244.                 $linea_size = 1;
  245.                
  246.                 $len = mb_strlen($lin->descripcion.' ');    /// -------------------------- Cambiado
  247.                 if ($this->impresion['print_ref'])
  248.                     {
  249.                     $len = mb_strlen($lin->referencia . ' ' . $lin->descripcion);          
  250.                 }                                           /// -------------------------- Cambiado
  251.                 while ($len > 85) {
  252.                     $len -= 85;
  253.                     $linea_size += 0.5;
  254.                 }
  255.  
  256.                 $aux = explode("\n", $lin->descripcion);
  257.                 if (count($aux) > 1) {
  258.                     $linea_size += 0.5 * ( count($aux) - 1);
  259.                 }
  260.  
  261.                 if ($linea_size > 1) {
  262.                     $lppag -= $linea_size - 1;
  263.                 }
  264.             }
  265.         }
  266.  
  267.         /*
  268.          * Creamos la tabla con las lineas del documento
  269.          */
  270.         $pdf_doc->new_table();
  271.        
  272.         $table_header = array(    ///------------------------------- Cambiado
  273.             'alb' => '<b>' . ucfirst(FS_ALBARAN) . '</b>',
  274.             'descripcion' => '<b>Descripción</b>',
  275.             'cantidad' => '<b>Cant.</b>',
  276.             'pvp' => '<b>Precio</b>',
  277.         );
  278.        
  279.         if ($this->impresion['print_ref']) {       
  280.         $table_header = array(
  281.             'alb' => '<b>' . ucfirst(FS_ALBARAN) . '</b>',
  282.             'descripcion' => '<b>Ref. + Descripción</b>',
  283.             'cantidad' => '<b>Cant.</b>',
  284.             'pvp' => '<b>Precio</b>',
  285.         );
  286.         }    ///----------------------------------------------------- Cambiado
  287.        
  288.         /// ¿Desactivamos la columna de albaran?
  289.         if (get_class_name($this->documento) == 'factura_cliente') {
  290.             if ($this->impresion['print_alb']) {
  291.                 /// aunque esté activada, si la factura no viene de un albaran, la desactivamos
  292.                 $this->impresion['print_alb'] = FALSE;
  293.                 foreach ($lineas as $lin) {
  294.                     if ($lin->idalbaran) {
  295.                         $this->impresion['print_alb'] = TRUE;
  296.                         break;
  297.                     }
  298.                 }
  299.             }
  300.  
  301.             if (!$this->impresion['print_alb']) {
  302.                 unset($table_header['alb']);
  303.             }
  304.         } else {
  305.             unset($table_header['alb']);
  306.         }
  307.  
  308.         if ($this->impresion['print_dto'] AND ! isset($_GET['noval'])) {
  309.             $table_header['dto'] = '<b>Dto.</b>';
  310.         }
  311.  
  312.         if ($multi_iva AND ! isset($_GET['noval'])) {
  313.             $table_header['iva'] = '<b>' . FS_IVA . '</b>';
  314.         }
  315.  
  316.         if ($multi_re AND ! isset($_GET['noval'])) {
  317.             $table_header['re'] = '<b>R.E.</b>';
  318.         }
  319.  
  320.         if ($multi_irpf AND ! isset($_GET['noval'])) {
  321.             $table_header['irpf'] = '<b>' . FS_IRPF . '</b>';
  322.         }
  323.  
  324.         if (isset($_GET['noval'])) {
  325.             unset($table_header['pvp']);
  326.         } else {
  327.             $table_header['importe'] = '<b>Importe</b>';
  328.         }
  329.  
  330.         $pdf_doc->add_table_header($table_header);
  331.  
  332.         for ($i = $linea_actual; (($linea_actual < ($lppag + $i)) AND ( $linea_actual < count($lineas)));) {
  333.             $descripcion = fs_fix_html($lineas[$linea_actual]->descripcion);
  334.    
  335.         if (!is_null($lineas[$linea_actual]->referencia)) {
  336.            
  337.             ///----------------------------------------------------- Cambiado
  338.             if ($this->impresion['print_ref']) {
  339.                 $descripcion = '<b>' . $lineas[$linea_actual]->referencia . '</b> ' . $descripcion;
  340.             }
  341.         }
  342.             /// ¿El articulo tiene trazabilidad?
  343.             $descripcion .= $this->generar_trazabilidad($lineas[$linea_actual]);
  344.  
  345.             $fila = array(
  346.                 'alb' => '-',
  347.                 'cantidad' => $this->show_numero($lineas[$linea_actual]->cantidad, $dec_cantidad),
  348.                 'descripcion' => $descripcion,
  349.                 'pvp' => $this->show_precio($lineas[$linea_actual]->pvpunitario, $this->documento->coddivisa, TRUE, FS_NF0_ART),
  350.                 'dto' => $this->show_numero($lineas[$linea_actual]->dtopor) . " %",
  351.                 'iva' => $this->show_numero($lineas[$linea_actual]->iva) . " %",
  352.                 're' => $this->show_numero($lineas[$linea_actual]->recargo) . " %",
  353.                 'irpf' => $this->show_numero($lineas[$linea_actual]->irpf) . " %",
  354.                 'importe' => $this->show_precio($lineas[$linea_actual]->pvptotal, $this->documento->coddivisa)
  355.             );
  356.  
  357.             if ($lineas[$linea_actual]->dtopor == 0) {
  358.                 $fila['dto'] = '';
  359.             }
  360.  
  361.             if ($lineas[$linea_actual]->recargo == 0) {
  362.                 $fila['re'] = '';
  363.             }
  364.  
  365.             if ($lineas[$linea_actual]->irpf == 0) {
  366.                 $fila['irpf'] = '';
  367.             }
  368.  
  369.             if (!$lineas[$linea_actual]->mostrar_cantidad) {
  370.                 $fila['cantidad'] = '';
  371.             }
  372.  
  373.             if (!$lineas[$linea_actual]->mostrar_precio) {
  374.                 $fila['pvp'] = '';
  375.                 $fila['dto'] = '';
  376.                 $fila['iva'] = '';
  377.                 $fila['re'] = '';
  378.                 $fila['irpf'] = '';
  379.                 $fila['importe'] = '';
  380.             }
  381.  
  382.             if (get_class_name($lineas[$linea_actual]) == 'linea_factura_cliente' AND $this->impresion['print_alb']) {
  383.                 $fila['alb'] = $lineas[$linea_actual]->albaran_numero();
  384.             }
  385.  
  386.             $pdf_doc->add_table_row($fila);
  387.             $linea_actual++;
  388.         }
  389.  
  390.         $pdf_doc->save_table(
  391.             array(
  392.                 'fontSize' => 8,
  393.                 'cols' => array(
  394.                     'cantidad' => array('justification' => 'right'),
  395.                     'pvp' => array('justification' => 'right'),
  396.                     'dto' => array('justification' => 'right'),
  397.                     'iva' => array('justification' => 'right'),
  398.                     're' => array('justification' => 'right'),
  399.                     'irpf' => array('justification' => 'right'),
  400.                     'importe' => array('justification' => 'right')
  401.                 ),
  402.                 'width' => 520,
  403.                 'shaded' => 1,
  404.                 'shadeCol' => array(0.95, 0.95, 0.95),
  405.                 'lineCol' => array(0.3, 0.3, 0.3),
  406.             )
  407.         );
  408.  
  409.         /// ¿Última página?
  410.         if ($linea_actual == count($lineas) && $this->documento->observaciones != '') {
  411.             $pdf_doc->pdf->ezText("\n" . fs_fix_html($this->documento->observaciones), 9);
  412.         }
  413.     }
  414.  
  415.     /**
  416.      * Devuelve el texto con los números de serie o lotes de la $linea
  417.      * @param linea_albaran_compra $linea
  418.      * @return string
  419.      */
  420.     private function generar_trazabilidad($linea)
  421.     {
  422.         $lineast = array();
  423.         if (get_class_name($linea) == 'linea_albaran_cliente') {
  424.             $lineast = $this->articulo_traza->all_from_linea('idlalbventa', $linea->idlinea);
  425.         } else if (get_class_name($linea) == 'linea_factura_cliente') {
  426.             $lineast = $this->articulo_traza->all_from_linea('idlfacventa', $linea->idlinea);
  427.         }
  428.  
  429.         $lote = FALSE;
  430.         $txt = '';
  431.         foreach ($lineast as $lt) {
  432.             $salto = "\n";
  433.             if ($lt->numserie) {
  434.                 $txt .= $salto . 'N/S: ' . $lt->numserie . ' ';
  435.                 $salto = '';
  436.             }
  437.  
  438.             if ($lt->lote AND $lt->lote != $lote) {
  439.                 $txt .= $salto . 'Lote: ' . $lt->lote;
  440.                 $lote = $lt->lote;
  441.             }
  442.         }
  443.  
  444.         return $txt;
  445.     }
  446.  
  447.     private function generar_pdf_datos_cliente(&$pdf_doc, &$lppag)
  448.     {
  449.         $tipo_doc = ucfirst(FS_ALBARAN);
  450.         $width_campo1 = 90;
  451.         $rectificativa = FALSE;
  452.         if (get_class_name($this->documento) == 'factura_cliente') {
  453.             if ($this->documento->idfacturarect) {
  454.                 $tipo_doc = ucfirst(FS_FACTURA_RECTIFICATIVA);
  455.                 $rectificativa = TRUE;
  456.                 $width_campo1 = 110;
  457.             } else {
  458.                 $tipo_doc = 'Factura';
  459.             }
  460.         }
  461.  
  462.         $tipoidfiscal = FS_CIFNIF;
  463.         if ($this->cliente) {
  464.             $tipoidfiscal = $this->cliente->tipoidfiscal;
  465.         }
  466.  
  467.         /*
  468.          * Esta es la tabla con los datos del cliente:
  469.          * Albarán:                 Fecha:
  470.          * Cliente:               CIF/NIF:
  471.          * Dirección:           Teléfonos:
  472.          */
  473.         $pdf_doc->new_table();
  474.         $pdf_doc->add_table_row(
  475.             array(
  476.                 'campo1' => "<b>" . $tipo_doc . ":</b>",
  477.                 'dato1' => $this->documento->codigo,
  478.                 'campo2' => "<b>Fecha:</b> " . $this->documento->fecha
  479.             )
  480.         );
  481.  
  482.         if ($rectificativa) {
  483.             $pdf_doc->add_table_row(
  484.                 array(
  485.                     'campo1' => "<b>Original:</b>",
  486.                     'dato1' => $this->documento->codigorect,
  487.                     'campo2' => '',
  488.                 )
  489.             );
  490.         }
  491.  
  492.         $pdf_doc->add_table_row(
  493.             array(
  494.                 'campo1' => "<b>Cliente:</b> ",
  495.                 'dato1' => fs_fix_html($this->documento->nombrecliente),
  496.                 'campo2' => "<b>" . $tipoidfiscal . ":</b> " . $this->documento->cifnif
  497.             )
  498.         );
  499.  
  500.         $direccion = $this->documento->direccion;
  501.         if ($this->documento->apartado) {
  502.             $direccion .= ' - ' . ucfirst(FS_APARTADO) . ': ' . $this->documento->apartado;
  503.         }
  504.         if ($this->documento->codpostal) {
  505.             $direccion .= ' - CP: ' . $this->documento->codpostal;
  506.         }
  507.         $direccion .= ' - ' . $this->documento->ciudad;
  508.         if ($this->documento->provincia) {
  509.             $direccion .= ' (' . $this->documento->provincia . ')';
  510.         }
  511.         if ($this->documento->codpais != $this->empresa->codpais) {
  512.             $pais0 = new pais();
  513.             $pais = $pais0->get($this->documento->codpais);
  514.             if ($pais) {
  515.                 $direccion .= ' ' . $pais->nombre;
  516.             }
  517.         }
  518.         $row = array(
  519.             'campo1' => "<b>Dirección:</b>",
  520.             'dato1' => fs_fix_html($direccion),
  521.             'campo2' => ''
  522.         );
  523.  
  524.         if (!$this->cliente) {
  525.             /// nada
  526.         } else if ($this->cliente->telefono1) {
  527.             $row['campo2'] = "<b>Teléfonos:</b> " . $this->cliente->telefono1;
  528.             if ($this->cliente->telefono2) {
  529.                 $row['campo2'] .= "\n" . $this->cliente->telefono2;
  530.                 $lppag -= 2;
  531.             }
  532.         } else if ($this->cliente->telefono2) {
  533.             $row['campo2'] = "<b>Teléfonos:</b> " . $this->cliente->telefono2;
  534.         }
  535.         $pdf_doc->add_table_row($row);
  536.  
  537.         /* Si tenemos dirección de envío y es diferente a la de facturación */
  538.         if ($this->documento->envio_direccion && $this->documento->direccion != $this->documento->envio_direccion) {
  539.             $direccionenv = '';
  540.             if ($this->documento->envio_codigo) {
  541.                 $direccionenv .= 'Cod. Seg.: "' . $this->documento->envio_codigo . '" - ';
  542.             }
  543.             if ($this->documento->envio_nombre) {
  544.                 $direccionenv .= $this->documento->envio_nombre . ' ' . $this->documento->envio_apellidos . ' - ';
  545.             }
  546.             $direccionenv .= $this->documento->envio_direccion;
  547.             if ($this->documento->envio_apartado) {
  548.                 $direccionenv .= ' - ' . ucfirst(FS_APARTADO) . ': ' . $this->documento->envio_apartado;
  549.             }
  550.             if ($this->documento->envio_codpostal) {
  551.                 $direccionenv .= ' - CP: ' . $this->documento->envio_codpostal;
  552.             }
  553.             $direccionenv .= ' - ' . $this->documento->envio_ciudad;
  554.             if ($this->documento->envio_provincia) {
  555.                 $direccionenv .= ' (' . $this->documento->envio_provincia . ')';
  556.             }
  557.             if ($this->documento->envio_codpais != $this->empresa->codpais) {
  558.                 $pais0 = new pais();
  559.                 $pais = $pais0->get($this->documento->envio_codpais);
  560.                 if ($pais) {
  561.                     $direccionenv .= ' ' . $pais->nombre;
  562.                 }
  563.             }
  564.             /* Tal y como está la plantilla actualmente:
  565.              * Cada 54 caracteres es una línea en la dirección y no sabemos cuantas líneas tendrá,
  566.              * a partir de ahí es una linea a restar por cada 54 caracteres
  567.              */
  568.             $lppag -= ceil(strlen($direccionenv) / 54);
  569.             $row_dir_env = array(
  570.                 'campo1' => "<b>Dir.Obra: </b>", /// "<b>Enviar a:</b>", -------------------------------------- Cambiado
  571.                 'dato1' => fs_fix_html($direccionenv),
  572.                 'campo2' => ''
  573.             );
  574.             $pdf_doc->add_table_row($row_dir_env);
  575.         }
  576.  
  577.         if ($this->empresa->codpais != 'ESP') {
  578.             $pdf_doc->add_table_row(
  579.                 array(
  580.                     'campo1' => "<b>Régimen " . FS_IVA . ":</b> ",
  581.                     'dato1' => $this->cliente->regimeniva,
  582.                     'campo2' => ''
  583.                 )
  584.             );
  585.         }
  586.  
  587.         $pdf_doc->save_table(
  588.             array(
  589.                 'cols' => array(
  590.                     'campo1' => array('width' => $width_campo1, 'justification' => 'right'),
  591.                     'dato1' => array('justification' => 'left'),
  592.                     'campo2' => array('justification' => 'right')
  593.                 ),
  594.                 'showLines' => 0,
  595.                 'width' => 520,
  596.                 'shaded' => 0
  597.             )
  598.         );
  599.         $pdf_doc->pdf->ezText("\n", 10);
  600.     }
  601.  
  602.     private function generar_pdf_totales(&$pdf_doc, &$lineas_iva, $pagina)
  603.     {
  604.         if (isset($_GET['noval'])) {
  605.             $pdf_doc->pdf->addText(10, 10, 8, $pdf_doc->center_text('Página ' . $pagina . '/' . $this->numpaginas, 250));
  606.         } else {
  607.             /*
  608.              * Rellenamos la última tabla de la página:
  609.              *
  610.              * Página            Neto    IVA   Total
  611.              */
  612.             $pdf_doc->new_table();
  613.             $titulo = array('pagina' => '<b>Página</b>', 'neto' => '<b>Neto</b>',);
  614.             $fila = array(
  615.                 'pagina' => $pagina . '/' . $this->numpaginas,
  616.                 'neto' => $this->show_precio($this->documento->neto, $this->documento->coddivisa),
  617.             );
  618.             $opciones = array(
  619.                 'cols' => array(
  620.                     'neto' => array('justification' => 'right'),
  621.                 ),
  622.                 'showLines' => 3,
  623.                 'shaded' => 2,
  624.                 'shadeCol2' => array(0.95, 0.95, 0.95),
  625.                 'lineCol' => array(0.3, 0.3, 0.3),
  626.                 'width' => 520
  627.             );
  628.             foreach ($lineas_iva as $li) {
  629.                 $imp = $this->impuesto->get($li['codimpuesto']);
  630.                 if ($imp) {
  631.                     $titulo['iva' . $li['iva']] = '<b>' . $imp->descripcion . '</b>';
  632.                 } else
  633.                     $titulo['iva' . $li['iva']] = '<b>' . FS_IVA . ' ' . $li['iva'] . '%</b>';
  634.  
  635.                 $fila['iva' . $li['iva']] = $this->show_precio($li['totaliva'], $this->documento->coddivisa);
  636.  
  637.                 if ($li['totalrecargo'] != 0) {
  638.                     $fila['iva' . $li['iva']] .= "\nR.E. " . $li['recargo'] . "%: " . $this->show_precio($li['totalrecargo'], $this->documento->coddivisa);
  639.                 }
  640.  
  641.                 $opciones['cols']['iva' . $li['iva']] = array('justification' => 'right');
  642.             }
  643.  
  644.             if ($this->documento->totalirpf != 0) {
  645.                 $titulo['irpf'] = '<b>' . FS_IRPF . ' ' . $this->documento->irpf . '%</b>';
  646.                 $fila['irpf'] = $this->show_precio($this->documento->totalirpf);
  647.                 $opciones['cols']['irpf'] = array('justification' => 'right');
  648.             }
  649.  
  650.             $titulo['liquido'] = '<b>Total</b>';
  651.             $fila['liquido'] = $this->show_precio($this->documento->total, $this->documento->coddivisa);
  652.             $opciones['cols']['liquido'] = array('justification' => 'right');
  653.  
  654.             $pdf_doc->add_table_header($titulo);
  655.             $pdf_doc->add_table_row($fila);
  656.             $pdf_doc->save_table($opciones);
  657.         }
  658.     }
  659.  
  660.     public function generar_pdf_albaran($archivo = FALSE)
  661.     {
  662.         if (!$archivo) {
  663.             /// desactivamos la plantilla HTML
  664.             $this->template = FALSE;
  665.         }
  666.  
  667.         /// Creamos el PDF y escribimos sus metadatos
  668.         $pdf_doc = new fs_pdf();
  669.         $pdf_doc->pdf->addInfo('Title', ucfirst(FS_ALBARAN) . ' ' . $this->documento->codigo);
  670.         $pdf_doc->pdf->addInfo('Subject', ucfirst(FS_ALBARAN) . ' de cliente ' . $this->documento->codigo);
  671.         $pdf_doc->pdf->addInfo('Author', $this->empresa->nombre);
  672.  
  673.         $lineas = $this->documento->get_lineas();
  674.         $lineas_iva = $pdf_doc->get_lineas_iva($lineas);
  675.         if ($lineas) {
  676.             $linea_actual = 0;
  677.             $pagina = 1;
  678.  
  679.             /// imprimimos las páginas necesarias
  680.             while ($linea_actual < count($lineas)) {
  681.                 $lppag = 35;
  682.  
  683.                 /// salto de página
  684.                 if ($linea_actual > 0) {
  685.                     $pdf_doc->pdf->ezNewPage();
  686.                 }
  687.  
  688.                 $pdf_doc->generar_pdf_cabecera($this->empresa, $lppag);
  689.                 $this->generar_pdf_datos_cliente($pdf_doc, $lppag);
  690.                 $this->generar_pdf_lineas($pdf_doc, $lineas, $linea_actual, $lppag);
  691.  
  692.                 $pdf_doc->set_y(80);
  693.                 $this->generar_pdf_totales($pdf_doc, $lineas_iva, $pagina);
  694.                 $pagina++;
  695.             }
  696.         } else {
  697.             $pdf_doc->pdf->ezText('¡' . ucfirst(FS_ALBARAN) . ' sin líneas!', 20);
  698.         }
  699.  
  700.         if ($archivo) {
  701.             if (!file_exists('tmp/' . FS_TMP_NAME . 'enviar')) {
  702.                 mkdir('tmp/' . FS_TMP_NAME . 'enviar');
  703.             }
  704.  
  705.             $pdf_doc->save('tmp/' . FS_TMP_NAME . 'enviar/' . $archivo);
  706.         } else
  707.             $pdf_doc->show(FS_ALBARAN . '_' . $this->documento->codigo . '.pdf');
  708.     }
  709.  
  710.     public function generar_pdf_factura($tipo = 'simple', $archivo = FALSE)
  711.     {
  712.         if (!$archivo) {
  713.             /// desactivamos la plantilla HTML
  714.             $this->template = FALSE;
  715.         }
  716.  
  717.         /// Creamos el PDF y escribimos sus metadatos
  718.         $pdf_doc = new fs_pdf();
  719.         $pdf_doc->pdf->addInfo('Title', ucfirst(FS_FACTURA) . ' ' . $this->documento->codigo);
  720.         $pdf_doc->pdf->addInfo('Subject', ucfirst(FS_FACTURA) . ' ' . $this->documento->codigo);
  721.         $pdf_doc->pdf->addInfo('Author', $this->empresa->nombre);
  722.  
  723.         $lineas = $this->documento->get_lineas();
  724.         $lineas_iva = $pdf_doc->get_lineas_iva($lineas);
  725.         if ($lineas) {
  726.             $linea_actual = 0;
  727.             $pagina = 1;
  728.  
  729.             /// imprimimos las páginas necesarias
  730.             while ($linea_actual < count($lineas)) {
  731.                 $lppag = 35;
  732.  
  733.                 /// salto de página
  734.                 if ($linea_actual > 0) {
  735.                     $pdf_doc->pdf->ezNewPage();
  736.                 }
  737.  
  738.                 /*
  739.                  * Creamos la cabecera de la página, en este caso para el modelo carta
  740.                  */
  741.                 if ($tipo == 'carta') {
  742.                     $pdf_doc->generar_pdf_cabecera($this->empresa, $lppag);
  743.  
  744.                     $direccion = $this->documento->nombrecliente . "\n" . $this->documento->direccion;
  745.                     if ($this->documento->apartado) {
  746.                         $direccion .= "\n " . ucfirst(FS_APARTADO) . ": " . $this->documento->apartado;
  747.                     }
  748.  
  749.                     if ($this->documento->codpostal) {
  750.                         $direccion .= "\n CP: " . $this->documento->codpostal . ' - ';
  751.                     } else {
  752.                         $direccion .= "\n";
  753.                     }
  754.                     $direccion .= $this->documento->ciudad . "\n(" . $this->documento->provincia . ")";
  755.                     if ($this->documento->codpais != $this->empresa->codpais) {
  756.                         $pais0 = new pais();
  757.                         $pais = $pais0->get($this->documento->codpais);
  758.                         if ($pais) {
  759.                             $direccion .= ' ' . $pais->nombre;
  760.                         }
  761.                     }
  762.                     $pdf_doc->new_table();
  763.                     $pdf_doc->add_table_row(
  764.                         array(
  765.                             'campos' => "<b>" . ucfirst(FS_FACTURA) . ":</b>\n<b>Fecha:</b>\n<b>" . $this->cliente->tipoidfiscal . ":</b>",
  766.                             'factura' => $this->documento->codigo . "\n" . $this->documento->fecha . "\n" . $this->documento->cifnif,
  767.                             'cliente' => fs_fix_html($direccion)
  768.                         )
  769.                     );
  770.                     $pdf_doc->save_table(
  771.                         array(
  772.                             'cols' => array(
  773.                                 'campos' => array('justification' => 'right', 'width' => 100),
  774.                                 'factura' => array('justification' => 'left'),
  775.                                 'cliente' => array('justification' => 'right')
  776.                             ),
  777.                             'showLines' => 0,
  778.                             'width' => 520
  779.                         )
  780.                     );
  781.                     $pdf_doc->pdf->ezText("\n\n\n", 14);
  782.                 } else { /// esta es la cabecera de la página para el modelo 'simple'
  783.                     $pdf_doc->generar_pdf_cabecera($this->empresa, $lppag);
  784.                     $this->generar_pdf_datos_cliente($pdf_doc, $lppag);
  785.                 }
  786.  
  787.                 $this->generar_pdf_lineas($pdf_doc, $lineas, $linea_actual, $lppag, $this->documento);
  788.  
  789.                 if ($linea_actual == count($lineas)) {
  790.                     if (!$this->documento->pagada AND $this->impresion['print_formapago']) {
  791.                         $fp0 = new forma_pago();
  792.                         $forma_pago = $fp0->get($this->documento->codpago);
  793.                         if ($forma_pago) {
  794.                             $texto_pago = "\n<b>Forma de pago</b>: " . $forma_pago->descripcion;
  795.  
  796.                             if (!$forma_pago->imprimir) {
  797.                                 /// nada
  798.                             } else if ($forma_pago->domiciliado) {
  799.                                 $cbc0 = new cuenta_banco_cliente();
  800.                                 $encontrada = FALSE;
  801.                                 foreach ($cbc0->all_from_cliente($this->documento->codcliente) as $cbc) {
  802.                                     $texto_pago .= "\n<b>Domiciliado en</b>: ";
  803.                                     if ($cbc->iban) {
  804.                                         $texto_pago .= $cbc->iban(TRUE);
  805.                                     }
  806.  
  807.                                     if ($cbc->swift) {
  808.                                         $texto_pago .= "\n<b>SWIFT/BIC</b>: " . $cbc->swift;
  809.                                     }
  810.                                     $encontrada = TRUE;
  811.                                     break;
  812.                                 }
  813.                                 if (!$encontrada) {
  814.                                     $texto_pago .= "\n<b>El cliente no tiene cuenta bancaria asignada.</b>";
  815.                                 }
  816.                             } else if ($forma_pago->codcuenta) {
  817.                                 $cb0 = new cuenta_banco();
  818.                                 $cuenta_banco = $cb0->get($forma_pago->codcuenta);
  819.                                 if ($cuenta_banco) {
  820.                                     if ($cuenta_banco->iban) {
  821.                                         $texto_pago .= "\n<b>IBAN</b>: " . $cuenta_banco->iban(TRUE);
  822.                                     }
  823.  
  824.                                     if ($cuenta_banco->swift) {
  825.                                         $texto_pago .= "\n<b>SWIFT o BIC</b>: " . $cuenta_banco->swift;
  826.                                     }
  827.                                 }
  828.                             }
  829.  
  830.                             $texto_pago .= "\n<b>Vencimiento</b>: " . $this->documento->vencimiento;
  831.                             $pdf_doc->pdf->ezText($texto_pago, 9);
  832.                         }
  833.                     }
  834.                 }
  835.  
  836.                 $pdf_doc->set_y(80);
  837.                 $this->generar_pdf_totales($pdf_doc, $lineas_iva, $pagina);
  838.  
  839.                 /// pié de página para la factura
  840.                 if ($this->empresa->pie_factura) {
  841.                     $pdf_doc->pdf->addText(10, 10, 8, $pdf_doc->center_text(fs_fix_html($this->empresa->pie_factura), 180));
  842.                 }
  843.  
  844.                 $pagina++;
  845.             }
  846.         } else {
  847.             $pdf_doc->pdf->ezText('¡' . ucfirst(FS_FACTURA) . ' sin líneas!', 20);
  848.         }
  849.  
  850.         if ($archivo) {
  851.             if (!file_exists('tmp/' . FS_TMP_NAME . 'enviar')) {
  852.                 mkdir('tmp/' . FS_TMP_NAME . 'enviar');
  853.             }
  854.  
  855.             $pdf_doc->save('tmp/' . FS_TMP_NAME . 'enviar/' . $archivo);
  856.         } else
  857.             $pdf_doc->show(FS_FACTURA . '_' . $this->documento->codigo . '.pdf');
  858.     }
  859.  
  860.     private function enviar_email($doc, $tipo = 'simple')
  861.     {
  862.         if ($this->empresa->can_send_mail()) {
  863.             if ($doc == 'factura') {
  864.                 $filename = 'factura_' . $this->documento->codigo . '.pdf';
  865.                 $this->generar_pdf_factura($tipo, $filename);
  866.             } else {
  867.                 $filename = 'albaran_' . $this->documento->codigo . '.pdf';
  868.                 $this->generar_pdf_albaran($filename);
  869.             }
  870.  
  871.             $razonsocial = $this->documento->nombrecliente;
  872.             if ($this->cliente) {
  873.                 if ($_POST['email'] != $this->cliente->email AND isset($_POST['guardar'])) {
  874.                     $this->cliente->email = $_POST['email'];
  875.                     $this->cliente->save();
  876.                 }
  877.             }
  878.  
  879.             if (file_exists('tmp/' . FS_TMP_NAME . 'enviar/' . $filename)) {
  880.                 $mail = $this->empresa->new_mail();
  881.                 $mail->FromName = $this->user->get_agente_fullname();
  882.  
  883.                 if ($_POST['de'] != $mail->From) {
  884.                     $mail->addReplyTo($_POST['de'], $mail->FromName);
  885.                 }
  886.  
  887.                 $mail->addAddress($_POST['email'], $razonsocial);
  888.                 if ($_POST['email_copia']) {
  889.                     if (isset($_POST['cco'])) {
  890.                         $mail->addBCC($_POST['email_copia'], $razonsocial);
  891.                     } else {
  892.                         $mail->addCC($_POST['email_copia'], $razonsocial);
  893.                     }
  894.                 }
  895.  
  896.                 if ($doc == 'factura') {
  897.                     $mail->Subject = $this->empresa->nombre . ': Su factura ' . $this->documento->codigo;
  898.                 } else {
  899.                     $mail->Subject = $this->empresa->nombre . ': Su ' . FS_ALBARAN . ' ' . $this->documento->codigo;
  900.                 }
  901.  
  902.                 if ($this->is_html($_POST['mensaje'])) {
  903.                     $mail->AltBody = strip_tags($_POST['mensaje']);
  904.                     $mail->msgHTML($_POST['mensaje']);
  905.                     $mail->isHTML(TRUE);
  906.                 } else {
  907.                     $mail->Body = $_POST['mensaje'];
  908.                 }
  909.  
  910.                 $mail->addAttachment('tmp/' . FS_TMP_NAME . 'enviar/' . $filename);
  911.                 if (is_uploaded_file($_FILES['adjunto']['tmp_name'])) {
  912.                     $mail->addAttachment($_FILES['adjunto']['tmp_name'], $_FILES['adjunto']['name']);
  913.                 }
  914.  
  915.                 if ($this->empresa->mail_connect($mail)) {
  916.                     if ($mail->send()) {
  917.                         $this->new_message('Mensaje enviado correctamente.');
  918.  
  919.                         /// nos guardamos la fecha de envío
  920.                         $this->documento->femail = $this->today();
  921.                         $this->documento->save();
  922.  
  923.                         $this->empresa->save_mail($mail);
  924.                     } else
  925.                         $this->new_error_msg("Error al enviar el email: " . $mail->ErrorInfo);
  926.                 } else
  927.                     $this->new_error_msg("Error al enviar el email: " . $mail->ErrorInfo);
  928.  
  929.                 unlink('tmp/' . FS_TMP_NAME . 'enviar/' . $filename);
  930.             } else
  931.                 $this->new_error_msg('Imposible generar el PDF.');
  932.         }
  933.     }
  934.  
  935.     public function is_html($txt)
  936.     {
  937.         return ( $txt != strip_tags($txt) ) ? TRUE : FALSE;
  938.     }
  939. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement