tpv_recambios   F
last analyzed

Complexity

Total Complexity 122

Size/Duplication

Total Lines 815
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 444
c 1
b 0
f 0
dl 0
loc 815
rs 2
wmc 122

20 Methods

Rating   Name   Duplication   Size   Complexity  
A imprimir_ticket_regalo() 0 14 4
A generar_asiento() 0 10 2
C new_search_postprocess() 0 33 12
A comprobar_opciones() 0 25 4
F private_core() 0 120 29
A info_factura_dgii() 0 6 1
B new_search() 0 38 8
A cerrar_caja() 0 29 3
A get_precios_articulo() 0 6 1
A get_tarifas_articulo() 0 17 3
A generar_comprobante_fiscal() 0 14 2
F nueva_factura_cliente() 0 198 33
A get_combinaciones_articulo() 0 33 5
A buscar_cliente() 0 14 2
A reimprimir_ticket() 0 19 4
A imprimir_ticket() 0 17 4
A share_extensions() 0 8 1
A abrir_caja() 0 7 2
A __construct() 0 3 1
A datos_cliente() 0 7 1

How to fix   Complexity   

Complex Class

Complex classes like tpv_recambios 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 tpv_recambios, and based on these observations, apply Extract Interface, too.

1
<?php
2
/*
3
 * This file is part of facturacion_base
4
 * Copyright (C) 2013-2018  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/republica_dominicana/extras/rd_controller.php';
21
22
class tpv_recambios extends rd_controller
23
{
24
25
    /**
26
     *
27
     * @var 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...
28
     */
29
    public $agente;
30
31
    /**
32
     *
33
     * @var 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...
34
     */
35
    public $almacen;
36
37
    /**
38
     *
39
     * @var articulo|bool
40
     */
41
    public $articulo;
42
43
    /**
44
     *
45
     * @var caja|bool
0 ignored issues
show
Bug introduced by
The type caja 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...
46
     */
47
    public $caja;
48
49
    /**
50
     *
51
     * @var cliente
0 ignored issues
show
Bug introduced by
The type 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...
52
     */
53
    public $cliente;
54
55
    /**
56
     *
57
     * @var cliente|bool
58
     */
59
    public $cliente_s;
60
61
    /**
62
     *
63
     * @var 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...
64
     */
65
    public $divisa;
66
67
    /**
68
     *
69
     * @var 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...
70
     */
71
    public $ejercicio;
72
73
    /**
74
     *
75
     * @var articulo[]
76
     */
77
    public $equivalentes;
78
79
    /**
80
     *
81
     * @var 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...
82
     */
83
    public $fabricante;
84
85
    /**
86
     *
87
     * @var 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...
88
     */
89
    public $familia;
90
91
    /**
92
     *
93
     * @var 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...
94
     */
95
    public $forma_pago;
96
97
    /**
98
     *
99
     * @var bool
100
     */
101
    public $imprimir_descripciones;
102
103
    /**
104
     *
105
     * @var bool
106
     */
107
    public $imprimir_observaciones;
108
109
    /**
110
     *
111
     * @var 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...
112
     */
113
    public $impuesto;
114
115
    /**
116
     *
117
     * @var articulo[]
118
     */
119
    public $results;
120
121
    /**
122
     *
123
     * @var 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...
124
     */
125
    public $serie;
126
127
    /**
128
     *
129
     * @var terminal_caja|bool
130
     */
131
    public $terminal;
132
133
    /**
134
     *
135
     * @var array
136
     */
137
    public $ultimas_compras;
138
139
    /**
140
     *
141
     * @var array
142
     */
143
    public $ultimas_ventas;
144
    public $ncf_numero;
145
146
    public function __construct()
147
    {
148
        parent::__construct(__CLASS__, 'TPV Genérico', 'TPV');
149
    }
150
151
    protected function private_core()
152
    {
153
        parent::private_core();
154
        $this->share_extensions();
155
156
        $this->articulo = new articulo();
157
        $this->cliente = new cliente();
158
        $this->cliente_s = FALSE;
159
        $this->fabricante = new fabricante();
160
        $this->familia = new familia();
161
        $this->impuesto = new impuesto();
162
        $this->results = [];
163
164
        if (isset($_REQUEST['buscar_cliente'])) {
165
            $this->buscar_cliente();
166
        } else if (isset($_REQUEST['datoscliente'])) {
167
            $this->datos_cliente();
168
        } else if ($this->query != '') {
169
            $this->new_search();
170
        } else if (isset($_REQUEST['referencia4precios'])) {
171
            $this->get_precios_articulo();
172
        } else if (isset($_POST['referencia4combi'])) {
173
            $this->get_combinaciones_articulo();
174
        } else {
175
            $this->agente = $this->user->get_agente();
176
            $this->almacen = new almacen();
177
            $this->divisa = new divisa();
178
            $this->ejercicio = new ejercicio();
179
            $this->forma_pago = new forma_pago();
180
            $this->serie = new serie();
181
182
            $this->comprobar_opciones();
183
184
            if ($this->agente) {
185
                $this->caja = FALSE;
186
                $this->terminal = FALSE;
187
                $caja = new caja();
188
                $terminal0 = new terminal_caja();
189
                foreach ($caja->all_by_agente($this->agente->codagente) as $cj) {
190
                    if ($cj->abierta()) {
191
                        $this->caja = $cj;
192
                        $this->terminal = $terminal0->get($cj->fs_id);
193
                        break;
194
                    }
195
                }
196
197
                if (!$this->caja) {
198
                    if (isset($_POST['terminal'])) {
199
                        $this->terminal = $terminal0->get($_POST['terminal']);
200
                        if (!$this->terminal) {
201
                            $this->new_error_msg('Terminal no encontrado.');
202
                        } else if ($this->terminal->disponible()) {
203
                            $this->caja = new caja();
204
                            $this->caja->fs_id = $this->terminal->id;
205
                            $this->caja->codagente = $this->agente->codagente;
206
                            $this->caja->dinero_inicial = floatval($_POST['d_inicial']);
207
                            $this->caja->dinero_fin = floatval($_POST['d_inicial']);
208
                            if ($this->caja->save()) {
209
                                $this->new_message("Caja iniciada con " . $this->show_precio($this->caja->dinero_inicial));
210
                            } else {
211
                                $this->new_error_msg("¡Imposible guardar los datos de caja!");
212
                            }
213
                        } else {
214
                            $this->new_error_msg('El terminal ya no está disponible.');
215
                        }
216
                    } else if (isset($_GET['terminal'])) {
217
                        $this->terminal = $terminal0->get($_GET['terminal']);
218
                        if ($this->terminal) {
219
                            $this->terminal->abrir_cajon();
220
                            $this->terminal->save();
221
                        } else {
222
                            $this->new_error_msg('Terminal no encontrado.');
223
                        }
224
                    }
225
                }
226
227
                if ($this->caja) {
228
                    if (isset($_POST['cliente'])) {
229
                        $this->cliente_s = $this->cliente->get($_POST['cliente']);
230
                    } else if ($this->terminal) {
231
                        $this->cliente_s = $this->cliente->get($this->terminal->codcliente);
232
                    }
233
234
                    if (!$this->cliente_s) {
235
                        foreach ($this->cliente->all() as $cli) {
236
                            $this->cliente_s = $cli;
237
                            break;
238
                        }
239
                    }
240
241
                    if (isset($_GET['abrir_caja'])) {
242
                        $this->abrir_caja();
243
                    } else if (isset($_GET['cerrar_caja'])) {
244
                        $this->cerrar_caja();
245
                    } else if (isset($_POST['cliente'])) {
246
                        if (intval($_POST['numlineas']) > 0) {
247
                            $this->nueva_factura_cliente();
248
                        }
249
                    } else if (isset($_GET['reticket'])) {
250
                        $this->reimprimir_ticket();
251
                    } elseif (isset($_REQUEST['generar_comprobante'])) {
252
                        $this->generar_comprobante_fiscal();
253
                    }
254
255
                    if ($this->cliente_s) {
256
                        //Elegimos el número de NCF
257
                        $this->cliente_s->tipo_comprobante = $this->ncf_entidad_tipo->get($this->empresa->id, $this->cliente_s->codcliente, 'CLI')->tipo_comprobante;
258
                        //Elegimos el tipo de comprobante a generar
259
                        $numero_ncf = $this->generar_numero_ncf($this->empresa->id, $this->terminal->codalmacen, $this->cliente_s->tipo_comprobante, $this->cliente_s->codpago);
260
                        if ($numero_ncf['NCF'] == 'NO_DISPONIBLE') {
261
                            $this->ncf_numero = '';
262
                        } else {
263
                            $this->ncf_numero = $numero_ncf['NCF'];
264
                        }
265
                    }
266
                } else {
267
                    $this->results = $terminal0->disponibles();
268
                }
269
            } else {
270
                $this->new_error_msg('No tienes un <a href="' . $this->user->url() . '">agente asociado</a>
271
               a tu usuario, y por tanto no puedes hacer tickets.');
272
            }
273
        }
274
    }
275
276
    private function buscar_cliente()
277
    {
278
        /// desactivamos la plantilla HTML
279
        $this->template = false;
280
281
        $json = array();
282
        foreach ($this->cliente->search($_REQUEST['buscar_cliente']) as $cli) {
283
            $tipo_comprobante_d = $this->ncf_entidad_tipo->get($this->empresa->id, $cli->codcliente, 'CLI');
284
            $cli->tipo_comprobante = $tipo_comprobante_d->tipo_comprobante;
285
            $json[] = array('value' => $cli->razonsocial, 'data' => $cli->codcliente, 'full' => $cli);
286
        }
287
288
        header('Content-Type: application/json');
289
        echo json_encode(array('query' => $_REQUEST['buscar_cliente'], 'suggestions' => $json));
290
    }
291
292
    private function comprobar_opciones()
293
    {
294
        $fsvar = new fs_var();
0 ignored issues
show
Bug introduced by
The type fs_var 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...
295
296
        $this->imprimir_descripciones = ($fsvar->simple_get('tpv_gen_descripcion') == '1');
297
        $this->imprimir_observaciones = ($fsvar->simple_get('tpv_gen_observaciones') == '1');
298
299
        /**
300
         * Si se detectan datos por post de que se está creando una factura, modificamos las opciones
301
         */
302
        if (isset($_POST['cliente'])) {
303
            if (isset($_POST['imprimir_desc'])) {
304
                $this->imprimir_descripciones = TRUE;
305
                $fsvar->simple_save('tpv_gen_descripcion', '1');
306
            } else {
307
                $this->imprimir_descripciones = FALSE;
308
                $fsvar->simple_delete('tpv_gen_descripcion');
309
            }
310
311
            if (isset($_POST['imprimir_obs'])) {
312
                $this->imprimir_observaciones = TRUE;
313
                $fsvar->simple_save('tpv_gen_observaciones', '1');
314
            } else {
315
                $this->imprimir_observaciones = FALSE;
316
                $fsvar->simple_delete('tpv_gen_observaciones');
317
            }
318
        }
319
    }
320
321
    private function generar_comprobante_fiscal()
322
    {
323
        /// desactivamos la plantilla HTML
324
        $this->template = false;
325
        $tipo_comprobante = \filter_input(INPUT_GET, 'generar_comprobante');
326
        $numero_ncf = $this->generar_numero_ncf($this->empresa->id, $this->terminal->codalmacen, $tipo_comprobante, $this->cliente_s->codpago);
0 ignored issues
show
Bug introduced by
The property codpago does not exist on boolean.
Loading history...
327
        if ($numero_ncf['NCF'] == 'NO_DISPONIBLE') {
328
            $this->ncf_numero = '';
329
        } else {
330
            $this->ncf_numero = $numero_ncf['NCF'];
331
        }
332
333
        header('Content-Type: application/json');
334
        echo json_encode(array('ncf_numero' => $this->ncf_numero, 'tipo_comprobante' => $tipo_comprobante, 'terminal' => $this->terminal, 'cliente' => $this->cliente_s));
335
    }
336
337
    private function datos_cliente()
338
    {
339
        /// desactivamos la plantilla HTML
340
        $this->template = FALSE;
341
342
        header('Content-Type: application/json');
343
        echo json_encode($this->cliente->get($_REQUEST['datoscliente']));
344
    }
345
346
    private function new_search()
347
    {
348
        /// desactivamos la plantilla HTML
349
        $this->template = FALSE;
350
351
        $codfamilia = '';
352
        if (isset($_REQUEST['codfamilia'])) {
353
            $codfamilia = $_REQUEST['codfamilia'];
354
        }
355
        $codfabricante = '';
356
        if (isset($_REQUEST['codfabricante'])) {
357
            $codfabricante = $_REQUEST['codfabricante'];
358
        }
359
        $con_stock = isset($_REQUEST['con_stock']);
360
        $this->results = $this->articulo->search($this->query, 0, $codfamilia, $con_stock, $codfabricante);
361
362
        /// buscamos por código de barras de la combinación
363
        $combi0 = 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...
364
        foreach ($combi0->search($this->query) as $combi) {
365
            $articulo = $this->articulo->get($combi->referencia);
366
            if ($articulo) {
367
                $articulo->codbarras = $combi->codbarras;
368
                $this->results[] = $articulo;
369
            }
370
        }
371
372
        /// ejecutamos las funciones de las extensiones
373
        foreach ($this->extensions as $ext) {
374
            if ($ext->type == 'function' && $ext->params == 'new_search') {
375
                $name = $ext->text;
376
                $name($this->db, $this->results);
377
            }
378
        }
379
380
        $this->new_search_postprocess();
381
382
        header('Content-Type: application/json');
383
        echo json_encode($this->results);
384
    }
385
386
    private function new_search_postprocess()
387
    {
388
        $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...
389
390
        /// añadimos el descuento y la cantidad
391
        foreach ($this->results as $i => $value) {
392
            $this->results[$i]->query = $this->query;
393
            $this->results[$i]->dtopor = 0;
394
            $this->results[$i]->cantidad = 1;
395
396
            $this->results[$i]->stockalm = $value->stockfis;
397
            if ($this->multi_almacen && isset($_REQUEST['codalmacen'])) {
398
                $this->results[$i]->stockalm = $stock->total_from_articulo($this->results[$i]->referencia, $_REQUEST['codalmacen']);
399
            }
400
        }
401
402
        if (isset($_REQUEST['codcliente'])) {
403
            $cliente = $this->cliente->get($_REQUEST['codcliente']);
404
            $tarifa0 = new tarifa();
0 ignored issues
show
Bug introduced by
The type tarifa 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...
405
406
            if ($cliente && $cliente->codtarifa) {
407
                $tarifa = $tarifa0->get($cliente->codtarifa);
408
                if ($tarifa) {
409
                    $tarifa->set_precios($this->results);
410
                }
411
            } else if ($cliente && $cliente->codgrupo) {
412
                $grupo0 = new grupo_clientes();
0 ignored issues
show
Bug introduced by
The type grupo_clientes 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...
413
414
                $grupo = $grupo0->get($cliente->codgrupo);
415
                if ($grupo) {
416
                    $tarifa = $tarifa0->get($grupo->codtarifa);
417
                    if ($tarifa) {
418
                        $tarifa->set_precios($this->results);
419
                    }
420
                }
421
            }
422
        }
423
    }
424
425
    private function get_precios_articulo()
426
    {
427
        /// cambiamos la plantilla HTML
428
        $this->template = 'ajax/tpv_recambios_precios';
429
430
        $this->articulo = $this->articulo->get($_REQUEST['referencia4precios']);
431
    }
432
433
    private function get_combinaciones_articulo()
434
    {
435
        /// cambiamos la plantilla HTML
436
        $this->template = 'ajax/tpv_recambios_combinaciones';
437
438
        $impuestos = $this->impuesto->all();
439
440
        $this->results = [];
441
        $comb1 = new articulo_combinacion();
442
        foreach ($comb1->all_from_ref($_POST['referencia4combi']) as $com) {
443
            if (isset($this->results[$com->codigo])) {
444
                $this->results[$com->codigo]['desc'] .= ', ' . $com->nombreatributo . ' - ' . $com->valor;
445
                $this->results[$com->codigo]['txt'] .= ', ' . $com->nombreatributo . ' - ' . $com->valor;
446
            } else {
447
                $iva = 0;
448
                foreach ($impuestos as $imp) {
449
                    if ($imp->codimpuesto == $_POST['codimpuesto']) {
450
                        $iva = $imp->iva;
451
                        break;
452
                    }
453
                }
454
455
                $this->results[$com->codigo] = array(
456
                    'ref' => $_POST['referencia4combi'],
457
                    'desc' => base64_decode($_POST['desc']) . "\n" . $com->nombreatributo . ' - ' . $com->valor,
458
                    'pvp' => floatval($_POST['pvp']) + $com->impactoprecio,
459
                    'dto' => floatval($_POST['dto']),
460
                    'codimpuesto' => $_POST['codimpuesto'],
461
                    'iva' => $iva,
462
                    'cantidad' => floatval($_POST['cantidad']),
463
                    'txt' => $com->nombreatributo . ' - ' . $com->valor,
464
                    'codigo' => $com->codigo,
465
                    'stockfis' => $com->stockfis,
466
                );
467
            }
468
        }
469
    }
470
471
    public function get_tarifas_articulo($ref)
472
    {
473
        $tarlist = [];
474
        $articulo = new articulo();
475
        $tarifa = new tarifa();
476
477
        foreach ($tarifa->all() as $tar) {
478
            $art = $articulo->get($ref);
479
            if ($art) {
480
                $art->dtopor = 0;
481
                $aux = array($art);
482
                $tar->set_precios($aux);
483
                $tarlist[] = $aux[0];
484
            }
485
        }
486
487
        return $tarlist;
488
    }
489
490
    private function nueva_factura_cliente()
491
    {
492
        $continuar = TRUE;
493
494
        $ejercicio = $this->ejercicio->get_by_fecha($_POST['fecha']);
495
        if (!$ejercicio) {
496
            $this->new_error_msg('Ejercicio no encontrado o está cerrado.');
497
            $continuar = FALSE;
498
        }
499
500
        $serie = $this->serie->get($_POST['serie']);
501
        if (!$serie) {
502
            $this->new_error_msg('Serie no encontrada.');
503
            $continuar = FALSE;
504
        }
505
506
        $forma_pago = $this->forma_pago->get($_POST['forma_pago']);
507
        if ($forma_pago) {
508
            $this->save_codpago($_POST['forma_pago']);
509
        } else {
510
            $this->new_error_msg('Forma de pago no encontrada.');
511
            $continuar = FALSE;
512
        }
513
514
        $divisa = $this->divisa->get($_POST['divisa']);
515
        if (!$divisa) {
516
            $this->new_error_msg('Divisa no encontrada.');
517
            $continuar = FALSE;
518
        }
519
520
        $factura = new factura_cliente();
521
522
        if ($this->duplicated_petition($_POST['petition_id'])) {
523
            $this->new_error_msg('Petición duplicada. Has hecho doble clic sobre el botón Guardar
524
               y se han enviado dos peticiones. Mira en <a href="' . $factura->url() . '">Facturas</a>
525
               para ver si la factura se ha guardado correctamente.');
526
            $continuar = FALSE;
527
        }
528
529
        if ($continuar) {
530
            $factura->codejercicio = $ejercicio->codejercicio;
531
            $factura->codserie = $serie->codserie;
532
            $factura->set_fecha_hora($_POST['fecha'], $factura->hora);
533
534
            $factura->codalmacen = $_POST['almacen'];
535
            $factura->codpago = $forma_pago->codpago;
536
            $factura->coddivisa = $divisa->coddivisa;
537
            $factura->tasaconv = $divisa->tasaconv;
538
539
            if ($_POST['tasaconv'] != '') {
540
                $factura->tasaconv = floatval($_POST['tasaconv']);
541
            }
542
543
            // Cambia el agente?
544
            $factura->codagente = isset($_POST['codagente']) ? $_POST['codagente'] : $this->agente->codagente;
545
            $factura->observaciones = $_POST['observaciones'];
546
            $factura->porcomision = $this->agente->porcomision;
547
548
            if ($forma_pago->genrecibos == 'Pagados') {
549
                $factura->pagada = TRUE;
550
            }
551
552
            $factura->vencimiento = $forma_pago->calcular_vencimiento($factura->fecha, $this->cliente_s->diaspago);
0 ignored issues
show
Bug introduced by
The property diaspago does not exist on boolean.
Loading history...
553
554
            $factura->codcliente = $this->cliente_s->codcliente;
0 ignored issues
show
Bug introduced by
The property codcliente does not exist on boolean.
Loading history...
555
            $factura->cifnif = $_POST['cifnif'];
556
            $factura->nombrecliente = $_POST['nombrecliente'];
557
            $factura->ciudad = $this->empresa->ciudad;
558
            $factura->codpais = $this->empresa->codpais;
559
            $factura->codpostal = $this->empresa->codpostal;
560
            $factura->provincia = $this->empresa->provincia;
561
562
            foreach ($this->cliente_s->get_direcciones() as $d) {
563
                if ($d->domfacturacion) {
564
                    $factura->apartado = $d->apartado;
565
                    $factura->ciudad = $d->ciudad;
566
                    $factura->coddir = $d->id;
567
                    $factura->codpais = $d->codpais;
568
                    $factura->codpostal = $d->codpostal;
569
                    $factura->direccion = $d->direccion;
570
                    $factura->provincia = $d->provincia;
571
                    break;
572
                }
573
            }
574
575
            /// función auxiliar para implementar en los plugins que lo necesiten
576
            if (!fs_generar_numero2($factura)) {
577
                $factura->numero2 = $_POST['numero2'];
578
            }
579
580
            $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...
581
            if ($regularizacion->get_fecha_inside($factura->fecha)) {
582
                $this->new_error_msg("El " . FS_IVA . " de ese periodo ya ha sido regularizado."
583
                        . " No se pueden añadir más facturas en esa fecha.");
584
            } else if ($factura->save()) {
585
                $trazabilidad = FALSE;
586
                $n = floatval($_POST['numlineas']);
587
                for ($i = 1; $i <= $n; $i++) {
588
                    if (isset($_POST['referencia_' . $i])) {
589
                        $articulo = $this->articulo->get($_POST['referencia_' . $i]);
590
                        if ($articulo) {
591
                            $linea = new linea_factura_cliente();
0 ignored issues
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...
592
                            $linea->idfactura = $factura->idfactura;
593
                            $linea->referencia = $articulo->referencia;
594
                            $linea->descripcion = $_POST['desc_' . $i];
595
596
                            if (!$serie->siniva || $this->cliente_s->regimeniva != 'Exento') {
0 ignored issues
show
Bug introduced by
The property regimeniva does not exist on boolean.
Loading history...
597
                                $linea->codimpuesto = $articulo->codimpuesto;
598
                                $linea->iva = floatval($_POST['iva_' . $i]);
599
                                $linea->recargo = floatval($_POST['recargo_' . $i]);
600
                            }
601
602
                            $linea->irpf = floatval($_POST['irpf_' . $i]);
603
                            $linea->pvpunitario = floatval($_POST['pvp_' . $i]);
604
                            $linea->cantidad = floatval($_POST['cantidad_' . $i]);
605
                            $linea->dtopor = floatval($_POST['dto_' . $i]);
606
                            $linea->pvpsindto = $linea->pvpunitario * $linea->cantidad;
607
                            $linea->pvptotal = $linea->cantidad * $linea->pvpunitario * (100 - $linea->dtopor) / 100;
608
609
                            if ($articulo) {
610
                                if ($articulo->trazabilidad) {
611
                                    $trazabilidad = TRUE;
612
                                }
613
614
                                if ($_POST['codcombinacion_' . $i]) {
615
                                    $linea->codcombinacion = $_POST['codcombinacion_' . $i];
616
                                }
617
                            }
618
619
                            if ($linea->save()) {
620
                                /// descontamos del stock
621
                                $articulo->sum_stock($factura->codalmacen, 0 - $linea->cantidad, FALSE, $linea->codcombinacion);
622
623
                                if ($linea->irpf > $factura->irpf) {
624
                                    $factura->irpf = $linea->irpf;
625
                                }
626
                            } else {
627
                                $this->new_error_msg("¡Imposible guardar la linea con referencia: " . $linea->referencia);
628
                                $continuar = FALSE;
629
                            }
630
                        } else {
631
                            $this->new_error_msg("Artículo no encontrado: " . $_POST['referencia_' . $i]);
632
                            $continuar = FALSE;
633
                        }
634
                    }
635
                }
636
637
                if ($continuar) {
0 ignored issues
show
introduced by
The condition $continuar is always true.
Loading history...
638
                    /// obtenemos los subtotales por impuesto
639
                    foreach ($this->fbase_get_subtotales_documento($factura->get_lineas()) as $subt) {
640
                        $factura->netosindto += $subt['netosindto'];
641
                        $factura->neto += $subt['neto'];
642
                        $factura->totaliva += $subt['iva'];
643
                        $factura->totalirpf += $subt['irpf'];
644
                        $factura->totalrecargo += $subt['recargo'];
645
                    }
646
647
                    $factura->total = round($factura->neto + $factura->totaliva - $factura->totalirpf + $factura->totalrecargo, FS_NF0);
648
649
                    if (abs(floatval($_POST['tpv_total2']) - $factura->total) >= .02) {
650
                        $this->new_error_msg("El total difiere entre la vista y el controlador (" . $_POST['tpv_total2'] .
651
                                " frente a " . $factura->total . "). Debes informar del error.");
652
                        $factura->delete();
653
                    } else if ($factura->save()) {
654
                        $this->generar_asiento($factura);
655
656
                        /// Función de ejecución de tareas post guardado correcto de la factura
657
                        fs_documento_post_save($factura);
658
659
                        $this->new_message("<a href='" . $factura->url() . "'>Factura</a> guardada correctamente.");
660
                        if ($_POST['regalo'] == 'TRUE') {
661
                            $this->imprimir_ticket_regalo($factura);
662
                        } else {
663
                            $this->imprimir_ticket($factura, floatval($_POST['num_tickets']));
0 ignored issues
show
Bug introduced by
floatval($_POST['num_tickets']) of type double is incompatible with the type type expected by parameter $num_tickets of tpv_recambios::imprimir_ticket(). ( Ignorable by Annotation )

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

663
                            $this->imprimir_ticket($factura, /** @scrutinizer ignore-type */ floatval($_POST['num_tickets']));
Loading history...
664
                        }
665
666
                        /// actualizamos la caja
667
                        $this->caja->dinero_fin += $factura->total;
0 ignored issues
show
Bug introduced by
The property dinero_fin does not exist on boolean.
Loading history...
668
                        $this->caja->tickets += 1;
0 ignored issues
show
Bug introduced by
The property tickets does not exist on boolean.
Loading history...
669
                        $this->caja->ip = $_SERVER['REMOTE_ADDR'];
0 ignored issues
show
Bug introduced by
The property ip does not exist on boolean.
Loading history...
670
                        if ($this->caja->save()) {
671
                            if ($trazabilidad) {
0 ignored issues
show
introduced by
The condition $trazabilidad is always false.
Loading history...
672
                                header('Location: index.php?page=ventas_trazabilidad&doc=factura&id=' . $factura->idfactura
673
                                        . '&volver=' . urlencode($this->url()));
674
                            }
675
                        } else {
676
                            $this->new_error_msg("¡Imposible actualizar la caja!");
677
                        }
678
                    } else {
679
                        $this->new_error_msg("¡Imposible actualizar la <a href='" . $factura->url() . "'>factura</a>!");
680
                    }
681
                } else if ($factura->delete()) {
682
                    $this->new_message("Factura eliminada correctamente.");
683
                } else {
684
                    $this->new_error_msg("¡Imposible eliminar la <a href='" . $factura->url() . "'>factura</a>!");
685
                }
686
            } else {
687
                $this->new_error_msg("¡Imposible guardar la factura!");
688
            }
689
        }
690
    }
691
692
    private function abrir_caja()
693
    {
694
        if ($this->terminal) {
695
                $this->terminal->abrir_cajon();
696
                $this->terminal->save();
697
        } else {
698
            $this->new_error_msg('Terminal no encontrado.');
699
        }
700
    }
701
702
    private function cerrar_caja()
703
    {
704
        $this->caja->fecha_fin = Date('d-m-Y H:i:s');
0 ignored issues
show
Bug introduced by
The property fecha_fin does not exist on boolean.
Loading history...
705
        if ($this->caja->save()) {
706
            if ($this->terminal) {
707
                $this->terminal->add_linea_big("\nCIERRE DE CAJA:\n\n");
708
                $this->terminal->add_linea("Empleado: " . $this->user->codagente . " " . $this->agente->get_fullname() . "\n");
709
                $this->terminal->add_linea("Caja: " . $this->caja->fs_id . "\n");
0 ignored issues
show
Bug introduced by
The property fs_id does not exist on boolean.
Loading history...
710
                $this->terminal->add_linea("Fecha inicial: " . $this->caja->fecha_inicial . "\n");
0 ignored issues
show
Bug introduced by
The property fecha_inicial does not exist on boolean.
Loading history...
711
                $this->terminal->add_linea("Dinero inicial: " . $this->show_precio($this->caja->dinero_inicial, FALSE, FALSE) . "\n");
0 ignored issues
show
Bug introduced by
The property dinero_inicial does not exist on boolean.
Loading history...
712
                $this->terminal->add_linea("Fecha fin: " . $this->caja->show_fecha_fin() . "\n");
713
                $this->terminal->add_linea("Dinero fin: " . $this->show_precio($this->caja->dinero_fin, FALSE, FALSE) . "\n");
0 ignored issues
show
Bug introduced by
The property dinero_fin does not exist on boolean.
Loading history...
714
                $this->terminal->add_linea("Diferencia: " . $this->show_precio($this->caja->diferencia(), FALSE, FALSE) . "\n");
715
                $this->terminal->add_linea("Tickets: " . $this->caja->tickets . "\n\n");
0 ignored issues
show
Bug introduced by
The property tickets does not exist on boolean.
Loading history...
716
                $this->terminal->add_linea("Dinero pesado:\n\n\n");
717
                $this->terminal->add_linea("Observaciones:\n\n\n\n");
718
                $this->terminal->add_linea("Firma:\n\n\n\n\n\n\n\n\n\n");
719
                $this->terminal->cortar_papel();
720
                $this->terminal->abrir_cajon();
721
                $this->terminal->save();
722
723
                /// recargamos la página
724
                header('location: ' . $this->url() . '&terminal=' . $this->terminal->id);
725
            } else {
726
                /// recargamos la página
727
                header('location: ' . $this->url());
728
            }
729
        } else {
730
            $this->new_error_msg("¡Imposible cerrar la caja!");
731
        }
732
    }
733
734
    private function reimprimir_ticket()
735
    {
736
        $factura = new factura_cliente();
737
        $fac0 = FALSE;
738
739
        if ($_GET['reticket'] == '') {
740
            foreach ($factura->all(0, FS_ITEM_LIMIT, 'idfactura DESC') as $fac) {
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...
741
                $fac0 = $fac;
742
                break;
743
            }
744
        } else {
745
            $fac0 = $factura->get_by_codigo($_GET['reticket']);
746
        }
747
748
        if ($fac0) {
749
            $this->info_factura_dgii($fac0);
750
            $this->imprimir_ticket($fac0, 1, FALSE);
0 ignored issues
show
Bug introduced by
1 of type integer is incompatible with the type type expected by parameter $num_tickets of tpv_recambios::imprimir_ticket(). ( Ignorable by Annotation )

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

750
            $this->imprimir_ticket($fac0, /** @scrutinizer ignore-type */ 1, FALSE);
Loading history...
Bug introduced by
FALSE of type false is incompatible with the type type expected by parameter $cajon of tpv_recambios::imprimir_ticket(). ( Ignorable by Annotation )

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

750
            $this->imprimir_ticket($fac0, 1, /** @scrutinizer ignore-type */ FALSE);
Loading history...
751
        } else {
752
            $this->new_error_msg("Ticket no encontrado.");
753
        }
754
    }
755
756
    /**
757
     * Añade el ticket a la cola de impresión.
758
     * @param factura_cliente $factura
759
     * @param type $num_tickets
760
     * @param type $cajon
761
     */
762
    private function imprimir_ticket($factura, $num_tickets = 1, $cajon = TRUE)
763
    {
764
        if ($this->terminal) {
765
            if ($cajon) {
766
                $this->terminal->abrir_cajon();
767
            }
768
769
            while ($num_tickets > 0) {
770
                $this->info_factura_dgii($factura);
771
                $this->terminal->imprimir_ticket($factura, $this->empresa, $this->imprimir_descripciones, $this->imprimir_observaciones);
772
                $num_tickets--;
773
            }
774
775
            $this->terminal->save();
776
            $this->new_message('<a href="#" data-toggle="modal" data-target="#modal_ayuda_ticket">¿No se imprime el ticket?</a>');
777
        } else {
778
            $this->new_error_msg('Terminal no encontrado.');
779
        }
780
    }
781
782
    /**
783
     * Imprime uno o varios tickets de la factura.
784
     * @param factura_cliente $factura
785
     * @param type $num_tickets
786
     * @param type $cajon
787
     */
788
    private function imprimir_ticket_regalo($factura, $num_tickets = 1, $cajon = TRUE)
789
    {
790
        if ($this->terminal) {
791
            if ($cajon) {
792
                $this->terminal->abrir_cajon();
793
            }
794
795
            while ($num_tickets > 0) {
796
                $this->info_factura_dgii($factura);
797
                $this->terminal->imprimir_ticket_regalo($factura, $this->empresa, $this->imprimir_descripciones, $this->imprimir_observaciones);
798
                $num_tickets--;
799
            }
800
801
            $this->terminal->save();
802
        }
803
    }
804
805
    /**
806
     * Genera el asiento para la factura, si procede
807
     * @param factura_cliente $factura
808
     */
809
    private function generar_asiento(&$factura)
810
    {
811
        if ($this->empresa->contintegrada) {
812
            $asiento_factura = new asiento_factura();
0 ignored issues
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...
813
            $asiento_factura->generar_asiento_venta($factura);
814
            return;
815
        }
816
817
            /// de todas formas forzamos la generación de las líneas de iva
818
            $factura->get_lineas_iva();
819
    }
820
    
821
    private function info_factura_dgii(&$fact)
822
    {
823
        $ncf_ventas = $this->ncf_ventas->get_ncf($this->empresa->id, $fact->idfactura, $fact->codcliente);
824
        $fact->fecha_vencimiento = $ncf_ventas->fecha_vencimiento;
825
        $ncf_tipo = $this->ncf_tipo->get($ncf_ventas->tipo_comprobante);
826
        $fact->tipo_comprobante = $ncf_tipo->descripcion;
827
    }
828
829
    private function share_extensions()
830
    {
831
        $fsext = new fs_extension();
0 ignored issues
show
Bug introduced by
The type fs_extension 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...
832
        $fsext->name = 'api_remote_printer';
833
        $fsext->from = __CLASS__;
834
        $fsext->type = 'api';
835
        $fsext->text = 'remote_printer';
836
        $fsext->save();
837
    }
838
}
839