Passed
Push — master ( a7c403...3906a7 )
by Joe Nilson
02:19
created

ver_residente::lineasLibresFactura()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 25
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 21
nc 10
nop 2
dl 0
loc 25
rs 8.9617
c 0
b 0
f 0
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
45
    public function __construct()
46
    {
47
        parent::__construct(__CLASS__, 'Residente', 'residentes', false, false);
48
    }
49
    
50
    public function initVars()
51
    {
52
        $this->cliente = new cliente();
53
        $this->facturas = array();
54
        $this->impuesto = new impuesto();
1 ignored issue
show
Bug introduced by
The type impuesto 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...
55
        $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...
56
        $this->residente = false;
57
        $this->articulos = new articulo();
1 ignored issue
show
Bug introduced by
The type articulo 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->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...
59
        $this->familia = $this->familias->get('RESIDENT');
60
    }
61
62
    protected function private_core()
63
    {
64
        $this->initVars();
65
66
        if (\filter_input(INPUT_GET, 'id')) {
67
            $res0 = new residentes_edificaciones();
68
            $this->residente = $res0->get(\filter_input(INPUT_GET, 'id'));
69
            $this->cliente_data = $this->cliente->get($this->residente->codcliente);
70
            $this->cliente_data->codcontacto = '';
71
            
72
            if (class_exists('contacto_cliente')) {
73
                $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...
74
                $infoCRM = $concli->all_from_cliente($this->residente->codcliente);
75
                $this->cliente_data->codcontacto = $infoCRM[0]->codcontacto;
76
            }
77
        }
78
        
79
        if ($this->residente) {
80
            $accion = \filter_input(INPUT_POST, 'accion');
81
            if ($accion == 'generar_factura') {
82
                $this->nueva_factura();
83
            }
84
            $this->informacionResidente();
85
        } else {
86
            $this->new_error_msg('Residente no encontrado.');
87
        }
88
    }
89
90
    public function url()
91
    {
92
        if (\filter_input(INPUT_GET, 'id')) {
93
            return $this->residente->url();
94
        }
95
        return parent::url();
96
    }
97
    
98
    public function informacionResidente()
99
    {
100
        $this->page->title = 'Residente ' . $this->residente->nombre;
101
        $factura = new factura_cliente();
102
        $facts = $factura->all_from_cliente($this->residente->codcliente);
103
        $this->facturas = array();
104
        $articulos_cobrados = array();
105
        
106
        foreach ($facts as $fac) {
107
            $fac->referencias = "";
108
            foreach ($fac->get_lineas() as $linea) {
109
                if ($linea->referencia) {
110
                    $fac->referencias .= $linea->referencia . " ";
111
                    $this->validarArticulos($articulos_cobrados, $fac, $linea);
112
                } else {
113
                    $fac->referencias .= $linea->descripcion . " ";
114
                }
115
            }
116
            $this->facturas[] = $fac;
117
        }
118
        $this->generarArticulosCobrables($articulos_cobrados);
119
    }
120
    
121
    public function validarArticulos(&$articulos_cobrados, &$fac, &$linea)
122
    {
123
        if (!$fac->idfacturarect) {
124
            $rectificativas = $fac->get_rectificativas();
125
            $articulosDevueltos = array();
126
            $this->validarDevoluciones($articulosDevueltos, $rectificativas);
127
            
128
            if (!isset($articulosDevueltos[$linea->referencia])) {
129
                $articulos_cobrados[$linea->referencia] = 1;
130
            }
131
        }
132
    }
133
    
134
    public function validarDevoluciones(&$articulosDevueltos, $rectificativas)
135
    {
136
        foreach ($rectificativas as $rectificativa) {
137
            $lineas_r = $rectificativa->get_lineas();
138
            foreach ($lineas_r as $linea_r) {
139
                $articulosDevueltos[$linea_r->referencia] = 1;
140
            }
141
        }
142
    }
143
    
144
    public function generarArticulosCobrables($articulos_cobrados)
145
    {
146
        foreach ($this->familia->get_articulos(0, 1000) as $art) {
147
            if (!isset($articulos_cobrados[$art->referencia]) && $art->bloqueado == 0) {
148
                $this->articulos_cobrables[] = $art;
149
            }
150
        }
151
    }
152
153
    private function nueva_factura()
154
    {
155
        $cliente = $this->cliente->get($this->residente->codcliente);
156
        if ($cliente) {
157
            $factura = new factura_cliente();
158
            
159
            $this->cabeceraFactura($factura, $cliente);
160
            
161
            $this->datosClienteFactura($factura, $cliente);
162
            
163
            /// función auxiliar para implementar en los plugins que lo necesiten
164
            if (!fs_generar_numero2($factura)) {
165
                $factura->numero2 = '';
166
            }
167
            if ($factura->save()) {
168
                $this->lineasFactura($factura);
169
170
                $this->lineasLibresFactura($factura, 'otro');
171
                $this->lineasLibresFactura($factura, 'otro2');
172
173
                $this->totalFactura($factura);
174
            } else {
175
                $this->new_error_msg('Imposible guardar la factura.');
176
            }
177
        } else {
178
            $this->new_error_msg('Cliente no encontrado.');
179
        }
180
    }
181
    
182
    private function cabeceraFactura(&$factura, $cliente)
183
    {
184
        $factura->codserie = ($cliente->codserie) ?: $this->empresa->codserie;
185
        $factura->codagente = $this->user->codagente;
186
        $factura->codpago = \filter_input(INPUT_POST, 'forma_pago');
187
        $factura->codalmacen = $this->empresa->codalmacen;
188
        $factura->set_fecha_hora($this->today(), $this->hour());
189
        $factura->observaciones = htmlentities(trim(\filter_input(INPUT_POST, 'observaciones')));
190
        $this->datosContabilidadFactura($factura, $cliente);
191
        
192
        $div0 = new divisa();
1 ignored issue
show
Bug introduced by
The type divisa 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...
193
        $divisa = $div0->get($cliente->coddivisa);
194
        if ($divisa) {
195
            $factura->coddivisa = $divisa->coddivisa;
196
            $factura->tasaconv = $divisa->tasaconv;
197
        }
198
    }
199
    
200
    private function datosContabilidadFactura(&$factura, $cliente)
201
    {
202
        $eje0 = new ejercicio();
1 ignored issue
show
Bug introduced by
The type ejercicio 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...
203
        $ejercicio = $eje0->get_by_fecha(date('d-m-Y'));
204
        if ($ejercicio) {
205
            $factura->codejercicio = $ejercicio->codejercicio;
206
        }
207
        if ($this->empresa->contintegrada) {
208
            $cliente->get_subcuenta($this->empresa->codejercicio);
209
        }
210
211
        $forma_pago = $this->forma_pago->get($factura->codpago);
212
        if ($forma_pago->genrecibos === 'Pagados') {
213
            $factura->pagada = true;
214
        }
215
    }
216
    
217
    private function datosClienteFactura(&$factura, $cliente)
218
    {
219
        $factura->codcliente = $cliente->codcliente;
220
        foreach ($cliente->get_direcciones() as $d) {
221
            if ($d->domfacturacion) {
222
                $factura->codcliente = $cliente->codcliente;
223
                $factura->cifnif = $cliente->cifnif;
224
                $factura->nombrecliente = $cliente->nombre;
225
                $factura->apartado = $d->apartado;
226
                $factura->ciudad = $d->ciudad;
227
                $factura->coddir = $d->id;
228
                $factura->codpais = $d->codpais;
229
                $factura->codpostal = $d->codpostal;
230
                $factura->direccion = $d->direccion;
231
                $factura->provincia = $d->provincia;
232
                break;
233
            }
234
        }
235
    }
236
    
237
    private function lineasFactura(&$factura)
238
    {
239
        $art0 = new articulo();
240
        $lineas = \filter_input(INPUT_POST, 'numlineas');
241
        for ($x = 0; $x < $lineas; $x++) {
242
            $referencia = \filter_input(INPUT_POST, 'referencia_' . $x);
243
            $importe = \filter_input(INPUT_POST, 'importe_' . $x);
244
            $impuesto = \filter_input(INPUT_POST, 'impuesto_' . $x);
245
            $art = $art0->get($referencia);
246
            if ((float)$importe) {
247
                $linea = new linea_factura_cliente();
1 ignored issue
show
Bug introduced by
The type linea_factura_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...
248
                $linea->idfactura = $factura->idfactura;
249
                $linea->referencia = $referencia;
250
                $linea->descripcion = ($art) ? $art->descripcion : $referencia . ' Articulo libre';
251
                $linea->cantidad = 1;
252
                $imp = $this->impuesto->get($impuesto);
253
                if ($imp) {
254
                    $linea->codimpuesto = $imp->codimpuesto;
255
                    $linea->iva = $imp->iva;
256
                    $linea->pvpsindto = $importe;
257
                    $linea->pvpunitario = $importe;
258
                    $linea->pvptotal = $linea->pvpunitario * $linea->cantidad;
259
                    if ($linea->save()) {
260
                        $factura->neto += $linea->pvptotal;
261
                        $factura->totaliva += $linea->pvpunitario * $linea->iva / 100;
262
                    }
263
                }
264
            }
265
        }
266
    }
267
    
268
    private function lineasLibresFactura(&$factura, $linea_nombre)
269
    {
270
        if (\filter_input(INPUT_POST, 'desc_'.$linea_nombre) !== '') {
271
            $art0 = new articulo();
272
            $linea = new linea_factura_cliente();
273
            $linea->idfactura = $factura->idfactura;
274
            $linea->descripcion = \filter_input(INPUT_POST, 'desc_'.$linea_nombre);
275
            $linea->cantidad = 1;
276
            $imp = $this->impuesto->get(\filter_input(INPUT_POST, 'impuesto_'.$linea_nombre));
277
            if ($imp) {
278
                $linea->codimpuesto = $imp->codimpuesto;
279
                $linea->iva = $imp->iva;
280
                $linea->pvpsindto = $linea->pvptotal = $linea->pvpunitario =
281
                    (100 * (float)\filter_input(INPUT_POST, $linea_nombre)) / (100 + $imp->iva);
282
                
283
                $articulo = (\filter_input(INPUT_POST, 'ref_'.$linea_nombre))
284
                    ? $art0->get(\filter_input(INPUT_POST, 'ref_'.$linea_nombre))
285
                    : '';
286
                if ($articulo !== '') {
287
                    $linea->referencia = $articulo->referencia;
288
                    $articulo->sum_stock($this->empresa->codalmacen, -1);
289
                }
290
                if ($linea->save()) {
291
                    $factura->neto += $linea->pvptotal;
292
                    $factura->totaliva += $linea->pvpunitario * $linea->iva / 100;
293
                }
294
            }
295
        }
296
    }
297
    
298
    private function totalFactura(&$factura)
299
    {
300
        /// redondeamos
301
        $factura->neto = round($factura->neto, FS_NF0);
1 ignored issue
show
Bug introduced by
The constant FS_NF0 was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
302
        $factura->totaliva = round($factura->totaliva, FS_NF0);
303
        $factura->totalirpf = round($factura->totalirpf, FS_NF0);
304
        $factura->totalrecargo = round($factura->totalrecargo, FS_NF0);
305
        $factura->total = $factura->neto + $factura->totaliva - $factura->totalirpf + $factura->totalrecargo;
306
307
        if (abs((float)(\filter_input(INPUT_POST, 'total_importe')) - $factura->total) > .01) {
308
            $this->new_error_msg("El total difiere entre la vista y el controlador (" .
309
                \filter_input(INPUT_POST, 'total_importe') .
310
                " frente a " . $factura->total . "). Debes informar del error.");
311
            $factura->delete();
312
        } elseif ($factura->save()) {
313
            $this->generar_asiento($factura);
314
            /// Función de ejecución de tareas post guardado correcto de la factura
315
            fs_documento_post_save($factura);
316
            $this->new_message("<a href='" . $factura->url() . "'>Factura</a> guardada correctamente.");
317
            $this->new_change('Factura Cliente ' . $factura->codigo, $factura->url(), true);
318
        } else {
319
            $this->new_error_msg("¡Imposible actualizar la <a href='" . $factura->url() . "'>Factura</a>!");
320
        }
321
    }
322
323
    /**
324
     * Genera el asiento para la factura, si procede
325
     * @param factura_cliente $factura
326
     */
327
    private function generar_asiento(&$factura)
328
    {
329
        if ($this->empresa->contintegrada) {
330
            $asiento_factura = new asiento_factura();
1 ignored issue
show
Bug introduced by
The type asiento_factura 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...
331
            $asiento_factura->generar_asiento_venta($factura);
332
        } else {
333
            /// de todas formas forzamos la generación de las líneas de iva
334
            $factura->get_lineas_iva();
335
        }
336
    }
337
338
    private function buscar_referencia()
339
    {
340
        /// desactivamos la plantilla HTML
341
        $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...
342
343
        $articulo = new articulo();
344
        $json = array();
345
        foreach ($articulo->search($_REQUEST['buscar_referencia']) as $art) {
346
            $json[] = array(
347
                'value' => $art->referencia,
348
                'data' => $art->referencia,
349
                'pvpi' => $art->pvp_iva(false),
350
                'codimpuesto' => $art->codimpuesto,
351
                'descripcion' => $art->descripcion
352
            );
353
        }
354
355
        header('Content-Type: application/json');
356
        echo json_encode(array('query' => $_REQUEST['buscar_referencia'], 'suggestions' => $json), JSON_THROW_ON_ERROR);
357
    }
358
}
359