informe_contabilidad::libro_mayor_csv()   B
last analyzed

Complexity

Conditions 10
Paths 35

Size

Total Lines 77
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 10
eloc 50
c 1
b 1
f 0
nc 35
nop 7
dl 0
loc 77
rs 7.2242

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/*
3
 * This file is part of facturacion_base
4
 * Copyright (C) 2014-2017  Carlos Garcia Gomez  [email protected]
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as
8
 * published by the Free Software Foundation, either version 3 of the
9
 * License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU Lesser General Public License for more details.
15
 * 
16
 * You should have received a copy of the GNU Lesser General Public License
17
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19
20
require_once 'plugins/facturacion_base/extras/inventarios_balances.php';
21
22
class informe_contabilidad extends fs_controller
0 ignored issues
show
Bug introduced by
The type fs_controller 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...
23
{
24
    private $balance;
25
    private $balance_cuenta_a;
26
    public $cuentas;
27
    public $ejercicio;
28
    public $epigrafes;
29
    public $grupos;
30
31
    public function __construct()
32
    {
33
        parent::__construct(__CLASS__, 'Contabilidad', 'informes', false, true);
34
    }
35
36
    protected function private_core()
37
    {
38
        $this->balance = new balance();
0 ignored issues
show
Bug introduced by
The type balance 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...
39
        $this->balance_cuenta_a = new balance_cuenta_a();
0 ignored issues
show
Bug introduced by
The type balance_cuenta_a 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...
40
        $this->ejercicio = 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...
41
42
        if (isset($_REQUEST['buscar_subcuenta'])) {
43
            /// esto es para el autocompletar las subcuentas de la vista
44
            $this->buscar_subcuenta();
45
        } elseif (isset($_GET['diario'])) {
46
            $this->libro_diario_csv($_GET['diario']);
47
        } elseif (isset($_GET['balance']) && isset($_GET['eje'])) {
48
            $this->template = FALSE;
49
            $iba = new inventarios_balances($this->db);
50
            if ($_GET['balance'] === 'pyg') {
51
                $iba->generar_pyg($_GET['eje']);
52
            } else {
53
                $iba->generar_sit($_GET['eje']);
54
            }
55
        } elseif (isset($_POST['informe'])) {
56
            if ($_POST['informe'] === 'sumasysaldos') {
57
                $this->balance_sumas_y_saldos();
58
            } elseif ($_POST['informe'] === 'situacion') {
59
                $this->balance_situacion();
60
            } elseif ($_POST['informe'] === 'perdidasyg') {
61
                $this->balance_perdidasyg();
62
            } elseif ($_POST['informe'] === 'librom') {
63
                if ($_POST['filtro'] === '') {
64
                    $this->libro_mayor_csv(
65
                        $_POST['codejercicio'], $_POST['desde'], $_POST['hasta']
66
                    );
67
                } elseif (isset($_POST['codgrupo'])) {
68
                    $this->libro_mayor_csv(
69
                        $_POST['codejercicio'], $_POST['desde'], $_POST['hasta'], $_POST['codgrupo']
70
                    );
71
                } elseif (isset($_POST['codepigrafe'])) {
72
                    $this->libro_mayor_csv(
73
                        $_POST['codejercicio'], $_POST['desde'], $_POST['hasta'], false, $_POST['codepigrafe']
74
                    );
75
                } elseif (isset($_POST['codcuenta'])) {
76
                    $this->libro_mayor_csv(
77
                        $_POST['codejercicio'], $_POST['desde'], $_POST['hasta'], false, false, $_POST['codcuenta']
78
                    );
79
                } elseif (isset($_POST['codsubcuenta'])) {
80
                    $this->libro_mayor_csv(
81
                        $_POST['codejercicio'], $_POST['desde'], $_POST['hasta'], false, false, false, $_POST['codsubcuenta']
82
                    );
83
                } else {
84
                    $this->template = 'ajax/informe_libro_mayor';
85
86
                    $this->grupos = false;
87
                    $this->epigrafes = false;
88
                    $this->cuentas = false;
89
90
                    if ($_POST['filtro'] === 'grupo') {
91
                        $ge = new grupo_epigrafes();
0 ignored issues
show
Bug introduced by
The type grupo_epigrafes 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...
92
                        $this->grupos = $ge->all_from_ejercicio($_POST['codejercicio']);
93
                    } elseif ($_POST['filtro'] === 'epigrafe') {
94
                        $ep = new epigrafe();
0 ignored issues
show
Bug introduced by
The type epigrafe 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...
95
                        $this->epigrafes = $ep->all_from_ejercicio($_POST['codejercicio']);
96
                    } elseif ($_POST['filtro'] === 'cuenta') {
97
                        $cuenta = new cuenta();
0 ignored issues
show
Bug introduced by
The type cuenta 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...
98
                        $this->cuentas = $cuenta->full_from_ejercicio($_POST['codejercicio']);
99
                    }
100
                }
101
            }
102
        }
103
    }
104
105
    private function buscar_subcuenta()
106
    {
107
        /// desactivamos la plantilla HTML
108
        $this->template = false;
109
110
        $subcuenta = new subcuenta();
0 ignored issues
show
Bug introduced by
The type subcuenta 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...
111
        $eje0 = new ejercicio();
112
        $ejercicio = $eje0->get($_REQUEST['codejercicio']);
113
        $json = array();
114
        foreach ($subcuenta->search_by_ejercicio($ejercicio->codejercicio, $_REQUEST['buscar_subcuenta']) as $subc) {
115
            $json[] = array(
116
                'value' => $subc->codsubcuenta,
117
                'data' => $subc->descripcion,
118
                'saldo' => $subc->saldo,
119
                'link' => $subc->url()
120
            );
121
        }
122
123
        header('Content-Type: application/json');
124
        echo \json_encode(array('query' => $_REQUEST['buscar_subcuenta'], 'suggestions' => $json), JSON_THROW_ON_ERROR);
125
    }
126
127
    public function existe_libro_diario($codeje)
128
    {
129
        return file_exists('tmp/' . FS_TMP_NAME . 'libro_diario/' . $codeje . '.pdf');
0 ignored issues
show
Bug introduced by
The constant FS_TMP_NAME was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
130
    }
131
132
    public function existe_libro_inventarios($codeje)
133
    {
134
        return file_exists('tmp/' . FS_TMP_NAME . 'inventarios_balances/' . $codeje . '.pdf');
0 ignored issues
show
Bug introduced by
The constant FS_TMP_NAME was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
135
    }
136
137
    private function libro_diario_csv($codeje, $desde = false, $hasta = false)
138
    {
139
        $this->template = false;
140
        header("content-type:application/csv;charset=UTF-8");
141
        header("Content-Disposition: attachment; filename=\"diario_{$codeje}.csv\"");
142
        echo "asiento;fecha;subcuenta;concepto;debe;haber;saldo\n";
143
144
        /// obtenemos el saldo inicial
145
        $saldo = 0;
146
        if ($desde) {
147
            $sql = "SELECT SUM(p.debe) as debe, SUM(p.haber) as haber"
148
                . " FROM co_asientos a, co_partidas p"
149
                . " WHERE a.codejercicio = " . $this->empresa->var2str($codeje)
150
                . " AND p.idasiento = a.idasiento"
151
                . " AND a.fecha < " . $this->empresa->var2str($desde);
152
153
            $data = $this->db->select($sql);
154
            if ($data) {
155
                $saldo = (float)$data[0]['debe'] - (float)$data[0]['haber'];
156
                echo '-;' . date('d-m-Y', strtotime($desde)) . ';-;Saldo inicial;0;0;' . number_format($saldo, FS_NF0, FS_NF1, FS_NF2) . "\n";
157
            }
158
        }
159
160
        /// ahora las líneas
161
        $sql = "SELECT a.numero,a.fecha,p.codsubcuenta,p.concepto,p.debe,p.haber"
162
            . " FROM co_asientos a, co_partidas p"
163
            . " WHERE a.codejercicio = " . $this->empresa->var2str($codeje)
164
            . " AND p.idasiento = a.idasiento";
165
166
        if ($desde && $hasta) {
167
            $sql .= " AND a.fecha >= " . $this->empresa->var2str($desde);
168
            $sql .= " AND a.fecha <= " . $this->empresa->var2str($hasta);
169
        }
170
171
        $sql .= " ORDER BY a.numero ASC";
172
173
        $offset = 0;
174
        $data = $this->db->select_limit($sql, 1000, $offset);
175
        while ($data) {
176
            foreach ($data as $par) {
177
                $saldo += (float)$par['debe'] - (float)$par['haber'];
178
179
                echo $par['numero'] . ';'
180
                . date('d-m-Y', strtotime($par['fecha'])) . ';'
181
                . fs_fix_html($par['codsubcuenta']) . ';'
182
                . fs_fix_html($par['concepto']) . ';'
183
                . number_format($par['debe'], FS_NF0, FS_NF1, FS_NF2) . ';'
184
                . number_format($par['haber'], FS_NF0, FS_NF1, FS_NF2) . ';'
185
                . number_format($saldo, FS_NF0, FS_NF1, FS_NF2) . "\n";
186
                $offset++;
187
            }
188
189
            $data = $this->db->select_limit($sql, 1000, $offset);
190
        }
191
    }
192
193
    private function libro_mayor_csv (
194
        $codeje,
195
        $desde,
196
        $hasta,
197
        $codgrupo = false,
198
        $codepi = false,
199
        $codcuenta = false,
200
        $codsubc = false
201
    )
202
    {
203
        $this->template = false;
204
205
        header("content-type:application/csv;charset=UTF-8");
206
        header("Content-Disposition: attachment; filename=\"mayor.csv\"");
207
        echo "asiento;fecha;subcuenta;concepto;debe;haber;saldo\n";
208
209
        /// ahora las líneas
210
        $sql = "SELECT a.numero,a.fecha,p.codsubcuenta,p.concepto,p.debe,p.haber"
211
            . " FROM co_asientos a, co_partidas p"
212
            . " WHERE a.codejercicio = " . $this->empresa->var2str($codeje)
213
            . " AND p.idasiento = a.idasiento"
214
            . " AND a.fecha >= " . $this->empresa->var2str($desde)
215
            . " AND a.fecha <= " . $this->empresa->var2str($hasta);
216
217
        if ($codgrupo) {
218
            $sql .= " AND p.codsubcuenta LIKE '" . $this->empresa->no_html($codgrupo) . "%'";
219
        } elseif ($codepi) {
220
            $sql .= " AND p.codsubcuenta LIKE '" . $this->empresa->no_html($codepi) . "%'";
221
        } elseif ($codcuenta) {
222
            $sql .= " AND p.codsubcuenta LIKE '" . $this->empresa->no_html($codcuenta) . "%'";
223
        } elseif ($codsubc) {
224
            $sql .= " AND p.codsubcuenta IN ('" . implode("','", $codsubc) . "')";
225
        }
226
227
        $sql .= " ORDER BY p.codsubcuenta ASC, a.numero ASC";
228
229
        $codsubcuenta = false;
230
        $offset = 0;
231
        $saldo = 0;
232
        $data = $this->db->select_limit($sql, 1000, $offset);
233
        while ($data) {
234
            foreach ($data as $par) {
235
                if ($codsubcuenta !== $par['codsubcuenta']) {
236
                    if ($codsubcuenta) {
237
                        echo ";;;;;;\n";
238
                    }
239
240
                    /// obtenemos el saldo inicial
241
                    $codsubcuenta = $par['codsubcuenta'];
242
                    $saldo = 0;
243
                    $sql2 = "SELECT SUM(p.debe) as debe, SUM(p.haber) as haber"
244
                        . " FROM co_asientos a, co_partidas p"
245
                        . " WHERE a.codejercicio = " . $this->empresa->var2str($codeje)
246
                        . " AND p.idasiento = a.idasiento"
247
                        . " AND a.fecha < " . $this->empresa->var2str($desde)
248
                        . " AND p.codsubcuenta = " . $this->empresa->var2str($codsubcuenta);
249
250
                    $data = $this->db->select($sql2);
251
                    if ($data) {
252
                        $saldo = (float)$data[0]['debe'] - (float)$data[0]['haber'];
253
                        echo '-;' . date('d-m-Y', strtotime($desde)) . ';' . $codsubcuenta . ';Saldo inicial;0;0;' . number_format($saldo, FS_NF0, FS_NF1, FS_NF2) . "\n";
254
                    }
255
                }
256
257
                $saldo += (float)$par['debe'] - (float)$par['haber'];
258
259
                echo $par['numero'] . ';'
260
                . date('d-m-Y', strtotime($par['fecha'])) . ';'
261
                . fs_fix_html($par['codsubcuenta']) . ';'
262
                . fs_fix_html($par['concepto']) . ';'
263
                . number_format($par['debe'], FS_NF0, FS_NF1, FS_NF2) . ';'
264
                . number_format($par['haber'], FS_NF0, FS_NF1, FS_NF2) . ';'
265
                . number_format($saldo, FS_NF0, FS_NF1, FS_NF2) . "\n";
266
                $offset++;
267
            }
268
269
            $data = $this->db->select_limit($sql, 1000, $offset);
270
        }
271
    }
272
273
    private function balance_sumas_y_saldos()
274
    {
275
        $eje = $this->ejercicio->get($_POST['codejercicio']);
276
        if ($eje) {
277
            if (strtotime($_POST['desde']) < strtotime($eje->fechainicio) || strtotime($_POST['hasta']) > strtotime($eje->fechafin)) {
278
                $this->new_error_msg('La fecha está fuera del rango del ejercicio.');
279
            } else {
280
                $this->template = false;
281
282
                $excluir = false;
283
                if (isset($eje->idasientocierre) && isset($eje->idasientopyg)) {
284
                    $excluir = array($eje->idasientocierre, $eje->idasientopyg);
285
                }
286
287
                if ($_POST['formato'] === 'csv') {
288
                    header("content-type:application/csv;charset=UTF-8");
289
                    header("Content-Disposition: attachment; filename=\"sumasysaldos.csv\"");
290
                    echo "cuenta;descripcion;debe;haber;saldo\n";
291
292
                    $pdf_doc = false;
293
                    if ($_POST['tipo'] === '3') {
294
                        $this->sumas_y_saldos($pdf_doc, $eje, 3, 'de ' . $_POST['desde'] . ' a ' . $_POST['hasta'], $_POST['desde'], $_POST['hasta'], $excluir);
0 ignored issues
show
Bug introduced by
$pdf_doc of type false is incompatible with the type fs_pdf expected by parameter $pdf_doc of informe_contabilidad::sumas_y_saldos(). ( Ignorable by Annotation )

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

294
                        $this->sumas_y_saldos(/** @scrutinizer ignore-type */ $pdf_doc, $eje, 3, 'de ' . $_POST['desde'] . ' a ' . $_POST['hasta'], $_POST['desde'], $_POST['hasta'], $excluir);
Loading history...
Bug introduced by
'de ' . $_POST['desde'] . ' a ' . $_POST['hasta'] of type string is incompatible with the type type expected by parameter $titulo of informe_contabilidad::sumas_y_saldos(). ( Ignorable by Annotation )

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

294
                        $this->sumas_y_saldos($pdf_doc, $eje, 3, /** @scrutinizer ignore-type */ 'de ' . $_POST['desde'] . ' a ' . $_POST['hasta'], $_POST['desde'], $_POST['hasta'], $excluir);
Loading history...
Bug introduced by
$excluir of type array|false is incompatible with the type type expected by parameter $excluir of informe_contabilidad::sumas_y_saldos(). ( Ignorable by Annotation )

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

294
                        $this->sumas_y_saldos($pdf_doc, $eje, 3, 'de ' . $_POST['desde'] . ' a ' . $_POST['hasta'], $_POST['desde'], $_POST['hasta'], /** @scrutinizer ignore-type */ $excluir);
Loading history...
295
                    } else {
296
                        $this->sumas_y_saldos($pdf_doc, $eje, 10, 'de ' . $_POST['desde'] . ' a ' . $_POST['hasta'], $_POST['desde'], $_POST['hasta'], $excluir);
297
                    }
298
                } else {
299
                    $pdf_doc = new fs_pdf('letter');
300
                    $pdf_doc->pdf->addInfo('Title', 'Balance de situación de ' . fs_fix_html($this->empresa->nombre));
301
                    $pdf_doc->pdf->addInfo('Subject', 'Balance de situación de ' . fs_fix_html($this->empresa->nombre));
302
                    $pdf_doc->pdf->addInfo('Author', fs_fix_html($this->empresa->nombre));
303
                    $pdf_doc->pdf->ezStartPageNumbers(580, 10, 10, 'left', '{PAGENUM} de {TOTALPAGENUM}');
304
305
                    if ($_POST['tipo'] === '3') {
306
                        $this->sumas_y_saldos($pdf_doc, $eje, 3, 'de ' . $_POST['desde'] . ' a ' . $_POST['hasta'], $_POST['desde'], $_POST['hasta'], $excluir);
307
                    } else {
308
                        $this->sumas_y_saldos($pdf_doc, $eje, 10, 'de ' . $_POST['desde'] . ' a ' . $_POST['hasta'], $_POST['desde'], $_POST['hasta'], $excluir);
309
                    }
310
311
                    $pdf_doc->show();
312
                }
313
            }
314
        }
315
    }
316
317
    /**
318
     * Función auxiliar para generar el balance de sumas y saldos, en su versión de 3 dígitos.
319
     * @param fs_pdf $pdf_doc
320
     * @param object $eje
321
     * @param int $tipo
322
     * @param type $titulo
323
     * @param type $fechaini
324
     * @param type $fechafin
325
     * @param type $excluir
326
     */
327
    public function sumas_y_saldos(&$pdf_doc, &$eje, $tipo = 3, $titulo, $fechaini, $fechafin, $excluir = false)
328
    {
329
        $ge0 = new grupo_epigrafes();
330
        $epi0 = new epigrafe();
331
        $cuenta0 = new cuenta();
332
        $subcuenta0 = new subcuenta();
333
334
        $lineas = array();
335
336
        $sql = "SELECT p.codsubcuenta, SUM(p.debe) as debe, SUM(p.haber) as haber" .
337
            " FROM co_partidas p, co_asientos a WHERE p.idasiento = a.idasiento" .
338
            " AND a.codejercicio = " . $this->empresa->var2str($eje->codejercicio) .
339
            " AND a.fecha >= " . $this->empresa->var2str($fechaini) .
340
            " AND fecha <= " . $this->empresa->var2str($fechafin);
341
342
        if ($excluir) {
343
            foreach ($excluir as $exc) {
344
                $sql .= " AND p.idasiento != " . $this->empresa->var2str($exc);
345
            }
346
        }
347
348
        $sql .= " GROUP BY p.codsubcuenta ORDER BY codsubcuenta ASC;";
349
350
        $data = $this->db->select($sql);
351
        if ($data) {
352
            $grupos = $ge0->all_from_ejercicio($eje->codejercicio);
353
            $epigrafes = $epi0->all_from_ejercicio($eje->codejercicio);
354
355
            for ($i = 1; $i < 10; $i++) {
356
                $debe = 0;
357
                $haber = 0;
358
                foreach ($data as $d) {
359
                    if (strpos($d['codsubcuenta'], (string)$i) === 0) {
360
                        $debe += (float)$d['debe'];
361
                        $haber += (float)$d['haber'];
362
                    }
363
                }
364
365
                /// añadimos el grupo
366
                foreach ($grupos as $ge) {
367
                    if ($ge->codgrupo === $i) {
368
                        $lineas[] = array(
369
                            'cuenta' => $i,
370
                            'descripcion' => $ge->descripcion,
371
                            'debe' => $debe,
372
                            'haber' => $haber
373
                        );
374
                        break;
375
                    }
376
                }
377
378
                for ($j = 0; $j < 10; $j++) {
379
                    $debe = 0;
380
                    $haber = 0;
381
                    foreach ($data as $d) {
382
                        if (strpos($d['codsubcuenta'], (string)$i . $j) === 0) {
383
                            $debe += (float)$d['debe'];
384
                            $haber += (float)$d['haber'];
385
                        }
386
                    }
387
388
                    /// añadimos el epígrafe
389
                    foreach ($epigrafes as $ep) {
390
                        if ($ep->codepigrafe === (string) $i . $j) {
391
                            $lineas[] = array(
392
                                'cuenta' => $i . $j,
393
                                'descripcion' => $ep->descripcion,
394
                                'debe' => $debe,
395
                                'haber' => $haber
396
                            );
397
                            break;
398
                        }
399
                    }
400
401
                    for ($k = 0; $k < 10; $k++) {
402
                        $debe = 0;
403
                        $haber = 0;
404
                        foreach ($data as $d) {
405
                            if (strpos($d['codsubcuenta'], (string)$i . $j . $k) === 0) {
406
                                $debe += (float)$d['debe'];
407
                                $haber += (float)$d['haber'];
408
                            }
409
                        }
410
411
                        /// añadimos la cuenta
412
                        if ($debe !== 0 || $haber !== 0) {
413
                            $cuenta = $cuenta0->get_by_codigo($i . $j . $k, $eje->codejercicio);
414
                            if ($cuenta) {
415
                                $lineas[] = array(
416
                                    'cuenta' => $i . $j . $k,
417
                                    'descripcion' => $cuenta->descripcion,
418
                                    'debe' => $debe,
419
                                    'haber' => $haber
420
                                );
421
                            } else {
422
                                $lineas[] = array(
423
                                    'cuenta' => $i . $j . $k,
424
                                    'descripcion' => '-',
425
                                    'debe' => $debe,
426
                                    'haber' => $haber
427
                                );
428
                            }
429
                        }
430
431
                        if ($tipo === 10) {
432
                            /// añadimos las subcuentas
433
                            foreach ($data as $d) {
434
                                if (strpos($d['codsubcuenta'], (string)$i . $j . $k) === 0) {
435
                                    $desc = '';
436
                                    $subc = $subcuenta0->get_by_codigo($d['codsubcuenta'], $eje->codejercicio);
437
                                    if ($subc) {
438
                                        $desc = $subc->descripcion;
439
                                    }
440
441
                                    $lineas[] = array(
442
                                        'cuenta' => $d['codsubcuenta'],
443
                                        'descripcion' => $desc,
444
                                        'debe' => (float)$d['debe'],
445
                                        'haber' => (float)$d['haber']
446
                                    );
447
                                }
448
                            }
449
                        }
450
                    }
451
                }
452
            }
453
        }
454
455
        /// a partir de la lista generamos el documento
456
        $linea = 0;
457
        $tdebe = 0;
458
        $thaber = 0;
459
        while ($linea < count($lineas)) {
460
            if ($pdf_doc) {
461
                if ($linea > 0) {
462
                    $pdf_doc->pdf->ezNewPage();
463
                }
464
465
                $pdf_doc->pdf->ezText(fs_fix_html($this->empresa->nombre) . " - Balance de sumas y saldos " . $eje->year() . ' ' . $titulo . ".\n\n", 12);
466
467
                /// Creamos la tabla con las lineas
468
                $pdf_doc->new_table();
469
                $pdf_doc->add_table_header(
470
                    array(
471
                        'cuenta' => '<b>Cuenta</b>',
472
                        'descripcion' => '<b>Descripción</b>',
473
                        'debe' => '<b>Debe</b>',
474
                        'haber' => '<b>Haber</b>',
475
                        'saldo' => '<b>Saldo</b>'
476
                    )
477
                );
478
479
                for ($i = $linea; $i < min(array($linea + 48, count($lineas))); $i++) {
480
                    if (strlen($lineas[$i]['cuenta']) === 1) {
481
                        $a = '<b>';
482
                        $b = '</b>';
483
                        $tdebe += $lineas[$i]['debe'];
484
                        $thaber += $lineas[$i]['haber'];
485
                    } elseif (strlen($lineas[$i]['cuenta']) === 2) {
486
                        $a = $b = '';
487
                    } else {
488
                        $a = '<i>';
489
                        $b = '</i>';
490
                    }
491
492
                    $pdf_doc->add_table_row(
493
                        array(
494
                            'cuenta' => $a . $lineas[$i]['cuenta'] . $b,
495
                            'descripcion' => $a . substr(fs_fix_html($lineas[$i]['descripcion']), 0, 50) . $b,
496
                            'debe' => $a . $this->show_numero($lineas[$i]['debe']) . $b,
497
                            'haber' => $a . $this->show_numero($lineas[$i]['haber']) . $b,
498
                            'saldo' => $a . $this->show_numero((float)$lineas[$i]['debe'] - (float)$lineas[$i]['haber']) . $b
499
                        )
500
                    );
501
                }
502
                $linea += 48;
503
504
                /// añadimos las sumas de la línea actual
505
                $desc = 'Suma y sigue';
506
                if ($linea >= count($lineas)) {
507
                    $desc = 'Totales';
508
                }
509
                $pdf_doc->add_table_row(
510
                    array(
511
                        'cuenta' => '',
512
                        'descripcion' => '<b>' . fs_fix_html($desc) . '</b>',
513
                        'debe' => '<b>' . $this->show_numero($tdebe) . '</b>',
514
                        'haber' => '<b>' . $this->show_numero($thaber) . '</b>',
515
                        'saldo' => '<b>' . $this->show_numero($tdebe - $thaber) . '</b>'
516
                    )
517
                );
518
                $pdf_doc->save_table(
519
                    array(
520
                        'fontSize' => 9,
521
                        'cols' => array(
522
                            'debe' => array('justification' => 'right'),
523
                            'haber' => array('justification' => 'right'),
524
                            'saldo' => array('justification' => 'right')
525
                        ),
526
                        'width' => 540,
527
                        'shaded' => 0
528
                    )
529
                );
530
            } else {
531
                for ($i = $linea; $i < min(array($linea + 48, count($lineas))); $i++) {
532
                    if (strlen($lineas[$i]['cuenta']) === 1) {
533
                        $tdebe += $lineas[$i]['debe'];
534
                        $thaber += $lineas[$i]['haber'];
535
                    }
536
537
                    echo $lineas[$i]['cuenta'] . ';' .
538
                    substr(fs_fix_html($lineas[$i]['descripcion']), 0, 50) . ';' .
539
                    number_format($lineas[$i]['debe'], FS_NF0, FS_NF1, FS_NF2) . ';' .
540
                    number_format($lineas[$i]['haber'], FS_NF0, FS_NF1, FS_NF2) . ';' .
541
                    number_format((float)$lineas[$i]['debe'] - (float)$lineas[$i]['haber'], FS_NF0, FS_NF1, FS_NF2) . "\n";
542
                }
543
                $linea += 48;
544
            }
545
        }
546
    }
547
548
    private function balance_situacion()
549
    {
550
        $eje = $this->ejercicio->get($_POST['codejercicio']);
551
        if ($eje) {
552
            if (strtotime($_POST['desde']) < strtotime($eje->fechainicio) || strtotime($_POST['hasta']) > strtotime($eje->fechafin)) {
553
                $this->new_error_msg('La fecha está fuera del rango del ejercicio.');
554
            } else {
555
                $this->template = false;
556
                $pdf_doc = new fs_pdf();
557
                $pdf_doc->pdf->addInfo('Title', 'Balance de situación de ' . fs_fix_html($this->empresa->nombre));
558
                $pdf_doc->pdf->addInfo('Subject', 'Balance de situación de ' . fs_fix_html($this->empresa->nombre));
559
                $pdf_doc->pdf->addInfo('Author', fs_fix_html($this->empresa->nombre));
560
                $pdf_doc->pdf->ezStartPageNumbers(580, 10, 10, 'left', '{PAGENUM} de {TOTALPAGENUM}');
561
562
                $this->situacion($pdf_doc, $eje);
563
564
                $pdf_doc->show();
565
            }
566
        }
567
    }
568
569
    /**
570
     * Función auxiliar para generar el informe de situación.
571
     * Para generar este informe hay que leer los códigos de balance con naturaleza A o P
572
     * en orden. Pero como era demasiado sencillo, los hijos de puta de facturalux decidieron
573
     * añadir números romanos, para que no puedas ordenarlos fácilemnte.
574
     * @param fs_pdf $pdf_doc
575
     * @param type $eje
576
     */
577
    private function situacion(&$pdf_doc, &$eje)
578
    {
579
        $nivel0 = array('A', 'P');
580
        //$nivel1 = array('A', 'B', 'C');
581
        $nivel1 = array('', '1', '2', '3', '4', '5', '6', '7', '8', '9');
582
        $nivel2 = array('', '1', '2', '3', '4', '5', '6', '7', '8', '9');
0 ignored issues
show
Unused Code introduced by
The assignment to $nivel2 is dead and can be removed.
Loading history...
583
        $nivel3 = array('', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X');
0 ignored issues
show
Unused Code introduced by
The assignment to $nivel3 is dead and can be removed.
Loading history...
584
        $nivel4 = array('', '1', '2', '3', '4', '5', '6', '7', '8', '9');
0 ignored issues
show
Unused Code introduced by
The assignment to $nivel4 is dead and can be removed.
Loading history...
585
        $balances = $this->balance->all();
586
587
        $np = false;
588
        foreach ($nivel0 as $nv0) {
589
            if ($np) {
590
                $pdf_doc->pdf->ezNewPage();
591
            } else {
592
                $np = true;
593
            }
594
595
            $pdf_doc->pdf->ezText(fs_fix_html($this->empresa->nombre) . " - Balance de situación de "
596
                . $_POST['desde'] . " a " . $_POST['hasta'] . ".\n\n", 13);
597
598
            /// creamos las cabeceras de la tabla
599
            $pdf_doc->new_table();
600
            $pdf_doc->add_table_header(
601
                [
602
                    'descripcion' => '<b>Descripción</b>',
603
                    'actual' => '<b>' . $eje->year() . '</b>'
604
                ]
605
            );
606
607
            $desc1 = '';
608
            $desc2 = '';
609
            $desc3 = '';
610
            foreach ($nivel1 as $nv1) {
611
                //foreach ($nivel2 as $nv2) {
612
                    //foreach ($nivel3 as $nv3) {
613
                        //foreach ($nivel4 as $nv4) {
614
                            foreach ($balances as $bal) {
615
                                if ($bal->naturaleza === $nv0 && $bal->nivel1 === $nv1) {
616
                                    if ($bal->descripcion1 !== $desc1 && $bal->descripcion1 !== '') {
617
                                        $pdf_doc->add_table_row(
618
                                            array(
619
                                                'descripcion' => "\n<b>" . $bal->descripcion1 . '</b>',
620
                                                'actual' => "\n<b>" . $this->get_saldo_balance2($nv0 . '-' . $nv1, $eje, $nv0) . '</b>'
621
                                            )
622
                                        );
623
624
                                        $desc1 = $bal->descripcion1;
625
                                    }
626
627
                                    if ($bal->descripcion2 !== $desc2 && $bal->descripcion2 !== '') {
628
                                        $pdf_doc->add_table_row(
629
                                            array(
630
                                                'descripcion' => ' <b>' . $bal->descripcion2 . '</b>',
631
                                                'actual' => $this->get_saldo_balance2($nv0 . '-' . $nv1, $eje, $nv0)
632
                                            )
633
                                        );
634
635
                                        $desc2 = $bal->descripcion2;
636
                                    }
637
638
                                    if ($bal->descripcion3 !== $desc3 && $bal->descripcion3 !== '') {
639
                                        $pdf_doc->add_table_row(
640
                                            array(
641
                                                'descripcion' => '  ' . $bal->descripcion3,
642
                                                'actual' => $this->get_saldo_balance2($nv0 . '-' . $nv1, $eje, $nv0)
643
                                            )
644
                                        );
645
646
                                        $desc3 = $bal->descripcion3;
647
                                    }
648
649
                                    break;
650
                                }
651
                            }
652
                        //}
653
                    //}
654
                //}
655
            }
656
657
            if ($nv0 === 'A') {
658
                $pdf_doc->add_table_row(
659
                    array(
660
                        'descripcion' => "\n<b>TOTAL ACTIVO (A+B)</b>",
661
                        'actual' => "\n<b>" . $this->get_saldo_balance2($nv0 . '-', $eje, $nv0) . '</b>'
662
                    )
663
                );
664
            } elseif ($nv0 === 'P') {
665
                $pdf_doc->add_table_row(
666
                    array(
667
                        'descripcion' => "\n<b>TOTAL PATRIMONIO NETO (A+B+C)</b>",
668
                        'actual' => "\n<b>" . $this->get_saldo_balance2($nv0 . '-', $eje, $nv0) . '</b>'
669
                    )
670
                );
671
            }
672
673
            $pdf_doc->save_table(
674
                [
675
                    'fontSize' => 12,
676
                    'cols' => [
677
                        'actual' => ['justification' => 'right']
678
                    ],
679
                    'width' => 540,
680
                    'shaded' => 0
681
                ]
682
            );
683
        }
684
    }
685
686
    private function balance_perdidasyg()
687
    {
688
        $eje = $this->ejercicio->get($_POST['codejercicio']);
689
        if ($eje) {
690
            if (strtotime($_POST['desde']) < strtotime($eje->fechainicio) || strtotime($_POST['hasta']) > strtotime($eje->fechafin)) {
691
                $this->new_error_msg('La fecha está fuera del rango del ejercicio.');
692
            } else {
693
                $this->template = false;
694
                $pdf_doc = new fs_pdf();
695
                $pdf_doc->pdf->addInfo('Title', 'Balance de pérdidas y ganancias de ' . fs_fix_html($this->empresa->nombre));
696
                $pdf_doc->pdf->addInfo('Subject', 'Balance de pérdidas y ganancias de ' . fs_fix_html($this->empresa->nombre));
697
                $pdf_doc->pdf->addInfo('Author', fs_fix_html($this->empresa->nombre));
698
                $pdf_doc->pdf->ezStartPageNumbers(580, 10, 10, 'left', '{PAGENUM} de {TOTALPAGENUM}');
699
700
                $this->perdidas_y_ganancias($pdf_doc, $eje);
701
702
                $pdf_doc->show();
703
            }
704
        }
705
    }
706
707
    /**
708
     * Función auxiliar para generar el balance de pérdidas y ganancias.
709
     * Este informe se confecciona a partir de las cuentas que señalan los códigos
710
     * de balance que empiezan por PG.
711
     */
712
    private function perdidas_y_ganancias(&$pdf_doc, &$eje)
713
    {
714
        $pdf_doc->pdf->ezText(fs_fix_html($this->empresa->nombre) . " - Cuenta de pérdidas y ganancias abreviada de "
715
            . $_POST['desde'] . " a " . $_POST['hasta'] . ".\n\n", 13);
716
717
        /// creamos las cabeceras de la tabla
718
        $pdf_doc->new_table();
719
        $pdf_doc->add_table_header(
720
            array(
721
                'descripcion' => '<b>Descripción</b>',
722
                'actual' => '<b>' . $eje->year() . '</b>'
723
            )
724
        );
725
726
        $balances = $this->balance->all();
727
        $num = 1;
728
        $continuar = true;
729
        $totales = array($eje->year() => array('a' => 0, 'b' => 0, 'c' => 0, 'd' => 0));
730
        while ($continuar) {
731
            if ($num === 12) {
732
                $pdf_doc->add_table_row(
733
                    array(
734
                        'descripcion' => "\n<b>A) RESULTADOS DE EXPLOTACIÓN (1+2+3+4+5+6+7+8+9+10+11)</b>",
735
                        'actual' => "\n<b>" . $this->show_numero($totales[$eje->year()]['a']) . '</b>'
736
                    )
737
                );
738
            } elseif ($num === 17) {
739
                $pdf_doc->add_table_row(
740
                    array(
741
                        'descripcion' => "\n<b>B) RESULTADO FINANCIERO (12+13+14+15+16)</b>",
742
                        'actual' => "\n<b>" . $this->show_numero($totales[$eje->year()]['b']) . '</b>'
743
                    )
744
                );
745
                $pdf_doc->add_table_row(
746
                    array(
747
                        'descripcion' => "<b>C) RESULTADO ANTES DE IMPUESTOS (A+B)</b>",
748
                        'actual' => '<b>' . $this->show_numero($totales[$eje->year()]['c']) . '</b>'
749
                    )
750
                );
751
            }
752
753
            $encontrado = false;
754
            foreach ($balances as $bal) {
755
                if ($bal->naturaleza === 'PG' && strpos($bal->codbalance, 'PG-' . $num) !== false) {
756
                    $saldo1 = $this->get_saldo_balance('PG-' . $num, $eje);
757
758
                    /// añadimos la fila
759
                    $pdf_doc->add_table_row(
760
                        array(
761
                            'descripcion' => $bal->descripcion2,
762
                            'actual' => $this->show_numero($saldo1)
763
                        )
764
                    );
765
766
                    /// sumamos donde corresponda
767
                    if ($num <= 11) {
768
                        $totales[$eje->year()]['a'] += $saldo1;
769
                    } elseif ($num <= 16) {
770
                        $totales[$eje->year()]['b'] += $saldo1;
771
                        $totales[$eje->year()]['c'] = $totales[$eje->year()]['a'] + $totales[$eje->year()]['b'];
772
                    } elseif ($num === 17) {
773
                        $totales[$eje->year()]['d'] = $totales[$eje->year()]['c'] + $saldo1;
774
                    }
775
776
                    $encontrado = true;
777
                    $num++;
778
                    break;
779
                }
780
            }
781
782
            $continuar = $encontrado;
783
        }
784
785
        $pdf_doc->add_table_row(
786
            array(
787
                'descripcion' => "\n<b>D) RESULTADO DEL EJERCICIO (C+17)</b>",
788
                'actual' => "\n<b>" . $this->show_numero($totales[$eje->year()]['d']) . '</b>'
789
            )
790
        );
791
792
        $pdf_doc->save_table(
793
            array(
794
                'fontSize' => 12,
795
                'cols' => array(
796
                    'actual' => array('justification' => 'right')
797
                ),
798
                'width' => 540,
799
                'shaded' => 0
800
            )
801
        );
802
    }
803
804
    private function get_saldo_balance($codbalance, &$ejercicio)
805
    {
806
        $total = 0;
807
808
        foreach ($this->balance_cuenta_a->search_by_codbalance($codbalance) as $bca) {
809
            $total += $bca->saldo($ejercicio, $_POST['desde'], $_POST['hasta']);
810
        }
811
812
        return $total;
813
    }
814
815
    /**
816
     * @param $codbalance
817
     * @param $ejercicio
818
     * @param $naturaleza
819
     * @return string
820
     */
821
    private function get_saldo_balance2($codbalance, $ejercicio, $naturaleza = 'A')
822
    {
823
        $total = 0;
824
825
        foreach ($this->balance_cuenta_a->search_by_codbalance($codbalance) as $bca) {
826
            $total += $bca->saldo($ejercicio, $_POST['desde'], $_POST['hasta']);
827
        }
828
829
        if ($naturaleza === 'A') {
830
            return $this->show_numero(0 - $total);
831
        }
832
833
        return $this->show_numero($total);
834
    }
835
}
836