informe_estadocuenta::prepararDatos()   A
last analyzed

Complexity

Conditions 5
Paths 9

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 10
c 0
b 0
f 0
nc 9
nop 5
dl 0
loc 16
rs 9.6111
1
<?php
2
3
/*
4
 * Copyright (C) 2017 Joe Nilson <joenilson at gmail.com>
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public License
17
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19
require_once 'plugins/republica_dominicana/extras/rd_controller.php';
20
require_once 'plugins/republica_dominicana/extras/rospdf/pdf-php/src/Cezpdf_DOM.php';
21
require_once 'extras/xlsxwriter.class.php';
22
23
/**
24
 * Description of informe_estadocuenta
25
 *
26
 * @author Joe Nilson <joenilson at gmail.com>
27
 */
28
class informe_estadocuenta extends rd_controller
29
{
30
    public $cliente;
31
    public $desde;
32
    public $hasta;
33
    public $estado;
34
    public $resultados;
35
    public $resultados_d30;
36
    public $resultados_d60;
37
    public $resultados_d90;
38
    public $resultados_d120;
39
    public $resultados_md120;
40
    public $vencimientos = array(30,60,90,120,121);
41
    public $current_date;
42
    public $sql_aux;
43
    public $limit;
44
    public $sort;
45
    public $order;
46
    public $fileXLSX;
47
    public $filePDF;
48
    public $archivo = 'Estado_Cuenta';
49
    public function __construct()
50
    {
51
        parent::__construct(__CLASS__, 'Estado de Cuenta Clientes', 'informes', false, true, false);
52
    }
53
54
    protected function private_core()
55
    {
56
        parent::private_core();
57
        $this->share_extensions();
58
        $this->init_filters();
59
        $this->sql_aux();
60
        if (isset($_REQUEST['buscar_cliente'])) {
61
            $this->fbase_buscar_cliente($_REQUEST['buscar_cliente']);
62
        } elseif (\filter_input(INPUT_POST, 'listado_facturas')) {
63
            $this->tabla_de_datos();
64
        } elseif(\filter_input(INPUT_POST, 'generar')) {
65
            $this->vencimiento_facturas();
66
            $this->sort = 'codalmacen, fecha, idfactura ';
67
            $this->order = 'ASC';
68
            $this->crearXLSX();
69
            $this->crearPDF();
70
        }
71
    }
72
73
    protected function init_filters()
74
    {
75
        $cli0 = 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...
76
        $this->hasta = $this->confirmarValor($this->filter_request('hasta'),\date('d-m-Y'));
77
        $this->codserie = $this->confirmarValor($this->filter_request('codserie'),false);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type string expected by parameter $valor2 of rd_controller::confirmarValor(). ( Ignorable by Annotation )

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

77
        $this->codserie = $this->confirmarValor($this->filter_request('codserie'),/** @scrutinizer ignore-type */ false);
Loading history...
Bug Best Practice introduced by
The property codserie does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
78
        $this->codpago = $this->confirmarValor($this->filter_request('codpago'),false);
0 ignored issues
show
Bug Best Practice introduced by
The property codpago does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
79
        $this->codagente = $this->confirmarValor($this->filter_request('codagente'),false);
0 ignored issues
show
Bug Best Practice introduced by
The property codagente does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
80
        $this->codalmacen = $this->confirmarValor($this->filter_request('codalmacen'),false);
0 ignored issues
show
Bug Best Practice introduced by
The property codalmacen does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
81
        $this->coddivisa = $this->confirmarValor($this->filter_request('coddivisa'),$this->empresa->coddivisa);
0 ignored issues
show
Bug Best Practice introduced by
The property coddivisa does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
82
        $this->cliente = ($this->filter_request('codcliente') && $this->filter_request('codcliente') != '')?$cli0->get($this->filter_request('codcliente')):false;
83
        $this->current_date = $this->empresa->var2str(\date('Y-m-d', strtotime($this->hasta)));
84
    }
85
86
    public function vencimiento_facturas()
87
    {
88
        list($funcion, $separador) = $this->funcionIntervalo();
89
        $sql = "select codalmacen, ".
90
        " sum(case when ".$funcion.$this->current_date.$separador."vencimiento) <= 30 then total else 0 end) as d30, ".
91
        " sum(case when ".$funcion.$this->current_date.$separador."vencimiento) > 30 and ".$funcion.$this->current_date.$separador."vencimiento) <= 60 then total else 0 end) as d60, ".
92
        " sum(case when ".$funcion.$this->current_date.$separador."vencimiento) > 60 and ".$funcion.$this->current_date.$separador."vencimiento) <= 90 then total else 0 end) as d90, ".
93
        " sum(case when ".$funcion.$this->current_date.$separador."vencimiento) > 90 and ".$funcion.$this->current_date.$separador."vencimiento) <= 120 then total else 0 end) as d120, ".
94
        " sum(case when ".$funcion.$this->current_date.$separador."vencimiento) > 120 then total else 0 end) as mas120 ".
95
        " from facturascli "." where anulada = false and pagada = false and idfacturarect IS NULL ".$this->sql_aux." group by codalmacen;";
96
        $data = $this->db->select($sql);
97
        $this->resultados = array();
98
        if (!empty($data)) {
99
            $totalDeuda = 0;
100
            foreach ($data as $d) {
101
                $this->comprobar_deuda($d, $totalDeuda);
102
            }
103
        }
104
    }
105
106
    public function comprobar_deuda($datos, &$totalDeuda)
107
    {
108
        $totalDeuda += $datos['d30']+$datos['d60']+$datos['d90']+$datos['d120']+$datos['mas120'];
109
        if($totalDeuda){
110
            $item = new stdClass();
111
            $item->codalmacen = $datos['codalmacen'];
112
            $item->nombre_almacen = $this->almacen->get($datos['codalmacen'])->nombre;
113
            $item->d30 = $datos['d30'];
114
            $item->d30_pcj = round(($datos['d30']/$totalDeuda)*100, 0);
115
            $item->d60 = $datos['d60'];
116
            $item->d60_pcj = round(($datos['d60']/$totalDeuda)*100, 0);
117
            $item->d90 = $datos['d90'];
118
            $item->d90_pcj = round(($datos['d90']/$totalDeuda)*100, 0);
119
            $item->d120 = $datos['d120'];
120
            $item->d120_pcj = round(($datos['d120']/$totalDeuda)*100, 0);
121
            $item->mas120 = $datos['mas120'];
122
            $item->mas120_pcj = round(($datos['mas120']/$totalDeuda)*100, 0);
123
            $item->totaldeuda = $totalDeuda;
124
            $this->resultados[] = $item;
125
        }
126
    }
127
128
    public function tabla_de_datos()
129
    {
130
        $data = array();
131
        $this->template = false;
132
        $dias = \filter_input(INPUT_POST, 'dias');
133
        $offset = \filter_input(INPUT_POST, 'offset');
134
        $sort = \filter_input(INPUT_POST, 'sort');
135
        $order = \filter_input(INPUT_POST, 'order');
136
        $limit = \filter_input(INPUT_POST, 'limit');
137
        $this->limit = ($limit)?$limit:FS_ITEM_LIMIT;
0 ignored issues
show
Bug introduced by
The constant FS_ITEM_LIMIT was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
138
        $this->sort = ($sort and $sort!='undefined')?$sort:'codalmacen, fecha, idfactura ';
139
        $this->order = ($order and $order!='undefined')?$order:'ASC';
140
        $datos = $this->listado_facturas($dias, $offset);
141
        $resultados = $datos['resultados'];
142
        $total_informacion = $datos['total'];
143
        header('Content-Type: application/json');
144
        $data['rows'] = $resultados;
145
        $data['total'] = $total_informacion;
146
        echo json_encode($data);
147
    }
148
149
    public function listado_facturas($dias, $offset = 0)
150
    {
151
        list($funcion, $separador) = $this->funcionIntervalo();
152
        
153
        $intervalo = $this->intervalo_tiempo($dias);
154
        $sql = "SELECT codalmacen, idfactura, codigo, numero2, nombrecliente, direccion, fecha, vencimiento, coddivisa, total, pagada, ".$funcion.$this->current_date.$separador."vencimiento) as atraso ".
155
            " FROM facturascli ".
156
            " WHERE anulada = false and pagada = false and idfacturarect IS NULL ".$intervalo.$this->sql_aux.
157
            " ORDER BY ".$this->sort.' '.$this->order;
158
        if($offset){
159
            $data = $this->db->select_limit($sql, $this->limit, $offset);
160
        }else{
161
            $data = $this->db->select($sql);
162
        }
163
        foreach($data as $key=>$valores) {
164
            $valores['abono'] = 0;
165
            $valores['saldo'] = $valores['total'];
166
            $this->abonos_factura($valores['idfactura'],$valores);
167
            $data[$key]=$valores;
168
        }
169
        
170
        $sql_total = "SELECT count(*) as total".
171
            " FROM facturascli ".
172
            " WHERE anulada = false and pagada = false and idfacturarect IS NULL ".$intervalo.$this->sql_aux.";";
173
        $data_total = $this->db->select($sql_total);
174
        return array('resultados'=>$data,'total'=>$data_total[0]['total']);
175
    }
176
    
177
    private function abonos_factura($idfactura, &$valores)
178
    {
179
        
180
        if($this->tesoreria === true) {
181
            $recibos = new recibo_cliente();
0 ignored issues
show
Bug introduced by
The type recibo_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...
182
            $recibos_factura = $recibos->all_from_factura($idfactura);
183
            $this->recibos_factura($recibos_factura, $valores);
184
        }
185
        
186
        $factura = new factura_cliente();
187
        if($factura->get($idfactura)) {
188
            $factura_actual = $factura->get($idfactura);
189
            $this->rectificativas_factura($factura_actual, $valores);
190
        }
191
    }
192
    
193
    private function recibos_factura($recibos_factura, &$valores) 
194
    {
195
        foreach($recibos_factura as $recibo) {
196
            if($recibo->estado === 'Pagado') {
197
                $valores['abono'] += $recibo->importe;
198
                $valores['saldo'] -= $recibo->importe;
199
            }
200
        }
201
    }
202
    
203
    private function rectificativas_factura($factura, &$valores) 
204
    {
205
        $rects = $factura->get_rectificativas();
206
        if($rects) {
207
            foreach($rects as $rect) {
208
                if($rect->anulada === false) {
209
                    $valores['abono'] += ($rect->total*-1);
210
                    $valores['saldo'] -= ($rect->total*-1);
211
                }
212
            }
213
        }
214
    }
215
216
    public function intervalo_tiempo($dias)
217
    {
218
        list($funcion, $separador) = $this->funcionIntervalo();
219
        $intervalo = '';
220
        switch ($dias) {
221
            case 30:
222
                $intervalo = " AND ".$funcion.$this->current_date.$separador."vencimiento) <= 30";
223
                break;
224
            case 60:
225
                $intervalo = " AND ".$funcion.$this->current_date.$separador."vencimiento) > 30 and ".$funcion.$this->current_date.$separador."vencimiento) <= 60";
226
                break;
227
            case 90:
228
                $intervalo = " AND ".$funcion.$this->current_date.$separador."vencimiento) > 60 and ".$funcion.$this->current_date.$separador."vencimiento) <= 90";
229
                break;
230
            case 120:
231
                $intervalo = " AND ".$funcion.$this->current_date.$separador."vencimiento) > 90 and ".$funcion.$this->current_date.$separador."vencimiento) <= 120";
232
                break;
233
            case 121:
234
                $intervalo = " AND ".$funcion.$this->current_date.$separador."vencimiento) > 120";
235
                break;
236
        }
237
        return $intervalo;
238
    }
239
240
    public function funcionIntervalo()
241
    {
242
        $funcion =  "datediff(";
243
        $separador = " , ";
244
        if(FS_DB_TYPE === 'POSTGRESQL'){
0 ignored issues
show
Bug introduced by
The constant FS_DB_TYPE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
245
            $funcion = "(";
246
            $separador = " - ";
247
        }
248
        return array($funcion, $separador);
249
    }
250
251
    public function sql_aux()
252
    {
253
        $estado = ($this->estado == 'pagada')?true:false;
254
        $sql = '';
255
        $sql .= ($this->hasta)?' AND fecha <= '.$this->empresa->var2str(\date('Y-m-d', strtotime($this->hasta))):'';
256
        $sql .= ($this->codserie)?' AND codserie = '.$this->empresa->var2str($this->codserie):'';
257
        $sql .= ($this->codpago)?' AND codpago = '.$this->empresa->var2str($this->codpago):'';
258
        $sql .= ($this->codagente)?' AND codagente = '.$this->empresa->var2str($this->codagente):'';
259
        $sql .= ($this->codalmacen)?' AND codalmacen = '.$this->empresa->var2str($this->codalmacen):'';
260
        $sql .= ($this->coddivisa)?' AND coddivisa = '.$this->empresa->var2str($this->coddivisa):'';
261
        $sql .= ($this->cliente)?' AND codcliente = '.$this->empresa->var2str($this->cliente->codcliente):'';
262
        $sql .= ($this->estado)?' AND pagada = '.$this->empresa->var2str($estado):'';
263
        $this->sql_aux = $sql;
264
    }
265
266
    private function share_extensions()
267
    {
268
        $extensiones = array(
269
            array(
270
                'name' => '001_informe_estadocuenta_js',
271
                'page_from' => __CLASS__,
272
                'page_to' => __CLASS__,
273
                'type' => 'head',
274
                'text' => '<script src="' . FS_PATH . 'plugins/republica_dominicana/view/js/bootstrap-table.min.js" type="text/javascript"></script>',
0 ignored issues
show
Bug introduced by
The constant FS_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
275
                'params' => ''
276
            ),
277
            array(
278
                'name' => '002_informe_estadocuenta_js',
279
                'page_from' => __CLASS__,
280
                'page_to' => __CLASS__,
281
                'type' => 'head',
282
                'text' => '<script src="' . FS_PATH . 'plugins/republica_dominicana/view/js/locale/bootstrap-table-es-MX.min.js" type="text/javascript"></script>',
283
                'params' => ''
284
            ),
285
            array(
286
                'name' => '003_informe_estadocuenta_js',
287
                'page_from' => __CLASS__,
288
                'page_to' => __CLASS__,
289
                'type' => 'head',
290
                'text' => '<script src="' . FS_PATH . 'plugins/republica_dominicana/view/js/plugins/bootstrap-table-filter.min.js" type="text/javascript"></script>',
291
                'params' => ''
292
            ),
293
            array(
294
                'name' => '004_informe_estadocuenta_js',
295
                'page_from' => __CLASS__,
296
                'page_to' => __CLASS__,
297
                'type' => 'head',
298
                'text' => '<script src="' . FS_PATH . 'plugins/republica_dominicana/view/js/plugins/bootstrap-table-toolbar.min.js" type="text/javascript"></script>',
299
                'params' => ''
300
            ),
301
            array(
302
                'name' => '005_informe_estadocuenta_js',
303
                'page_from' => __CLASS__,
304
                'page_to' => __CLASS__,
305
                'type' => 'head',
306
                'text' => '<script src="' . FS_PATH . 'plugins/republica_dominicana/view/js/plugins/bootstrap-table-mobile.min.js" type="text/javascript"></script>',
307
                'params' => ''
308
            ),
309
            array(
310
                'name' => '001_informe_estadocuenta_css',
311
                'page_from' => __CLASS__,
312
                'page_to' => __CLASS__,
313
                'type' => 'head',
314
                'text' => '<link rel="stylesheet" type="text/css" media="screen" href="' . FS_PATH . 'plugins/republica_dominicana/view/css/bootstrap-table.min.css"/>',
315
                'params' => ''
316
            ),
317
        );
318
319
        foreach ($extensiones as $ext) {
320
            $fext = new fs_extension($ext);
0 ignored issues
show
Bug introduced by
The type fs_extension was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
321
            if (!$fext->save()) {
322
                $this->new_error_msg('Imposible guardar los datos de la extensión ' . $ext['name'] . '.');
323
            }
324
        }
325
    }
326
327
    public function crearPDF()
328
    {
329
        $this->carpetasPlugin();
330
        $pdf_doc = new Cezpdf_DOM('letter', 'portrait');
0 ignored issues
show
Bug introduced by
The type Cezpdf_DOM 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...
331
        $all = $pdf_doc->openObject();
332
        $pdf_doc->saveState();
333
        $pdf_doc->ezStartPageNumbers(590,25,8,'right','{PAGENUM} de {TOTALPAGENUM}',1);
334
        $this->archivoPDF = $this->exportDir . DIRECTORY_SEPARATOR . $this->archivo . "_" . $this->user->nick . ".pdf";
0 ignored issues
show
Bug Best Practice introduced by
The property archivoPDF does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
335
        $this->archivoPDFPath = $this->publicPath . DIRECTORY_SEPARATOR . $this->archivo . "_" . $this->user->nick . ".pdf";
0 ignored issues
show
Bug Best Practice introduced by
The property archivoPDFPath does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
336
        if (file_exists($this->archivoPDF)) {
337
            unlink($this->archivoPDF);
338
        }
339
        $pdf_doc->selectFont(__DIR__ . "/ezpdf/fonts/Helvetica.afm");
340
        $pdf_doc->selectFont('Helvetica');
341
        //$pdf_doc->ezSetMargins (25,25,25,25);
342
        
343
        $logo = '';
344
        if(file_exists(FS_PATH.FS_MYDOCS.'images/logo.png')){
0 ignored issues
show
Bug introduced by
The constant FS_MYDOCS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant FS_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
345
            $logo = FS_PATH.FS_MYDOCS.'images/logo.png';
346
        }elseif(file_exists(FS_PATH.FS_MYDOCS.'images/logo.jpg')){
347
            $logo = FS_PATH.FS_MYDOCS.'images/logo.jpg';
348
        }
349
        
350
        if($logo){
351
            $pdf_doc->ezImage($logo, 0, 80, 'none', 'left');
352
        }
353
        
354
        $pdf_doc->addText(110,745,9,'<b>'.$this->empresa->nombre.'</b>',0, 'left');
355
        $pdf_doc->addText(110,730,9,'<b>'.$this->empresa->direccion.'</b>',0, 'left');
356
        $pdf_doc->addText(580,745,9,'<b>'.'Estado de Cuenta'.'</b>',0, 'right');
357
        $pdf_doc->addText(580,730,9,'<b>'.'Al: '.'</b>'.\date('d-m-Y'),0, 'right');
358
        
359
        $pdf_doc->line(30, 670, 580, 670);
360
        
361
        if($this->cliente) {
362
            $cli = new cliente();
363
            $datos_cli = $cli->get($this->cliente->codcliente);
364
            $direccion = $datos_cli->get_direcciones();
365
            $pdf_doc->addText(110, 690, 10, "<b>Estado de cuenta de:</b> ".$this->cliente->razonsocial, 430, 'left'); 
366
            $pdf_doc->addText(110, 680, 10, "<b>Dirección:</b> ".$direccion[0]->direccion, 430, 'left'); 
367
        } else {
368
            $pdf_doc->addText(50, 690, 12, "<b>Estado de cuenta General</b>", 530, 'center');
369
        }
370
        
371
        
372
        $pdf_doc->restoreState();
373
        $pdf_doc->closeObject();
374
        
375
        $pdf_doc->ezSetY(660);
376
377
        $pdf_doc->addObject($all,'all');
378
        $pdf_doc->ezSetMargins(130,40,50,50);
379
        
380
        if($this->cliente) {
381
            $columnas = array('numero2' => FS_NUMERO2, 'codigo' => 'Factura', 'total'=> 'Importe', 'abono'=>'Abonos', 'saldo' => 'Saldo', 'vencimiento'=>'Vencimiento', 'atraso' => 'Atraso');
382
        } else {
383
            $columnas = array('codalmacen' => 'Almacen', 'nombrecliente' => 'Cliente', 'direccion' => 'Dirección', 'numero2' => FS_NUMERO2, 'total'=> 'Importe', 'abono'=>'Abonos', 'saldo' => 'Saldo', 'vencimiento'=>'Vencimiento', 'atraso' => 'Atraso');
384
        }
385
        
386
        $conf = [
387
            'evenColumns' => 0,
388
            'width' => 550,
389
            'shaded' => 1,
390
            'fontSize' => 8,
391
            'titleFontSize' => 9,
392
            'xPos' => 'center',
393
            'xOrientation' => 'center',
394
            'gridlines' => 31,
395
            'cols' => [
396
                'total' => ['justification' => 'right'],
397
                'abono' => ['justification' => 'right'],
398
                'saldo' => ['justification' => 'right'],
399
                'atraso' => ['justification' => 'right']
400
            ] // global background color for 'num' column
401
        ];
402
        
403
        foreach($this->vencimientos as $dias){
404
            $total_importe = 0;
405
            $total_abono = 0;
406
            $total_saldo = 0;            
407
            $hoja_nombre = ($dias!==121)?'Facturas a '.$dias.' dias':'Facturas a mas de 120 dias';
408
            $datos = $this->listado_facturas($dias);
409
            $total_documentos = count($datos['resultados']);
410
            $lineaFinal = array();
411
            foreach($datos['resultados'] as $linea){
412
                $total_importe += $linea['total'];
413
                $total_abono += $linea['abono'];
414
                $total_saldo += $linea['saldo'];
415
            }
416
            $lineaFinal['numero2'] = "<b>".$total_documentos.' Facturas'."</b>";
417
            $lineaFinal['total'] = "<b>".$total_importe."</b>";
418
            $lineaFinal['abono'] = "<b>".$total_abono."</b>";
419
            $lineaFinal['saldo'] = "<b>".$total_saldo."</b>";
420
            $datos['resultados'][] = $lineaFinal;
421
            $pdf_doc->ezTable($datos['resultados'], $columnas, "<b>$hoja_nombre</b>", $conf);
422
            
423
        }
424
        
425
        $this->guardarPDF($this->archivoPDF, $pdf_doc);
426
        $this->filePDF = $this->archivoPDFPath;
427
    }
428
429
    /**
430
     * Vuelca el documento PDF en la salida estándar.
431
     * @param string $filename
432
     */
433
    public function mostrarPDF($filename = 'doc.pdf')
434
    {
435
        $this->pdf->ezStream(array('Content-Disposition' => $filename));
436
    }
437
438
    /**
439
     * Guarda el documento PDF en el archivo $filename
440
     * @param string $filename
441
     * @return boolean
442
     */
443
    public function guardarPDF($filename, $pdf_doc)
444
    {
445
        if ($filename) {
446
            if (file_exists($filename)) {
447
                unlink($filename);
448
            }
449
450
            $file = fopen($filename, 'a');
451
            if ($file) {
0 ignored issues
show
introduced by
$file is of type resource, thus it always evaluated to false.
Loading history...
452
                fwrite($file, $pdf_doc->ezOutput());
453
                fclose($file);
454
                return TRUE;
455
            }
456
457
            return TRUE;
458
        }
459
460
        return FALSE;
461
    }
462
463
464
    public function crearXLSX()
465
    {
466
        $this->carpetasPlugin();
467
        $this->archivoXLSX = $this->exportDir . DIRECTORY_SEPARATOR . $this->archivo . "_" . $this->user->nick . ".xlsx";
0 ignored issues
show
Bug Best Practice introduced by
The property archivoXLSX does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
468
        $this->archivoXLSXPath = $this->publicPath . DIRECTORY_SEPARATOR . $this->archivo . "_" . $this->user->nick . ".xlsx";
0 ignored issues
show
Bug Best Practice introduced by
The property archivoXLSXPath does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
469
        if (file_exists($this->archivoXLSX)) {
470
            unlink($this->archivoXLSX);
471
        }
472
        $style_header = array('border'=>'left,right,top,bottom','font'=>'Arial','font-size'=>10,'font-style'=>'bold');
473
        $header = array('Almacén'=>'string','Cliente'=>'string','direccion'=>'string','Factura'=>'string', ucfirst(FS_NUMERO2)=>'string',
474
            'Importe'=>'price','Abono'=>'price','Saldo'=>'price','Fecha de Emisión'=>'date','Fecha de Vencimiento'=>'date','Días Atraso'=>'integer');
475
        $headerText = array('codalmacen'=>'Almacén','nombrecliente'=>'Cliente','codigo'=>'Factura','numero2'=>ucfirst(FS_NUMERO2),'total'=>'Importe','abono'=>'Abono','saldo'=>'Saldo','fecha'=>'Fecha de Emisión','vencimiento'=>'Fecha de Vencimiento','atraso'=>'Días Atraso');
476
        $writer = new XLSXWriter();
0 ignored issues
show
Bug introduced by
The type XLSXWriter 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...
477
        foreach($this->vencimientos as $dias){
478
            $hoja_nombre = ($dias!==121)?'Facturas a '.$dias.' dias':'Facturas a mas de 120 dias';
479
            $writer->writeSheetRow($hoja_nombre, $headerText, $style_header);
480
            $writer->writeSheetHeader($hoja_nombre, $header, true);
481
            $datos = $this->listado_facturas($dias);
482
            $this->agregarDatosXLSX($writer, $hoja_nombre, $datos['resultados'], $headerText);
483
        }
484
        $writer->writeToFile($this->archivoXLSXPath);
485
        $this->fileXLSX = $this->archivoXLSXPath;
486
    }
487
488
    public function agregarDatosXLSX(&$writer, $hoja_nombre, $datos, $indice)
489
    {
490
        $style_footer = array('border'=>'left,right,top,bottom','font'=>'Arial','font-size'=>10,'font-style'=>'bold','color'=>'#fff','fill'=>'#000');
491
        $total_importe = 0;
492
        $total_abono = 0;
493
        $total_saldo = 0;
494
        if($datos){
495
            $total_documentos = count($datos);
496
            foreach($datos as $linea){
497
                $data = $this->prepararDatos($linea, $indice, $total_importe, $total_abono, $total_saldo);
498
                $writer->writeSheetRow($hoja_nombre, $data);
499
            }
500
            $writer->writeSheetRow($hoja_nombre, array('','','',$total_documentos.' Documentos',$total_importe,$total_abono,$total_saldo,'','',''), $style_footer);
501
        }
502
    }
503
504
    public function prepararDatos($linea, $indice, &$total_importe, &$total_abono, &$total_saldo)
505
    {
506
        $item = array();
507
        foreach($indice as $idx=>$desc){
508
            $item[] = $linea[$idx];
509
            if($idx == 'total'){
510
                $total_importe += $linea['total'];
511
            }
512
            if($idx == 'abono'){
513
                $total_abono += $linea['abono'];
514
            }
515
            if($idx == 'saldo'){
516
                $total_saldo += $linea['saldo'];
517
            }
518
        }
519
        return $item;
520
    }
521
}
522