Passed
Push — master ( 63d1f8...7c50e7 )
by Joe Nilson
02:33
created

documentos_residentes::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
/*
3
 * Copyright (C) 2018 Joe Nilson <joenilson at gmail.com>
4
 *
5
 * This program is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU Lesser General Public License as published by
7
 * the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public License
16
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
 */
18
require_once 'plugins/residentes/extras/residentes_pdf.php';
19
require_once 'plugins/residentes/extras/fpdf183/ResidentesFpdf.php';
20
require_once 'extras/phpmailer/class.phpmailer.php';
21
require_once 'extras/phpmailer/class.smtp.php';
22
require_once 'plugins/residentes/extras/residentes_controller.php';
23
24
/**
25
 * Class Controller to manage all the documents to be printed, showed or emailed
26
 * in the Residentes plugin for FS_2017
27
 * @author Joe Nilson <joenilson at gmail.com>
28
 */
29
class documentos_residentes extends residentes_controller
30
{
31
    public $archivo;
32
    public $cliente_residente;
33
    public $documento;
34
    public $numpaginas;
35
    public $pagado;
36
    public $pendiente;
37
    public $tipo_accion;
38
    public $idprogramacion;
39
    public $idfactura;
40
41
    public function __construct()
42
    {
43
        parent::__construct(__CLASS__, 'Documentos Residentes', 'admin', false, false, false);
44
    }
45
46
    protected function private_core()
47
    {
48
        parent::private_core();
49
        $this->init();
50
        $cod = $this->filter_request('codcliente');
51
        if ($cod) {
0 ignored issues
show
introduced by
$cod is of type type, thus it always evaluated to true.
Loading history...
52
            $cliente = new cliente();
53
            $this->cliente_residente = $cliente->get($cod);
54
            $residente_informacion = new residentes_informacion();
55
            $informacion = $residente_informacion->get($cod);
56
            $residente_edificacion = new residentes_edificaciones();
57
            $residente = $residente_edificacion->get_by_field('codcliente', $cod);
0 ignored issues
show
Bug introduced by
'codcliente' of type string is incompatible with the type FacturaScripts\model\type expected by parameter $field of FacturaScripts\model\res...aciones::get_by_field(). ( Ignorable by Annotation )

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

57
            $residente = $residente_edificacion->get_by_field(/** @scrutinizer ignore-type */ 'codcliente', $cod);
Loading history...
58
            $this->cliente_residente->inmueble = $residente[0];
59
            $this->cliente_residente->informacion = $informacion;
60
        }
61
        $info_accion = $this->filter_request('info_accion');
62
        $tipo_documento = $this->filter_request('tipo_documento');
63
        $this->tipo_accion = $tipo_documento;
64
        if ($this->cliente_residente && $info_accion) {
65
            switch ($info_accion) {
66
                case 'imprimir':
67
                    $this->template = false;
68
                    $this->imprimir_documento($tipo_documento);
69
                    break;
70
                case 'enviar':
71
                    $this->enviar_documento($tipo_documento);
72
                    break;
73
                default:
74
                    break;
75
            }
76
        }
77
    }
78
79
    public function crear_documento($tipo_documento)
80
    {
81
        $this->archivo = \date('dmYhis') . '.pdf';
82
        switch ($tipo_documento) {
83
            case 'informacion_cobros':
84
                $this->documento = new residentes_pdf('letter', 'portrait');
85
                $this->documento->pdf->addInfo('Title', 'Pagos Residente ' .
86
                                        $this->cliente_residente->codcliente);
87
                $this->documento->pdf->addInfo('Subject', 'Pagos del Residente ' .
88
                                        $this->cliente_residente->codcliente);
89
                $this->documento->pdf->addInfo('Author', $this->empresa->nombre);
90
                $this->documento->pdf->ezSetMargins(10, 10, 10, 10);
91
                $this->crear_documento_cobros();
92
                break;
93
            case 'factura_residente_detallada':
94
                $this->idprogramacion = $this->filter_request('idprogramacion');
95
                $this->crearFacturaDetallada();
96
                break;
97
            default:
98
                $this->documento = false;
99
                break;
100
        }
101
    }
102
103
    private function datosFactura()
104
    {
105
        $datosFacturaCabecera = [];
106
        $datosFacturaDetalle = [];
107
        $this->idfactura = $this->filter_request('idfactura');
108
        if ($this->idfactura != '') {
0 ignored issues
show
introduced by
The condition $this->idfactura != '' is always true.
Loading history...
109
            $facturas = new factura_cliente();
1 ignored issue
show
Bug introduced by
The type factura_cliente 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
            $factura = $facturas->get($this->idfactura);
111
            $datosFacturaCabecera = (array) $factura;
112
            if ($this->RD_plugin) {
113
                $ncf = new ncf_ventas();
1 ignored issue
show
Bug introduced by
The type ncf_ventas 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...
114
                $ncfTipo = $ncf->get($this->empresa->id, $factura->numero2);
115
                //var_dump($ncfTipo);
116
                $datosFacturaCabecera['tiponcf'] = $ncfTipo[0]->tipo_descripcion;
117
                $datosFacturaCabecera['vencimientoncf'] = $ncfTipo[0]->fecha_vencimiento;
118
            }
119
120
            $lineas = $factura->get_lineas();
121
            $totalAntesDescuento = 0;
122
            $totalDescuento = 0;
123
            foreach ($lineas as $linea) {
124
                $totalAntesDescuento += $linea->pvpsindto;
125
                $totalDescuento += ($linea->pvpsindto - $linea->pvptotal);
126
                $datosFacturaDetalle[] = (array) $linea;
127
            }
128
            $datosFacturaCabecera['total_antes_descuento'] = $totalAntesDescuento;
129
            $datosFacturaCabecera['total_descuento'] = $totalDescuento;
130
        }
131
        return [$datosFacturaCabecera, $datosFacturaDetalle];
132
    }
133
134
    public function crearFacturaDetallada()
135
    {
136
        $customerInfo = (array) $this->cliente_residente;
137
        $customerInfo['direccion'] = trim($this->cliente_residente->inmueble->codigo_externo()) . ' numero '
138
            . $this->cliente_residente->inmueble->numero;
139
        $datosFactura = $this->datosFactura();
140
        $datosEmpresa = (array) $this->empresa;
141
        $this->documento = new ResidentesFpdf('L', 'mm', 'A5');
142
        //var_dump($datosFactura[1]);
143
        $this->documento->createDocument($datosEmpresa, $datosFactura[0], $datosFactura[1], $customerInfo);
144
        $this->documento->Output('I');
145
    }
146
147
    public function crearFacturaDetalladaOLD()
148
    {
149
        $this->pendiente = $this->pagosFactura(false);
150
        $this->pagado = $this->pagosFactura(true);
151
        $linea_actual = 0;
152
        $pagina = 1;
153
        $lppag = 28; /// líneas por página
154
        while ($linea_actual < count($this->pendiente)) {
155
            /// salto de página
156
            if ($linea_actual > 0) {
157
                $this->documento->pdf->ezNewPage();
158
            }
159
            $this->pdfGenerarCabecera($this->documento, $this->empresa, $lppag);
160
            $this->generar_datos_residente($this->documento, 'factura_detallada', $lppag);
161
            $this->pdfFacturaResumen($this->documento, $this->empresa, $lppag);
162
            $this->pdfFacturaDetalle($this->documento, $empresa, $lppag, $lppag);
1 ignored issue
show
Comprehensibility Best Practice introduced by
The variable $empresa seems to be never defined.
Loading history...
163
164
            $this->generar_pdf_lineas(
165
                $this->documento,
166
                $this->pendiente,
167
                $linea_actual,
168
                $lppag,
169
                'pendiente'
170
            );
171
            //$this->documento->set_y($this->documento->pdf->y - 16);
172
            $pagina++;
173
        }
174
175
//        $linea_actual2 = 0;
176
//        $linea_actual2 = $linea_actual;
177
//        while ($linea_actual2 < count($this->pagado)) {
178
//            if ($linea_actual2 > 0) {
179
//                $this->documento->pdf->ezNewPage();
180
//                $this->pdfGenerarCabecera($this->documento, $this->empresa, $lppag);
181
//                $this->pdfFacturaResumen($this->documento, $this->empresa, $lppag);
182
//                $this->generar_datos_residente($this->documento, 'factura_detallada', $lppag);
183
//            } elseif ($linea_actual2 === 0) {
184
//                $this->generar_datos_residente($this->documento, 'factura_detallada', $lppag);
185
//            }
186
//            $this->generar_pdf_lineas(
187
//                $this->documento,
188
//                $this->pagado,
189
//                $linea_actual2,
190
//                $lppag,
191
//                'pagado'
192
//            );
193
//            $pagina++;
194
//        }
195
196
        $this->documento->set_y(80);
197
        if ($this->empresa->pie_factura) {
198
            $this->documento->pdf->addText(20, 40, 8, fs_fix_html('<b>Generado por:</b> ' .
1 ignored issue
show
Bug introduced by
The function fs_fix_html 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

198
            $this->documento->pdf->addText(20, 40, 8, /** @scrutinizer ignore-call */ fs_fix_html('<b>Generado por:</b> ' .
Loading history...
199
                $this->user->get_agente_fullname()), 0);
200
            $this->documento->pdf->addText(
201
                10,
202
                20,
203
                8,
204
                $this->documento->center_text(fs_fix_html($this->empresa->pie_factura), 180)
205
            );
206
        }
207
208
        if ($this->filter_request('info_accion') == 'enviar') {
0 ignored issues
show
introduced by
The condition $this->filter_request('info_accion') == 'enviar' is always false.
Loading history...
209
            $this->documento->save('tmp/' . FS_TMP_NAME . 'enviar/' . $this->archivo);
1 ignored issue
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...
210
        } else {
211
            $this->documento->show('documento_cobros_' . \date('dmYhis') . '.pdf');
212
        }
213
    }
214
215
    public function crear_documento_cobros()
216
    {
217
        $this->pendiente = $this->pagosFactura(false);
218
        $this->pagado = $this->pagosFactura(true);
219
220
        $linea_actual = 0;
221
        $pagina = 1;
222
        $lppag = 30; /// líneas por página
223
        while ($linea_actual < count($this->pendiente)) {
224
            /// salto de página
225
            if ($linea_actual > 0) {
226
                $this->documento->pdf->ezNewPage();
227
            }
228
            $this->documento->generar_pdf_cabecera($this->empresa, $lppag);
229
            $this->generar_datos_residente($this->documento, 'informe_cobros', $lppag);
230
            $this->generar_pdf_lineas(
231
                $this->documento,
232
                $this->pendiente,
233
                $linea_actual,
234
                $lppag,
235
                'pendiente'
236
            );
237
            $this->documento->set_y($this->documento->pdf->y - 16);
238
        }
239
240
        $linea_actual2 = 0;
241
        while ($linea_actual2 < count($this->pagado)) {
242
            if ($linea_actual2 > 0) {
243
                $this->documento->pdf->ezNewPage();
244
            } elseif ($linea_actual === 0) {
245
                $this->documento->generar_pdf_cabecera($this->empresa, $lppag);
246
                $this->generar_datos_residente($this->documento, 'informe_cobros', $lppag);
247
            }
248
            $this->generar_pdf_lineas(
249
                $this->documento,
250
                $this->pagado,
251
                $linea_actual2,
252
                $lppag,
253
                'pagado'
254
            );
255
            $pagina++;
256
        }
257
        $this->documento->set_y(80);
258
        if ($this->empresa->pie_factura) {
259
            $this->documento->pdf->addText(20, 40, 8, fs_fix_html('<b>Generado por:</b> ' .
1 ignored issue
show
Bug introduced by
The function fs_fix_html 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

259
            $this->documento->pdf->addText(20, 40, 8, /** @scrutinizer ignore-call */ fs_fix_html('<b>Generado por:</b> ' .
Loading history...
260
                $this->user->get_agente_fullname()), 0);
261
            $this->documento->pdf->addText(
262
                10,
263
                30,
264
                8,
265
                $this->documento->center_text(fs_fix_html($this->empresa->pie_factura), 180)
266
            );
267
        }
268
269
        if ($this->filter_request('info_accion') == 'enviar') {
0 ignored issues
show
introduced by
The condition $this->filter_request('info_accion') == 'enviar' is always false.
Loading history...
270
            $this->documento->save('tmp/' . FS_TMP_NAME . 'enviar/' . $this->archivo);
1 ignored issue
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...
271
        } else {
272
            $this->documento->show('documento_cobros_' . \date('dmYhis') . '.pdf');
273
        }
274
    }
275
276
    public function enviar_documento($tipo_documento)
277
    {
278
        $this->crear_documento($tipo_documento);
279
        $tipo_doc = $this->generar_tipo_doc($tipo_documento);
280
        if (file_exists('tmp/' . FS_TMP_NAME . 'enviar/' . $this->archivo)) {
1 ignored issue
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...
281
            $mail = $this->empresa->new_mail();
282
            $mail->FromName = $this->user->get_agente_fullname();
283
284
            if ($_POST['de'] !== $mail->From) {
285
                $mail->addReplyTo($_POST['de'], $mail->FromName);
286
            }
287
288
            $mail->addAddress($_POST['email'], $this->cliente_residente->nombre);
289
            if ($_POST['email_copia']) {
290
                if (isset($_POST['cco'])) {
291
                    $mail->addBCC($_POST['email_copia'], $this->cliente_residente->nombre);
292
                } else {
293
                    $mail->addCC($_POST['email_copia'], $this->cliente_residente->nombre);
294
                }
295
            }
296
297
            $mail->Subject = $this->empresa->nombre . ': ' . $tipo_doc;
298
299
            if ($this->is_html($_POST['mensaje'])) {
300
                $mail->AltBody = strip_tags($_POST['mensaje']);
301
                $mail->msgHTML($_POST['mensaje']);
302
                $mail->isHTML(true);
303
            } else {
304
                $mail->Body = $_POST['mensaje'];
305
            }
306
307
            $mail->addAttachment('tmp/' . FS_TMP_NAME . 'enviar/' . $this->archivo);
308
            if (is_uploaded_file($_FILES['adjunto']['tmp_name'])) {
309
                $mail->addAttachment($_FILES['adjunto']['tmp_name'], $_FILES['adjunto']['name']);
310
            }
311
312
            if ($this->empresa->mail_connect($mail) && $mail->send()) {
313
                $this->new_message('Mensaje enviado correctamente.');
314
                $this->empresa->save_mail($mail);
315
            } else {
316
                $this->new_error_msg("Error al enviar el email: " . $mail->ErrorInfo);
317
            }
318
319
            unlink('tmp/' . FS_TMP_NAME . 'enviar/' . $this->archivo);
320
        } else {
321
            $this->new_error_msg('Imposible generar el PDF.');
322
        }
323
    }
324
325
    public function generar_datos_residente(&$pdf_doc, $tipo_documento, &$lppag, $table_width = 560)
326
    {
327
        $width_campo1 = 110;
328
        $tipo_doc = $this->generar_tipo_doc($tipo_documento);
329
        $tipo_residente = ($this->cliente_residente->informacion->propietario) ? 'Propietario' : 'Inquilino';
330
        /*
331
         * Esta es la tabla con los datos del cliente:
332
         * Informe Cobros           Fecha:
333
         * Cliente:        Tipo Residente:
334
         * Dirección:           Teléfonos:
335
         */
336
        $pdf_doc->new_table();
337
        $pdf_doc->add_table_row(
338
            array(
339
                'campo1' => "<b>" . $tipo_doc . "</b>",
340
                'dato1' => '',
341
                'campo2' => "<b>Fecha Impresión:</b> " . \date('d-m-Y H:i:s')
342
            )
343
        );
344
345
        $pdf_doc->add_table_row(
346
            array(
347
                'campo1' => "<b>Residente:</b>",
348
                'dato1' => fs_fix_html($this->cliente_residente->nombre),
1 ignored issue
show
Bug introduced by
The function fs_fix_html 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

348
                'dato1' => /** @scrutinizer ignore-call */ fs_fix_html($this->cliente_residente->nombre),
Loading history...
349
                'campo2' => "<b>Tipo Residente:</b> " . $tipo_residente
350
            )
351
        );
352
353
        $row = array(
354
            'campo1' => "<b>Inmueble:</b>",
355
            'dato1' => fs_fix_html($this->cliente_residente->inmueble->codigo_externo() .
356
                ' - ' . $this->cliente_residente->inmueble->numero),
357
            'campo2' => ''
358
        );
359
360
        if (!$this->cliente_residente) {
361
            /// nada
362
        } elseif ($this->cliente_residente->telefono1) {
363
            $row['campo2'] = "<b>Teléfonos:</b> " . $this->cliente_residente->telefono1;
364
            if ($this->cliente_residente->telefono2) {
365
                $row['campo2'] .= "\n" . $this->cliente_residente->telefono2;
366
                $lppag -= 2;
367
            }
368
        } elseif ($this->cliente_residente->telefono2) {
369
            $row['campo2'] = "<b>Teléfonos:</b> " . $this->cliente_residente->telefono2;
370
        }
371
        $pdf_doc->add_table_row($row);
372
373
        $pdf_doc->save_table(
374
            array(
375
                'cols' => array(
376
                    'campo1' => array('width' => $width_campo1, 'justification' => 'right'),
377
                    'dato1' => array('justification' => 'left'),
378
                    'campo2' => array('justification' => 'right')
379
                ),
380
                'showLines' => 0,
381
                'width' => $table_width,
382
                'shaded' => 0,
383
                'fontSize' => 8
384
            )
385
        );
386
        $pdf_doc->pdf->ezText("\n", 10);
387
    }
388
389
    public function generar_pdf_lineas(&$pdf_doc, &$items, &$linea_actual, &$lppag, $tipo, $table_width = 540)
390
    {
391
        /// calculamos el número de páginas
392
        if (!isset($this->numpaginas)) {
393
            $this->numpaginas = 0;
394
            $lineas = 0;
395
            while ($lineas < count($items)) {
396
                $lppag2 = $lppag;
397
                $this->verificar_longitud_linea($items, $lineas, $lppag2);
398
                $lineas += $lppag2;
399
                $this->numpaginas++;
400
            }
401
402
            if ($this->numpaginas === 0) {
403
                $this->numpaginas = 1;
404
            }
405
        }
406
407
        /// leemos las líneas para ver si hay que mostrar mas información
408
        $this->verificar_longitud_linea($items, $linea_actual, $lppag);
409
410
        /*
411
         * Creamos la tabla con las lineas de pendientes
412
         */
413
        $pdf_doc->new_table();
414
        [$table_header, $array_cols] = $this->generar_pdf_lineas_tablas($tipo);
415
        $pdf_doc->add_table_header($table_header);
416
417
        for ($i = $linea_actual; (($linea_actual < ($lppag + $i)) && ( $linea_actual < count($items)));) {
418
            $fila = $this->generar_pdf_lineas_fila($tipo, $items, $linea_actual);
419
            $pdf_doc->add_table_row($fila);
420
            $linea_actual++;
421
        }
422
423
        $pdf_doc->save_table(
424
            array(
425
                'fontSize' => 8,
426
                'cols' => $array_cols,
427
                'width' => $table_width,
428
                'shaded' => 1,
429
                'shadeCol' => array(0.95, 0.95, 0.95),
430
                'lineCol' => array(0.3, 0.3, 0.3),
431
            )
432
        );
433
    }
434
    
435
    public function generar_pdf_lineas_tablas($tipo)
436
    {
437
        $table_header = array(
438
            'item' => '<b>Pendiente de Pago</b>', 'fecha' => '<b>Fecha</b>',
439
            'vencimiento' => '<b>Vencimiento</b>', 'importe' => '<b>Monto</b>',
440
            'descuento' => '<b>Descuento</b>', 'total' => '<b>Total</b>', 'atraso' => '<b>Atraso</b>',
441
        );
442
        $array_cols = array(
443
            'item' => array('justification' => 'left'), 'fecha' => array('justification' => 'center'),
444
            'vencimiento' => array('justification' => 'center'), 'importe' => array('justification' => 'right'),
445
            'descuento' => array('justification' => 'right'),
446
            'total' => array('justification' => 'right'), 'atraso' => array('justification' => 'center')
447
        );
448
        if ($tipo === 'pagado') {
449
            $table_header = array(
450
                'item' => '<b>Pagos Realizados</b>', 'fecha' => '<b>Fecha</b>',
451
                'importe' => '<b>Monto</b>', 'f_pago' => '<b>F. Pago</b>'
452
            );
453
            $array_cols = array(
454
                'item' => array('justification' => 'left'), 'fecha' => array('justification' => 'center'),
455
                'importe' => array('justification' => 'right'), 'f_pago' => array('justification' => 'center')
456
            );
457
        }
458
        
459
        return array($table_header,$array_cols);
460
    }
461
    
462
    public function generar_pdf_lineas_fila($tipo, $items, $linea_actual)
463
    {
464
        $descripcion = fs_fix_html($items[$linea_actual]->descripcion);
1 ignored issue
show
Bug introduced by
The function fs_fix_html 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

464
        $descripcion = /** @scrutinizer ignore-call */ fs_fix_html($items[$linea_actual]->descripcion);
Loading history...
465
        $fila = array(
466
            'item' => $descripcion,
467
            'fecha' => $items[$linea_actual]->fecha,
468
            'vencimiento' => $items[$linea_actual]->vencimiento,
469
            'importe' => $this->show_precio($items[$linea_actual]->pvpsindto, $this->empresa->coddivisa, true, FS_NF0),
1 ignored issue
show
Bug introduced by
The constant FS_NF0 was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
470
            'descuento' => $this->show_numero($items[$linea_actual]->dtopor) . " %",
471
            'total' => $this->show_precio($items[$linea_actual]->pvptotal, $this->empresa->coddivisa, true, FS_NF0),
472
            'atraso' => $items[$linea_actual]->dias_atraso
473
        );
474
        if ($tipo === 'pagado') {
475
            $fila = array(
476
            'item' => $descripcion,
477
            'fecha' => $items[$linea_actual]->fecha,
478
            'importe' => $this->show_precio($items[$linea_actual]->pvptotal, $this->empresa->coddivisa, true, FS_NF0),
479
            'f_pago' => $items[$linea_actual]->f_pago
480
            );
481
        }
482
        return $fila;
483
    }
484
485
    public function verificar_longitud_linea($items, &$lineas, &$lppag2)
486
    {
487
        foreach ($items as $i => $lin) {
488
            if ($i >= $lineas && $i < $lineas + $lppag2) {
489
                $linea_size = 1;
490
                $len = mb_strlen($lin->descripcion);
491
                while ($len > 85) {
492
                    $len -= 85;
493
                    $linea_size += 0.5;
494
                }
495
                $aux = explode("\n", $lin->descripcion);
496
                if (count($aux) > 1) {
497
                    $linea_size += 0.5 * ( count($aux) - 1);
498
                }
499
                if ($linea_size > 1) {
500
                    $lppag2 -= $linea_size - 1;
501
                }
502
            }
503
        }
504
    }
505
506
    public function pdfGenerarCabecera(&$pdf_doc, &$empresa, &$lppag)
507
    {
508
        /// ¿Añadimos el logo?
509
        if ($pdf_doc->logo !== false) {
510
            if (function_exists('imagecreatefromstring')) {
511
                $lppag -= 4; /// si metemos el logo, caben menos líneas
512
                $pdf_doc_LOGO_X = 20;
513
                $pdf_doc_LOGO_Y = 320;
514
                $tamanyo = $pdf_doc->calcular_tamanyo_logo();
515
                if (strtolower(substr($pdf_doc->logo, -4)) === '.png') {
516
                    $pdf_doc->pdf->addPngFromFile($pdf_doc->logo, $pdf_doc_LOGO_X, $pdf_doc_LOGO_Y, $tamanyo[0], $tamanyo[1]);
517
                } elseif (function_exists('imagepng')) {
518
                    /**
519
                     * La librería ezpdf tiene problemas al redimensionar jpegs,
520
                     * así que hacemos la conversión a png para evitar estos problemas.
521
                     */
522
                    if (imagepng(imagecreatefromstring(file_get_contents($pdf_doc->logo)), FS_MYDOCS
1 ignored issue
show
Bug introduced by
The constant FS_MYDOCS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
523
                        . 'images/logo.png')) {
524
                        $pdf_doc->pdf->addPngFromFile(
525
                            FS_MYDOCS . 'images/logo.png',
526
                            $pdf_doc_LOGO_X,
527
                            $pdf_doc_LOGO_Y,
528
                            $tamanyo[0],
529
                            $tamanyo[1]
530
                        );
531
                    } else {
532
                        $pdf_doc->pdf->addJpegFromFile($pdf_doc->logo, $pdf_doc_LOGO_X, $pdf_doc_LOGO_Y, $tamanyo[0], $tamanyo[1]);
533
                    }
534
                } else {
535
                    $pdf_doc->pdf->addJpegFromFile($pdf_doc->logo, $pdf_doc_LOGO_X, $pdf_doc_LOGO_Y, $tamanyo[0], $tamanyo[1]);
536
                }
537
                $pdf_doc->set_y(400);
538
                $pdf_doc->pdf->ez['leftMargin'] = 120;
539
                $pdf_doc->pdf->ezText(
540
                    "<b>" . fs_fix_html($empresa->nombre) . "</b>",
1 ignored issue
show
Bug introduced by
The function fs_fix_html 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

540
                    "<b>" . /** @scrutinizer ignore-call */ fs_fix_html($empresa->nombre) . "</b>",
Loading history...
541
                    12,
542
                    array('justification' => 'left')
543
                );
544
                $pdf_doc->pdf->ezText(FS_CIFNIF . ": " . $empresa->cifnif, 8, array('justification' => 'left'));
1 ignored issue
show
Bug introduced by
The constant FS_CIFNIF was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
545
546
                $direccion = $empresa->direccion . "\n";
547
                if ($empresa->apartado) {
548
                    $direccion .= ucfirst(FS_APARTADO) . ': ' . $empresa->apartado . ' - ';
1 ignored issue
show
Bug introduced by
The constant FS_APARTADO was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
549
                }
550
551
                if ($empresa->codpostal) {
552
                    $direccion .= 'CP: ' . $empresa->codpostal . ' - ';
553
                }
554
555
                if ($empresa->ciudad) {
556
                    $direccion .= $empresa->ciudad . ' - ';
557
                }
558
559
                if ($empresa->provincia) {
560
                    $direccion .= '(' . $empresa->provincia . ')';
561
                }
562
563
                if ($empresa->telefono) {
564
                    $direccion .= "\nTeléfono: " . $empresa->telefono . ' - '.$pdf_doc_LOGO_X."/".$pdf_doc_LOGO_Y;
565
                }
566
567
                $pdf_doc->pdf->ezText(fs_fix_html($direccion) . "\n", 8, array('justification' => 'left'));
568
                $pdf_doc->set_y($pdf_doc_LOGO_Y);
569
570
                $pdf_doc->pdf->ez['leftMargin'] = 10;
571
            } else {
572
                die('ERROR: no se encuentra la función imagecreatefromstring(). '
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
573
                    . 'Y por tanto no se puede usar el logotipo en los documentos.');
574
            }
575
        } else {
576
            $pdf_doc->pdf->ezText(
577
                "<b>" . fs_fix_html($empresa->nombre) . "</b>",
578
                12,
579
                array('justification' => 'left')
580
            );
581
            $pdf_doc->pdf->ezText(FS_CIFNIF . ": " . $empresa->cifnif, 8, array('justification' => 'left'));
582
583
            $direccion = $empresa->direccion;
584
            if ($empresa->apartado) {
585
                $direccion .= ' - ' . ucfirst(FS_APARTADO) . ': ' . $empresa->apartado;
586
            }
587
588
            if ($empresa->codpostal) {
589
                $direccion .= ' - CP: ' . $empresa->codpostal;
590
            }
591
592
            if ($empresa->ciudad) {
593
                $direccion .= ' - ' . $empresa->ciudad;
594
            }
595
596
            if ($empresa->provincia) {
597
                $direccion .= ' (' . $empresa->provincia . ')';
598
            }
599
600
            if ($empresa->telefono) {
601
                $direccion .= ' - Teléfono: ' . $empresa->telefono;
602
            }
603
604
            $pdf_doc->pdf->ezText(fs_fix_html($direccion), 8, array('justification' => 'left'));
605
        }
606
    }
607
608
    public function pdfFacturaResumen(&$pdf_doc, &$empresa, &$lppag)
609
    {
610
        $pdf_doc->set_y(420);
611
        $pdf_doc->pdf->ez['leftMargin'] = 440;
612
        $pdf_doc->pdf->ez['rightMargin'] = 10;
613
614
        $facturas = new factura_cliente();
615
        $clientes = new cliente();
616
        $cliente = $clientes->get($this->filter_request('codcliente'));
0 ignored issues
show
Unused Code introduced by
The assignment to $cliente is dead and can be removed.
Loading history...
617
        $factura = $facturas->get($this->filter_request('idfactura'));
618
        $tipo_factura = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $tipo_factura is dead and can be removed.
Loading history...
619
        if (isset($factura->ncf_tipo)) {
620
            $tipo_factura = $factura->ncf_tipo;
621
        }
622
623
        $pdf_doc->new_table();
624
        $pdf_doc->add_table_row(
625
            array(
626
                'campos' => "<b>" . ucfirst(FS_FACTURA) . ":</b>\n <b>".FS_NUMERO2.":</b>\n<b>Fecha:</b>\n<b>" . 'F. Pago' . ":</b>",
2 ignored issues
show
Bug introduced by
The constant FS_NUMERO2 was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant FS_FACTURA was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
627
                'factura' => $factura->codigo . "\n" . $factura->numero2 . "\n" . $factura->fecha . "\n" . $factura->codpago,
628
            )
629
        );
630
        $pdf_doc->save_table(
631
            array(
632
                'cols' => array(
633
                    'campos' => array('justification' => 'right', 'width' => 120),
634
                    'factura' => array('justification' => 'left')
635
                ),
636
                'showLines' => 0,
637
                'fontSize' => 9,
638
                'width' => 320
639
            )
640
        );
641
642
        $pdf_doc->set_y(240);
643
        $pdf_doc->pdf->ez['leftMargin'] = 10;
644
    }
645
646
    public function pdfFacturaDetalle(&$pdf_doc, &$empresa, &$lppag,  &$linea_actual)
647
    {
648
        $facturas = new factura_cliente();
649
        $clientes = new cliente();
650
        $cliente = $clientes->get($this->filter_request('codcliente'));
0 ignored issues
show
Unused Code introduced by
The assignment to $cliente is dead and can be removed.
Loading history...
651
        $factura = $facturas->get($this->filter_request('idfactura'));
652
        $lineas = $factura->get_lineas();
653
654
        $pdf_doc->new_table();
655
        $table_header = array(
656
            'descripcion' => '<b>Ref. + Descripción</b>',
657
            'cantidad' => '<b>Cant.</b>',
658
            'pvp' => '<b>Precio</b>',
659
            'dto' => '<b>Dto.</b>',
660
            'importe' => '<b>Importe</b>'
661
        );
662
663
        $pdf_doc->add_table_header($table_header);
664
665
        for ($i = $linea_actual; (($linea_actual < ($lppag + $i)) && ( $linea_actual < count($lineas)));) {
666
            $descripcion = fs_fix_html($lineas[$linea_actual]->descripcion);
1 ignored issue
show
Bug introduced by
The function fs_fix_html 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

666
            $descripcion = /** @scrutinizer ignore-call */ fs_fix_html($lineas[$linea_actual]->descripcion);
Loading history...
667
            if (!is_null($lineas[$linea_actual]->referencia) && $this->impresion['print_ref']) {
668
                $descripcion = '<b>' . $lineas[$linea_actual]->referencia . '</b> ' . $descripcion;
669
            }
670
671
            /// ¿El articulo tiene trazabilidad?
672
            //$descripcion .= $this->generar_trazabilidad($lineas[$linea_actual]);
673
674
            $due_lineas = $this->fbase_calc_desc_due([$lineas[$linea_actual]->dtopor, $lineas[$linea_actual]->dtopor2, $lineas[$linea_actual]->dtopor3, $lineas[$linea_actual]->dtopor4]);
675
676
            $fila = array(
677
                'descripcion' => $descripcion,
678
                'cantidad' => $this->show_numero($lineas[$linea_actual]->cantidad, 0),
679
                'pvp' => $this->show_precio($lineas[$linea_actual]->pvpunitario, $factura->coddivisa, true, FS_NF0_ART),
1 ignored issue
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...
680
                'dto' => $this->show_numero($due_lineas) . " %",
681
                'importe' => $this->show_precio($lineas[$linea_actual]->pvptotal, $this->documento->coddivisa)
682
            );
683
684
            if ($lineas[$linea_actual]->dtopor == 0) {
685
                $fila['dto'] = '';
686
            }
687
688
            if (!$lineas[$linea_actual]->mostrar_cantidad) {
689
                $fila['cantidad'] = '';
690
            }
691
692
            if (!$lineas[$linea_actual]->mostrar_precio) {
693
                $fila['pvp'] = '';
694
                $fila['dto'] = '';
695
                $fila['importe'] = '';
696
            }
697
698
            $pdf_doc->add_table_row($fila);
699
            $linea_actual++;
700
        }
701
702
        $pdf_doc->save_table(
703
            array(
704
                'fontSize' => 8,
705
                'cols' => array(
706
                    'cantidad' => array('justification' => 'right'),
707
                    'pvp' => array('justification' => 'right'),
708
                    'dto' => array('justification' => 'right'),
709
                    'iva' => array('justification' => 'right'),
710
                    'importe' => array('justification' => 'right')
711
                ),
712
                'width' => 540,
713
                'shaded' => 1,
714
                'shadeCol' => array(0.95, 0.95, 0.95),
715
                'lineCol' => array(0.3, 0.3, 0.3),
716
            )
717
        );
718
719
        /// ¿Última página?
720
        if ($linea_actual == count($lineas) && $this->documento->observaciones != '') {
721
            $pdf_doc->pdf->ezText("\n" . fs_fix_html($this->documento->observaciones), 9);
722
        }
723
    }
724
725
    public function generar_tipo_doc($tipo_documento)
726
    {
727
        return ucfirst(str_replace('_', ' ', $tipo_documento));
728
    }
729
730
    public function imprimir_documento($tipo_documento)
731
    {
732
        $this->template = false;
1 ignored issue
show
Bug Best Practice introduced by
The property template does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
733
        $this->crear_documento($tipo_documento);
734
    }
735
736
    public function init()
737
    {
738
        $this->existe_tesoreria();
739
        $this->cliente_residente = false;
740
        if (!file_exists('tmp/' . FS_TMP_NAME . 'enviar') &&
1 ignored issue
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...
741
            !mkdir($concurrentDirectory = 'tmp/' . FS_TMP_NAME . 'enviar') &&
742
            !is_dir($concurrentDirectory)) {
743
            throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
744
        }
745
    }
746
747
    public function is_html($txt)
748
    {
749
        return $txt !== strip_tags($txt);
750
    }
751
}
752