Passed
Push — master ( d67de9...7babde )
by Joe Nilson
02:15
created

documentos_residentes::crearEstadoCuenta()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 9
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 11
rs 9.9666
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->crearEstadoCuenta();
85
                break;
86
            case 'factura_residente_detallada':
87
                $this->idprogramacion = $this->filter_request('idprogramacion');
88
                $this->crearFacturaDetallada();
89
                break;
90
            default:
91
                $this->documento = false;
92
                break;
93
        }
94
    }
95
96
    private function datosFactura()
97
    {
98
        $datosFacturaCabecera = [];
99
        $datosFacturaDetalle = [];
100
        $this->idfactura = $this->filter_request('idfactura');
101
        if ($this->idfactura != '') {
0 ignored issues
show
introduced by
The condition $this->idfactura != '' is always true.
Loading history...
102
            $facturas = new factura_cliente();
103
            $factura = $facturas->get($this->idfactura);
104
            $datosFacturaCabecera = (array) $factura;
105
            if ($this->RD_plugin) {
106
                $ncf = new ncf_ventas();
107
                $ncfTipo = $ncf->get($this->empresa->id, $factura->numero2);
108
                $datosFacturaCabecera['tiponcf'] = $ncfTipo[0]->tipo_descripcion;
109
                $datosFacturaCabecera['vencimientoncf'] = $ncfTipo[0]->fecha_vencimiento;
110
            }
111
            $lineas = $factura->get_lineas();
112
            $totalAntesDescuento = 0;
113
            $totalDescuento = 0;
114
            foreach ($lineas as $linea) {
115
                $totalAntesDescuento += $linea->pvpsindto;
116
                $totalDescuento += ($linea->pvpsindto - $linea->pvptotal);
117
                $datosFacturaDetalle[] = (array) $linea;
118
            }
119
            $datosFacturaCabecera['total_antes_descuento'] = $totalAntesDescuento;
120
            $datosFacturaCabecera['total_descuento'] = $totalDescuento;
121
        }
122
        return [$datosFacturaCabecera, $datosFacturaDetalle];
123
    }
124
    public function crearEstadoCuenta()
125
    {
126
        $this->documento = new residentes_pdf('letter', 'portrait');
127
        $this->documento->cliente_residente = $this->cliente_residente;
128
        $this->documento->pdf->addInfo('Title', 'Pagos Residente ' .
129
            $this->cliente_residente->codcliente);
130
        $this->documento->pdf->addInfo('Subject', 'Pagos del Residente ' .
131
            $this->cliente_residente->codcliente);
132
        $this->documento->pdf->addInfo('Author', $this->empresa->nombre);
133
        $this->documento->pdf->ezSetMargins(10, 10, 10, 10);
134
        $this->crear_documento_cobros();
135
    }
136
137
    public function crearFacturaDetallada()
138
    {
139
        $customerInfo = (array) $this->cliente_residente;
140
        $customerInfo['direccion'] = trim($this->cliente_residente->inmueble->codigo_externo()) . ' numero '
141
            . $this->cliente_residente->inmueble->numero;
142
        $datosFactura = $this->datosFactura();
143
        $datosEmpresa = (array) $this->empresa;
144
        $this->documento = new ResidentesFpdf('L', 'mm', 'A5');
0 ignored issues
show
Bug introduced by
The type ResidentesFpdf 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...
145
//        $this->documento = new ResidentesFpdf('P', 'mm', 'letter');
146
        $this->documento->createDocument($datosEmpresa, $datosFactura[0], $datosFactura[1], $customerInfo);
147
        $this->pendiente = $this->pagosFactura(false);
148
        $this->documento->addEstadoCuentaPendiente($this->pendiente);
149
150
        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...
151
            $this->documento->Output(
152
                'tmp/' . FS_TMP_NAME . 'enviar/',
153
                $this->archivo
154
            );
155
        } else {
156
            $this->documento->Output(
157
                'I',
158
                'factura_' .$datosFactura[0]['numero2']. '_' . \date('dmYhis') . '.pdf'
159
            );
160
        }
161
    }
162
163
    public function crear_documento_cobros()
164
    {
165
        $this->pendiente = $this->pagosFactura(false);
166
        $this->pagado = $this->pagosFactura(true);
167
168
        $linea_actual = 0;
169
        $pagina = 1;
170
        $lppag = 32; /// líneas por página
171
        while ($linea_actual < count($this->pendiente)) {
172
            /// salto de página
173
            if ($linea_actual > 0) {
174
                $this->documento->pdf->ezNewPage();
175
            }
176
            $this->documento->generar_pdf_cabecera($this->empresa, $lppag);
177
            $this->documento->generar_datos_residente($this->documento, 'informe_cobros', $lppag);
178
            $this->documento->generar_pdf_lineas(
179
                $this->documento,
180
                $this->pendiente,
181
                $linea_actual,
182
                $lppag,
183
                'pendiente'
184
            );
185
            $this->documento->set_y($this->documento->pdf->y - 16);
186
        }
187
188
        $linea_actual2 = 0;
189
        while ($linea_actual2 < count($this->pagado)) {
190
            if ($linea_actual2 > 0) {
191
                $this->documento->pdf->ezNewPage();
192
            } elseif ($linea_actual === 0) {
193
                $this->documento->generar_pdf_cabecera($this->empresa, $lppag);
194
                $this->documento->generar_datos_residente($this->documento, 'informe_cobros', $lppag);
195
            }
196
            $this->documento->generar_pdf_lineas(
197
                $this->documento,
198
                $this->pagado,
199
                $linea_actual2,
200
                $lppag,
201
                'pagado'
202
            );
203
            $pagina++;
204
        }
205
        $this->documento->set_y(80);
206
        if ($this->empresa->pie_factura) {
207
            $this->documento->pdf->addText(20, 40, 8, fs_fix_html('<b>Generado por:</b> ' .
208
                $this->user->get_agente_fullname()), 0);
209
            $this->documento->pdf->addText(
210
                10,
211
                30,
212
                8,
213
                $this->documento->center_text(fs_fix_html($this->empresa->pie_factura), 180)
214
            );
215
        }
216
217
        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...
218
            $this->documento->save('tmp/' . FS_TMP_NAME . 'enviar/' . $this->archivo);
219
        } else {
220
            $this->documento->show('documento_cobros_' . \date('dmYhis') . '.pdf');
221
        }
222
    }
223
224
    public function enviar_documento($tipo_documento)
225
    {
226
        $this->crear_documento($tipo_documento);
227
        $tipo_doc = $this->generar_tipo_doc($tipo_documento);
228
        if (file_exists('tmp/' . FS_TMP_NAME . 'enviar/' . $this->archivo)) {
229
            $mail = $this->empresa->new_mail();
230
            $mail->FromName = $this->user->get_agente_fullname();
231
232
            if ($_POST['de'] !== $mail->From) {
233
                $mail->addReplyTo($_POST['de'], $mail->FromName);
234
            }
235
236
            $mail->addAddress($_POST['email'], $this->cliente_residente->nombre);
237
            if ($_POST['email_copia']) {
238
                if (isset($_POST['cco'])) {
239
                    $mail->addBCC($_POST['email_copia'], $this->cliente_residente->nombre);
240
                } else {
241
                    $mail->addCC($_POST['email_copia'], $this->cliente_residente->nombre);
242
                }
243
            }
244
245
            $mail->Subject = $this->empresa->nombre . ': ' . $tipo_doc;
246
247
            if ($this->is_html($_POST['mensaje'])) {
248
                $mail->AltBody = strip_tags($_POST['mensaje']);
249
                $mail->msgHTML($_POST['mensaje']);
250
                $mail->isHTML(true);
251
            } else {
252
                $mail->Body = $_POST['mensaje'];
253
            }
254
255
            $mail->addAttachment('tmp/' . FS_TMP_NAME . 'enviar/' . $this->archivo);
256
            if (is_uploaded_file($_FILES['adjunto']['tmp_name'])) {
257
                $mail->addAttachment($_FILES['adjunto']['tmp_name'], $_FILES['adjunto']['name']);
258
            }
259
260
            if ($this->empresa->mail_connect($mail) && $mail->send()) {
261
                $this->new_message('Mensaje enviado correctamente.');
262
                $this->empresa->save_mail($mail);
263
            } else {
264
                $this->new_error_msg("Error al enviar el email: " . $mail->ErrorInfo);
265
            }
266
267
            unlink('tmp/' . FS_TMP_NAME . 'enviar/' . $this->archivo);
268
        } else {
269
            $this->new_error_msg('Imposible generar el PDF.');
270
        }
271
    }
272
273
//    public function pdfGenerarCabecera(&$pdf_doc, &$empresa, &$lppag)
274
//    {
275
//        /// ¿Añadimos el logo?
276
//        if ($pdf_doc->logo !== false) {
277
//            if (function_exists('imagecreatefromstring')) {
278
//                $lppag -= 4; /// si metemos el logo, caben menos líneas
279
//                $pdf_doc_LOGO_X = 20;
280
//                $pdf_doc_LOGO_Y = 320;
281
//                $tamanyo = $pdf_doc->calcular_tamanyo_logo();
282
//                if (strtolower(substr($pdf_doc->logo, -4)) === '.png') {
283
//                    $pdf_doc->pdf->addPngFromFile($pdf_doc->logo, $pdf_doc_LOGO_X, $pdf_doc_LOGO_Y, $tamanyo[0], $tamanyo[1]);
284
//                } elseif (function_exists('imagepng')) {
285
//                    /**
286
//                     * La librería ezpdf tiene problemas al redimensionar jpegs,
287
//                     * así que hacemos la conversión a png para evitar estos problemas.
288
//                     */
289
//                    if (imagepng(imagecreatefromstring(file_get_contents($pdf_doc->logo)), FS_MYDOCS
290
//                        . 'images/logo.png')) {
291
//                        $pdf_doc->pdf->addPngFromFile(
292
//                            FS_MYDOCS . 'images/logo.png',
293
//                            $pdf_doc_LOGO_X,
294
//                            $pdf_doc_LOGO_Y,
295
//                            $tamanyo[0],
296
//                            $tamanyo[1]
297
//                        );
298
//                    } else {
299
//                        $pdf_doc->pdf->addJpegFromFile($pdf_doc->logo, $pdf_doc_LOGO_X, $pdf_doc_LOGO_Y, $tamanyo[0], $tamanyo[1]);
300
//                    }
301
//                } else {
302
//                    $pdf_doc->pdf->addJpegFromFile($pdf_doc->logo, $pdf_doc_LOGO_X, $pdf_doc_LOGO_Y, $tamanyo[0], $tamanyo[1]);
303
//                }
304
//                $pdf_doc->set_y(400);
305
//                $pdf_doc->pdf->ez['leftMargin'] = 120;
306
//                $pdf_doc->pdf->ezText(
307
//                    "<b>" . fs_fix_html($empresa->nombre) . "</b>",
308
//                    12,
309
//                    array('justification' => 'left')
310
//                );
311
//                $pdf_doc->pdf->ezText(FS_CIFNIF . ": " . $empresa->cifnif, 8, array('justification' => 'left'));
312
//
313
//                $direccion = $empresa->direccion . "\n";
314
//                if ($empresa->apartado) {
315
//                    $direccion .= ucfirst(FS_APARTADO) . ': ' . $empresa->apartado . ' - ';
316
//                }
317
//
318
//                if ($empresa->codpostal) {
319
//                    $direccion .= 'CP: ' . $empresa->codpostal . ' - ';
320
//                }
321
//
322
//                if ($empresa->ciudad) {
323
//                    $direccion .= $empresa->ciudad . ' - ';
324
//                }
325
//
326
//                if ($empresa->provincia) {
327
//                    $direccion .= '(' . $empresa->provincia . ')';
328
//                }
329
//
330
//                if ($empresa->telefono) {
331
//                    $direccion .= "\nTeléfono: " . $empresa->telefono . ' - '.$pdf_doc_LOGO_X."/".$pdf_doc_LOGO_Y;
332
//                }
333
//
334
//                $pdf_doc->pdf->ezText(fs_fix_html($direccion) . "\n", 8, array('justification' => 'left'));
335
//                $pdf_doc->set_y($pdf_doc_LOGO_Y);
336
//
337
//                $pdf_doc->pdf->ez['leftMargin'] = 10;
338
//            } else {
339
//                die('ERROR: no se encuentra la función imagecreatefromstring(). '
340
//                    . 'Y por tanto no se puede usar el logotipo en los documentos.');
341
//            }
342
//        } else {
343
//            $pdf_doc->pdf->ezText(
344
//                "<b>" . fs_fix_html($empresa->nombre) . "</b>",
345
//                12,
346
//                array('justification' => 'left')
347
//            );
348
//            $pdf_doc->pdf->ezText(FS_CIFNIF . ": " . $empresa->cifnif, 8, array('justification' => 'left'));
349
//
350
//            $direccion = $empresa->direccion;
351
//            if ($empresa->apartado) {
352
//                $direccion .= ' - ' . ucfirst(FS_APARTADO) . ': ' . $empresa->apartado;
353
//            }
354
//
355
//            if ($empresa->codpostal) {
356
//                $direccion .= ' - CP: ' . $empresa->codpostal;
357
//            }
358
//
359
//            if ($empresa->ciudad) {
360
//                $direccion .= ' - ' . $empresa->ciudad;
361
//            }
362
//
363
//            if ($empresa->provincia) {
364
//                $direccion .= ' (' . $empresa->provincia . ')';
365
//            }
366
//
367
//            if ($empresa->telefono) {
368
//                $direccion .= ' - Teléfono: ' . $empresa->telefono;
369
//            }
370
//
371
//            $pdf_doc->pdf->ezText(fs_fix_html($direccion), 8, array('justification' => 'left'));
372
//        }
373
//    }
374
//
375
//    public function pdfFacturaResumen(&$pdf_doc, &$empresa, &$lppag)
376
//    {
377
//        $pdf_doc->set_y(420);
378
//        $pdf_doc->pdf->ez['leftMargin'] = 440;
379
//        $pdf_doc->pdf->ez['rightMargin'] = 10;
380
//
381
//        $facturas = new factura_cliente();
382
//        $clientes = new cliente();
383
//        $cliente = $clientes->get($this->filter_request('codcliente'));
384
//        $factura = $facturas->get($this->filter_request('idfactura'));
385
//        $tipo_factura = '';
386
//        if (isset($factura->ncf_tipo)) {
387
//            $tipo_factura = $factura->ncf_tipo;
388
//        }
389
//
390
//        $pdf_doc->new_table();
391
//        $pdf_doc->add_table_row(
392
//            array(
393
//                'campos' => "<b>" . ucfirst(FS_FACTURA) . ":</b>\n <b>".FS_NUMERO2.":</b>\n<b>Fecha:</b>\n<b>" . 'F. Pago' . ":</b>",
394
//                'factura' => $factura->codigo . "\n" . $factura->numero2 . "\n" . $factura->fecha . "\n" . $factura->codpago,
395
//            )
396
//        );
397
//        $pdf_doc->save_table(
398
//            array(
399
//                'cols' => array(
400
//                    'campos' => array('justification' => 'right', 'width' => 120),
401
//                    'factura' => array('justification' => 'left')
402
//                ),
403
//                'showLines' => 0,
404
//                'fontSize' => 9,
405
//                'width' => 320
406
//            )
407
//        );
408
//
409
//        $pdf_doc->set_y(240);
410
//        $pdf_doc->pdf->ez['leftMargin'] = 10;
411
//    }
412
//
413
//    public function pdfFacturaDetalle(&$pdf_doc, &$empresa, &$lppag,  &$linea_actual)
414
//    {
415
//        $facturas = new factura_cliente();
416
//        $clientes = new cliente();
417
//        $cliente = $clientes->get($this->filter_request('codcliente'));
418
//        $factura = $facturas->get($this->filter_request('idfactura'));
419
//        $lineas = $factura->get_lineas();
420
//
421
//        $pdf_doc->new_table();
422
//        $table_header = array(
423
//            'descripcion' => '<b>Ref. + Descripción</b>',
424
//            'cantidad' => '<b>Cant.</b>',
425
//            'pvp' => '<b>Precio</b>',
426
//            'dto' => '<b>Dto.</b>',
427
//            'importe' => '<b>Importe</b>'
428
//        );
429
//
430
//        $pdf_doc->add_table_header($table_header);
431
//
432
//        for ($i = $linea_actual; (($linea_actual < ($lppag + $i)) && ( $linea_actual < count($lineas)));) {
433
//            $descripcion = fs_fix_html($lineas[$linea_actual]->descripcion);
434
//            if (!is_null($lineas[$linea_actual]->referencia) && $this->impresion['print_ref']) {
435
//                $descripcion = '<b>' . $lineas[$linea_actual]->referencia . '</b> ' . $descripcion;
436
//            }
437
//
438
//            /// ¿El articulo tiene trazabilidad?
439
//            //$descripcion .= $this->generar_trazabilidad($lineas[$linea_actual]);
440
//
441
//            $due_lineas = $this->fbase_calc_desc_due([$lineas[$linea_actual]->dtopor, $lineas[$linea_actual]->dtopor2, $lineas[$linea_actual]->dtopor3, $lineas[$linea_actual]->dtopor4]);
442
//
443
//            $fila = array(
444
//                'descripcion' => $descripcion,
445
//                'cantidad' => $this->show_numero($lineas[$linea_actual]->cantidad, 0),
446
//                'pvp' => $this->show_precio($lineas[$linea_actual]->pvpunitario, $factura->coddivisa, true, FS_NF0_ART),
447
//                'dto' => $this->show_numero($due_lineas) . " %",
448
//                'importe' => $this->show_precio($lineas[$linea_actual]->pvptotal, $this->documento->coddivisa)
449
//            );
450
//
451
//            if ($lineas[$linea_actual]->dtopor == 0) {
452
//                $fila['dto'] = '';
453
//            }
454
//
455
//            if (!$lineas[$linea_actual]->mostrar_cantidad) {
456
//                $fila['cantidad'] = '';
457
//            }
458
//
459
//            if (!$lineas[$linea_actual]->mostrar_precio) {
460
//                $fila['pvp'] = '';
461
//                $fila['dto'] = '';
462
//                $fila['importe'] = '';
463
//            }
464
//
465
//            $pdf_doc->add_table_row($fila);
466
//            $linea_actual++;
467
//        }
468
//
469
//        $pdf_doc->save_table(
470
//            array(
471
//                'fontSize' => 8,
472
//                'cols' => array(
473
//                    'cantidad' => array('justification' => 'right'),
474
//                    'pvp' => array('justification' => 'right'),
475
//                    'dto' => array('justification' => 'right'),
476
//                    'iva' => array('justification' => 'right'),
477
//                    'importe' => array('justification' => 'right')
478
//                ),
479
//                'width' => 540,
480
//                'shaded' => 1,
481
//                'shadeCol' => array(0.95, 0.95, 0.95),
482
//                'lineCol' => array(0.3, 0.3, 0.3),
483
//            )
484
//        );
485
//
486
//        /// ¿Última página?
487
//        if ($linea_actual == count($lineas) && $this->documento->observaciones != '') {
488
//            $pdf_doc->pdf->ezText("\n" . fs_fix_html($this->documento->observaciones), 9);
489
//        }
490
//    }
491
492
493
494
    public function imprimir_documento($tipo_documento)
495
    {
496
        $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...
497
        $this->crear_documento($tipo_documento);
498
    }
499
500
    public function init()
501
    {
502
        $this->existe_tesoreria();
503
        $this->cliente_residente = false;
504
        if (!file_exists('tmp/' . FS_TMP_NAME . 'enviar') &&
505
            !mkdir($concurrentDirectory = 'tmp/' . FS_TMP_NAME . 'enviar') &&
506
            !is_dir($concurrentDirectory)) {
507
            throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
508
        }
509
    }
510
511
    public function is_html($txt)
512
    {
513
        return $txt !== strip_tags($txt);
514
    }
515
}
516