lista_residentes::buscar()   A
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 16
c 0
b 0
f 0
nc 8
nop 0
dl 0
loc 24
rs 9.7333
1
<?php
2
/*
3
 * Copyright (C) 2017 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
/**
19
 * @author Carlos García Gómez      [email protected]
20
 * @author Joe Nilson Zegarra Galvez      [email protected]
21
 * @copyright 2015, Carlos García Gómez. All Rights Reserved.
22
 */
23
require_once 'plugins/residentes/extras/residentes_controller.php';
24
/**
25
 * Description of lista_residentes
26
 *
27
 * @author carlos <[email protected]>
28
 * @author Joe Nilson <joenilson at gmail.com>
29
 */
30
class lista_residentes extends residentes_controller
31
{
32
    public $bloque;
33
    public $cliente;
34
    public $deudores;
35
    public $residente;
36
    public $query;
37
    public $query_r;
38
    public $query_i;
39
    public $query_v;
40
    public $order;
41
    public $sort;
42
    public $offset;
43
    public $resultados;
44
    public $total_resultados;
45
    public $edificacion_tipo;
46
    public $edificacion_mapa;
47
    public $tipo_edificaciones;
48
    public $residente_informacion;
49
    public $residente_vehiculo;
50
    public $cli;
51
52
    public function __construct()
53
    {
54
        parent::__construct(__CLASS__, 'Residentes', 'residentes', false, true);
55
    }
56
57
    protected function private_core()
58
    {
59
        parent::private_core();
60
        $this->init_variables();
61
        $this->filters();
62
63
        if ($this->filter_request('buscar_cliente')) {
64
            $this->buscar_cliente();
65
        } elseif ($this->filter_request('buscar_cliente_avanzado')) {
66
            $this->buscar_cliente_avanzado();
67
        } elseif ($this->filter_request('buscar_inmueble')) {
68
            $this->buscar_inmueble();
69
        } elseif (filter_input(INPUT_GET, 'delete')) {
70
            $inq = $this->residente->get(filter_input(INPUT_GET, 'delete'));
71
            if ($inq) {
72
                $inq->ocupado = false;
73
                $inq->codcliente = '';
74
                $inq->fecha_disponibilidad = null;
75
                $inq->fecha_ocupacion = null;
76
                if ($inq->save()) {
77
                    $this->new_message('Inquilino removido correctamente.');
78
                } else {
79
                    $this->new_error_msg('Error al remover el inquilino.');
80
                }
81
            } else {
82
                $this->new_error_msg('Inquilino no encontrado.');
83
            }
84
        }
85
        
86
        $tipo = $this->filter_request('type');
87
        if ($tipo === 'select-iddireccion') {
88
            $this->mostrar_direcciones_residente(\filter_input(INPUT_GET, 'codcliente'));
89
        }
90
91
        $accion = $this->filter_request('accion');
92
        switch ($accion) {
93
            case "agregar_residente":
94
                $this->agregar_residente();
95
                break;
96
            case "mostrar_informacion_residente":
97
                $this->mostrar_informacion_residente();
98
                break;
99
            default:
100
                $this->buscar();
101
                break;
102
        }
103
    }
104
105
106
    public function init_variables()
107
    {
108
        $this->bloque = '';
109
        $this->offset = 0;
110
        $this->cliente = new cliente();
111
        $this->residente = new residentes_edificaciones();
112
        $this->residente_informacion = new residentes_informacion();
113
        $this->residente_vehiculo = new residentes_vehiculos();
114
        $this->edificacion_tipo = new residentes_edificaciones_tipo();
115
        $this->edificacion_mapa = new residentes_edificaciones_mapa();
116
        $this->tipo_edificaciones = $this->edificacion_tipo->all();
117
    }
118
119
    public function filters()
120
    {
121
        $this->query_r = '';
122
        if ($this->filter_request('query_r')) {
123
            $this->query_r = $this->filter_request('query_r');
124
        }
125
126
        $this->query_v = '';
127
        if ($this->filter_request('query_v')) {
128
            $this->query_v = $this->filter_request('query_v');
129
        }
130
131
        $this->query_i = '';
132
        if ($this->filter_request('query_i')) {
133
            $this->query_i = $this->filter_request('query_i');
134
        }
135
136
        $this->sort = 'ASC';
137
        if ($this->filter_request('sort')) {
138
            $this->sort = $this->filter_request('sort');
139
        }
140
141
        $this->order = 'r.codigo, r.numero ';
142
        if ($this->filter_request('orden')) {
143
            $this->order = $this->filter_request('orden');
144
        }
145
146
        $this->offset = ($this->filter_request('offset')) ?: 0;
147
148
        $this->deudores = $this->filter_request('deudores');
149
        if ($this->deudores) {
150
            $this->sort = 'DESC';
151
            $this->order = 'pendiente';
152
        }
153
        
154
        $this->disponibles = $this->filter_request('disponibles');
0 ignored issues
show
Bug Best Practice introduced by
The property disponibles does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
155
        if ($this->disponibles) {
156
            $this->sort = 'ASC';
157
            $this->order = 'codcliente';
158
        }
159
    }
160
161
    public function buscar()
162
    {
163
        $where = "";
164
        if ($this->query_r) {
165
            $param = mb_strtolower($this->cliente->no_html($this->query_r), 'UTF8');
166
            $where = " WHERE ".$this->buscar_residentes($param);
167
        }
168
169
        if ($this->query_v) {
170
            $param = mb_strtolower($this->cliente->no_html($this->query_v), 'UTF8');
171
            $where = " WHERE ".$this->buscar_vehiculos($param);
172
        }
173
174
        if ($this->query_i) {
175
            $param = mb_strtolower($this->cliente->no_html($this->query_i), 'UTF8');
176
            $where = " WHERE ".$this->buscar_inmuebles($param);
177
        }
178
179
        [$this->resultados, $this->total_resultados] = $this->residente->lista_residentes(
180
            $where,
181
            $this->order,
182
            $this->sort,
183
            FS_ITEM_LIMIT,
184
            $this->offset
185
        );
186
    }
187
188
    public function buscar_residentes($param)
189
    {
190
        if (is_numeric($param)) {
191
            $where = "(r.codcliente LIKE '%" . $param . "%'"
192
                    . " OR c.cifnif LIKE '%" . $param . "%'"
193
                    . " OR c.telefono1 LIKE '" . $param . "%'"
194
                    . " OR c.telefono2 LIKE '" . $param . "%'"
195
                    . " OR ca_telefono LIKE '" . $param . "%'"
196
                    . " OR c.observaciones LIKE '%" . $param . "%')";
197
        } else {
198
            $buscar = str_replace(' ', '%', $param);
199
            $where = "(lower(nombre) LIKE '%" . $buscar . "%'"
200
                    . " OR lower(razonsocial) LIKE '%" . $buscar . "%'"
201
                    . " OR lower(ca_apellidos) LIKE '%" . $buscar . "%'"
202
                    . " OR lower(ca_nombres) LIKE '%" . $buscar . "%'"
203
                    . " OR lower(cifnif) LIKE '%" . $buscar . "%'"
204
                    . " OR lower(observaciones) LIKE '%" . $buscar . "%'"
205
                    . " OR lower(ca_email) LIKE '%" . $buscar . "%'"
206
                    . " OR lower(email) LIKE '%" . $buscar . "%')";
207
        }
208
        return $where;
209
    }
210
211
    public function buscar_inmuebles($param)
212
    {
213
        if (is_numeric($param)) {
214
            $where = " r.codigo LIKE '%" . $param . "%'"
215
                    . " OR r.numero LIKE '%" . $param . "%'"
216
                    . " OR CONCAT(r.codigo, r.numero) LIKE '%" . $param . "%'";
217
        } else {
218
            $buscar = str_replace(' ', '%', $param);
219
            $where = " lower(r.codigo) LIKE '%" . $buscar . "%'"
220
                    . " OR lower(r.numero) LIKE '%" . $buscar . "%'"
221
                    . " OR CONCAT(lower(r.codigo), r.numero) LIKE '%" . $param . "%'";
222
        }
223
        return $where;
224
    }
225
226
    public function buscar_vehiculos($param)
227
    {
228
        if (is_numeric($param)) {
229
            $where = "(r.codcliente LIKE '%" . $param . "%'"
230
                    . " OR vehiculo_placa LIKE '%" . $param . "%'"
231
                    . " OR CAST(idvehiculo AS CHAR) LIKE '" . $param . "%'"
232
                    . " OR telefono2 LIKE '" . $param . "%'"
233
                    . " OR observaciones LIKE '%" . $param . "%')";
234
        } else {
235
            $buscar = str_replace(' ', '%', $param);
236
            $where = "(lower(vehiculo_marca) LIKE '%" . $buscar . "%'"
237
                    . " OR lower(vehiculo_modelo) LIKE '%" . $buscar . "%'"
238
                    . " OR lower(vehiculo_color) LIKE '%" . $buscar . "%'"
239
                    . " OR lower(vehiculo_placa) LIKE '%" . $buscar . "%'"
240
                    . " OR lower(vehiculo_tipo) LIKE '%" . $buscar . "%'"
241
                    . " OR lower(codigo_tarjeta) LIKE '%" . $buscar . "%')";
242
        }
243
        return $where;
244
    }
245
246
    public function agregar_residente()
247
    {
248
        $id_edificacion = \filter_input(INPUT_POST, 'id_edificacion');
249
        $codcliente = \filter_input(INPUT_POST, 'codcliente');
250
        $iddireccion = \filter_input(INPUT_POST, 'iddireccion');
251
        $fecha_ocupacion = \filter_input(INPUT_POST, 'fecha_ocupacion');
252
        $fecha_disponibilidad = \filter_input(INPUT_POST, 'fecha_disponibilidad');
253
        $accion = \filter_input(INPUT_POST, 'accion');
254
        $inmueble = $this->residente->get($id_edificacion);
255
        if ($inmueble && $accion === 'agregar_residente') {
256
            $nueva_direccion = $inmueble->codigo_externo().' Apartamento '.$inmueble->numero;
257
            $inmueble->ocupado = true;
258
            $inmueble->codcliente = $codcliente;
259
            $inmueble->iddireccion = $this->actualizar_direccion_residente($codcliente, $iddireccion, $nueva_direccion);
260
            $inmueble->fecha_ocupacion = ($fecha_ocupacion)?\date('Y-m-d', strtotime($fecha_ocupacion)):null;
261
            $inmueble->fecha_disponibilidad = ($fecha_disponibilidad)
262
                ?\date('Y-m-d', strtotime($fecha_disponibilidad))
263
                :null;
264
            if ($inmueble->save()) {
265
                $this->new_message('Residente agregado exitosamente.');
266
            } else {
267
                $this->new_error_msg('No se pudo agregar al residente confirme el nombre '.
268
                                    'del residente y las fechs de ocupación y disponibilidad');
269
            }
270
        } elseif ($inmueble && $accion === 'quitar_residente') {
271
            $inmueble->ocupado = false;
272
            $inmueble->codcliente = '';
273
            $inmueble->iddireccion = null;
274
            $inmueble->fecha_ocupacion = '';
275
            $inmueble->fecha_disponibilidad = '';
276
            if ($inmueble->save()) {
277
                $this->new_message('Residente removido exitosamente.');
278
            } else {
279
                $this->new_error_msg('No se pudo remover al residente');
280
            }
281
        }
282
    }
283
284
    private function buscar_cliente()
285
    {
286
        /// desactivamos la plantilla HTML
287
        $this->template = false;
288
289
        $json = array();
290
        foreach ($this->cliente->search($_REQUEST['buscar_cliente']) as $cli) {
291
            $json[] = array('value' => $cli->nombre, 'data' => $cli->codcliente);
292
        }
293
294
        header('Content-Type: application/json');
295
        echo json_encode(array('query' => $_REQUEST['buscar_cliente'], 'suggestions' => $json), JSON_THROW_ON_ERROR);
296
    }
297
298
    private function buscar_cliente_avanzado()
299
    {
300
        /// desactivamos la plantilla HTML
301
        $this->template = false;
302
        $json = array();
303
        //Buscamos en la lista de clientes
304
        foreach ($this->cliente->search($_REQUEST['buscar_cliente_avanzado']) as $cli) {
305
            $lista = $this->residente->get_by_field('codcliente', $cli->codcliente);
306
            if ($lista) {
307
                foreach ($lista as $residente) {
308
                    $json[$cli->codcliente] = array('value' => $cli->nombre,
309
                        'data' => $cli->codcliente,
310
                        'nombre' => $cli->nombre,
311
                        'asignado' => true);
312
                }
313
            } else {
314
                $json[$cli->codcliente] = array('value' => $cli->nombre,
315
                    'data' => $cli->codcliente,
316
                    'nombre' => $cli->nombre,
317
                    'asignado' => false);
318
            }
319
        }
320
        //Buscamos en los datos adicionales del residente
321
        foreach ($this->residente_informacion->search($_REQUEST['buscar_cliente_avanzado']) as $cli) {
322
            if (!empty($cli)) {
323
                $json[$cli->codcliente] = array('value' => $cli->nombre, 'data' => $cli->codcliente);
324
            }
325
        }
326
        //Buscamos en los datos de vehiculos del residente
327
        foreach ($this->residente_vehiculo->search($_REQUEST['buscar_cliente_avanzado']) as $cli) {
328
            if (!empty($cli)) {
329
                $json[$cli->codcliente] = array(
330
                    'value' => $cli->nombre.' '.$cli->vehiculo_placa." ".
331
                                $cli->vehiculo_marca.''.$cli->vehiculo_modelo, 'data' => $cli->codcliente);
332
            }
333
        }
334
        //Buscamos en las residencias
335
        foreach ($this->residente->search($_REQUEST['buscar_cliente_avanzado']) as $cli) {
336
            if (!empty($cli)) {
337
                $json[$cli->codcliente] = array('value' => $cli->nombre." ".$cli->codigo.' '.
338
                                            $cli->numero, 'data' => $cli->id, 'asignado' => true);
339
            }
340
        }
341
342
        header('Content-Type: application/json');
343
        echo json_encode(
344
            array('query' => $_REQUEST['buscar_cliente_avanzado'], 'suggestions' => $json),
345
            JSON_THROW_ON_ERROR
346
        );
347
    }
348
349
    private function buscar_inmueble()
350
    {
351
        /// desactivamos la plantilla HTML
352
        $this->template = false;
353
354
        $json = array();
355
        foreach ($this->residente->search($_REQUEST['buscar_inmueble'], 'inmueble') as $inmueble) {
356
            if (!$inmueble->ocupado) {
357
                $json[] = array('value' => $inmueble->codigo.$inmueble->numero, 'data' => $inmueble->id);
358
            }
359
        }
360
361
        header('Content-Type: application/json');
362
        echo json_encode(
363
            array('query' => $_REQUEST['buscar_inmueble'], 'suggestions' => $json),
364
            JSON_THROW_ON_ERROR
365
        );
366
    }
367
368
    public function paginas()
369
    {
370
        $url = $this->url() . "&query=" . $this->query
371
                . "&query_r=" . $this->query_r
372
                . "&query_v=" . $this->query_v
373
                . "&query_i=" . $this->query_i
374
                . "&orden=" . $this->order
375
                . "&deudores=" . $this->deudores
376
                . "&disponibles=" . $this->disponibles;
377
378
        $paginas = array();
379
        $i = 0;
380
        $num = 0;
381
        $actual = 1;
382
383
        /// añadimos todas la página
384
        while ($num < $this->total_resultados) {
385
            $paginas[$i] = array(
386
                'url' => $url . "&offset=" . ($i * FS_ITEM_LIMIT),
387
                'num' => $i + 1,
388
                'actual' => ($num === $this->offset)
389
            );
390
391
            if ($num === $this->offset) {
392
                $actual = $i;
393
            }
394
395
            $i++;
396
            $num += FS_ITEM_LIMIT;
397
        }
398
399
        /// ahora descartamos
400
        foreach ($paginas as $j => $value) {
401
            $enmedio = (int)($i / 2);
402
403
            /**
404
             * descartamos todo excepto la primera, la última, la de enmedio,
405
             * la actual, las 5 anteriores y las 5 siguientes
406
             */
407
            if (($j>1 && $j<$actual-5 && $j !== $enmedio) || ($j > $actual + 5 && $j < $i - 1 && $j !== $enmedio)) {
408
                unset($paginas[$j]);
409
            }
410
        }
411
412
        if (count($paginas) > 1) {
413
            return $paginas;
414
        } else {
415
            return array();
416
        }
417
    }
418
}
419