informe_residentes::shared_extensions()   B
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 71
Code Lines 60

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 3
eloc 60
nc 3
nop 0
dl 0
loc 71
rs 8.8727
c 1
b 1
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * Copyright (C) 2017 Joe Nilson <joenilson at gmail.com>
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public License
17
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19
/**
20
 * @author Carlos García Gómez      [email protected]
21
 * @author Joe Nilson Zegarra Galvez      [email protected]
22
 * @copyright 2015, Carlos García Gómez. All Rights Reserved.
23
 */
24
require_once 'plugins/facturacion_base/extras/xlsxwriter.class.php';
25
require_once 'plugins/residentes/extras/residentes_controller.php';
26
/**
27
 * Description of informe_residentes
28
 *
29
 * @author carlos <[email protected]>
30
 * @author Joe Nilson <joenilson at gmail.com>
31
 */
32
class informe_residentes extends residentes_controller
33
{
34
    /**
35
     * @var string
36
     */
37
    public $bloque;
38
    /**
39
     * @var string
40
     */
41
    public $cliente;
42
    /**
43
     * @var string
44
     */
45
    public $clientes;
46
    public $desde;
47
    public $hasta;
48
    public $resultado;
49
    public $resultados;
50
    public $tipo;
51
    public $residentes;
52
    public $edificaciones;
53
    public $total;
54
    public $total_resultado;
55
    public $lista;
56
    public $vehiculos;
57
    public $mapa;
58
    public $padre;
59
    public $codigo_edificacion;
60
    public $edificaciones_tipo;
61
    public $edificaciones_mapa;
62
    public $inmuebles_libres;
63
    public $inmuebles_ocupados;
64
    public $total_vehiculos;
65
    public $limit;
66
    public $offset;
67
    public $order;
68
    public $search;
69
    public $sort;
70
    public $archivo = 'Residentes';
71
    public $archivoXLSX;
72
    public $fileXLSX;
73
    public $archivoXLSXPath;
74
    public $documentosDir;
75
    public $exportDir;
76
    public $publicPath;
77
    public $where_code;
78
    public $pagos_pendientes;
79
    public $pagos_realizados;
80
81
    public function __construct()
82
    {
83
        parent::__construct(__CLASS__, 'Residentes', 'informes', false, true);
84
    }
85
86
    protected function private_core()
87
    {
88
        $this->shared_extensions();
89
        $this->init_variables();
90
        $this->init_filters();
91
92
        $tipos = $this->edificaciones_tipo->all();
93
        $this->padre = $tipos[0];
94
95
        $this->tipo = 'informacion';
96
        if (isset($_GET['tipo'])) {
97
            $this->tipo = $_GET['tipo'];
98
        }
99
100
        if ($this->tipo === 'mostrar_informacion_residente') {
101
            $this->mostrar_informacion_residente();
102
        }
103
104
        $this->codigo_edificacion = null;
105
        if ($this->filter_request('codigo_edificacion')) {
106
            $this->codigo_edificacion = $this->filter_request('codigo_edificacion');
107
        }
108
109
        if ($this->codigo_edificacion) {
110
            $this->where_code = " AND r.codigo like '" . $this->codigo_edificacion . "%' ";
0 ignored issues
show
Bug introduced by
Are you sure $this->codigo_edificacion of type string|true can be used in concatenation? ( Ignorable by Annotation )

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

110
            $this->where_code = " AND r.codigo like '" . /** @scrutinizer ignore-type */ $this->codigo_edificacion . "%' ";
Loading history...
111
        }
112
113
        if ($this->tipo === 'informacion') {
114
            $this->mapa = $this->edificaciones_mapa->get_by_field('id_tipo', $this->padre->id);
115
            $this->informacion_edificaciones();
116
        }
117
118
        if ($this->filter_request('lista')) {
119
            $this->procesarLista($this->filter_request('lista'));
120
        }
121
    }
122
123
    public function init_variables()
124
    {
125
        $this->edificaciones_tipo = new residentes_edificaciones_tipo();
126
        $this->edificaciones_mapa = new residentes_edificaciones_mapa();
127
        $this->edificaciones = new residentes_edificaciones();
128
        $this->vehiculos = new residentes_vehiculos();
129
        $this->clientes = new cliente();
130
    }
131
132
    public function init_filters()
133
    {
134
        $this->desde = \Date('01-m-Y');
135
        if ($this->filter_request('desde')) {
136
            $this->desde = $this->filter_request('desde');
137
        }
138
139
        $this->hasta = \Date('t-m-Y');
140
        if ($this->filter_request('hasta')) {
141
            $this->hasta = $this->filter_request('hasta');
142
        }
143
144
        $sort = $this->filter_request('sort');
145
        $order = $this->filter_request('order');
146
        $this->offset = $this->confirmarValor($this->filter_request('offset'), 0);
147
        $this->limit = $this->confirmarValor($this->filter_request('limit'), FS_ITEM_LIMIT);
148
        $this->search = $this->confirmarValor($this->filter_request('search'), false);
149
        $this->sort = ($sort and $sort!='undefined')?$sort:'r.codigo, r.numero';
150
        $this->order = ($order and $order!='undefined')?$order:'ASC';
151
    }
152
153
    public function informacion_edificaciones()
154
    {
155
        $this->resultado = array();
156
        [$edificaciones, $inmuebles, $vehiculos, $inmuebles_ocupados] = $this->datosInformacion();
157
        foreach ($edificaciones as $edif) {
158
            $l = new stdClass();
159
            $l->descripcion = $edif['descripcion'];
160
            $l->cantidad = $edif['total'];
161
            $this->resultado[] = $l;
162
        }
163
        if ($inmuebles) {
164
            $l = new stdClass();
165
            $l->descripcion = 'Inmueble';
166
            $l->cantidad = $inmuebles;
167
            $this->resultado[] = $l;
168
        }
169
        //Verificamos los que están ocupados
170
        $this->inmuebles_libres = $inmuebles-$inmuebles_ocupados;
171
        $this->inmuebles_ocupados = $inmuebles_ocupados;
172
        $this->total_vehiculos = $vehiculos;
173
        $this->carpetasPlugin();
174
        $this->generarArchivoExcel();
175
    }
176
177
    public function generarArchivoExcel()
178
    {
179
        $this->archivoXLSX = $this->exportDir . DIRECTORY_SEPARATOR .
180
                            $this->archivo . "_" . $this->user->nick . ".xlsx";
181
        $this->archivoXLSXPath = $this->publicPath . DIRECTORY_SEPARATOR .
182
                            $this->archivo . "_" . $this->user->nick . ".xlsx";
183
        if (file_exists($this->archivoXLSX)) {
184
            unlink($this->archivoXLSX);
185
        }
186
        $writer = new XLSXWriter();
187
        $headerR = array(
188
            'Código'=>'string',
189
            'Residente'=>'string',
190
            FS_CIFNIF=>'string',
191
            'Teléfono'=>'string',
192
            'Email'=>'string',
193
            'Ubicación'=>'string',
194
            'Inmueble'=>'string',
195
            'Fecha de Ocupación'=>'date');
196
        $headerTextR = array(
197
            'codcliente'=>'Código',
198
            'nombre'=>'Residente',
199
            'cifnif'=>FS_CIFNIF,
200
            'telefono1'=>'Teléfono',
201
            'email'=>'Email',
202
            'codigo'=>'Ubicación',
203
            'numero'=>'Inmueble',
204
            'fecha_ocupacion'=>'Fecha Ocupación');
205
        $dataResidentes = $this->edificaciones->listaResidentes(true);
206
        $this->crearXLSX($writer, 'Residentes', $headerR, $headerTextR, $dataResidentes[0]);
207
        $headerI = array(
208
            'Pertenece'=>'string',
209
            'Edificación'=>'string',
210
            'Código'=>'string',
211
            'Residente'=>'string',
212
            FS_CIFNIF=>'string',
213
            'Teléfono'=>'string',
214
            'Email'=>'string',
215
            'Ubicación'=>'string',
216
            'Inmueble Nro'=>'integer',
217
            'Fecha de Ocupación'=>'date',
218
            'Ocupado'=>'string');
219
        $headerTextI = array(
220
            'padre_desc'=>'Pertenece',
221
            'edif_desc'=>'Edificacion',
222
            'codcliente'=>'Código',
223
            'nombre'=>'Residente',
224
            'cifnif'=>FS_CIFNIF,
225
            'telefono1'=>'Teléfono',
226
            'email'=>'Email',
227
            'codigo'=>'Ubicación',
228
            'numero'=>'Inmueble Nro',
229
            'fecha_ocupacion'=>'Fecha Ocupación',
230
            'ocupado'=>'Ocupado');
231
        $dataInmuebles = $this->edificaciones->listaInmuebles(true);
232
        $this->crearXLSX($writer, 'Inmuebles', $headerI, $headerTextI, $dataInmuebles[0]);
233
        $headerC = array(
234
            'Código'=>'string',
235
            'Residente'=>'string',
236
            FS_CIFNIF=>'string',
237
            'Teléfono'=>'string',
238
            'Email'=>'string',
239
            'Ubicación'=>'string',
240
            'Inmueble'=>'string',
241
            'Pagado'=>'price',
242
            'Pendiente'=>'price');
243
        $headerTextC = array(
244
            'codcliente'=>'Código',
245
            'nombre'=>'Residente',
246
            'cifnif'=>FS_CIFNIF,
247
            'telefono1'=>'Teléfono',
248
            'email'=>'Email',
249
            'codigo'=>'Ubicación',
250
            'numero'=>'Inmueble',
251
            'pagado'=>'Pagado',
252
            'pendiente'=>'Pendiente');
253
        $dataCobros = $this->edificaciones->listaCobros(true);
254
        $this->crearXLSX($writer, 'Cobros', $headerC, $headerTextC, $dataCobros[0]);
255
        $writer->writeToFile($this->archivoXLSXPath);
256
        $this->fileXLSX = $this->archivoXLSXPath;
257
    }
258
259
    public function datosInformacion()
260
    {
261
        $ret = new residentes_edificaciones_tipo();
262
        return $ret->datosInformacion();
263
    }
264
265
    /**
266
     * @throws JsonException
267
     */
268
    public function procesarLista($lista)
269
    {
270
        $this->template = false;
271
        $resultados = [];
272
        $cantidad = 0;
273
        switch ($lista) {
274
            case 'informe_residentes':
275
                [$resultados, $cantidad] = $this->edificaciones->listaResidentes(
276
                    false,
277
                    $this->where_code,
278
                    $this->sort,
279
                    $this->order,
280
                    $this->limit,
281
                    $this->offset
282
                );
283
                break;
284
            case 'informe_inmuebles':
285
                [$resultados, $cantidad] = $this->edificaciones->listaInmuebles(
286
                    false,
287
                    $this->where_code,
288
                    $this->sort,
289
                    $this->order,
290
                    $this->limit,
291
                    $this->offset
292
                );
293
                break;
294
            case 'informe_cobros':
295
                [$resultados, $cantidad] = $this->edificaciones->listaCobros(
296
                    false,
297
                    $this->where_code,
298
                    $this->sort,
299
                    $this->order,
300
                    $this->limit,
301
                    $this->offset
302
                );
303
                break;
304
            default:
305
                break;
306
        }
307
        header('Content-Type: application/json');
308
        $data = [];
309
        $data['rows'] = $resultados;
310
        $data['total'] = $cantidad;
311
        echo json_encode($data, JSON_THROW_ON_ERROR);
312
    }
313
314
    /**
315
     * Función para devolver un valor u otro dependiendo si está presente
316
     * el primer valor y si la variable existe
317
     * @param string $variable
318
     * @param string $valor_si
319
     * @param string $valor_no
320
     * @return string
321
     */
322
    public function setValor($variable, $valor_si, $valor_no)
323
    {
324
        $valor = $valor_no;
325
        if (!empty($variable) && ($variable === $valor_si)) {
326
            $valor = $valor_si;
327
        }
328
        return $valor;
329
    }
330
331
    /**
332
     * Función para devolver el valor que no esté vacio
333
     * @param string $valor1
334
     * @param string|boolean $valor2
335
     * @return string|boolean
336
     */
337
    public function confirmarValor($valor1, $valor2)
338
    {
339
        $valor = $valor2;
340
        if (!empty($valor1)) {
341
            $valor = $valor1;
342
        }
343
        return $valor;
344
    }
345
346
    /**
347
     * Función para devolver el valor de una variable pasada ya sea por POST o GET
348
     * @param string $nombre
349
     * @return string|boolean
350
     */
351
    public function filter_request($nombre)
352
    {
353
        $nombre_post = \filter_input(INPUT_POST, $nombre);
354
        $nombre_get = \filter_input(INPUT_GET, $nombre);
355
        return ($nombre_post) ?: $nombre_get;
356
    }
357
358
    public function filter_request_array($nombre)
359
    {
360
        $nombre_post = \filter_input(INPUT_POST, $nombre, FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
361
        $nombre_get = \filter_input(INPUT_GET, $nombre, FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
362
        return ($nombre_post) ?: $nombre_get;
363
    }
364
365
    public function crearXLSX(&$writer, $hoja_nombre, $header, $headerText, $data)
366
    {
367
        $style_header = array('border'=>'left,right,top,bottom','font'=>'Arial','font-size'=>10,'font-style'=>'bold');
368
        $writer->writeSheetRow($hoja_nombre, $headerText, $style_header);
369
        $writer->writeSheetHeader($hoja_nombre, $header, true);
370
        $this->agregarDatosXLSX($writer, $hoja_nombre, $data, $headerText);
371
    }
372
373
    public function agregarDatosXLSX(&$writer, $hoja_nombre, $datos, $indice)
374
    {
375
        $total_importe = 0;
376
        if ($datos) {
377
            foreach ($datos as $linea) {
378
                $data = $this->prepararDatosXLSX($linea, $indice, $total_importe);
379
                $writer->writeSheetRow($hoja_nombre, $data);
380
            }
381
        }
382
    }
383
384
    public function prepararDatosXLSX($linea, $indice, &$total_importe)
385
    {
386
        $item = array();
387
        foreach ($indice as $idx => $desc) {
388
            $item[] = $linea[$idx];
389
            if ($idx === 'total') {
390
                $total_importe += $linea['total'];
391
            }
392
        }
393
        return $item;
394
    }
395
396
    public function carpetasPlugin()
397
    {
398
        $basepath = dirname(__DIR__, 3);
399
        $this->documentosDir = $basepath . DIRECTORY_SEPARATOR . FS_MYDOCS . 'documentos';
400
        $this->exportDir = $this->documentosDir . DIRECTORY_SEPARATOR . "informes_residentes";
401
        $this->publicPath = FS_PATH . FS_MYDOCS . 'documentos' . DIRECTORY_SEPARATOR . 'informes_residentes';
0 ignored issues
show
Bug introduced by
The constant FS_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
402
        if (!is_dir($this->documentosDir)) {
403
            if (!mkdir($concurrentDirectory = $this->documentosDir) && !is_dir($concurrentDirectory)) {
404
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
405
            }
406
        }
407
408
        if (!is_dir($this->exportDir)) {
409
            if (!mkdir($concurrentDirectory = $this->exportDir) && !is_dir($concurrentDirectory)) {
410
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
411
            }
412
        }
413
    }
414
415
    public function url()
416
    {
417
        if (isset($_REQUEST['inmueble'])) {
418
            return 'index.php?page=informe_residentes&inmueble=' . $_REQUEST['inmueble'];
419
        }
420
421
        return parent::url();
422
    }
423
424
    private function str2bool($v)
0 ignored issues
show
Unused Code introduced by
The method str2bool() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
425
    {
426
        return ($v === 't' or $v === '1');
427
    }
428
429
    public function shared_extensions()
430
    {
431
        $extensiones = array(
432
            array(
433
                'name' => '001_informe_edificaciones_js',
434
                'page_from' => __CLASS__,
435
                'page_to' => __CLASS__,
436
                'type' => 'head',
437
                'text' => '<script src="' . FS_PATH .
0 ignored issues
show
Bug introduced by
The constant FS_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
438
                                'plugins/residentes/view/js/1/bootstrap-table.min.js" type="text/javascript"></script>',
439
                'params' => ''
440
            ),
441
            array(
442
                'name' => '002_informe_edificaciones_js',
443
                'page_from' => __CLASS__,
444
                'page_to' => __CLASS__,
445
                'type' => 'head',
446
                'text' => '<script src="' . FS_PATH .
447
                    'plugins/residentes/view/js/1/bootstrap-table-locale-all.min.js" type="text/javascript"></script>',
448
                'params' => ''
449
            ),
450
            array(
451
                'name' => '003_informe_edificaciones_js',
452
                'page_from' => __CLASS__,
453
                'page_to' => __CLASS__,
454
                'type' => 'head',
455
                'text' => '<script src="' . FS_PATH .
456
                'plugins/residentes/view/js/plugins/bootstrap-table-filter.min.js" type="text/javascript"></script>',
457
                'params' => ''
458
            ),
459
            array(
460
                'name' => '004_informe_edificaciones_js',
461
                'page_from' => __CLASS__,
462
                'page_to' => __CLASS__,
463
                'type' => 'head',
464
                'text' => '<script src="' . FS_PATH .
465
                'plugins/residentes/view/js/plugins/bootstrap-table-toolbar.min.js" type="text/javascript"></script>',
466
                'params' => ''
467
            ),
468
            array(
469
                'name' => '005_informe_edificaciones_js',
470
                'page_from' => __CLASS__,
471
                'page_to' => __CLASS__,
472
                'type' => 'head',
473
                'text' => '<script src="' . FS_PATH .
474
                'plugins/residentes/view/js/plugins/bootstrap-table-mobile.min.js" type="text/javascript"></script>',
475
                'params' => ''
476
            ),
477
            array(
478
                'name' => '009_informe_edificaciones_js',
479
                'page_from' => __CLASS__,
480
                'page_to' => __CLASS__,
481
                'type' => 'head',
482
                'text' => '<script src="' . FS_PATH . 'view/js/chart.bundle.min.js" type="text/javascript"></script>',
483
                'params' => ''
484
            ),
485
            array(
486
                'name' => '001_informe_edificaciones_css',
487
                'page_from' => __CLASS__,
488
                'page_to' => __CLASS__,
489
                'type' => 'head',
490
                'text' => '<link rel="stylesheet" type="text/css" media="screen" href="' . FS_PATH .
491
                    'plugins/residentes/view/css/bootstrap-table.min.css"/>',
492
                'params' => ''
493
            ),
494
        );
495
496
        foreach ($extensiones as $ext) {
497
            $fsext0 = new fs_extension($ext);
498
            if (!$fsext0->save()) {
499
                $this->new_error_msg('Imposible guardar los datos de la extensión ' . $ext['name'] . '.');
500
            }
501
        }
502
    }
503
}
504