ver_residente::initVars()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 8
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 10
rs 10
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
    /**
102
     * @return void
103
     */
104
    public function informacionResidente()
105
    {
106
        $this->page->title = 'Residente ' . $this->residente->nombre;
107
        $this->facturas = [];
108
        $referencias = [];
109
        $articulosCobrados = [];
110
        $documentosResidentes = $this->residente->facturas_from_cliente("DESC");
111
        foreach($documentosResidentes as $doc) {
112
            //convert array $doc to standard object
113
            $fac = (object) $doc;
114
            if(!isset($referencias[$fac->idfactura]))
115
            {
116
                $referencias[$fac->idfactura] = "";
117
            }
118
119
            if ($fac->qdadfinal > 0 && $fac->cantidaddev >= 0) {
120
                $articulosCobrados[$fac->referencia] = 1;
121
            }
122
123
            if ($fac->referencia) {
124
                $referencias[$fac->idfactura] .= $fac->referencia . " ";
125
            } else {
126
                $referencias[$fac->idfactura] .= $fac->descripcion . " ";
127
            }
128
            $this->facturas[$fac->idfactura] = $fac;
129
        }
130
131
        $facturas = new factura_cliente();
132
        foreach ($this->facturas as $factura) {
133
            $facturaFinal = $facturas->get($factura->idfactura);
134
            $facturaFinal->referencias = $referencias[$factura->idfactura];
135
136
            $this->facturas[$factura->idfactura] = $facturaFinal;
137
        }
138
        $this->generarArticulosCobrables($articulosCobrados);
139
    }
140
//
141
//    public function validarArticulos(&$articulosCobrados, &$fac, &$linea)
142
//    {
143
//        if (!in_array($fac->idfacturarect, ['', null], true)) {
144
//            $rectificativas = $fac->get_rectificativas();
145
//            $articulosDevueltos = array();
146
//            $this->validarDevoluciones($articulosDevueltos, $rectificativas);
147
//
148
//            if (!isset($articulosDevueltos[$linea->referencia])) {
149
//                $articulosCobrados[$linea->referencia] = 1;
150
//            }
151
//        }
152
//    }
153
    
154
    public function validarDevoluciones(&$articulosDevueltos, $rectificativas)
155
    {
156
        foreach ($rectificativas as $rectificativa) {
157
            $lineas_r = $rectificativa->get_lineas();
158
            foreach ($lineas_r as $linea_r) {
159
                $articulosDevueltos[$linea_r->referencia] = 1;
160
            }
161
        }
162
    }
163
    
164
    public function generarArticulosCobrables($articulos_cobrados)
165
    {
166
        $articulos = $this->familia->get_articulos(0, 1000);
167
        foreach ($articulos as $art) {
168
            if (isset($articulos_cobrados[$art->referencia]) === false && !$art->bloqueado) {
169
                $this->articulos_cobrables[] = $art;
170
            }
171
        }
172
    }
173
174
    private function nueva_factura()
175
    {
176
        $cliente = $this->cliente->get($this->residente->codcliente);
177
        if ($cliente) {
178
            $factura = new factura_cliente();
179
            
180
            $this->cabeceraFactura($factura, $cliente);
181
            
182
            $this->datosClienteFactura($factura, $cliente);
183
            
184
            /// función auxiliar para implementar en los plugins que lo necesiten
185
            if (!fs_generar_numero2($factura)) {
186
                $factura->numero2 = '';
187
            }
188
            if ($factura->save()) {
189
                $this->lineasFactura($factura);
190
191
                $this->lineasLibresFactura($factura, 'otro');
192
                $this->lineasLibresFactura($factura, 'otro2');
193
194
                $this->totalFactura($factura);
195
            } else {
196
                $this->new_error_msg('Imposible guardar la factura.');
197
            }
198
        } else {
199
            $this->new_error_msg('Cliente no encontrado.');
200
        }
201
    }
202
    
203
    private function cabeceraFactura(&$factura, $cliente)
204
    {
205
        $factura->codserie = ($cliente->codserie) ?: $this->empresa->codserie;
206
        $factura->codagente = $this->user->codagente;
207
        $factura->codpago = \filter_input(INPUT_POST, 'forma_pago');
208
        $factura->codalmacen = $this->empresa->codalmacen;
209
        $factura->set_fecha_hora($this->today(), $this->hour());
210
        $factura->observaciones = htmlentities(trim(\filter_input(INPUT_POST, 'observaciones')));
211
        $this->datosContabilidadFactura($factura, $cliente);
212
        
213
        $div0 = new divisa();
214
        $divisa = $div0->get($cliente->coddivisa);
215
        if ($divisa) {
216
            $factura->coddivisa = $divisa->coddivisa;
217
            $factura->tasaconv = $divisa->tasaconv;
218
        }
219
    }
220
    
221
    private function datosContabilidadFactura(&$factura, $cliente)
222
    {
223
        $eje0 = new ejercicio();
224
        $ejercicio = $eje0->get_by_fecha(date('d-m-Y'));
225
        if ($ejercicio) {
226
            $factura->codejercicio = $ejercicio->codejercicio;
227
        }
228
        if ($this->empresa->contintegrada) {
229
            $cliente->get_subcuenta($this->empresa->codejercicio);
230
        }
231
232
        $forma_pago = $this->forma_pago->get($factura->codpago);
233
        if ($forma_pago->genrecibos === 'Pagados') {
234
            $factura->pagada = true;
235
        }
236
    }
237
    
238
    private function datosClienteFactura(&$factura, $cliente)
239
    {
240
        $factura->codcliente = $cliente->codcliente;
241
        foreach ($cliente->get_direcciones() as $d) {
242
            if ($d->domfacturacion) {
243
                $factura->codcliente = $cliente->codcliente;
244
                $factura->cifnif = $cliente->cifnif;
245
                $factura->nombrecliente = $cliente->nombre;
246
                $factura->apartado = $d->apartado;
247
                $factura->ciudad = $d->ciudad;
248
                $factura->coddir = $d->id;
249
                $factura->codpais = $d->codpais;
250
                $factura->codpostal = $d->codpostal;
251
                $factura->direccion = $d->direccion;
252
                $factura->provincia = $d->provincia;
253
                break;
254
            }
255
        }
256
    }
257
    
258
    private function lineasFactura(&$factura)
259
    {
260
        $art0 = new articulo();
261
        $lineas = \filter_input(INPUT_POST, 'numlineas');
262
        for ($x = 0; $x < $lineas; $x++) {
263
            $referencia = \filter_input(INPUT_POST, 'referencia_' . $x);
264
            $importe = \filter_input(INPUT_POST, 'importe_' . $x);
265
            $impuesto = \filter_input(INPUT_POST, 'impuesto_' . $x);
266
            $art = $art0->get($referencia);
267
            if ((float)$importe) {
268
                $linea = new linea_factura_cliente();
269
                $linea->idfactura = $factura->idfactura;
270
                $linea->referencia = $referencia;
271
                $linea->descripcion = ($art) ? $art->descripcion : $referencia . ' Articulo libre';
272
                $linea->cantidad = 1;
273
                $imp = $this->impuesto->get($impuesto);
274
                if ($imp) {
275
                    $linea->codimpuesto = $imp->codimpuesto;
276
                    $linea->iva = $imp->iva;
277
                    $linea->pvpsindto = $importe;
278
                    $linea->pvpunitario = $importe;
279
                    $linea->pvptotal = $linea->pvpunitario * $linea->cantidad;
280
                    if ($linea->save()) {
281
                        $factura->neto += $linea->pvptotal;
282
                        $factura->totaliva += $linea->pvpunitario * $linea->iva / 100;
283
                    }
284
                }
285
            }
286
        }
287
    }
288
    
289
    private function lineasLibresFactura(&$factura, $linea_nombre)
290
    {
291
        if (\filter_input(INPUT_POST, 'desc_'.$linea_nombre) !== '') {
292
            $art0 = new articulo();
293
            $linea = new linea_factura_cliente();
294
            $linea->idfactura = $factura->idfactura;
295
            $linea->descripcion = \filter_input(INPUT_POST, 'desc_'.$linea_nombre);
296
            $linea->cantidad = 1;
297
            $imp = $this->impuesto->get(\filter_input(INPUT_POST, 'impuesto_'.$linea_nombre));
298
            if ($imp) {
299
                $linea->codimpuesto = $imp->codimpuesto;
300
                $linea->iva = $imp->iva;
301
                $linea->pvpsindto = $linea->pvptotal = $linea->pvpunitario =
302
                    (100 * (float)\filter_input(INPUT_POST, $linea_nombre)) / (100 + $imp->iva);
303
                
304
                $articulo = (\filter_input(INPUT_POST, 'ref_'.$linea_nombre))
305
                    ? $art0->get(\filter_input(INPUT_POST, 'ref_'.$linea_nombre))
306
                    : '';
307
                if ($articulo !== '') {
308
                    $linea->referencia = $articulo->referencia;
309
                    $articulo->sum_stock($this->empresa->codalmacen, -1);
310
                }
311
                if ($linea->save()) {
312
                    $factura->neto += $linea->pvptotal;
313
                    $factura->totaliva += $linea->pvpunitario * $linea->iva / 100;
314
                }
315
            }
316
        }
317
    }
318
    
319
    private function totalFactura(&$factura)
320
    {
321
        /// redondeamos
322
        $factura->neto = round($factura->neto, FS_NF0);
323
        $factura->totaliva = round($factura->totaliva, FS_NF0);
324
        $factura->totalirpf = round($factura->totalirpf, FS_NF0);
325
        $factura->totalrecargo = round($factura->totalrecargo, FS_NF0);
326
        $factura->total = $factura->neto + $factura->totaliva - $factura->totalirpf + $factura->totalrecargo;
327
328
        if (abs((float)(\filter_input(INPUT_POST, 'total_importe')) - $factura->total) > .01) {
329
            $this->new_error_msg("El total difiere entre la vista y el controlador (" .
330
                \filter_input(INPUT_POST, 'total_importe') .
331
                " frente a " . $factura->total . "). Debes informar del error.");
332
            $factura->delete();
333
        } elseif ($factura->save()) {
334
            $this->generar_asiento($factura);
335
            /// Función de ejecución de tareas post guardado correcto de la factura
336
            fs_documento_post_save($factura);
337
            $this->new_message("<a href='" . $factura->url() . "'>Factura</a> guardada correctamente.");
338
            $this->new_change('Factura Cliente ' . $factura->codigo, $factura->url(), true);
339
        } else {
340
            $this->new_error_msg("¡Imposible actualizar la <a href='" . $factura->url() . "'>Factura</a>!");
341
        }
342
    }
343
344
    /**
345
     * Genera el asiento para la factura, si procede
346
     * @param factura_cliente $factura
347
     */
348
    private function generar_asiento(&$factura)
349
    {
350
        if ($this->empresa->contintegrada) {
351
            $asiento_factura = new asiento_factura();
352
            $asiento_factura->generar_asiento_venta($factura);
353
        } else {
354
            /// de todas formas forzamos la generación de las líneas de iva
355
            $factura->get_lineas_iva();
356
        }
357
    }
358
359
    private function buscar_referencia()
360
    {
361
        /// desactivamos la plantilla HTML
362
        $this->template = false;
363
364
        $articulo = new articulo();
365
        $json = array();
366
        foreach ($articulo->search($_REQUEST['buscar_referencia']) as $art) {
367
            $json[] = array(
368
                'value' => $art->referencia,
369
                'data' => $art->referencia,
370
                'pvpi' => $art->pvp_iva(false),
371
                'codimpuesto' => $art->codimpuesto,
372
                'descripcion' => $art->descripcion
373
            );
374
        }
375
376
        header('Content-Type: application/json');
377
        echo json_encode(array('query' => $_REQUEST['buscar_referencia'], 'suggestions' => $json), JSON_THROW_ON_ERROR);
378
    }
379
380
    public function paginas()
381
    {
382
        $url = $this->url();
383
384
        $paginas = array();
385
        $i = 0;
386
        $num = 0;
387
        $actual = 1;
388
389
        /// añadimos todas la página
390
        while ($num < $this->total_facturas) {
391
            $paginas[$i] = array(
392
                'url' => $url . "&offset=" . ($i * FS_ITEM_LIMIT),
393
                'num' => $i + 1,
394
                'actual' => ($num == $this->offset)
395
            );
396
397
            if ($num == $this->offset) {
398
                $actual = $i;
399
            }
400
401
            $i++;
402
            $num += FS_ITEM_LIMIT;
403
        }
404
405
        /// ahora descartamos
406
        foreach ($paginas as $j => $value) {
407
            $enmedio = (int)($i / 2);
408
409
            /**
410
             * descartamos todo excepto la primera, la última, la de enmedio,
411
             * la actual, las 5 anteriores y las 5 siguientes
412
             */
413
            if (($j>1 && $j<$actual-5 && $j !== $enmedio) || ($j > $actual + 5 && $j < $i - 1 && $j !== $enmedio)) {
414
                unset($paginas[$j]);
415
            }
416
        }
417
418
        if (count($paginas) > 1) {
419
            return $paginas;
420
        } else {
421
            return array();
422
        }
423
    }
424
}
425