nueva_compra   F
last analyzed

Complexity

Total Complexity 169

Size/Duplication

Total Lines 933
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 587
c 1
b 0
f 0
dl 0
loc 933
rs 2
wmc 169

17 Methods

Rating   Name   Duplication   Size   Complexity  
A nueva_linea() 0 22 4
F nuevo_albaran_proveedor() 0 149 29
F private_core() 0 88 23
C search_from_proveedor() 0 74 13
A datos_proveedor() 0 7 1
A url() 0 3 1
A nuevo_documento() 0 20 2
A actualizar_precio_proveedor() 0 17 4
B new_search() 0 49 11
A generar_ncf() 0 15 3
A get_precios_articulo() 0 7 1
F nuevo_pedido_proveedor() 0 134 27
B new_articulo() 0 69 10
A tipos_a_guardar() 0 17 5
F nueva_factura_proveedor() 0 160 31
A __construct() 0 3 1
A get_combinaciones_articulo() 0 21 3

How to fix   Complexity   

Complex Class

Complex classes like nueva_compra often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use nueva_compra, and based on these observations, apply Extract Interface, too.

1
<?php
2
/*
3
 * This file is part of facturacion_base
4
 * Copyright (C) 2014-2017  Carlos Garcia Gomez  [email protected]
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
8
 * published by the Free Software Foundation, either version 3 of the
9
 * License, or (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
require_once 'plugins/facturacion_base/extras/fbase_controller.php';
21
22
class nueva_compra extends fbase_controller
0 ignored issues
show
Bug introduced by
The type fbase_controller 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...
23
{
24
25
    public $agente;
26
    public $almacen;
27
    public $articulo;
28
    public $articulo_prov;
29
    public $divisa;
30
    public $fabricante;
31
    public $familia;
32
    public $forma_pago;
33
    public $impuesto;
34
    public $proveedor;
35
    public $proveedor_s;
36
    public $results;
37
    public $serie;
38
    public $tipo;
39
    public $ncf_tipo_compras;
40
    public $ncf_tipo_pagos_compras;
41
    public $ncf_rango;
42
43
    public function __construct()
44
    {
45
        parent::__construct(__CLASS__, 'Nueva compra...', 'compras', FALSE, FALSE, TRUE);
46
    }
47
48
    protected function private_core()
49
    {
50
        parent::private_core();
51
52
        $this->articulo_prov = new articulo_proveedor();
0 ignored issues
show
Bug introduced by
The type articulo_proveedor 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...
53
        $this->fabricante = new fabricante();
0 ignored issues
show
Bug introduced by
The type fabricante 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...
54
        $this->familia = 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...
55
        $this->impuesto = new impuesto();
0 ignored issues
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...
56
        $this->proveedor = new proveedor();
57
        $this->ncf_tipo_compras = new ncf_tipo_compras();
58
        $this->ncf_tipo_pagos_compras = new ncf_tipo_pagos_compras();
59
        $this->ncf_rango = new ncf_rango();
60
        $this->proveedor_s = FALSE;
61
        $this->results = array();
62
        
63
        if (isset($_REQUEST['tipo'])) {
64
            $this->tipo = $_REQUEST['tipo'];
65
        } else {
66
            foreach ($this->tipos_a_guardar() as $t) {
67
                $this->tipo = $t['tipo'];
68
                break;
69
            }
70
        }
71
        
72
        if (filter_input(INPUT_GET, 'generar_comprobante')) {
73
            $this->generar_ncf(filter_input(INPUT_GET, 'generar_comprobante'));
74
        }
75
76
        if (isset($_REQUEST['buscar_proveedor'])) {
77
            $this->fbase_buscar_proveedor($_REQUEST['buscar_proveedor']);
78
        } else if (isset($_REQUEST['datosproveedor'])) {
79
            $this->datos_proveedor();
80
        } else if (isset($_REQUEST['new_articulo'])) {
81
            $this->new_articulo();
82
        } else if ($this->query != '') {
83
            $this->new_search();
84
        } else if (isset($_POST['referencia4precios'])) {
85
            $this->get_precios_articulo();
86
        } else if (isset($_POST['referencia4combi'])) {
87
            $this->get_combinaciones_articulo();
88
        } else if (isset($_POST['proveedor'])) {
89
            $this->proveedor_s = $this->proveedor->get($_POST['proveedor']);
90
91
            if (isset($_POST['nuevo_proveedor']) && $_POST['nuevo_proveedor'] != '') {
92
                $this->proveedor_s = FALSE;
93
                if ($_POST['nuevo_cifnif'] != '') {
94
                    $this->proveedor_s = $this->proveedor->get_by_cifnif($_POST['nuevo_cifnif']);
95
                    if ($this->proveedor_s) {
96
                        $this->new_advice('Ya existe un proveedor con ese ' . FS_CIFNIF . '. Se ha seleccionado.');
97
                    }
98
                }
99
100
                if (!$this->proveedor_s) {
101
                    $this->proveedor_s = new proveedor();
102
                    $this->proveedor_s->codproveedor = $this->proveedor_s->get_new_codigo();
103
                    $this->proveedor_s->nombre = $this->proveedor_s->razonsocial = $_POST['nuevo_proveedor'];
104
                    $this->proveedor_s->tipoidfiscal = $_POST['nuevo_tipoidfiscal'];
105
                    $this->proveedor_s->cifnif = $_POST['nuevo_cifnif'];
106
                    $this->proveedor_s->acreedor = isset($_POST['acreedor']);
107
                    $this->proveedor_s->personafisica = isset($_POST['personafisica']);
108
                    $this->proveedor_s->save();
109
110
                    if ($this->empresa->contintegrada) {
111
                        /// forzamos crear la subcuenta
112
                        $this->proveedor_s->get_subcuenta($this->empresa->codejercicio);
113
                    }
114
                }
115
            }
116
117
            if (isset($_POST['codagente'])) {
118
                $agente = new agente();
0 ignored issues
show
Bug introduced by
The type agente 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...
119
                $this->agente = $agente->get($_POST['codagente']);
120
            } else {
121
                $this->agente = $this->user->get_agente();
122
            }
123
124
            $this->almacen = new almacen();
0 ignored issues
show
Bug introduced by
The type almacen 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...
125
            $this->serie = new serie();
0 ignored issues
show
Bug introduced by
The type serie 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...
126
            $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...
127
            $this->divisa = new divisa();
0 ignored issues
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...
128
129
            if (isset($_POST['tipo'])) {
130
                if ($_POST['tipo'] == 'factura') {
131
                    $this->nueva_factura_proveedor();
132
                } else if ($_POST['tipo'] == 'albaran') {
133
                    $this->nuevo_albaran_proveedor();
134
                } else if ($_POST['tipo'] == 'pedido' && class_exists('pedido_proveedor')) {
135
                    $this->nuevo_pedido_proveedor();
136
                }
137
            }
138
        }
139
    }
140
141
    /**
142
     * Devuelve los tipos de documentos a guardar,
143
     * así para añadir tipos no hay que tocar la vista.
144
     * @return type
145
     */
146
    public function tipos_a_guardar()
147
    {
148
        $tipos = array();
149
150
        if ($this->user->have_access_to('compras_pedido') && class_exists('pedido_proveedor')) {
151
            $tipos[] = array('tipo' => 'pedido', 'nombre' => ucfirst(FS_PEDIDO) . ' de compra');
0 ignored issues
show
Bug introduced by
The constant FS_PEDIDO was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
152
        }
153
154
        if ($this->user->have_access_to('compras_albaran')) {
155
            $tipos[] = array('tipo' => 'albaran', 'nombre' => ucfirst(FS_ALBARAN) . ' de compra');
0 ignored issues
show
Bug introduced by
The constant FS_ALBARAN was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
156
        }
157
158
        if ($this->user->have_access_to('compras_factura')) {
159
            $tipos[] = array('tipo' => 'factura', 'nombre' => 'Factura de compra');
160
        }
161
162
        return $tipos;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $tipos returns the type array|array<mixed,array<string,string>> which is incompatible with the documented return type type.
Loading history...
163
    }
164
165
    public function url()
166
    {
167
        return 'index.php?page=' . __CLASS__ . '&tipo=' . $this->tipo;
168
    }
169
170
    private function datos_proveedor()
171
    {
172
        /// desactivamos la plantilla HTML
173
        $this->template = FALSE;
174
175
        header('Content-Type: application/json');
176
        echo json_encode($this->proveedor->get($_REQUEST['datosproveedor']));
177
    }
178
179
    private function new_articulo()
180
    {
181
        /// desactivamos la plantilla HTML
182
        $this->template = FALSE;
183
184
        $art0 = new articulo();
185
        if ($_REQUEST['referencia'] != '') {
186
            $art0->referencia = $_REQUEST['referencia'];
187
        } else {
188
            $art0->referencia = $art0->get_new_referencia();
189
        }
190
191
        if ($art0->exists()) {
192
            $this->results[] = $art0->get($art0->referencia);
193
        } else {
194
            $art0->descripcion = $_REQUEST['descripcion'];
195
            $art0->codbarras = $_REQUEST['codbarras'];
196
            $art0->set_impuesto($_REQUEST['codimpuesto']);
197
            $art0->set_pvp(floatval($_REQUEST['pvp']));
198
            $art0->costemedio = floatval($_REQUEST['coste']);
199
            $art0->preciocoste = floatval($_REQUEST['coste']);
200
201
            $art0->secompra = isset($_POST['secompra']);
202
            $art0->sevende = isset($_POST['sevende']);
203
            $art0->nostock = isset($_POST['nostock']);
204
            $art0->publico = isset($_POST['publico']);
205
206
            if ($_POST['codfamilia'] != '') {
207
                $art0->codfamilia = $_REQUEST['codfamilia'];
208
            }
209
210
            if ($_POST['codfabricante'] != '') {
211
                $art0->codfabricante = $_REQUEST['codfabricante'];
212
            }
213
214
            if ($_POST['refproveedor'] != '' && $_POST['refproveedor'] != $_POST['referencia']) {
215
                $art0->equivalencia = $_POST['refproveedor'];
216
            }
217
218
            if ($art0->save()) {
219
                $art0->coste = floatval($_POST['coste']);
220
                $art0->dtopor = 0;
221
222
                /// buscamos y guardamos el artículo del proveedor
223
                $ap = $this->articulo_prov->get_by($art0->referencia, $_POST['codproveedor'], $_POST['refproveedor']);
224
                if ($ap) {
225
                    $art0->coste = $ap->precio;
226
                    $art0->dtopor = $ap->dto;
227
                } else {
228
                    $ap = new articulo_proveedor();
229
                    $ap->codproveedor = $_POST['codproveedor'];
230
                }
231
                $ap->referencia = $art0->referencia;
232
                $ap->refproveedor = $_POST['refproveedor'];
233
                $ap->descripcion = $art0->descripcion;
234
                $ap->codimpuesto = $art0->codimpuesto;
235
                $ap->precio = floatval($_POST['coste']);
236
237
                /// pero solamente si tiene una refproveedor asignada
238
                if ($_POST['refproveedor'] != '') {
239
                    $ap->save();
240
                }
241
242
                $this->results[] = $art0;
243
            }
244
        }
245
246
        header('Content-Type: application/json');
247
        echo json_encode($this->results);
248
    }
249
250
    private function new_search()
251
    {
252
        /// desactivamos la plantilla HTML
253
        $this->template = FALSE;
254
255
        $stock = new stock();
0 ignored issues
show
Bug introduced by
The type stock 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...
256
        $this->results = $this->search_from_proveedor();
257
258
        /// completamos los datos de la búsqueda
259
        foreach ($this->results as $i => $value) {
260
            $this->results[$i]->query = $this->query;
261
            $this->results[$i]->coste = $value->preciocoste();
262
            $this->results[$i]->dtopor = 0;
263
            $this->results[$i]->cantidad = 1;
264
            $this->results[$i]->coddivisa = $this->empresa->coddivisa;
265
266
            /// si tenemos un codproveedor, ahí que buscar el coste para este proveedor
267
            if (isset($_REQUEST['codproveedor'])) {
268
                $ap = $this->articulo_prov->get_by($value->referencia, $_REQUEST['codproveedor']);
269
                if ($ap) {
270
                    $this->results[$i]->coste = $ap->precio;
271
                    $this->results[$i]->dtopor = $ap->dto;
272
                }
273
            }
274
275
            /// añadimos el stock del almacén y el general
276
            $this->results[$i]->stockalm = $this->results[$i]->stockfis;
277
            if ($this->multi_almacen && isset($_REQUEST['codalmacen'])) {
278
                $this->results[$i]->stockalm = $stock->total_from_articulo($this->results[$i]->referencia, $_REQUEST['codalmacen']);
279
            }
280
281
            /// convertimos la divisa
282
            if (isset($_REQUEST['coddivisa']) && $_REQUEST['coddivisa'] != $this->empresa->coddivisa) {
283
                $this->results[$i]->coddivisa = $_REQUEST['coddivisa'];
284
                $this->results[$i]->coste = $this->divisa_convert($value->coste, $this->empresa->coddivisa, $_REQUEST['coddivisa']);
285
                $this->results[$i]->pvp = $this->divisa_convert($value->pvp, $this->empresa->coddivisa, $_REQUEST['coddivisa']);
286
            }
287
        }
288
289
        /// ejecutamos las funciones de las extensiones
290
        foreach ($this->extensions as $ext) {
291
            if ($ext->type == 'function' && $ext->params == 'new_search') {
292
                $name = $ext->text;
293
                $name($this->db, $this->results);
294
            }
295
        }
296
297
        header('Content-Type: application/json');
298
        echo json_encode($this->results);
299
    }
300
    
301
    
302
    private function generar_ncf($tipo)
303
    {
304
        /// desactivamos la plantilla HTML
305
        $this->template = false;
306
        $tipo_comprobante = ($tipo == 'informal')?'11':'13';
307
        $codalmacen = \filter_input(INPUT_GET, 'codalmacen');
308
        $numero_ncf = $this->ncf_rango->generate($this->empresa->id, $codalmacen, $tipo_comprobante);
309
        if ($numero_ncf['NCF'] == 'NO_DISPONIBLE') {
310
            $ncf_numero = '';
311
        } else {
312
            $ncf_numero = $numero_ncf['NCF'];
313
        }
314
315
        header('Content-Type: application/json');
316
        echo json_encode(array('ncf_numero' => $ncf_numero, 'tipo_comprobante' => $tipo_comprobante));
317
    }
318
319
    private function get_precios_articulo()
320
    {
321
        /// cambiamos la plantilla HTML
322
        $this->template = 'ajax/nueva_compra_precios';
323
324
        $articulo = new articulo();
325
        $this->articulo = $articulo->get($_POST['referencia4precios']);
326
    }
327
328
    private function get_combinaciones_articulo()
329
    {
330
        /// cambiamos la plantilla HTML
331
        $this->template = 'ajax/nueva_compra_combinaciones';
332
333
        $this->results = array();
334
        $comb1 = new articulo_combinacion();
0 ignored issues
show
Bug introduced by
The type articulo_combinacion 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...
335
        foreach ($comb1->all_from_ref($_POST['referencia4combi']) as $com) {
336
            if (isset($this->results[$com->codigo])) {
337
                $this->results[$com->codigo]['desc'] .= ', ' . $com->nombreatributo . ' - ' . $com->valor;
338
                $this->results[$com->codigo]['txt'] .= ', ' . $com->nombreatributo . ' - ' . $com->valor;
339
            } else {
340
                $this->results[$com->codigo] = array(
341
                    'ref' => $_POST['referencia4combi'],
342
                    'desc' => base64_decode($_POST['desc']) . "\n" . $com->nombreatributo . ' - ' . $com->valor,
343
                    'pvp' => floatval($_POST['pvp']) + $com->impactoprecio,
344
                    'dto' => floatval($_POST['dto']),
345
                    'codimpuesto' => $_POST['codimpuesto'],
346
                    'txt' => $com->nombreatributo . ' - ' . $com->valor,
347
                    'codigo' => $com->codigo,
348
                    'stockfis' => $com->stockfis,
349
                );
350
            }
351
        }
352
    }
353
354
    private function nuevo_pedido_proveedor()
355
    {
356
        $continuar = TRUE;
357
358
        $proveedor = $this->proveedor->get($_POST['proveedor']);
359
        if (!$proveedor) {
360
            $this->new_error_msg('Proveedor no encontrado.');
361
            $continuar = FALSE;
362
        }
363
364
        $almacen = $this->almacen->get($_POST['almacen']);
365
        if ($almacen) {
366
            $this->save_codalmacen($_POST['almacen']);
367
        } else {
368
            $this->new_error_msg('Almacén no encontrado.');
369
            $continuar = FALSE;
370
        }
371
372
        $eje0 = new ejercicio();
0 ignored issues
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...
373
        $ejercicio = $eje0->get_by_fecha($_POST['fecha'], FALSE);
374
        if (!$ejercicio) {
375
            $this->new_error_msg('Ejercicio no encontrado.');
376
            $continuar = FALSE;
377
        }
378
379
        $serie = $this->serie->get($_POST['serie']);
380
        if (!$serie) {
381
            $this->new_error_msg('Serie no encontrada.');
382
            $continuar = FALSE;
383
        }
384
385
        $forma_pago = $this->forma_pago->get($_POST['forma_pago']);
386
        if ($forma_pago) {
387
            $this->save_codpago($_POST['forma_pago']);
388
        } else {
389
            $this->new_error_msg('Forma de pago no encontrada.');
390
            $continuar = FALSE;
391
        }
392
393
        $divisa = $this->divisa->get($_POST['divisa']);
394
        if (!$divisa) {
395
            $this->new_error_msg('Divisa no encontrada.');
396
            $continuar = FALSE;
397
        }
398
399
        $pedido = new pedido_proveedor();
0 ignored issues
show
Bug introduced by
The type pedido_proveedor 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...
400
401
        if ($this->duplicated_petition($_POST['petition_id'])) {
402
            $this->new_error_msg('Petición duplicada. Has hecho doble clic sobre el botón guardar
403
               y se han enviado dos peticiones. Mira en <a href="' . $pedido->url() . '">' . FS_PEDIDOS . '</a>
0 ignored issues
show
Bug introduced by
The constant FS_PEDIDOS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
404
               para ver si el ' . FS_PEDIDO . ' se ha guardado correctamente.');
0 ignored issues
show
Bug introduced by
The constant FS_PEDIDO was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
405
            $continuar = FALSE;
406
        }
407
408
        if ($continuar) {
409
            $this->nuevo_documento($pedido, $proveedor, $almacen, $ejercicio, $serie, $forma_pago, $divisa);
410
411
            /// función auxiliar para implementar en los plugins que lo necesiten
412
            if (!fs_generar_numproveedor($pedido)) {
413
                $pedido->numproveedor = $_POST['numproveedor'];
414
            }
415
416
            if ($pedido->save()) {
417
                $art0 = new articulo();
418
                $n = floatval($_POST['numlineas']);
419
                for ($i = 0; $i < $n; $i++) {
420
                    if (isset($_POST['referencia_' . $i])) {
421
                        $linea = new linea_pedido_proveedor();
0 ignored issues
show
Bug introduced by
The type linea_pedido_proveedor 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...
422
                        $linea->idpedido = $pedido->idpedido;
423
                        $this->nueva_linea($linea, $i, $serie, $proveedor);
424
425
                        $articulo = $art0->get($_POST['referencia_' . $i]);
426
                        if ($articulo) {
427
                            $linea->referencia = $articulo->referencia;
428
                            if ($_POST['codcombinacion_' . $i]) {
429
                                $linea->codcombinacion = $_POST['codcombinacion_' . $i];
430
                            }
431
                        }
432
433
                        if ($linea->save()) {
434
                            if ($articulo && isset($_POST['costemedio'])) {
435
                                if ($articulo->costemedio == 0 && $linea->cantidad > 0) {
436
                                    $articulo->costemedio = $linea->pvptotal / $linea->cantidad;
437
                                    $articulo->save();
438
                                }
439
440
                                $this->actualizar_precio_proveedor($pedido->codproveedor, $linea);
441
                            }
442
443
                            if ($linea->irpf > $pedido->irpf) {
444
                                $pedido->irpf = $linea->irpf;
445
                            }
446
                        } else {
447
                            $this->new_error_msg("¡Imposible guardar la linea con referencia: " . $linea->referencia);
448
                            $continuar = FALSE;
449
                        }
450
                    }
451
                }
452
453
                if ($continuar) {
0 ignored issues
show
introduced by
The condition $continuar is always true.
Loading history...
454
                    /// obtenemos los subtotales por impuesto
455
                    foreach ($this->fbase_get_subtotales_documento($pedido->get_lineas()) as $subt) {
456
                        $pedido->neto += $subt['neto'];
457
                        $pedido->totaliva += $subt['iva'];
458
                        $pedido->totalirpf += $subt['irpf'];
459
                        $pedido->totalrecargo += $subt['recargo'];
460
                    }
461
462
                    $pedido->total = round($pedido->neto + $pedido->totaliva - $pedido->totalirpf + $pedido->totalrecargo, FS_NF0);
463
464
                    if (abs(floatval($_POST['atotal']) - $pedido->total) >= .02) {
465
                        $this->new_error_msg("El total difiere entre la vista y el controlador ("
466
                            . $_POST['atotal'] . " frente a " . $pedido->total . "). Debes informar del error.");
467
                        $pedido->delete();
468
                    } else if ($pedido->save()) {
469
                        /// Función de ejecución de tareas post guardado correcto del pedido
470
                        fs_documento_post_save($pedido);
471
472
                        $this->new_message("<a href='" . $pedido->url() . "'>" . ucfirst(FS_PEDIDO) . "</a> guardado correctamente.");
473
                        $this->new_change(ucfirst(FS_PEDIDO) . ' Proveedor ' . $pedido->codigo, $pedido->url(), TRUE);
474
475
                        if ($_POST['redir'] == 'TRUE') {
476
                            header('Location: ' . $pedido->url());
477
                        }
478
                    } else {
479
                        $this->new_error_msg("¡Imposible actualizar el <a href='" . $pedido->url() . "'>" . FS_PEDIDO . "</a>!");
480
                    }
481
                } else if ($pedido->delete()) {
482
                    $this->new_message(ucfirst(FS_PEDIDO) . " eliminado correctamente.");
483
                } else {
484
                    $this->new_error_msg("¡Imposible eliminar el <a href='" . $pedido->url() . "'>" . FS_PEDIDO . "</a>!");
485
                }
486
            } else {
487
                $this->new_error_msg("¡Imposible guardar el " . FS_PEDIDO . "!");
488
            }
489
        }
490
    }
491
492
    private function nuevo_albaran_proveedor()
493
    {
494
        $continuar = TRUE;
495
496
        $proveedor = $this->proveedor->get($_POST['proveedor']);
497
        if (!$proveedor) {
498
            $this->new_error_msg('Proveedor no encontrado.');
499
            $continuar = FALSE;
500
        }
501
502
        $almacen = $this->almacen->get($_POST['almacen']);
503
        if ($almacen) {
504
            $this->save_codalmacen($_POST['almacen']);
505
        } else {
506
            $this->new_error_msg('Almacén no encontrado.');
507
            $continuar = FALSE;
508
        }
509
510
        $eje0 = new ejercicio();
511
        $ejercicio = $eje0->get_by_fecha($_POST['fecha'], FALSE);
512
        if (!$ejercicio) {
513
            $this->new_error_msg('Ejercicio no encontrado.');
514
            $continuar = FALSE;
515
        }
516
517
        $serie = $this->serie->get($_POST['serie']);
518
        if (!$serie) {
519
            $this->new_error_msg('Serie no encontrada.');
520
            $continuar = FALSE;
521
        }
522
523
        $forma_pago = $this->forma_pago->get($_POST['forma_pago']);
524
        if ($forma_pago) {
525
            $this->save_codpago($_POST['forma_pago']);
526
        } else {
527
            $this->new_error_msg('Forma de pago no encontrada.');
528
            $continuar = FALSE;
529
        }
530
531
        $divisa = $this->divisa->get($_POST['divisa']);
532
        if (!$divisa) {
533
            $this->new_error_msg('Divisa no encontrada.');
534
            $continuar = FALSE;
535
        }
536
537
        $albaran = new albaran_proveedor();
0 ignored issues
show
Bug introduced by
The type albaran_proveedor 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...
538
539
        if ($this->duplicated_petition($_POST['petition_id'])) {
540
            $this->new_error_msg('Petición duplicada. Has hecho doble clic sobre el botón guardar
541
               y se han enviado dos peticiones. Mira en <a href="' . $albaran->url() . '">' . FS_ALBARANES . '</a>
0 ignored issues
show
Bug introduced by
The constant FS_ALBARANES was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
542
               para ver si el ' . FS_ALBARAN . ' se ha guardado correctamente.');
0 ignored issues
show
Bug introduced by
The constant FS_ALBARAN was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
543
            $continuar = FALSE;
544
        }
545
546
        if ($continuar) {
547
            $this->nuevo_documento($albaran, $proveedor, $almacen, $ejercicio, $serie, $forma_pago, $divisa);
548
549
            /// función auxiliar para implementar en los plugins que lo necesiten
550
            if (!fs_generar_numproveedor($albaran)) {
551
                $albaran->numproveedor = $_POST['numproveedor'];
552
            }
553
554
            if ($albaran->save()) {
555
                $trazabilidad = FALSE;
556
557
                $art0 = new articulo();
558
                $n = floatval($_POST['numlineas']);
559
                for ($i = 0; $i < $n; $i++) {
560
                    if (isset($_POST['referencia_' . $i])) {
561
                        $linea = new linea_albaran_proveedor();
0 ignored issues
show
Bug introduced by
The type linea_albaran_proveedor 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...
562
                        $linea->idalbaran = $albaran->idalbaran;
563
                        $this->nueva_linea($linea, $i, $serie, $proveedor);
564
565
                        $articulo = $art0->get($_POST['referencia_' . $i]);
566
                        if ($articulo) {
567
                            $linea->referencia = $articulo->referencia;
568
                            if ($articulo->trazabilidad) {
569
                                $trazabilidad = TRUE;
570
                            }
571
572
                            if ($_POST['codcombinacion_' . $i]) {
573
                                $linea->codcombinacion = $_POST['codcombinacion_' . $i];
574
                            }
575
                        }
576
577
                        if ($linea->save()) {
578
                            if ($articulo) {
579
                                if (isset($_POST['stock'])) {
580
                                    $articulo->sum_stock($albaran->codalmacen, $linea->cantidad, isset($_POST['costemedio']), $linea->codcombinacion);
581
                                } else if (isset($_POST['costemedio'])) {
582
                                    /// modificamos virtualmente el stock para que se recalcule el coste medio
583
                                    $articulo->stockfis += $linea->cantidad;
584
                                    $articulo->costemedio = $articulo->get_costemedio();
585
                                    $articulo->stockfis -= $linea->cantidad;
586
                                    $articulo->save();
587
                                }
588
589
                                if (isset($_POST['costemedio'])) {
590
                                    $this->actualizar_precio_proveedor($albaran->codproveedor, $linea);
591
                                }
592
                            }
593
594
                            if ($linea->irpf > $albaran->irpf) {
595
                                $albaran->irpf = $linea->irpf;
596
                            }
597
                        } else {
598
                            $this->new_error_msg("¡Imposible guardar la linea con referencia: " . $linea->referencia);
599
                            $continuar = FALSE;
600
                        }
601
                    }
602
                }
603
604
                if ($continuar) {
0 ignored issues
show
introduced by
The condition $continuar is always true.
Loading history...
605
                    /// obtenemos los subtotales por impuesto
606
                    foreach ($this->fbase_get_subtotales_documento($albaran->get_lineas()) as $subt) {
607
                        $albaran->neto += $subt['neto'];
608
                        $albaran->totaliva += $subt['iva'];
609
                        $albaran->totalirpf += $subt['irpf'];
610
                        $albaran->totalrecargo += $subt['recargo'];
611
                    }
612
613
                    $albaran->total = round($albaran->neto + $albaran->totaliva - $albaran->totalirpf + $albaran->totalrecargo, FS_NF0);
614
615
                    if (abs(floatval($_POST['atotal']) - $albaran->total) >= .02) {
616
                        $this->new_error_msg("El total difiere entre la vista y el controlador (" .
617
                                $_POST['atotal'] . " frente a " . $albaran->total . "). Debes informar del error.");
618
                        $albaran->delete();
619
                    } else if ($albaran->save()) {
620
                        /// Función de ejecución de tareas post guardado correcto del albaran
621
                        fs_documento_post_save($albaran);
622
623
                        $this->new_message("<a href='" . $albaran->url() . "'>" . ucfirst(FS_ALBARAN) . "</a> guardado correctamente.");
624
                        $this->new_change(ucfirst(FS_ALBARAN) . ' Proveedor ' . $albaran->codigo, $albaran->url(), TRUE);
625
626
                        if ($trazabilidad) {
0 ignored issues
show
introduced by
The condition $trazabilidad is always false.
Loading history...
627
                            header('Location: index.php?page=compras_trazabilidad&doc=albaran&id=' . $albaran->idalbaran);
628
                        } else if ($_POST['redir'] == 'TRUE') {
629
                            header('Location: ' . $albaran->url());
630
                        }
631
                    } else {
632
                        $this->new_error_msg("¡Imposible actualizar el <a href='" . $albaran->url() . "'>" . FS_ALBARAN . "</a>!");
633
                    }
634
                } else if ($albaran->delete()) {
635
                    $this->new_message(FS_ALBARAN . " eliminado correctamente.");
636
                } else {
637
                    $this->new_error_msg("¡Imposible eliminar el <a href='" . $albaran->url() . "'>" . FS_ALBARAN . "</a>!");
638
                }
639
            } else {
640
                $this->new_error_msg("¡Imposible guardar el " . FS_ALBARAN . "!");
641
            }
642
        }
643
    }
644
645
    private function nueva_factura_proveedor()
646
    {
647
        $continuar = TRUE;
648
649
        $proveedor = $this->proveedor->get($_POST['proveedor']);
650
        if (!$proveedor) {
651
            $this->new_error_msg('Proveedor no encontrado.');
652
            $continuar = FALSE;
653
        }
654
655
        $almacen = $this->almacen->get($_POST['almacen']);
656
        if ($almacen) {
657
            $this->save_codalmacen($_POST['almacen']);
658
        } else {
659
            $this->new_error_msg('Almacén no encontrado.');
660
            $continuar = FALSE;
661
        }
662
663
        $eje0 = new ejercicio();
664
        $ejercicio = $eje0->get_by_fecha($_POST['fecha']);
665
        if (!$ejercicio) {
666
            $this->new_error_msg('Ejercicio no encontrado o está cerrado.');
667
            $continuar = FALSE;
668
        }
669
670
        $serie = $this->serie->get($_POST['serie']);
671
        if (!$serie) {
672
            $this->new_error_msg('Serie no encontrada.');
673
            $continuar = FALSE;
674
        }
675
676
        $forma_pago = $this->forma_pago->get($_POST['forma_pago']);
677
        if ($forma_pago) {
678
            $this->save_codpago($_POST['forma_pago']);
679
        } else {
680
            $this->new_error_msg('Forma de pago no encontrada.');
681
            $continuar = FALSE;
682
        }
683
684
        $divisa = $this->divisa->get($_POST['divisa']);
685
        if (!$divisa) {
686
            $this->new_error_msg('Divisa no encontrada.');
687
            $continuar = FALSE;
688
        }
689
690
        $factura = new factura_proveedor();
691
692
        if ($this->duplicated_petition($_POST['petition_id'])) {
693
            $this->new_error_msg('Petición duplicada. Has hecho doble clic sobre el botón guardar
694
               y se han enviado dos peticiones. Mira en <a href="' . $factura->url() . '">Facturas</a>
695
               para ver si la factura se ha guardado correctamente.');
696
            $continuar = FALSE;
697
        }
698
699
        if ($continuar) {
700
            $this->nuevo_documento($factura, $proveedor, $almacen, $ejercicio, $serie, $forma_pago, $divisa);
701
            $factura->set_fecha_hora($_POST['fecha'], $_POST['hora']);
702
703
            if ($forma_pago->genrecibos == 'Pagados') {
704
                $factura->pagada = TRUE;
705
            }
706
707
            /// función auxiliar para implementar en los plugins que lo necesiten
708
            if (!fs_generar_numproveedor($factura)) {
709
                $factura->numproveedor = $_POST['numproveedor'];
710
            }
711
712
            $regularizacion = new regularizacion_iva();
0 ignored issues
show
Bug introduced by
The type regularizacion_iva 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...
713
            if ($regularizacion->get_fecha_inside($factura->fecha)) {
714
                $this->new_error_msg("El " . FS_IVA . " de ese periodo ya ha sido regularizado."
715
                        . " No se pueden añadir más facturas en esa fecha.");
716
            } else if ($factura->save()) {
717
                $trazabilidad = FALSE;
718
719
                $art0 = new articulo();
720
                $n = floatval($_POST['numlineas']);
721
                for ($i = 0; $i < $n; $i++) {
722
                    if (isset($_POST['referencia_' . $i])) {
723
                        $linea = new linea_factura_proveedor();
0 ignored issues
show
Bug introduced by
The type linea_factura_proveedor 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...
724
                        $linea->idfactura = $factura->idfactura;
725
                        $this->nueva_linea($linea, $i, $serie, $proveedor);
726
727
                        $articulo = $art0->get($_POST['referencia_' . $i]);
728
                        if ($articulo) {
729
                            $linea->referencia = $articulo->referencia;
730
                            if ($articulo->trazabilidad) {
731
                                $trazabilidad = TRUE;
732
                            }
733
734
                            if ($_POST['codcombinacion_' . $i]) {
735
                                $linea->codcombinacion = $_POST['codcombinacion_' . $i];
736
                            }
737
                        }
738
739
                        if ($linea->save()) {
740
                            if ($articulo) {
741
                                if (isset($_POST['stock'])) {
742
                                    $articulo->sum_stock($factura->codalmacen, $linea->cantidad, isset($_POST['costemedio']), $linea->codcombinacion);
743
                                } else if (isset($_POST['costemedio'])) {
744
                                    /// modificamos virtualmente el stock para que se recalcule el coste medio
745
                                    $articulo->stockfis += $linea->cantidad;
746
                                    $articulo->costemedio = $articulo->get_costemedio();
747
                                    $articulo->stockfis -= $linea->cantidad;
748
                                    $articulo->save();
749
                                }
750
751
                                if (isset($_POST['costemedio'])) {
752
                                    $this->actualizar_precio_proveedor($factura->codproveedor, $linea);
753
                                }
754
                            }
755
756
                            if ($linea->irpf > $factura->irpf) {
757
                                $factura->irpf = $linea->irpf;
758
                            }
759
                        } else {
760
                            $this->new_error_msg("¡Imposible guardar la linea con referencia: " . $linea->referencia);
761
                            $continuar = FALSE;
762
                        }
763
                    }
764
                }
765
766
                if ($continuar) {
0 ignored issues
show
introduced by
The condition $continuar is always true.
Loading history...
767
                    /// obtenemos los subtotales por impuesto
768
                    foreach ($this->fbase_get_subtotales_documento($factura->get_lineas()) as $subt) {
769
                        $factura->neto += $subt['neto'];
770
                        $factura->totaliva += $subt['iva'];
771
                        $factura->totalirpf += $subt['irpf'];
772
                        $factura->totalrecargo += $subt['recargo'];
773
                    }
774
775
                    $factura->total = round($factura->neto + $factura->totaliva - $factura->totalirpf + $factura->totalrecargo, FS_NF0);
776
777
                    if (abs(floatval($_POST['atotal']) - $factura->total) >= .02) {
778
                        $this->new_error_msg("El total difiere entre el controlador y la vista (" .
779
                                $factura->total . " frente a " . $_POST['atotal'] . "). Debes informar del error.");
780
                        $factura->delete();
781
                    } else if ($factura->save()) {
782
                        $this->fbase_generar_asiento($factura, FALSE);
783
784
                        /// Función de ejecución de tareas post guardado correcto de la factura
785
                        fs_documento_post_save($factura);
786
787
                        $this->new_message("<a href='" . $factura->url() . "'>Factura</a> guardada correctamente.");
788
                        $this->new_change('Factura Proveedor ' . $factura->codigo, $factura->url(), TRUE);
789
790
                        if ($trazabilidad) {
0 ignored issues
show
introduced by
The condition $trazabilidad is always false.
Loading history...
791
                            header('Location: index.php?page=compras_trazabilidad&doc=factura&id=' . $factura->idfactura);
792
                        } else if ($_POST['redir'] == 'TRUE') {
793
                            header('Location: ' . $factura->url());
794
                        }
795
                    } else {
796
                        $this->new_error_msg("¡Imposible actualizar la <a href='" . $factura->url() . "'>factura</a>!");
797
                    }
798
                } else if ($factura->delete()) {
799
                    $this->new_message("Factura eliminada correctamente.");
800
                } else {
801
                    $this->new_error_msg("¡Imposible eliminar la <a href='" . $factura->url() . "'>factura</a>!");
802
                }
803
            } else {
804
                $this->new_error_msg("¡Imposible guardar la factura!");
805
            }
806
        }
807
    }
808
809
    /**
810
     * Actualiza los datos de artículos de proveedor en base a las líneas del documento de compra.
811
     * @param string $codproveedor
812
     * @param linea_albaran_proveedor $linea
813
     */
814
    private function actualizar_precio_proveedor($codproveedor, $linea)
815
    {
816
        if (!is_null($linea->referencia)) {
817
            $artp = $this->articulo_prov->get_by($linea->referencia, $codproveedor, $linea->referencia);
818
            if (!$artp) {
819
                $artp = new articulo_proveedor();
820
                $artp->codproveedor = $codproveedor;
821
                $artp->referencia = $linea->referencia;
822
                $artp->refproveedor = $linea->referencia;
823
                $artp->codimpuesto = $linea->codimpuesto;
824
                $artp->descripcion = $linea->descripcion;
825
            }
826
827
            if ($artp->referencia == $linea->referencia) {
828
                $artp->precio = $linea->pvpunitario;
829
                $artp->dto = $linea->dtopor;
830
                $artp->save();
831
            }
832
        }
833
    }
834
835
    private function search_from_proveedor()
836
    {
837
        $artilist = array();
838
        $query = $this->articulo_prov->no_html(mb_strtolower($this->query, 'UTF8'));
839
        $sql = "SELECT * FROM articulos WHERE bloqueado = false";
840
        $separador = ' AND';
841
842
        if ($_REQUEST['codfamilia'] != '') {
843
            $sql .= $separador . " codfamilia = " . $this->articulo_prov->var2str($_REQUEST['codfamilia']);
844
        }
845
846
        if ($_REQUEST['codfabricante'] != '') {
847
            $sql .= $separador . " codfabricante = " . $this->articulo_prov->var2str($_REQUEST['codfabricante']);
848
        }
849
850
        if (isset($_REQUEST['con_stock'])) {
851
            $sql .= $separador . " stockfis > 0";
852
        }
853
854
        if (isset($_REQUEST['solo_proveedor']) && isset($_REQUEST['codproveedor'])) {
855
            $sql .= $separador . " referencia IN (SELECT referencia FROM articulosprov WHERE codproveedor = "
856
                    . $this->articulo_prov->var2str($_REQUEST['codproveedor']) . ")";
857
        }
858
859
        if (is_numeric($query)) {
860
            $sql .= $separador . " (referencia = " . $this->articulo_prov->var2str($query)
861
                    . " OR referencia LIKE '%" . $query . "%'"
862
                    . " OR partnumber LIKE '%" . $query . "%'"
863
                    . " OR equivalencia LIKE '%" . $query . "%'"
864
                    . " OR descripcion LIKE '%" . $query . "%'"
865
                    . " OR codbarras = " . $this->articulo_prov->var2str($query) . ")";
866
        } else {
867
            /// ¿La búsqueda son varias palabras?
868
            $palabras = explode(' ', $query);
869
            if (count($palabras) > 1) {
870
                $sql .= $separador . " (lower(referencia) = " . $this->articulo_prov->var2str($query)
871
                        . " OR lower(referencia) LIKE '%" . $query . "%'"
872
                        . " OR lower(partnumber) LIKE '%" . $query . "%'"
873
                        . " OR lower(equivalencia) LIKE '%" . $query . "%'"
874
                        . " OR (";
875
876
                foreach ($palabras as $i => $pal) {
877
                    if ($i == 0) {
878
                        $sql .= "lower(descripcion) LIKE '%" . $pal . "%'";
879
                    } else {
880
                        $sql .= " AND lower(descripcion) LIKE '%" . $pal . "%'";
881
                    }
882
                }
883
884
                $sql .= "))";
885
            } else {
886
                $sql .= $separador . " (lower(referencia) = " . $this->articulo_prov->var2str($query)
887
                        . " OR lower(referencia) LIKE '%" . $query . "%'"
888
                        . " OR lower(partnumber) LIKE '%" . $query . "%'"
889
                        . " OR lower(equivalencia) LIKE '%" . $query . "%'"
890
                        . " OR lower(codbarras) = " . $this->articulo_prov->var2str($query)
891
                        . " OR lower(descripcion) LIKE '%" . $query . "%')";
892
            }
893
        }
894
895
        if (strtolower(FS_DB_TYPE) == 'mysql') {
0 ignored issues
show
Bug introduced by
The constant FS_DB_TYPE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
896
            $sql .= " ORDER BY lower(referencia) ASC";
897
        } else {
898
            $sql .= " ORDER BY referencia ASC";
899
        }
900
901
        $data = $this->db->select_limit($sql, FS_ITEM_LIMIT, 0);
0 ignored issues
show
Bug introduced by
The constant FS_ITEM_LIMIT was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
902
        if ($data) {
903
            foreach ($data as $a) {
904
                $artilist[] = new articulo($a);
905
            }
906
        }
907
908
        return $artilist;
909
    }
910
911
    private function nuevo_documento(&$documento, $proveedor, $almacen, $ejercicio, $serie, $forma_pago, $divisa)
912
    {
913
        $documento->fecha = $_POST['fecha'];
914
        $documento->hora = $_POST['hora'];
915
        $documento->codproveedor = $proveedor->codproveedor;
916
        $documento->nombre = $_POST['nombre'];
917
        $documento->cifnif = $_POST['cifnif'];
918
        $documento->codalmacen = $almacen->codalmacen;
919
        $documento->codejercicio = $ejercicio->codejercicio;
920
        $documento->codserie = $serie->codserie;
921
        $documento->codpago = $forma_pago->codpago;
922
        $documento->coddivisa = $divisa->coddivisa;
923
        $documento->tasaconv = $divisa->tasaconv_compra;
924
925
        if ($_POST['tasaconv'] != '') {
926
            $documento->tasaconv = floatval($_POST['tasaconv']);
927
        }
928
929
        $documento->codagente = $this->agente->codagente;
930
        $documento->observaciones = $_POST['observaciones'];
931
    }
932
933
    private function nueva_linea(&$linea, $i, $serie, $proveedor)
934
    {
935
        $linea->descripcion = $_POST['desc_' . $i];
936
937
        if (!$serie->siniva && $proveedor->regimeniva != 'Exento') {
938
            $imp0 = $this->impuesto->get_by_iva($_POST['iva_' . $i]);
939
            if ($imp0) {
940
                $linea->codimpuesto = $imp0->codimpuesto;
941
                $linea->iva = floatval($_POST['iva_' . $i]);
942
                $linea->recargo = floatval(fs_filter_input_post('recargo_' . $i, 0));
0 ignored issues
show
Bug introduced by
The function fs_filter_input_post was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

942
                $linea->recargo = floatval(/** @scrutinizer ignore-call */ fs_filter_input_post('recargo_' . $i, 0));
Loading history...
943
            } else {
944
                $linea->iva = floatval($_POST['iva_' . $i]);
945
                $linea->recargo = floatval(fs_filter_input_post('recargo_' . $i, 0));
946
            }
947
        }
948
949
        $linea->irpf = floatval(fs_filter_input_post('irpf_' . $i, 0));
950
        $linea->pvpunitario = floatval($_POST['pvp_' . $i]);
951
        $linea->cantidad = floatval($_POST['cantidad_' . $i]);
952
        $linea->dtopor = floatval(fs_filter_input_post('dto_' . $i, 0));
953
        $linea->pvpsindto = $linea->cantidad * $linea->pvpunitario;
954
        $linea->pvptotal = $linea->cantidad * $linea->pvpunitario * (100 - $linea->dtopor) / 100;
955
    }
956
}
957