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

get_by_id_and_status()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 3
nop 2
dl 0
loc 13
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * Copyright (C) 2019 joenilson.
5
 *
6
 * This library is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
8
 * License as published by the Free Software Foundation; either
9
 * version 3 of the License, or (at your option) any later version.
10
 *
11
 * This library 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 GNU
14
 * Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with this library; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA 02110-1301  USA
20
 */
21
22
namespace FacturaScripts\model;
23
24
/**
25
 * Description of residentes_facturacion_programada
26
 *
27
 * @author joenilson
28
 */
29
class residentes_facturacion_programada extends \fs_model
30
{
31
    public $id;
32
    public $descripcion;
33
    public $forma_pago;
34
    public $formato_factura;
35
    public $fecha_envio;
36
    public $hora_envio;
37
    public $residentes_facturar;
38
    public $facturas_generadas;
39
    public $usuario_creacion;
40
    public $usuario_modificacion;
41
    public $estado;
42
    public $fecha_creacion;
43
    public $fecha_modificacion;
44
    
45
    public $ahora;
46
    public $horaActual;
47
    public function __construct($t = false)
48
    {
49
        parent::__construct('residentes_fact_prog', 'plugins/residentes');
50
        if ($t) {
51
            $this->id = $t['id'];
52
            $this->descripcion = $t['descripcion'];
53
            $this->forma_pago = $t['forma_pago'];
54
            $this->formato_factura = $t['formato_factura'];
55
            $this->fecha_envio = $t['fecha_envio'];
56
            $this->hora_envio = $t['hora_envio'];
57
            $this->residentes_facturar = $t['residentes_facturar'];
58
            $this->facturas_generadas = $t['facturas_generadas'];
59
            $this->usuario_creacion = $t['usuario_creacion'];
60
            $this->usuario_modificacion = $t['usuario_modificacion'];
61
            $this->estado = $t['estado'];
62
            $this->fecha_creacion = $t['fecha_creacion'];
63
            $this->fecha_modificacion = $t['fecha_modificacion'];
64
        } else {
65
            $this->id = null;
66
            $this->descripcion = '';
67
            $this->forma_pago = '';
68
            $this->formato_factura = 'plantillas_pdf';
69
            $this->fecha_envio = null;
70
            $this->hora_envio = null;
71
            $this->residentes_facturar = 0;
72
            $this->facturas_generadas = 0;
73
            $this->usuario_creacion = null;
74
            $this->usuario_modificacion = null;
75
            $this->estado = 'ENCOLA';
76
            $this->fecha_creacion = null;
77
            $this->fecha_modificacion = null;
78
        }
79
        $this->ahora = new \DateTime('NOW');
80
        $this->horaActual = strtotime($this->ahora->format('H'));
81
    }
82
83
    public function install()
84
    {
85
        return "";
86
    }
87
    
88
    public function exists()
89
    {
90
        if (is_null($this->id)) {
91
            return false;
92
        }
93
        return true;
94
    }
95
    
96
    public function save()
97
    {
98
        if ($this->exists()) {
99
            $sql = "UPDATE ".$this->table_name." SET ".
100
            "descripcion = ".$this->var2str($this->descripcion).", ".
101
            "forma_pago = ".$this->var2str($this->forma_pago).", ".
102
            "formato_factura = ".$this->var2str($this->formato_factura).", ".
103
            "fecha_envio = ".$this->var2str($this->fecha_envio).", ".
104
            "hora_envio = ".$this->var2str($this->hora_envio).", ".
105
            "residentes_facturar = ".$this->intval($this->residentes_facturar).", ".
106
            "facturas_generadas = ".$this->intval($this->facturas_generadas).", ".
107
            "estado = ".$this->var2str($this->estado).", ".
108
            "usuario_modificacion = ".$this->var2str($this->usuario_modificacion).", ".
109
            "fecha_modificacion = ".$this->var2str($this->fecha_modificacion)." ".
110
            "WHERE id = ".$this->intval($this->id).";";
111
            $data = $this->db->exec($sql);
112
            return $data;
113
        } else {
114
            $sql = "INSERT INTO ".$this->table_name.
115
            " (descripcion, forma_pago, formato_factura, fecha_envio, hora_envio, residentes_facturar, ".
116
                "facturas_generadas, usuario_creacion, fecha_creacion, estado) VALUES (".
117
            $this->var2str($this->descripcion).", ".
118
            $this->var2str($this->forma_pago).", ".
119
            $this->var2str($this->formato_factura).", ".
120
            $this->var2str($this->fecha_envio).", ".
121
            $this->var2str($this->hora_envio).", ".
122
            $this->intval($this->residentes_facturar).", ".
123
            $this->intval($this->facturas_generadas).", ".
124
            $this->var2str($this->usuario_creacion).", ".
125
            $this->var2str($this->fecha_creacion).", ".
126
            $this->var2str($this->estado).");";
127
            if ($this->db->exec($sql)) {
128
                return $this->db->lastval();
129
            } else {
130
                return false;
131
            }
132
        }
133
    }
134
135
    /**
136
     * @param integer $id
137
     * @return residentes_facturacion_programada|false
138
     */
139
    public function get($id)
140
    {
141
        $sql = "select * from ".$this->table_name." WHERE id = ".$this->intval($id);
142
        
143
        $data = $this->db->select($sql);
144
        if ($data) {
145
            return new residentes_facturacion_programada($data[0]);
146
        }
147
        return false;
148
    }
149
150
    /**
151
     * @param string $date
152
     * @return array|false
153
     */
154
    public function get_by_date($date)
155
    {
156
        $sql = "select * from ".$this->table_name." WHERE fecha_envio = ".$this->var2str($date).
157
            " ORDER BY fecha_envio, hora_envio";
158
        $data = $this->db->select($sql);
159
        $lista = array();
160
        if ($data) {
161
            foreach ($data as $d) {
162
                $lista[] = new residentes_facturacion_programada($d);
163
            }
164
            return $lista;
165
        }
166
        return false;
167
    }
168
169
    /**
170
     * @param integer $id
171
     * @param string $status
172
     * @return array|false
173
     */
174
    public function get_by_id_and_status($id, $status = 'CONCLUIDO')
175
    {
176
        $sql = "select * from ".$this->table_name." WHERE ESTADO = ".$this->var2str($status).
177
            " ORDER BY fecha_envio, hora_envio";
178
        $data = $this->db->select($sql);
179
        $lista = array();
180
        if ($data) {
181
            foreach ($data as $d) {
182
                $lista[] = new residentes_facturacion_programada($d);
183
            }
184
            return $lista;
185
        }
186
        return false;
187
    }
188
    
189
    public function get_by_date_status($date, $status)
190
    {
191
        $sql = "select * from ".$this->table_name." WHERE fecha_envio = ".$this->var2str($date)
192
                ." AND "."estado = ".$this->var2str($status)." ORDER BY fecha_envio, hora_envio";
193
        $data = $this->db->select($sql);
194
        $lista = array();
195
        if ($data) {
196
            foreach ($data as $d) {
197
                $lista[] = new residentes_facturacion_programada($d);
198
            }
199
            return $lista;
200
        }
201
        return false;
202
    }
203
    
204
    public function get_by_date_hour_status($date, $hour, $status)
205
    {
206
        $sql = "select * from ".$this->table_name." WHERE fecha_envio = ".$this->var2str($date)
207
                ." AND ".
208
                " hora_envio = ".$this->var2str($hour).
209
                " AND ".
210
                "estado = ".$this->var2str($status)." ORDER BY fecha_envio, hora_envio";
211
        $data = $this->db->select($sql);
212
        if ($data) {
213
            return new residentes_facturacion_programada($data[0]);
214
        }
215
        return false;
216
    }
217
    
218
    public function all()
219
    {
220
        $sql = "select * from ".$this->table_name." ORDER BY fecha_envio, hora_envio";
221
        $data = $this->db->select($sql);
222
        $lista = array();
223
        if ($data) {
224
            foreach ($data as $d) {
225
                $lista[] = new residentes_facturacion_programada($d);
226
            }
227
            return $lista;
228
        }
229
        return false;
230
    }
231
    
232
    public function delete()
233
    {
234
        $sql = "DELETE from ".$this->table_name." WHERE id = ".$this->intval($this->id);
235
        $data = $this->db->exec($sql);
236
        if ($data) {
237
            return true;
238
        }
239
        return false;
240
    }
241
    
242
    public function eliminar_facturas()
243
    {
244
        $rfpe = new residentes_facturacion_programada_edificaciones();
245
        $listaResidentes = $rfpe->getByIdProgramacion($this->id);
246
        foreach ($listaResidentes as $residente) {
247
            $fact = new factura_cliente();
248
            $f = $fact->get($residente->idfactura);
249
            if ($f) {
250
                $f->delete();
251
            }
252
            $residente->procesado = false;
253
            $residente->idfactura = '';
254
            $residente->save();
255
        }
256
    }
257
    
258
    public function conceptoFacturable($codcliente, $referencia)
259
    {
260
        $sql = "SELECT count(referencia) as facturado from lineasfacturascli where referencia = ".
261
            $this->var2str($referencia)." ".
262
            " AND idfactura IN (select idfactura from facturascli WHERE codcliente = ".$this->var2str($codcliente).");";
263
        $data = $this->db->select($sql);
264
        if (!$data[0]['facturado']) {
265
            return true;
266
        }
267
        return false;
268
    }
269
    
270
    public function startJob($jobDisponible)
271
    {
272
        $idProg = $jobDisponible->id;
273
        $residentesProgramados = new residentes_facturacion_programada_edificaciones();
274
        $listaResidentes = $residentesProgramados->getByIdProgramacionPendientes($idProg);
275
        foreach ($listaResidentes as $residente) {
276
            $this->stepJob($residente, $jobDisponible);
277
        }
278
        
279
        $this->finishJob($jobDisponible);
280
    }
281
    
282
    public function stepJob(&$residente, &$jobDisponible)
283
    {
284
        if ($residente->procesado === false) {
285
            $this->nuevaFactura($residente, $jobDisponible);
286
        }
287
    }
288
    
289
    public function stopJob()
290
    {
291
    }
292
    
293
    public function finishJob(&$jobDisponible)
294
    {
295
        $residentesProgramados = new residentes_facturacion_programada_edificaciones();
296
        $residentesPendientes = $residentesProgramados->getByIdProgramacionPendientes($jobDisponible->id);
297
        $residentesFacturados = $residentesProgramados->getByIdProgramacion($jobDisponible->id);
298
        if ($residentesPendientes === false) {
299
            $jobDisponible->estado = 'CONCLUIDO';
300
            $jobDisponible->facturas_generadas = ($residentesFacturados) ? count($residentesFacturados) : 0;
301
            $jobDisponible->usuario_modificacion = 'cron';
302
            $jobDisponible->fecha_modificacion = \date('Y-m-d H:i:s');
303
            $jobDisponible->save();
304
        }
305
    }
306
    
307
    public function initCron()
308
    {
309
        $ahora = \date('Y-m-d');
310
        $horaActual = \date('H');
311
        $jobDisponible = $this->get_by_date_hour_status($ahora, $horaActual, 'ENCOLA');
312
        if ($jobDisponible) {
313
            echo " ** Se inicia el proceso de Facturación Programada ".$ahora." ".$horaActual." ** \n";
314
            $this->new_advice(' ** Se inicia el proceso de Facturación Programada ** ');
315
            $jobDisponible->estado = 'ENPROCESO';
316
            $jobDisponible->usuario_modificacion = 'cron';
317
            $jobDisponible->fecha_modificacion = \date('Y-m-d H:i:s');
318
            $jobDisponible->save();
319
            $this->startJob($jobDisponible);
320
        } else {
321
            echo " ** No coincide la hora de proceso con la de ejecucion de cron se omite el proceso ".
322
                "$ahora $horaActual ** \n";
323
            $this->new_advice(' ** No coincide la hora de proceso con la de ejecucion de cron se omite el proceso ** ');
324
        }
325
    }
326
    
327
    public function statusJob()
328
    {
329
    }
330
    
331
    public function nuevaFactura($resProgramado, &$jobDisponible)
332
    {
333
        $clienteTable = new cliente();
1 ignored issue
show
Bug introduced by
The type FacturaScripts\model\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...
334
        $empresaTable = new empresa();
0 ignored issues
show
Bug introduced by
The type FacturaScripts\model\empresa was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
335
        $residente = $clienteTable->get($resProgramado->codcliente);
336
        if ($residente) {
337
            $factura = new factura_cliente();
338
            $this->nuevaCabeceraFactura($factura, $residente, $empresaTable, $jobDisponible);
339
            
340
            if ($factura->save()) {
341
                $conceptosProgramados = new residentes_facturacion_programada_conceptos();
342
                $listaArticulos = $conceptosProgramados->getConceptosByIdProgramacion($resProgramado->idprogramacion);
343
                
344
                $this->nuevoDetalleFactura($factura, $residente, $listaArticulos);
345
                
346
                $this->nuevoTotalFactura($factura, $resProgramado, $empresaTable);
347
                ++$jobDisponible->facturas_generadas;
348
                $jobDisponible->save();
349
            } else {
350
                $this->new_error_msg('Imposible guardar la factura.');
351
            }
352
        } else {
353
            $this->new_error_msg('Cliente no encontrado.');
354
        }
355
    }
356
    
357
    public function nuevaCabeceraFactura(&$factura, &$residente, &$empresaTable, &$jobDisponible)
358
    {
359
        $factura->codserie = ($residente->codserie) ?: $empresaTable->codserie;
360
        $factura->codpago = $jobDisponible->forma_pago;
361
        $factura->codalmacen = $empresaTable->codalmacen;
362
        $factura->codagente = '1';
363
        $factura->set_fecha_hora(\date('Y-m-d'), \date('H:i:s'));
364
365
        $this->nuevaVerificacionContabilidadFactura($factura, $residente, $empresaTable);
366
367
        $this->nuevaDivisaFactura($factura, $residente);
368
369
        $factura->codcliente = $residente->codcliente;
370
        $this->nuevaInformacionResidenteFactura($factura, $residente);
371
        
372
        /// función auxiliar para implementar en los plugins que lo necesiten
373
        if (!fs_generar_numero2($factura)) {
374
            $factura->numero2 = '';
375
            echo "No hay funcion libre. \n";
376
        }
377
    }
378
    
379
    public function nuevoDetalleFactura(&$factura, &$residente, $listaArticulos)
380
    {
381
        $art0 = new articulo();
382
        $impuesto = new impuesto();
383
        
384
        foreach ($listaArticulos as $concepto) {
385
            $art = $art0->get($concepto->referencia);
386
            if ($this->conceptoFacturable($residente->codcliente, $concepto->referencia)) {
387
                $linea = new linea_factura_cliente();
388
                $linea->idfactura = $factura->idfactura;
389
                $linea->referencia = $concepto->referencia;
390
                $linea->descripcion = $art->descripcion;
391
                $linea->cantidad = $concepto->cantidad;
392
                $imp = $impuesto->get($concepto->codimpuesto);
393
                $linea->codimpuesto = $imp->codimpuesto;
394
                $linea->iva = $imp->iva;
395
                $linea->pvpsindto = $concepto->pvp;
396
                $linea->pvpunitario = $concepto->pvp;
397
                $linea->pvptotal = $concepto->pvp * $concepto->cantidad;
398
                $this->nuevoTotalLineasFactura($factura, $linea);
399
            }
400
        }
401
    }
402
    
403
    public function nuevoTotalLineasFactura(&$factura, &$linea)
404
    {
405
        if ($linea->save()) {
406
            $factura->neto += $linea->pvptotal;
407
            $factura->totaliva += $linea->pvptotal * $linea->iva / 100;
408
        }
409
    }
410
    
411
    public function nuevoTotalFactura(&$factura, &$residenteProgramado, &$empresaTable)
412
    {
413
        /// redondeamos
414
        $factura->neto = round($factura->neto, FS_NF0);
415
        $factura->totaliva = round($factura->totaliva, FS_NF0);
416
        $factura->totalirpf = round($factura->totalirpf, FS_NF0);
417
        $factura->totalrecargo = round($factura->totalrecargo, FS_NF0);
418
        $factura->total = $factura->neto + $factura->totaliva - $factura->totalirpf + $factura->totalrecargo;
419
420
        if ($factura->save()) {
421
            $this->generar_asiento($factura, $empresaTable);
422
            /// Función de ejecución de tareas post guardado correcto de la factura
423
            fs_documento_post_save($factura);
424
            //Actualizamos la data del residente
425
            $residenteProgramado->idfactura = $factura->idfactura;
426
            $residenteProgramado->procesado = true;
427
            $residenteProgramado->save();
428
        } else {
429
            $factura->delete();
430
        }
431
    }
432
    
433
    public function nuevaVerificacionContabilidadFactura(&$factura, &$residente, &$empresaTable)
434
    {
435
        $eje0 = new ejercicio();
436
        $ejercicio = $eje0->get_by_fecha(date('d-m-Y'));
437
        if ($ejercicio) {
438
            $factura->codejercicio = $ejercicio->codejercicio;
439
        }
440
        if ($empresaTable->contintegrada) {
441
            /// forzamos crear la subcuenta
442
            $residente->get_subcuenta($empresaTable->codejercicio);
443
        }
444
    }
445
    
446
    public function nuevaDivisaFactura(&$factura, &$residente)
447
    {
448
        $div0 = new divisa();
0 ignored issues
show
Bug introduced by
The type FacturaScripts\model\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...
449
        $divisa = $div0->get($residente->coddivisa);
450
        if ($divisa) {
451
            $factura->coddivisa = $divisa->coddivisa;
452
            $factura->tasaconv = $divisa->tasaconv;
453
        }
454
    }
455
    
456
    public function nuevaInformacionResidenteFactura(&$factura, &$residente)
457
    {
458
        foreach ($residente->get_direcciones() as $d) {
459
            if ($d->domfacturacion) {
460
                $factura->codcliente = $residente->codcliente;
461
                $factura->cifnif = $residente->cifnif;
462
                $factura->nombrecliente = $residente->nombre;
463
                $factura->apartado = $d->apartado;
464
                $factura->ciudad = $d->ciudad;
465
                $factura->coddir = $d->id;
466
                $factura->codpais = $d->codpais;
467
                $factura->codpostal = $d->codpostal;
468
                $factura->direccion = $d->direccion;
469
                $factura->provincia = $d->provincia;
470
                break;
471
            }
472
        }
473
    }
474
475
    /**
476
     * Genera el asiento para la factura, si procede
477
     * @param factura_cliente $factura
478
     */
479
    public function generar_asiento(&$factura, &$empresaTable)
480
    {
481
        if ($empresaTable->contintegrada) {
482
            $asiento_factura = new asiento_factura();
0 ignored issues
show
Bug introduced by
The type FacturaScripts\model\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...
483
            $asiento_factura->generar_asiento_venta($factura);
484
        } else {
485
            /// de todas formas forzamos la generación de las líneas de iva
486
            $factura->get_lineas_iva();
487
        }
488
    }
489
}
490