nueva_venta::datos_cliente()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 7
rs 10
1
<?php
2
/*
3
 * This file is part of facturacion_base
4
 * Copyright (C) 2014-2017  Carlos Garcia Gomez       [email protected]
5
 * Copyright (C) 2014-2015  Francesc Pineda Segarra   [email protected]
6
 *
7
 * This program is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU Lesser General Public License as
9
 * published by the Free Software Foundation, either version 3 of the
10
 * License, or (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public License
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
 */
20
21
require_once 'plugins/republica_dominicana/extras/rd_controller.php';
22
23
class nueva_venta extends rd_controller
24
{
25
26
    public $agencia;
27
    public $agente;
28
    public $almacen;
29
    public $articulo;
30
    public $cliente;
31
    public $cliente_s;
32
    public $direccion;
33
    public $divisa;
34
    public $fabricante;
35
    public $familia;
36
    public $forma_pago;
37
    public $grupo;
38
    public $impuesto;
39
    public $nuevocli_setup;
40
    public $pais;
41
    public $results;
42
    public $serie;
43
    public $tipo;
44
    public $cliente_rutas;
45
46
    public function __construct()
47
    {
48
        parent::__construct(__CLASS__, 'Nueva venta...', 'ventas', FALSE, FALSE, TRUE);
49
    }
50
51
    protected function private_core()
52
    {
53
        parent::private_core();
54
55
        $this->agencia = new agencia_transporte();
0 ignored issues
show
Bug introduced by
The type agencia_transporte 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->cliente = new 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...
57
        $this->cliente_s = FALSE;
58
        $this->direccion = FALSE;
59
        $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...
60
        $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...
61
        $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...
62
        $this->results = array();
63
        $this->grupo = 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...
64
        $this->pais = new pais();
0 ignored issues
show
Bug introduced by
The type pais 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...
65
66
        /// cargamos la configuración
67
        $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...
68
        $this->nuevocli_setup = $fsvar->array_get(
69
                array(
70
            'nuevocli_cifnif_req' => 0,
71
            'nuevocli_direccion' => 0,
72
            'nuevocli_direccion_req' => 0,
73
            'nuevocli_codpostal' => 0,
74
            'nuevocli_codpostal_req' => 0,
75
            'nuevocli_pais' => 0,
76
            'nuevocli_pais_req' => 0,
77
            'nuevocli_provincia' => 0,
78
            'nuevocli_provincia_req' => 0,
79
            'nuevocli_ciudad' => 0,
80
            'nuevocli_ciudad_req' => 0,
81
            'nuevocli_telefono1' => 0,
82
            'nuevocli_telefono1_req' => 0,
83
            'nuevocli_telefono2' => 0,
84
            'nuevocli_telefono2_req' => 0,
85
            'nuevocli_email' => 0,
86
            'nuevocli_email_req' => 0,
87
            'nuevocli_codgrupo' => '',
88
            ), FALSE
89
        );
90
91
        if (isset($_REQUEST['tipo'])) {
92
            $this->tipo = $_REQUEST['tipo'];
93
        } else {
94
            foreach ($this->tipos_a_guardar() as $t) {
95
                $this->tipo = $t['tipo'];
96
                break;
97
            }
98
        }
99
100
        if (isset($_REQUEST['buscar_cliente'])) {
101
            $this->fbase_buscar_cliente($_REQUEST['buscar_cliente']);
102
        } else if (isset($_REQUEST['datoscliente'])) {
103
            $this->datos_cliente();
104
        } else if (isset($_REQUEST['new_articulo'])) {
105
            $this->new_articulo();
106
        } else if ($this->query != '') {
107
            $this->new_search();
108
        } else if (isset($_POST['referencia4precios'])) {
109
            $this->get_precios_articulo();
110
        } else if (isset($_POST['referencia4combi'])) {
111
            $this->get_combinaciones_articulo();
112
        } else if (isset($_POST['cliente'])) {
113
            $this->cliente_s = $this->cliente->get($_POST['cliente']);
114
115
            /**
116
             * Nuevo cliente
117
             */
118
            if (isset($_POST['nuevo_cliente']) && $_POST['nuevo_cliente'] != '') {
119
                $this->cliente_s = FALSE;
120
                if ($_POST['nuevo_cifnif'] != '') {
121
                    $this->cliente_s = $this->cliente->get_by_cifnif($_POST['nuevo_cifnif']);
122
                    if ($this->cliente_s) {
123
                        $this->new_advice('Ya existe un cliente con ese ' . FS_CIFNIF . '. Se ha seleccionado.');
124
                    }
125
                }
126
127
                if (!$this->cliente_s) {
128
                    $this->cliente_s = new cliente();
129
                    $this->cliente_s->codcliente = $this->cliente_s->get_new_codigo();
130
                    $this->cliente_s->nombre = $this->cliente_s->razonsocial = $_POST['nuevo_cliente'];
131
                    $this->cliente_s->tipoidfiscal = $_POST['nuevo_tipoidfiscal'];
132
                    $this->cliente_s->cifnif = $_POST['nuevo_cifnif'];
133
                    $this->cliente_s->personafisica = isset($_POST['personafisica']);
134
135
                    if (isset($_POST['nuevo_email'])) {
136
                        $this->cliente_s->email = $_POST['nuevo_email'];
137
                    }
138
139
                    if (isset($_POST['codgrupo']) && $_POST['codgrupo'] != '') {
140
                        $this->cliente_s->codgrupo = $_POST['codgrupo'];
141
                    }
142
143
                    if (isset($_POST['nuevo_telefono1'])) {
144
                        $this->cliente_s->telefono1 = $_POST['nuevo_telefono1'];
145
                    }
146
147
                    if (isset($_POST['nuevo_telefono2'])) {
148
                        $this->cliente_s->telefono2 = $_POST['nuevo_telefono2'];
149
                    }
150
151
                    if ($this->cliente_s->save()) {
152
                        if (isset($_POST['tipo_comprobante'])) {
153
                            $ncf_entidad_tipo = new ncf_entidad_tipo();
154
                            $ncf_entidad_tipo->idempresa = $this->empresa->id;
155
                            $ncf_entidad_tipo->entidad = $this->cliente_s->codcliente;
156
                            $ncf_entidad_tipo->tipo_entidad = 'CLI';
0 ignored issues
show
Documentation Bug introduced by
It seems like 'CLI' of type string is incompatible with the declared type varchar of property $tipo_entidad.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
157
                            $ncf_entidad_tipo->tipo_comprobante = \filter_input(INPUT_POST, 'tipo_comprobante');
158
                            $ncf_entidad_tipo->usuario_creacion = $this->user->nick;
159
                            $ncf_entidad_tipo->fecha_creacion = \Date('d-m-Y H:i:s');
160
                            $ncf_entidad_tipo->usuario_modificacion = $this->user->nick;
161
                            $ncf_entidad_tipo->fecha_modificacion = \Date('d-m-Y H:i:s');
162
                            $ncf_entidad_tipo->estado = true;
163
                            if (!$ncf_entidad_tipo->save()) {
164
                                $this->new_error_msg("¡Imposible actualizar información de NCF para  Cliente " . $ncf_entidad_tipo->entidad . "!");
165
                            } else {
166
                                $this->ncf_cliente_tipo = $this->ncf_entidad_tipo->get($this->empresa->id, $this->cliente_s->codcliente, 'CLI');
167
                            }
168
                        }
169
                        if ($this->empresa->contintegrada) {
170
                            /// forzamos crear la subcuenta
171
                            $this->cliente_s->get_subcuenta($this->empresa->codejercicio);
172
                        }
173
174
                        $dircliente = new direccion_cliente();
0 ignored issues
show
Bug introduced by
The type direccion_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...
175
                        $dircliente->codcliente = $this->cliente_s->codcliente;
176
                        $dircliente->codpais = $this->empresa->codpais;
177
                        $dircliente->provincia = $this->empresa->provincia;
178
                        $dircliente->ciudad = $this->empresa->ciudad;
179
180
                        if (isset($_POST['nuevo_pais'])) {
181
                            $dircliente->codpais = $_POST['nuevo_pais'];
182
                        }
183
184
                        if (isset($_POST['nuevo_provincia'])) {
185
                            $dircliente->provincia = $_POST['nuevo_provincia'];
186
                        }
187
188
                        if (isset($_POST['nuevo_ciudad'])) {
189
                            $dircliente->ciudad = $_POST['nuevo_ciudad'];
190
                        }
191
192
                        if (isset($_POST['nuevo_codpostal'])) {
193
                            $dircliente->codpostal = $_POST['nuevo_codpostal'];
194
                        }
195
196
                        if (isset($_POST['nuevo_direccion'])) {
197
                            $dircliente->direccion = $_POST['nuevo_direccion'];
198
                        }
199
200
                        if ($dircliente->save()) {
201
                            $this->new_message('Cliente agregado correctamente.');
202
                        }
203
                    } else {
204
                        $this->new_error_msg("¡Imposible guardar la dirección del cliente!");
205
                    }
206
                }
207
            }
208
209
            if ($this->cliente_s) {
210
                foreach ($this->cliente_s->get_direcciones() as $dir) {
211
                    if ($dir->domfacturacion) {
212
                        $this->direccion = $dir;
213
                        break;
214
                    }
215
                }
216
                if (class_exists('distribucion_clientes')) {
217
                    $this->cliente_rutas = $this->distribucion_clientes->get($this->empresa->id, $this->cliente_s->codcliente);
218
                }
219
            }
220
221
            if (isset($_POST['codagente'])) {
222
                $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...
223
                $this->agente = $agente->get($_POST['codagente']);
224
            } else {
225
                $this->agente = $this->user->get_agente();
226
            }
227
228
            $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...
229
            $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...
230
            $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...
231
            $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...
232
233
            if (isset($_POST['tipo'])) {
234
                if ($_POST['tipo'] == 'factura') {
235
                    $this->nueva_factura_cliente();
236
                } else if ($_POST['tipo'] == 'albaran') {
237
                    $this->nuevo_albaran_cliente();
238
                } else if ($_POST['tipo'] == 'pedido' && class_exists('pedido_cliente')) {
239
                    $this->nuevo_pedido_cliente();
240
                } else if ($_POST['tipo'] == 'presupuesto' && class_exists('presupuesto_cliente')) {
241
                    $this->nuevo_presupuesto_cliente();
242
                }
243
244
                /// si el cliente no tiene cifnif nos guardamos el que indique
245
                if ($this->cliente_s->cifnif == '') {
246
                    $this->cliente_s->cifnif = $_POST['cifnif'];
247
                    $this->cliente_s->save();
248
                }
249
250
                /// ¿Guardamos la dirección como nueva?
251
                if ($_POST['coddir'] == 'nueva') {
252
                    $this->direccion = new direccion_cliente();
253
                    $this->direccion->codcliente = $this->cliente_s->codcliente;
254
                    $this->direccion->codpais = $_POST['codpais'];
255
                    $this->direccion->provincia = $_POST['provincia'];
256
                    $this->direccion->ciudad = $_POST['ciudad'];
257
                    $this->direccion->codpostal = $_POST['codpostal'];
258
                    $this->direccion->direccion = $_POST['direccion'];
259
                    $this->direccion->apartado = $_POST['apartado'];
260
                    $this->direccion->save();
261
                } else if ($_POST['envio_coddir'] == 'nueva') {
262
                    $this->direccion = new direccion_cliente();
263
                    $this->direccion->codcliente = $this->cliente_s->codcliente;
264
                    $this->direccion->codpais = $_POST['envio_codpais'];
265
                    $this->direccion->provincia = $_POST['envio_provincia'];
266
                    $this->direccion->ciudad = $_POST['envio_ciudad'];
267
                    $this->direccion->codpostal = $_POST['envio_codpostal'];
268
                    $this->direccion->direccion = $_POST['envio_direccion'];
269
                    $this->direccion->apartado = $_POST['envio_apartado'];
270
                    $this->direccion->domfacturacion = FALSE;
271
                    $this->direccion->domenvio = TRUE;
272
                    $this->direccion->save();
273
                }
274
            }
275
        }
276
    }
277
278
    /**
279
     * Devuelve los tipos de documentos a guardar,
280
     * así para añadir tipos no hay que tocar la vista.
281
     * @return type
282
     */
283
    public function tipos_a_guardar()
284
    {
285
        $tipos = array();
286
287
        if ($this->user->have_access_to('ventas_presupuesto') && class_exists('presupuesto_cliente')) {
288
            $tipos[] = array('tipo' => 'presupuesto', 'nombre' => ucfirst(FS_PRESUPUESTO) . ' para cliente');
0 ignored issues
show
Bug introduced by
The constant FS_PRESUPUESTO was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
289
        }
290
291
        if ($this->user->have_access_to('ventas_pedido') && class_exists('pedido_cliente')) {
292
            $tipos[] = array('tipo' => 'pedido', 'nombre' => ucfirst(FS_PEDIDO) . ' de cliente');
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...
293
        }
294
295
        if ($this->user->have_access_to('ventas_albaran')) {
296
            $tipos[] = array('tipo' => 'albaran', 'nombre' => ucfirst(FS_ALBARAN) . ' de cliente');
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...
297
        }
298
299
        if ($this->user->have_access_to('ventas_factura')) {
300
            $tipos[] = array('tipo' => 'factura', 'nombre' => 'Factura de cliente');
301
        }
302
303
        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...
304
    }
305
306
    public function url()
307
    {
308
        return 'index.php?page=' . __CLASS__ . '&tipo=' . $this->tipo;
309
    }
310
311
    private function datos_cliente()
312
    {
313
        /// desactivamos la plantilla HTML
314
        $this->template = FALSE;
315
316
        header('Content-Type: application/json');
317
        echo json_encode($this->cliente->get($_REQUEST['datoscliente']));
318
    }
319
320
    private function new_articulo()
321
    {
322
        /// desactivamos la plantilla HTML
323
        $this->template = FALSE;
324
325
        $art0 = new articulo();
326
        if ($_REQUEST['referencia'] != '') {
327
            $art0->referencia = $_REQUEST['referencia'];
328
        } else {
329
            $art0->referencia = $art0->get_new_referencia();
330
        }
331
332
        if ($art0->exists()) {
333
            $this->results[] = $art0->get($art0->referencia);
334
        } else {
335
            $art0->descripcion = $_REQUEST['descripcion'];
336
            $art0->codbarras = $_REQUEST['codbarras'];
337
            $art0->set_impuesto($_REQUEST['codimpuesto']);
338
            $art0->set_pvp(floatval($_REQUEST['pvp']));
339
340
            $art0->secompra = isset($_POST['secompra']);
341
            $art0->sevende = isset($_POST['sevende']);
342
            $art0->nostock = isset($_POST['nostock']);
343
            $art0->publico = isset($_POST['publico']);
344
345
            if ($_REQUEST['codfamilia'] != '') {
346
                $art0->codfamilia = $_REQUEST['codfamilia'];
347
            }
348
349
            if ($_REQUEST['codfabricante'] != '') {
350
                $art0->codfabricante = $_REQUEST['codfabricante'];
351
            }
352
353
            if ($art0->save()) {
354
                $this->results[] = $art0;
355
            }
356
        }
357
358
        header('Content-Type: application/json');
359
        echo json_encode($this->results);
360
    }
361
362
    private function new_search()
363
    {
364
        /// desactivamos la plantilla HTML
365
        $this->template = FALSE;
366
367
        $articulo = new articulo();
368
        $codfamilia = '';
369
        if (isset($_REQUEST['codfamilia'])) {
370
            $codfamilia = $_REQUEST['codfamilia'];
371
        }
372
        $codfabricante = '';
373
        if (isset($_REQUEST['codfabricante'])) {
374
            $codfabricante = $_REQUEST['codfabricante'];
375
        }
376
        $con_stock = isset($_REQUEST['con_stock']);
377
        $this->results = $articulo->search($this->query, 0, $codfamilia, $con_stock, $codfabricante);
378
379
        /// añadimos la busqueda, el descuento, la cantidad, etc...
380
        $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...
381
        foreach ($this->results as $i => $value) {
382
            $this->results[$i]->query = $this->query;
383
            $this->results[$i]->dtopor = 0;
384
            $this->results[$i]->cantidad = 1;
385
            $this->results[$i]->coddivisa = $this->empresa->coddivisa;
386
387
            /// añadimos el stock del almacén y el general
388
            $this->results[$i]->stockalm = $this->results[$i]->stockfis;
389
            if ($this->multi_almacen && isset($_REQUEST['codalmacen'])) {
390
                $this->results[$i]->stockalm = $stock->total_from_articulo($this->results[$i]->referencia, $_REQUEST['codalmacen']);
391
            }
392
        }
393
394
        /// ejecutamos las funciones de las extensiones
395
        foreach ($this->extensions as $ext) {
396
            if ($ext->type == 'function' && $ext->params == 'new_search') {
397
                $name = $ext->text;
398
                $name($this->db, $this->results);
399
            }
400
        }
401
402
        /// buscamos el grupo de clientes y la tarifa
403
        if (isset($_REQUEST['codcliente'])) {
404
            $cliente = $this->cliente->get($_REQUEST['codcliente']);
405
            $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...
406
407
            if ($cliente && $cliente->codtarifa) {
408
                $tarifa = $tarifa0->get($cliente->codtarifa);
409
                if ($tarifa) {
410
                    $tarifa->set_precios($this->results);
411
                }
412
            } else if ($cliente && $cliente->codgrupo) {
413
                $grupo0 = new grupo_clientes();
414
415
                $grupo = $grupo0->get($cliente->codgrupo);
416
                if ($grupo) {
417
                    $tarifa = $tarifa0->get($grupo->codtarifa);
418
                    if ($tarifa) {
419
                        $tarifa->set_precios($this->results);
420
                    }
421
                }
422
            }
423
        }
424
425
        /// convertimos la divisa
426
        if (isset($_REQUEST['coddivisa']) && $_REQUEST['coddivisa'] != $this->empresa->coddivisa) {
427
            foreach ($this->results as $i => $value) {
428
                $this->results[$i]->coddivisa = $_REQUEST['coddivisa'];
429
                $this->results[$i]->pvp = $this->divisa_convert($value->pvp, $this->empresa->coddivisa, $_REQUEST['coddivisa']);
430
            }
431
        }
432
433
        header('Content-Type: application/json');
434
        echo json_encode($this->results);
435
    }
436
437
    private function get_precios_articulo()
438
    {
439
        /// cambiamos la plantilla HTML
440
        $this->template = 'ajax/nueva_venta_precios';
441
442
        $articulo = new articulo();
443
        $this->articulo = $articulo->get($_POST['referencia4precios']);
444
    }
445
446
    private function get_combinaciones_articulo()
447
    {
448
        /// cambiamos la plantilla HTML
449
        $this->template = 'ajax/nueva_venta_combinaciones';
450
451
        $impuestos = $this->impuesto->all();
452
453
        $this->results = array();
454
        $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...
455
        foreach ($comb1->all_from_ref($_POST['referencia4combi']) as $com) {
456
            if (isset($this->results[$com->codigo])) {
457
                $this->results[$com->codigo]['desc'] .= ', ' . $com->nombreatributo . ' - ' . $com->valor;
458
                $this->results[$com->codigo]['txt'] .= ', ' . $com->nombreatributo . ' - ' . $com->valor;
459
            } else {
460
                $iva = 0;
461
                foreach ($impuestos as $imp) {
462
                    if ($imp->codimpuesto == $_POST['codimpuesto']) {
463
                        $iva = $imp->iva;
464
                        break;
465
                    }
466
                }
467
468
                $this->results[$com->codigo] = array(
469
                    'ref' => $_POST['referencia4combi'],
470
                    'desc' => base64_decode($_POST['desc']) . "\n" . $com->nombreatributo . ' - ' . $com->valor,
471
                    'pvp' => floatval($_POST['pvp']) + $com->impactoprecio,
472
                    'dto' => floatval($_POST['dto']),
473
                    'codimpuesto' => $_POST['codimpuesto'],
474
                    'iva' => $iva,
475
                    'cantidad' => floatval($_POST['cantidad']),
476
                    'txt' => $com->nombreatributo . ' - ' . $com->valor,
477
                    'codigo' => $com->codigo,
478
                    'stockfis' => $com->stockfis,
479
                );
480
            }
481
        }
482
    }
483
484
    public function get_tarifas_articulo($ref)
485
    {
486
        $tarlist = array();
487
        $articulo = new articulo();
488
        $tarifa = new tarifa();
489
490
        foreach ($tarifa->all() as $tar) {
491
            $art = $articulo->get($ref);
492
            if ($art) {
493
                $art->dtopor = 0;
494
                $aux = array($art);
495
                $tar->set_precios($aux);
496
                $tarlist[] = $aux[0];
497
            }
498
        }
499
500
        return $tarlist;
501
    }
502
    
503
    private function nuevo_presupuesto_cliente()
504
    {
505
        $continuar = TRUE;
506
507
        $cliente = $this->cliente->get($_POST['cliente']);
508
        if (!$cliente) {
509
            $this->new_error_msg('Cliente no encontrado.');
510
            $continuar = FALSE;
511
        }
512
513
        $almacen = $this->almacen->get($_POST['almacen']);
514
        if ($almacen) {
515
            $this->save_codalmacen($_POST['almacen']);
516
        } else {
517
            $this->new_error_msg('Almacén no encontrado.');
518
            $continuar = FALSE;
519
        }
520
521
        $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...
522
        $ejercicio = $eje0->get_by_fecha($_POST['fecha'], FALSE);
523
        if (!$ejercicio) {
524
            $this->new_error_msg('Ejercicio no encontrado.');
525
            $continuar = FALSE;
526
        }
527
528
        $serie = $this->serie->get($_POST['serie']);
529
        if (!$serie) {
530
            $this->new_error_msg('Serie no encontrada.');
531
            $continuar = FALSE;
532
        }
533
534
        $forma_pago = $this->forma_pago->get($_POST['forma_pago']);
535
        if ($forma_pago) {
536
            $this->save_codpago($_POST['forma_pago']);
537
        } else {
538
            $this->new_error_msg('Forma de pago no encontrada.');
539
            $continuar = FALSE;
540
        }
541
542
        $divisa = $this->divisa->get($_POST['divisa']);
543
        if (!$divisa) {
544
            $this->new_error_msg('Divisa no encontrada.');
545
            $continuar = FALSE;
546
        }
547
548
        $presupuesto = new presupuesto_cliente();
0 ignored issues
show
Bug introduced by
The type presupuesto_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...
549
550
        if ($this->duplicated_petition($_POST['petition_id'])) {
551
            $this->new_error_msg('Petición duplicada. Has hecho doble clic sobre el botón guardar
552
               y se han enviado dos peticiones. Mira en <a href="' . $presupuesto->url() . '">Presupuestos</a>
553
               para ver si el presupuesto se ha guardado correctamente.');
554
            $continuar = FALSE;
555
        }
556
557
        if ($continuar) {
558
            $this->nuevo_documento($presupuesto, $ejercicio, $serie, $almacen, $forma_pago, $divisa, $cliente);
559
560
            /// establecemos la fecha de finoferta
561
            $presupuesto->finoferta = date("Y-m-d", strtotime($_POST['fecha'] . " +1 month"));
562
            $fsvar = new fs_var();
563
            $dias = $fsvar->simple_get('presu_validez');
564
            if ($dias) {
565
                $presupuesto->finoferta = date("Y-m-d", strtotime($_POST['fecha'] . " +" . intval($dias) . " days"));
566
            }
567
568
            /// función auxiliar para implementar en los plugins que lo necesiten
569
            if (!fs_generar_numero2($presupuesto)) {
570
                $presupuesto->numero2 = $_POST['numero2'];
571
            }
572
573
            if ($presupuesto->save()) {
574
                $art0 = new articulo();
575
                $n = floatval($_POST['numlineas']);
576
                for ($i = 0; $i <= $n; $i++) {
577
                    if (isset($_POST['referencia_' . $i])) {
578
                        $linea = new linea_presupuesto_cliente();
0 ignored issues
show
Bug introduced by
The type linea_presupuesto_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...
579
                        $linea->idpresupuesto = $presupuesto->idpresupuesto;
580
                        $this->nueva_linea($linea, $i, $serie, $cliente);
581
582
                        $articulo = $art0->get($_POST['referencia_' . $i]);
583
                        if ($articulo) {
584
                            $linea->referencia = $articulo->referencia;
585
                            if ($_POST['codcombinacion_' . $i]) {
586
                                $linea->codcombinacion = $_POST['codcombinacion_' . $i];
587
                            }
588
                        }
589
590
                        if ($linea->save()) {
591
                            if ($linea->irpf > $presupuesto->irpf) {
592
                                $presupuesto->irpf = $linea->irpf;
593
                            }
594
                        } else {
595
                            $this->new_error_msg("¡Imposible guardar la linea con referencia: " . $linea->referencia);
596
                            $continuar = FALSE;
597
                        }
598
                    }
599
                }
600
601
                if ($continuar) {
0 ignored issues
show
introduced by
The condition $continuar is always true.
Loading history...
602
                    /// obtenemos los subtotales por impuesto
603
                    $due_totales = $this->fbase_calc_due([$presupuesto->dtopor1, $presupuesto->dtopor2, $presupuesto->dtopor3, $presupuesto->dtopor4, $presupuesto->dtopor5]);
604
                    foreach ($this->fbase_get_subtotales_documento($presupuesto->get_lineas(), $due_totales) as $subt) {
605
                        $presupuesto->netosindto += $subt['netosindto'];
606
                        $presupuesto->neto += $subt['neto'];
607
                        $presupuesto->totaliva += $subt['iva'];
608
                        $presupuesto->totalirpf += $subt['irpf'];
609
                        $presupuesto->totalrecargo += $subt['recargo'];
610
                    }
611
612
                    $presupuesto->total = round($presupuesto->neto + $presupuesto->totaliva - $presupuesto->totalirpf + $presupuesto->totalrecargo, FS_NF0);
613
614
                    if (abs(floatval($_POST['atotal']) - $presupuesto->total) >= .02) {
615
                        $this->new_error_msg("El total difiere entre el controlador y la vista (" .
616
                                $presupuesto->total . " frente a " . $_POST['atotal'] . "). Debes informar del error.");
617
                        $presupuesto->delete();
618
                    } else if ($presupuesto->save()) {
619
                        /// Función de ejecución de tareas post guardado correcto del presupuesto
620
                        fs_documento_post_save($presupuesto);
621
622
                        $this->new_message("<a href='" . $presupuesto->url() . "'>" . ucfirst(FS_PRESUPUESTO) . "</a> guardado correctamente.");
0 ignored issues
show
Bug introduced by
The constant FS_PRESUPUESTO was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
623
                        $this->new_change(ucfirst(FS_PRESUPUESTO) . ' a Cliente ' . $presupuesto->codigo, $presupuesto->url(), TRUE);
624
625
                        if ($_POST['redir'] == 'TRUE') {
626
                            header('Location: ' . $presupuesto->url());
627
                        }
628
                    } else {
629
                        $this->new_error_msg("¡Imposible actualizar el <a href='" . $presupuesto->url() . "'>" . FS_PRESUPUESTO . "</a>!");
630
                    }
631
                } else if ($presupuesto->delete()) {
632
                    $this->new_message(ucfirst(FS_PRESUPUESTO) . " eliminado correctamente.");
633
                } else {
634
                    $this->new_error_msg("¡Imposible eliminar el <a href='" . $presupuesto->url() . "'>" . FS_PRESUPUESTO . "</a>!");
635
                }
636
            } else {
637
                $this->new_error_msg("¡Imposible guardar el " . FS_PRESUPUESTO . "!");
638
            }
639
        }
640
    }
641
    
642
    private function nuevo_pedido_cliente()
643
    {
644
        $continuar = TRUE;
645
646
        $cliente = $this->cliente->get($_POST['cliente']);
647
        if (!$cliente) {
648
            $this->new_error_msg('Cliente no encontrado.');
649
            $continuar = FALSE;
650
        }
651
652
        $almacen = $this->almacen->get($_POST['almacen']);
653
        if ($almacen) {
654
            $this->save_codalmacen($_POST['almacen']);
655
        } else {
656
            $this->new_error_msg('Almacén no encontrado.');
657
            $continuar = FALSE;
658
        }
659
660
        $eje0 = new ejercicio();
661
        $ejercicio = $eje0->get_by_fecha($_POST['fecha'], FALSE);
662
        if (!$ejercicio) {
663
            $this->new_error_msg('Ejercicio no encontrado.');
664
            $continuar = FALSE;
665
        }
666
667
        $serie = $this->serie->get($_POST['serie']);
668
        if (!$serie) {
669
            $this->new_error_msg('Serie no encontrada.');
670
            $continuar = FALSE;
671
        }
672
673
        $forma_pago = $this->forma_pago->get($_POST['forma_pago']);
674
        if ($forma_pago) {
675
            $this->save_codpago($_POST['forma_pago']);
676
        } else {
677
            $this->new_error_msg('Forma de pago no encontrada.');
678
            $continuar = FALSE;
679
        }
680
681
        $divisa = $this->divisa->get($_POST['divisa']);
682
        if (!$divisa) {
683
            $this->new_error_msg('Divisa no encontrada.');
684
            $continuar = FALSE;
685
        }
686
687
        $pedido = new pedido_cliente();
0 ignored issues
show
Bug introduced by
The type pedido_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...
688
689
        if ($this->duplicated_petition($_POST['petition_id'])) {
690
            $this->new_error_msg('Petición duplicada. Has hecho doble clic sobre el botón guardar
691
               y se han enviado dos peticiones. Mira en <a href="' . $pedido->url() . '">Pedidos</a>
692
               para ver si el pedido se ha guardado correctamente.');
693
            $continuar = FALSE;
694
        }
695
696
        if ($continuar) {
697
            $this->nuevo_documento($pedido, $ejercicio, $serie, $almacen, $forma_pago, $divisa, $cliente);
698
699
            /// función auxiliar para implementar en los plugins que lo necesiten
700
            if (!fs_generar_numero2($pedido)) {
701
                $pedido->numero2 = $_POST['numero2'];
702
            }
703
704
            if ($pedido->save()) {
705
                $art0 = new articulo();
706
                $n = floatval($_POST['numlineas']);
707
                for ($i = 0; $i <= $n; $i++) {
708
                    if (isset($_POST['referencia_' . $i])) {
709
                        $linea = new linea_pedido_cliente();
0 ignored issues
show
Bug introduced by
The type linea_pedido_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...
710
                        $linea->idpedido = $pedido->idpedido;
711
                        $this->nueva_linea($linea, $i, $serie, $cliente);
712
713
                        $articulo = $art0->get($_POST['referencia_' . $i]);
714
                        if ($articulo) {
715
                            $linea->referencia = $articulo->referencia;
716
                            if ($_POST['codcombinacion_' . $i]) {
717
                                $linea->codcombinacion = $_POST['codcombinacion_' . $i];
718
                            }
719
                        }
720
721
                        if ($linea->save()) {
722
                            if ($linea->irpf > $pedido->irpf) {
723
                                $pedido->irpf = $linea->irpf;
724
                            }
725
                        } else {
726
                            $this->new_error_msg("¡Imposible guardar la linea con referencia: " . $linea->referencia);
727
                            $continuar = FALSE;
728
                        }
729
                    }
730
                }
731
732
                if ($continuar) {
0 ignored issues
show
introduced by
The condition $continuar is always true.
Loading history...
733
                    /// obtenemos los subtotales por impuesto
734
                    $due_totales = $this->fbase_calc_due([$pedido->dtopor1, $pedido->dtopor2, $pedido->dtopor3, $pedido->dtopor4, $pedido->dtopor5]);
735
                    foreach ($this->fbase_get_subtotales_documento($pedido->get_lineas(), $due_totales) as $subt) {
736
                        $pedido->netosindto += $subt['netosindto'];
737
                        $pedido->neto += $subt['neto'];
738
                        $pedido->totaliva += $subt['iva'];
739
                        $pedido->totalirpf += $subt['irpf'];
740
                        $pedido->totalrecargo += $subt['recargo'];
741
                    }
742
743
                    $pedido->total = round($pedido->neto + $pedido->totaliva - $pedido->totalirpf + $pedido->totalrecargo, FS_NF0);
744
745
                    if (abs(floatval($_POST['atotal']) - $pedido->total) >= .02) {
746
                        $this->new_error_msg("El total difiere entre el controlador y la vista ("
747
                            . $pedido->total . " frente a " . $_POST['atotal'] . "). Debes informar del error.");
748
                        $pedido->delete();
749
                    } else if ($pedido->save()) {
750
                        /// Función de ejecución de tareas post guardado correcto del pedido
751
                        fs_documento_post_save($pedido);
752
753
                        $this->new_message("<a href='" . $pedido->url() . "'>" . ucfirst(FS_PEDIDO) . "</a> 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...
754
                        $this->new_change(ucfirst(FS_PEDIDO) . " a Cliente " . $pedido->codigo, $pedido->url(), TRUE);
755
756
                        if ($_POST['redir'] == 'TRUE') {
757
                            header('Location: ' . $pedido->url());
758
                        }
759
                    } else {
760
                        $this->new_error_msg("¡Imposible actualizar el <a href='" . $pedido->url() . "'>" . FS_PEDIDO . "</a>!");
761
                    }
762
                } else if ($pedido->delete()) {
763
                    $this->new_message(ucfirst(FS_PEDIDO) . " eliminado correctamente.");
764
                } else {
765
                    $this->new_error_msg("¡Imposible eliminar el <a href='" . $pedido->url() . "'>" . FS_PEDIDO . "</a>!");
766
                }
767
            } else {
768
                $this->new_error_msg("¡Imposible guardar el " . FS_PEDIDO . "!");
769
            }
770
        }
771
    }
772
    
773
    private function nuevo_albaran_cliente()
774
    {
775
        $continuar = TRUE;
776
777
        $cliente = $this->cliente->get($_POST['cliente']);
778
        if (!$cliente) {
779
            $this->new_error_msg('Cliente no encontrado.');
780
            $continuar = FALSE;
781
        }
782
783
        $almacen = $this->almacen->get($_POST['almacen']);
784
        if ($almacen) {
785
            $this->save_codalmacen($_POST['almacen']);
786
        } else {
787
            $this->new_error_msg('Almacén no encontrado.');
788
            $continuar = FALSE;
789
        }
790
791
        $eje0 = new ejercicio();
792
        $ejercicio = $eje0->get_by_fecha($_POST['fecha'], FALSE);
793
        if (!$ejercicio) {
794
            $this->new_error_msg('Ejercicio no encontrado.');
795
            $continuar = FALSE;
796
        }
797
798
        $serie = $this->serie->get($_POST['serie']);
799
        if (!$serie) {
800
            $this->new_error_msg('Serie no encontrada.');
801
            $continuar = FALSE;
802
        }
803
804
        $forma_pago = $this->forma_pago->get($_POST['forma_pago']);
805
        if ($forma_pago) {
806
            $this->save_codpago($_POST['forma_pago']);
807
        } else {
808
            $this->new_error_msg('Forma de pago no encontrada.');
809
            $continuar = FALSE;
810
        }
811
812
        $divisa = $this->divisa->get($_POST['divisa']);
813
        if (!$divisa) {
814
            $this->new_error_msg('Divisa no encontrada.');
815
            $continuar = FALSE;
816
        }
817
818
        $art0 = new articulo();
819
        $albaran = new albaran_cliente();
0 ignored issues
show
Bug introduced by
The type albaran_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...
820
        $stock0 = new stock();
821
822
        if ($this->duplicated_petition($_POST['petition_id'])) {
823
            $this->new_error_msg('Petición duplicada. Has hecho doble clic sobre el botón guardar
824
               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...
825
               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...
826
            $continuar = FALSE;
827
        }
828
829
        if ($continuar) {
830
            $this->nuevo_documento($albaran, $ejercicio, $serie, $almacen, $forma_pago, $divisa, $cliente);
831
832
            /// función auxiliar para implementar en los plugins que lo necesiten
833
            if (!fs_generar_numero2($albaran)) {
834
                $albaran->numero2 = $_POST['numero2'];
835
            }
836
837
            if ($albaran->save()) {
838
                $trazabilidad = FALSE;
839
840
                $n = floatval($_POST['numlineas']);
841
                for ($i = 0; $i <= $n; $i++) {
842
                    if (isset($_POST['referencia_' . $i])) {
843
                        $linea = new linea_albaran_cliente();
0 ignored issues
show
Bug introduced by
The type linea_albaran_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...
844
                        $linea->idalbaran = $albaran->idalbaran;
845
                        $this->nueva_linea($linea, $i, $serie, $cliente);
846
847
                        $articulo = $art0->get($_POST['referencia_' . $i]);
848
                        if ($articulo) {
849
                            $linea->referencia = $articulo->referencia;
850
                            if ($articulo->trazabilidad) {
851
                                $trazabilidad = TRUE;
852
                            }
853
854
                            if ($_POST['codcombinacion_' . $i]) {
855
                                $linea->codcombinacion = $_POST['codcombinacion_' . $i];
856
                            }
857
                        }
858
859
                        if ($linea->save()) {
860
                            if ($articulo && isset($_POST['stock'])) {
861
                                $stockfis = $articulo->stockfis;
862
                                if ($this->multi_almacen) {
863
                                    $stockfis = $stock0->total_from_articulo($articulo->referencia, $albaran->codalmacen);
864
                                }
865
866
                                if (!$articulo->controlstock && $linea->cantidad > $stockfis) {
867
                                    $this->new_error_msg("No hay suficiente stock del artículo <b>" . $linea->referencia . '</b>.');
868
                                    $linea->delete();
869
                                    $continuar = FALSE;
870
                                } else {
871
                                    /// descontamos del stock
872
                                    $articulo->sum_stock($albaran->codalmacen, 0 - $linea->cantidad, FALSE, $linea->codcombinacion);
873
                                }
874
                            }
875
876
                            if ($linea->irpf > $albaran->irpf) {
877
                                $albaran->irpf = $linea->irpf;
878
                            }
879
                        } else {
880
                            $this->new_error_msg("¡Imposible guardar la linea con referencia: " . $linea->referencia);
881
                            $continuar = FALSE;
882
                        }
883
                    }
884
                }
885
886
                if ($continuar) {
0 ignored issues
show
introduced by
The condition $continuar is always true.
Loading history...
887
                    /// obtenemos los subtotales por impuesto
888
                    $due_totales = $this->fbase_calc_due([$albaran->dtopor1, $albaran->dtopor2, $albaran->dtopor3, $albaran->dtopor4, $albaran->dtopor5]);
889
                    foreach ($this->fbase_get_subtotales_documento($albaran->get_lineas(), $due_totales) as $subt) {
890
                        $albaran->netosindto += $subt['netosindto'];
891
                        $albaran->neto += $subt['neto'];
892
                        $albaran->totaliva += $subt['iva'];
893
                        $albaran->totalirpf += $subt['irpf'];
894
                        $albaran->totalrecargo += $subt['recargo'];
895
                    }
896
897
                    $albaran->total = round($albaran->neto + $albaran->totaliva - $albaran->totalirpf + $albaran->totalrecargo, FS_NF0);
898
899
                    if (abs(floatval($_POST['atotal']) - $albaran->total) >= .02) {
900
                        $this->new_error_msg("El total difiere entre la vista y el controlador (" . $_POST['atotal'] .
901
                                " frente a " . $albaran->total . "). Debes informar del error.");
902
                        $albaran->delete();
903
                    } else if ($albaran->save()) {
904
                        /// Función de ejecución de tareas post guardado correcto del albaran
905
                        fs_documento_post_save($albaran);
906
907
                        $this->new_message("<a href='" . $albaran->url() . "'>" . ucfirst(FS_ALBARAN) . "</a> guardado correctamente.");
908
                        $this->new_change(ucfirst(FS_ALBARAN) . ' Cliente ' . $albaran->codigo, $albaran->url(), TRUE);
909
910
                        if ($trazabilidad) {
0 ignored issues
show
introduced by
The condition $trazabilidad is always false.
Loading history...
911
                            header('Location: index.php?page=ventas_trazabilidad&doc=albaran&id=' . $albaran->idalbaran);
912
                        } else if ($_POST['redir'] == 'TRUE') {
913
                            header('Location: ' . $albaran->url());
914
                        }
915
                    } else {
916
                        $this->new_error_msg("¡Imposible actualizar el <a href='" . $albaran->url() . "'>" . FS_ALBARAN . "</a>!");
917
                    }
918
                } else {
919
                    /// actualizamos el stock
920
                    foreach ($albaran->get_lineas() as $linea) {
921
                        if ($linea->referencia) {
922
                            $articulo = $art0->get($linea->referencia);
923
                            if ($articulo) {
924
                                $articulo->sum_stock($albaran->codalmacen, $linea->cantidad, FALSE, $linea->codcombinacion);
925
                            }
926
                        }
927
                    }
928
929
                    if (!$albaran->delete()) {
930
                        $this->new_error_msg("¡Imposible eliminar el <a href='" . $albaran->url() . "'>" . FS_ALBARAN . "</a>!");
931
                    }
932
                }
933
            } else {
934
                $this->new_error_msg("¡Imposible guardar el " . FS_ALBARAN . "!");
935
            }
936
        }
937
    }
938
939
    private function nueva_factura_cliente()
940
    {
941
        $continuar = TRUE;
942
943
        $cliente = $this->cliente->get($_POST['cliente']);
944
        if (!$cliente) {
945
            $this->new_error_msg('Cliente no encontrado.');
946
            $continuar = FALSE;
947
        }
948
949
        $almacen = $this->almacen->get($_POST['almacen']);
950
        if ($almacen) {
951
            $this->save_codalmacen($_POST['almacen']);
952
        } else {
953
            $this->new_error_msg('Almacén no encontrado.');
954
            $continuar = FALSE;
955
        }
956
957
        $eje0 = new ejercicio();
958
        $ejercicio = $eje0->get_by_fecha($_POST['fecha']);
959
        if (!$ejercicio) {
960
            $this->new_error_msg('Ejercicio no encontrado o está cerrado.');
961
            $continuar = FALSE;
962
        }
963
964
        $serie = $this->serie->get($_POST['serie']);
965
        if (!$serie) {
966
            $this->new_error_msg('Serie no encontrada.');
967
            $continuar = FALSE;
968
        }
969
970
        $forma_pago = $this->forma_pago->get($_POST['forma_pago']);
971
        if ($forma_pago) {
972
            $this->save_codpago($_POST['forma_pago']);
973
        } else {
974
            $this->new_error_msg('Forma de pago no encontrada.');
975
            $continuar = FALSE;
976
        }
977
978
        $divisa = $this->divisa->get($_POST['divisa']);
979
        if (!$divisa) {
980
            $this->new_error_msg('Divisa no encontrada.');
981
            $continuar = FALSE;
982
        }
983
984
        $art0 = new articulo();
985
        $factura = new factura_cliente();
986
        $stock0 = new stock();
987
988
        if ($this->duplicated_petition($_POST['petition_id'])) {
989
            $this->new_error_msg('Petición duplicada. Has hecho doble clic sobre el botón guardar
990
               y se han enviado dos peticiones. Mira en <a href="' . $factura->url() . '">Facturas</a>
991
               para ver si la factura se ha guardado correctamente.');
992
            $continuar = FALSE;
993
        }
994
995
        if ($continuar) {
996
            $this->nuevo_documento($factura, $ejercicio, $serie, $almacen, $forma_pago, $divisa, $cliente);
997
            $factura->set_fecha_hora($_POST['fecha'], $_POST['hora']);
998
999
            if ($forma_pago->genrecibos == 'Pagados') {
1000
                $factura->pagada = TRUE;
1001
            }
1002
1003
            $factura->vencimiento = $forma_pago->calcular_vencimiento($factura->fecha, $cliente->diaspago);
1004
1005
            /// función auxiliar para implementar en los plugins que lo necesiten
1006
            if (!fs_generar_numero2($factura)) {
1007
                $factura->numero2 = $_POST['numero2'];
1008
            }
1009
1010
            $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...
1011
            if ($regularizacion->get_fecha_inside($factura->fecha)) {
1012
                $this->new_error_msg("El " . FS_IVA . " de ese periodo ya ha sido regularizado."
1013
                        . " No se pueden añadir más facturas en esa fecha.");
1014
            } else if ($factura->save()) {
1015
                $trazabilidad = FALSE;
1016
1017
                $n = floatval($_POST['numlineas']);
1018
                for ($i = 0; $i <= $n; $i++) {
1019
                    if (isset($_POST['referencia_' . $i])) {
1020
                        $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...
1021
                        $linea->idfactura = $factura->idfactura;
1022
                        $this->nueva_linea($linea, $i, $serie, $cliente);
1023
1024
                        $articulo = $art0->get($_POST['referencia_' . $i]);
1025
                        if ($articulo) {
1026
                            $linea->referencia = $articulo->referencia;
1027
                            if ($articulo->trazabilidad) {
1028
                                $trazabilidad = TRUE;
1029
                            }
1030
1031
                            if ($_POST['codcombinacion_' . $i]) {
1032
                                $linea->codcombinacion = $_POST['codcombinacion_' . $i];
1033
                            }
1034
                        }
1035
1036
                        if ($linea->save()) {
1037
                            if ($articulo && isset($_POST['stock'])) {
1038
                                $stockfis = $articulo->stockfis;
1039
                                if ($this->multi_almacen) {
1040
                                    $stockfis = $stock0->total_from_articulo($articulo->referencia, $factura->codalmacen);
1041
                                }
1042
1043
                                if (!$articulo->controlstock && $linea->cantidad > $stockfis) {
1044
                                    $this->new_error_msg("No hay suficiente stock del artículo <b>" . $linea->referencia . '</b>.');
1045
                                    $linea->delete();
1046
                                    $continuar = FALSE;
1047
                                } else {
1048
                                    /// descontamos del stock
1049
                                    $articulo->sum_stock($factura->codalmacen, 0 - $linea->cantidad, FALSE, $linea->codcombinacion);
1050
                                }
1051
                            }
1052
1053
                            if ($linea->irpf > $factura->irpf) {
1054
                                $factura->irpf = $linea->irpf;
1055
                            }
1056
                        } else {
1057
                            $this->new_error_msg("¡Imposible guardar la linea con referencia: " . $linea->referencia);
1058
                            $continuar = FALSE;
1059
                        }
1060
                    }
1061
                }
1062
1063
                if ($continuar) {
0 ignored issues
show
introduced by
The condition $continuar is always true.
Loading history...
1064
                    /// obtenemos los subtotales por impuesto
1065
                    $due_totales = $this->fbase_calc_due([$factura->dtopor1, $factura->dtopor2, $factura->dtopor3, $factura->dtopor4, $factura->dtopor5]);
1066
                    foreach ($this->fbase_get_subtotales_documento($factura->get_lineas(), $due_totales) as $subt) {
1067
                        $factura->netosindto += $subt['netosindto'];
1068
                        $factura->neto += $subt['neto'];
1069
                        $factura->totaliva += $subt['iva'];
1070
                        $factura->totalirpf += $subt['irpf'];
1071
                        $factura->totalrecargo += $subt['recargo'];
1072
                    }
1073
1074
                    $factura->total = round($factura->neto + $factura->totaliva - $factura->totalirpf + $factura->totalrecargo, FS_NF0);
1075
1076
                    if (abs(floatval($_POST['atotal']) - $factura->total) >= .02) {
1077
                        $this->new_error_msg("El total difiere entre la vista y el controlador (" . $_POST['atotal'] .
1078
                                " frente a " . $factura->total . "). Debes informar del error.");
1079
                        $factura->delete();
1080
                    } else if ($factura->save()) {
1081
                        $this->fbase_generar_asiento($factura, FALSE);
1082
1083
                        /// Función de ejecución de tareas post guardado correcto de la factura
1084
                        fs_documento_post_save($factura);
1085
                        
1086
                        $this->new_message("<a href='" . $factura->url() . "'>Factura</a> guardada correctamente.");
1087
                        $this->new_change('Factura Cliente ' . $factura->codigo, $factura->url(), TRUE);
1088
1089
                        if ($trazabilidad) {
0 ignored issues
show
introduced by
The condition $trazabilidad is always false.
Loading history...
1090
                            header('Location: index.php?page=ventas_trazabilidad&doc=factura&id=' . $factura->idfactura);
1091
                        } else if ($_POST['redir'] == 'TRUE') {
1092
                            header('Location: ' . $factura->url());
1093
                        }
1094
                    } else {
1095
                        $this->new_error_msg("¡Imposible actualizar la <a href='" . $factura->url() . "'>Factura</a>!");
1096
                    }
1097
                } else {
1098
                    /// actualizamos el stock
1099
                    foreach ($factura->get_lineas() as $linea) {
1100
                        if ($linea->referencia) {
1101
                            $articulo = $art0->get($linea->referencia);
1102
                            if ($articulo) {
1103
                                $articulo->sum_stock($factura->codalmacen, $linea->cantidad, FALSE, $linea->codcombinacion);
1104
                            }
1105
                        }
1106
                    }
1107
1108
                    if (!$factura->delete()) {
1109
                        $this->new_error_msg("¡Imposible eliminar la <a href='" . $factura->url() . "'>Factura</a>!");
1110
                    }
1111
                }
1112
            } else {
1113
                $this->new_error_msg("¡Imposible guardar la Factura!");
1114
            }
1115
        }
1116
    }
1117
1118
    private function nuevo_documento(&$documento, $ejercicio, $serie, $almacen, $forma_pago, $divisa, $cliente)
1119
    {
1120
        $documento->fecha = $_POST['fecha'];
1121
        $documento->hora = $_POST['hora'];
1122
        $documento->codejercicio = $ejercicio->codejercicio;
1123
        $documento->codserie = $serie->codserie;
1124
        $documento->codalmacen = $almacen->codalmacen;
1125
        $documento->codpago = $forma_pago->codpago;
1126
        $documento->coddivisa = $divisa->coddivisa;
1127
        $documento->tasaconv = $divisa->tasaconv;
1128
1129
        if ($_POST['tasaconv'] != '') {
1130
            $documento->tasaconv = floatval($_POST['tasaconv']);
1131
        }
1132
1133
        $documento->codagente = $this->agente->codagente;
1134
        $documento->observaciones = $_POST['observaciones'];
1135
        $documento->porcomision = $this->agente->porcomision;
1136
1137
        $documento->codcliente = $cliente->codcliente;
1138
        $documento->cifnif = $_POST['cifnif'];
1139
        $documento->nombrecliente = $_POST['nombrecliente'];
1140
        $documento->codpais = $_POST['codpais'];
1141
        $documento->provincia = $_POST['provincia'];
1142
        $documento->ciudad = $_POST['ciudad'];
1143
        $documento->codpostal = $_POST['codpostal'];
1144
        $documento->direccion = $_POST['direccion'];
1145
        $documento->apartado = $_POST['apartado'];
1146
1147
        if (is_numeric($_POST['coddir'])) {
1148
            $documento->coddir = $_POST['coddir'];
1149
        }
1150
1151
        /// envío
1152
        $documento->envio_nombre = $_POST['envio_nombre'];
1153
        $documento->envio_apellidos = $_POST['envio_apellidos'];
1154
        if ($_POST['envio_codtrans'] != '') {
1155
            $documento->envio_codtrans = $_POST['envio_codtrans'];
1156
        }
1157
        $documento->envio_codigo = $_POST['envio_codigo'];
1158
        $documento->envio_codpais = $_POST['envio_codpais'];
1159
        $documento->envio_provincia = $_POST['envio_provincia'];
1160
        $documento->envio_ciudad = $_POST['envio_ciudad'];
1161
        $documento->envio_codpostal = $_POST['envio_codpostal'];
1162
        $documento->envio_direccion = $_POST['envio_direccion'];
1163
        $documento->envio_apartado = $_POST['envio_apartado'];
1164
1165
        $documento->dtopor1 = floatval($_POST['adtopor1']);
1166
        $documento->dtopor2 = floatval($_POST['adtopor2']);
1167
        $documento->dtopor3 = floatval($_POST['adtopor3']);
1168
        $documento->dtopor4 = floatval($_POST['adtopor4']);
1169
        $documento->dtopor5 = floatval($_POST['adtopor5']);
1170
    }
1171
1172
    private function nueva_linea(&$linea, $i, $serie, $cliente)
1173
    {
1174
        $linea->descripcion = $_POST['desc_' . $i];
1175
1176
        if (!$serie->siniva && $cliente->regimeniva != 'Exento') {
1177
            $imp0 = $this->impuesto->get_by_iva($_POST['iva_' . $i]);
1178
            if ($imp0) {
1179
                $linea->codimpuesto = $imp0->codimpuesto;
1180
                $linea->iva = floatval($_POST['iva_' . $i]);
1181
                $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

1181
                $linea->recargo = floatval(/** @scrutinizer ignore-call */ fs_filter_input_post('recargo_' . $i, 0));
Loading history...
1182
        } else {
1183
                $linea->iva = floatval($_POST['iva_' . $i]);
1184
                $linea->recargo = floatval(fs_filter_input_post('recargo_' . $i, 0));
1185
        }
1186
    }
1187
1188
        $linea->irpf = floatval(fs_filter_input_post('irpf_' . $i, 0));
1189
        $linea->pvpunitario = floatval($_POST['pvp_' . $i]);
1190
        $linea->cantidad = floatval($_POST['cantidad_' . $i]);
1191
        $linea->dtopor = floatval(fs_filter_input_post('dto_' . $i, 0));
1192
        $linea->dtopor2 = floatval(fs_filter_input_post('dto2_' . $i, 0));
1193
        $linea->dtopor3 = floatval(fs_filter_input_post('dto3_' . $i, 0));
1194
        $linea->dtopor4 = floatval(fs_filter_input_post('dto4_' . $i, 0));
1195
        $linea->pvpsindto = $linea->pvpunitario * $linea->cantidad;
1196
1197
        // Descuento Unificado Equivalente
1198
        $due_linea = $this->fbase_calc_due(array($linea->dtopor, $linea->dtopor2, $linea->dtopor3, $linea->dtopor4));
1199
        $linea->pvptotal = $linea->cantidad * $linea->pvpunitario * $due_linea;
1200
    }
1201
}
1202