Passed
Push — master ( 8b860d...46546a )
by Joe Nilson
02:24
created

ver_residente::paginas()   B

Complexity

Conditions 11
Paths 18

Size

Total Lines 42
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 22
nc 18
nop 0
dl 0
loc 42
rs 7.3166
c 0
b 0
f 0

How to fix   Complexity   

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/residentes/extras/residentes_controller.php';
25
26
/**
27
 * Description of ver_residente
28
 *
29
 * @author carlos
30
 */
31
class ver_residente extends residentes_controller
32
{
33
    public $cliente;
34
    public $cliente_data;
35
    public $articulos;
36
    public $articulos_cobrables;
37
    public $familia;
38
    public $familias;
39
    public $facturas;
40
    public $impuesto;
41
    public $residente;
42
    public $forma_pago;
43
    public $lista_notas;
44
    public $total_facturas = 0;
45
    public $offset = 0;
46
47
    public function __construct()
48
    {
49
        parent::__construct(__CLASS__, 'Residente', 'residentes', false, false);
50
    }
51
    
52
    public function initVars()
53
    {
54
        $this->cliente = new cliente();
55
        $this->facturas = array();
56
        $this->impuesto = new impuesto();
57
        $this->forma_pago = new forma_pago();
0 ignored issues
show
Bug introduced by
The type forma_pago 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...
58
        $this->residente = false;
59
        $this->articulos = new articulo();
60
        $this->familias = new familia();
0 ignored issues
show
Bug introduced by
The type familia 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...
61
        $this->familia = $this->familias->get('RESIDENT');
62
    }
63
64
    protected function private_core()
65
    {
66
        $this->initVars();
67
68
        if (\filter_input(INPUT_GET, 'id')) {
69
            $res0 = new residentes_edificaciones();
70
            $this->residente = $res0->get(\filter_input(INPUT_GET, 'id'));
71
            $this->cliente_data = $this->cliente->get($this->residente->codcliente);
72
            $this->cliente_data->codcontacto = '';
73
            $this->total_facturas = $this->residente->totalFacturas();
74
            $this->offset = \filter_input(INPUT_GET, 'offset') ?? 0;
75
            if (class_exists('contacto_cliente')) {
76
                $concli = new contacto_cliente();
0 ignored issues
show
Bug introduced by
The type contacto_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...
77
                $infoCRM = $concli->all_from_cliente($this->residente->codcliente);
78
                $this->cliente_data->codcontacto = $infoCRM[0]->codcontacto;
79
            }
80
        }
81
        
82
        if ($this->residente) {
83
            $accion = \filter_input(INPUT_POST, 'accion');
84
            if ($accion == 'generar_factura') {
85
                $this->nueva_factura();
86
            }
87
            $this->informacionResidente();
88
        } else {
89
            $this->new_error_msg('Residente no encontrado.');
90
        }
91
    }
92
93
    public function url()
94
    {
95
        if (\filter_input(INPUT_GET, 'id')) {
96
            return $this->residente->url();
97
        }
98
        return parent::url();
99
    }
100
    
101
    public function informacionResidente()
102
    {
103
        $this->page->title = 'Residente ' . $this->residente->nombre;
104
        $factura = new factura_cliente();
105
        $totalFacturas = $this->residente->totalFacturas();
106
        $cantidadGrupos = ceil($totalFacturas/FS_ITEM_LIMIT);
107
        $facts = [];
108
        for($i = 0; $i < $cantidadGrupos; $i++ ) {
109
            $documentos = $factura->all_from_cliente($this->residente->codcliente, FS_ITEM_LIMIT * $i);
110
            $facts = array_merge($facts, $documentos);
111
        }
112
        $this->facturas = array();
113
        $articulosCobrados = array();
114
        foreach ($facts as $fac) {
115
            if(!$fac->anulada) {
116
                $fac->referencias = "";
117
                foreach ($fac->get_lineas() as $linea) {
118
                    if ($linea->referencia) {
119
                        $fac->referencias .= $linea->referencia . " ";
120
                        $this->validarArticulos($articulosCobrados, $fac, $linea);
121
                    } else {
122
                        $fac->referencias .= $linea->descripcion . " ";
123
                    }
124
                }
125
                $this->facturas[] = $fac;
126
            }
127
        }
128
        $this->generarArticulosCobrables($articulosCobrados);
129
    }
130
    
131
    public function validarArticulos(&$articulosCobrados, &$fac, &$linea)
132
    {
133
        if (!$fac->idfacturarect) {
134
            $rectificativas = $fac->get_rectificativas();
135
            $articulosDevueltos = array();
136
            $this->validarDevoluciones($articulosDevueltos, $rectificativas);
137
            
138
            if (!isset($articulosDevueltos[$linea->referencia])) {
139
                $articulosCobrados[$linea->referencia] = 1;
140
            }
141
        }
142
    }
143
    
144
    public function validarDevoluciones(&$articulosDevueltos, $rectificativas)
145
    {
146
        foreach ($rectificativas as $rectificativa) {
147
            $lineas_r = $rectificativa->get_lineas();
148
            foreach ($lineas_r as $linea_r) {
149
                $articulosDevueltos[$linea_r->referencia] = 1;
150
            }
151
        }
152
    }
153
    
154
    public function generarArticulosCobrables($articulos_cobrados)
155
    {
156
        $articulos = $this->familia->get_articulos(0, 1000);
157
        foreach ($articulos as $art) {
158
            if (isset($articulos_cobrados[$art->referencia]) === false && !$art->bloqueado) {
159
                $this->articulos_cobrables[] = $art;
160
            }
161
        }
162
    }
163
164
    private function nueva_factura()
165
    {
166
        $cliente = $this->cliente->get($this->residente->codcliente);
167
        if ($cliente) {
168
            $factura = new factura_cliente();
169
            
170
            $this->cabeceraFactura($factura, $cliente);
171
            
172
            $this->datosClienteFactura($factura, $cliente);
173
            
174
            /// función auxiliar para implementar en los plugins que lo necesiten
175
            if (!fs_generar_numero2($factura)) {
176
                $factura->numero2 = '';
177
            }
178
            if ($factura->save()) {
179
                $this->lineasFactura($factura);
180
181
                $this->lineasLibresFactura($factura, 'otro');
182
                $this->lineasLibresFactura($factura, 'otro2');
183
184
                $this->totalFactura($factura);
185
            } else {
186
                $this->new_error_msg('Imposible guardar la factura.');
187
            }
188
        } else {
189
            $this->new_error_msg('Cliente no encontrado.');
190
        }
191
    }
192
    
193
    private function cabeceraFactura(&$factura, $cliente)
194
    {
195
        $factura->codserie = ($cliente->codserie) ?: $this->empresa->codserie;
196
        $factura->codagente = $this->user->codagente;
197
        $factura->codpago = \filter_input(INPUT_POST, 'forma_pago');
198
        $factura->codalmacen = $this->empresa->codalmacen;
199
        $factura->set_fecha_hora($this->today(), $this->hour());
200
        $factura->observaciones = htmlentities(trim(\filter_input(INPUT_POST, 'observaciones')));
201
        $this->datosContabilidadFactura($factura, $cliente);
202
        
203
        $div0 = new divisa();
204
        $divisa = $div0->get($cliente->coddivisa);
205
        if ($divisa) {
206
            $factura->coddivisa = $divisa->coddivisa;
207
            $factura->tasaconv = $divisa->tasaconv;
208
        }
209
    }
210
    
211
    private function datosContabilidadFactura(&$factura, $cliente)
212
    {
213
        $eje0 = new ejercicio();
214
        $ejercicio = $eje0->get_by_fecha(date('d-m-Y'));
215
        if ($ejercicio) {
216
            $factura->codejercicio = $ejercicio->codejercicio;
217
        }
218
        if ($this->empresa->contintegrada) {
219
            $cliente->get_subcuenta($this->empresa->codejercicio);
220
        }
221
222
        $forma_pago = $this->forma_pago->get($factura->codpago);
223
        if ($forma_pago->genrecibos === 'Pagados') {
224
            $factura->pagada = true;
225
        }
226
    }
227
    
228
    private function datosClienteFactura(&$factura, $cliente)
229
    {
230
        $factura->codcliente = $cliente->codcliente;
231
        foreach ($cliente->get_direcciones() as $d) {
232
            if ($d->domfacturacion) {
233
                $factura->codcliente = $cliente->codcliente;
234
                $factura->cifnif = $cliente->cifnif;
235
                $factura->nombrecliente = $cliente->nombre;
236
                $factura->apartado = $d->apartado;
237
                $factura->ciudad = $d->ciudad;
238
                $factura->coddir = $d->id;
239
                $factura->codpais = $d->codpais;
240
                $factura->codpostal = $d->codpostal;
241
                $factura->direccion = $d->direccion;
242
                $factura->provincia = $d->provincia;
243
                break;
244
            }
245
        }
246
    }
247
    
248
    private function lineasFactura(&$factura)
249
    {
250
        $art0 = new articulo();
251
        $lineas = \filter_input(INPUT_POST, 'numlineas');
252
        for ($x = 0; $x < $lineas; $x++) {
253
            $referencia = \filter_input(INPUT_POST, 'referencia_' . $x);
254
            $importe = \filter_input(INPUT_POST, 'importe_' . $x);
255
            $impuesto = \filter_input(INPUT_POST, 'impuesto_' . $x);
256
            $art = $art0->get($referencia);
257
            if ((float)$importe) {
258
                $linea = new linea_factura_cliente();
259
                $linea->idfactura = $factura->idfactura;
260
                $linea->referencia = $referencia;
261
                $linea->descripcion = ($art) ? $art->descripcion : $referencia . ' Articulo libre';
262
                $linea->cantidad = 1;
263
                $imp = $this->impuesto->get($impuesto);
264
                if ($imp) {
265
                    $linea->codimpuesto = $imp->codimpuesto;
266
                    $linea->iva = $imp->iva;
267
                    $linea->pvpsindto = $importe;
268
                    $linea->pvpunitario = $importe;
269
                    $linea->pvptotal = $linea->pvpunitario * $linea->cantidad;
270
                    if ($linea->save()) {
271
                        $factura->neto += $linea->pvptotal;
272
                        $factura->totaliva += $linea->pvpunitario * $linea->iva / 100;
273
                    }
274
                }
275
            }
276
        }
277
    }
278
    
279
    private function lineasLibresFactura(&$factura, $linea_nombre)
280
    {
281
        if (\filter_input(INPUT_POST, 'desc_'.$linea_nombre) !== '') {
282
            $art0 = new articulo();
283
            $linea = new linea_factura_cliente();
284
            $linea->idfactura = $factura->idfactura;
285
            $linea->descripcion = \filter_input(INPUT_POST, 'desc_'.$linea_nombre);
286
            $linea->cantidad = 1;
287
            $imp = $this->impuesto->get(\filter_input(INPUT_POST, 'impuesto_'.$linea_nombre));
288
            if ($imp) {
289
                $linea->codimpuesto = $imp->codimpuesto;
290
                $linea->iva = $imp->iva;
291
                $linea->pvpsindto = $linea->pvptotal = $linea->pvpunitario =
292
                    (100 * (float)\filter_input(INPUT_POST, $linea_nombre)) / (100 + $imp->iva);
293
                
294
                $articulo = (\filter_input(INPUT_POST, 'ref_'.$linea_nombre))
295
                    ? $art0->get(\filter_input(INPUT_POST, 'ref_'.$linea_nombre))
296
                    : '';
297
                if ($articulo !== '') {
298
                    $linea->referencia = $articulo->referencia;
299
                    $articulo->sum_stock($this->empresa->codalmacen, -1);
300
                }
301
                if ($linea->save()) {
302
                    $factura->neto += $linea->pvptotal;
303
                    $factura->totaliva += $linea->pvpunitario * $linea->iva / 100;
304
                }
305
            }
306
        }
307
    }
308
    
309
    private function totalFactura(&$factura)
310
    {
311
        /// redondeamos
312
        $factura->neto = round($factura->neto, FS_NF0);
313
        $factura->totaliva = round($factura->totaliva, FS_NF0);
314
        $factura->totalirpf = round($factura->totalirpf, FS_NF0);
315
        $factura->totalrecargo = round($factura->totalrecargo, FS_NF0);
316
        $factura->total = $factura->neto + $factura->totaliva - $factura->totalirpf + $factura->totalrecargo;
317
318
        if (abs((float)(\filter_input(INPUT_POST, 'total_importe')) - $factura->total) > .01) {
319
            $this->new_error_msg("El total difiere entre la vista y el controlador (" .
320
                \filter_input(INPUT_POST, 'total_importe') .
321
                " frente a " . $factura->total . "). Debes informar del error.");
322
            $factura->delete();
323
        } elseif ($factura->save()) {
324
            $this->generar_asiento($factura);
325
            /// Función de ejecución de tareas post guardado correcto de la factura
326
            fs_documento_post_save($factura);
327
            $this->new_message("<a href='" . $factura->url() . "'>Factura</a> guardada correctamente.");
328
            $this->new_change('Factura Cliente ' . $factura->codigo, $factura->url(), true);
329
        } else {
330
            $this->new_error_msg("¡Imposible actualizar la <a href='" . $factura->url() . "'>Factura</a>!");
331
        }
332
    }
333
334
    /**
335
     * Genera el asiento para la factura, si procede
336
     * @param factura_cliente $factura
337
     */
338
    private function generar_asiento(&$factura)
339
    {
340
        if ($this->empresa->contintegrada) {
341
            $asiento_factura = new asiento_factura();
342
            $asiento_factura->generar_asiento_venta($factura);
343
        } else {
344
            /// de todas formas forzamos la generación de las líneas de iva
345
            $factura->get_lineas_iva();
346
        }
347
    }
348
349
    private function buscar_referencia()
350
    {
351
        /// desactivamos la plantilla HTML
352
        $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...
353
354
        $articulo = new articulo();
355
        $json = array();
356
        foreach ($articulo->search($_REQUEST['buscar_referencia']) as $art) {
357
            $json[] = array(
358
                'value' => $art->referencia,
359
                'data' => $art->referencia,
360
                'pvpi' => $art->pvp_iva(false),
361
                'codimpuesto' => $art->codimpuesto,
362
                'descripcion' => $art->descripcion
363
            );
364
        }
365
366
        header('Content-Type: application/json');
367
        echo json_encode(array('query' => $_REQUEST['buscar_referencia'], 'suggestions' => $json), JSON_THROW_ON_ERROR);
368
    }
369
370
    public function paginas()
371
    {
372
        $url = $this->url();
373
374
        $paginas = array();
375
        $i = 0;
376
        $num = 0;
377
        $actual = 1;
378
379
        /// añadimos todas la página
380
        while ($num < $this->total_facturas) {
381
            $paginas[$i] = array(
382
                'url' => $url . "&offset=" . ($i * FS_ITEM_LIMIT),
383
                'num' => $i + 1,
384
                'actual' => ($num == $this->offset)
385
            );
386
387
            if ($num == $this->offset) {
388
                $actual = $i;
389
            }
390
391
            $i++;
392
            $num += FS_ITEM_LIMIT;
393
        }
394
395
        /// ahora descartamos
396
        foreach ($paginas as $j => $value) {
397
            $enmedio = (int)($i / 2);
398
399
            /**
400
             * descartamos todo excepto la primera, la última, la de enmedio,
401
             * la actual, las 5 anteriores y las 5 siguientes
402
             */
403
            if (($j>1 && $j<$actual-5 && $j !== $enmedio) || ($j > $actual + 5 && $j < $i - 1 && $j !== $enmedio)) {
404
                unset($paginas[$j]);
405
            }
406
        }
407
408
        if (count($paginas) > 1) {
409
            return $paginas;
410
        } else {
411
            return array();
412
        }
413
    }
414
}
415