Passed
Push — master ( 11ca94...9f95e8 )
by Joe Nilson
02:08
created

tratamientoPosteriorFactura()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 7
c 0
b 0
f 0
nc 4
nop 4
dl 0
loc 12
rs 10
1
<?php
2
/*
3
 * Copyright (C) 2021 Joe Nilson <[email protected]>
4
 *
5
 * This program is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU Lesser General Public License as
7
 * published by the Free Software Foundation, either version 3 of the
8
 * License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU Lesser General Public License for more details.
14
 * You should have received a copy of the GNU Lesser General Public License
15
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
 */
17
require_once 'base/fs_model.php';
18
require_once 'plugins/residentes/extras/residentesFacturaDetallada.php';
19
20
class residentesFacturaProgramada extends fs_model
21
{
22
    public $db;
23
    public $log;
24
    public $ahora;
25
    public $horaActual;
26
    public $residentesFactProg;
27
    public $residentesFactProgEdif;
28
    public $residentesFactProgCon;
29
    public function __construct(&$db, &$core_log)
30
    {
31
        $this->db = $db;
32
        $this->log = $core_log;
33
        $this->ahora = \date('Y-m-d');
34
        $this->horaActual = \date('H');
35
        $this->residentesFactProg = new residentes_facturacion_programada();
36
        $this->residentesFactProgEdif = new residentes_facturacion_programada_edificaciones();
37
        $this->residentesFactProgCon = new residentes_facturacion_programada_conceptos();
38
    }
39
40
    public function conceptoFacturable($codcliente, $referencia)
41
    {
42
        $sql = "SELECT count(referencia) as facturado from lineasfacturascli where referencia = ".
43
            $this->var2str($referencia) .
44
            " AND idfactura IN (select idfactura from facturascli WHERE codcliente = ".$this->var2str($codcliente).");";
45
        $data = $this->db->select($sql);
46
        if (!$data[0]['facturado']) {
47
            return true;
48
        }
49
        return false;
50
    }
51
52
    public function tratamientoPosteriorFactura(&$cliente_residente, &$empresaTable, &$factura, $tratamiento)
53
    {
54
        switch ($tratamiento) {
55
            case "enviar":
56
57
                break;
58
            case "imprimir":
59
60
                break;
61
            case "generar":
62
63
                break;
64
        }
65
66
    }
67
68
    public function nuevaFactura($residenteProg, &$jobDisponible)
69
    {
70
        $clienteTable = new cliente();
71
        $empresaTable = new empresa();
72
        $cliente_residente = $clienteTable->get($residenteProg->codcliente);
73
        $residenteInformacion = new residentes_informacion();
74
        $informacion = $residenteInformacion->get($residenteProg->codcliente);
75
        $residenteEdificacion = new residentes_edificaciones();
76
        $residenteEdif = $residenteEdificacion->get_by_field('codcliente', $residenteProg->codcliente);
77
        $cliente_residente->inmueble = $residenteEdif[0];
78
        $cliente_residente->informacion = $informacion;
79
80
        $residente = $clienteTable->get($residenteProg->codcliente);
81
82
        if ($residente) {
83
            $factura = new factura_cliente();
84
            $this->nuevaCabeceraFactura($factura, $residente, $empresaTable, $jobDisponible);
85
86
            if ($factura->save()) {
87
                $listaArticulos = $this->residentesFactProgCon->getConceptosByIdProgramacion($residenteProg->idprogramacion);
88
89
                $this->nuevoDetalleFactura($factura, $residente, $listaArticulos);
90
91
                $this->nuevoTotalFactura($factura, $residenteProg, $empresaTable);
92
                if (!in_array($cliente_residente->email, [null, ''], true) && $jobDisponible->tipo_programacion === 'enviar') {
93
                    $archivo = $factura->codigo . '_' . $factura->numero2 . '.pdf';
94
                    $documento = new residentesFacturaDetallada('L', 'mm', 'A5', $jobDisponible->tipo_programacion, $archivo, 'cron');
95
                    $documento->crearFactura($empresaTable, $factura, $cliente_residente);
96
                }
97
                ++$jobDisponible->facturas_generadas;
98
                $jobDisponible->save();
99
            } else {
100
                $this->log->new_error_msg('Imposible guardar la factura.');
101
            }
102
        } else {
103
            $this->log->new_error_msg('Cliente no encontrado.');
104
        }
105
    }
106
107
    public function nuevaCabeceraFactura(&$factura, &$residente, &$empresaTable, &$jobDisponible)
108
    {
109
        $factura->codserie = ($residente->codserie) ?: $empresaTable->codserie;
110
        $factura->codpago = $jobDisponible->forma_pago;
111
        $factura->codalmacen = $empresaTable->codalmacen;
112
        $factura->codagente = '1';
113
        $factura->set_fecha_hora(\date('Y-m-d'), \date('H:i:s'));
114
115
        $this->nuevaVerificacionContabilidadFactura($factura, $residente, $empresaTable);
116
117
        $this->nuevaDivisaFactura($factura, $residente);
118
119
        $factura->codcliente = $residente->codcliente;
120
        $this->nuevaInformacionResidenteFactura($factura, $residente);
121
122
        /// función auxiliar para implementar en los plugins que lo necesiten
123
        if (!fs_generar_numero2($factura)) {
124
            $factura->numero2 = '';
125
            echo "No hay funcion libre. \n";
126
        }
127
    }
128
129
    public function nuevoDetalleFactura(&$factura, &$residente, $listaArticulos)
130
    {
131
        $art0 = new articulo();
132
        $impuesto = new impuesto();
133
134
        foreach ($listaArticulos as $concepto) {
135
            $art = $art0->get($concepto->referencia);
136
            if ($this->conceptoFacturable($residente->codcliente, $concepto->referencia)) {
137
                $linea = new linea_factura_cliente();
138
                $linea->idfactura = $factura->idfactura;
139
                $linea->referencia = $concepto->referencia;
140
                $linea->descripcion = $art->descripcion;
141
                $linea->cantidad = $concepto->cantidad;
142
                $imp = $impuesto->get($concepto->codimpuesto);
143
                $linea->codimpuesto = $imp->codimpuesto;
144
                $linea->iva = $imp->iva;
145
                $linea->pvpsindto = $concepto->pvp;
146
                $linea->pvpunitario = $concepto->pvp;
147
                $linea->pvptotal = $concepto->pvp * $concepto->cantidad;
148
                $this->nuevoTotalLineasFactura($factura, $linea);
149
            }
150
        }
151
    }
152
153
    public function nuevoTotalLineasFactura(&$factura, &$linea)
154
    {
155
        if ($linea->save()) {
156
            $factura->neto += $linea->pvptotal;
157
            $factura->totaliva += $linea->pvptotal * $linea->iva / 100;
158
        }
159
    }
160
161
    /**
162
     * @param factura_cliente $factura
163
     * @param object $residenteProgramado
164
     * @param object $empresaTable
165
     */
166
    public function nuevoTotalFactura(&$factura, &$residenteProgramado, &$empresaTable)
167
    {
168
        /// redondeamos
169
        $factura->neto = round($factura->neto, FS_NF0);
170
        $factura->totaliva = round($factura->totaliva, FS_NF0);
171
        $factura->totalirpf = round($factura->totalirpf, FS_NF0);
172
        $factura->totalrecargo = round($factura->totalrecargo, FS_NF0);
173
        $factura->total = $factura->neto + $factura->totaliva - $factura->totalirpf + $factura->totalrecargo;
174
        if ($factura->save()) {
175
            $this->generar_asiento($factura, $empresaTable);
176
            /// Función de ejecución de tareas post guardado correcto de la factura
177
            fs_documento_post_save($factura);
178
            //Actualizamos la data del residente
179
            $residenteProgramado->idfactura = $factura->idfactura;
180
            $residenteProgramado->procesado = true;
181
            $residenteProgramado->save();
182
        } else {
183
            $factura->delete();
184
        }
185
    }
186
187
    public function nuevaVerificacionContabilidadFactura(&$factura, &$residente, &$empresaTable)
188
    {
189
        $eje0 = new ejercicio();
190
        $ejercicio = $eje0->get_by_fecha(date('d-m-Y'));
191
        if ($ejercicio) {
192
            $factura->codejercicio = $ejercicio->codejercicio;
193
        }
194
        if ($empresaTable->contintegrada) {
195
            /// forzamos crear la subcuenta
196
            $residente->get_subcuenta($empresaTable->codejercicio);
197
        }
198
    }
199
200
    public function nuevaDivisaFactura(&$factura, &$residente)
201
    {
202
        $div0 = new divisa();
203
        $divisa = $div0->get($residente->coddivisa);
204
        if ($divisa) {
205
            $factura->coddivisa = $divisa->coddivisa;
206
            $factura->tasaconv = $divisa->tasaconv;
207
        }
208
    }
209
210
    public function nuevaInformacionResidenteFactura(&$factura, &$residente)
211
    {
212
        foreach ($residente->get_direcciones() as $d) {
213
            if ($d->domfacturacion) {
214
                $factura->codcliente = $residente->codcliente;
215
                $factura->cifnif = $residente->cifnif;
216
                $factura->nombrecliente = $residente->nombre;
217
                $factura->apartado = $d->apartado;
218
                $factura->ciudad = $d->ciudad;
219
                $factura->coddir = $d->id;
220
                $factura->codpais = $d->codpais;
221
                $factura->codpostal = $d->codpostal;
222
                $factura->direccion = $d->direccion;
223
                $factura->provincia = $d->provincia;
224
                break;
225
            }
226
        }
227
    }
228
229
    /**
230
     * Genera el asiento para la factura, si procede
231
     * @param factura_cliente $factura
232
     */
233
    public function generar_asiento(&$factura, &$empresaTable)
234
    {
235
        if ($empresaTable->contintegrada) {
236
            $asiento_factura = new asiento_factura();
237
            $asiento_factura->generar_asiento_venta($factura);
238
        } else {
239
            /// de todas formas forzamos la generación de las líneas de iva
240
            $factura->get_lineas_iva();
241
        }
242
    }
243
244
    public function delete()
245
    {
246
        // TODO: Implement delete() method.
247
    }
248
249
    public function exists()
250
    {
251
        // TODO: Implement exists() method.
252
    }
253
254
    public function save()
255
    {
256
        // TODO: Implement save() method.
257
    }
258
}