compras_imprimir_ncf::share_extensions()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 3
eloc 12
c 2
b 1
f 0
nc 3
nop 0
dl 0
loc 16
rs 9.8666
1
<?php
2
3
/*
4
 * This file is part of facturacion_base
5
 * Copyright (C) 2014-2017  Carlos Garcia Gomez  [email protected]
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 __DIR__ . '/../../facturacion_base/extras/fs_pdf.php';
22
require_once 'extras/phpmailer/class.phpmailer.php';
23
require_once 'extras/phpmailer/class.smtp.php';
24
require_once 'plugins/republica_dominicana/extras/rd_controller.php';
25
26
/**
27
 * Esta clase agrupa los procedimientos de imprimir/enviar albaranes de proveedor
28
 * e imprimir facturas de proveedor adecuados para República Dominicana.
29
 * @since 50
30
 */
31
class compras_imprimir_ncf extends rd_controller
32
{
33
    public $documento;
34
    public $impresion;
35
    public $impuesto;
36
    public $proveedor;
37
    private $articulo_proveedor;
38
    private $articulo_traza;
39
    private $numpaginas;
40
41
    public function __construct()
42
    {
43
        parent::__construct(__CLASS__, 'imprimir_ncf', 'compras', false, false);
44
    }
45
46
    protected function private_core()
47
    {
48
        parent::private_core();
49
        $this->articulo_proveedor = new articulo_proveedor();
0 ignored issues
show
Bug introduced by
The type articulo_proveedor was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
50
        $this->documento = false;
51
        $this->impuesto = new impuesto();
0 ignored issues
show
Bug introduced by
The type impuesto was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
52
        $this->proveedor = false;
53
        /// obtenemos los datos de configuración de impresión
54
        $this->impresion = array(
55
            'print_ref' => '1',
56
            'print_dto' => '1',
57
            'print_alb' => '0'
58
        );
59
        $fsvar = new fs_var();
0 ignored issues
show
Bug introduced by
The type fs_var was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
60
        $this->impresion = $fsvar->array_get($this->impresion, false);
61
62
        $albaran = $this->filter_request('albaran');
63
        $id = $this->filter_request('id');
64
        $factura = $this->filter_request('factura');
65
        if ($albaran and $id) {
66
            $this->articulo_traza = new articulo_traza();
0 ignored issues
show
Bug introduced by
The type articulo_traza was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
67
68
            $alb = new albaran_proveedor();
0 ignored issues
show
Bug introduced by
The type albaran_proveedor was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
69
            $this->documento = $alb->get($id);
70
            if ($this->documento) {
71
                $proveedor = new proveedor();
72
                $this->proveedor = $proveedor->get($this->documento->codproveedor);
73
            }
74
75
            if (\filter_input(INPUT_POST, 'email')) {
76
                $this->enviar_email();
77
            } else {
78
                $this->generar_pdf_albaran();
79
            }
80
        } elseif ($factura and $id) {
81
            $this->articulo_traza = new articulo_traza();
82
83
            $fac = new factura_proveedor();
84
            $this->documento = $fac->get($id);
85
            if ($this->documento) {
86
                $proveedor = new proveedor();
87
                $this->proveedor = $proveedor->get($this->documento->codproveedor);
88
            }
89
90
            $this->generar_pdf_factura();
91
        }
92
93
        $this->share_extensions();
94
    }
95
96
    private function share_extensions()
97
    {
98
        $extensiones = array(
99
            array(
100
                'name' => 'imprimir_factura_proveedor_ncf',
101
                'page_from' => __CLASS__,
102
                'page_to' => 'compras_factura',
103
                'type' => 'pdf',
104
                'text' => 'Factura con ' . FS_NUMERO2,
105
                'params' => '&factura=TRUE'
106
            ),
107
        );
108
        foreach ($extensiones as $ext) {
109
            $fsext = new fs_extension($ext);
0 ignored issues
show
Bug introduced by
The type fs_extension was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
110
            if (!$fsext->save()) {
111
                $this->new_error_msg('Error al guardar la extensión ' . $ext['name']);
112
            }
113
        }
114
    }
115
116
    public function numero_paginas($lineas, $lppag)
117
    {
118
        /// calculamos el número de páginas
119
        if (!isset($this->numpaginas)) {
120
            $this->numpaginas = 0;
121
            $linea_a = 0;
122
            $cantidad_lineas = count($lineas);
123
            while ($linea_a < $cantidad_lineas) {
124
                $lppag2 = $lppag;
125
                foreach ($lineas as $i => $lin) {
126
                    if ($i >= $linea_a and $i < $linea_a + $lppag2) {
127
                        $linea_size = 1;
128
                        $len = mb_strlen($lin->referencia . ' ' . $lin->descripcion);
129
                        while ($len > 85) {
130
                            $len -= 85;
131
                            $linea_size += 0.5;
132
                        }
133
134
                        $aux = explode("\n", $lin->descripcion);
135
                        if (count($aux) > 1) {
136
                            $linea_size += 0.5 * (count($aux) - 1);
137
                        }
138
139
                        if ($linea_size > 1) {
140
                            $lppag2 -= $linea_size - 1;
141
                        }
142
                    }
143
                }
144
145
                $linea_a += $lppag2;
146
                $this->numpaginas++;
147
            }
148
149
            if ($this->numpaginas == 0) {
150
                $this->numpaginas = 1;
151
            }
152
        }
153
    }
154
155
    public function lineaSize($i, $lin, $linea_actual, &$lppag)
156
    {
157
        /// restamos líneas al documento en función del tamaño de la descripción
158
        if ($i >= $linea_actual and $i < $linea_actual + $lppag) {
159
            $linea_size = 1;
160
            $len = mb_strlen($lin->referencia . ' ' . $lin->descripcion);
161
            while ($len > 85) {
162
                $len -= 85;
163
                $linea_size += 0.5;
164
            }
165
166
            $aux = explode("\n", $lin->descripcion);
167
            if (count($aux) > 1) {
168
                $linea_size += 0.5 * (count($aux) - 1);
169
            }
170
171
            if ($linea_size > 1) {
172
                $lppag -= $linea_size - 1;
173
            }
174
        }
175
    }
176
177
    private function generar_pdf_lineas(&$pdf_doc, &$lineas, &$linea_actual, &$lppag)
178
    {
179
        $this->numero_paginas($lineas, $lppag);
180
181
        if ($this->impresion['print_dto']) {
182
            $this->impresion['print_dto'] = false;
183
184
            /// leemos las líneas para ver si de verdad mostramos los descuentos
185
            foreach ($lineas as $lin) {
186
                if ($lin->dtopor != 0) {
187
                    $this->impresion['print_dto'] = true;
188
                    break;
189
                }
190
            }
191
        }
192
193
        $dec_cantidad = 0;
194
        $multi_iva = false;
195
        $multi_re = false;
196
        $multi_irpf = false;
197
        $iva = false;
198
        $re = false;
199
        $irpf = false;
200
        /// leemos las líneas para ver si hay que mostrar los tipos de iva, re o irpf
201
        foreach ($lineas as $i => $lin) {
202
            if ($lin->cantidad != intval($lin->cantidad)) {
203
                $dec_cantidad = 2;
204
            }
205
206
            if ($iva === false) {
207
                $iva = $lin->iva;
208
            } elseif ($lin->iva != $iva) {
209
                $multi_iva = true;
210
            }
211
212
            if ($re === false) {
213
                $re = $lin->recargo;
214
            } elseif ($lin->recargo != $re) {
215
                $multi_re = true;
216
            }
217
218
            if ($irpf === false) {
219
                $irpf = $lin->irpf;
220
            } elseif ($lin->irpf != $irpf) {
221
                $multi_irpf = true;
222
            }
223
224
            $this->lineaSize($i, $lin, $linea_actual, $lppag);
225
        }
226
227
        /*
228
         * Creamos la tabla con las lineas del documento
229
         */
230
        $pdf_doc->new_table();
231
        $table_header = array(
232
            'cantidad' => '<b>Cant.</b>',
233
            'descripcion' => '<b>Ref. Prov. + Descripción</b>',
234
            'pvp' => '<b>Precio</b>',
235
        );
236
237
        if ($this->impresion['print_dto']) {
238
            $table_header['dto'] = '<b>Dto.</b>';
239
        }
240
241
        if ($multi_iva) {
242
            $table_header['iva'] = '<b>' . FS_IVA . '</b>';
243
        }
244
245
        if ($multi_re) {
246
            $table_header['re'] = '<b>R.E.</b>';
247
        }
248
249
        if ($multi_irpf) {
250
            $table_header['irpf'] = '<b>' . FS_IRPF . '</b>';
251
        }
252
253
        $table_header['importe'] = '<b>Importe</b>';
254
        $pdf_doc->add_table_header($table_header);
255
256
        for ($i = $linea_actual; (($linea_actual < ($lppag + $i)) and ($linea_actual < count($lineas)));) {
257
            $descripcion = $pdf_doc->fix_html($lineas[$linea_actual]->descripcion);
258
            if (!is_null($lineas[$linea_actual]->referencia)) {
259
                $descripcion = '<b>' . $this->get_referencia_proveedor($lineas[$linea_actual]->referencia)
260
                        . '</b> ' . $descripcion;
261
            }
262
263
            /// ¿El articulo tiene trazabilidad?
264
            $descripcion .= $this->generar_trazabilidad($lineas[$linea_actual]);
265
266
            $fila = array(
267
                'cantidad' => $this->show_numero($lineas[$linea_actual]->cantidad, $dec_cantidad),
268
                'descripcion' => $descripcion,
269
                'pvp' => $this->show_precio($lineas[$linea_actual]->pvpunitario, $this->documento->coddivisa, true, FS_NF0_ART),
0 ignored issues
show
Bug introduced by
The constant FS_NF0_ART was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
270
                'dto' => $this->show_numero($lineas[$linea_actual]->dtopor) . " %",
271
                'iva' => $this->show_numero($lineas[$linea_actual]->iva) . " %",
272
                're' => $this->show_numero($lineas[$linea_actual]->recargo) . " %",
273
                'irpf' => $this->show_numero($lineas[$linea_actual]->irpf) . " %",
274
                'importe' => $this->show_precio($lineas[$linea_actual]->pvptotal, $this->documento->coddivisa)
275
            );
276
277
            if ($lineas[$linea_actual]->dtopor == 0) {
278
                $fila['dto'] = '';
279
            }
280
281
            if ($lineas[$linea_actual]->recargo == 0) {
282
                $fila['re'] = '';
283
            }
284
285
            if ($lineas[$linea_actual]->irpf == 0) {
286
                $fila['irpf'] = '';
287
            }
288
289
            $pdf_doc->add_table_row($fila);
290
            $linea_actual++;
291
        }
292
293
        $pdf_doc->save_table(
294
                array(
295
                    'fontSize' => 8,
296
                    'cols' => array(
297
                        'cantidad' => array('justification' => 'right'),
298
                        'pvp' => array('justification' => 'right'),
299
                        'dto' => array('justification' => 'right'),
300
                        'iva' => array('justification' => 'right'),
301
                        're' => array('justification' => 'right'),
302
                        'irpf' => array('justification' => 'right'),
303
                        'importe' => array('justification' => 'right')
304
                    ),
305
                    'width' => 520,
306
                    'shaded' => 1,
307
                    'shadeCol' => array(0.95, 0.95, 0.95),
308
                    'lineCol' => array(0.3, 0.3, 0.3),
309
                )
310
        );
311
312
        /// ¿Última página?
313
        if ($linea_actual == count($lineas)) {
314
            if ($this->documento->observaciones != '') {
315
                $pdf_doc->pdf->ezText("\n" . $pdf_doc->fix_html($this->documento->observaciones), 9);
316
            }
317
        }
318
319
        $pdf_doc->set_y(80);
320
    }
321
322
    private function get_referencia_proveedor($ref)
323
    {
324
        $artprov = $this->articulo_proveedor->get_by($ref, $this->documento->codproveedor);
325
        if ($artprov) {
326
            return $artprov->refproveedor;
327
        } else {
328
            return $ref;
329
        }
330
    }
331
332
    /**
333
     * Devuelve el texto con los números de serie o lotes de la $linea
334
     * @param linea_albaran_compra $linea
0 ignored issues
show
Bug introduced by
The type linea_albaran_compra was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
335
     * @return string
336
     */
337
    private function generar_trazabilidad($linea)
338
    {
339
        $lineast = array();
340
        if (get_class_name($linea) == 'linea_albaran_proveedor') {
0 ignored issues
show
Bug introduced by
The function get_class_name was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

340
        if (/** @scrutinizer ignore-call */ get_class_name($linea) == 'linea_albaran_proveedor') {
Loading history...
341
            $lineast = $this->articulo_traza->all_from_linea('idlalbcompra', $linea->idlinea);
342
        } else {
343
            $lineast = $this->articulo_traza->all_from_linea('idlfaccompra', $linea->idlinea);
344
        }
345
346
        $txt = '';
347
        foreach ($lineast as $lt) {
348
            $txt .= "\n";
349
            if ($lt->numserie) {
350
                $txt .= 'N/S: ' . $lt->numserie . ' ';
351
            }
352
353
            if ($lt->lote) {
354
                $txt .= 'Lote: ' . $lt->lote;
355
            }
356
        }
357
358
        return $txt;
359
    }
360
361
    private function generar_pdf_datos_proveedor(&$pdf_doc)
362
    {
363
        $tipo_doc = ucfirst(FS_ALBARAN);
0 ignored issues
show
Bug introduced by
The constant FS_ALBARAN was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
364
        $rectificativa = false;
365
        if (get_class_name($this->documento) == 'factura_proveedor') {
0 ignored issues
show
Bug introduced by
The function get_class_name was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

365
        if (/** @scrutinizer ignore-call */ get_class_name($this->documento) == 'factura_proveedor') {
Loading history...
366
            if ($this->documento->idfacturarect) {
367
                $tipo_doc = ucfirst(FS_FACTURA_RECTIFICATIVA);
0 ignored issues
show
Bug introduced by
The constant FS_FACTURA_RECTIFICATIVA was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
368
                $rectificativa = true;
369
            } else {
370
                $tipo_doc = 'Factura';
371
            }
372
        }
373
374
        $tipoidfiscal = FS_CIFNIF;
375
        if ($this->proveedor) {
376
            $tipoidfiscal = $this->proveedor->tipoidfiscal;
377
        }
378
379
        /*
380
         * Esta es la tabla con los datos del proveedor:
381
         * Documento:               Fecha:
382
         * Proveedor:             CIF/NIF:
383
         * NCF:           NumeroProveedor:
384
         */
385
        $pdf_doc->new_table();
386
        $pdf_doc->add_table_row(
387
                array(
388
                    'campo1' => "<b>" . $tipo_doc . ":</b>",
389
                    'dato1' => $this->documento->codigo,
390
                    'campo2' => "<b>Fecha:</b> " . $this->documento->fecha,
391
                )
392
        );
393
394
        if ($rectificativa) {
395
            $pdf_doc->add_table_row(
396
                    array(
397
                        'campo1' => "<b>Original:</b>",
398
                        'dato1' => $this->documento->codigorect,
399
                        'campo2' => '',
400
                    )
401
            );
402
        }
403
404
        $pdf_doc->add_table_row(
405
                array(
406
                    'campo1' => "<b>Proveedor:</b>",
407
                    'dato1' => $pdf_doc->fix_html($this->documento->nombre),
408
                    'campo2' => "<b>" . $tipoidfiscal . ":</b> " . $this->documento->cifnif
409
                )
410
        );
411
        $this->ncf_length = (\strtotime($this->documento->fecha) < (\strtotime('01-05-2018'))) ? 19 : $this->ncf_length;
412
        if (!empty($this->documento->numproveedor) and strlen($this->documento->numproveedor) == $this->ncf_length) {
413
            $pdf_doc->add_table_row(
414
                    array(
415
                        'campo1' => "<b>" . FS_NUMERO2 . ":</b>",
416
                        'dato1' => $this->documento->numproveedor,
417
                        'campo2' => ''
418
                    )
419
            );
420
            $this->tipo_documento_pos = (\strtotime($this->documento->fecha) < (\strtotime('01-05-2018'))) ? 9 : $this->tipo_documento_pos;
421
            $pdf_doc->add_table_row(
422
                    array(
423
                        'campo1' => '',
424
                        'dato1' => "<b>" . $this->ncf_tipo->get(substr($this->documento->numproveedor, $this->tipo_documento_pos, 2))->descripcion . "</b>",
425
                        'campo2' => ''
426
                    )
427
            );
428
        } else {
429
            $pdf_doc->add_table_row(
430
                    array(
431
                        'campo1' => "<b>" . FS_NUMERO2 . ":</b>",
432
                        'dato1' => $this->documento->numproveedor,
433
                        'campo2' => ''
434
                    )
435
            );
436
        }
437
438
        $pdf_doc->save_table(
439
                array(
440
                    'cols' => array(
441
                        'campo1' => array('width' => 90, 'justification' => 'right'),
442
                        'dato1' => array('justification' => 'left'),
443
                        'campo2' => array('justification' => 'right'),
444
                    ),
445
                    'showLines' => 0,
446
                    'width' => 520,
447
                    'shaded' => 0
448
                )
449
        );
450
        $pdf_doc->pdf->ezText("\n", 10);
451
    }
452
453
    private function generar_pdf_totales(&$pdf_doc, &$lineas_iva, $pagina)
454
    {
455
        /*
456
         * Rellenamos la última tabla de la página:
457
         *
458
         * Página            Neto    IVA   Total
459
         */
460
        $pdf_doc->new_table();
461
        $titulo = array('pagina' => '<b>Página</b>', 'neto' => '<b>Neto</b>',);
462
        $fila = array(
463
            'pagina' => $pagina . '/' . $this->numpaginas,
464
            'neto' => $this->show_precio($this->documento->neto, $this->documento->coddivisa),
465
        );
466
        $opciones = array(
467
            'cols' => array(
468
                'neto' => array('justification' => 'right'),
469
            ),
470
            'showLines' => 3,
471
            'shaded' => 2,
472
            'shadeCol2' => array(0.95, 0.95, 0.95),
473
            'lineCol' => array(0.3, 0.3, 0.3),
474
            'width' => 520
475
        );
476
        foreach ($lineas_iva as $li) {
477
            $imp = $this->impuesto->get($li['codimpuesto']);
478
            if ($imp) {
479
                $titulo['iva' . $li['iva']] = '<b>' . $imp->descripcion . '</b>';
480
            } else {
481
                $titulo['iva' . $li['iva']] = '<b>' . FS_IVA . ' ' . $li['iva'] . '%</b>';
482
            }
483
484
            $fila['iva' . $li['iva']] = $this->show_precio($li['totaliva'], $this->documento->coddivisa);
485
486
            if ($li['totalrecargo'] != 0) {
487
                $fila['iva' . $li['iva']] .= "\nR.E. " . $li['recargo'] . "%: " . $this->show_precio($li['totalrecargo'], $this->documento->coddivisa);
488
            }
489
490
            $opciones['cols']['iva' . $li['iva']] = array('justification' => 'right');
491
        }
492
493
        if ($this->documento->totalirpf != 0) {
494
            $titulo['irpf'] = '<b>' . FS_IRPF . ' ' . $this->documento->irpf . '%</b>';
495
            $fila['irpf'] = $this->show_precio($this->documento->totalirpf);
496
            $opciones['cols']['irpf'] = array('justification' => 'right');
497
        }
498
499
        $titulo['liquido'] = '<b>Total</b>';
500
        $fila['liquido'] = $this->show_precio($this->documento->total, $this->documento->coddivisa);
501
        $opciones['cols']['liquido'] = array('justification' => 'right');
502
        $pdf_doc->add_table_header($titulo);
503
        $pdf_doc->add_table_row($fila);
504
        $pdf_doc->save_table($opciones);
505
    }
506
507
    private function generar_pdf_albaran($archivo = false)
508
    {
509
        if (!$archivo) {
510
            /// desactivamos la plantilla HTML
511
            $this->template = false;
512
        }
513
514
        /// Creamos el PDF y escribimos sus metadatos
515
        $pdf_doc = new fs_pdf();
516
        $pdf_doc->pdf->addInfo('Title', ucfirst(FS_ALBARAN) . ' ' . $this->documento->codigo);
0 ignored issues
show
Bug introduced by
The constant FS_ALBARAN was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
517
        $pdf_doc->pdf->addInfo('Subject', ucfirst(FS_ALBARAN) . ' de proveedor ' . $this->documento->codigo);
518
        $pdf_doc->pdf->addInfo('Author', $this->empresa->nombre);
519
520
        $lineas = $this->documento->get_lineas();
521
        $lineas_iva = $pdf_doc->get_lineas_iva($lineas);
522
        if ($lineas) {
523
            $linea_actual = 0;
524
            $pagina = 1;
525
526
            /// imprimimos las páginas necesarias
527
            while ($linea_actual < count($lineas)) {
528
                $lppag = 35;
529
530
                /// salto de página
531
                if ($linea_actual > 0) {
532
                    $pdf_doc->pdf->ezNewPage();
533
                }
534
535
                $pdf_doc->generar_pdf_cabecera($this->empresa, $lppag);
536
                $this->generar_pdf_datos_proveedor($pdf_doc);
537
                $this->generar_pdf_lineas($pdf_doc, $lineas, $linea_actual, $lppag);
538
                $this->generar_pdf_totales($pdf_doc, $lineas_iva, $pagina);
539
                $pagina++;
540
            }
541
        } else {
542
            $pdf_doc->pdf->ezText('¡' . ucfirst(FS_ALBARAN) . ' sin líneas!', 20);
543
        }
544
545
        if ($archivo) {
546
            if (!file_exists('tmp/' . FS_TMP_NAME . 'enviar')) {
0 ignored issues
show
Bug introduced by
The constant FS_TMP_NAME was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
547
                mkdir('tmp/' . FS_TMP_NAME . 'enviar');
548
            }
549
550
            $pdf_doc->save('tmp/' . FS_TMP_NAME . 'enviar/' . $archivo);
551
        } else {
552
            $pdf_doc->show(FS_ALBARAN . '_compra_' . $this->documento->codigo . '.pdf');
553
        }
554
    }
555
556
    private function generar_pdf_factura($archivo = false)
557
    {
558
        if (!$archivo) {
559
            /// desactivamos la plantilla HTML
560
            $this->template = false;
561
        }
562
563
        /// Creamos el PDF y escribimos sus metadatos
564
        $pdf_doc = new fs_pdf();
565
        $pdf_doc->pdf->addInfo('Title', 'Factura ' . $this->documento->codigo);
566
        $pdf_doc->pdf->addInfo('Subject', 'Factura de proveedor ' . $this->documento->codigo);
567
        $pdf_doc->pdf->addInfo('Author', $this->empresa->nombre);
568
569
        $lineas = $this->documento->get_lineas();
570
        $lineas_iva = $pdf_doc->get_lineas_iva($lineas);
571
        if ($lineas) {
572
            $lineasfact = count($lineas);
573
            $linea_actual = 0;
574
            $pagina = 1;
575
576
            // Imprimimos las páginas necesarias
577
            while ($linea_actual < $lineasfact) {
578
                $lppag = 35; /// líneas por página
579
                /// salto de página
580
                if ($linea_actual > 0) {
581
                    $pdf_doc->pdf->ezNewPage();
582
                }
583
584
                $pdf_doc->generar_pdf_cabecera($this->empresa, $lppag);
585
                $this->generar_pdf_datos_proveedor($pdf_doc);
586
                $this->generar_pdf_lineas($pdf_doc, $lineas, $linea_actual, $lppag);
587
                $this->generar_pdf_totales($pdf_doc, $lineas_iva, $pagina);
588
                $pagina++;
589
            }
590
        } else {
591
            $pdf_doc->pdf->ezText('¡Factura sin líneas!', 20);
592
        }
593
594
        if ($archivo) {
595
            if (!file_exists('tmp/' . FS_TMP_NAME . 'enviar')) {
0 ignored issues
show
Bug introduced by
The constant FS_TMP_NAME was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
596
                mkdir('tmp/' . FS_TMP_NAME . 'enviar');
597
            }
598
599
            $pdf_doc->save('tmp/' . FS_TMP_NAME . 'enviar/' . $archivo);
600
        } else {
601
            $pdf_doc->show('factura_compra_' . $this->documento->codigo . '.pdf');
602
        }
603
    }
604
605
    private function enviar_email()
606
    {
607
        if ($this->empresa->can_send_mail()) {
608
            $this->verificar_email();
609
            $filename = 'albaran_' . $this->documento->codigo . '.pdf';
610
            $this->generar_pdf_albaran($filename);
611
612
613
            $this->procesar_email($filename);
614
        }
615
    }
616
617
    public function procesar_email($filename)
618
    {
619
        $email = \filter_input(INPUT_POST, 'email');
620
        $de = \filter_input(INPUT_POST, 'de');
621
        $email_copia = \filter_input(INPUT_POST, 'email_copia');
622
        $cco = \filter_input(INPUT_POST, 'cco');
623
        $mensaje = \filter_input(INPUT_POST, 'mensaje');
624
        if (file_exists('tmp/' . FS_TMP_NAME . 'enviar/' . $filename)) {
0 ignored issues
show
Bug introduced by
The constant FS_TMP_NAME was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
625
            $razonsocial = $this->documento->nombre;
626
            $mail = $this->empresa->new_mail();
627
            $mail->FromName = $this->user->get_agente_fullname();
628
629
            if ($de != $mail->From) {
630
                $mail->addReplyTo($de, $mail->FromName);
631
            }
632
633
            $mail->addAddress($email, $razonsocial);
634
            if ($email_copia) {
635
                if ($cco) {
636
                    $mail->addBCC($email_copia, $razonsocial);
637
                } else {
638
                    $mail->addCC($email_copia, $razonsocial);
639
                }
640
            }
641
642
            $mail->Subject = $this->empresa->nombre . ': Mi ' . FS_ALBARAN . ' ' . $this->documento->codigo;
0 ignored issues
show
Bug introduced by
The constant FS_ALBARAN was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
643
            if ($this->is_html($mensaje)) {
644
                $mail->AltBody = strip_tags($mensaje);
645
                $mail->msgHTML($mensaje);
646
                $mail->isHTML(true);
647
            } else {
648
                $mail->Body = $mensaje;
649
            }
650
651
            $mail->addAttachment('tmp/' . FS_TMP_NAME . 'enviar/' . $filename);
652
            if (is_uploaded_file($_FILES['adjunto']['tmp_name'])) {
653
                $mail->addAttachment($_FILES['adjunto']['tmp_name'], $_FILES['adjunto']['name']);
654
            }
655
656
            $this->verificar_envio($mail);
657
658
            unlink('tmp/' . FS_TMP_NAME . 'enviar/' . $filename);
659
        } else {
660
            $this->new_error_msg('Imposible generar el PDF.');
661
        }
662
    }
663
664
    public function verificar_envio($mail)
665
    {
666
        if ($this->empresa->mail_connect($mail)) {
667
            if ($mail->send()) {
668
                $this->new_message('Mensaje enviado correctamente.');
669
                $this->empresa->save_mail($mail);
670
            } else {
671
                $this->new_error_msg("Error al enviar el email: " . $mail->ErrorInfo);
672
            }
673
        } else {
674
            $this->new_error_msg("Error al enviar el email: " . $mail->ErrorInfo);
675
        }
676
    }
677
678
    public function verificar_email()
679
    {
680
        $email = \filter_input(INPUT_POST, 'email');
681
        $guardar = \filter_input(INPUT_POST, 'guardar');
682
        if ($this->proveedor) {
683
            if ($email != $this->proveedor->email and $guardar) {
684
                $this->proveedor->email = $email;
685
                $this->proveedor->save();
686
            }
687
        }
688
    }
689
690
    public function is_html($txt)
691
    {
692
        if (stripos($txt, '<html') === false) {
693
            return false;
694
        } else {
695
            return true;
696
        }
697
    }
698
}
699